Create a user.groups module in ResourceLoader, which bundles a CSS and JS page for...
[lhc/web/wiklou.git] / includes / User.php
1 <?php
2 /**
3 * Implements the User class for the %MediaWiki software.
4 * @file
5 */
6
7 /**
8 * Int Serialized record version.
9 * @ingroup Constants
10 */
11 define( 'MW_USER_VERSION', 8 );
12
13 /**
14 * String Some punctuation to prevent editing from broken text-mangling proxies.
15 * @ingroup Constants
16 */
17 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
18
19 /**
20 * Thrown by User::setPassword() on error.
21 * @ingroup Exception
22 */
23 class PasswordError extends MWException {
24 // NOP
25 }
26
27 /**
28 * The User object encapsulates all of the user-specific settings (user_id,
29 * name, rights, password, email address, options, last login time). Client
30 * classes use the getXXX() functions to access these fields. These functions
31 * do all the work of determining whether the user is logged in,
32 * whether the requested option can be satisfied from cookies or
33 * whether a database query is needed. Most of the settings needed
34 * for rendering normal pages are set in the cookie to minimize use
35 * of the database.
36 */
37 class User {
38
39 /**
40 * Array of Strings List of member variables which are saved to the
41 * shared cache (memcached). Any operation which changes the
42 * corresponding database fields must call a cache-clearing function.
43 * @showinitializer
44 */
45 static $mCacheVars = array(
46 // user table
47 'mId',
48 'mName',
49 'mRealName',
50 'mPassword',
51 'mNewpassword',
52 'mNewpassTime',
53 'mEmail',
54 'mTouched',
55 'mToken',
56 'mEmailAuthenticated',
57 'mEmailToken',
58 'mEmailTokenExpires',
59 'mRegistration',
60 'mEditCount',
61 // user_group table
62 'mGroups',
63 // user_properties table
64 'mOptionOverrides',
65 );
66
67 /**
68 * Array of Strings Core rights.
69 * Each of these should have a corresponding message of the form
70 * "right-$right".
71 * @showinitializer
72 */
73 static $mCoreRights = array(
74 'apihighlimits',
75 'autoconfirmed',
76 'autopatrol',
77 'bigdelete',
78 'block',
79 'blockemail',
80 'bot',
81 'browsearchive',
82 'createaccount',
83 'createpage',
84 'createtalk',
85 'delete',
86 'deletedhistory',
87 'deletedtext',
88 'deleterevision',
89 'disableaccount',
90 'edit',
91 'editinterface',
92 'editusercssjs', #deprecated
93 'editusercss',
94 'edituserjs',
95 'hideuser',
96 'import',
97 'importupload',
98 'ipblock-exempt',
99 'markbotedits',
100 'mergehistory',
101 'minoredit',
102 'move',
103 'movefile',
104 'move-rootuserpages',
105 'move-subpages',
106 'nominornewtalk',
107 'noratelimit',
108 'override-export-depth',
109 'patrol',
110 'protect',
111 'proxyunbannable',
112 'purge',
113 'read',
114 'reupload',
115 'reupload-shared',
116 'rollback',
117 'selenium',
118 'sendemail',
119 'siteadmin',
120 'suppressionlog',
121 'suppressredirect',
122 'suppressrevision',
123 'trackback',
124 'undelete',
125 'unwatchedpages',
126 'upload',
127 'upload_by_url',
128 'userrights',
129 'userrights-interwiki',
130 'writeapi',
131 );
132 /**
133 * String Cached results of getAllRights()
134 */
135 static $mAllRights = false;
136
137 /** @name Cache variables */
138 //@{
139 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
140 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
141 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups, $mOptionOverrides;
142 //@}
143
144 /**
145 * Bool Whether the cache variables have been loaded.
146 */
147 var $mDataLoaded, $mAuthLoaded, $mOptionsLoaded;
148
149 /**
150 * String Initialization data source if mDataLoaded==false. May be one of:
151 * - 'defaults' anonymous user initialised from class defaults
152 * - 'name' initialise from mName
153 * - 'id' initialise from mId
154 * - 'session' log in from cookies or session if possible
155 *
156 * Use the User::newFrom*() family of functions to set this.
157 */
158 var $mFrom;
159
160 /**
161 * Lazy-initialized variables, invalidated with clearInstanceCache
162 */
163 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
164 $mBlockreason, $mBlock, $mEffectiveGroups, $mBlockedGlobally,
165 $mLocked, $mHideName, $mOptions;
166
167 static $idCacheByName = array();
168
169 /**
170 * Lightweight constructor for an anonymous user.
171 * Use the User::newFrom* factory functions for other kinds of users.
172 *
173 * @see newFromName()
174 * @see newFromId()
175 * @see newFromConfirmationCode()
176 * @see newFromSession()
177 * @see newFromRow()
178 */
179 function __construct() {
180 $this->clearInstanceCache( 'defaults' );
181 }
182
183 /**
184 * Load the user table data for this object from the source given by mFrom.
185 */
186 function load() {
187 if ( $this->mDataLoaded ) {
188 return;
189 }
190 wfProfileIn( __METHOD__ );
191
192 # Set it now to avoid infinite recursion in accessors
193 $this->mDataLoaded = true;
194
195 switch ( $this->mFrom ) {
196 case 'defaults':
197 $this->loadDefaults();
198 break;
199 case 'name':
200 $this->mId = self::idFromName( $this->mName );
201 if ( !$this->mId ) {
202 # Nonexistent user placeholder object
203 $this->loadDefaults( $this->mName );
204 } else {
205 $this->loadFromId();
206 }
207 break;
208 case 'id':
209 $this->loadFromId();
210 break;
211 case 'session':
212 $this->loadFromSession();
213 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
214 break;
215 default:
216 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
217 }
218 wfProfileOut( __METHOD__ );
219 }
220
221 /**
222 * Load user table data, given mId has already been set.
223 * @return Bool false if the ID does not exist, true otherwise
224 * @private
225 */
226 function loadFromId() {
227 global $wgMemc;
228 if ( $this->mId == 0 ) {
229 $this->loadDefaults();
230 return false;
231 }
232
233 # Try cache
234 $key = wfMemcKey( 'user', 'id', $this->mId );
235 $data = $wgMemc->get( $key );
236 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
237 # Object is expired, load from DB
238 $data = false;
239 }
240
241 if ( !$data ) {
242 wfDebug( "User: cache miss for user {$this->mId}\n" );
243 # Load from DB
244 if ( !$this->loadFromDatabase() ) {
245 # Can't load from ID, user is anonymous
246 return false;
247 }
248 $this->saveToCache();
249 } else {
250 wfDebug( "User: got user {$this->mId} from cache\n" );
251 # Restore from cache
252 foreach ( self::$mCacheVars as $name ) {
253 $this->$name = $data[$name];
254 }
255 }
256 return true;
257 }
258
259 /**
260 * Save user data to the shared cache
261 */
262 function saveToCache() {
263 $this->load();
264 $this->loadGroups();
265 $this->loadOptions();
266 if ( $this->isAnon() ) {
267 // Anonymous users are uncached
268 return;
269 }
270 $data = array();
271 foreach ( self::$mCacheVars as $name ) {
272 $data[$name] = $this->$name;
273 }
274 $data['mVersion'] = MW_USER_VERSION;
275 $key = wfMemcKey( 'user', 'id', $this->mId );
276 global $wgMemc;
277 $wgMemc->set( $key, $data );
278 }
279
280
281 /** @name newFrom*() static factory methods */
282 //@{
283
284 /**
285 * Static factory method for creation from username.
286 *
287 * This is slightly less efficient than newFromId(), so use newFromId() if
288 * you have both an ID and a name handy.
289 *
290 * @param $name String Username, validated by Title::newFromText()
291 * @param $validate String|Bool Validate username. Takes the same parameters as
292 * User::getCanonicalName(), except that true is accepted as an alias
293 * for 'valid', for BC.
294 *
295 * @return User object, or false if the username is invalid
296 * (e.g. if it contains illegal characters or is an IP address). If the
297 * username is not present in the database, the result will be a user object
298 * with a name, zero user ID and default settings.
299 */
300 static function newFromName( $name, $validate = 'valid' ) {
301 if ( $validate === true ) {
302 $validate = 'valid';
303 }
304 $name = self::getCanonicalName( $name, $validate );
305 if ( $name === false ) {
306 return false;
307 } else {
308 # Create unloaded user object
309 $u = new User;
310 $u->mName = $name;
311 $u->mFrom = 'name';
312 return $u;
313 }
314 }
315
316 /**
317 * Static factory method for creation from a given user ID.
318 *
319 * @param $id Int Valid user ID
320 * @return User The corresponding User object
321 */
322 static function newFromId( $id ) {
323 $u = new User;
324 $u->mId = $id;
325 $u->mFrom = 'id';
326 return $u;
327 }
328
329 /**
330 * Factory method to fetch whichever user has a given email confirmation code.
331 * This code is generated when an account is created or its e-mail address
332 * has changed.
333 *
334 * If the code is invalid or has expired, returns NULL.
335 *
336 * @param $code String Confirmation code
337 * @return User
338 */
339 static function newFromConfirmationCode( $code ) {
340 $dbr = wfGetDB( DB_SLAVE );
341 $id = $dbr->selectField( 'user', 'user_id', array(
342 'user_email_token' => md5( $code ),
343 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
344 ) );
345 if( $id !== false ) {
346 return User::newFromId( $id );
347 } else {
348 return null;
349 }
350 }
351
352 /**
353 * Create a new user object using data from session or cookies. If the
354 * login credentials are invalid, the result is an anonymous user.
355 *
356 * @return User
357 */
358 static function newFromSession() {
359 $user = new User;
360 $user->mFrom = 'session';
361 return $user;
362 }
363
364 /**
365 * Create a new user object from a user row.
366 * The row should have all fields from the user table in it.
367 * @param $row array A row from the user table
368 * @return User
369 */
370 static function newFromRow( $row ) {
371 $user = new User;
372 $user->loadFromRow( $row );
373 return $user;
374 }
375
376 //@}
377
378
379 /**
380 * Get the username corresponding to a given user ID
381 * @param $id Int User ID
382 * @return String The corresponding username
383 */
384 static function whoIs( $id ) {
385 $dbr = wfGetDB( DB_SLAVE );
386 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), __METHOD__ );
387 }
388
389 /**
390 * Get the real name of a user given their user ID
391 *
392 * @param $id Int User ID
393 * @return String The corresponding user's real name
394 */
395 static function whoIsReal( $id ) {
396 $dbr = wfGetDB( DB_SLAVE );
397 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__ );
398 }
399
400 /**
401 * Get database id given a user name
402 * @param $name String Username
403 * @return Int|Null The corresponding user's ID, or null if user is nonexistent
404 */
405 static function idFromName( $name ) {
406 $nt = Title::makeTitleSafe( NS_USER, $name );
407 if( is_null( $nt ) ) {
408 # Illegal name
409 return null;
410 }
411
412 if ( isset( self::$idCacheByName[$name] ) ) {
413 return self::$idCacheByName[$name];
414 }
415
416 $dbr = wfGetDB( DB_SLAVE );
417 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
418
419 if ( $s === false ) {
420 $result = null;
421 } else {
422 $result = $s->user_id;
423 }
424
425 self::$idCacheByName[$name] = $result;
426
427 if ( count( self::$idCacheByName ) > 1000 ) {
428 self::$idCacheByName = array();
429 }
430
431 return $result;
432 }
433
434 /**
435 * Reset the cache used in idFromName(). For use in tests.
436 */
437 public static function resetIdByNameCache() {
438 self::$idCacheByName = array();
439 }
440
441 /**
442 * Does the string match an anonymous IPv4 address?
443 *
444 * This function exists for username validation, in order to reject
445 * usernames which are similar in form to IP addresses. Strings such
446 * as 300.300.300.300 will return true because it looks like an IP
447 * address, despite not being strictly valid.
448 *
449 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
450 * address because the usemod software would "cloak" anonymous IP
451 * addresses like this, if we allowed accounts like this to be created
452 * new users could get the old edits of these anonymous users.
453 *
454 * @param $name String to match
455 * @return Bool
456 */
457 static function isIP( $name ) {
458 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP::isIPv6($name);
459 }
460
461 /**
462 * Is the input a valid username?
463 *
464 * Checks if the input is a valid username, we don't want an empty string,
465 * an IP address, anything that containins slashes (would mess up subpages),
466 * is longer than the maximum allowed username size or doesn't begin with
467 * a capital letter.
468 *
469 * @param $name String to match
470 * @return Bool
471 */
472 static function isValidUserName( $name ) {
473 global $wgContLang, $wgMaxNameChars;
474
475 if ( $name == ''
476 || User::isIP( $name )
477 || strpos( $name, '/' ) !== false
478 || strlen( $name ) > $wgMaxNameChars
479 || $name != $wgContLang->ucfirst( $name ) ) {
480 wfDebugLog( 'username', __METHOD__ .
481 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
482 return false;
483 }
484
485 // Ensure that the name can't be misresolved as a different title,
486 // such as with extra namespace keys at the start.
487 $parsed = Title::newFromText( $name );
488 if( is_null( $parsed )
489 || $parsed->getNamespace()
490 || strcmp( $name, $parsed->getPrefixedText() ) ) {
491 wfDebugLog( 'username', __METHOD__ .
492 ": '$name' invalid due to ambiguous prefixes" );
493 return false;
494 }
495
496 // Check an additional blacklist of troublemaker characters.
497 // Should these be merged into the title char list?
498 $unicodeBlacklist = '/[' .
499 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
500 '\x{00a0}' . # non-breaking space
501 '\x{2000}-\x{200f}' . # various whitespace
502 '\x{2028}-\x{202f}' . # breaks and control chars
503 '\x{3000}' . # ideographic space
504 '\x{e000}-\x{f8ff}' . # private use
505 ']/u';
506 if( preg_match( $unicodeBlacklist, $name ) ) {
507 wfDebugLog( 'username', __METHOD__ .
508 ": '$name' invalid due to blacklisted characters" );
509 return false;
510 }
511
512 return true;
513 }
514
515 /**
516 * Usernames which fail to pass this function will be blocked
517 * from user login and new account registrations, but may be used
518 * internally by batch processes.
519 *
520 * If an account already exists in this form, login will be blocked
521 * by a failure to pass this function.
522 *
523 * @param $name String to match
524 * @return Bool
525 */
526 static function isUsableName( $name ) {
527 global $wgReservedUsernames;
528 // Must be a valid username, obviously ;)
529 if ( !self::isValidUserName( $name ) ) {
530 return false;
531 }
532
533 static $reservedUsernames = false;
534 if ( !$reservedUsernames ) {
535 $reservedUsernames = $wgReservedUsernames;
536 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
537 }
538
539 // Certain names may be reserved for batch processes.
540 foreach ( $reservedUsernames as $reserved ) {
541 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
542 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
543 }
544 if ( $reserved == $name ) {
545 return false;
546 }
547 }
548 return true;
549 }
550
551 /**
552 * Usernames which fail to pass this function will be blocked
553 * from new account registrations, but may be used internally
554 * either by batch processes or by user accounts which have
555 * already been created.
556 *
557 * Additional blacklisting may be added here rather than in
558 * isValidUserName() to avoid disrupting existing accounts.
559 *
560 * @param $name String to match
561 * @return Bool
562 */
563 static function isCreatableName( $name ) {
564 global $wgInvalidUsernameCharacters;
565
566 // Ensure that the username isn't longer than 235 bytes, so that
567 // (at least for the builtin skins) user javascript and css files
568 // will work. (bug 23080)
569 if( strlen( $name ) > 235 ) {
570 wfDebugLog( 'username', __METHOD__ .
571 ": '$name' invalid due to length" );
572 return false;
573 }
574
575 // Preg yells if you try to give it an empty string
576 if( $wgInvalidUsernameCharacters !== '' ) {
577 if( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
578 wfDebugLog( 'username', __METHOD__ .
579 ": '$name' invalid due to wgInvalidUsernameCharacters" );
580 return false;
581 }
582 }
583
584 return self::isUsableName( $name );
585 }
586
587 /**
588 * Is the input a valid password for this user?
589 *
590 * @param $password String Desired password
591 * @return Bool
592 */
593 function isValidPassword( $password ) {
594 //simple boolean wrapper for getPasswordValidity
595 return $this->getPasswordValidity( $password ) === true;
596 }
597
598 /**
599 * Given unvalidated password input, return error message on failure.
600 *
601 * @param $password String Desired password
602 * @return mixed: true on success, string or array of error message on failure
603 */
604 function getPasswordValidity( $password ) {
605 global $wgMinimalPasswordLength, $wgContLang;
606
607 static $blockedLogins = array(
608 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
609 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
610 );
611
612 $result = false; //init $result to false for the internal checks
613
614 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
615 return $result;
616
617
618 if ( $result === false ) {
619 if( strlen( $password ) < $wgMinimalPasswordLength ) {
620 return 'passwordtooshort';
621 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) {
622 return 'password-name-match';
623 } elseif ( isset( $blockedLogins[ $this->getName() ] ) && $password == $blockedLogins[ $this->getName() ] ) {
624 return 'password-login-forbidden';
625 } else {
626 //it seems weird returning true here, but this is because of the
627 //initialization of $result to false above. If the hook is never run or it
628 //doesn't modify $result, then we will likely get down into this if with
629 //a valid password.
630 return true;
631 }
632 } elseif( $result === true ) {
633 return true;
634 } else {
635 return $result; //the isValidPassword hook set a string $result and returned true
636 }
637 }
638
639 /**
640 * Does a string look like an e-mail address?
641 *
642 * This validates an email address using an HTML5 specification found at:
643 * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
644 * Which as of 2011-01-24 says:
645 *
646 * A valid e-mail address is a string that matches the ABNF production
647 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
648 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
649 * 3.5.
650 *
651 * This function is an implementation of the specification as requested in
652 * bug 22449.
653 *
654 * Client-side forms will use the same standard validation rules via JS or
655 * HTML 5 validation; additional restrictions can be enforced server-side
656 * by extensions via the 'isValidEmailAddr' hook.
657 *
658 * Note that this validation doesn't 100% match RFC 2822, but is believed
659 * to be liberal enough for wide use. Some invalid addresses will still
660 * pass validation here.
661 *
662 * @param $addr String E-mail address
663 * @return Bool
664 */
665 public static function isValidEmailAddr( $addr ) {
666 $result = null;
667 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
668 return $result;
669 }
670
671 // Please note strings below are enclosed in brackets [], this make the
672 // hyphen "-" a range indicator. Hence it is double backslashed below.
673 // See bug 26948
674 $rfc5322_atext = "a-z0-9!#$%&'*+\\-\/=?^_`{|}~" ;
675 $rfc1034_ldh_str = "a-z0-9\\-" ;
676
677 $HTML5_email_regexp = "/
678 ^ # start of string
679 [$rfc5322_atext\\.]+ # user part which is liberal :p
680 @ # 'apostrophe'
681 [$rfc1034_ldh_str]+ # First domain part
682 (\\.[$rfc1034_ldh_str]+)* # Following part prefixed with a dot
683 $ # End of string
684 /ix" ; // case Insensitive, eXtended
685
686 return (bool) preg_match( $HTML5_email_regexp, $addr );
687 }
688
689 /**
690 * Given unvalidated user input, return a canonical username, or false if
691 * the username is invalid.
692 * @param $name String User input
693 * @param $validate String|Bool type of validation to use:
694 * - false No validation
695 * - 'valid' Valid for batch processes
696 * - 'usable' Valid for batch processes and login
697 * - 'creatable' Valid for batch processes, login and account creation
698 */
699 static function getCanonicalName( $name, $validate = 'valid' ) {
700 # Force usernames to capital
701 global $wgContLang;
702 $name = $wgContLang->ucfirst( $name );
703
704 # Reject names containing '#'; these will be cleaned up
705 # with title normalisation, but then it's too late to
706 # check elsewhere
707 if( strpos( $name, '#' ) !== false )
708 return false;
709
710 # Clean up name according to title rules
711 $t = ( $validate === 'valid' ) ?
712 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
713 # Check for invalid titles
714 if( is_null( $t ) ) {
715 return false;
716 }
717
718 # Reject various classes of invalid names
719 global $wgAuth;
720 $name = $wgAuth->getCanonicalName( $t->getText() );
721
722 switch ( $validate ) {
723 case false:
724 break;
725 case 'valid':
726 if ( !User::isValidUserName( $name ) ) {
727 $name = false;
728 }
729 break;
730 case 'usable':
731 if ( !User::isUsableName( $name ) ) {
732 $name = false;
733 }
734 break;
735 case 'creatable':
736 if ( !User::isCreatableName( $name ) ) {
737 $name = false;
738 }
739 break;
740 default:
741 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
742 }
743 return $name;
744 }
745
746 /**
747 * Count the number of edits of a user
748 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
749 *
750 * @param $uid Int User ID to check
751 * @return Int the user's edit count
752 */
753 static function edits( $uid ) {
754 wfProfileIn( __METHOD__ );
755 $dbr = wfGetDB( DB_SLAVE );
756 // check if the user_editcount field has been initialized
757 $field = $dbr->selectField(
758 'user', 'user_editcount',
759 array( 'user_id' => $uid ),
760 __METHOD__
761 );
762
763 if( $field === null ) { // it has not been initialized. do so.
764 $dbw = wfGetDB( DB_MASTER );
765 $count = $dbr->selectField(
766 'revision', 'count(*)',
767 array( 'rev_user' => $uid ),
768 __METHOD__
769 );
770 $dbw->update(
771 'user',
772 array( 'user_editcount' => $count ),
773 array( 'user_id' => $uid ),
774 __METHOD__
775 );
776 } else {
777 $count = $field;
778 }
779 wfProfileOut( __METHOD__ );
780 return $count;
781 }
782
783 /**
784 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
785 * @todo hash random numbers to improve security, like generateToken()
786 *
787 * @return String new random password
788 */
789 static function randomPassword() {
790 global $wgMinimalPasswordLength;
791 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
792 $l = strlen( $pwchars ) - 1;
793
794 $pwlength = max( 7, $wgMinimalPasswordLength );
795 $digit = mt_rand( 0, $pwlength - 1 );
796 $np = '';
797 for ( $i = 0; $i < $pwlength; $i++ ) {
798 $np .= $i == $digit ? chr( mt_rand( 48, 57 ) ) : $pwchars{ mt_rand( 0, $l ) };
799 }
800 return $np;
801 }
802
803 /**
804 * Set cached properties to default.
805 *
806 * @note This no longer clears uncached lazy-initialised properties;
807 * the constructor does that instead.
808 * @private
809 */
810 function loadDefaults( $name = false ) {
811 wfProfileIn( __METHOD__ );
812
813 global $wgRequest;
814
815 $this->mId = 0;
816 $this->mName = $name;
817 $this->mRealName = '';
818 $this->mPassword = $this->mNewpassword = '';
819 $this->mNewpassTime = null;
820 $this->mEmail = '';
821 $this->mOptionOverrides = null;
822 $this->mOptionsLoaded = false;
823
824 if( $wgRequest->getCookie( 'LoggedOut' ) !== null ) {
825 $this->mTouched = wfTimestamp( TS_MW, $wgRequest->getCookie( 'LoggedOut' ) );
826 } else {
827 $this->mTouched = '0'; # Allow any pages to be cached
828 }
829
830 $this->setToken(); # Random
831 $this->mEmailAuthenticated = null;
832 $this->mEmailToken = '';
833 $this->mEmailTokenExpires = null;
834 $this->mRegistration = wfTimestamp( TS_MW );
835 $this->mGroups = array();
836
837 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
838
839 wfProfileOut( __METHOD__ );
840 }
841
842 /**
843 * Load user data from the session or login cookie. If there are no valid
844 * credentials, initialises the user as an anonymous user.
845 * @return Bool True if the user is logged in, false otherwise.
846 */
847 private function loadFromSession() {
848 global $wgRequest, $wgExternalAuthType, $wgAutocreatePolicy;
849
850 $result = null;
851 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
852 if ( $result !== null ) {
853 return $result;
854 }
855
856 if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
857 $extUser = ExternalUser::newFromCookie();
858 if ( $extUser ) {
859 # TODO: Automatically create the user here (or probably a bit
860 # lower down, in fact)
861 }
862 }
863
864 if ( $wgRequest->getCookie( 'UserID' ) !== null ) {
865 $sId = intval( $wgRequest->getCookie( 'UserID' ) );
866 if( isset( $_SESSION['wsUserID'] ) && $sId != $_SESSION['wsUserID'] ) {
867 $this->loadDefaults(); // Possible collision!
868 wfDebugLog( 'loginSessions', "Session user ID ({$_SESSION['wsUserID']}) and
869 cookie user ID ($sId) don't match!" );
870 return false;
871 }
872 $_SESSION['wsUserID'] = $sId;
873 } else if ( isset( $_SESSION['wsUserID'] ) ) {
874 if ( $_SESSION['wsUserID'] != 0 ) {
875 $sId = $_SESSION['wsUserID'];
876 } else {
877 $this->loadDefaults();
878 return false;
879 }
880 } else {
881 $this->loadDefaults();
882 return false;
883 }
884
885 if ( isset( $_SESSION['wsUserName'] ) ) {
886 $sName = $_SESSION['wsUserName'];
887 } else if ( $wgRequest->getCookie('UserName') !== null ) {
888 $sName = $wgRequest->getCookie('UserName');
889 $_SESSION['wsUserName'] = $sName;
890 } else {
891 $this->loadDefaults();
892 return false;
893 }
894
895 $this->mId = $sId;
896 if ( !$this->loadFromId() ) {
897 # Not a valid ID, loadFromId has switched the object to anon for us
898 return false;
899 }
900
901 global $wgBlockDisablesLogin;
902 if( $wgBlockDisablesLogin && $this->isBlocked() ) {
903 # User blocked and we've disabled blocked user logins
904 $this->loadDefaults();
905 return false;
906 }
907
908 if ( isset( $_SESSION['wsToken'] ) ) {
909 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken;
910 $from = 'session';
911 } else if ( $wgRequest->getCookie( 'Token' ) !== null ) {
912 $passwordCorrect = $this->mToken == $wgRequest->getCookie( 'Token' );
913 $from = 'cookie';
914 } else {
915 # No session or persistent login cookie
916 $this->loadDefaults();
917 return false;
918 }
919
920 if ( ( $sName == $this->mName ) && $passwordCorrect ) {
921 $_SESSION['wsToken'] = $this->mToken;
922 wfDebug( "User: logged in from $from\n" );
923 return true;
924 } else {
925 # Invalid credentials
926 wfDebug( "User: can't log in from $from, invalid credentials\n" );
927 $this->loadDefaults();
928 return false;
929 }
930 }
931
932 /**
933 * Load user and user_group data from the database.
934 * $this::mId must be set, this is how the user is identified.
935 *
936 * @return Bool True if the user exists, false if the user is anonymous
937 * @private
938 */
939 function loadFromDatabase() {
940 # Paranoia
941 $this->mId = intval( $this->mId );
942
943 /** Anonymous user */
944 if( !$this->mId ) {
945 $this->loadDefaults();
946 return false;
947 }
948
949 $dbr = wfGetDB( DB_MASTER );
950 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ );
951
952 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
953
954 if ( $s !== false ) {
955 # Initialise user table data
956 $this->loadFromRow( $s );
957 $this->mGroups = null; // deferred
958 $this->getEditCount(); // revalidation for nulls
959 return true;
960 } else {
961 # Invalid user_id
962 $this->mId = 0;
963 $this->loadDefaults();
964 return false;
965 }
966 }
967
968 /**
969 * Initialize this object from a row from the user table.
970 *
971 * @param $row Array Row from the user table to load.
972 */
973 function loadFromRow( $row ) {
974 $this->mDataLoaded = true;
975
976 if ( isset( $row->user_id ) ) {
977 $this->mId = intval( $row->user_id );
978 }
979 $this->mName = $row->user_name;
980 $this->mRealName = $row->user_real_name;
981 $this->mPassword = $row->user_password;
982 $this->mNewpassword = $row->user_newpassword;
983 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
984 $this->mEmail = $row->user_email;
985 $this->decodeOptions( $row->user_options );
986 $this->mTouched = wfTimestamp(TS_MW,$row->user_touched);
987 $this->mToken = $row->user_token;
988 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
989 $this->mEmailToken = $row->user_email_token;
990 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
991 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
992 $this->mEditCount = $row->user_editcount;
993 }
994
995 /**
996 * Load the groups from the database if they aren't already loaded.
997 * @private
998 */
999 function loadGroups() {
1000 if ( is_null( $this->mGroups ) ) {
1001 $dbr = wfGetDB( DB_MASTER );
1002 $res = $dbr->select( 'user_groups',
1003 array( 'ug_group' ),
1004 array( 'ug_user' => $this->mId ),
1005 __METHOD__ );
1006 $this->mGroups = array();
1007 foreach ( $res as $row ) {
1008 $this->mGroups[] = $row->ug_group;
1009 }
1010 }
1011 }
1012
1013 /**
1014 * Clear various cached data stored in this object.
1015 * @param $reloadFrom String Reload user and user_groups table data from a
1016 * given source. May be "name", "id", "defaults", "session", or false for
1017 * no reload.
1018 */
1019 function clearInstanceCache( $reloadFrom = false ) {
1020 $this->mNewtalk = -1;
1021 $this->mDatePreference = null;
1022 $this->mBlockedby = -1; # Unset
1023 $this->mHash = false;
1024 $this->mSkin = null;
1025 $this->mRights = null;
1026 $this->mEffectiveGroups = null;
1027 $this->mOptions = null;
1028
1029 if ( $reloadFrom ) {
1030 $this->mDataLoaded = false;
1031 $this->mFrom = $reloadFrom;
1032 }
1033 }
1034
1035 /**
1036 * Combine the language default options with any site-specific options
1037 * and add the default language variants.
1038 *
1039 * @return Array of String options
1040 */
1041 static function getDefaultOptions() {
1042 global $wgNamespacesToBeSearchedDefault;
1043 /**
1044 * Site defaults will override the global/language defaults
1045 */
1046 global $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1047 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
1048
1049 /**
1050 * default language setting
1051 */
1052 $variant = $wgContLang->getDefaultVariant();
1053 $defOpt['variant'] = $variant;
1054 $defOpt['language'] = $variant;
1055 foreach( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1056 $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1057 }
1058 $defOpt['skin'] = $wgDefaultSkin;
1059
1060 return $defOpt;
1061 }
1062
1063 /**
1064 * Get a given default option value.
1065 *
1066 * @param $opt String Name of option to retrieve
1067 * @return String Default option value
1068 */
1069 public static function getDefaultOption( $opt ) {
1070 $defOpts = self::getDefaultOptions();
1071 if( isset( $defOpts[$opt] ) ) {
1072 return $defOpts[$opt];
1073 } else {
1074 return null;
1075 }
1076 }
1077
1078
1079 /**
1080 * Get blocking information
1081 * @private
1082 * @param $bFromSlave Bool Whether to check the slave database first. To
1083 * improve performance, non-critical checks are done
1084 * against slaves. Check when actually saving should be
1085 * done against master.
1086 */
1087 function getBlockedStatus( $bFromSlave = true ) {
1088 global $wgProxyWhitelist, $wgUser;
1089
1090 if ( -1 != $this->mBlockedby ) {
1091 return;
1092 }
1093
1094 wfProfileIn( __METHOD__ );
1095 wfDebug( __METHOD__.": checking...\n" );
1096
1097 // Initialize data...
1098 // Otherwise something ends up stomping on $this->mBlockedby when
1099 // things get lazy-loaded later, causing false positive block hits
1100 // due to -1 !== 0. Probably session-related... Nothing should be
1101 // overwriting mBlockedby, surely?
1102 $this->load();
1103
1104 $this->mBlockedby = 0;
1105 $this->mHideName = 0;
1106 $this->mAllowUsertalk = 0;
1107
1108 # Check if we are looking at an IP or a logged-in user
1109 if ( $this->isIP( $this->getName() ) ) {
1110 $ip = $this->getName();
1111 } else {
1112 # Check if we are looking at the current user
1113 # If we don't, and the user is logged in, we don't know about
1114 # his IP / autoblock status, so ignore autoblock of current user's IP
1115 if ( $this->getID() != $wgUser->getID() ) {
1116 $ip = '';
1117 } else {
1118 # Get IP of current user
1119 $ip = wfGetIP();
1120 }
1121 }
1122
1123 if ( $this->isAllowed( 'ipblock-exempt' ) ) {
1124 # Exempt from all types of IP-block
1125 $ip = '';
1126 }
1127
1128 # User/IP blocking
1129 $this->mBlock = new Block();
1130 $this->mBlock->fromMaster( !$bFromSlave );
1131 if ( $this->mBlock->load( $ip , $this->mId ) ) {
1132 wfDebug( __METHOD__ . ": Found block.\n" );
1133 $this->mBlockedby = $this->mBlock->mBy;
1134 if( $this->mBlockedby == 0 )
1135 $this->mBlockedby = $this->mBlock->mByName;
1136 $this->mBlockreason = $this->mBlock->mReason;
1137 $this->mHideName = $this->mBlock->mHideName;
1138 $this->mAllowUsertalk = $this->mBlock->mAllowUsertalk;
1139 if ( $this->isLoggedIn() && $wgUser->getID() == $this->getID() ) {
1140 $this->spreadBlock();
1141 }
1142 } else {
1143 // Bug 13611: don't remove mBlock here, to allow account creation blocks to
1144 // apply to users. Note that the existence of $this->mBlock is not used to
1145 // check for edit blocks, $this->mBlockedby is instead.
1146 }
1147
1148 # Proxy blocking
1149 if ( !$this->isAllowed( 'proxyunbannable' ) && !in_array( $ip, $wgProxyWhitelist ) ) {
1150 # Local list
1151 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1152 $this->mBlockedby = wfMsg( 'proxyblocker' );
1153 $this->mBlockreason = wfMsg( 'proxyblockreason' );
1154 }
1155
1156 # DNSBL
1157 if ( !$this->mBlockedby && !$this->getID() ) {
1158 if ( $this->isDnsBlacklisted( $ip ) ) {
1159 $this->mBlockedby = wfMsg( 'sorbs' );
1160 $this->mBlockreason = wfMsg( 'sorbsreason' );
1161 }
1162 }
1163 }
1164
1165 # Extensions
1166 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1167
1168 wfProfileOut( __METHOD__ );
1169 }
1170
1171 /**
1172 * Whether the given IP is in a DNS blacklist.
1173 *
1174 * @param $ip String IP to check
1175 * @param $checkWhitelist Bool: whether to check the whitelist first
1176 * @return Bool True if blacklisted.
1177 */
1178 function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1179 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1180 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1181
1182 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
1183 return false;
1184
1185 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
1186 return false;
1187
1188 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1189 return $this->inDnsBlacklist( $ip, $urls );
1190 }
1191
1192 /**
1193 * Whether the given IP is in a given DNS blacklist.
1194 *
1195 * @param $ip String IP to check
1196 * @param $bases String|Array of Strings: URL of the DNS blacklist
1197 * @return Bool True if blacklisted.
1198 */
1199 function inDnsBlacklist( $ip, $bases ) {
1200 wfProfileIn( __METHOD__ );
1201
1202 $found = false;
1203 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1204 if( IP::isIPv4( $ip ) ) {
1205 # Reverse IP, bug 21255
1206 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1207
1208 foreach( (array)$bases as $base ) {
1209 # Make hostname
1210 $host = "$ipReversed.$base";
1211
1212 # Send query
1213 $ipList = gethostbynamel( $host );
1214
1215 if( $ipList ) {
1216 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1217 $found = true;
1218 break;
1219 } else {
1220 wfDebug( "Requested $host, not found in $base.\n" );
1221 }
1222 }
1223 }
1224
1225 wfProfileOut( __METHOD__ );
1226 return $found;
1227 }
1228
1229 /**
1230 * Is this user subject to rate limiting?
1231 *
1232 * @return Bool True if rate limited
1233 */
1234 public function isPingLimitable() {
1235 global $wgRateLimitsExcludedGroups;
1236 global $wgRateLimitsExcludedIPs;
1237 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1238 // Deprecated, but kept for backwards-compatibility config
1239 return false;
1240 }
1241
1242
1243
1244 if( in_array( wfGetIP(), $wgRateLimitsExcludedIPs ) ) {
1245 // No other good way currently to disable rate limits
1246 // for specific IPs. :P
1247 // But this is a crappy hack and should die.
1248 return false;
1249 }
1250 return !$this->isAllowed('noratelimit');
1251 }
1252
1253 /**
1254 * Primitive rate limits: enforce maximum actions per time period
1255 * to put a brake on flooding.
1256 *
1257 * @note When using a shared cache like memcached, IP-address
1258 * last-hit counters will be shared across wikis.
1259 *
1260 * @param $action String Action to enforce; 'edit' if unspecified
1261 * @return Bool True if a rate limiter was tripped
1262 */
1263 function pingLimiter( $action = 'edit' ) {
1264 # Call the 'PingLimiter' hook
1265 $result = false;
1266 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1267 return $result;
1268 }
1269
1270 global $wgRateLimits;
1271 if( !isset( $wgRateLimits[$action] ) ) {
1272 return false;
1273 }
1274
1275 # Some groups shouldn't trigger the ping limiter, ever
1276 if( !$this->isPingLimitable() )
1277 return false;
1278
1279 global $wgMemc, $wgRateLimitLog;
1280 wfProfileIn( __METHOD__ );
1281
1282 $limits = $wgRateLimits[$action];
1283 $keys = array();
1284 $id = $this->getId();
1285 $ip = wfGetIP();
1286 $userLimit = false;
1287
1288 if( isset( $limits['anon'] ) && $id == 0 ) {
1289 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1290 }
1291
1292 if( isset( $limits['user'] ) && $id != 0 ) {
1293 $userLimit = $limits['user'];
1294 }
1295 if( $this->isNewbie() ) {
1296 if( isset( $limits['newbie'] ) && $id != 0 ) {
1297 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1298 }
1299 if( isset( $limits['ip'] ) ) {
1300 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1301 }
1302 $matches = array();
1303 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1304 $subnet = $matches[1];
1305 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1306 }
1307 }
1308 // Check for group-specific permissions
1309 // If more than one group applies, use the group with the highest limit
1310 foreach ( $this->getGroups() as $group ) {
1311 if ( isset( $limits[$group] ) ) {
1312 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1313 $userLimit = $limits[$group];
1314 }
1315 }
1316 }
1317 // Set the user limit key
1318 if ( $userLimit !== false ) {
1319 wfDebug( __METHOD__ . ": effective user limit: $userLimit\n" );
1320 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1321 }
1322
1323 $triggered = false;
1324 foreach( $keys as $key => $limit ) {
1325 list( $max, $period ) = $limit;
1326 $summary = "(limit $max in {$period}s)";
1327 $count = $wgMemc->get( $key );
1328 // Already pinged?
1329 if( $count ) {
1330 if( $count > $max ) {
1331 wfDebug( __METHOD__ . ": tripped! $key at $count $summary\n" );
1332 if( $wgRateLimitLog ) {
1333 @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1334 }
1335 $triggered = true;
1336 } else {
1337 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1338 }
1339 } else {
1340 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1341 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1342 }
1343 $wgMemc->incr( $key );
1344 }
1345
1346 wfProfileOut( __METHOD__ );
1347 return $triggered;
1348 }
1349
1350 /**
1351 * Check if user is blocked
1352 *
1353 * @param $bFromSlave Bool Whether to check the slave database instead of the master
1354 * @return Bool True if blocked, false otherwise
1355 */
1356 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1357 $this->getBlockedStatus( $bFromSlave );
1358 return $this->mBlockedby !== 0;
1359 }
1360
1361 /**
1362 * Check if user is blocked from editing a particular article
1363 *
1364 * @param $title Title to check
1365 * @param $bFromSlave Bool whether to check the slave database instead of the master
1366 * @return Bool
1367 */
1368 function isBlockedFrom( $title, $bFromSlave = false ) {
1369 global $wgBlockAllowsUTEdit;
1370 wfProfileIn( __METHOD__ );
1371
1372 $blocked = $this->isBlocked( $bFromSlave );
1373 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1374 # If a user's name is suppressed, they cannot make edits anywhere
1375 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName() &&
1376 $title->getNamespace() == NS_USER_TALK ) {
1377 $blocked = false;
1378 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1379 }
1380
1381 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1382
1383 wfProfileOut( __METHOD__ );
1384 return $blocked;
1385 }
1386
1387 /**
1388 * If user is blocked, return the name of the user who placed the block
1389 * @return String name of blocker
1390 */
1391 function blockedBy() {
1392 $this->getBlockedStatus();
1393 return $this->mBlockedby;
1394 }
1395
1396 /**
1397 * If user is blocked, return the specified reason for the block
1398 * @return String Blocking reason
1399 */
1400 function blockedFor() {
1401 $this->getBlockedStatus();
1402 return $this->mBlockreason;
1403 }
1404
1405 /**
1406 * If user is blocked, return the ID for the block
1407 * @return Int Block ID
1408 */
1409 function getBlockId() {
1410 $this->getBlockedStatus();
1411 return ( $this->mBlock ? $this->mBlock->mId : false );
1412 }
1413
1414 /**
1415 * Check if user is blocked on all wikis.
1416 * Do not use for actual edit permission checks!
1417 * This is intented for quick UI checks.
1418 *
1419 * @param $ip String IP address, uses current client if none given
1420 * @return Bool True if blocked, false otherwise
1421 */
1422 function isBlockedGlobally( $ip = '' ) {
1423 if( $this->mBlockedGlobally !== null ) {
1424 return $this->mBlockedGlobally;
1425 }
1426 // User is already an IP?
1427 if( IP::isIPAddress( $this->getName() ) ) {
1428 $ip = $this->getName();
1429 } else if( !$ip ) {
1430 $ip = wfGetIP();
1431 }
1432 $blocked = false;
1433 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1434 $this->mBlockedGlobally = (bool)$blocked;
1435 return $this->mBlockedGlobally;
1436 }
1437
1438 /**
1439 * Check if user account is locked
1440 *
1441 * @return Bool True if locked, false otherwise
1442 */
1443 function isLocked() {
1444 if( $this->mLocked !== null ) {
1445 return $this->mLocked;
1446 }
1447 global $wgAuth;
1448 $authUser = $wgAuth->getUserInstance( $this );
1449 $this->mLocked = (bool)$authUser->isLocked();
1450 return $this->mLocked;
1451 }
1452
1453 /**
1454 * Check if user account is hidden
1455 *
1456 * @return Bool True if hidden, false otherwise
1457 */
1458 function isHidden() {
1459 if( $this->mHideName !== null ) {
1460 return $this->mHideName;
1461 }
1462 $this->getBlockedStatus();
1463 if( !$this->mHideName ) {
1464 global $wgAuth;
1465 $authUser = $wgAuth->getUserInstance( $this );
1466 $this->mHideName = (bool)$authUser->isHidden();
1467 }
1468 return $this->mHideName;
1469 }
1470
1471 /**
1472 * Get the user's ID.
1473 * @return Int The user's ID; 0 if the user is anonymous or nonexistent
1474 */
1475 function getId() {
1476 if( $this->mId === null and $this->mName !== null
1477 and User::isIP( $this->mName ) ) {
1478 // Special case, we know the user is anonymous
1479 return 0;
1480 } elseif( $this->mId === null ) {
1481 // Don't load if this was initialized from an ID
1482 $this->load();
1483 }
1484 return $this->mId;
1485 }
1486
1487 /**
1488 * Set the user and reload all fields according to a given ID
1489 * @param $v Int User ID to reload
1490 */
1491 function setId( $v ) {
1492 $this->mId = $v;
1493 $this->clearInstanceCache( 'id' );
1494 }
1495
1496 /**
1497 * Get the user name, or the IP of an anonymous user
1498 * @return String User's name or IP address
1499 */
1500 function getName() {
1501 if ( !$this->mDataLoaded && $this->mFrom == 'name' ) {
1502 # Special case optimisation
1503 return $this->mName;
1504 } else {
1505 $this->load();
1506 if ( $this->mName === false ) {
1507 # Clean up IPs
1508 $this->mName = IP::sanitizeIP( wfGetIP() );
1509 }
1510 return $this->mName;
1511 }
1512 }
1513
1514 /**
1515 * Set the user name.
1516 *
1517 * This does not reload fields from the database according to the given
1518 * name. Rather, it is used to create a temporary "nonexistent user" for
1519 * later addition to the database. It can also be used to set the IP
1520 * address for an anonymous user to something other than the current
1521 * remote IP.
1522 *
1523 * @note User::newFromName() has rougly the same function, when the named user
1524 * does not exist.
1525 * @param $str String New user name to set
1526 */
1527 function setName( $str ) {
1528 $this->load();
1529 $this->mName = $str;
1530 }
1531
1532 /**
1533 * Get the user's name escaped by underscores.
1534 * @return String Username escaped by underscores.
1535 */
1536 function getTitleKey() {
1537 return str_replace( ' ', '_', $this->getName() );
1538 }
1539
1540 /**
1541 * Check if the user has new messages.
1542 * @return Bool True if the user has new messages
1543 */
1544 function getNewtalk() {
1545 $this->load();
1546
1547 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1548 if( $this->mNewtalk === -1 ) {
1549 $this->mNewtalk = false; # reset talk page status
1550
1551 # Check memcached separately for anons, who have no
1552 # entire User object stored in there.
1553 if( !$this->mId ) {
1554 global $wgMemc;
1555 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1556 $newtalk = $wgMemc->get( $key );
1557 if( strval( $newtalk ) !== '' ) {
1558 $this->mNewtalk = (bool)$newtalk;
1559 } else {
1560 // Since we are caching this, make sure it is up to date by getting it
1561 // from the master
1562 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1563 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1564 }
1565 } else {
1566 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1567 }
1568 }
1569
1570 return (bool)$this->mNewtalk;
1571 }
1572
1573 /**
1574 * Return the talk page(s) this user has new messages on.
1575 * @return Array of String page URLs
1576 */
1577 function getNewMessageLinks() {
1578 $talks = array();
1579 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) )
1580 return $talks;
1581
1582 if( !$this->getNewtalk() )
1583 return array();
1584 $up = $this->getUserPage();
1585 $utp = $up->getTalkPage();
1586 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL() ) );
1587 }
1588
1589 /**
1590 * Internal uncached check for new messages
1591 *
1592 * @see getNewtalk()
1593 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1594 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1595 * @param $fromMaster Bool true to fetch from the master, false for a slave
1596 * @return Bool True if the user has new messages
1597 * @private
1598 */
1599 function checkNewtalk( $field, $id, $fromMaster = false ) {
1600 if ( $fromMaster ) {
1601 $db = wfGetDB( DB_MASTER );
1602 } else {
1603 $db = wfGetDB( DB_SLAVE );
1604 }
1605 $ok = $db->selectField( 'user_newtalk', $field,
1606 array( $field => $id ), __METHOD__ );
1607 return $ok !== false;
1608 }
1609
1610 /**
1611 * Add or update the new messages flag
1612 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1613 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1614 * @return Bool True if successful, false otherwise
1615 * @private
1616 */
1617 function updateNewtalk( $field, $id ) {
1618 $dbw = wfGetDB( DB_MASTER );
1619 $dbw->insert( 'user_newtalk',
1620 array( $field => $id ),
1621 __METHOD__,
1622 'IGNORE' );
1623 if ( $dbw->affectedRows() ) {
1624 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
1625 return true;
1626 } else {
1627 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
1628 return false;
1629 }
1630 }
1631
1632 /**
1633 * Clear the new messages flag for the given user
1634 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1635 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1636 * @return Bool True if successful, false otherwise
1637 * @private
1638 */
1639 function deleteNewtalk( $field, $id ) {
1640 $dbw = wfGetDB( DB_MASTER );
1641 $dbw->delete( 'user_newtalk',
1642 array( $field => $id ),
1643 __METHOD__ );
1644 if ( $dbw->affectedRows() ) {
1645 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
1646 return true;
1647 } else {
1648 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
1649 return false;
1650 }
1651 }
1652
1653 /**
1654 * Update the 'You have new messages!' status.
1655 * @param $val Bool Whether the user has new messages
1656 */
1657 function setNewtalk( $val ) {
1658 if( wfReadOnly() ) {
1659 return;
1660 }
1661
1662 $this->load();
1663 $this->mNewtalk = $val;
1664
1665 if( $this->isAnon() ) {
1666 $field = 'user_ip';
1667 $id = $this->getName();
1668 } else {
1669 $field = 'user_id';
1670 $id = $this->getId();
1671 }
1672 global $wgMemc;
1673
1674 if( $val ) {
1675 $changed = $this->updateNewtalk( $field, $id );
1676 } else {
1677 $changed = $this->deleteNewtalk( $field, $id );
1678 }
1679
1680 if( $this->isAnon() ) {
1681 // Anons have a separate memcached space, since
1682 // user records aren't kept for them.
1683 $key = wfMemcKey( 'newtalk', 'ip', $id );
1684 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
1685 }
1686 if ( $changed ) {
1687 $this->invalidateCache();
1688 }
1689 }
1690
1691 /**
1692 * Generate a current or new-future timestamp to be stored in the
1693 * user_touched field when we update things.
1694 * @return String Timestamp in TS_MW format
1695 */
1696 private static function newTouchedTimestamp() {
1697 global $wgClockSkewFudge;
1698 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1699 }
1700
1701 /**
1702 * Clear user data from memcached.
1703 * Use after applying fun updates to the database; caller's
1704 * responsibility to update user_touched if appropriate.
1705 *
1706 * Called implicitly from invalidateCache() and saveSettings().
1707 */
1708 private function clearSharedCache() {
1709 $this->load();
1710 if( $this->mId ) {
1711 global $wgMemc;
1712 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1713 }
1714 }
1715
1716 /**
1717 * Immediately touch the user data cache for this account.
1718 * Updates user_touched field, and removes account data from memcached
1719 * for reload on the next hit.
1720 */
1721 function invalidateCache() {
1722 if( wfReadOnly() ) {
1723 return;
1724 }
1725 $this->load();
1726 if( $this->mId ) {
1727 $this->mTouched = self::newTouchedTimestamp();
1728
1729 $dbw = wfGetDB( DB_MASTER );
1730 $dbw->update( 'user',
1731 array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
1732 array( 'user_id' => $this->mId ),
1733 __METHOD__ );
1734
1735 $this->clearSharedCache();
1736 }
1737 }
1738
1739 /**
1740 * Validate the cache for this account.
1741 * @param $timestamp String A timestamp in TS_MW format
1742 */
1743 function validateCache( $timestamp ) {
1744 $this->load();
1745 return ( $timestamp >= $this->mTouched );
1746 }
1747
1748 /**
1749 * Get the user touched timestamp
1750 * @return String timestamp
1751 */
1752 function getTouched() {
1753 $this->load();
1754 return $this->mTouched;
1755 }
1756
1757 /**
1758 * Set the password and reset the random token.
1759 * Calls through to authentication plugin if necessary;
1760 * will have no effect if the auth plugin refuses to
1761 * pass the change through or if the legal password
1762 * checks fail.
1763 *
1764 * As a special case, setting the password to null
1765 * wipes it, so the account cannot be logged in until
1766 * a new password is set, for instance via e-mail.
1767 *
1768 * @param $str String New password to set
1769 * @throws PasswordError on failure
1770 */
1771 function setPassword( $str ) {
1772 global $wgAuth;
1773
1774 if( $str !== null ) {
1775 if( !$wgAuth->allowPasswordChange() ) {
1776 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1777 }
1778
1779 if( !$this->isValidPassword( $str ) ) {
1780 global $wgMinimalPasswordLength;
1781 $valid = $this->getPasswordValidity( $str );
1782 if ( is_array( $valid ) ) {
1783 $message = array_shift( $valid );
1784 $params = $valid;
1785 } else {
1786 $message = $valid;
1787 $params = array( $wgMinimalPasswordLength );
1788 }
1789 throw new PasswordError( wfMsgExt( $message, array( 'parsemag' ), $params ) );
1790 }
1791 }
1792
1793 if( !$wgAuth->setPassword( $this, $str ) ) {
1794 throw new PasswordError( wfMsg( 'externaldberror' ) );
1795 }
1796
1797 $this->setInternalPassword( $str );
1798
1799 return true;
1800 }
1801
1802 /**
1803 * Set the password and reset the random token unconditionally.
1804 *
1805 * @param $str String New password to set
1806 */
1807 function setInternalPassword( $str ) {
1808 $this->load();
1809 $this->setToken();
1810
1811 if( $str === null ) {
1812 // Save an invalid hash...
1813 $this->mPassword = '';
1814 } else {
1815 $this->mPassword = self::crypt( $str );
1816 }
1817 $this->mNewpassword = '';
1818 $this->mNewpassTime = null;
1819 }
1820
1821 /**
1822 * Get the user's current token.
1823 * @return String Token
1824 */
1825 function getToken() {
1826 $this->load();
1827 return $this->mToken;
1828 }
1829
1830 /**
1831 * Set the random token (used for persistent authentication)
1832 * Called from loadDefaults() among other places.
1833 *
1834 * @param $token String If specified, set the token to this value
1835 * @private
1836 */
1837 function setToken( $token = false ) {
1838 global $wgSecretKey, $wgProxyKey;
1839 $this->load();
1840 if ( !$token ) {
1841 if ( $wgSecretKey ) {
1842 $key = $wgSecretKey;
1843 } elseif ( $wgProxyKey ) {
1844 $key = $wgProxyKey;
1845 } else {
1846 $key = microtime();
1847 }
1848 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
1849 } else {
1850 $this->mToken = $token;
1851 }
1852 }
1853
1854 /**
1855 * Set the cookie password
1856 *
1857 * @param $str String New cookie password
1858 * @private
1859 */
1860 function setCookiePassword( $str ) {
1861 $this->load();
1862 $this->mCookiePassword = md5( $str );
1863 }
1864
1865 /**
1866 * Set the password for a password reminder or new account email
1867 *
1868 * @param $str String New password to set
1869 * @param $throttle Bool If true, reset the throttle timestamp to the present
1870 */
1871 function setNewpassword( $str, $throttle = true ) {
1872 $this->load();
1873 $this->mNewpassword = self::crypt( $str );
1874 if ( $throttle ) {
1875 $this->mNewpassTime = wfTimestampNow();
1876 }
1877 }
1878
1879 /**
1880 * Has password reminder email been sent within the last
1881 * $wgPasswordReminderResendTime hours?
1882 * @return Bool
1883 */
1884 function isPasswordReminderThrottled() {
1885 global $wgPasswordReminderResendTime;
1886 $this->load();
1887 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1888 return false;
1889 }
1890 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1891 return time() < $expiry;
1892 }
1893
1894 /**
1895 * Get the user's e-mail address
1896 * @return String User's email address
1897 */
1898 function getEmail() {
1899 $this->load();
1900 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
1901 return $this->mEmail;
1902 }
1903
1904 /**
1905 * Get the timestamp of the user's e-mail authentication
1906 * @return String TS_MW timestamp
1907 */
1908 function getEmailAuthenticationTimestamp() {
1909 $this->load();
1910 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
1911 return $this->mEmailAuthenticated;
1912 }
1913
1914 /**
1915 * Set the user's e-mail address
1916 * @param $str String New e-mail address
1917 */
1918 function setEmail( $str ) {
1919 $this->load();
1920 $this->mEmail = $str;
1921 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
1922 }
1923
1924 /**
1925 * Get the user's real name
1926 * @return String User's real name
1927 */
1928 function getRealName() {
1929 $this->load();
1930 return $this->mRealName;
1931 }
1932
1933 /**
1934 * Set the user's real name
1935 * @param $str String New real name
1936 */
1937 function setRealName( $str ) {
1938 $this->load();
1939 $this->mRealName = $str;
1940 }
1941
1942 /**
1943 * Get the user's current setting for a given option.
1944 *
1945 * @param $oname String The option to check
1946 * @param $defaultOverride String A default value returned if the option does not exist
1947 * @return String User's current value for the option
1948 * @see getBoolOption()
1949 * @see getIntOption()
1950 */
1951 function getOption( $oname, $defaultOverride = null ) {
1952 $this->loadOptions();
1953
1954 if ( is_null( $this->mOptions ) ) {
1955 if($defaultOverride != '') {
1956 return $defaultOverride;
1957 }
1958 $this->mOptions = User::getDefaultOptions();
1959 }
1960
1961 if ( array_key_exists( $oname, $this->mOptions ) ) {
1962 return $this->mOptions[$oname];
1963 } else {
1964 return $defaultOverride;
1965 }
1966 }
1967
1968 /**
1969 * Get all user's options
1970 *
1971 * @return array
1972 */
1973 public function getOptions() {
1974 $this->loadOptions();
1975 return $this->mOptions;
1976 }
1977
1978 /**
1979 * Get the user's current setting for a given option, as a boolean value.
1980 *
1981 * @param $oname String The option to check
1982 * @return Bool User's current value for the option
1983 * @see getOption()
1984 */
1985 function getBoolOption( $oname ) {
1986 return (bool)$this->getOption( $oname );
1987 }
1988
1989
1990 /**
1991 * Get the user's current setting for a given option, as a boolean value.
1992 *
1993 * @param $oname String The option to check
1994 * @param $defaultOverride Int A default value returned if the option does not exist
1995 * @return Int User's current value for the option
1996 * @see getOption()
1997 */
1998 function getIntOption( $oname, $defaultOverride=0 ) {
1999 $val = $this->getOption( $oname );
2000 if( $val == '' ) {
2001 $val = $defaultOverride;
2002 }
2003 return intval( $val );
2004 }
2005
2006 /**
2007 * Set the given option for a user.
2008 *
2009 * @param $oname String The option to set
2010 * @param $val mixed New value to set
2011 */
2012 function setOption( $oname, $val ) {
2013 $this->load();
2014 $this->loadOptions();
2015
2016 if ( $oname == 'skin' ) {
2017 # Clear cached skin, so the new one displays immediately in Special:Preferences
2018 $this->mSkin = null;
2019 }
2020
2021 // Explicitly NULL values should refer to defaults
2022 global $wgDefaultUserOptions;
2023 if( is_null( $val ) && isset( $wgDefaultUserOptions[$oname] ) ) {
2024 $val = $wgDefaultUserOptions[$oname];
2025 }
2026
2027 $this->mOptions[$oname] = $val;
2028 }
2029
2030 /**
2031 * Reset all options to the site defaults
2032 */
2033 function resetOptions() {
2034 $this->mOptions = self::getDefaultOptions();
2035 }
2036
2037 /**
2038 * Get the user's preferred date format.
2039 * @return String User's preferred date format
2040 */
2041 function getDatePreference() {
2042 // Important migration for old data rows
2043 if ( is_null( $this->mDatePreference ) ) {
2044 global $wgLang;
2045 $value = $this->getOption( 'date' );
2046 $map = $wgLang->getDatePreferenceMigrationMap();
2047 if ( isset( $map[$value] ) ) {
2048 $value = $map[$value];
2049 }
2050 $this->mDatePreference = $value;
2051 }
2052 return $this->mDatePreference;
2053 }
2054
2055 /**
2056 * Get the user preferred stub threshold
2057 */
2058 function getStubThreshold() {
2059 global $wgMaxArticleSize; # Maximum article size, in Kb
2060 $threshold = intval( $this->getOption( 'stubthreshold' ) );
2061 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2062 # If they have set an impossible value, disable the preference
2063 # so we can use the parser cache again.
2064 $threshold = 0;
2065 }
2066 return $threshold;
2067 }
2068
2069 /**
2070 * Get the permissions this user has.
2071 * @return Array of String permission names
2072 */
2073 function getRights() {
2074 if ( is_null( $this->mRights ) ) {
2075 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2076 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2077 // Force reindexation of rights when a hook has unset one of them
2078 $this->mRights = array_values( $this->mRights );
2079 }
2080 return $this->mRights;
2081 }
2082
2083 /**
2084 * Get the list of explicit group memberships this user has.
2085 * The implicit * and user groups are not included.
2086 * @return Array of String internal group names
2087 */
2088 function getGroups() {
2089 $this->load();
2090 return $this->mGroups;
2091 }
2092
2093 /**
2094 * Get the list of implicit group memberships this user has.
2095 * This includes all explicit groups, plus 'user' if logged in,
2096 * '*' for all accounts, and autopromoted groups
2097 * @param $recache Bool Whether to avoid the cache
2098 * @return Array of String internal group names
2099 */
2100 function getEffectiveGroups( $recache = false ) {
2101 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2102 wfProfileIn( __METHOD__ );
2103 $this->mEffectiveGroups = $this->getGroups();
2104 $this->mEffectiveGroups[] = '*';
2105 if( $this->getId() ) {
2106 $this->mEffectiveGroups[] = 'user';
2107
2108 $this->mEffectiveGroups = array_unique( array_merge(
2109 $this->mEffectiveGroups,
2110 Autopromote::getAutopromoteGroups( $this )
2111 ) );
2112
2113 # Hook for additional groups
2114 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2115 }
2116 wfProfileOut( __METHOD__ );
2117 }
2118 return $this->mEffectiveGroups;
2119 }
2120
2121 /**
2122 * Get the user's edit count.
2123 * @return Int
2124 */
2125 function getEditCount() {
2126 if( $this->getId() ) {
2127 if ( !isset( $this->mEditCount ) ) {
2128 /* Populate the count, if it has not been populated yet */
2129 $this->mEditCount = User::edits( $this->mId );
2130 }
2131 return $this->mEditCount;
2132 } else {
2133 /* nil */
2134 return null;
2135 }
2136 }
2137
2138 /**
2139 * Add the user to the given group.
2140 * This takes immediate effect.
2141 * @param $group String Name of the group to add
2142 */
2143 function addGroup( $group ) {
2144 $dbw = wfGetDB( DB_MASTER );
2145 if( $this->getId() ) {
2146 $dbw->insert( 'user_groups',
2147 array(
2148 'ug_user' => $this->getID(),
2149 'ug_group' => $group,
2150 ),
2151 __METHOD__,
2152 array( 'IGNORE' ) );
2153 }
2154
2155 $this->loadGroups();
2156 $this->mGroups[] = $group;
2157 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2158
2159 $this->invalidateCache();
2160 }
2161
2162 /**
2163 * Remove the user from the given group.
2164 * This takes immediate effect.
2165 * @param $group String Name of the group to remove
2166 */
2167 function removeGroup( $group ) {
2168 $this->load();
2169 $dbw = wfGetDB( DB_MASTER );
2170 $dbw->delete( 'user_groups',
2171 array(
2172 'ug_user' => $this->getID(),
2173 'ug_group' => $group,
2174 ), __METHOD__ );
2175
2176 $this->loadGroups();
2177 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2178 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2179
2180 $this->invalidateCache();
2181 }
2182
2183 /**
2184 * Get whether the user is logged in
2185 * @return Bool
2186 */
2187 function isLoggedIn() {
2188 return $this->getID() != 0;
2189 }
2190
2191 /**
2192 * Get whether the user is anonymous
2193 * @return Bool
2194 */
2195 function isAnon() {
2196 return !$this->isLoggedIn();
2197 }
2198
2199 /**
2200
2201 * Check if user is allowed to access a feature / make an action
2202 * @param $action String action to be checked
2203 * @return Boolean: True if action is allowed, else false
2204 */
2205 function isAllowed( $action = '' ) {
2206 if ( $action === '' ) {
2207 return true; // In the spirit of DWIM
2208 }
2209 # Patrolling may not be enabled
2210 if( $action === 'patrol' || $action === 'autopatrol' ) {
2211 global $wgUseRCPatrol, $wgUseNPPatrol;
2212 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2213 return false;
2214 }
2215 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2216 # by misconfiguration: 0 == 'foo'
2217 return in_array( $action, $this->getRights(), true );
2218 }
2219
2220 /**
2221 * Check whether to enable recent changes patrol features for this user
2222 * @return Boolean: True or false
2223 */
2224 public function useRCPatrol() {
2225 global $wgUseRCPatrol;
2226 return( $wgUseRCPatrol && ( $this->isAllowed( 'patrol' ) || $this->isAllowed( 'patrolmarks' ) ) );
2227 }
2228
2229 /**
2230 * Check whether to enable new pages patrol features for this user
2231 * @return Bool True or false
2232 */
2233 public function useNPPatrol() {
2234 global $wgUseRCPatrol, $wgUseNPPatrol;
2235 return( ( $wgUseRCPatrol || $wgUseNPPatrol ) && ( $this->isAllowed( 'patrol' ) || $this->isAllowed( 'patrolmarks' ) ) );
2236 }
2237
2238 /**
2239 * Get the current skin, loading it if required, and setting a title
2240 * @param $t Title: the title to use in the skin
2241 * @return Skin The current skin
2242 * @todo: FIXME : need to check the old failback system [AV]
2243 */
2244 function getSkin( $t = null ) {
2245 if( !$this->mSkin ) {
2246 global $wgOut;
2247 $this->mSkin = $this->createSkinObject();
2248 $this->mSkin->setTitle( $wgOut->getTitle() );
2249 }
2250 if ( $t && ( !$this->mSkin->getTitle() || !$t->equals( $this->mSkin->getTitle() ) ) ) {
2251 $skin = $this->createSkinObject();
2252 $skin->setTitle( $t );
2253 return $skin;
2254 } else {
2255 return $this->mSkin;
2256 }
2257 }
2258
2259 // Creates a Skin object, for getSkin()
2260 private function createSkinObject() {
2261 wfProfileIn( __METHOD__ );
2262
2263 global $wgHiddenPrefs;
2264 if( !in_array( 'skin', $wgHiddenPrefs ) ) {
2265 global $wgRequest;
2266 # get the user skin
2267 $userSkin = $this->getOption( 'skin' );
2268 $userSkin = $wgRequest->getVal( 'useskin', $userSkin );
2269 } else {
2270 # if we're not allowing users to override, then use the default
2271 global $wgDefaultSkin;
2272 $userSkin = $wgDefaultSkin;
2273 }
2274
2275 $skin = Skin::newFromKey( $userSkin );
2276 wfProfileOut( __METHOD__ );
2277
2278 return $skin;
2279 }
2280
2281 /**
2282 * Check the watched status of an article.
2283 * @param $title Title of the article to look at
2284 * @return Bool
2285 */
2286 function isWatched( $title ) {
2287 $wl = WatchedItem::fromUserTitle( $this, $title );
2288 return $wl->isWatched();
2289 }
2290
2291 /**
2292 * Watch an article.
2293 * @param $title Title of the article to look at
2294 */
2295 function addWatch( $title ) {
2296 $wl = WatchedItem::fromUserTitle( $this, $title );
2297 $wl->addWatch();
2298 $this->invalidateCache();
2299 }
2300
2301 /**
2302 * Stop watching an article.
2303 * @param $title Title of the article to look at
2304 */
2305 function removeWatch( $title ) {
2306 $wl = WatchedItem::fromUserTitle( $this, $title );
2307 $wl->removeWatch();
2308 $this->invalidateCache();
2309 }
2310
2311 /**
2312 * Clear the user's notification timestamp for the given title.
2313 * If e-notif e-mails are on, they will receive notification mails on
2314 * the next change of the page if it's watched etc.
2315 * @param $title Title of the article to look at
2316 */
2317 function clearNotification( &$title ) {
2318 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2319
2320 # Do nothing if the database is locked to writes
2321 if( wfReadOnly() ) {
2322 return;
2323 }
2324
2325 if( $title->getNamespace() == NS_USER_TALK &&
2326 $title->getText() == $this->getName() ) {
2327 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2328 return;
2329 $this->setNewtalk( false );
2330 }
2331
2332 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2333 return;
2334 }
2335
2336 if( $this->isAnon() ) {
2337 // Nothing else to do...
2338 return;
2339 }
2340
2341 // Only update the timestamp if the page is being watched.
2342 // The query to find out if it is watched is cached both in memcached and per-invocation,
2343 // and when it does have to be executed, it can be on a slave
2344 // If this is the user's newtalk page, we always update the timestamp
2345 if( $title->getNamespace() == NS_USER_TALK &&
2346 $title->getText() == $wgUser->getName() )
2347 {
2348 $watched = true;
2349 } elseif ( $this->getId() == $wgUser->getId() ) {
2350 $watched = $title->userIsWatching();
2351 } else {
2352 $watched = true;
2353 }
2354
2355 // If the page is watched by the user (or may be watched), update the timestamp on any
2356 // any matching rows
2357 if ( $watched ) {
2358 $dbw = wfGetDB( DB_MASTER );
2359 $dbw->update( 'watchlist',
2360 array( /* SET */
2361 'wl_notificationtimestamp' => null
2362 ), array( /* WHERE */
2363 'wl_title' => $title->getDBkey(),
2364 'wl_namespace' => $title->getNamespace(),
2365 'wl_user' => $this->getID()
2366 ), __METHOD__
2367 );
2368 }
2369 }
2370
2371 /**
2372 * Resets all of the given user's page-change notification timestamps.
2373 * If e-notif e-mails are on, they will receive notification mails on
2374 * the next change of any watched page.
2375 *
2376 * @param $currentUser Int User ID
2377 */
2378 function clearAllNotifications( $currentUser ) {
2379 global $wgUseEnotif, $wgShowUpdatedMarker;
2380 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2381 $this->setNewtalk( false );
2382 return;
2383 }
2384 if( $currentUser != 0 ) {
2385 $dbw = wfGetDB( DB_MASTER );
2386 $dbw->update( 'watchlist',
2387 array( /* SET */
2388 'wl_notificationtimestamp' => null
2389 ), array( /* WHERE */
2390 'wl_user' => $currentUser
2391 ), __METHOD__
2392 );
2393 # We also need to clear here the "you have new message" notification for the own user_talk page
2394 # This is cleared one page view later in Article::viewUpdates();
2395 }
2396 }
2397
2398 /**
2399 * Set this user's options from an encoded string
2400 * @param $str String Encoded options to import
2401 * @private
2402 */
2403 function decodeOptions( $str ) {
2404 if( !$str )
2405 return;
2406
2407 $this->mOptionsLoaded = true;
2408 $this->mOptionOverrides = array();
2409
2410 // If an option is not set in $str, use the default value
2411 $this->mOptions = self::getDefaultOptions();
2412
2413 $a = explode( "\n", $str );
2414 foreach ( $a as $s ) {
2415 $m = array();
2416 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2417 $this->mOptions[$m[1]] = $m[2];
2418 $this->mOptionOverrides[$m[1]] = $m[2];
2419 }
2420 }
2421 }
2422
2423 /**
2424 * Set a cookie on the user's client. Wrapper for
2425 * WebResponse::setCookie
2426 * @param $name String Name of the cookie to set
2427 * @param $value String Value to set
2428 * @param $exp Int Expiration time, as a UNIX time value;
2429 * if 0 or not specified, use the default $wgCookieExpiration
2430 */
2431 protected function setCookie( $name, $value, $exp = 0 ) {
2432 global $wgRequest;
2433 $wgRequest->response()->setcookie( $name, $value, $exp );
2434 }
2435
2436 /**
2437 * Clear a cookie on the user's client
2438 * @param $name String Name of the cookie to clear
2439 */
2440 protected function clearCookie( $name ) {
2441 $this->setCookie( $name, '', time() - 86400 );
2442 }
2443
2444 /**
2445 * Set the default cookies for this session on the user's client.
2446 */
2447 function setCookies() {
2448 $this->load();
2449 if ( 0 == $this->mId ) return;
2450 $session = array(
2451 'wsUserID' => $this->mId,
2452 'wsToken' => $this->mToken,
2453 'wsUserName' => $this->getName()
2454 );
2455 $cookies = array(
2456 'UserID' => $this->mId,
2457 'UserName' => $this->getName(),
2458 );
2459 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2460 $cookies['Token'] = $this->mToken;
2461 } else {
2462 $cookies['Token'] = false;
2463 }
2464
2465 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2466 #check for null, since the hook could cause a null value
2467 if ( !is_null( $session ) && isset( $_SESSION ) ){
2468 $_SESSION = $session + $_SESSION;
2469 }
2470 foreach ( $cookies as $name => $value ) {
2471 if ( $value === false ) {
2472 $this->clearCookie( $name );
2473 } else {
2474 $this->setCookie( $name, $value );
2475 }
2476 }
2477 }
2478
2479 /**
2480 * Log this user out.
2481 */
2482 function logout() {
2483 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
2484 $this->doLogout();
2485 }
2486 }
2487
2488 /**
2489 * Clear the user's cookies and session, and reset the instance cache.
2490 * @private
2491 * @see logout()
2492 */
2493 function doLogout() {
2494 $this->clearInstanceCache( 'defaults' );
2495
2496 $_SESSION['wsUserID'] = 0;
2497
2498 $this->clearCookie( 'UserID' );
2499 $this->clearCookie( 'Token' );
2500
2501 # Remember when user logged out, to prevent seeing cached pages
2502 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
2503 }
2504
2505 /**
2506 * Save this user's settings into the database.
2507 * @todo Only rarely do all these fields need to be set!
2508 */
2509 function saveSettings() {
2510 $this->load();
2511 if ( wfReadOnly() ) { return; }
2512 if ( 0 == $this->mId ) { return; }
2513
2514 $this->mTouched = self::newTouchedTimestamp();
2515
2516 $dbw = wfGetDB( DB_MASTER );
2517 $dbw->update( 'user',
2518 array( /* SET */
2519 'user_name' => $this->mName,
2520 'user_password' => $this->mPassword,
2521 'user_newpassword' => $this->mNewpassword,
2522 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2523 'user_real_name' => $this->mRealName,
2524 'user_email' => $this->mEmail,
2525 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2526 'user_options' => '',
2527 'user_touched' => $dbw->timestamp( $this->mTouched ),
2528 'user_token' => $this->mToken,
2529 'user_email_token' => $this->mEmailToken,
2530 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
2531 ), array( /* WHERE */
2532 'user_id' => $this->mId
2533 ), __METHOD__
2534 );
2535
2536 $this->saveOptions();
2537
2538 wfRunHooks( 'UserSaveSettings', array( $this ) );
2539 $this->clearSharedCache();
2540 $this->getUserPage()->invalidateCache();
2541 }
2542
2543 /**
2544 * If only this user's username is known, and it exists, return the user ID.
2545 * @return Int
2546 */
2547 function idForName() {
2548 $s = trim( $this->getName() );
2549 if ( $s === '' ) return 0;
2550
2551 $dbr = wfGetDB( DB_SLAVE );
2552 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
2553 if ( $id === false ) {
2554 $id = 0;
2555 }
2556 return $id;
2557 }
2558
2559 /**
2560 * Add a user to the database, return the user object
2561 *
2562 * @param $name String Username to add
2563 * @param $params Array of Strings Non-default parameters to save to the database:
2564 * - password The user's password. Password logins will be disabled if this is omitted.
2565 * - newpassword A temporary password mailed to the user
2566 * - email The user's email address
2567 * - email_authenticated The email authentication timestamp
2568 * - real_name The user's real name
2569 * - options An associative array of non-default options
2570 * - token Random authentication token. Do not set.
2571 * - registration Registration timestamp. Do not set.
2572 *
2573 * @return User object, or null if the username already exists
2574 */
2575 static function createNew( $name, $params = array() ) {
2576 $user = new User;
2577 $user->load();
2578 if ( isset( $params['options'] ) ) {
2579 $user->mOptions = $params['options'] + (array)$user->mOptions;
2580 unset( $params['options'] );
2581 }
2582 $dbw = wfGetDB( DB_MASTER );
2583 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2584 $fields = array(
2585 'user_id' => $seqVal,
2586 'user_name' => $name,
2587 'user_password' => $user->mPassword,
2588 'user_newpassword' => $user->mNewpassword,
2589 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
2590 'user_email' => $user->mEmail,
2591 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
2592 'user_real_name' => $user->mRealName,
2593 'user_options' => '',
2594 'user_token' => $user->mToken,
2595 'user_registration' => $dbw->timestamp( $user->mRegistration ),
2596 'user_editcount' => 0,
2597 );
2598 foreach ( $params as $name => $value ) {
2599 $fields["user_$name"] = $value;
2600 }
2601 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
2602 if ( $dbw->affectedRows() ) {
2603 $newUser = User::newFromId( $dbw->insertId() );
2604 } else {
2605 $newUser = null;
2606 }
2607 return $newUser;
2608 }
2609
2610 /**
2611 * Add this existing user object to the database
2612 */
2613 function addToDatabase() {
2614 $this->load();
2615 $dbw = wfGetDB( DB_MASTER );
2616 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2617 $dbw->insert( 'user',
2618 array(
2619 'user_id' => $seqVal,
2620 'user_name' => $this->mName,
2621 'user_password' => $this->mPassword,
2622 'user_newpassword' => $this->mNewpassword,
2623 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2624 'user_email' => $this->mEmail,
2625 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2626 'user_real_name' => $this->mRealName,
2627 'user_options' => '',
2628 'user_token' => $this->mToken,
2629 'user_registration' => $dbw->timestamp( $this->mRegistration ),
2630 'user_editcount' => 0,
2631 ), __METHOD__
2632 );
2633 $this->mId = $dbw->insertId();
2634
2635 // Clear instance cache other than user table data, which is already accurate
2636 $this->clearInstanceCache();
2637
2638 $this->saveOptions();
2639 }
2640
2641 /**
2642 * If this (non-anonymous) user is blocked, block any IP address
2643 * they've successfully logged in from.
2644 */
2645 function spreadBlock() {
2646 wfDebug( __METHOD__ . "()\n" );
2647 $this->load();
2648 if ( $this->mId == 0 ) {
2649 return;
2650 }
2651
2652 $userblock = Block::newFromDB( '', $this->mId );
2653 if ( !$userblock ) {
2654 return;
2655 }
2656
2657 $userblock->doAutoblock( wfGetIP() );
2658 }
2659
2660 /**
2661 * Generate a string which will be different for any combination of
2662 * user options which would produce different parser output.
2663 * This will be used as part of the hash key for the parser cache,
2664 * so users with the same options can share the same cached data
2665 * safely.
2666 *
2667 * Extensions which require it should install 'PageRenderingHash' hook,
2668 * which will give them a chance to modify this key based on their own
2669 * settings.
2670 *
2671 * @deprecated @since 1.17 use the ParserOptions object to get the relevant options
2672 * @return String Page rendering hash
2673 */
2674 function getPageRenderingHash() {
2675 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2676 if( $this->mHash ){
2677 return $this->mHash;
2678 }
2679 wfDeprecated( __METHOD__ );
2680
2681 // stubthreshold is only included below for completeness,
2682 // since it disables the parser cache, its value will always
2683 // be 0 when this function is called by parsercache.
2684
2685 $confstr = $this->getOption( 'math' );
2686 $confstr .= '!' . $this->getStubThreshold();
2687 if ( $wgUseDynamicDates ) { # This is wrong (bug 24714)
2688 $confstr .= '!' . $this->getDatePreference();
2689 }
2690 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ? '1' : '' );
2691 $confstr .= '!' . $wgLang->getCode();
2692 $confstr .= '!' . $this->getOption( 'thumbsize' );
2693 // add in language specific options, if any
2694 $extra = $wgContLang->getExtraHashOptions();
2695 $confstr .= $extra;
2696
2697 // Since the skin could be overloading link(), it should be
2698 // included here but in practice, none of our skins do that.
2699
2700 $confstr .= $wgRenderHashAppend;
2701
2702 // Give a chance for extensions to modify the hash, if they have
2703 // extra options or other effects on the parser cache.
2704 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2705
2706 // Make it a valid memcached key fragment
2707 $confstr = str_replace( ' ', '_', $confstr );
2708 $this->mHash = $confstr;
2709 return $confstr;
2710 }
2711
2712 /**
2713 * Get whether the user is explicitly blocked from account creation.
2714 * @return Bool
2715 */
2716 function isBlockedFromCreateAccount() {
2717 $this->getBlockedStatus();
2718 return $this->mBlock && $this->mBlock->mCreateAccount;
2719 }
2720
2721 /**
2722 * Get whether the user is blocked from using Special:Emailuser.
2723 * @return Bool
2724 */
2725 function isBlockedFromEmailuser() {
2726 $this->getBlockedStatus();
2727 return $this->mBlock && $this->mBlock->mBlockEmail;
2728 }
2729
2730 /**
2731 * Get whether the user is allowed to create an account.
2732 * @return Bool
2733 */
2734 function isAllowedToCreateAccount() {
2735 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2736 }
2737
2738 /**
2739 * Get this user's personal page title.
2740 *
2741 * @return Title: User's personal page title
2742 */
2743 function getUserPage() {
2744 return Title::makeTitle( NS_USER, $this->getName() );
2745 }
2746
2747 /**
2748 * Get this user's talk page title.
2749 *
2750 * @return Title: User's talk page title
2751 */
2752 function getTalkPage() {
2753 $title = $this->getUserPage();
2754 return $title->getTalkPage();
2755 }
2756
2757 /**
2758 * Get the maximum valid user ID.
2759 * @return Integer: User ID
2760 * @static
2761 */
2762 function getMaxID() {
2763 static $res; // cache
2764
2765 if ( isset( $res ) ) {
2766 return $res;
2767 } else {
2768 $dbr = wfGetDB( DB_SLAVE );
2769 return $res = $dbr->selectField( 'user', 'max(user_id)', false, __METHOD__ );
2770 }
2771 }
2772
2773 /**
2774 * Determine whether the user is a newbie. Newbies are either
2775 * anonymous IPs, or the most recently created accounts.
2776 * @return Bool
2777 */
2778 function isNewbie() {
2779 return !$this->isAllowed( 'autoconfirmed' );
2780 }
2781
2782 /**
2783 * Check to see if the given clear-text password is one of the accepted passwords
2784 * @param $password String: user password.
2785 * @return Boolean: True if the given password is correct, otherwise False.
2786 */
2787 function checkPassword( $password ) {
2788 global $wgAuth;
2789 $this->load();
2790
2791 // Even though we stop people from creating passwords that
2792 // are shorter than this, doesn't mean people wont be able
2793 // to. Certain authentication plugins do NOT want to save
2794 // domain passwords in a mysql database, so we should
2795 // check this (incase $wgAuth->strict() is false).
2796 if( !$this->isValidPassword( $password ) ) {
2797 return false;
2798 }
2799
2800 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2801 return true;
2802 } elseif( $wgAuth->strict() ) {
2803 /* Auth plugin doesn't allow local authentication */
2804 return false;
2805 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2806 /* Auth plugin doesn't allow local authentication for this user name */
2807 return false;
2808 }
2809 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
2810 return true;
2811 } elseif ( function_exists( 'iconv' ) ) {
2812 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2813 # Check for this with iconv
2814 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2815 if ( self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) ) {
2816 return true;
2817 }
2818 }
2819 return false;
2820 }
2821
2822 /**
2823 * Check if the given clear-text password matches the temporary password
2824 * sent by e-mail for password reset operations.
2825 * @return Boolean: True if matches, false otherwise
2826 */
2827 function checkTemporaryPassword( $plaintext ) {
2828 global $wgNewPasswordExpiry;
2829 if( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
2830 if ( is_null( $this->mNewpassTime ) ) {
2831 return true;
2832 }
2833 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
2834 return ( time() < $expiry );
2835 } else {
2836 return false;
2837 }
2838 }
2839
2840 /**
2841 * Initialize (if necessary) and return a session token value
2842 * which can be used in edit forms to show that the user's
2843 * login credentials aren't being hijacked with a foreign form
2844 * submission.
2845 *
2846 * @param $salt String|Array of Strings Optional function-specific data for hashing
2847 * @return String The new edit token
2848 */
2849 function editToken( $salt = '' ) {
2850 if ( $this->isAnon() ) {
2851 return EDIT_TOKEN_SUFFIX;
2852 } else {
2853 if( !isset( $_SESSION['wsEditToken'] ) ) {
2854 $token = $this->generateToken();
2855 $_SESSION['wsEditToken'] = $token;
2856 } else {
2857 $token = $_SESSION['wsEditToken'];
2858 }
2859 if( is_array( $salt ) ) {
2860 $salt = implode( '|', $salt );
2861 }
2862 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2863 }
2864 }
2865
2866 /**
2867 * Generate a looking random token for various uses.
2868 *
2869 * @param $salt String Optional salt value
2870 * @return String The new random token
2871 */
2872 function generateToken( $salt = '' ) {
2873 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2874 return md5( $token . $salt );
2875 }
2876
2877 /**
2878 * Check given value against the token value stored in the session.
2879 * A match should confirm that the form was submitted from the
2880 * user's own login session, not a form submission from a third-party
2881 * site.
2882 *
2883 * @param $val String Input value to compare
2884 * @param $salt String Optional function-specific data for hashing
2885 * @return Boolean: Whether the token matches
2886 */
2887 function matchEditToken( $val, $salt = '' ) {
2888 $sessionToken = $this->editToken( $salt );
2889 if ( $val != $sessionToken ) {
2890 wfDebug( "User::matchEditToken: broken session data\n" );
2891 }
2892 return $val == $sessionToken;
2893 }
2894
2895 /**
2896 * Check given value against the token value stored in the session,
2897 * ignoring the suffix.
2898 *
2899 * @param $val String Input value to compare
2900 * @param $salt String Optional function-specific data for hashing
2901 * @return Boolean: Whether the token matches
2902 */
2903 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2904 $sessionToken = $this->editToken( $salt );
2905 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2906 }
2907
2908 /**
2909 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2910 * mail to the user's given address.
2911 *
2912 * @param $type String: message to send, either "created", "changed" or "set"
2913 * @return Status object
2914 */
2915 function sendConfirmationMail( $type = 'created' ) {
2916 global $wgLang;
2917 $expiration = null; // gets passed-by-ref and defined in next line.
2918 $token = $this->confirmationToken( $expiration );
2919 $url = $this->confirmationTokenUrl( $token );
2920 $invalidateURL = $this->invalidationTokenUrl( $token );
2921 $this->saveSettings();
2922
2923 if ( $type == 'created' || $type === false ) {
2924 $message = 'confirmemail_body';
2925 } elseif ( $type === true ) {
2926 $message = 'confirmemail_body_changed';
2927 } else {
2928 $message = 'confirmemail_body_' . $type;
2929 }
2930
2931 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2932 wfMsg( $message,
2933 wfGetIP(),
2934 $this->getName(),
2935 $url,
2936 $wgLang->timeanddate( $expiration, false ),
2937 $invalidateURL,
2938 $wgLang->date( $expiration, false ),
2939 $wgLang->time( $expiration, false ) ) );
2940 }
2941
2942 /**
2943 * Send an e-mail to this user's account. Does not check for
2944 * confirmed status or validity.
2945 *
2946 * @param $subject String Message subject
2947 * @param $body String Message body
2948 * @param $from String Optional From address; if unspecified, default $wgPasswordSender will be used
2949 * @param $replyto String Reply-To address
2950 * @return Status
2951 */
2952 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2953 if( is_null( $from ) ) {
2954 global $wgPasswordSender, $wgPasswordSenderName;
2955 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
2956 } else {
2957 $sender = new MailAddress( $from );
2958 }
2959
2960 $to = new MailAddress( $this );
2961 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
2962 }
2963
2964 /**
2965 * Generate, store, and return a new e-mail confirmation code.
2966 * A hash (unsalted, since it's used as a key) is stored.
2967 *
2968 * @note Call saveSettings() after calling this function to commit
2969 * this change to the database.
2970 *
2971 * @param[out] &$expiration \mixed Accepts the expiration time
2972 * @return String New token
2973 * @private
2974 */
2975 function confirmationToken( &$expiration ) {
2976 global $wgUserEmailConfirmationTokenExpiry;
2977 $now = time();
2978 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
2979 $expiration = wfTimestamp( TS_MW, $expires );
2980 $token = wfGenerateToken( $this->mId . $this->mEmail . $expires );
2981 $hash = md5( $token );
2982 $this->load();
2983 $this->mEmailToken = $hash;
2984 $this->mEmailTokenExpires = $expiration;
2985 return $token;
2986 }
2987
2988 /**
2989 * Return a URL the user can use to confirm their email address.
2990 * @param $token String Accepts the email confirmation token
2991 * @return String New token URL
2992 * @private
2993 */
2994 function confirmationTokenUrl( $token ) {
2995 return $this->getTokenUrl( 'ConfirmEmail', $token );
2996 }
2997
2998 /**
2999 * Return a URL the user can use to invalidate their email address.
3000 * @param $token String Accepts the email confirmation token
3001 * @return String New token URL
3002 * @private
3003 */
3004 function invalidationTokenUrl( $token ) {
3005 return $this->getTokenUrl( 'Invalidateemail', $token );
3006 }
3007
3008 /**
3009 * Internal function to format the e-mail validation/invalidation URLs.
3010 * This uses $wgArticlePath directly as a quickie hack to use the
3011 * hardcoded English names of the Special: pages, for ASCII safety.
3012 *
3013 * @note Since these URLs get dropped directly into emails, using the
3014 * short English names avoids insanely long URL-encoded links, which
3015 * also sometimes can get corrupted in some browsers/mailers
3016 * (bug 6957 with Gmail and Internet Explorer).
3017 *
3018 * @param $page String Special page
3019 * @param $token String Token
3020 * @return String Formatted URL
3021 */
3022 protected function getTokenUrl( $page, $token ) {
3023 global $wgArticlePath;
3024 return wfExpandUrl(
3025 str_replace(
3026 '$1',
3027 "Special:$page/$token",
3028 $wgArticlePath ) );
3029 }
3030
3031 /**
3032 * Mark the e-mail address confirmed.
3033 *
3034 * @note Call saveSettings() after calling this function to commit the change.
3035 */
3036 function confirmEmail() {
3037 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3038 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3039 return true;
3040 }
3041
3042 /**
3043 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3044 * address if it was already confirmed.
3045 *
3046 * @note Call saveSettings() after calling this function to commit the change.
3047 */
3048 function invalidateEmail() {
3049 $this->load();
3050 $this->mEmailToken = null;
3051 $this->mEmailTokenExpires = null;
3052 $this->setEmailAuthenticationTimestamp( null );
3053 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3054 return true;
3055 }
3056
3057 /**
3058 * Set the e-mail authentication timestamp.
3059 * @param $timestamp String TS_MW timestamp
3060 */
3061 function setEmailAuthenticationTimestamp( $timestamp ) {
3062 $this->load();
3063 $this->mEmailAuthenticated = $timestamp;
3064 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
3065 }
3066
3067 /**
3068 * Is this user allowed to send e-mails within limits of current
3069 * site configuration?
3070 * @return Bool
3071 */
3072 function canSendEmail() {
3073 global $wgEnableEmail, $wgEnableUserEmail;
3074 if( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
3075 return false;
3076 }
3077 $canSend = $this->isEmailConfirmed();
3078 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3079 return $canSend;
3080 }
3081
3082 /**
3083 * Is this user allowed to receive e-mails within limits of current
3084 * site configuration?
3085 * @return Bool
3086 */
3087 function canReceiveEmail() {
3088 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3089 }
3090
3091 /**
3092 * Is this user's e-mail address valid-looking and confirmed within
3093 * limits of the current site configuration?
3094 *
3095 * @note If $wgEmailAuthentication is on, this may require the user to have
3096 * confirmed their address by returning a code or using a password
3097 * sent to the address from the wiki.
3098 *
3099 * @return Bool
3100 */
3101 function isEmailConfirmed() {
3102 global $wgEmailAuthentication;
3103 $this->load();
3104 $confirmed = true;
3105 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3106 if( $this->isAnon() )
3107 return false;
3108 if( !self::isValidEmailAddr( $this->mEmail ) )
3109 return false;
3110 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
3111 return false;
3112 return true;
3113 } else {
3114 return $confirmed;
3115 }
3116 }
3117
3118 /**
3119 * Check whether there is an outstanding request for e-mail confirmation.
3120 * @return Bool
3121 */
3122 function isEmailConfirmationPending() {
3123 global $wgEmailAuthentication;
3124 return $wgEmailAuthentication &&
3125 !$this->isEmailConfirmed() &&
3126 $this->mEmailToken &&
3127 $this->mEmailTokenExpires > wfTimestamp();
3128 }
3129
3130 /**
3131 * Get the timestamp of account creation.
3132 *
3133 * @return String|Bool Timestamp of account creation, or false for
3134 * non-existent/anonymous user accounts.
3135 */
3136 public function getRegistration() {
3137 return $this->getId() > 0
3138 ? $this->mRegistration
3139 : false;
3140 }
3141
3142 /**
3143 * Get the timestamp of the first edit
3144 *
3145 * @return String|Bool Timestamp of first edit, or false for
3146 * non-existent/anonymous user accounts.
3147 */
3148 public function getFirstEditTimestamp() {
3149 if( $this->getId() == 0 ) {
3150 return false; // anons
3151 }
3152 $dbr = wfGetDB( DB_SLAVE );
3153 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3154 array( 'rev_user' => $this->getId() ),
3155 __METHOD__,
3156 array( 'ORDER BY' => 'rev_timestamp ASC' )
3157 );
3158 if( !$time ) {
3159 return false; // no edits
3160 }
3161 return wfTimestamp( TS_MW, $time );
3162 }
3163
3164 /**
3165 * Get the permissions associated with a given list of groups
3166 *
3167 * @param $groups Array of Strings List of internal group names
3168 * @return Array of Strings List of permission key names for given groups combined
3169 */
3170 static function getGroupPermissions( $groups ) {
3171 global $wgGroupPermissions, $wgRevokePermissions;
3172 $rights = array();
3173 // grant every granted permission first
3174 foreach( $groups as $group ) {
3175 if( isset( $wgGroupPermissions[$group] ) ) {
3176 $rights = array_merge( $rights,
3177 // array_filter removes empty items
3178 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3179 }
3180 }
3181 // now revoke the revoked permissions
3182 foreach( $groups as $group ) {
3183 if( isset( $wgRevokePermissions[$group] ) ) {
3184 $rights = array_diff( $rights,
3185 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3186 }
3187 }
3188 return array_unique( $rights );
3189 }
3190
3191 /**
3192 * Get all the groups who have a given permission
3193 *
3194 * @param $role String Role to check
3195 * @return Array of Strings List of internal group names with the given permission
3196 */
3197 static function getGroupsWithPermission( $role ) {
3198 global $wgGroupPermissions;
3199 $allowedGroups = array();
3200 foreach ( $wgGroupPermissions as $group => $rights ) {
3201 if ( isset( $rights[$role] ) && $rights[$role] ) {
3202 $allowedGroups[] = $group;
3203 }
3204 }
3205 return $allowedGroups;
3206 }
3207
3208 /**
3209 * Get the localized descriptive name for a group, if it exists
3210 *
3211 * @param $group String Internal group name
3212 * @return String Localized descriptive group name
3213 */
3214 static function getGroupName( $group ) {
3215 $msg = wfMessage( "group-$group" );
3216 return $msg->isBlank() ? $group : $msg->text();
3217 }
3218
3219 /**
3220 * Get the localized descriptive name for a member of a group, if it exists
3221 *
3222 * @param $group String Internal group name
3223 * @return String Localized name for group member
3224 */
3225 static function getGroupMember( $group ) {
3226 $msg = wfMessage( "group-$group-member" );
3227 return $msg->isBlank() ? $group : $msg->text();
3228 }
3229
3230 /**
3231 * Return the set of defined explicit groups.
3232 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3233 * are not included, as they are defined automatically, not in the database.
3234 * @return Array of internal group names
3235 */
3236 static function getAllGroups() {
3237 global $wgGroupPermissions, $wgRevokePermissions;
3238 return array_diff(
3239 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3240 self::getImplicitGroups()
3241 );
3242 }
3243
3244 /**
3245 * Get a list of all available permissions.
3246 * @return Array of permission names
3247 */
3248 static function getAllRights() {
3249 if ( self::$mAllRights === false ) {
3250 global $wgAvailableRights;
3251 if ( count( $wgAvailableRights ) ) {
3252 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
3253 } else {
3254 self::$mAllRights = self::$mCoreRights;
3255 }
3256 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
3257 }
3258 return self::$mAllRights;
3259 }
3260
3261 /**
3262 * Get a list of implicit groups
3263 * @return Array of Strings Array of internal group names
3264 */
3265 public static function getImplicitGroups() {
3266 global $wgImplicitGroups;
3267 $groups = $wgImplicitGroups;
3268 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3269 return $groups;
3270 }
3271
3272 /**
3273 * Get the title of a page describing a particular group
3274 *
3275 * @param $group String Internal group name
3276 * @return Title|Bool Title of the page if it exists, false otherwise
3277 */
3278 static function getGroupPage( $group ) {
3279 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
3280 if( $msg->exists() ) {
3281 $title = Title::newFromText( $msg->text() );
3282 if( is_object( $title ) )
3283 return $title;
3284 }
3285 return false;
3286 }
3287
3288 /**
3289 * Create a link to the group in HTML, if available;
3290 * else return the group name.
3291 *
3292 * @param $group String Internal name of the group
3293 * @param $text String The text of the link
3294 * @return String HTML link to the group
3295 */
3296 static function makeGroupLinkHTML( $group, $text = '' ) {
3297 if( $text == '' ) {
3298 $text = self::getGroupName( $group );
3299 }
3300 $title = self::getGroupPage( $group );
3301 if( $title ) {
3302 global $wgUser;
3303 $sk = $wgUser->getSkin();
3304 return $sk->link( $title, htmlspecialchars( $text ) );
3305 } else {
3306 return $text;
3307 }
3308 }
3309
3310 /**
3311 * Create a link to the group in Wikitext, if available;
3312 * else return the group name.
3313 *
3314 * @param $group String Internal name of the group
3315 * @param $text String The text of the link
3316 * @return String Wikilink to the group
3317 */
3318 static function makeGroupLinkWiki( $group, $text = '' ) {
3319 if( $text == '' ) {
3320 $text = self::getGroupName( $group );
3321 }
3322 $title = self::getGroupPage( $group );
3323 if( $title ) {
3324 $page = $title->getPrefixedText();
3325 return "[[$page|$text]]";
3326 } else {
3327 return $text;
3328 }
3329 }
3330
3331 /**
3332 * Returns an array of the groups that a particular group can add/remove.
3333 *
3334 * @param $group String: the group to check for whether it can add/remove
3335 * @return Array array( 'add' => array( addablegroups ),
3336 * 'remove' => array( removablegroups ),
3337 * 'add-self' => array( addablegroups to self),
3338 * 'remove-self' => array( removable groups from self) )
3339 */
3340 static function changeableByGroup( $group ) {
3341 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
3342
3343 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
3344 if( empty( $wgAddGroups[$group] ) ) {
3345 // Don't add anything to $groups
3346 } elseif( $wgAddGroups[$group] === true ) {
3347 // You get everything
3348 $groups['add'] = self::getAllGroups();
3349 } elseif( is_array( $wgAddGroups[$group] ) ) {
3350 $groups['add'] = $wgAddGroups[$group];
3351 }
3352
3353 // Same thing for remove
3354 if( empty( $wgRemoveGroups[$group] ) ) {
3355 } elseif( $wgRemoveGroups[$group] === true ) {
3356 $groups['remove'] = self::getAllGroups();
3357 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
3358 $groups['remove'] = $wgRemoveGroups[$group];
3359 }
3360
3361 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
3362 if( empty( $wgGroupsAddToSelf['user']) || $wgGroupsAddToSelf['user'] !== true ) {
3363 foreach( $wgGroupsAddToSelf as $key => $value ) {
3364 if( is_int( $key ) ) {
3365 $wgGroupsAddToSelf['user'][] = $value;
3366 }
3367 }
3368 }
3369
3370 if( empty( $wgGroupsRemoveFromSelf['user']) || $wgGroupsRemoveFromSelf['user'] !== true ) {
3371 foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
3372 if( is_int( $key ) ) {
3373 $wgGroupsRemoveFromSelf['user'][] = $value;
3374 }
3375 }
3376 }
3377
3378 // Now figure out what groups the user can add to him/herself
3379 if( empty( $wgGroupsAddToSelf[$group] ) ) {
3380 } elseif( $wgGroupsAddToSelf[$group] === true ) {
3381 // No idea WHY this would be used, but it's there
3382 $groups['add-self'] = User::getAllGroups();
3383 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
3384 $groups['add-self'] = $wgGroupsAddToSelf[$group];
3385 }
3386
3387 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
3388 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
3389 $groups['remove-self'] = User::getAllGroups();
3390 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
3391 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
3392 }
3393
3394 return $groups;
3395 }
3396
3397 /**
3398 * Returns an array of groups that this user can add and remove
3399 * @return Array array( 'add' => array( addablegroups ),
3400 * 'remove' => array( removablegroups ),
3401 * 'add-self' => array( addablegroups to self),
3402 * 'remove-self' => array( removable groups from self) )
3403 */
3404 function changeableGroups() {
3405 if( $this->isAllowed( 'userrights' ) ) {
3406 // This group gives the right to modify everything (reverse-
3407 // compatibility with old "userrights lets you change
3408 // everything")
3409 // Using array_merge to make the groups reindexed
3410 $all = array_merge( User::getAllGroups() );
3411 return array(
3412 'add' => $all,
3413 'remove' => $all,
3414 'add-self' => array(),
3415 'remove-self' => array()
3416 );
3417 }
3418
3419 // Okay, it's not so simple, we will have to go through the arrays
3420 $groups = array(
3421 'add' => array(),
3422 'remove' => array(),
3423 'add-self' => array(),
3424 'remove-self' => array()
3425 );
3426 $addergroups = $this->getEffectiveGroups();
3427
3428 foreach( $addergroups as $addergroup ) {
3429 $groups = array_merge_recursive(
3430 $groups, $this->changeableByGroup( $addergroup )
3431 );
3432 $groups['add'] = array_unique( $groups['add'] );
3433 $groups['remove'] = array_unique( $groups['remove'] );
3434 $groups['add-self'] = array_unique( $groups['add-self'] );
3435 $groups['remove-self'] = array_unique( $groups['remove-self'] );
3436 }
3437 return $groups;
3438 }
3439
3440 /**
3441 * Increment the user's edit-count field.
3442 * Will have no effect for anonymous users.
3443 */
3444 function incEditCount() {
3445 if( !$this->isAnon() ) {
3446 $dbw = wfGetDB( DB_MASTER );
3447 $dbw->update( 'user',
3448 array( 'user_editcount=user_editcount+1' ),
3449 array( 'user_id' => $this->getId() ),
3450 __METHOD__ );
3451
3452 // Lazy initialization check...
3453 if( $dbw->affectedRows() == 0 ) {
3454 // Pull from a slave to be less cruel to servers
3455 // Accuracy isn't the point anyway here
3456 $dbr = wfGetDB( DB_SLAVE );
3457 $count = $dbr->selectField( 'revision',
3458 'COUNT(rev_user)',
3459 array( 'rev_user' => $this->getId() ),
3460 __METHOD__ );
3461
3462 // Now here's a goddamn hack...
3463 if( $dbr !== $dbw ) {
3464 // If we actually have a slave server, the count is
3465 // at least one behind because the current transaction
3466 // has not been committed and replicated.
3467 $count++;
3468 } else {
3469 // But if DB_SLAVE is selecting the master, then the
3470 // count we just read includes the revision that was
3471 // just added in the working transaction.
3472 }
3473
3474 $dbw->update( 'user',
3475 array( 'user_editcount' => $count ),
3476 array( 'user_id' => $this->getId() ),
3477 __METHOD__ );
3478 }
3479 }
3480 // edit count in user cache too
3481 $this->invalidateCache();
3482 }
3483
3484 /**
3485 * Get the description of a given right
3486 *
3487 * @param $right String Right to query
3488 * @return String Localized description of the right
3489 */
3490 static function getRightDescription( $right ) {
3491 $key = "right-$right";
3492 $name = wfMsg( $key );
3493 return $name == '' || wfEmptyMsg( $key, $name )
3494 ? $right
3495 : $name;
3496 }
3497
3498 /**
3499 * Make an old-style password hash
3500 *
3501 * @param $password String Plain-text password
3502 * @param $userId String User ID
3503 * @return String Password hash
3504 */
3505 static function oldCrypt( $password, $userId ) {
3506 global $wgPasswordSalt;
3507 if ( $wgPasswordSalt ) {
3508 return md5( $userId . '-' . md5( $password ) );
3509 } else {
3510 return md5( $password );
3511 }
3512 }
3513
3514 /**
3515 * Make a new-style password hash
3516 *
3517 * @param $password String Plain-text password
3518 * @param $salt String Optional salt, may be random or the user ID.
3519 * If unspecified or false, will generate one automatically
3520 * @return String Password hash
3521 */
3522 static function crypt( $password, $salt = false ) {
3523 global $wgPasswordSalt;
3524
3525 $hash = '';
3526 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3527 return $hash;
3528 }
3529
3530 if( $wgPasswordSalt ) {
3531 if ( $salt === false ) {
3532 $salt = substr( wfGenerateToken(), 0, 8 );
3533 }
3534 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3535 } else {
3536 return ':A:' . md5( $password );
3537 }
3538 }
3539
3540 /**
3541 * Compare a password hash with a plain-text password. Requires the user
3542 * ID if there's a chance that the hash is an old-style hash.
3543 *
3544 * @param $hash String Password hash
3545 * @param $password String Plain-text password to compare
3546 * @param $userId String User ID for old-style password salt
3547 * @return Boolean:
3548 */
3549 static function comparePasswords( $hash, $password, $userId = false ) {
3550 $type = substr( $hash, 0, 3 );
3551
3552 $result = false;
3553 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3554 return $result;
3555 }
3556
3557 if ( $type == ':A:' ) {
3558 # Unsalted
3559 return md5( $password ) === substr( $hash, 3 );
3560 } elseif ( $type == ':B:' ) {
3561 # Salted
3562 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3563 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3564 } else {
3565 # Old-style
3566 return self::oldCrypt( $password, $userId ) === $hash;
3567 }
3568 }
3569
3570 /**
3571 * Add a newuser log entry for this user
3572 *
3573 * @param $byEmail Boolean: account made by email?
3574 * @param $reason String: user supplied reason
3575 */
3576 public function addNewUserLogEntry( $creator, $byEmail = false ) {
3577 global $wgUser, $wgNewUserLog;
3578 if( empty( $wgNewUserLog ) ) {
3579 return true; // disabled
3580 }
3581
3582 $action = ( $creator == $wgUser )
3583 ? 'create2' # Safe to publish the creator
3584 : 'create'; # Creator is an IP, don't splash it all over Special:Log
3585
3586 $message = $byEmail
3587 ? wfMsgForContent( 'newuserlog-byemail' )
3588 : '';
3589
3590 $log = new LogPage( 'newusers' );
3591 $log->addEntry(
3592 $action,
3593 $this->getUserPage(),
3594 $message,
3595 array( $this->getId() ),
3596 $creator
3597 );
3598 return true;
3599 }
3600
3601 /**
3602 * Add an autocreate newuser log entry for this user
3603 * Used by things like CentralAuth and perhaps other authplugins.
3604 */
3605 public function addNewUserLogEntryAutoCreate() {
3606 global $wgNewUserLog;
3607 if( empty( $wgNewUserLog ) ) {
3608 return true; // disabled
3609 }
3610 $log = new LogPage( 'newusers', false );
3611 $log->addEntry(
3612 'autocreate',
3613 $this->getUserPage(),
3614 '',
3615 array( $this->getId() ),
3616 $this->getId()
3617 );
3618 return true;
3619 }
3620
3621 protected function loadOptions() {
3622 $this->load();
3623 if ( $this->mOptionsLoaded || !$this->getId() )
3624 return;
3625
3626 $this->mOptions = self::getDefaultOptions();
3627
3628 // Maybe load from the object
3629 if ( !is_null( $this->mOptionOverrides ) ) {
3630 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
3631 foreach( $this->mOptionOverrides as $key => $value ) {
3632 $this->mOptions[$key] = $value;
3633 }
3634 } else {
3635 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
3636 // Load from database
3637 $dbr = wfGetDB( DB_SLAVE );
3638
3639 $res = $dbr->select(
3640 'user_properties',
3641 '*',
3642 array( 'up_user' => $this->getId() ),
3643 __METHOD__
3644 );
3645
3646 foreach ( $res as $row ) {
3647 $this->mOptionOverrides[$row->up_property] = $row->up_value;
3648 $this->mOptions[$row->up_property] = $row->up_value;
3649 }
3650 }
3651
3652 $this->mOptionsLoaded = true;
3653
3654 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
3655 }
3656
3657 protected function saveOptions() {
3658 global $wgAllowPrefChange;
3659
3660 $extuser = ExternalUser::newFromUser( $this );
3661
3662 $this->loadOptions();
3663 $dbw = wfGetDB( DB_MASTER );
3664
3665 $insert_rows = array();
3666
3667 $saveOptions = $this->mOptions;
3668
3669 // Allow hooks to abort, for instance to save to a global profile.
3670 // Reset options to default state before saving.
3671 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) )
3672 return;
3673
3674 foreach( $saveOptions as $key => $value ) {
3675 # Don't bother storing default values
3676 if ( ( is_null( self::getDefaultOption( $key ) ) &&
3677 !( $value === false || is_null($value) ) ) ||
3678 $value != self::getDefaultOption( $key ) ) {
3679 $insert_rows[] = array(
3680 'up_user' => $this->getId(),
3681 'up_property' => $key,
3682 'up_value' => $value,
3683 );
3684 }
3685 if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
3686 switch ( $wgAllowPrefChange[$key] ) {
3687 case 'local':
3688 case 'message':
3689 break;
3690 case 'semiglobal':
3691 case 'global':
3692 $extuser->setPref( $key, $value );
3693 }
3694 }
3695 }
3696
3697 $dbw->begin();
3698 $dbw->delete( 'user_properties', array( 'up_user' => $this->getId() ), __METHOD__ );
3699 $dbw->insert( 'user_properties', $insert_rows, __METHOD__ );
3700 $dbw->commit();
3701 }
3702
3703 /**
3704 * Provide an array of HTML5 attributes to put on an input element
3705 * intended for the user to enter a new password. This may include
3706 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
3707 *
3708 * Do *not* use this when asking the user to enter his current password!
3709 * Regardless of configuration, users may have invalid passwords for whatever
3710 * reason (e.g., they were set before requirements were tightened up).
3711 * Only use it when asking for a new password, like on account creation or
3712 * ResetPass.
3713 *
3714 * Obviously, you still need to do server-side checking.
3715 *
3716 * NOTE: A combination of bugs in various browsers means that this function
3717 * actually just returns array() unconditionally at the moment. May as
3718 * well keep it around for when the browser bugs get fixed, though.
3719 *
3720 * FIXME : This does not belong here; put it in Html or Linker or somewhere
3721 *
3722 * @return array Array of HTML attributes suitable for feeding to
3723 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
3724 * That will potentially output invalid XHTML 1.0 Transitional, and will
3725 * get confused by the boolean attribute syntax used.)
3726 */
3727 public static function passwordChangeInputAttribs() {
3728 global $wgMinimalPasswordLength;
3729
3730 if ( $wgMinimalPasswordLength == 0 ) {
3731 return array();
3732 }
3733
3734 # Note that the pattern requirement will always be satisfied if the
3735 # input is empty, so we need required in all cases.
3736 #
3737 # FIXME (bug 23769): This needs to not claim the password is required
3738 # if e-mail confirmation is being used. Since HTML5 input validation
3739 # is b0rked anyway in some browsers, just return nothing. When it's
3740 # re-enabled, fix this code to not output required for e-mail
3741 # registration.
3742 #$ret = array( 'required' );
3743 $ret = array();
3744
3745 # We can't actually do this right now, because Opera 9.6 will print out
3746 # the entered password visibly in its error message! When other
3747 # browsers add support for this attribute, or Opera fixes its support,
3748 # we can add support with a version check to avoid doing this on Opera
3749 # versions where it will be a problem. Reported to Opera as
3750 # DSK-262266, but they don't have a public bug tracker for us to follow.
3751 /*
3752 if ( $wgMinimalPasswordLength > 1 ) {
3753 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
3754 $ret['title'] = wfMsgExt( 'passwordtooshort', 'parsemag',
3755 $wgMinimalPasswordLength );
3756 }
3757 */
3758
3759 return $ret;
3760 }
3761
3762
3763
3764
3765 }