Add feature to block common (weak) passwords.
[mediawiki.git] / includes / User.php
blob9eec233e2c6d30b8a7f724c608cd0dc001922310
1 <?php
2 /**
3 * Implements the User class for the %MediaWiki software.
4 * @file
5 */
7 /**
8 * \int Number of characters in user_token field.
9 * @ingroup Constants
11 define( 'USER_TOKEN_LENGTH', 32 );
13 /**
14 * \int Serialized record version.
15 * @ingroup Constants
17 define( 'MW_USER_VERSION', 8 );
19 /**
20 * \string Some punctuation to prevent editing from broken text-mangling proxies.
21 * @ingroup Constants
23 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
25 /**
26 * Thrown by User::setPassword() on error.
27 * @ingroup Exception
29 class PasswordError extends MWException {
30 // NOP
33 /**
34 * The User object encapsulates all of the user-specific settings (user_id,
35 * name, rights, password, email address, options, last login time). Client
36 * classes use the getXXX() functions to access these fields. These functions
37 * do all the work of determining whether the user is logged in,
38 * whether the requested option can be satisfied from cookies or
39 * whether a database query is needed. Most of the settings needed
40 * for rendering normal pages are set in the cookie to minimize use
41 * of the database.
43 class User {
44 /**
45 * Global constants made accessible as class constants so that autoloader
46 * magic can be used.
48 const USER_TOKEN_LENGTH = USER_TOKEN_LENGTH;
49 const MW_USER_VERSION = MW_USER_VERSION;
50 const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
52 /**
53 * \type{\arrayof{\string}} List of member variables which are saved to the
54 * shared cache (memcached). Any operation which changes the
55 * corresponding database fields must call a cache-clearing function.
56 * @showinitializer
58 static $mCacheVars = array(
59 // user table
60 'mId',
61 'mName',
62 'mRealName',
63 'mPassword',
64 'mNewpassword',
65 'mNewpassTime',
66 'mEmail',
67 'mTouched',
68 'mToken',
69 'mEmailAuthenticated',
70 'mEmailToken',
71 'mEmailTokenExpires',
72 'mRegistration',
73 'mEditCount',
74 // user_group table
75 'mGroups',
76 // user_properties table
77 'mOptionOverrides',
80 /**
81 * \type{\arrayof{\string}} Core rights.
82 * Each of these should have a corresponding message of the form
83 * "right-$right".
84 * @showinitializer
86 static $mCoreRights = array(
87 'apihighlimits',
88 'autoconfirmed',
89 'autopatrol',
90 'bigdelete',
91 'block',
92 'blockemail',
93 'bot',
94 'browsearchive',
95 'createaccount',
96 'createpage',
97 'createtalk',
98 'delete',
99 'deletedhistory',
100 'deletedtext',
101 'deleterevision',
102 'edit',
103 'editinterface',
104 'editusercssjs',
105 'hideuser',
106 'import',
107 'importupload',
108 'ipblock-exempt',
109 'markbotedits',
110 'minoredit',
111 'move',
112 'movefile',
113 'move-rootuserpages',
114 'move-subpages',
115 'nominornewtalk',
116 'noratelimit',
117 'override-export-depth',
118 'patrol',
119 'protect',
120 'proxyunbannable',
121 'purge',
122 'read',
123 'reupload',
124 'reupload-shared',
125 'rollback',
126 'selenium',
127 'sendemail',
128 'siteadmin',
129 'suppressionlog',
130 'suppressredirect',
131 'suppressrevision',
132 'trackback',
133 'undelete',
134 'unwatchedpages',
135 'upload',
136 'upload_by_url',
137 'userrights',
138 'userrights-interwiki',
139 'writeapi',
142 * \string Cached results of getAllRights()
144 static $mAllRights = false;
146 /** @name Cache variables */
147 //@{
148 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
149 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
150 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups, $mOptionOverrides;
151 //@}
154 * \bool Whether the cache variables have been loaded.
156 var $mDataLoaded, $mAuthLoaded, $mOptionsLoaded;
159 * \string Initialization data source if mDataLoaded==false. May be one of:
160 * - 'defaults' anonymous user initialised from class defaults
161 * - 'name' initialise from mName
162 * - 'id' initialise from mId
163 * - 'session' log in from cookies or session if possible
165 * Use the User::newFrom*() family of functions to set this.
167 var $mFrom;
169 /** @name Lazy-initialized variables, invalidated with clearInstanceCache */
170 //@{
171 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
172 $mBlockreason, $mBlock, $mEffectiveGroups, $mBlockedGlobally,
173 $mLocked, $mHideName, $mOptions;
174 //@}
176 static $idCacheByName = array();
179 * Lightweight constructor for an anonymous user.
180 * Use the User::newFrom* factory functions for other kinds of users.
182 * @see newFromName()
183 * @see newFromId()
184 * @see newFromConfirmationCode()
185 * @see newFromSession()
186 * @see newFromRow()
188 function __construct() {
189 $this->clearInstanceCache( 'defaults' );
193 * Load the user table data for this object from the source given by mFrom.
195 function load() {
196 if ( $this->mDataLoaded ) {
197 return;
199 wfProfileIn( __METHOD__ );
201 # Set it now to avoid infinite recursion in accessors
202 $this->mDataLoaded = true;
204 switch ( $this->mFrom ) {
205 case 'defaults':
206 $this->loadDefaults();
207 break;
208 case 'name':
209 $this->mId = self::idFromName( $this->mName );
210 if ( !$this->mId ) {
211 # Nonexistent user placeholder object
212 $this->loadDefaults( $this->mName );
213 } else {
214 $this->loadFromId();
216 break;
217 case 'id':
218 $this->loadFromId();
219 break;
220 case 'session':
221 $this->loadFromSession();
222 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
223 break;
224 default:
225 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
227 wfProfileOut( __METHOD__ );
231 * Load user table data, given mId has already been set.
232 * @return \bool false if the ID does not exist, true otherwise
233 * @private
235 function loadFromId() {
236 global $wgMemc;
237 if ( $this->mId == 0 ) {
238 $this->loadDefaults();
239 return false;
242 # Try cache
243 $key = wfMemcKey( 'user', 'id', $this->mId );
244 $data = $wgMemc->get( $key );
245 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
246 # Object is expired, load from DB
247 $data = false;
250 if ( !$data ) {
251 wfDebug( "User: cache miss for user {$this->mId}\n" );
252 # Load from DB
253 if ( !$this->loadFromDatabase() ) {
254 # Can't load from ID, user is anonymous
255 return false;
257 $this->saveToCache();
258 } else {
259 wfDebug( "User: got user {$this->mId} from cache\n" );
260 # Restore from cache
261 foreach ( self::$mCacheVars as $name ) {
262 $this->$name = $data[$name];
265 return true;
269 * Save user data to the shared cache
271 function saveToCache() {
272 $this->load();
273 $this->loadGroups();
274 $this->loadOptions();
275 if ( $this->isAnon() ) {
276 // Anonymous users are uncached
277 return;
279 $data = array();
280 foreach ( self::$mCacheVars as $name ) {
281 $data[$name] = $this->$name;
283 $data['mVersion'] = MW_USER_VERSION;
284 $key = wfMemcKey( 'user', 'id', $this->mId );
285 global $wgMemc;
286 $wgMemc->set( $key, $data );
290 /** @name newFrom*() static factory methods */
291 //@{
294 * Static factory method for creation from username.
296 * This is slightly less efficient than newFromId(), so use newFromId() if
297 * you have both an ID and a name handy.
299 * @param $name \string Username, validated by Title::newFromText()
300 * @param $validate \mixed Validate username. Takes the same parameters as
301 * User::getCanonicalName(), except that true is accepted as an alias
302 * for 'valid', for BC.
304 * @return \type{User} The User object, or false if the username is invalid
305 * (e.g. if it contains illegal characters or is an IP address). If the
306 * username is not present in the database, the result will be a user object
307 * with a name, zero user ID and default settings.
309 static function newFromName( $name, $validate = 'valid' ) {
310 if ( $validate === true ) {
311 $validate = 'valid';
313 $name = self::getCanonicalName( $name, $validate );
314 if ( $name === false ) {
315 return false;
316 } else {
317 # Create unloaded user object
318 $u = new User;
319 $u->mName = $name;
320 $u->mFrom = 'name';
321 return $u;
326 * Static factory method for creation from a given user ID.
328 * @param $id \int Valid user ID
329 * @return \type{User} The corresponding User object
331 static function newFromId( $id ) {
332 $u = new User;
333 $u->mId = $id;
334 $u->mFrom = 'id';
335 return $u;
339 * Factory method to fetch whichever user has a given email confirmation code.
340 * This code is generated when an account is created or its e-mail address
341 * has changed.
343 * If the code is invalid or has expired, returns NULL.
345 * @param $code \string Confirmation code
346 * @return \type{User}
348 static function newFromConfirmationCode( $code ) {
349 $dbr = wfGetDB( DB_SLAVE );
350 $id = $dbr->selectField( 'user', 'user_id', array(
351 'user_email_token' => md5( $code ),
352 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
353 ) );
354 if( $id !== false ) {
355 return User::newFromId( $id );
356 } else {
357 return null;
362 * Create a new user object using data from session or cookies. If the
363 * login credentials are invalid, the result is an anonymous user.
365 * @return \type{User}
367 static function newFromSession() {
368 $user = new User;
369 $user->mFrom = 'session';
370 return $user;
374 * Create a new user object from a user row.
375 * The row should have all fields from the user table in it.
376 * @param $row array A row from the user table
377 * @return \type{User}
379 static function newFromRow( $row ) {
380 $user = new User;
381 $user->loadFromRow( $row );
382 return $user;
385 //@}
389 * Get the username corresponding to a given user ID
390 * @param $id \int User ID
391 * @return \string The corresponding username
393 static function whoIs( $id ) {
394 $dbr = wfGetDB( DB_SLAVE );
395 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), __METHOD__ );
399 * Get the real name of a user given their user ID
401 * @param $id \int User ID
402 * @return \string The corresponding user's real name
404 static function whoIsReal( $id ) {
405 $dbr = wfGetDB( DB_SLAVE );
406 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__ );
410 * Get database id given a user name
411 * @param $name \string Username
412 * @return \types{\int,\null} The corresponding user's ID, or null if user is nonexistent
414 static function idFromName( $name ) {
415 $nt = Title::makeTitleSafe( NS_USER, $name );
416 if( is_null( $nt ) ) {
417 # Illegal name
418 return null;
421 if ( isset( self::$idCacheByName[$name] ) ) {
422 return self::$idCacheByName[$name];
425 $dbr = wfGetDB( DB_SLAVE );
426 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
428 if ( $s === false ) {
429 $result = null;
430 } else {
431 $result = $s->user_id;
434 self::$idCacheByName[$name] = $result;
436 if ( count( self::$idCacheByName ) > 1000 ) {
437 self::$idCacheByName = array();
440 return $result;
444 * Does the string match an anonymous IPv4 address?
446 * This function exists for username validation, in order to reject
447 * usernames which are similar in form to IP addresses. Strings such
448 * as 300.300.300.300 will return true because it looks like an IP
449 * address, despite not being strictly valid.
451 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
452 * address because the usemod software would "cloak" anonymous IP
453 * addresses like this, if we allowed accounts like this to be created
454 * new users could get the old edits of these anonymous users.
456 * @param $name \string String to match
457 * @return \bool True or false
459 static function isIP( $name ) {
460 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP::isIPv6($name);
464 * Is the input a valid username?
466 * Checks if the input is a valid username, we don't want an empty string,
467 * an IP address, anything that containins slashes (would mess up subpages),
468 * is longer than the maximum allowed username size or doesn't begin with
469 * a capital letter.
471 * @param $name \string String to match
472 * @return \bool True or false
474 static function isValidUserName( $name ) {
475 global $wgContLang, $wgMaxNameChars;
477 if ( $name == ''
478 || User::isIP( $name )
479 || strpos( $name, '/' ) !== false
480 || strlen( $name ) > $wgMaxNameChars
481 || $name != $wgContLang->ucfirst( $name ) ) {
482 wfDebugLog( 'username', __METHOD__ .
483 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
484 return false;
487 // Ensure that the name can't be misresolved as a different title,
488 // such as with extra namespace keys at the start.
489 $parsed = Title::newFromText( $name );
490 if( is_null( $parsed )
491 || $parsed->getNamespace()
492 || strcmp( $name, $parsed->getPrefixedText() ) ) {
493 wfDebugLog( 'username', __METHOD__ .
494 ": '$name' invalid due to ambiguous prefixes" );
495 return false;
498 // Check an additional blacklist of troublemaker characters.
499 // Should these be merged into the title char list?
500 $unicodeBlacklist = '/[' .
501 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
502 '\x{00a0}' . # non-breaking space
503 '\x{2000}-\x{200f}' . # various whitespace
504 '\x{2028}-\x{202f}' . # breaks and control chars
505 '\x{3000}' . # ideographic space
506 '\x{e000}-\x{f8ff}' . # private use
507 ']/u';
508 if( preg_match( $unicodeBlacklist, $name ) ) {
509 wfDebugLog( 'username', __METHOD__ .
510 ": '$name' invalid due to blacklisted characters" );
511 return false;
514 return true;
518 * Usernames which fail to pass this function will be blocked
519 * from user login and new account registrations, but may be used
520 * internally by batch processes.
522 * If an account already exists in this form, login will be blocked
523 * by a failure to pass this function.
525 * @param $name \string String to match
526 * @return \bool True or false
528 static function isUsableName( $name ) {
529 global $wgReservedUsernames;
530 // Must be a valid username, obviously ;)
531 if ( !self::isValidUserName( $name ) ) {
532 return false;
535 static $reservedUsernames = false;
536 if ( !$reservedUsernames ) {
537 $reservedUsernames = $wgReservedUsernames;
538 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
541 // Certain names may be reserved for batch processes.
542 foreach ( $reservedUsernames as $reserved ) {
543 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
544 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
546 if ( $reserved == $name ) {
547 return false;
550 return true;
554 * Usernames which fail to pass this function will be blocked
555 * from new account registrations, but may be used internally
556 * either by batch processes or by user accounts which have
557 * already been created.
559 * Additional blacklisting may be added here rather than in
560 * isValidUserName() to avoid disrupting existing accounts.
562 * @param $name \string String to match
563 * @return \bool True or false
565 static function isCreatableName( $name ) {
566 global $wgInvalidUsernameCharacters;
568 // Ensure that the username isn't longer than 235 bytes, so that
569 // (at least for the builtin skins) user javascript and css files
570 // will work. (bug 23080)
571 if( strlen( $name ) > 235 ) {
572 wfDebugLog( 'username', __METHOD__ .
573 ": '$name' invalid due to length" );
574 return false;
577 if( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
578 wfDebugLog( 'username', __METHOD__ .
579 ": '$name' invalid due to wgInvalidUsernameCharacters" );
580 return false;
583 return self::isUsableName( $name );
587 * Is the input a valid password for this user?
589 * @param $password String Desired password
590 * @return bool True or false
592 function isValidPassword( $password ) {
593 //simple boolean wrapper for getPasswordValidity
594 return $this->getPasswordValidity( $password ) === true;
598 * Given unvalidated password input, return error message on failure.
600 * @param $password String Desired password
601 * @return mixed: true on success, string of error message on failure
603 function getPasswordValidity( $password ) {
604 global $wgMinimalPasswordLength, $wgWeakPasswords, $wgContLang;
606 $result = false; //init $result to false for the internal checks
608 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
609 return $result;
611 $lcPassword = $wgContLang->lc( $password );
613 if ( $result === false ) {
614 if( strlen( $password ) < $wgMinimalPasswordLength ) {
615 return 'passwordtooshort';
616 } elseif ( $lcPassword == $wgContLang->lc( $this->mName ) ) {
617 return 'password-name-match';
618 } elseif ( in_array( $lcPassword, $wgWeakPasswords ) ) {
619 return 'password-too-weak';
620 } else {
621 //it seems weird returning true here, but this is because of the
622 //initialization of $result to false above. If the hook is never run or it
623 //doesn't modify $result, then we will likely get down into this if with
624 //a valid password.
625 return true;
627 } elseif( $result === true ) {
628 return true;
629 } else {
630 return $result; //the isValidPassword hook set a string $result and returned true
635 * Does a string look like an e-mail address?
637 * There used to be a regular expression here, it got removed because it
638 * rejected valid addresses. Actually just check if there is '@' somewhere
639 * in the given address.
641 * @todo Check for RFC 2822 compilance (bug 959)
643 * @param $addr \string E-mail address
644 * @return \bool True or false
646 public static function isValidEmailAddr( $addr ) {
647 $result = null;
648 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
649 return $result;
652 return strpos( $addr, '@' ) !== false;
656 * Given unvalidated user input, return a canonical username, or false if
657 * the username is invalid.
658 * @param $name \string User input
659 * @param $validate \types{\string,\bool} Type of validation to use:
660 * - false No validation
661 * - 'valid' Valid for batch processes
662 * - 'usable' Valid for batch processes and login
663 * - 'creatable' Valid for batch processes, login and account creation
665 static function getCanonicalName( $name, $validate = 'valid' ) {
666 # Force usernames to capital
667 global $wgContLang;
668 $name = $wgContLang->ucfirst( $name );
670 # Reject names containing '#'; these will be cleaned up
671 # with title normalisation, but then it's too late to
672 # check elsewhere
673 if( strpos( $name, '#' ) !== false )
674 return false;
676 # Clean up name according to title rules
677 $t = ( $validate === 'valid' ) ?
678 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
679 # Check for invalid titles
680 if( is_null( $t ) ) {
681 return false;
684 # Reject various classes of invalid names
685 $name = $t->getText();
686 global $wgAuth;
687 $name = $wgAuth->getCanonicalName( $t->getText() );
689 switch ( $validate ) {
690 case false:
691 break;
692 case 'valid':
693 if ( !User::isValidUserName( $name ) ) {
694 $name = false;
696 break;
697 case 'usable':
698 if ( !User::isUsableName( $name ) ) {
699 $name = false;
701 break;
702 case 'creatable':
703 if ( !User::isCreatableName( $name ) ) {
704 $name = false;
706 break;
707 default:
708 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
710 return $name;
714 * Count the number of edits of a user
715 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
717 * @param $uid \int User ID to check
718 * @return \int The user's edit count
720 static function edits( $uid ) {
721 wfProfileIn( __METHOD__ );
722 $dbr = wfGetDB( DB_SLAVE );
723 // check if the user_editcount field has been initialized
724 $field = $dbr->selectField(
725 'user', 'user_editcount',
726 array( 'user_id' => $uid ),
727 __METHOD__
730 if( $field === null ) { // it has not been initialized. do so.
731 $dbw = wfGetDB( DB_MASTER );
732 $count = $dbr->selectField(
733 'revision', 'count(*)',
734 array( 'rev_user' => $uid ),
735 __METHOD__
737 $dbw->update(
738 'user',
739 array( 'user_editcount' => $count ),
740 array( 'user_id' => $uid ),
741 __METHOD__
743 } else {
744 $count = $field;
746 wfProfileOut( __METHOD__ );
747 return $count;
751 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
752 * @todo hash random numbers to improve security, like generateToken()
754 * @return \string New random password
756 static function randomPassword() {
757 global $wgMinimalPasswordLength;
758 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
759 $l = strlen( $pwchars ) - 1;
761 $pwlength = max( 7, $wgMinimalPasswordLength );
762 $digit = mt_rand( 0, $pwlength - 1 );
763 $np = '';
764 for ( $i = 0; $i < $pwlength; $i++ ) {
765 $np .= $i == $digit ? chr( mt_rand( 48, 57 ) ) : $pwchars{ mt_rand( 0, $l ) };
767 return $np;
771 * Set cached properties to default.
773 * @note This no longer clears uncached lazy-initialised properties;
774 * the constructor does that instead.
775 * @private
777 function loadDefaults( $name = false ) {
778 wfProfileIn( __METHOD__ );
780 global $wgRequest;
782 $this->mId = 0;
783 $this->mName = $name;
784 $this->mRealName = '';
785 $this->mPassword = $this->mNewpassword = '';
786 $this->mNewpassTime = null;
787 $this->mEmail = '';
788 $this->mOptionOverrides = null;
789 $this->mOptionsLoaded = false;
791 if( $wgRequest->getCookie( 'LoggedOut' ) !== null ) {
792 $this->mTouched = wfTimestamp( TS_MW, $wgRequest->getCookie( 'LoggedOut' ) );
793 } else {
794 $this->mTouched = '0'; # Allow any pages to be cached
797 $this->setToken(); # Random
798 $this->mEmailAuthenticated = null;
799 $this->mEmailToken = '';
800 $this->mEmailTokenExpires = null;
801 $this->mRegistration = wfTimestamp( TS_MW );
802 $this->mGroups = array();
804 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
806 wfProfileOut( __METHOD__ );
810 * @deprecated Use wfSetupSession().
812 function SetupSession() {
813 wfDeprecated( __METHOD__ );
814 wfSetupSession();
818 * Load user data from the session or login cookie. If there are no valid
819 * credentials, initialises the user as an anonymous user.
820 * @return \bool True if the user is logged in, false otherwise.
822 private function loadFromSession() {
823 global $wgRequest, $wgExternalAuthType, $wgAutocreatePolicy;
825 $result = null;
826 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
827 if ( $result !== null ) {
828 return $result;
831 if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
832 $extUser = ExternalUser::newFromCookie();
833 if ( $extUser ) {
834 # TODO: Automatically create the user here (or probably a bit
835 # lower down, in fact)
839 if ( $wgRequest->getCookie( 'UserID' ) !== null ) {
840 $sId = intval( $wgRequest->getCookie( 'UserID' ) );
841 if( isset( $_SESSION['wsUserID'] ) && $sId != $_SESSION['wsUserID'] ) {
842 $this->loadDefaults(); // Possible collision!
843 wfDebugLog( 'loginSessions', "Session user ID ({$_SESSION['wsUserID']}) and
844 cookie user ID ($sId) don't match!" );
845 return false;
847 $_SESSION['wsUserID'] = $sId;
848 } else if ( isset( $_SESSION['wsUserID'] ) ) {
849 if ( $_SESSION['wsUserID'] != 0 ) {
850 $sId = $_SESSION['wsUserID'];
851 } else {
852 $this->loadDefaults();
853 return false;
855 } else {
856 $this->loadDefaults();
857 return false;
860 if ( isset( $_SESSION['wsUserName'] ) ) {
861 $sName = $_SESSION['wsUserName'];
862 } else if ( $wgRequest->getCookie('UserName') !== null ) {
863 $sName = $wgRequest->getCookie('UserName');
864 $_SESSION['wsUserName'] = $sName;
865 } else {
866 $this->loadDefaults();
867 return false;
870 $this->mId = $sId;
871 if ( !$this->loadFromId() ) {
872 # Not a valid ID, loadFromId has switched the object to anon for us
873 return false;
876 global $wgBlockDisablesLogin;
877 if( $wgBlockDisablesLogin && $this->isBlocked() ) {
878 # User blocked and we've disabled blocked user logins
879 $this->loadDefaults();
880 return false;
883 if ( isset( $_SESSION['wsToken'] ) ) {
884 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken;
885 $from = 'session';
886 } else if ( $wgRequest->getCookie( 'Token' ) !== null ) {
887 $passwordCorrect = $this->mToken == $wgRequest->getCookie( 'Token' );
888 $from = 'cookie';
889 } else {
890 # No session or persistent login cookie
891 $this->loadDefaults();
892 return false;
895 if ( ( $sName == $this->mName ) && $passwordCorrect ) {
896 $_SESSION['wsToken'] = $this->mToken;
897 wfDebug( "User: logged in from $from\n" );
898 return true;
899 } else {
900 # Invalid credentials
901 wfDebug( "User: can't log in from $from, invalid credentials\n" );
902 $this->loadDefaults();
903 return false;
908 * Load user and user_group data from the database.
909 * $this::mId must be set, this is how the user is identified.
911 * @return \bool True if the user exists, false if the user is anonymous
912 * @private
914 function loadFromDatabase() {
915 # Paranoia
916 $this->mId = intval( $this->mId );
918 /** Anonymous user */
919 if( !$this->mId ) {
920 $this->loadDefaults();
921 return false;
924 $dbr = wfGetDB( DB_MASTER );
925 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ );
927 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
929 if ( $s !== false ) {
930 # Initialise user table data
931 $this->loadFromRow( $s );
932 $this->mGroups = null; // deferred
933 $this->getEditCount(); // revalidation for nulls
934 return true;
935 } else {
936 # Invalid user_id
937 $this->mId = 0;
938 $this->loadDefaults();
939 return false;
944 * Initialize this object from a row from the user table.
946 * @param $row \type{\arrayof{\mixed}} Row from the user table to load.
948 function loadFromRow( $row ) {
949 $this->mDataLoaded = true;
951 if ( isset( $row->user_id ) ) {
952 $this->mId = intval( $row->user_id );
954 $this->mName = $row->user_name;
955 $this->mRealName = $row->user_real_name;
956 $this->mPassword = $row->user_password;
957 $this->mNewpassword = $row->user_newpassword;
958 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
959 $this->mEmail = $row->user_email;
960 $this->decodeOptions( $row->user_options );
961 $this->mTouched = wfTimestamp(TS_MW,$row->user_touched);
962 $this->mToken = $row->user_token;
963 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
964 $this->mEmailToken = $row->user_email_token;
965 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
966 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
967 $this->mEditCount = $row->user_editcount;
971 * Load the groups from the database if they aren't already loaded.
972 * @private
974 function loadGroups() {
975 if ( is_null( $this->mGroups ) ) {
976 $dbr = wfGetDB( DB_MASTER );
977 $res = $dbr->select( 'user_groups',
978 array( 'ug_group' ),
979 array( 'ug_user' => $this->mId ),
980 __METHOD__ );
981 $this->mGroups = array();
982 foreach ( $res as $row ) {
983 $this->mGroups[] = $row->ug_group;
989 * Clear various cached data stored in this object.
990 * @param $reloadFrom \string Reload user and user_groups table data from a
991 * given source. May be "name", "id", "defaults", "session", or false for
992 * no reload.
994 function clearInstanceCache( $reloadFrom = false ) {
995 $this->mNewtalk = -1;
996 $this->mDatePreference = null;
997 $this->mBlockedby = -1; # Unset
998 $this->mHash = false;
999 $this->mSkin = null;
1000 $this->mRights = null;
1001 $this->mEffectiveGroups = null;
1002 $this->mOptions = null;
1004 if ( $reloadFrom ) {
1005 $this->mDataLoaded = false;
1006 $this->mFrom = $reloadFrom;
1011 * Combine the language default options with any site-specific options
1012 * and add the default language variants.
1014 * @return \type{\arrayof{\string}} Array of options
1016 static function getDefaultOptions() {
1017 global $wgNamespacesToBeSearchedDefault;
1019 * Site defaults will override the global/language defaults
1021 global $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1022 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
1025 * default language setting
1027 $variant = $wgContLang->getPreferredVariant( false );
1028 $defOpt['variant'] = $variant;
1029 $defOpt['language'] = $variant;
1030 foreach( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1031 $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1033 $defOpt['skin'] = $wgDefaultSkin;
1035 return $defOpt;
1039 * Get a given default option value.
1041 * @param $opt \string Name of option to retrieve
1042 * @return \string Default option value
1044 public static function getDefaultOption( $opt ) {
1045 $defOpts = self::getDefaultOptions();
1046 if( isset( $defOpts[$opt] ) ) {
1047 return $defOpts[$opt];
1048 } else {
1049 return null;
1055 * Get blocking information
1056 * @private
1057 * @param $bFromSlave \bool Whether to check the slave database first. To
1058 * improve performance, non-critical checks are done
1059 * against slaves. Check when actually saving should be
1060 * done against master.
1062 function getBlockedStatus( $bFromSlave = true ) {
1063 global $wgProxyWhitelist, $wgUser;
1065 if ( -1 != $this->mBlockedby ) {
1066 wfDebug( "User::getBlockedStatus: already loaded.\n" );
1067 return;
1070 wfProfileIn( __METHOD__ );
1071 wfDebug( __METHOD__.": checking...\n" );
1073 // Initialize data...
1074 // Otherwise something ends up stomping on $this->mBlockedby when
1075 // things get lazy-loaded later, causing false positive block hits
1076 // due to -1 !== 0. Probably session-related... Nothing should be
1077 // overwriting mBlockedby, surely?
1078 $this->load();
1080 $this->mBlockedby = 0;
1081 $this->mHideName = 0;
1082 $this->mAllowUsertalk = 0;
1084 # Check if we are looking at an IP or a logged-in user
1085 if ( $this->isIP( $this->getName() ) ) {
1086 $ip = $this->getName();
1087 } else {
1088 # Check if we are looking at the current user
1089 # If we don't, and the user is logged in, we don't know about
1090 # his IP / autoblock status, so ignore autoblock of current user's IP
1091 if ( $this->getID() != $wgUser->getID() ) {
1092 $ip = '';
1093 } else {
1094 # Get IP of current user
1095 $ip = wfGetIP();
1099 if ( $this->isAllowed( 'ipblock-exempt' ) ) {
1100 # Exempt from all types of IP-block
1101 $ip = '';
1104 # User/IP blocking
1105 $this->mBlock = new Block();
1106 $this->mBlock->fromMaster( !$bFromSlave );
1107 if ( $this->mBlock->load( $ip , $this->mId ) ) {
1108 wfDebug( __METHOD__ . ": Found block.\n" );
1109 $this->mBlockedby = $this->mBlock->mBy;
1110 if( $this->mBlockedby == 0 )
1111 $this->mBlockedby = $this->mBlock->mByName;
1112 $this->mBlockreason = $this->mBlock->mReason;
1113 $this->mHideName = $this->mBlock->mHideName;
1114 $this->mAllowUsertalk = $this->mBlock->mAllowUsertalk;
1115 if ( $this->isLoggedIn() && $wgUser->getID() == $this->getID() ) {
1116 $this->spreadBlock();
1118 } else {
1119 // Bug 13611: don't remove mBlock here, to allow account creation blocks to
1120 // apply to users. Note that the existence of $this->mBlock is not used to
1121 // check for edit blocks, $this->mBlockedby is instead.
1124 # Proxy blocking
1125 if ( !$this->isAllowed( 'proxyunbannable' ) && !in_array( $ip, $wgProxyWhitelist ) ) {
1126 # Local list
1127 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1128 $this->mBlockedby = wfMsg( 'proxyblocker' );
1129 $this->mBlockreason = wfMsg( 'proxyblockreason' );
1132 # DNSBL
1133 if ( !$this->mBlockedby && !$this->getID() ) {
1134 if ( $this->isDnsBlacklisted( $ip ) ) {
1135 $this->mBlockedby = wfMsg( 'sorbs' );
1136 $this->mBlockreason = wfMsg( 'sorbsreason' );
1141 # Extensions
1142 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1144 wfProfileOut( __METHOD__ );
1148 * Whether the given IP is in a DNS blacklist.
1150 * @param $ip \string IP to check
1151 * @param $checkWhitelist Boolean: whether to check the whitelist first
1152 * @return \bool True if blacklisted.
1154 function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1155 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1156 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1158 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
1159 return false;
1161 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
1162 return false;
1164 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1165 return $this->inDnsBlacklist( $ip, $urls );
1169 * Whether the given IP is in a given DNS blacklist.
1171 * @param $ip \string IP to check
1172 * @param $bases \string or Array of Strings: URL of the DNS blacklist
1173 * @return \bool True if blacklisted.
1175 function inDnsBlacklist( $ip, $bases ) {
1176 wfProfileIn( __METHOD__ );
1178 $found = false;
1179 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1180 if( IP::isIPv4( $ip ) ) {
1181 # Reverse IP, bug 21255
1182 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1184 foreach( (array)$bases as $base ) {
1185 # Make hostname
1186 $host = "$ipReversed.$base";
1188 # Send query
1189 $ipList = gethostbynamel( $host );
1191 if( $ipList ) {
1192 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1193 $found = true;
1194 break;
1195 } else {
1196 wfDebug( "Requested $host, not found in $base.\n" );
1201 wfProfileOut( __METHOD__ );
1202 return $found;
1206 * Is this user subject to rate limiting?
1208 * @return \bool True if rate limited
1210 public function isPingLimitable() {
1211 global $wgRateLimitsExcludedGroups;
1212 global $wgRateLimitsExcludedIPs;
1213 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1214 // Deprecated, but kept for backwards-compatibility config
1215 return false;
1218 wfDebug( "Checking the list of IP addresses excluded from rate limit..\n" );
1220 // Read list of IP addresses from MediaWiki namespace
1221 $message = wfMsgForContentNoTrans( 'ratelimit-excluded-ips' );
1222 $lines = explode( "\n", $message );
1223 foreach( $lines as $line ) {
1224 // Remove comment lines
1225 $comment = substr( trim( $line ), 0, 1 );
1226 if ( $comment == '#' || $comment == '' ) {
1227 continue;
1229 // Remove additional comments after an IP address
1230 $comment = strpos( $line, '#' );
1231 if ( $comment > 0 ) {
1232 $line = trim( substr( $line, 0, $comment-1 ) );
1233 if ( IP::isValid( $line ) ) {
1234 $wgRateLimitsExcludedIPs[] = IP::sanitizeIP( $line );
1239 $ip = IP::sanitizeIP( wfGetIP() );
1240 if( in_array( $ip, $wgRateLimitsExcludedIPs ) ) {
1241 // No other good way currently to disable rate limits
1242 // for specific IPs. :P
1243 // But this is a crappy hack and should die.
1244 wfDebug( "IP $ip matches the list of rate limit excluded IPs\n" );
1245 return false;
1247 return !$this->isAllowed('noratelimit');
1251 * Primitive rate limits: enforce maximum actions per time period
1252 * to put a brake on flooding.
1254 * @note When using a shared cache like memcached, IP-address
1255 * last-hit counters will be shared across wikis.
1257 * @param $action \string Action to enforce; 'edit' if unspecified
1258 * @return \bool True if a rate limiter was tripped
1260 function pingLimiter( $action = 'edit' ) {
1261 # Call the 'PingLimiter' hook
1262 $result = false;
1263 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1264 return $result;
1267 global $wgRateLimits;
1268 if( !isset( $wgRateLimits[$action] ) ) {
1269 return false;
1272 # Some groups shouldn't trigger the ping limiter, ever
1273 if( !$this->isPingLimitable() )
1274 return false;
1276 global $wgMemc, $wgRateLimitLog;
1277 wfProfileIn( __METHOD__ );
1279 $limits = $wgRateLimits[$action];
1280 $keys = array();
1281 $id = $this->getId();
1282 $ip = wfGetIP();
1283 $userLimit = false;
1285 if( isset( $limits['anon'] ) && $id == 0 ) {
1286 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1289 if( isset( $limits['user'] ) && $id != 0 ) {
1290 $userLimit = $limits['user'];
1292 if( $this->isNewbie() ) {
1293 if( isset( $limits['newbie'] ) && $id != 0 ) {
1294 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1296 if( isset( $limits['ip'] ) ) {
1297 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1299 $matches = array();
1300 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1301 $subnet = $matches[1];
1302 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1305 // Check for group-specific permissions
1306 // If more than one group applies, use the group with the highest limit
1307 foreach ( $this->getGroups() as $group ) {
1308 if ( isset( $limits[$group] ) ) {
1309 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1310 $userLimit = $limits[$group];
1314 // Set the user limit key
1315 if ( $userLimit !== false ) {
1316 wfDebug( __METHOD__ . ": effective user limit: $userLimit\n" );
1317 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1320 $triggered = false;
1321 foreach( $keys as $key => $limit ) {
1322 list( $max, $period ) = $limit;
1323 $summary = "(limit $max in {$period}s)";
1324 $count = $wgMemc->get( $key );
1325 // Already pinged?
1326 if( $count ) {
1327 if( $count > $max ) {
1328 wfDebug( __METHOD__ . ": tripped! $key at $count $summary\n" );
1329 if( $wgRateLimitLog ) {
1330 @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1332 $triggered = true;
1333 } else {
1334 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1336 } else {
1337 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1338 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1340 $wgMemc->incr( $key );
1343 wfProfileOut( __METHOD__ );
1344 return $triggered;
1348 * Check if user is blocked
1350 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1351 * @return \bool True if blocked, false otherwise
1353 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1354 wfDebug( "User::isBlocked: enter\n" );
1355 $this->getBlockedStatus( $bFromSlave );
1356 return $this->mBlockedby !== 0;
1360 * Check if user is blocked from editing a particular article
1362 * @param $title \string Title to check
1363 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1364 * @return \bool True if blocked, false otherwise
1366 function isBlockedFrom( $title, $bFromSlave = false ) {
1367 global $wgBlockAllowsUTEdit;
1368 wfProfileIn( __METHOD__ );
1369 wfDebug( __METHOD__ . ": enter\n" );
1371 wfDebug( __METHOD__ . ": asking isBlocked()\n" );
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" );
1381 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1383 wfProfileOut( __METHOD__ );
1384 return $blocked;
1388 * If user is blocked, return the name of the user who placed the block
1389 * @return \string name of blocker
1391 function blockedBy() {
1392 $this->getBlockedStatus();
1393 return $this->mBlockedby;
1397 * If user is blocked, return the specified reason for the block
1398 * @return \string Blocking reason
1400 function blockedFor() {
1401 $this->getBlockedStatus();
1402 return $this->mBlockreason;
1406 * If user is blocked, return the ID for the block
1407 * @return \int Block ID
1409 function getBlockId() {
1410 $this->getBlockedStatus();
1411 return ( $this->mBlock ? $this->mBlock->mId : false );
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.
1419 * @param $ip \type{\string} IP address, uses current client if none given
1420 * @return \type{\bool} True if blocked, false otherwise
1422 function isBlockedGlobally( $ip = '' ) {
1423 if( $this->mBlockedGlobally !== null ) {
1424 return $this->mBlockedGlobally;
1426 // User is already an IP?
1427 if( IP::isIPAddress( $this->getName() ) ) {
1428 $ip = $this->getName();
1429 } else if( !$ip ) {
1430 $ip = wfGetIP();
1432 $blocked = false;
1433 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1434 $this->mBlockedGlobally = (bool)$blocked;
1435 return $this->mBlockedGlobally;
1439 * Check if user account is locked
1441 * @return \type{\bool} True if locked, false otherwise
1443 function isLocked() {
1444 if( $this->mLocked !== null ) {
1445 return $this->mLocked;
1447 global $wgAuth;
1448 $authUser = $wgAuth->getUserInstance( $this );
1449 $this->mLocked = (bool)$authUser->isLocked();
1450 return $this->mLocked;
1454 * Check if user account is hidden
1456 * @return \type{\bool} True if hidden, false otherwise
1458 function isHidden() {
1459 if( $this->mHideName !== null ) {
1460 return $this->mHideName;
1462 $this->getBlockedStatus();
1463 if( !$this->mHideName ) {
1464 global $wgAuth;
1465 $authUser = $wgAuth->getUserInstance( $this );
1466 $this->mHideName = (bool)$authUser->isHidden();
1468 return $this->mHideName;
1472 * Get the user's ID.
1473 * @return \int The user's ID; 0 if the user is anonymous or nonexistent
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();
1484 return $this->mId;
1488 * Set the user and reload all fields according to a given ID
1489 * @param $v \int User ID to reload
1491 function setId( $v ) {
1492 $this->mId = $v;
1493 $this->clearInstanceCache( 'id' );
1497 * Get the user name, or the IP of an anonymous user
1498 * @return \string User's name or IP address
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() );
1510 return $this->mName;
1515 * Set the user name.
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.
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
1527 function setName( $str ) {
1528 $this->load();
1529 $this->mName = $str;
1533 * Get the user's name escaped by underscores.
1534 * @return \string Username escaped by underscores.
1536 function getTitleKey() {
1537 return str_replace( ' ', '_', $this->getName() );
1541 * Check if the user has new messages.
1542 * @return \bool True if the user has new messages
1544 function getNewtalk() {
1545 $this->load();
1547 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1548 if( $this->mNewtalk === -1 ) {
1549 $this->mNewtalk = false; # reset talk page status
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 );
1565 } else {
1566 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1570 return (bool)$this->mNewtalk;
1574 * Return the talk page(s) this user has new messages on.
1575 * @return \type{\arrayof{\string}} Array of page URLs
1577 function getNewMessageLinks() {
1578 $talks = array();
1579 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) )
1580 return $talks;
1582 if( !$this->getNewtalk() )
1583 return array();
1584 $up = $this->getUserPage();
1585 $utp = $up->getTalkPage();
1586 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL() ) );
1590 * Internal uncached check for new messages
1592 * @see getNewtalk()
1593 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1594 * @param $id \types{\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
1599 function checkNewtalk( $field, $id, $fromMaster = false ) {
1600 if ( $fromMaster ) {
1601 $db = wfGetDB( DB_MASTER );
1602 } else {
1603 $db = wfGetDB( DB_SLAVE );
1605 $ok = $db->selectField( 'user_newtalk', $field,
1606 array( $field => $id ), __METHOD__ );
1607 return $ok !== false;
1611 * Add or update the new messages flag
1612 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1613 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1614 * @return \bool True if successful, false otherwise
1615 * @private
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;
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 \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1636 * @return \bool True if successful, false otherwise
1637 * @private
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;
1654 * Update the 'You have new messages!' status.
1655 * @param $val \bool Whether the user has new messages
1657 function setNewtalk( $val ) {
1658 if( wfReadOnly() ) {
1659 return;
1662 $this->load();
1663 $this->mNewtalk = $val;
1665 if( $this->isAnon() ) {
1666 $field = 'user_ip';
1667 $id = $this->getName();
1668 } else {
1669 $field = 'user_id';
1670 $id = $this->getId();
1672 global $wgMemc;
1674 if( $val ) {
1675 $changed = $this->updateNewtalk( $field, $id );
1676 } else {
1677 $changed = $this->deleteNewtalk( $field, $id );
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 );
1686 if ( $changed ) {
1687 $this->invalidateCache();
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
1696 private static function newTouchedTimestamp() {
1697 global $wgClockSkewFudge;
1698 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
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.
1706 * Called implicitly from invalidateCache() and saveSettings().
1708 private function clearSharedCache() {
1709 $this->load();
1710 if( $this->mId ) {
1711 global $wgMemc;
1712 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
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.
1721 function invalidateCache() {
1722 if( wfReadOnly() ) {
1723 return;
1725 $this->load();
1726 if( $this->mId ) {
1727 $this->mTouched = self::newTouchedTimestamp();
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__ );
1735 $this->clearSharedCache();
1740 * Validate the cache for this account.
1741 * @param $timestamp \string A timestamp in TS_MW format
1743 function validateCache( $timestamp ) {
1744 $this->load();
1745 return ( $timestamp >= $this->mTouched );
1749 * Get the user touched timestamp
1751 function getTouched() {
1752 $this->load();
1753 return $this->mTouched;
1757 * Set the password and reset the random token.
1758 * Calls through to authentication plugin if necessary;
1759 * will have no effect if the auth plugin refuses to
1760 * pass the change through or if the legal password
1761 * checks fail.
1763 * As a special case, setting the password to null
1764 * wipes it, so the account cannot be logged in until
1765 * a new password is set, for instance via e-mail.
1767 * @param $str \string New password to set
1768 * @throws PasswordError on failure
1770 function setPassword( $str ) {
1771 global $wgAuth;
1773 if( $str !== null ) {
1774 if( !$wgAuth->allowPasswordChange() ) {
1775 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1778 if( !$this->isValidPassword( $str ) ) {
1779 global $wgMinimalPasswordLength;
1780 $valid = $this->getPasswordValidity( $str );
1781 throw new PasswordError( wfMsgExt( $valid, array( 'parsemag' ),
1782 $wgMinimalPasswordLength ) );
1786 if( !$wgAuth->setPassword( $this, $str ) ) {
1787 throw new PasswordError( wfMsg( 'externaldberror' ) );
1790 $this->setInternalPassword( $str );
1792 return true;
1796 * Set the password and reset the random token unconditionally.
1798 * @param $str \string New password to set
1800 function setInternalPassword( $str ) {
1801 $this->load();
1802 $this->setToken();
1804 if( $str === null ) {
1805 // Save an invalid hash...
1806 $this->mPassword = '';
1807 } else {
1808 $this->mPassword = self::crypt( $str );
1810 $this->mNewpassword = '';
1811 $this->mNewpassTime = null;
1815 * Get the user's current token.
1816 * @return \string Token
1818 function getToken() {
1819 $this->load();
1820 return $this->mToken;
1824 * Set the random token (used for persistent authentication)
1825 * Called from loadDefaults() among other places.
1827 * @param $token \string If specified, set the token to this value
1828 * @private
1830 function setToken( $token = false ) {
1831 global $wgSecretKey, $wgProxyKey;
1832 $this->load();
1833 if ( !$token ) {
1834 if ( $wgSecretKey ) {
1835 $key = $wgSecretKey;
1836 } elseif ( $wgProxyKey ) {
1837 $key = $wgProxyKey;
1838 } else {
1839 $key = microtime();
1841 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
1842 } else {
1843 $this->mToken = $token;
1848 * Set the cookie password
1850 * @param $str \string New cookie password
1851 * @private
1853 function setCookiePassword( $str ) {
1854 $this->load();
1855 $this->mCookiePassword = md5( $str );
1859 * Set the password for a password reminder or new account email
1861 * @param $str \string New password to set
1862 * @param $throttle \bool If true, reset the throttle timestamp to the present
1864 function setNewpassword( $str, $throttle = true ) {
1865 $this->load();
1866 $this->mNewpassword = self::crypt( $str );
1867 if ( $throttle ) {
1868 $this->mNewpassTime = wfTimestampNow();
1873 * Has password reminder email been sent within the last
1874 * $wgPasswordReminderResendTime hours?
1875 * @return \bool True or false
1877 function isPasswordReminderThrottled() {
1878 global $wgPasswordReminderResendTime;
1879 $this->load();
1880 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1881 return false;
1883 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1884 return time() < $expiry;
1888 * Get the user's e-mail address
1889 * @return \string User's email address
1891 function getEmail() {
1892 $this->load();
1893 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
1894 return $this->mEmail;
1898 * Get the timestamp of the user's e-mail authentication
1899 * @return \string TS_MW timestamp
1901 function getEmailAuthenticationTimestamp() {
1902 $this->load();
1903 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
1904 return $this->mEmailAuthenticated;
1908 * Set the user's e-mail address
1909 * @param $str \string New e-mail address
1911 function setEmail( $str ) {
1912 $this->load();
1913 $this->mEmail = $str;
1914 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
1918 * Get the user's real name
1919 * @return \string User's real name
1921 function getRealName() {
1922 $this->load();
1923 return $this->mRealName;
1927 * Set the user's real name
1928 * @param $str \string New real name
1930 function setRealName( $str ) {
1931 $this->load();
1932 $this->mRealName = $str;
1936 * Get the user's current setting for a given option.
1938 * @param $oname \string The option to check
1939 * @param $defaultOverride \string A default value returned if the option does not exist
1940 * @return \string User's current value for the option
1941 * @see getBoolOption()
1942 * @see getIntOption()
1944 function getOption( $oname, $defaultOverride = null ) {
1945 $this->loadOptions();
1947 if ( is_null( $this->mOptions ) ) {
1948 if($defaultOverride != '') {
1949 return $defaultOverride;
1951 $this->mOptions = User::getDefaultOptions();
1954 if ( array_key_exists( $oname, $this->mOptions ) ) {
1955 return $this->mOptions[$oname];
1956 } else {
1957 return $defaultOverride;
1962 * Get all user's options
1964 * @return array
1966 public function getOptions() {
1967 $this->loadOptions();
1968 return $this->mOptions;
1972 * Get the user's current setting for a given option, as a boolean value.
1974 * @param $oname \string The option to check
1975 * @return \bool User's current value for the option
1976 * @see getOption()
1978 function getBoolOption( $oname ) {
1979 return (bool)$this->getOption( $oname );
1984 * Get the user's current setting for a given option, as a boolean value.
1986 * @param $oname \string The option to check
1987 * @param $defaultOverride \int A default value returned if the option does not exist
1988 * @return \int User's current value for the option
1989 * @see getOption()
1991 function getIntOption( $oname, $defaultOverride=0 ) {
1992 $val = $this->getOption( $oname );
1993 if( $val == '' ) {
1994 $val = $defaultOverride;
1996 return intval( $val );
2000 * Set the given option for a user.
2002 * @param $oname \string The option to set
2003 * @param $val \mixed New value to set
2005 function setOption( $oname, $val ) {
2006 $this->load();
2007 $this->loadOptions();
2009 if ( $oname == 'skin' ) {
2010 # Clear cached skin, so the new one displays immediately in Special:Preferences
2011 $this->mSkin = null;
2014 // Explicitly NULL values should refer to defaults
2015 global $wgDefaultUserOptions;
2016 if( is_null( $val ) && isset( $wgDefaultUserOptions[$oname] ) ) {
2017 $val = $wgDefaultUserOptions[$oname];
2020 $this->mOptions[$oname] = $val;
2024 * Reset all options to the site defaults
2026 function resetOptions() {
2027 $this->mOptions = User::getDefaultOptions();
2031 * Get the user's preferred date format.
2032 * @return \string User's preferred date format
2034 function getDatePreference() {
2035 // Important migration for old data rows
2036 if ( is_null( $this->mDatePreference ) ) {
2037 global $wgLang;
2038 $value = $this->getOption( 'date' );
2039 $map = $wgLang->getDatePreferenceMigrationMap();
2040 if ( isset( $map[$value] ) ) {
2041 $value = $map[$value];
2043 $this->mDatePreference = $value;
2045 return $this->mDatePreference;
2049 * Get the user preferred stub threshold
2051 function getStubThreshold() {
2052 global $wgMaxArticleSize; # Maximum article size, in Kb
2053 $threshold = intval( $this->getOption( 'stubthreshold' ) );
2054 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2055 # If they have set an impossible value, disable the preference
2056 # so we can use the parser cache again.
2057 $threshold = 0;
2059 return $threshold;
2063 * Get the permissions this user has.
2064 * @return \type{\arrayof{\string}} Array of permission names
2066 function getRights() {
2067 if ( is_null( $this->mRights ) ) {
2068 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2069 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2070 // Force reindexation of rights when a hook has unset one of them
2071 $this->mRights = array_values( $this->mRights );
2073 return $this->mRights;
2077 * Get the list of explicit group memberships this user has.
2078 * The implicit * and user groups are not included.
2079 * @return \type{\arrayof{\string}} Array of internal group names
2081 function getGroups() {
2082 $this->load();
2083 return $this->mGroups;
2087 * Get the list of implicit group memberships this user has.
2088 * This includes all explicit groups, plus 'user' if logged in,
2089 * '*' for all accounts and autopromoted groups
2090 * @param $recache \bool Whether to avoid the cache
2091 * @return \type{\arrayof{\string}} Array of internal group names
2093 function getEffectiveGroups( $recache = false ) {
2094 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2095 wfProfileIn( __METHOD__ );
2096 $this->mEffectiveGroups = $this->getGroups();
2097 $this->mEffectiveGroups[] = '*';
2098 if( $this->getId() ) {
2099 $this->mEffectiveGroups[] = 'user';
2101 $this->mEffectiveGroups = array_unique( array_merge(
2102 $this->mEffectiveGroups,
2103 Autopromote::getAutopromoteGroups( $this )
2104 ) );
2106 # Hook for additional groups
2107 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2109 wfProfileOut( __METHOD__ );
2111 return $this->mEffectiveGroups;
2115 * Get the user's edit count.
2116 * @return \int User'e edit count
2118 function getEditCount() {
2119 if( $this->getId() ) {
2120 if ( !isset( $this->mEditCount ) ) {
2121 /* Populate the count, if it has not been populated yet */
2122 $this->mEditCount = User::edits( $this->mId );
2124 return $this->mEditCount;
2125 } else {
2126 /* nil */
2127 return null;
2132 * Add the user to the given group.
2133 * This takes immediate effect.
2134 * @param $group \string Name of the group to add
2136 function addGroup( $group ) {
2137 $dbw = wfGetDB( DB_MASTER );
2138 if( $this->getId() ) {
2139 $dbw->insert( 'user_groups',
2140 array(
2141 'ug_user' => $this->getID(),
2142 'ug_group' => $group,
2144 __METHOD__,
2145 array( 'IGNORE' ) );
2148 $this->loadGroups();
2149 $this->mGroups[] = $group;
2150 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2152 $this->invalidateCache();
2156 * Remove the user from the given group.
2157 * This takes immediate effect.
2158 * @param $group \string Name of the group to remove
2160 function removeGroup( $group ) {
2161 $this->load();
2162 $dbw = wfGetDB( DB_MASTER );
2163 $dbw->delete( 'user_groups',
2164 array(
2165 'ug_user' => $this->getID(),
2166 'ug_group' => $group,
2167 ), __METHOD__ );
2169 $this->loadGroups();
2170 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2171 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2173 $this->invalidateCache();
2177 * Get whether the user is logged in
2178 * @return \bool True or false
2180 function isLoggedIn() {
2181 return $this->getID() != 0;
2185 * Get whether the user is anonymous
2186 * @return \bool True or false
2188 function isAnon() {
2189 return !$this->isLoggedIn();
2193 * Get whether the user is a bot
2194 * @return \bool True or false
2195 * @deprecated
2197 function isBot() {
2198 wfDeprecated( __METHOD__ );
2199 return $this->isAllowed( 'bot' );
2203 * Check if user is allowed to access a feature / make an action
2204 * @param $action \string action to be checked
2205 * @return \bool True if action is allowed, else false
2207 function isAllowed( $action = '' ) {
2208 if ( $action === '' )
2209 return true; // In the spirit of DWIM
2210 # Patrolling may not be enabled
2211 if( $action === 'patrol' || $action === 'autopatrol' ) {
2212 global $wgUseRCPatrol, $wgUseNPPatrol;
2213 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2214 return false;
2216 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2217 # by misconfiguration: 0 == 'foo'
2218 return in_array( $action, $this->getRights(), true );
2222 * Check whether to enable recent changes patrol features for this user
2223 * @return \bool True or false
2225 public function useRCPatrol() {
2226 global $wgUseRCPatrol;
2227 return( $wgUseRCPatrol && ( $this->isAllowed( 'patrol' ) || $this->isAllowed( 'patrolmarks' ) ) );
2231 * Check whether to enable new pages patrol features for this user
2232 * @return \bool True or false
2234 public function useNPPatrol() {
2235 global $wgUseRCPatrol, $wgUseNPPatrol;
2236 return( ( $wgUseRCPatrol || $wgUseNPPatrol ) && ( $this->isAllowed( 'patrol' ) || $this->isAllowed( 'patrolmarks' ) ) );
2240 * Get the current skin, loading it if required, and setting a title
2241 * @param $t Title: the title to use in the skin
2242 * @return Skin The current skin
2243 * @todo FIXME : need to check the old failback system [AV]
2245 function getSkin( $t = null ) {
2246 if ( $t ) {
2247 $skin = $this->createSkinObject();
2248 $skin->setTitle( $t );
2249 return $skin;
2250 } else {
2251 if ( ! $this->mSkin ) {
2252 $this->mSkin = $this->createSkinObject();
2255 if ( ! $this->mSkin->getTitle() ) {
2256 global $wgOut;
2257 $t = $wgOut->getTitle();
2258 $this->mSkin->setTitle($t);
2261 return $this->mSkin;
2265 // Creates a Skin object, for getSkin()
2266 private function createSkinObject() {
2267 wfProfileIn( __METHOD__ );
2269 global $wgHiddenPrefs;
2270 if( !in_array( 'skin', $wgHiddenPrefs ) ) {
2271 # get the user skin
2272 global $wgRequest;
2273 $userSkin = $this->getOption( 'skin' );
2274 $userSkin = $wgRequest->getVal( 'useskin', $userSkin );
2275 } else {
2276 # if we're not allowing users to override, then use the default
2277 global $wgDefaultSkin;
2278 $userSkin = $wgDefaultSkin;
2281 $skin = Skin::newFromKey( $userSkin );
2282 wfProfileOut( __METHOD__ );
2284 return $skin;
2288 * Check the watched status of an article.
2289 * @param $title \type{Title} Title of the article to look at
2290 * @return \bool True if article is watched
2292 function isWatched( $title ) {
2293 $wl = WatchedItem::fromUserTitle( $this, $title );
2294 return $wl->isWatched();
2298 * Watch an article.
2299 * @param $title \type{Title} Title of the article to look at
2301 function addWatch( $title ) {
2302 $wl = WatchedItem::fromUserTitle( $this, $title );
2303 $wl->addWatch();
2304 $this->invalidateCache();
2308 * Stop watching an article.
2309 * @param $title \type{Title} Title of the article to look at
2311 function removeWatch( $title ) {
2312 $wl = WatchedItem::fromUserTitle( $this, $title );
2313 $wl->removeWatch();
2314 $this->invalidateCache();
2318 * Clear the user's notification timestamp for the given title.
2319 * If e-notif e-mails are on, they will receive notification mails on
2320 * the next change of the page if it's watched etc.
2321 * @param $title \type{Title} Title of the article to look at
2323 function clearNotification( &$title ) {
2324 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2326 # Do nothing if the database is locked to writes
2327 if( wfReadOnly() ) {
2328 return;
2331 if( $title->getNamespace() == NS_USER_TALK &&
2332 $title->getText() == $this->getName() ) {
2333 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2334 return;
2335 $this->setNewtalk( false );
2338 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2339 return;
2342 if( $this->isAnon() ) {
2343 // Nothing else to do...
2344 return;
2347 // Only update the timestamp if the page is being watched.
2348 // The query to find out if it is watched is cached both in memcached and per-invocation,
2349 // and when it does have to be executed, it can be on a slave
2350 // If this is the user's newtalk page, we always update the timestamp
2351 if( $title->getNamespace() == NS_USER_TALK &&
2352 $title->getText() == $wgUser->getName() )
2354 $watched = true;
2355 } elseif ( $this->getId() == $wgUser->getId() ) {
2356 $watched = $title->userIsWatching();
2357 } else {
2358 $watched = true;
2361 // If the page is watched by the user (or may be watched), update the timestamp on any
2362 // any matching rows
2363 if ( $watched ) {
2364 $dbw = wfGetDB( DB_MASTER );
2365 $dbw->update( 'watchlist',
2366 array( /* SET */
2367 'wl_notificationtimestamp' => null
2368 ), array( /* WHERE */
2369 'wl_title' => $title->getDBkey(),
2370 'wl_namespace' => $title->getNamespace(),
2371 'wl_user' => $this->getID()
2372 ), __METHOD__
2378 * Resets all of the given user's page-change notification timestamps.
2379 * If e-notif e-mails are on, they will receive notification mails on
2380 * the next change of any watched page.
2382 * @param $currentUser \int User ID
2384 function clearAllNotifications( $currentUser ) {
2385 global $wgUseEnotif, $wgShowUpdatedMarker;
2386 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2387 $this->setNewtalk( false );
2388 return;
2390 if( $currentUser != 0 ) {
2391 $dbw = wfGetDB( DB_MASTER );
2392 $dbw->update( 'watchlist',
2393 array( /* SET */
2394 'wl_notificationtimestamp' => null
2395 ), array( /* WHERE */
2396 'wl_user' => $currentUser
2397 ), __METHOD__
2399 # We also need to clear here the "you have new message" notification for the own user_talk page
2400 # This is cleared one page view later in Article::viewUpdates();
2405 * Set this user's options from an encoded string
2406 * @param $str \string Encoded options to import
2407 * @private
2409 function decodeOptions( $str ) {
2410 if( !$str )
2411 return;
2413 $this->mOptionsLoaded = true;
2414 $this->mOptionOverrides = array();
2416 // If an option is not set in $str, use the default value
2417 $this->mOptions = self::getDefaultOptions();
2419 $a = explode( "\n", $str );
2420 foreach ( $a as $s ) {
2421 $m = array();
2422 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2423 $this->mOptions[$m[1]] = $m[2];
2424 $this->mOptionOverrides[$m[1]] = $m[2];
2430 * Set a cookie on the user's client. Wrapper for
2431 * WebResponse::setCookie
2432 * @param $name \string Name of the cookie to set
2433 * @param $value \string Value to set
2434 * @param $exp \int Expiration time, as a UNIX time value;
2435 * if 0 or not specified, use the default $wgCookieExpiration
2437 protected function setCookie( $name, $value, $exp = 0 ) {
2438 global $wgRequest;
2439 $wgRequest->response()->setcookie( $name, $value, $exp );
2443 * Clear a cookie on the user's client
2444 * @param $name \string Name of the cookie to clear
2446 protected function clearCookie( $name ) {
2447 $this->setCookie( $name, '', time() - 86400 );
2451 * Set the default cookies for this session on the user's client.
2453 function setCookies() {
2454 $this->load();
2455 if ( 0 == $this->mId ) return;
2456 $session = array(
2457 'wsUserID' => $this->mId,
2458 'wsToken' => $this->mToken,
2459 'wsUserName' => $this->getName()
2461 $cookies = array(
2462 'UserID' => $this->mId,
2463 'UserName' => $this->getName(),
2465 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2466 $cookies['Token'] = $this->mToken;
2467 } else {
2468 $cookies['Token'] = false;
2471 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2472 #check for null, since the hook could cause a null value
2473 if ( !is_null( $session ) && isset( $_SESSION ) ){
2474 $_SESSION = $session + $_SESSION;
2476 foreach ( $cookies as $name => $value ) {
2477 if ( $value === false ) {
2478 $this->clearCookie( $name );
2479 } else {
2480 $this->setCookie( $name, $value );
2486 * Log this user out.
2488 function logout() {
2489 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
2490 $this->doLogout();
2495 * Clear the user's cookies and session, and reset the instance cache.
2496 * @private
2497 * @see logout()
2499 function doLogout() {
2500 $this->clearInstanceCache( 'defaults' );
2502 $_SESSION['wsUserID'] = 0;
2504 $this->clearCookie( 'UserID' );
2505 $this->clearCookie( 'Token' );
2507 # Remember when user logged out, to prevent seeing cached pages
2508 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
2512 * Save this user's settings into the database.
2513 * @todo Only rarely do all these fields need to be set!
2515 function saveSettings() {
2516 $this->load();
2517 if ( wfReadOnly() ) { return; }
2518 if ( 0 == $this->mId ) { return; }
2520 $this->mTouched = self::newTouchedTimestamp();
2522 $dbw = wfGetDB( DB_MASTER );
2523 $dbw->update( 'user',
2524 array( /* SET */
2525 'user_name' => $this->mName,
2526 'user_password' => $this->mPassword,
2527 'user_newpassword' => $this->mNewpassword,
2528 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2529 'user_real_name' => $this->mRealName,
2530 'user_email' => $this->mEmail,
2531 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2532 'user_options' => '',
2533 'user_touched' => $dbw->timestamp( $this->mTouched ),
2534 'user_token' => $this->mToken,
2535 'user_email_token' => $this->mEmailToken,
2536 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
2537 ), array( /* WHERE */
2538 'user_id' => $this->mId
2539 ), __METHOD__
2542 $this->saveOptions();
2544 wfRunHooks( 'UserSaveSettings', array( $this ) );
2545 $this->clearSharedCache();
2546 $this->getUserPage()->invalidateCache();
2550 * If only this user's username is known, and it exists, return the user ID.
2552 function idForName() {
2553 $s = trim( $this->getName() );
2554 if ( $s === '' ) return 0;
2556 $dbr = wfGetDB( DB_SLAVE );
2557 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
2558 if ( $id === false ) {
2559 $id = 0;
2561 return $id;
2565 * Add a user to the database, return the user object
2567 * @param $name \string Username to add
2568 * @param $params \type{\arrayof{\string}} Non-default parameters to save to the database:
2569 * - password The user's password. Password logins will be disabled if this is omitted.
2570 * - newpassword A temporary password mailed to the user
2571 * - email The user's email address
2572 * - email_authenticated The email authentication timestamp
2573 * - real_name The user's real name
2574 * - options An associative array of non-default options
2575 * - token Random authentication token. Do not set.
2576 * - registration Registration timestamp. Do not set.
2578 * @return \type{User} A new User object, or null if the username already exists
2580 static function createNew( $name, $params = array() ) {
2581 $user = new User;
2582 $user->load();
2583 if ( isset( $params['options'] ) ) {
2584 $user->mOptions = $params['options'] + (array)$user->mOptions;
2585 unset( $params['options'] );
2587 $dbw = wfGetDB( DB_MASTER );
2588 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2589 $fields = array(
2590 'user_id' => $seqVal,
2591 'user_name' => $name,
2592 'user_password' => $user->mPassword,
2593 'user_newpassword' => $user->mNewpassword,
2594 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime ),
2595 'user_email' => $user->mEmail,
2596 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
2597 'user_real_name' => $user->mRealName,
2598 'user_options' => '',
2599 'user_token' => $user->mToken,
2600 'user_registration' => $dbw->timestamp( $user->mRegistration ),
2601 'user_editcount' => 0,
2603 foreach ( $params as $name => $value ) {
2604 $fields["user_$name"] = $value;
2606 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
2607 if ( $dbw->affectedRows() ) {
2608 $newUser = User::newFromId( $dbw->insertId() );
2609 } else {
2610 $newUser = null;
2612 return $newUser;
2616 * Add this existing user object to the database
2618 function addToDatabase() {
2619 $this->load();
2620 $dbw = wfGetDB( DB_MASTER );
2621 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2622 $dbw->insert( 'user',
2623 array(
2624 'user_id' => $seqVal,
2625 'user_name' => $this->mName,
2626 'user_password' => $this->mPassword,
2627 'user_newpassword' => $this->mNewpassword,
2628 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime ),
2629 'user_email' => $this->mEmail,
2630 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2631 'user_real_name' => $this->mRealName,
2632 'user_options' => '',
2633 'user_token' => $this->mToken,
2634 'user_registration' => $dbw->timestamp( $this->mRegistration ),
2635 'user_editcount' => 0,
2636 ), __METHOD__
2638 $this->mId = $dbw->insertId();
2640 // Clear instance cache other than user table data, which is already accurate
2641 $this->clearInstanceCache();
2643 $this->saveOptions();
2647 * If this (non-anonymous) user is blocked, block any IP address
2648 * they've successfully logged in from.
2650 function spreadBlock() {
2651 wfDebug( __METHOD__ . "()\n" );
2652 $this->load();
2653 if ( $this->mId == 0 ) {
2654 return;
2657 $userblock = Block::newFromDB( '', $this->mId );
2658 if ( !$userblock ) {
2659 return;
2662 $userblock->doAutoblock( wfGetIP() );
2666 * Generate a string which will be different for any combination of
2667 * user options which would produce different parser output.
2668 * This will be used as part of the hash key for the parser cache,
2669 * so users with the same options can share the same cached data
2670 * safely.
2672 * Extensions which require it should install 'PageRenderingHash' hook,
2673 * which will give them a chance to modify this key based on their own
2674 * settings.
2676 * @deprecated use the ParserOptions object to get the relevant options
2677 * @return \string Page rendering hash
2679 function getPageRenderingHash() {
2680 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2681 if( $this->mHash ){
2682 return $this->mHash;
2684 wfDeprecated( __METHOD__ );
2686 // stubthreshold is only included below for completeness,
2687 // since it disables the parser cache, its value will always
2688 // be 0 when this function is called by parsercache.
2690 $confstr = $this->getOption( 'math' );
2691 $confstr .= '!' . $this->getStubThreshold();
2692 if ( $wgUseDynamicDates ) { # This is wrong (bug 24714)
2693 $confstr .= '!' . $this->getDatePreference();
2695 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ? '1' : '' );
2696 $confstr .= '!' . $wgLang->getCode();
2697 $confstr .= '!' . $this->getOption( 'thumbsize' );
2698 // add in language specific options, if any
2699 $extra = $wgContLang->getExtraHashOptions();
2700 $confstr .= $extra;
2702 // Since the skin could be overloading link(), it should be
2703 // included here but in practice, none of our skins do that.
2705 $confstr .= $wgRenderHashAppend;
2707 // Give a chance for extensions to modify the hash, if they have
2708 // extra options or other effects on the parser cache.
2709 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2711 // Make it a valid memcached key fragment
2712 $confstr = str_replace( ' ', '_', $confstr );
2713 $this->mHash = $confstr;
2714 return $confstr;
2718 * Get whether the user is explicitly blocked from account creation.
2719 * @return \bool True if blocked
2721 function isBlockedFromCreateAccount() {
2722 $this->getBlockedStatus();
2723 return $this->mBlock && $this->mBlock->mCreateAccount;
2727 * Get whether the user is blocked from using Special:Emailuser.
2728 * @return \bool True if blocked
2730 function isBlockedFromEmailuser() {
2731 $this->getBlockedStatus();
2732 return $this->mBlock && $this->mBlock->mBlockEmail;
2736 * Get whether the user is allowed to create an account.
2737 * @return \bool True if allowed
2739 function isAllowedToCreateAccount() {
2740 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2744 * Get this user's personal page title.
2746 * @return \type{Title} User's personal page title
2748 function getUserPage() {
2749 return Title::makeTitle( NS_USER, $this->getName() );
2753 * Get this user's talk page title.
2755 * @return \type{Title} User's talk page title
2757 function getTalkPage() {
2758 $title = $this->getUserPage();
2759 return $title->getTalkPage();
2763 * Get the maximum valid user ID.
2764 * @return \int User ID
2765 * @static
2767 function getMaxID() {
2768 static $res; // cache
2770 if ( isset( $res ) ) {
2771 return $res;
2772 } else {
2773 $dbr = wfGetDB( DB_SLAVE );
2774 return $res = $dbr->selectField( 'user', 'max(user_id)', false, __METHOD__ );
2779 * Determine whether the user is a newbie. Newbies are either
2780 * anonymous IPs, or the most recently created accounts.
2781 * @return \bool True if the user is a newbie
2783 function isNewbie() {
2784 return !$this->isAllowed( 'autoconfirmed' );
2788 * Check to see if the given clear-text password is one of the accepted passwords
2789 * @param $password \string user password.
2790 * @return \bool True if the given password is correct, otherwise False.
2792 function checkPassword( $password ) {
2793 global $wgAuth;
2794 $this->load();
2796 // Even though we stop people from creating passwords that
2797 // are shorter than this, doesn't mean people wont be able
2798 // to. Certain authentication plugins do NOT want to save
2799 // domain passwords in a mysql database, so we should
2800 // check this (incase $wgAuth->strict() is false).
2801 if( !$this->isValidPassword( $password ) ) {
2802 return false;
2805 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2806 return true;
2807 } elseif( $wgAuth->strict() ) {
2808 /* Auth plugin doesn't allow local authentication */
2809 return false;
2810 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2811 /* Auth plugin doesn't allow local authentication for this user name */
2812 return false;
2814 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
2815 return true;
2816 } elseif ( function_exists( 'iconv' ) ) {
2817 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2818 # Check for this with iconv
2819 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2820 if ( self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) ) {
2821 return true;
2824 return false;
2828 * Check if the given clear-text password matches the temporary password
2829 * sent by e-mail for password reset operations.
2830 * @return \bool True if matches, false otherwise
2832 function checkTemporaryPassword( $plaintext ) {
2833 global $wgNewPasswordExpiry;
2834 if( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
2835 $this->load();
2836 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
2837 return ( time() < $expiry );
2838 } else {
2839 return false;
2844 * Initialize (if necessary) and return a session token value
2845 * which can be used in edit forms to show that the user's
2846 * login credentials aren't being hijacked with a foreign form
2847 * submission.
2849 * @param $salt \types{\string,\arrayof{\string}} Optional function-specific data for hashing
2850 * @return \string The new edit token
2852 function editToken( $salt = '' ) {
2853 if ( $this->isAnon() ) {
2854 return EDIT_TOKEN_SUFFIX;
2855 } else {
2856 if( !isset( $_SESSION['wsEditToken'] ) ) {
2857 $token = self::generateToken();
2858 $_SESSION['wsEditToken'] = $token;
2859 } else {
2860 $token = $_SESSION['wsEditToken'];
2862 if( is_array( $salt ) ) {
2863 $salt = implode( '|', $salt );
2865 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2870 * Generate a looking random token for various uses.
2872 * @param $salt \string Optional salt value
2873 * @return \string The new random token
2875 public static function generateToken( $salt = '' ) {
2876 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2877 return md5( $token . $salt );
2881 * Check given value against the token value stored in the session.
2882 * A match should confirm that the form was submitted from the
2883 * user's own login session, not a form submission from a third-party
2884 * site.
2886 * @param $val \string Input value to compare
2887 * @param $salt \string Optional function-specific data for hashing
2888 * @return \bool Whether the token matches
2890 function matchEditToken( $val, $salt = '' ) {
2891 $sessionToken = $this->editToken( $salt );
2892 if ( $val != $sessionToken ) {
2893 wfDebug( "User::matchEditToken: broken session data\n" );
2895 return $val == $sessionToken;
2899 * Check given value against the token value stored in the session,
2900 * ignoring the suffix.
2902 * @param $val \string Input value to compare
2903 * @param $salt \string Optional function-specific data for hashing
2904 * @return \bool Whether the token matches
2906 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2907 $sessionToken = $this->editToken( $salt );
2908 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2912 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2913 * mail to the user's given address.
2915 * @param $changed Boolean: whether the adress changed
2916 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure.
2918 function sendConfirmationMail( $changed = false ) {
2919 global $wgLang;
2920 $expiration = null; // gets passed-by-ref and defined in next line.
2921 $token = $this->confirmationToken( $expiration );
2922 $url = $this->confirmationTokenUrl( $token );
2923 $invalidateURL = $this->invalidationTokenUrl( $token );
2924 $this->saveSettings();
2926 $message = $changed ? 'confirmemail_body_changed' : 'confirmemail_body';
2927 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2928 wfMsg( $message,
2929 wfGetIP(),
2930 $this->getName(),
2931 $url,
2932 $wgLang->timeanddate( $expiration, false ),
2933 $invalidateURL,
2934 $wgLang->date( $expiration, false ),
2935 $wgLang->time( $expiration, false ) ) );
2939 * Send an e-mail to this user's account. Does not check for
2940 * confirmed status or validity.
2942 * @param $subject \string Message subject
2943 * @param $body \string Message body
2944 * @param $from \string Optional From address; if unspecified, default $wgPasswordSender will be used
2945 * @param $replyto \string Reply-To address
2946 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure
2948 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2949 if( is_null( $from ) ) {
2950 global $wgPasswordSender;
2951 $from = $wgPasswordSender;
2954 $to = new MailAddress( $this );
2955 $sender = new MailAddress( $from );
2956 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
2960 * Generate, store, and return a new e-mail confirmation code.
2961 * A hash (unsalted, since it's used as a key) is stored.
2963 * @note Call saveSettings() after calling this function to commit
2964 * this change to the database.
2966 * @param[out] &$expiration \mixed Accepts the expiration time
2967 * @return \string New token
2968 * @private
2970 function confirmationToken( &$expiration ) {
2971 $now = time();
2972 $expires = $now + 7 * 24 * 60 * 60;
2973 $expiration = wfTimestamp( TS_MW, $expires );
2974 $token = self::generateToken( $this->mId . $this->mEmail . $expires );
2975 $hash = md5( $token );
2976 $this->load();
2977 $this->mEmailToken = $hash;
2978 $this->mEmailTokenExpires = $expiration;
2979 return $token;
2983 * Return a URL the user can use to confirm their email address.
2984 * @param $token \string Accepts the email confirmation token
2985 * @return \string New token URL
2986 * @private
2988 function confirmationTokenUrl( $token ) {
2989 return $this->getTokenUrl( 'ConfirmEmail', $token );
2993 * Return a URL the user can use to invalidate their email address.
2994 * @param $token \string Accepts the email confirmation token
2995 * @return \string New token URL
2996 * @private
2998 function invalidationTokenUrl( $token ) {
2999 return $this->getTokenUrl( 'Invalidateemail', $token );
3003 * Internal function to format the e-mail validation/invalidation URLs.
3004 * This uses $wgArticlePath directly as a quickie hack to use the
3005 * hardcoded English names of the Special: pages, for ASCII safety.
3007 * @note Since these URLs get dropped directly into emails, using the
3008 * short English names avoids insanely long URL-encoded links, which
3009 * also sometimes can get corrupted in some browsers/mailers
3010 * (bug 6957 with Gmail and Internet Explorer).
3012 * @param $page \string Special page
3013 * @param $token \string Token
3014 * @return \string Formatted URL
3016 protected function getTokenUrl( $page, $token ) {
3017 global $wgArticlePath;
3018 return wfExpandUrl(
3019 str_replace(
3020 '$1',
3021 "Special:$page/$token",
3022 $wgArticlePath ) );
3026 * Mark the e-mail address confirmed.
3028 * @note Call saveSettings() after calling this function to commit the change.
3030 function confirmEmail() {
3031 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3032 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3033 return true;
3037 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3038 * address if it was already confirmed.
3040 * @note Call saveSettings() after calling this function to commit the change.
3042 function invalidateEmail() {
3043 $this->load();
3044 $this->mEmailToken = null;
3045 $this->mEmailTokenExpires = null;
3046 $this->setEmailAuthenticationTimestamp( null );
3047 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3048 return true;
3052 * Set the e-mail authentication timestamp.
3053 * @param $timestamp \string TS_MW timestamp
3055 function setEmailAuthenticationTimestamp( $timestamp ) {
3056 $this->load();
3057 $this->mEmailAuthenticated = $timestamp;
3058 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
3062 * Is this user allowed to send e-mails within limits of current
3063 * site configuration?
3064 * @return \bool True if allowed
3066 function canSendEmail() {
3067 global $wgEnableEmail, $wgEnableUserEmail;
3068 if( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
3069 return false;
3071 $canSend = $this->isEmailConfirmed();
3072 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3073 return $canSend;
3077 * Is this user allowed to receive e-mails within limits of current
3078 * site configuration?
3079 * @return \bool True if allowed
3081 function canReceiveEmail() {
3082 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3086 * Is this user's e-mail address valid-looking and confirmed within
3087 * limits of the current site configuration?
3089 * @note If $wgEmailAuthentication is on, this may require the user to have
3090 * confirmed their address by returning a code or using a password
3091 * sent to the address from the wiki.
3093 * @return \bool True if confirmed
3095 function isEmailConfirmed() {
3096 global $wgEmailAuthentication;
3097 $this->load();
3098 $confirmed = true;
3099 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3100 if( $this->isAnon() )
3101 return false;
3102 if( !self::isValidEmailAddr( $this->mEmail ) )
3103 return false;
3104 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
3105 return false;
3106 return true;
3107 } else {
3108 return $confirmed;
3113 * Check whether there is an outstanding request for e-mail confirmation.
3114 * @return \bool True if pending
3116 function isEmailConfirmationPending() {
3117 global $wgEmailAuthentication;
3118 return $wgEmailAuthentication &&
3119 !$this->isEmailConfirmed() &&
3120 $this->mEmailToken &&
3121 $this->mEmailTokenExpires > wfTimestamp();
3125 * Get the timestamp of account creation.
3127 * @return \types{\string,\bool} string Timestamp of account creation, or false for
3128 * non-existent/anonymous user accounts.
3130 public function getRegistration() {
3131 return $this->getId() > 0
3132 ? $this->mRegistration
3133 : false;
3137 * Get the timestamp of the first edit
3139 * @return \types{\string,\bool} string Timestamp of first edit, or false for
3140 * non-existent/anonymous user accounts.
3142 public function getFirstEditTimestamp() {
3143 if( $this->getId() == 0 ) return false; // anons
3144 $dbr = wfGetDB( DB_SLAVE );
3145 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3146 array( 'rev_user' => $this->getId() ),
3147 __METHOD__,
3148 array( 'ORDER BY' => 'rev_timestamp ASC' )
3150 if( !$time ) return false; // no edits
3151 return wfTimestamp( TS_MW, $time );
3155 * Get the permissions associated with a given list of groups
3157 * @param $groups \type{\arrayof{\string}} List of internal group names
3158 * @return \type{\arrayof{\string}} List of permission key names for given groups combined
3160 static function getGroupPermissions( $groups ) {
3161 global $wgGroupPermissions, $wgRevokePermissions;
3162 $rights = array();
3163 // grant every granted permission first
3164 foreach( $groups as $group ) {
3165 if( isset( $wgGroupPermissions[$group] ) ) {
3166 $rights = array_merge( $rights,
3167 // array_filter removes empty items
3168 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3171 // now revoke the revoked permissions
3172 foreach( $groups as $group ) {
3173 if( isset( $wgRevokePermissions[$group] ) ) {
3174 $rights = array_diff( $rights,
3175 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3178 return array_unique( $rights );
3182 * Get all the groups who have a given permission
3184 * @param $role \string Role to check
3185 * @return \type{\arrayof{\string}} List of internal group names with the given permission
3187 static function getGroupsWithPermission( $role ) {
3188 global $wgGroupPermissions;
3189 $allowedGroups = array();
3190 foreach ( $wgGroupPermissions as $group => $rights ) {
3191 if ( isset( $rights[$role] ) && $rights[$role] ) {
3192 $allowedGroups[] = $group;
3195 return $allowedGroups;
3199 * Get the localized descriptive name for a group, if it exists
3201 * @param $group \string Internal group name
3202 * @return \string Localized descriptive group name
3204 static function getGroupName( $group ) {
3205 $key = "group-$group";
3206 $name = wfMsg( $key );
3207 return $name == '' || wfEmptyMsg( $key, $name )
3208 ? $group
3209 : $name;
3213 * Get the localized descriptive name for a member of a group, if it exists
3215 * @param $group \string Internal group name
3216 * @return \string Localized name for group member
3218 static function getGroupMember( $group ) {
3219 $key = "group-$group-member";
3220 $name = wfMsg( $key );
3221 return $name == '' || wfEmptyMsg( $key, $name )
3222 ? $group
3223 : $name;
3227 * Return the set of defined explicit groups.
3228 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3229 * are not included, as they are defined automatically, not in the database.
3230 * @return \type{\arrayof{\string}} Array of internal group names
3232 static function getAllGroups() {
3233 global $wgGroupPermissions, $wgRevokePermissions;
3234 return array_diff(
3235 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3236 self::getImplicitGroups()
3241 * Get a list of all available permissions.
3242 * @return \type{\arrayof{\string}} Array of permission names
3244 static function getAllRights() {
3245 if ( self::$mAllRights === false ) {
3246 global $wgAvailableRights;
3247 if ( count( $wgAvailableRights ) ) {
3248 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
3249 } else {
3250 self::$mAllRights = self::$mCoreRights;
3252 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
3254 return self::$mAllRights;
3258 * Get a list of implicit groups
3259 * @return \type{\arrayof{\string}} Array of internal group names
3261 public static function getImplicitGroups() {
3262 global $wgImplicitGroups;
3263 $groups = $wgImplicitGroups;
3264 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3265 return $groups;
3269 * Get the title of a page describing a particular group
3271 * @param $group \string Internal group name
3272 * @return \types{\type{Title},\bool} Title of the page if it exists, false otherwise
3274 static function getGroupPage( $group ) {
3275 $page = wfMsgForContent( 'grouppage-' . $group );
3276 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3277 $title = Title::newFromText( $page );
3278 if( is_object( $title ) )
3279 return $title;
3281 return false;
3285 * Create a link to the group in HTML, if available;
3286 * else return the group name.
3288 * @param $group \string Internal name of the group
3289 * @param $text \string The text of the link
3290 * @return \string HTML link to the group
3292 static function makeGroupLinkHTML( $group, $text = '' ) {
3293 if( $text == '' ) {
3294 $text = self::getGroupName( $group );
3296 $title = self::getGroupPage( $group );
3297 if( $title ) {
3298 global $wgUser;
3299 $sk = $wgUser->getSkin();
3300 return $sk->link( $title, htmlspecialchars( $text ) );
3301 } else {
3302 return $text;
3307 * Create a link to the group in Wikitext, if available;
3308 * else return the group name.
3310 * @param $group \string Internal name of the group
3311 * @param $text \string The text of the link
3312 * @return \string Wikilink to the group
3314 static function makeGroupLinkWiki( $group, $text = '' ) {
3315 if( $text == '' ) {
3316 $text = self::getGroupName( $group );
3318 $title = self::getGroupPage( $group );
3319 if( $title ) {
3320 $page = $title->getPrefixedText();
3321 return "[[$page|$text]]";
3322 } else {
3323 return $text;
3328 * Returns an array of the groups that a particular group can add/remove.
3330 * @param $group String: the group to check for whether it can add/remove
3331 * @return Array array( 'add' => array( addablegroups ),
3332 * 'remove' => array( removablegroups ),
3333 * 'add-self' => array( addablegroups to self),
3334 * 'remove-self' => array( removable groups from self) )
3336 static function changeableByGroup( $group ) {
3337 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
3339 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
3340 if( empty( $wgAddGroups[$group] ) ) {
3341 // Don't add anything to $groups
3342 } elseif( $wgAddGroups[$group] === true ) {
3343 // You get everything
3344 $groups['add'] = self::getAllGroups();
3345 } elseif( is_array( $wgAddGroups[$group] ) ) {
3346 $groups['add'] = $wgAddGroups[$group];
3349 // Same thing for remove
3350 if( empty( $wgRemoveGroups[$group] ) ) {
3351 } elseif( $wgRemoveGroups[$group] === true ) {
3352 $groups['remove'] = self::getAllGroups();
3353 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
3354 $groups['remove'] = $wgRemoveGroups[$group];
3357 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
3358 if( empty( $wgGroupsAddToSelf['user']) || $wgGroupsAddToSelf['user'] !== true ) {
3359 foreach( $wgGroupsAddToSelf as $key => $value ) {
3360 if( is_int( $key ) ) {
3361 $wgGroupsAddToSelf['user'][] = $value;
3366 if( empty( $wgGroupsRemoveFromSelf['user']) || $wgGroupsRemoveFromSelf['user'] !== true ) {
3367 foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
3368 if( is_int( $key ) ) {
3369 $wgGroupsRemoveFromSelf['user'][] = $value;
3374 // Now figure out what groups the user can add to him/herself
3375 if( empty( $wgGroupsAddToSelf[$group] ) ) {
3376 } elseif( $wgGroupsAddToSelf[$group] === true ) {
3377 // No idea WHY this would be used, but it's there
3378 $groups['add-self'] = User::getAllGroups();
3379 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
3380 $groups['add-self'] = $wgGroupsAddToSelf[$group];
3383 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
3384 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
3385 $groups['remove-self'] = User::getAllGroups();
3386 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
3387 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
3390 return $groups;
3394 * Returns an array of groups that this user can add and remove
3395 * @return Array array( 'add' => array( addablegroups ),
3396 * 'remove' => array( removablegroups ),
3397 * 'add-self' => array( addablegroups to self),
3398 * 'remove-self' => array( removable groups from self) )
3400 function changeableGroups() {
3401 if( $this->isAllowed( 'userrights' ) ) {
3402 // This group gives the right to modify everything (reverse-
3403 // compatibility with old "userrights lets you change
3404 // everything")
3405 // Using array_merge to make the groups reindexed
3406 $all = array_merge( User::getAllGroups() );
3407 return array(
3408 'add' => $all,
3409 'remove' => $all,
3410 'add-self' => array(),
3411 'remove-self' => array()
3415 // Okay, it's not so simple, we will have to go through the arrays
3416 $groups = array(
3417 'add' => array(),
3418 'remove' => array(),
3419 'add-self' => array(),
3420 'remove-self' => array()
3422 $addergroups = $this->getEffectiveGroups();
3424 foreach( $addergroups as $addergroup ) {
3425 $groups = array_merge_recursive(
3426 $groups, $this->changeableByGroup( $addergroup )
3428 $groups['add'] = array_unique( $groups['add'] );
3429 $groups['remove'] = array_unique( $groups['remove'] );
3430 $groups['add-self'] = array_unique( $groups['add-self'] );
3431 $groups['remove-self'] = array_unique( $groups['remove-self'] );
3433 return $groups;
3437 * Increment the user's edit-count field.
3438 * Will have no effect for anonymous users.
3440 function incEditCount() {
3441 if( !$this->isAnon() ) {
3442 $dbw = wfGetDB( DB_MASTER );
3443 $dbw->update( 'user',
3444 array( 'user_editcount=user_editcount+1' ),
3445 array( 'user_id' => $this->getId() ),
3446 __METHOD__ );
3448 // Lazy initialization check...
3449 if( $dbw->affectedRows() == 0 ) {
3450 // Pull from a slave to be less cruel to servers
3451 // Accuracy isn't the point anyway here
3452 $dbr = wfGetDB( DB_SLAVE );
3453 $count = $dbr->selectField( 'revision',
3454 'COUNT(rev_user)',
3455 array( 'rev_user' => $this->getId() ),
3456 __METHOD__ );
3458 // Now here's a goddamn hack...
3459 if( $dbr !== $dbw ) {
3460 // If we actually have a slave server, the count is
3461 // at least one behind because the current transaction
3462 // has not been committed and replicated.
3463 $count++;
3464 } else {
3465 // But if DB_SLAVE is selecting the master, then the
3466 // count we just read includes the revision that was
3467 // just added in the working transaction.
3470 $dbw->update( 'user',
3471 array( 'user_editcount' => $count ),
3472 array( 'user_id' => $this->getId() ),
3473 __METHOD__ );
3476 // edit count in user cache too
3477 $this->invalidateCache();
3481 * Get the description of a given right
3483 * @param $right \string Right to query
3484 * @return \string Localized description of the right
3486 static function getRightDescription( $right ) {
3487 $key = "right-$right";
3488 $name = wfMsg( $key );
3489 return $name == '' || wfEmptyMsg( $key, $name )
3490 ? $right
3491 : $name;
3495 * Make an old-style password hash
3497 * @param $password \string Plain-text password
3498 * @param $userId \string User ID
3499 * @return \string Password hash
3501 static function oldCrypt( $password, $userId ) {
3502 global $wgPasswordSalt;
3503 if ( $wgPasswordSalt ) {
3504 return md5( $userId . '-' . md5( $password ) );
3505 } else {
3506 return md5( $password );
3511 * Make a new-style password hash
3513 * @param $password \string Plain-text password
3514 * @param $salt \string Optional salt, may be random or the user ID.
3515 * If unspecified or false, will generate one automatically
3516 * @return \string Password hash
3518 static function crypt( $password, $salt = false ) {
3519 global $wgPasswordSalt;
3521 $hash = '';
3522 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3523 return $hash;
3526 if( $wgPasswordSalt ) {
3527 if ( $salt === false ) {
3528 $salt = substr( wfGenerateToken(), 0, 8 );
3530 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3531 } else {
3532 return ':A:' . md5( $password );
3537 * Compare a password hash with a plain-text password. Requires the user
3538 * ID if there's a chance that the hash is an old-style hash.
3540 * @param $hash \string Password hash
3541 * @param $password \string Plain-text password to compare
3542 * @param $userId \string User ID for old-style password salt
3543 * @return \bool
3545 static function comparePasswords( $hash, $password, $userId = false ) {
3546 $type = substr( $hash, 0, 3 );
3548 $result = false;
3549 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3550 return $result;
3553 if ( $type == ':A:' ) {
3554 # Unsalted
3555 return md5( $password ) === substr( $hash, 3 );
3556 } elseif ( $type == ':B:' ) {
3557 # Salted
3558 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3559 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3560 } else {
3561 # Old-style
3562 return self::oldCrypt( $password, $userId ) === $hash;
3567 * Add a newuser log entry for this user
3569 * @param $byEmail Boolean: account made by email?
3570 * @param $reason String: user supplied reason
3572 public function addNewUserLogEntry( $byEmail = false, $reason = '' ) {
3573 global $wgUser, $wgContLang, $wgNewUserLog;
3574 if( empty( $wgNewUserLog ) ) {
3575 return true; // disabled
3578 if( $this->getName() == $wgUser->getName() ) {
3579 $action = 'create';
3580 } else {
3581 $action = 'create2';
3582 if ( $byEmail ) {
3583 if ( $reason === '' ) {
3584 $reason = wfMsgForContent( 'newuserlog-byemail' );
3585 } else {
3586 $reason = $wgContLang->commaList( array(
3587 $reason, wfMsgForContent( 'newuserlog-byemail' ) ) );
3591 $log = new LogPage( 'newusers' );
3592 $log->addEntry(
3593 $action,
3594 $this->getUserPage(),
3595 $reason,
3596 array( $this->getId() )
3598 return true;
3602 * Add an autocreate newuser log entry for this user
3603 * Used by things like CentralAuth and perhaps other authplugins.
3605 public function addNewUserLogEntryAutoCreate() {
3606 global $wgNewUserLog, $wgLogAutocreatedAccounts;
3607 if( !$wgNewUserLog || !$wgLogAutocreatedAccounts ) {
3608 return true; // disabled
3610 $log = new LogPage( 'newusers', false );
3611 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3612 return true;
3615 protected function loadOptions() {
3616 $this->load();
3617 if ( $this->mOptionsLoaded || !$this->getId() )
3618 return;
3620 $this->mOptions = self::getDefaultOptions();
3622 // Maybe load from the object
3623 if ( !is_null( $this->mOptionOverrides ) ) {
3624 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
3625 foreach( $this->mOptionOverrides as $key => $value ) {
3626 $this->mOptions[$key] = $value;
3628 } else {
3629 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
3630 // Load from database
3631 $dbr = wfGetDB( DB_SLAVE );
3633 $res = $dbr->select(
3634 'user_properties',
3635 '*',
3636 array( 'up_user' => $this->getId() ),
3637 __METHOD__
3640 foreach ( $res as $row ) {
3641 $this->mOptionOverrides[$row->up_property] = $row->up_value;
3642 $this->mOptions[$row->up_property] = $row->up_value;
3646 $this->mOptionsLoaded = true;
3648 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
3651 protected function saveOptions() {
3652 global $wgAllowPrefChange;
3654 $extuser = ExternalUser::newFromUser( $this );
3656 $this->loadOptions();
3657 $dbw = wfGetDB( DB_MASTER );
3659 $insert_rows = array();
3661 $saveOptions = $this->mOptions;
3663 // Allow hooks to abort, for instance to save to a global profile.
3664 // Reset options to default state before saving.
3665 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) )
3666 return;
3668 foreach( $saveOptions as $key => $value ) {
3669 # Don't bother storing default values
3670 if ( ( is_null( self::getDefaultOption( $key ) ) &&
3671 !( $value === false || is_null($value) ) ) ||
3672 $value != self::getDefaultOption( $key ) ) {
3673 $insert_rows[] = array(
3674 'up_user' => $this->getId(),
3675 'up_property' => $key,
3676 'up_value' => $value,
3679 if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
3680 switch ( $wgAllowPrefChange[$key] ) {
3681 case 'local':
3682 case 'message':
3683 break;
3684 case 'semiglobal':
3685 case 'global':
3686 $extuser->setPref( $key, $value );
3691 $dbw->begin();
3692 $dbw->delete( 'user_properties', array( 'up_user' => $this->getId() ), __METHOD__ );
3693 $dbw->insert( 'user_properties', $insert_rows, __METHOD__ );
3694 $dbw->commit();
3698 * Provide an array of HTML5 attributes to put on an input element
3699 * intended for the user to enter a new password. This may include
3700 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
3702 * Do *not* use this when asking the user to enter his current password!
3703 * Regardless of configuration, users may have invalid passwords for whatever
3704 * reason (e.g., they were set before requirements were tightened up).
3705 * Only use it when asking for a new password, like on account creation or
3706 * ResetPass.
3708 * Obviously, you still need to do server-side checking.
3710 * NOTE: A combination of bugs in various browsers means that this function
3711 * actually just returns array() unconditionally at the moment. May as
3712 * well keep it around for when the browser bugs get fixed, though.
3714 * @return array Array of HTML attributes suitable for feeding to
3715 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
3716 * That will potentially output invalid XHTML 1.0 Transitional, and will
3717 * get confused by the boolean attribute syntax used.)
3719 public static function passwordChangeInputAttribs() {
3720 global $wgMinimalPasswordLength;
3722 if ( $wgMinimalPasswordLength == 0 ) {
3723 return array();
3726 # Note that the pattern requirement will always be satisfied if the
3727 # input is empty, so we need required in all cases.
3729 # FIXME (bug 23769): This needs to not claim the password is required
3730 # if e-mail confirmation is being used. Since HTML5 input validation
3731 # is b0rked anyway in some browsers, just return nothing. When it's
3732 # re-enabled, fix this code to not output required for e-mail
3733 # registration.
3734 #$ret = array( 'required' );
3735 $ret = array();
3737 # We can't actually do this right now, because Opera 9.6 will print out
3738 # the entered password visibly in its error message! When other
3739 # browsers add support for this attribute, or Opera fixes its support,
3740 # we can add support with a version check to avoid doing this on Opera
3741 # versions where it will be a problem. Reported to Opera as
3742 # DSK-262266, but they don't have a public bug tracker for us to follow.
3744 if ( $wgMinimalPasswordLength > 1 ) {
3745 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
3746 $ret['title'] = wfMsgExt( 'passwordtooshort', 'parsemag',
3747 $wgMinimalPasswordLength );
3751 return $ret;
3755 * Format the user message using a hook, a template, or, failing these, a static format.
3756 * @param $subject String the subject of the message
3757 * @param $text String the content of the message
3758 * @param $signature String the signature, if provided.
3760 static protected function formatUserMessage( $subject, $text, $signature ) {
3761 if ( wfRunHooks( 'FormatUserMessage',
3762 array( $subject, &$text, $signature ) ) ) {
3764 $signature = empty($signature) ? "~~~~~" : "{$signature} ~~~~~";
3766 $template = Title::newFromText( wfMsgForContent( 'usermessage-template' ) );
3767 if ( !$template
3768 || $template->getNamespace() !== NS_TEMPLATE
3769 || !$template->exists() ) {
3770 $text = "\n== $subject ==\n\n$text\n\n-- $signature";
3771 } else {
3772 $text = '{{'. $template->getText()
3773 . " | subject=$subject | body=$text | signature=$signature }}";
3777 return $text;
3781 * Leave a user a message
3782 * @param $subject String the subject of the message
3783 * @param $text String the message to leave
3784 * @param $signature String Text to leave in the signature
3785 * @param $summary String the summary for this change, defaults to
3786 * "Leave system message."
3787 * @param $editor User The user leaving the message, defaults to
3788 * "{{MediaWiki:usermessage-editor}}"
3789 * @param $flags Int default edit flags
3791 * @return boolean true if it was successful
3793 public function leaveUserMessage( $subject, $text, $signature = "",
3794 $summary = null, $editor = null, $flags = 0 ) {
3795 if ( !isset( $summary ) ) {
3796 $summary = wfMsgForContent( 'usermessage-summary' );
3799 if ( !isset( $editor ) ) {
3800 $editor = User::newFromName( wfMsgForContent( 'usermessage-editor' ) );
3801 if ( !$editor->isLoggedIn() ) {
3802 $editor->addToDatabase();
3806 $article = new Article( $this->getTalkPage() );
3807 wfRunHooks( 'SetupUserMessageArticle',
3808 array( $this, &$article, $subject, $text, $signature, $summary, $editor ) );
3811 $text = self::formatUserMessage( $subject, $text, $signature );
3812 $flags = $article->checkFlags( $flags );
3814 if ( $flags & EDIT_UPDATE ) {
3815 $text = $article->getContent() . $text;
3818 $dbw = wfGetDB( DB_MASTER );
3819 $dbw->begin();
3821 try {
3822 $status = $article->doEdit( $text, $summary, $flags, false, $editor );
3823 } catch ( DBQueryError $e ) {
3824 $status = Status::newFatal("DB Error");
3827 if ( $status->isGood() ) {
3828 // Set newtalk with the right user ID
3829 $this->setNewtalk( true );
3830 wfRunHooks( 'AfterUserMessage',
3831 array( $this, $article, $summary, $text, $signature, $summary, $editor ) );
3832 $dbw->commit();
3833 } else {
3834 // The article was concurrently created
3835 wfDebug( __METHOD__ . ": Error ".$status->getWikiText() );
3836 $dbw->rollback();
3839 return $status->isGood();