Merge "Use correct fields for LinkBatch on Special:NewPages"
[mediawiki.git] / includes / User.php
blob961520a36656fe8875f6d9b1f41af745207d83ff
1 <?php
2 /**
3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
23 /**
24 * String Some punctuation to prevent editing from broken text-mangling proxies.
25 * @ingroup Constants
27 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
29 /**
30 * The User object encapsulates all of the user-specific settings (user_id,
31 * name, rights, password, email address, options, last login time). Client
32 * classes use the getXXX() functions to access these fields. These functions
33 * do all the work of determining whether the user is logged in,
34 * whether the requested option can be satisfied from cookies or
35 * whether a database query is needed. Most of the settings needed
36 * for rendering normal pages are set in the cookie to minimize use
37 * of the database.
39 class User implements IDBAccessObject {
40 /**
41 * @const int Number of characters in user_token field.
43 const TOKEN_LENGTH = 32;
45 /**
46 * Global constant made accessible as class constants so that autoloader
47 * magic can be used.
49 const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
51 /**
52 * @const int Serialized record version.
54 const VERSION = 10;
56 /**
57 * Maximum items in $mWatchedItems
59 const MAX_WATCHED_ITEMS_CACHE = 100;
61 /**
62 * Exclude user options that are set to their default value.
63 * @since 1.25
65 const GETOPTIONS_EXCLUDE_DEFAULTS = 1;
67 /**
68 * @var PasswordFactory Lazily loaded factory object for passwords
70 private static $mPasswordFactory = null;
72 /**
73 * Array of Strings List of member variables which are saved to the
74 * shared cache (memcached). Any operation which changes the
75 * corresponding database fields must call a cache-clearing function.
76 * @showinitializer
78 protected static $mCacheVars = array(
79 // user table
80 'mId',
81 'mName',
82 'mRealName',
83 'mEmail',
84 'mTouched',
85 'mToken',
86 'mEmailAuthenticated',
87 'mEmailToken',
88 'mEmailTokenExpires',
89 'mRegistration',
90 'mEditCount',
91 // user_groups table
92 'mGroups',
93 // user_properties table
94 'mOptionOverrides',
97 /**
98 * Array of Strings Core rights.
99 * Each of these should have a corresponding message of the form
100 * "right-$right".
101 * @showinitializer
103 protected static $mCoreRights = array(
104 'apihighlimits',
105 'applychangetags',
106 'autoconfirmed',
107 'autopatrol',
108 'bigdelete',
109 'block',
110 'blockemail',
111 'bot',
112 'browsearchive',
113 'changetags',
114 'createaccount',
115 'createpage',
116 'createtalk',
117 'delete',
118 'deletedhistory',
119 'deletedtext',
120 'deletelogentry',
121 'deleterevision',
122 'edit',
123 'editcontentmodel',
124 'editinterface',
125 'editprotected',
126 'editmyoptions',
127 'editmyprivateinfo',
128 'editmyusercss',
129 'editmyuserjs',
130 'editmywatchlist',
131 'editsemiprotected',
132 'editusercssjs', #deprecated
133 'editusercss',
134 'edituserjs',
135 'hideuser',
136 'import',
137 'importupload',
138 'ipblock-exempt',
139 'managechangetags',
140 'markbotedits',
141 'mergehistory',
142 'minoredit',
143 'move',
144 'movefile',
145 'move-categorypages',
146 'move-rootuserpages',
147 'move-subpages',
148 'nominornewtalk',
149 'noratelimit',
150 'override-export-depth',
151 'pagelang',
152 'passwordreset',
153 'patrol',
154 'patrolmarks',
155 'protect',
156 'proxyunbannable',
157 'purge',
158 'read',
159 'reupload',
160 'reupload-own',
161 'reupload-shared',
162 'rollback',
163 'sendemail',
164 'siteadmin',
165 'suppressionlog',
166 'suppressredirect',
167 'suppressrevision',
168 'unblockself',
169 'undelete',
170 'unwatchedpages',
171 'upload',
172 'upload_by_url',
173 'userrights',
174 'userrights-interwiki',
175 'viewmyprivateinfo',
176 'viewmywatchlist',
177 'viewsuppressed',
178 'writeapi',
182 * String Cached results of getAllRights()
184 protected static $mAllRights = false;
186 /** @name Cache variables */
187 //@{
188 public $mId;
190 public $mName;
192 public $mRealName;
195 * @todo Make this actually private
196 * @private
198 public $mPassword;
201 * @todo Make this actually private
202 * @private
204 public $mNewpassword;
206 public $mNewpassTime;
208 public $mEmail;
209 /** @var string TS_MW timestamp from the DB */
210 public $mTouched;
211 /** @var string TS_MW timestamp from cache */
212 protected $mQuickTouched;
214 protected $mToken;
216 public $mEmailAuthenticated;
218 protected $mEmailToken;
220 protected $mEmailTokenExpires;
222 protected $mRegistration;
224 protected $mEditCount;
226 public $mGroups;
228 protected $mOptionOverrides;
230 protected $mPasswordExpires;
231 //@}
234 * Bool Whether the cache variables have been loaded.
236 //@{
237 public $mOptionsLoaded;
240 * Array with already loaded items or true if all items have been loaded.
242 protected $mLoadedItems = array();
243 //@}
246 * String Initialization data source if mLoadedItems!==true. May be one of:
247 * - 'defaults' anonymous user initialised from class defaults
248 * - 'name' initialise from mName
249 * - 'id' initialise from mId
250 * - 'session' log in from cookies or session if possible
252 * Use the User::newFrom*() family of functions to set this.
254 public $mFrom;
257 * Lazy-initialized variables, invalidated with clearInstanceCache
259 protected $mNewtalk;
261 protected $mDatePreference;
263 public $mBlockedby;
265 protected $mHash;
267 public $mRights;
269 protected $mBlockreason;
271 protected $mEffectiveGroups;
273 protected $mImplicitGroups;
275 protected $mFormerGroups;
277 protected $mBlockedGlobally;
279 protected $mLocked;
281 public $mHideName;
283 public $mOptions;
286 * @var WebRequest
288 private $mRequest;
290 /** @var Block */
291 public $mBlock;
293 /** @var bool */
294 protected $mAllowUsertalk;
296 /** @var Block */
297 private $mBlockedFromCreateAccount = false;
299 /** @var array */
300 private $mWatchedItems = array();
302 /** @var integer User::READ_* constant bitfield used to load data */
303 protected $queryFlagsUsed = self::READ_NORMAL;
305 public static $idCacheByName = array();
308 * Lightweight constructor for an anonymous user.
309 * Use the User::newFrom* factory functions for other kinds of users.
311 * @see newFromName()
312 * @see newFromId()
313 * @see newFromConfirmationCode()
314 * @see newFromSession()
315 * @see newFromRow()
317 public function __construct() {
318 $this->clearInstanceCache( 'defaults' );
322 * @return string
324 public function __toString() {
325 return $this->getName();
329 * Load the user table data for this object from the source given by mFrom.
331 * @param integer $flags User::READ_* constant bitfield
333 public function load( $flags = self::READ_NORMAL ) {
334 if ( $this->mLoadedItems === true ) {
335 return;
338 // Set it now to avoid infinite recursion in accessors
339 $this->mLoadedItems = true;
340 $this->queryFlagsUsed = $flags;
342 switch ( $this->mFrom ) {
343 case 'defaults':
344 $this->loadDefaults();
345 break;
346 case 'name':
347 // Make sure this thread sees its own changes
348 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
349 $flags |= self::READ_LATEST;
350 $this->queryFlagsUsed = $flags;
353 $this->mId = self::idFromName( $this->mName, $flags );
354 if ( !$this->mId ) {
355 // Nonexistent user placeholder object
356 $this->loadDefaults( $this->mName );
357 } else {
358 $this->loadFromId( $flags );
360 break;
361 case 'id':
362 $this->loadFromId( $flags );
363 break;
364 case 'session':
365 if ( !$this->loadFromSession() ) {
366 // Loading from session failed. Load defaults.
367 $this->loadDefaults();
369 Hooks::run( 'UserLoadAfterLoadFromSession', array( $this ) );
370 break;
371 default:
372 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
377 * Load user table data, given mId has already been set.
378 * @param integer $flags User::READ_* constant bitfield
379 * @return bool False if the ID does not exist, true otherwise
381 public function loadFromId( $flags = self::READ_LATEST ) {
382 if ( $this->mId == 0 ) {
383 $this->loadDefaults();
384 return false;
387 // Try cache (unless this needs to lock the DB).
388 // NOTE: if this thread called saveSettings(), the cache was cleared.
389 if ( ( $flags & self::READ_LOCKING ) || !$this->loadFromCache() ) {
390 wfDebug( "User: cache miss for user {$this->mId}\n" );
391 // Load from DB (make sure this thread sees its own changes)
392 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
393 $flags |= self::READ_LATEST;
395 if ( !$this->loadFromDatabase( $flags ) ) {
396 // Can't load from ID, user is anonymous
397 return false;
399 $this->saveToCache();
402 $this->mLoadedItems = true;
403 $this->queryFlagsUsed = $flags;
405 return true;
409 * Load user data from shared cache, given mId has already been set.
411 * @return bool false if the ID does not exist or data is invalid, true otherwise
412 * @since 1.25
414 protected function loadFromCache() {
415 if ( $this->mId == 0 ) {
416 $this->loadDefaults();
417 return false;
420 $key = wfMemcKey( 'user', 'id', $this->mId );
421 $data = ObjectCache::getMainWANInstance()->get( $key );
422 if ( !is_array( $data ) || $data['mVersion'] < self::VERSION ) {
423 // Object is expired
424 return false;
427 wfDebug( "User: got user {$this->mId} from cache\n" );
429 // Restore from cache
430 foreach ( self::$mCacheVars as $name ) {
431 $this->$name = $data[$name];
434 return true;
438 * Save user data to the shared cache
440 * This method should not be called outside the User class
442 public function saveToCache() {
443 $this->load();
444 $this->loadGroups();
445 $this->loadOptions();
447 if ( $this->isAnon() ) {
448 // Anonymous users are uncached
449 return;
452 $data = array();
453 foreach ( self::$mCacheVars as $name ) {
454 $data[$name] = $this->$name;
456 $data['mVersion'] = self::VERSION;
457 $key = wfMemcKey( 'user', 'id', $this->mId );
459 ObjectCache::getMainWANInstance()->set( $key, $data, 3600 );
462 /** @name newFrom*() static factory methods */
463 //@{
466 * Static factory method for creation from username.
468 * This is slightly less efficient than newFromId(), so use newFromId() if
469 * you have both an ID and a name handy.
471 * @param string $name Username, validated by Title::newFromText()
472 * @param string|bool $validate Validate username. Takes the same parameters as
473 * User::getCanonicalName(), except that true is accepted as an alias
474 * for 'valid', for BC.
476 * @return User|bool User object, or false if the username is invalid
477 * (e.g. if it contains illegal characters or is an IP address). If the
478 * username is not present in the database, the result will be a user object
479 * with a name, zero user ID and default settings.
481 public static function newFromName( $name, $validate = 'valid' ) {
482 if ( $validate === true ) {
483 $validate = 'valid';
485 $name = self::getCanonicalName( $name, $validate );
486 if ( $name === false ) {
487 return false;
488 } else {
489 // Create unloaded user object
490 $u = new User;
491 $u->mName = $name;
492 $u->mFrom = 'name';
493 $u->setItemLoaded( 'name' );
494 return $u;
499 * Static factory method for creation from a given user ID.
501 * @param int $id Valid user ID
502 * @return User The corresponding User object
504 public static function newFromId( $id ) {
505 $u = new User;
506 $u->mId = $id;
507 $u->mFrom = 'id';
508 $u->setItemLoaded( 'id' );
509 return $u;
513 * Factory method to fetch whichever user has a given email confirmation code.
514 * This code is generated when an account is created or its e-mail address
515 * has changed.
517 * If the code is invalid or has expired, returns NULL.
519 * @param string $code Confirmation code
520 * @return User|null
522 public static function newFromConfirmationCode( $code ) {
523 $dbr = wfGetDB( DB_SLAVE );
524 $id = $dbr->selectField( 'user', 'user_id', array(
525 'user_email_token' => md5( $code ),
526 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
527 ) );
528 if ( $id !== false ) {
529 return User::newFromId( $id );
530 } else {
531 return null;
536 * Create a new user object using data from session or cookies. If the
537 * login credentials are invalid, the result is an anonymous user.
539 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
540 * @return User
542 public static function newFromSession( WebRequest $request = null ) {
543 $user = new User;
544 $user->mFrom = 'session';
545 $user->mRequest = $request;
546 return $user;
550 * Create a new user object from a user row.
551 * The row should have the following fields from the user table in it:
552 * - either user_name or user_id to load further data if needed (or both)
553 * - user_real_name
554 * - all other fields (email, password, etc.)
555 * It is useless to provide the remaining fields if either user_id,
556 * user_name and user_real_name are not provided because the whole row
557 * will be loaded once more from the database when accessing them.
559 * @param stdClass $row A row from the user table
560 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
561 * @return User
563 public static function newFromRow( $row, $data = null ) {
564 $user = new User;
565 $user->loadFromRow( $row, $data );
566 return $user;
569 //@}
572 * Get the username corresponding to a given user ID
573 * @param int $id User ID
574 * @return string|bool The corresponding username
576 public static function whoIs( $id ) {
577 return UserCache::singleton()->getProp( $id, 'name' );
581 * Get the real name of a user given their user ID
583 * @param int $id User ID
584 * @return string|bool The corresponding user's real name
586 public static function whoIsReal( $id ) {
587 return UserCache::singleton()->getProp( $id, 'real_name' );
591 * Get database id given a user name
592 * @param string $name Username
593 * @param integer $flags User::READ_* constant bitfield
594 * @return int|null The corresponding user's ID, or null if user is nonexistent
596 public static function idFromName( $name, $flags = self::READ_NORMAL ) {
597 $nt = Title::makeTitleSafe( NS_USER, $name );
598 if ( is_null( $nt ) ) {
599 // Illegal name
600 return null;
603 if ( isset( self::$idCacheByName[$name] ) ) {
604 return self::$idCacheByName[$name];
607 $db = ( $flags & self::READ_LATEST )
608 ? wfGetDB( DB_MASTER )
609 : wfGetDB( DB_SLAVE );
611 $s = $db->selectRow(
612 'user',
613 array( 'user_id' ),
614 array( 'user_name' => $nt->getText() ),
615 __METHOD__
618 if ( $s === false ) {
619 $result = null;
620 } else {
621 $result = $s->user_id;
624 self::$idCacheByName[$name] = $result;
626 if ( count( self::$idCacheByName ) > 1000 ) {
627 self::$idCacheByName = array();
630 return $result;
634 * Reset the cache used in idFromName(). For use in tests.
636 public static function resetIdByNameCache() {
637 self::$idCacheByName = array();
641 * Does the string match an anonymous IPv4 address?
643 * This function exists for username validation, in order to reject
644 * usernames which are similar in form to IP addresses. Strings such
645 * as 300.300.300.300 will return true because it looks like an IP
646 * address, despite not being strictly valid.
648 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
649 * address because the usemod software would "cloak" anonymous IP
650 * addresses like this, if we allowed accounts like this to be created
651 * new users could get the old edits of these anonymous users.
653 * @param string $name Name to match
654 * @return bool
656 public static function isIP( $name ) {
657 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
658 || IP::isIPv6( $name );
662 * Is the input a valid username?
664 * Checks if the input is a valid username, we don't want an empty string,
665 * an IP address, anything that contains slashes (would mess up subpages),
666 * is longer than the maximum allowed username size or doesn't begin with
667 * a capital letter.
669 * @param string $name Name to match
670 * @return bool
672 public static function isValidUserName( $name ) {
673 global $wgContLang, $wgMaxNameChars;
675 if ( $name == ''
676 || User::isIP( $name )
677 || strpos( $name, '/' ) !== false
678 || strlen( $name ) > $wgMaxNameChars
679 || $name != $wgContLang->ucfirst( $name )
681 wfDebugLog( 'username', __METHOD__ .
682 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
683 return false;
686 // Ensure that the name can't be misresolved as a different title,
687 // such as with extra namespace keys at the start.
688 $parsed = Title::newFromText( $name );
689 if ( is_null( $parsed )
690 || $parsed->getNamespace()
691 || strcmp( $name, $parsed->getPrefixedText() ) ) {
692 wfDebugLog( 'username', __METHOD__ .
693 ": '$name' invalid due to ambiguous prefixes" );
694 return false;
697 // Check an additional blacklist of troublemaker characters.
698 // Should these be merged into the title char list?
699 $unicodeBlacklist = '/[' .
700 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
701 '\x{00a0}' . # non-breaking space
702 '\x{2000}-\x{200f}' . # various whitespace
703 '\x{2028}-\x{202f}' . # breaks and control chars
704 '\x{3000}' . # ideographic space
705 '\x{e000}-\x{f8ff}' . # private use
706 ']/u';
707 if ( preg_match( $unicodeBlacklist, $name ) ) {
708 wfDebugLog( 'username', __METHOD__ .
709 ": '$name' invalid due to blacklisted characters" );
710 return false;
713 return true;
717 * Usernames which fail to pass this function will be blocked
718 * from user login and new account registrations, but may be used
719 * internally by batch processes.
721 * If an account already exists in this form, login will be blocked
722 * by a failure to pass this function.
724 * @param string $name Name to match
725 * @return bool
727 public static function isUsableName( $name ) {
728 global $wgReservedUsernames;
729 // Must be a valid username, obviously ;)
730 if ( !self::isValidUserName( $name ) ) {
731 return false;
734 static $reservedUsernames = false;
735 if ( !$reservedUsernames ) {
736 $reservedUsernames = $wgReservedUsernames;
737 Hooks::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
740 // Certain names may be reserved for batch processes.
741 foreach ( $reservedUsernames as $reserved ) {
742 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
743 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
745 if ( $reserved == $name ) {
746 return false;
749 return true;
753 * Usernames which fail to pass this function will be blocked
754 * from new account registrations, but may be used internally
755 * either by batch processes or by user accounts which have
756 * already been created.
758 * Additional blacklisting may be added here rather than in
759 * isValidUserName() to avoid disrupting existing accounts.
761 * @param string $name String to match
762 * @return bool
764 public static function isCreatableName( $name ) {
765 global $wgInvalidUsernameCharacters;
767 // Ensure that the username isn't longer than 235 bytes, so that
768 // (at least for the builtin skins) user javascript and css files
769 // will work. (bug 23080)
770 if ( strlen( $name ) > 235 ) {
771 wfDebugLog( 'username', __METHOD__ .
772 ": '$name' invalid due to length" );
773 return false;
776 // Preg yells if you try to give it an empty string
777 if ( $wgInvalidUsernameCharacters !== '' ) {
778 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
779 wfDebugLog( 'username', __METHOD__ .
780 ": '$name' invalid due to wgInvalidUsernameCharacters" );
781 return false;
785 return self::isUsableName( $name );
789 * Is the input a valid password for this user?
791 * @param string $password Desired password
792 * @return bool
794 public function isValidPassword( $password ) {
795 //simple boolean wrapper for getPasswordValidity
796 return $this->getPasswordValidity( $password ) === true;
801 * Given unvalidated password input, return error message on failure.
803 * @param string $password Desired password
804 * @return bool|string|array True on success, string or array of error message on failure
806 public function getPasswordValidity( $password ) {
807 $result = $this->checkPasswordValidity( $password );
808 if ( $result->isGood() ) {
809 return true;
810 } else {
811 $messages = array();
812 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
813 $messages[] = $error['message'];
815 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
816 $messages[] = $warning['message'];
818 if ( count( $messages ) === 1 ) {
819 return $messages[0];
821 return $messages;
826 * Check if this is a valid password for this user
828 * Create a Status object based on the password's validity.
829 * The Status should be set to fatal if the user should not
830 * be allowed to log in, and should have any errors that
831 * would block changing the password.
833 * If the return value of this is not OK, the password
834 * should not be checked. If the return value is not Good,
835 * the password can be checked, but the user should not be
836 * able to set their password to this.
838 * @param string $password Desired password
839 * @return Status
840 * @since 1.23
842 public function checkPasswordValidity( $password ) {
843 global $wgPasswordPolicy;
845 $upp = new UserPasswordPolicy(
846 $wgPasswordPolicy['policies'],
847 $wgPasswordPolicy['checks']
850 $status = Status::newGood();
851 $result = false; //init $result to false for the internal checks
853 if ( !Hooks::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
854 $status->error( $result );
855 return $status;
858 if ( $result === false ) {
859 $status->merge( $upp->checkUserPassword( $this, $password ) );
860 return $status;
861 } elseif ( $result === true ) {
862 return $status;
863 } else {
864 $status->error( $result );
865 return $status; //the isValidPassword hook set a string $result and returned true
870 * Expire a user's password
871 * @since 1.23
872 * @param int $ts Optional timestamp to convert, default 0 for the current time
874 public function expirePassword( $ts = 0 ) {
875 $this->loadPasswords();
876 $timestamp = wfTimestamp( TS_MW, $ts );
877 $this->mPasswordExpires = $timestamp;
878 $this->saveSettings();
882 * Clear the password expiration for a user
883 * @since 1.23
884 * @param bool $load Ensure user object is loaded first
886 public function resetPasswordExpiration( $load = true ) {
887 global $wgPasswordExpirationDays;
888 if ( $load ) {
889 $this->load();
891 $newExpire = null;
892 if ( $wgPasswordExpirationDays ) {
893 $newExpire = wfTimestamp(
894 TS_MW,
895 time() + ( $wgPasswordExpirationDays * 24 * 3600 )
898 // Give extensions a chance to force an expiration
899 Hooks::run( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
900 $this->mPasswordExpires = $newExpire;
904 * Check if the user's password is expired.
905 * TODO: Put this and password length into a PasswordPolicy object
906 * @since 1.23
907 * @return string|bool The expiration type, or false if not expired
908 * hard: A password change is required to login
909 * soft: Allow login, but encourage password change
910 * false: Password is not expired
912 public function getPasswordExpired() {
913 global $wgPasswordExpireGrace;
914 $expired = false;
915 $now = wfTimestamp();
916 $expiration = $this->getPasswordExpireDate();
917 $expUnix = wfTimestamp( TS_UNIX, $expiration );
918 if ( $expiration !== null && $expUnix < $now ) {
919 $expired = ( $expUnix + $wgPasswordExpireGrace < $now ) ? 'hard' : 'soft';
921 return $expired;
925 * Get this user's password expiration date. Since this may be using
926 * the cached User object, we assume that whatever mechanism is setting
927 * the expiration date is also expiring the User cache.
928 * @since 1.23
929 * @return string|bool The datestamp of the expiration, or null if not set
931 public function getPasswordExpireDate() {
932 $this->load();
933 return $this->mPasswordExpires;
937 * Given unvalidated user input, return a canonical username, or false if
938 * the username is invalid.
939 * @param string $name User input
940 * @param string|bool $validate Type of validation to use:
941 * - false No validation
942 * - 'valid' Valid for batch processes
943 * - 'usable' Valid for batch processes and login
944 * - 'creatable' Valid for batch processes, login and account creation
946 * @throws MWException
947 * @return bool|string
949 public static function getCanonicalName( $name, $validate = 'valid' ) {
950 // Force usernames to capital
951 global $wgContLang;
952 $name = $wgContLang->ucfirst( $name );
954 # Reject names containing '#'; these will be cleaned up
955 # with title normalisation, but then it's too late to
956 # check elsewhere
957 if ( strpos( $name, '#' ) !== false ) {
958 return false;
961 // Clean up name according to title rules,
962 // but only when validation is requested (bug 12654)
963 $t = ( $validate !== false ) ?
964 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
965 // Check for invalid titles
966 if ( is_null( $t ) ) {
967 return false;
970 // Reject various classes of invalid names
971 global $wgAuth;
972 $name = $wgAuth->getCanonicalName( $t->getText() );
974 switch ( $validate ) {
975 case false:
976 break;
977 case 'valid':
978 if ( !User::isValidUserName( $name ) ) {
979 $name = false;
981 break;
982 case 'usable':
983 if ( !User::isUsableName( $name ) ) {
984 $name = false;
986 break;
987 case 'creatable':
988 if ( !User::isCreatableName( $name ) ) {
989 $name = false;
991 break;
992 default:
993 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
995 return $name;
999 * Count the number of edits of a user
1001 * @param int $uid User ID to check
1002 * @return int The user's edit count
1004 * @deprecated since 1.21 in favour of User::getEditCount
1006 public static function edits( $uid ) {
1007 wfDeprecated( __METHOD__, '1.21' );
1008 $user = self::newFromId( $uid );
1009 return $user->getEditCount();
1013 * Return a random password.
1015 * @return string New random password
1017 public static function randomPassword() {
1018 global $wgMinimalPasswordLength;
1019 // Decide the final password length based on our min password length,
1020 // stopping at a minimum of 10 chars.
1021 $length = max( 10, $wgMinimalPasswordLength );
1022 // Multiply by 1.25 to get the number of hex characters we need
1023 $length = $length * 1.25;
1024 // Generate random hex chars
1025 $hex = MWCryptRand::generateHex( $length );
1026 // Convert from base 16 to base 32 to get a proper password like string
1027 return wfBaseConvert( $hex, 16, 32 );
1031 * Set cached properties to default.
1033 * @note This no longer clears uncached lazy-initialised properties;
1034 * the constructor does that instead.
1036 * @param string|bool $name
1038 public function loadDefaults( $name = false ) {
1040 $passwordFactory = self::getPasswordFactory();
1042 $this->mId = 0;
1043 $this->mName = $name;
1044 $this->mRealName = '';
1045 $this->mPassword = $passwordFactory->newFromCiphertext( null );
1046 $this->mNewpassword = $passwordFactory->newFromCiphertext( null );
1047 $this->mNewpassTime = null;
1048 $this->mEmail = '';
1049 $this->mOptionOverrides = null;
1050 $this->mOptionsLoaded = false;
1052 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1053 if ( $loggedOut !== null ) {
1054 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
1055 } else {
1056 $this->mTouched = '1'; # Allow any pages to be cached
1059 $this->mToken = null; // Don't run cryptographic functions till we need a token
1060 $this->mEmailAuthenticated = null;
1061 $this->mEmailToken = '';
1062 $this->mEmailTokenExpires = null;
1063 $this->mPasswordExpires = null;
1064 $this->resetPasswordExpiration( false );
1065 $this->mRegistration = wfTimestamp( TS_MW );
1066 $this->mGroups = array();
1068 Hooks::run( 'UserLoadDefaults', array( $this, $name ) );
1072 * Return whether an item has been loaded.
1074 * @param string $item Item to check. Current possibilities:
1075 * - id
1076 * - name
1077 * - realname
1078 * @param string $all 'all' to check if the whole object has been loaded
1079 * or any other string to check if only the item is available (e.g.
1080 * for optimisation)
1081 * @return bool
1083 public function isItemLoaded( $item, $all = 'all' ) {
1084 return ( $this->mLoadedItems === true && $all === 'all' ) ||
1085 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1089 * Set that an item has been loaded
1091 * @param string $item
1093 protected function setItemLoaded( $item ) {
1094 if ( is_array( $this->mLoadedItems ) ) {
1095 $this->mLoadedItems[$item] = true;
1100 * Load user data from the session or login cookie.
1102 * @return bool True if the user is logged in, false otherwise.
1104 private function loadFromSession() {
1105 $result = null;
1106 Hooks::run( 'UserLoadFromSession', array( $this, &$result ) );
1107 if ( $result !== null ) {
1108 return $result;
1111 $request = $this->getRequest();
1113 $cookieId = $request->getCookie( 'UserID' );
1114 $sessId = $request->getSessionData( 'wsUserID' );
1116 if ( $cookieId !== null ) {
1117 $sId = intval( $cookieId );
1118 if ( $sessId !== null && $cookieId != $sessId ) {
1119 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1120 cookie user ID ($sId) don't match!" );
1121 return false;
1123 $request->setSessionData( 'wsUserID', $sId );
1124 } elseif ( $sessId !== null && $sessId != 0 ) {
1125 $sId = $sessId;
1126 } else {
1127 return false;
1130 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1131 $sName = $request->getSessionData( 'wsUserName' );
1132 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1133 $sName = $request->getCookie( 'UserName' );
1134 $request->setSessionData( 'wsUserName', $sName );
1135 } else {
1136 return false;
1139 $proposedUser = User::newFromId( $sId );
1140 if ( !$proposedUser->isLoggedIn() ) {
1141 // Not a valid ID
1142 return false;
1145 global $wgBlockDisablesLogin;
1146 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1147 // User blocked and we've disabled blocked user logins
1148 return false;
1151 if ( $request->getSessionData( 'wsToken' ) ) {
1152 $passwordCorrect =
1153 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1154 $from = 'session';
1155 } elseif ( $request->getCookie( 'Token' ) ) {
1156 # Get the token from DB/cache and clean it up to remove garbage padding.
1157 # This deals with historical problems with bugs and the default column value.
1158 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1159 // Make comparison in constant time (bug 61346)
1160 $passwordCorrect = strlen( $token )
1161 && hash_equals( $token, $request->getCookie( 'Token' ) );
1162 $from = 'cookie';
1163 } else {
1164 // No session or persistent login cookie
1165 return false;
1168 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1169 $this->loadFromUserObject( $proposedUser );
1170 $request->setSessionData( 'wsToken', $this->mToken );
1171 wfDebug( "User: logged in from $from\n" );
1172 return true;
1173 } else {
1174 // Invalid credentials
1175 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1176 return false;
1181 * Load user and user_group data from the database.
1182 * $this->mId must be set, this is how the user is identified.
1184 * @param integer $flags User::READ_* constant bitfield
1185 * @return bool True if the user exists, false if the user is anonymous
1187 public function loadFromDatabase( $flags = self::READ_LATEST ) {
1188 // Paranoia
1189 $this->mId = intval( $this->mId );
1191 // Anonymous user
1192 if ( !$this->mId ) {
1193 $this->loadDefaults();
1194 return false;
1197 $db = ( $flags & self::READ_LATEST )
1198 ? wfGetDB( DB_MASTER )
1199 : wfGetDB( DB_SLAVE );
1201 $s = $db->selectRow(
1202 'user',
1203 self::selectFields(),
1204 array( 'user_id' => $this->mId ),
1205 __METHOD__,
1206 ( ( $flags & self::READ_LOCKING ) == self::READ_LOCKING )
1207 ? array( 'LOCK IN SHARE MODE' )
1208 : array()
1211 $this->queryFlagsUsed = $flags;
1212 Hooks::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1214 if ( $s !== false ) {
1215 // Initialise user table data
1216 $this->loadFromRow( $s );
1217 $this->mGroups = null; // deferred
1218 $this->getEditCount(); // revalidation for nulls
1219 return true;
1220 } else {
1221 // Invalid user_id
1222 $this->mId = 0;
1223 $this->loadDefaults();
1224 return false;
1229 * Initialize this object from a row from the user table.
1231 * @param stdClass $row Row from the user table to load.
1232 * @param array $data Further user data to load into the object
1234 * user_groups Array with groups out of the user_groups table
1235 * user_properties Array with properties out of the user_properties table
1237 protected function loadFromRow( $row, $data = null ) {
1238 $all = true;
1239 $passwordFactory = self::getPasswordFactory();
1241 $this->mGroups = null; // deferred
1243 if ( isset( $row->user_name ) ) {
1244 $this->mName = $row->user_name;
1245 $this->mFrom = 'name';
1246 $this->setItemLoaded( 'name' );
1247 } else {
1248 $all = false;
1251 if ( isset( $row->user_real_name ) ) {
1252 $this->mRealName = $row->user_real_name;
1253 $this->setItemLoaded( 'realname' );
1254 } else {
1255 $all = false;
1258 if ( isset( $row->user_id ) ) {
1259 $this->mId = intval( $row->user_id );
1260 $this->mFrom = 'id';
1261 $this->setItemLoaded( 'id' );
1262 } else {
1263 $all = false;
1266 if ( isset( $row->user_id ) && isset( $row->user_name ) ) {
1267 self::$idCacheByName[$row->user_name] = $row->user_id;
1270 if ( isset( $row->user_editcount ) ) {
1271 $this->mEditCount = $row->user_editcount;
1272 } else {
1273 $all = false;
1276 if ( isset( $row->user_password ) ) {
1277 // Check for *really* old password hashes that don't even have a type
1278 // The old hash format was just an md5 hex hash, with no type information
1279 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) {
1280 $row->user_password = ":A:{$this->mId}:{$row->user_password}";
1283 try {
1284 $this->mPassword = $passwordFactory->newFromCiphertext( $row->user_password );
1285 } catch ( PasswordError $e ) {
1286 wfDebug( 'Invalid password hash found in database.' );
1287 $this->mPassword = $passwordFactory->newFromCiphertext( null );
1290 try {
1291 $this->mNewpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword );
1292 } catch ( PasswordError $e ) {
1293 wfDebug( 'Invalid password hash found in database.' );
1294 $this->mNewpassword = $passwordFactory->newFromCiphertext( null );
1297 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
1298 $this->mPasswordExpires = wfTimestampOrNull( TS_MW, $row->user_password_expires );
1301 if ( isset( $row->user_email ) ) {
1302 $this->mEmail = $row->user_email;
1303 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1304 $this->mToken = $row->user_token;
1305 if ( $this->mToken == '' ) {
1306 $this->mToken = null;
1308 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1309 $this->mEmailToken = $row->user_email_token;
1310 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1311 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1312 } else {
1313 $all = false;
1316 if ( $all ) {
1317 $this->mLoadedItems = true;
1320 if ( is_array( $data ) ) {
1321 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1322 $this->mGroups = $data['user_groups'];
1324 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1325 $this->loadOptions( $data['user_properties'] );
1331 * Load the data for this user object from another user object.
1333 * @param User $user
1335 protected function loadFromUserObject( $user ) {
1336 $user->load();
1337 $user->loadGroups();
1338 $user->loadOptions();
1339 foreach ( self::$mCacheVars as $var ) {
1340 $this->$var = $user->$var;
1345 * Load the groups from the database if they aren't already loaded.
1347 private function loadGroups() {
1348 if ( is_null( $this->mGroups ) ) {
1349 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
1350 ? wfGetDB( DB_MASTER )
1351 : wfGetDB( DB_SLAVE );
1352 $res = $db->select( 'user_groups',
1353 array( 'ug_group' ),
1354 array( 'ug_user' => $this->mId ),
1355 __METHOD__ );
1356 $this->mGroups = array();
1357 foreach ( $res as $row ) {
1358 $this->mGroups[] = $row->ug_group;
1364 * Load the user's password hashes from the database
1366 * This is usually called in a scenario where the actual User object was
1367 * loaded from the cache, and then password comparison needs to be performed.
1368 * Password hashes are not stored in memcached.
1370 * @since 1.24
1372 private function loadPasswords() {
1373 if ( $this->getId() !== 0 &&
1374 ( $this->mPassword === null || $this->mNewpassword === null )
1376 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
1377 ? wfGetDB( DB_MASTER )
1378 : wfGetDB( DB_SLAVE );
1380 $this->loadFromRow( $db->selectRow(
1381 'user',
1382 array( 'user_password', 'user_newpassword',
1383 'user_newpass_time', 'user_password_expires' ),
1384 array( 'user_id' => $this->getId() ),
1385 __METHOD__
1386 ) );
1391 * Add the user to the group if he/she meets given criteria.
1393 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1394 * possible to remove manually via Special:UserRights. In such case it
1395 * will not be re-added automatically. The user will also not lose the
1396 * group if they no longer meet the criteria.
1398 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1400 * @return array Array of groups the user has been promoted to.
1402 * @see $wgAutopromoteOnce
1404 public function addAutopromoteOnceGroups( $event ) {
1405 global $wgAutopromoteOnceLogInRC, $wgAuth;
1407 if ( wfReadOnly() || !$this->getId() ) {
1408 return array();
1411 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1412 if ( !count( $toPromote ) ) {
1413 return array();
1416 if ( !$this->checkAndSetTouched() ) {
1417 return array(); // raced out (bug T48834)
1420 $oldGroups = $this->getGroups(); // previous groups
1421 foreach ( $toPromote as $group ) {
1422 $this->addGroup( $group );
1425 // update groups in external authentication database
1426 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1428 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1430 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1431 $logEntry->setPerformer( $this );
1432 $logEntry->setTarget( $this->getUserPage() );
1433 $logEntry->setParameters( array(
1434 '4::oldgroups' => $oldGroups,
1435 '5::newgroups' => $newGroups,
1436 ) );
1437 $logid = $logEntry->insert();
1438 if ( $wgAutopromoteOnceLogInRC ) {
1439 $logEntry->publish( $logid );
1442 return $toPromote;
1446 * Bump user_touched if it didn't change since this object was loaded
1448 * On success, the mTouched field is updated.
1449 * The user serialization cache is always cleared.
1451 * @return bool Whether user_touched was actually updated
1452 * @since 1.26
1454 protected function checkAndSetTouched() {
1455 $this->load();
1457 if ( !$this->mId ) {
1458 return false; // anon
1461 // Get a new user_touched that is higher than the old one
1462 $oldTouched = $this->mTouched;
1463 $newTouched = $this->newTouchedTimestamp();
1465 $dbw = wfGetDB( DB_MASTER );
1466 $dbw->update( 'user',
1467 array( 'user_touched' => $dbw->timestamp( $newTouched ) ),
1468 array(
1469 'user_id' => $this->mId,
1470 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1472 __METHOD__
1474 $success = ( $dbw->affectedRows() > 0 );
1476 if ( $success ) {
1477 $this->mTouched = $newTouched;
1480 // Clears on failure too since that is desired if the cache is stale
1481 $this->clearSharedCache();
1483 return $success;
1487 * Clear various cached data stored in this object. The cache of the user table
1488 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1490 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1491 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1493 public function clearInstanceCache( $reloadFrom = false ) {
1494 $this->mNewtalk = -1;
1495 $this->mDatePreference = null;
1496 $this->mBlockedby = -1; # Unset
1497 $this->mHash = false;
1498 $this->mRights = null;
1499 $this->mEffectiveGroups = null;
1500 $this->mImplicitGroups = null;
1501 $this->mGroups = null;
1502 $this->mOptions = null;
1503 $this->mOptionsLoaded = false;
1504 $this->mEditCount = null;
1506 if ( $reloadFrom ) {
1507 $this->mLoadedItems = array();
1508 $this->mFrom = $reloadFrom;
1513 * Combine the language default options with any site-specific options
1514 * and add the default language variants.
1516 * @return array Array of String options
1518 public static function getDefaultOptions() {
1519 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1521 static $defOpt = null;
1522 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1523 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1524 // mid-request and see that change reflected in the return value of this function.
1525 // Which is insane and would never happen during normal MW operation
1526 return $defOpt;
1529 $defOpt = $wgDefaultUserOptions;
1530 // Default language setting
1531 $defOpt['language'] = $wgContLang->getCode();
1532 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1533 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1535 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1536 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1538 $defOpt['skin'] = Skin::normalizeKey( $wgDefaultSkin );
1540 Hooks::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1542 return $defOpt;
1546 * Get a given default option value.
1548 * @param string $opt Name of option to retrieve
1549 * @return string Default option value
1551 public static function getDefaultOption( $opt ) {
1552 $defOpts = self::getDefaultOptions();
1553 if ( isset( $defOpts[$opt] ) ) {
1554 return $defOpts[$opt];
1555 } else {
1556 return null;
1561 * Get blocking information
1562 * @param bool $bFromSlave Whether to check the slave database first.
1563 * To improve performance, non-critical checks are done against slaves.
1564 * Check when actually saving should be done against master.
1566 private function getBlockedStatus( $bFromSlave = true ) {
1567 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1569 if ( -1 != $this->mBlockedby ) {
1570 return;
1573 wfDebug( __METHOD__ . ": checking...\n" );
1575 // Initialize data...
1576 // Otherwise something ends up stomping on $this->mBlockedby when
1577 // things get lazy-loaded later, causing false positive block hits
1578 // due to -1 !== 0. Probably session-related... Nothing should be
1579 // overwriting mBlockedby, surely?
1580 $this->load();
1582 # We only need to worry about passing the IP address to the Block generator if the
1583 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1584 # know which IP address they're actually coming from
1585 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1586 $ip = $this->getRequest()->getIP();
1587 } else {
1588 $ip = null;
1591 // User/IP blocking
1592 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1594 // Proxy blocking
1595 if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1596 && !in_array( $ip, $wgProxyWhitelist )
1598 // Local list
1599 if ( self::isLocallyBlockedProxy( $ip ) ) {
1600 $block = new Block;
1601 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1602 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1603 $block->setTarget( $ip );
1604 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1605 $block = new Block;
1606 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1607 $block->mReason = wfMessage( 'sorbsreason' )->text();
1608 $block->setTarget( $ip );
1612 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1613 if ( !$block instanceof Block
1614 && $wgApplyIpBlocksToXff
1615 && $ip !== null
1616 && !$this->isAllowed( 'proxyunbannable' )
1617 && !in_array( $ip, $wgProxyWhitelist )
1619 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1620 $xff = array_map( 'trim', explode( ',', $xff ) );
1621 $xff = array_diff( $xff, array( $ip ) );
1622 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1623 $block = Block::chooseBlock( $xffblocks, $xff );
1624 if ( $block instanceof Block ) {
1625 # Mangle the reason to alert the user that the block
1626 # originated from matching the X-Forwarded-For header.
1627 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1631 if ( $block instanceof Block ) {
1632 wfDebug( __METHOD__ . ": Found block.\n" );
1633 $this->mBlock = $block;
1634 $this->mBlockedby = $block->getByName();
1635 $this->mBlockreason = $block->mReason;
1636 $this->mHideName = $block->mHideName;
1637 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1638 } else {
1639 $this->mBlockedby = '';
1640 $this->mHideName = 0;
1641 $this->mAllowUsertalk = false;
1644 // Extensions
1645 Hooks::run( 'GetBlockedStatus', array( &$this ) );
1650 * Whether the given IP is in a DNS blacklist.
1652 * @param string $ip IP to check
1653 * @param bool $checkWhitelist Whether to check the whitelist first
1654 * @return bool True if blacklisted.
1656 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1657 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1659 if ( !$wgEnableDnsBlacklist ) {
1660 return false;
1663 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1664 return false;
1667 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1671 * Whether the given IP is in a given DNS blacklist.
1673 * @param string $ip IP to check
1674 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1675 * @return bool True if blacklisted.
1677 public function inDnsBlacklist( $ip, $bases ) {
1679 $found = false;
1680 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1681 if ( IP::isIPv4( $ip ) ) {
1682 // Reverse IP, bug 21255
1683 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1685 foreach ( (array)$bases as $base ) {
1686 // Make hostname
1687 // If we have an access key, use that too (ProjectHoneypot, etc.)
1688 if ( is_array( $base ) ) {
1689 if ( count( $base ) >= 2 ) {
1690 // Access key is 1, base URL is 0
1691 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1692 } else {
1693 $host = "$ipReversed.{$base[0]}";
1695 } else {
1696 $host = "$ipReversed.$base";
1699 // Send query
1700 $ipList = gethostbynamel( $host );
1702 if ( $ipList ) {
1703 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1704 $found = true;
1705 break;
1706 } else {
1707 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1712 return $found;
1716 * Check if an IP address is in the local proxy list
1718 * @param string $ip
1720 * @return bool
1722 public static function isLocallyBlockedProxy( $ip ) {
1723 global $wgProxyList;
1725 if ( !$wgProxyList ) {
1726 return false;
1729 if ( !is_array( $wgProxyList ) ) {
1730 // Load from the specified file
1731 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1734 if ( !is_array( $wgProxyList ) ) {
1735 $ret = false;
1736 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1737 $ret = true;
1738 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1739 // Old-style flipped proxy list
1740 $ret = true;
1741 } else {
1742 $ret = false;
1744 return $ret;
1748 * Is this user subject to rate limiting?
1750 * @return bool True if rate limited
1752 public function isPingLimitable() {
1753 global $wgRateLimitsExcludedIPs;
1754 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1755 // No other good way currently to disable rate limits
1756 // for specific IPs. :P
1757 // But this is a crappy hack and should die.
1758 return false;
1760 return !$this->isAllowed( 'noratelimit' );
1764 * Primitive rate limits: enforce maximum actions per time period
1765 * to put a brake on flooding.
1767 * The method generates both a generic profiling point and a per action one
1768 * (suffix being "-$action".
1770 * @note When using a shared cache like memcached, IP-address
1771 * last-hit counters will be shared across wikis.
1773 * @param string $action Action to enforce; 'edit' if unspecified
1774 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1775 * @return bool True if a rate limiter was tripped
1777 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1778 // Call the 'PingLimiter' hook
1779 $result = false;
1780 if ( !Hooks::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1781 return $result;
1784 global $wgRateLimits;
1785 if ( !isset( $wgRateLimits[$action] ) ) {
1786 return false;
1789 // Some groups shouldn't trigger the ping limiter, ever
1790 if ( !$this->isPingLimitable() ) {
1791 return false;
1794 global $wgMemc;
1796 $limits = $wgRateLimits[$action];
1797 $keys = array();
1798 $id = $this->getId();
1799 $userLimit = false;
1801 if ( isset( $limits['anon'] ) && $id == 0 ) {
1802 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1805 if ( isset( $limits['user'] ) && $id != 0 ) {
1806 $userLimit = $limits['user'];
1808 if ( $this->isNewbie() ) {
1809 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1810 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1812 if ( isset( $limits['ip'] ) ) {
1813 $ip = $this->getRequest()->getIP();
1814 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1816 if ( isset( $limits['subnet'] ) ) {
1817 $ip = $this->getRequest()->getIP();
1818 $matches = array();
1819 $subnet = false;
1820 if ( IP::isIPv6( $ip ) ) {
1821 $parts = IP::parseRange( "$ip/64" );
1822 $subnet = $parts[0];
1823 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1824 // IPv4
1825 $subnet = $matches[1];
1827 if ( $subnet !== false ) {
1828 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1832 // Check for group-specific permissions
1833 // If more than one group applies, use the group with the highest limit
1834 foreach ( $this->getGroups() as $group ) {
1835 if ( isset( $limits[$group] ) ) {
1836 if ( $userLimit === false
1837 || $limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1839 $userLimit = $limits[$group];
1843 // Set the user limit key
1844 if ( $userLimit !== false ) {
1845 list( $max, $period ) = $userLimit;
1846 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1847 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1850 $triggered = false;
1851 foreach ( $keys as $key => $limit ) {
1852 list( $max, $period ) = $limit;
1853 $summary = "(limit $max in {$period}s)";
1854 $count = $wgMemc->get( $key );
1855 // Already pinged?
1856 if ( $count ) {
1857 if ( $count >= $max ) {
1858 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1859 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1860 $triggered = true;
1861 } else {
1862 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1864 } else {
1865 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1866 if ( $incrBy > 0 ) {
1867 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1870 if ( $incrBy > 0 ) {
1871 $wgMemc->incr( $key, $incrBy );
1875 return $triggered;
1879 * Check if user is blocked
1881 * @param bool $bFromSlave Whether to check the slave database instead of
1882 * the master. Hacked from false due to horrible probs on site.
1883 * @return bool True if blocked, false otherwise
1885 public function isBlocked( $bFromSlave = true ) {
1886 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1890 * Get the block affecting the user, or null if the user is not blocked
1892 * @param bool $bFromSlave Whether to check the slave database instead of the master
1893 * @return Block|null
1895 public function getBlock( $bFromSlave = true ) {
1896 $this->getBlockedStatus( $bFromSlave );
1897 return $this->mBlock instanceof Block ? $this->mBlock : null;
1901 * Check if user is blocked from editing a particular article
1903 * @param Title $title Title to check
1904 * @param bool $bFromSlave Whether to check the slave database instead of the master
1905 * @return bool
1907 public function isBlockedFrom( $title, $bFromSlave = false ) {
1908 global $wgBlockAllowsUTEdit;
1910 $blocked = $this->isBlocked( $bFromSlave );
1911 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1912 // If a user's name is suppressed, they cannot make edits anywhere
1913 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
1914 && $title->getNamespace() == NS_USER_TALK ) {
1915 $blocked = false;
1916 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1919 Hooks::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1921 return $blocked;
1925 * If user is blocked, return the name of the user who placed the block
1926 * @return string Name of blocker
1928 public function blockedBy() {
1929 $this->getBlockedStatus();
1930 return $this->mBlockedby;
1934 * If user is blocked, return the specified reason for the block
1935 * @return string Blocking reason
1937 public function blockedFor() {
1938 $this->getBlockedStatus();
1939 return $this->mBlockreason;
1943 * If user is blocked, return the ID for the block
1944 * @return int Block ID
1946 public function getBlockId() {
1947 $this->getBlockedStatus();
1948 return ( $this->mBlock ? $this->mBlock->getId() : false );
1952 * Check if user is blocked on all wikis.
1953 * Do not use for actual edit permission checks!
1954 * This is intended for quick UI checks.
1956 * @param string $ip IP address, uses current client if none given
1957 * @return bool True if blocked, false otherwise
1959 public function isBlockedGlobally( $ip = '' ) {
1960 if ( $this->mBlockedGlobally !== null ) {
1961 return $this->mBlockedGlobally;
1963 // User is already an IP?
1964 if ( IP::isIPAddress( $this->getName() ) ) {
1965 $ip = $this->getName();
1966 } elseif ( !$ip ) {
1967 $ip = $this->getRequest()->getIP();
1969 $blocked = false;
1970 Hooks::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1971 $this->mBlockedGlobally = (bool)$blocked;
1972 return $this->mBlockedGlobally;
1976 * Check if user account is locked
1978 * @return bool True if locked, false otherwise
1980 public function isLocked() {
1981 if ( $this->mLocked !== null ) {
1982 return $this->mLocked;
1984 global $wgAuth;
1985 $authUser = $wgAuth->getUserInstance( $this );
1986 $this->mLocked = (bool)$authUser->isLocked();
1987 return $this->mLocked;
1991 * Check if user account is hidden
1993 * @return bool True if hidden, false otherwise
1995 public function isHidden() {
1996 if ( $this->mHideName !== null ) {
1997 return $this->mHideName;
1999 $this->getBlockedStatus();
2000 if ( !$this->mHideName ) {
2001 global $wgAuth;
2002 $authUser = $wgAuth->getUserInstance( $this );
2003 $this->mHideName = (bool)$authUser->isHidden();
2005 return $this->mHideName;
2009 * Get the user's ID.
2010 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2012 public function getId() {
2013 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
2014 // Special case, we know the user is anonymous
2015 return 0;
2016 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2017 // Don't load if this was initialized from an ID
2018 $this->load();
2020 return $this->mId;
2024 * Set the user and reload all fields according to a given ID
2025 * @param int $v User ID to reload
2027 public function setId( $v ) {
2028 $this->mId = $v;
2029 $this->clearInstanceCache( 'id' );
2033 * Get the user name, or the IP of an anonymous user
2034 * @return string User's name or IP address
2036 public function getName() {
2037 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2038 // Special case optimisation
2039 return $this->mName;
2040 } else {
2041 $this->load();
2042 if ( $this->mName === false ) {
2043 // Clean up IPs
2044 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
2046 return $this->mName;
2051 * Set the user name.
2053 * This does not reload fields from the database according to the given
2054 * name. Rather, it is used to create a temporary "nonexistent user" for
2055 * later addition to the database. It can also be used to set the IP
2056 * address for an anonymous user to something other than the current
2057 * remote IP.
2059 * @note User::newFromName() has roughly the same function, when the named user
2060 * does not exist.
2061 * @param string $str New user name to set
2063 public function setName( $str ) {
2064 $this->load();
2065 $this->mName = $str;
2069 * Get the user's name escaped by underscores.
2070 * @return string Username escaped by underscores.
2072 public function getTitleKey() {
2073 return str_replace( ' ', '_', $this->getName() );
2077 * Check if the user has new messages.
2078 * @return bool True if the user has new messages
2080 public function getNewtalk() {
2081 $this->load();
2083 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2084 if ( $this->mNewtalk === -1 ) {
2085 $this->mNewtalk = false; # reset talk page status
2087 // Check memcached separately for anons, who have no
2088 // entire User object stored in there.
2089 if ( !$this->mId ) {
2090 global $wgDisableAnonTalk;
2091 if ( $wgDisableAnonTalk ) {
2092 // Anon newtalk disabled by configuration.
2093 $this->mNewtalk = false;
2094 } else {
2095 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName() );
2097 } else {
2098 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
2102 return (bool)$this->mNewtalk;
2106 * Return the data needed to construct links for new talk page message
2107 * alerts. If there are new messages, this will return an associative array
2108 * with the following data:
2109 * wiki: The database name of the wiki
2110 * link: Root-relative link to the user's talk page
2111 * rev: The last talk page revision that the user has seen or null. This
2112 * is useful for building diff links.
2113 * If there are no new messages, it returns an empty array.
2114 * @note This function was designed to accomodate multiple talk pages, but
2115 * currently only returns a single link and revision.
2116 * @return array
2118 public function getNewMessageLinks() {
2119 $talks = array();
2120 if ( !Hooks::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2121 return $talks;
2122 } elseif ( !$this->getNewtalk() ) {
2123 return array();
2125 $utp = $this->getTalkPage();
2126 $dbr = wfGetDB( DB_SLAVE );
2127 // Get the "last viewed rev" timestamp from the oldest message notification
2128 $timestamp = $dbr->selectField( 'user_newtalk',
2129 'MIN(user_last_timestamp)',
2130 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2131 __METHOD__ );
2132 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2133 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2137 * Get the revision ID for the last talk page revision viewed by the talk
2138 * page owner.
2139 * @return int|null Revision ID or null
2141 public function getNewMessageRevisionId() {
2142 $newMessageRevisionId = null;
2143 $newMessageLinks = $this->getNewMessageLinks();
2144 if ( $newMessageLinks ) {
2145 // Note: getNewMessageLinks() never returns more than a single link
2146 // and it is always for the same wiki, but we double-check here in
2147 // case that changes some time in the future.
2148 if ( count( $newMessageLinks ) === 1
2149 && $newMessageLinks[0]['wiki'] === wfWikiID()
2150 && $newMessageLinks[0]['rev']
2152 $newMessageRevision = $newMessageLinks[0]['rev'];
2153 $newMessageRevisionId = $newMessageRevision->getId();
2156 return $newMessageRevisionId;
2160 * Internal uncached check for new messages
2162 * @see getNewtalk()
2163 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2164 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2165 * @return bool True if the user has new messages
2167 protected function checkNewtalk( $field, $id ) {
2168 $dbr = wfGetDB( DB_SLAVE );
2170 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__ );
2172 return $ok !== false;
2176 * Add or update the new messages flag
2177 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2178 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2179 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2180 * @return bool True if successful, false otherwise
2182 protected function updateNewtalk( $field, $id, $curRev = null ) {
2183 // Get timestamp of the talk page revision prior to the current one
2184 $prevRev = $curRev ? $curRev->getPrevious() : false;
2185 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2186 // Mark the user as having new messages since this revision
2187 $dbw = wfGetDB( DB_MASTER );
2188 $dbw->insert( 'user_newtalk',
2189 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2190 __METHOD__,
2191 'IGNORE' );
2192 if ( $dbw->affectedRows() ) {
2193 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2194 return true;
2195 } else {
2196 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2197 return false;
2202 * Clear the new messages flag for the given user
2203 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2204 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2205 * @return bool True if successful, false otherwise
2207 protected function deleteNewtalk( $field, $id ) {
2208 $dbw = wfGetDB( DB_MASTER );
2209 $dbw->delete( 'user_newtalk',
2210 array( $field => $id ),
2211 __METHOD__ );
2212 if ( $dbw->affectedRows() ) {
2213 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2214 return true;
2215 } else {
2216 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2217 return false;
2222 * Update the 'You have new messages!' status.
2223 * @param bool $val Whether the user has new messages
2224 * @param Revision $curRev New, as yet unseen revision of the user talk
2225 * page. Ignored if null or !$val.
2227 public function setNewtalk( $val, $curRev = null ) {
2228 if ( wfReadOnly() ) {
2229 return;
2232 $this->load();
2233 $this->mNewtalk = $val;
2235 if ( $this->isAnon() ) {
2236 $field = 'user_ip';
2237 $id = $this->getName();
2238 } else {
2239 $field = 'user_id';
2240 $id = $this->getId();
2243 if ( $val ) {
2244 $changed = $this->updateNewtalk( $field, $id, $curRev );
2245 } else {
2246 $changed = $this->deleteNewtalk( $field, $id );
2249 if ( $changed ) {
2250 $this->invalidateCache();
2255 * Generate a current or new-future timestamp to be stored in the
2256 * user_touched field when we update things.
2257 * @return string Timestamp in TS_MW format
2259 private function newTouchedTimestamp() {
2260 global $wgClockSkewFudge;
2262 $time = wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2263 if ( $this->mTouched && $time <= $this->mTouched ) {
2264 $time = wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $this->mTouched ) + 1 );
2267 return $time;
2271 * Clear user data from memcached.
2272 * Use after applying fun updates to the database; caller's
2273 * responsibility to update user_touched if appropriate.
2275 * Called implicitly from invalidateCache() and saveSettings().
2277 public function clearSharedCache() {
2278 $id = $this->getId();
2279 if ( $id ) {
2280 $key = wfMemcKey( 'user', 'id', $id );
2281 ObjectCache::getMainWANInstance()->delete( $key );
2286 * Immediately touch the user data cache for this account
2288 * Calls touch() and removes account data from memcached
2290 public function invalidateCache() {
2291 $this->touch();
2292 $this->clearSharedCache();
2296 * Update the "touched" timestamp for the user
2298 * This is useful on various login/logout events when making sure that
2299 * a browser or proxy that has multiple tenants does not suffer cache
2300 * pollution where the new user sees the old users content. The value
2301 * of getTouched() is checked when determining 304 vs 200 responses.
2302 * Unlike invalidateCache(), this preserves the User object cache and
2303 * avoids database writes.
2305 * @since 1.25
2307 public function touch() {
2308 $id = $this->getId();
2309 if ( $id ) {
2310 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2311 ObjectCache::getMainWANInstance()->touchCheckKey( $key );
2312 $this->mQuickTouched = null;
2317 * Validate the cache for this account.
2318 * @param string $timestamp A timestamp in TS_MW format
2319 * @return bool
2321 public function validateCache( $timestamp ) {
2322 return ( $timestamp >= $this->getTouched() );
2326 * Get the user touched timestamp
2327 * @return string TS_MW Timestamp
2329 public function getTouched() {
2330 $this->load();
2332 if ( $this->mId ) {
2333 if ( $this->mQuickTouched === null ) {
2334 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId );
2336 $timestamp = ObjectCache::getMainWANInstance()->getCheckKeyTime( $key );
2337 if ( $timestamp ) {
2338 $this->mQuickTouched = wfTimestamp( TS_MW, (int)$timestamp );
2339 } else {
2340 # Set the timestamp to get HTTP 304 cache hits
2341 $this->touch();
2345 return max( $this->mTouched, $this->mQuickTouched );
2348 return $this->mTouched;
2352 * Get the user_touched timestamp field (time of last DB updates)
2353 * @return string TS_MW Timestamp
2354 * @since 1.26
2356 public function getDBTouched() {
2357 $this->load();
2359 return $this->mTouched;
2363 * @return Password
2364 * @since 1.24
2366 public function getPassword() {
2367 $this->loadPasswords();
2369 return $this->mPassword;
2373 * @return Password
2374 * @since 1.24
2376 public function getTemporaryPassword() {
2377 $this->loadPasswords();
2379 return $this->mNewpassword;
2383 * Set the password and reset the random token.
2384 * Calls through to authentication plugin if necessary;
2385 * will have no effect if the auth plugin refuses to
2386 * pass the change through or if the legal password
2387 * checks fail.
2389 * As a special case, setting the password to null
2390 * wipes it, so the account cannot be logged in until
2391 * a new password is set, for instance via e-mail.
2393 * @param string $str New password to set
2394 * @throws PasswordError On failure
2396 * @return bool
2398 public function setPassword( $str ) {
2399 global $wgAuth;
2401 $this->loadPasswords();
2403 if ( $str !== null ) {
2404 if ( !$wgAuth->allowPasswordChange() ) {
2405 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2408 $status = $this->checkPasswordValidity( $str );
2409 if ( !$status->isGood() ) {
2410 throw new PasswordError( $status->getMessage()->text() );
2414 if ( !$wgAuth->setPassword( $this, $str ) ) {
2415 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2418 $this->setInternalPassword( $str );
2420 return true;
2424 * Set the password and reset the random token unconditionally.
2426 * @param string|null $str New password to set or null to set an invalid
2427 * password hash meaning that the user will not be able to log in
2428 * through the web interface.
2430 public function setInternalPassword( $str ) {
2431 $this->setToken();
2433 $passwordFactory = self::getPasswordFactory();
2434 $this->mPassword = $passwordFactory->newFromPlaintext( $str );
2436 $this->mNewpassword = $passwordFactory->newFromCiphertext( null );
2437 $this->mNewpassTime = null;
2441 * Get the user's current token.
2442 * @param bool $forceCreation Force the generation of a new token if the
2443 * user doesn't have one (default=true for backwards compatibility).
2444 * @return string Token
2446 public function getToken( $forceCreation = true ) {
2447 $this->load();
2448 if ( !$this->mToken && $forceCreation ) {
2449 $this->setToken();
2451 return $this->mToken;
2455 * Set the random token (used for persistent authentication)
2456 * Called from loadDefaults() among other places.
2458 * @param string|bool $token If specified, set the token to this value
2460 public function setToken( $token = false ) {
2461 $this->load();
2462 if ( !$token ) {
2463 $this->mToken = MWCryptRand::generateHex( self::TOKEN_LENGTH );
2464 } else {
2465 $this->mToken = $token;
2470 * Set the password for a password reminder or new account email
2472 * @param string $str New password to set or null to set an invalid
2473 * password hash meaning that the user will not be able to use it
2474 * @param bool $throttle If true, reset the throttle timestamp to the present
2476 public function setNewpassword( $str, $throttle = true ) {
2477 $this->loadPasswords();
2479 $this->mNewpassword = self::getPasswordFactory()->newFromPlaintext( $str );
2480 if ( $str === null ) {
2481 $this->mNewpassTime = null;
2482 } elseif ( $throttle ) {
2483 $this->mNewpassTime = wfTimestampNow();
2488 * Has password reminder email been sent within the last
2489 * $wgPasswordReminderResendTime hours?
2490 * @return bool
2492 public function isPasswordReminderThrottled() {
2493 global $wgPasswordReminderResendTime;
2494 $this->load();
2495 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
2496 return false;
2498 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
2499 return time() < $expiry;
2503 * Get the user's e-mail address
2504 * @return string User's email address
2506 public function getEmail() {
2507 $this->load();
2508 Hooks::run( 'UserGetEmail', array( $this, &$this->mEmail ) );
2509 return $this->mEmail;
2513 * Get the timestamp of the user's e-mail authentication
2514 * @return string TS_MW timestamp
2516 public function getEmailAuthenticationTimestamp() {
2517 $this->load();
2518 Hooks::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2519 return $this->mEmailAuthenticated;
2523 * Set the user's e-mail address
2524 * @param string $str New e-mail address
2526 public function setEmail( $str ) {
2527 $this->load();
2528 if ( $str == $this->mEmail ) {
2529 return;
2531 $this->invalidateEmail();
2532 $this->mEmail = $str;
2533 Hooks::run( 'UserSetEmail', array( $this, &$this->mEmail ) );
2537 * Set the user's e-mail address and a confirmation mail if needed.
2539 * @since 1.20
2540 * @param string $str New e-mail address
2541 * @return Status
2543 public function setEmailWithConfirmation( $str ) {
2544 global $wgEnableEmail, $wgEmailAuthentication;
2546 if ( !$wgEnableEmail ) {
2547 return Status::newFatal( 'emaildisabled' );
2550 $oldaddr = $this->getEmail();
2551 if ( $str === $oldaddr ) {
2552 return Status::newGood( true );
2555 $this->setEmail( $str );
2557 if ( $str !== '' && $wgEmailAuthentication ) {
2558 // Send a confirmation request to the new address if needed
2559 $type = $oldaddr != '' ? 'changed' : 'set';
2560 $result = $this->sendConfirmationMail( $type );
2561 if ( $result->isGood() ) {
2562 // Say to the caller that a confirmation mail has been sent
2563 $result->value = 'eauth';
2565 } else {
2566 $result = Status::newGood( true );
2569 return $result;
2573 * Get the user's real name
2574 * @return string User's real name
2576 public function getRealName() {
2577 if ( !$this->isItemLoaded( 'realname' ) ) {
2578 $this->load();
2581 return $this->mRealName;
2585 * Set the user's real name
2586 * @param string $str New real name
2588 public function setRealName( $str ) {
2589 $this->load();
2590 $this->mRealName = $str;
2594 * Get the user's current setting for a given option.
2596 * @param string $oname The option to check
2597 * @param string $defaultOverride A default value returned if the option does not exist
2598 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2599 * @return string User's current value for the option
2600 * @see getBoolOption()
2601 * @see getIntOption()
2603 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2604 global $wgHiddenPrefs;
2605 $this->loadOptions();
2607 # We want 'disabled' preferences to always behave as the default value for
2608 # users, even if they have set the option explicitly in their settings (ie they
2609 # set it, and then it was disabled removing their ability to change it). But
2610 # we don't want to erase the preferences in the database in case the preference
2611 # is re-enabled again. So don't touch $mOptions, just override the returned value
2612 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2613 return self::getDefaultOption( $oname );
2616 if ( array_key_exists( $oname, $this->mOptions ) ) {
2617 return $this->mOptions[$oname];
2618 } else {
2619 return $defaultOverride;
2624 * Get all user's options
2626 * @param int $flags Bitwise combination of:
2627 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2628 * to the default value. (Since 1.25)
2629 * @return array
2631 public function getOptions( $flags = 0 ) {
2632 global $wgHiddenPrefs;
2633 $this->loadOptions();
2634 $options = $this->mOptions;
2636 # We want 'disabled' preferences to always behave as the default value for
2637 # users, even if they have set the option explicitly in their settings (ie they
2638 # set it, and then it was disabled removing their ability to change it). But
2639 # we don't want to erase the preferences in the database in case the preference
2640 # is re-enabled again. So don't touch $mOptions, just override the returned value
2641 foreach ( $wgHiddenPrefs as $pref ) {
2642 $default = self::getDefaultOption( $pref );
2643 if ( $default !== null ) {
2644 $options[$pref] = $default;
2648 if ( $flags & self::GETOPTIONS_EXCLUDE_DEFAULTS ) {
2649 $options = array_diff_assoc( $options, self::getDefaultOptions() );
2652 return $options;
2656 * Get the user's current setting for a given option, as a boolean value.
2658 * @param string $oname The option to check
2659 * @return bool User's current value for the option
2660 * @see getOption()
2662 public function getBoolOption( $oname ) {
2663 return (bool)$this->getOption( $oname );
2667 * Get the user's current setting for a given option, as an integer value.
2669 * @param string $oname The option to check
2670 * @param int $defaultOverride A default value returned if the option does not exist
2671 * @return int User's current value for the option
2672 * @see getOption()
2674 public function getIntOption( $oname, $defaultOverride = 0 ) {
2675 $val = $this->getOption( $oname );
2676 if ( $val == '' ) {
2677 $val = $defaultOverride;
2679 return intval( $val );
2683 * Set the given option for a user.
2685 * You need to call saveSettings() to actually write to the database.
2687 * @param string $oname The option to set
2688 * @param mixed $val New value to set
2690 public function setOption( $oname, $val ) {
2691 $this->loadOptions();
2693 // Explicitly NULL values should refer to defaults
2694 if ( is_null( $val ) ) {
2695 $val = self::getDefaultOption( $oname );
2698 $this->mOptions[$oname] = $val;
2702 * Get a token stored in the preferences (like the watchlist one),
2703 * resetting it if it's empty (and saving changes).
2705 * @param string $oname The option name to retrieve the token from
2706 * @return string|bool User's current value for the option, or false if this option is disabled.
2707 * @see resetTokenFromOption()
2708 * @see getOption()
2710 public function getTokenFromOption( $oname ) {
2711 global $wgHiddenPrefs;
2712 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2713 return false;
2716 $token = $this->getOption( $oname );
2717 if ( !$token ) {
2718 $token = $this->resetTokenFromOption( $oname );
2719 if ( !wfReadOnly() ) {
2720 $this->saveSettings();
2723 return $token;
2727 * Reset a token stored in the preferences (like the watchlist one).
2728 * *Does not* save user's preferences (similarly to setOption()).
2730 * @param string $oname The option name to reset the token in
2731 * @return string|bool New token value, or false if this option is disabled.
2732 * @see getTokenFromOption()
2733 * @see setOption()
2735 public function resetTokenFromOption( $oname ) {
2736 global $wgHiddenPrefs;
2737 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2738 return false;
2741 $token = MWCryptRand::generateHex( 40 );
2742 $this->setOption( $oname, $token );
2743 return $token;
2747 * Return a list of the types of user options currently returned by
2748 * User::getOptionKinds().
2750 * Currently, the option kinds are:
2751 * - 'registered' - preferences which are registered in core MediaWiki or
2752 * by extensions using the UserGetDefaultOptions hook.
2753 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2754 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2755 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2756 * be used by user scripts.
2757 * - 'special' - "preferences" that are not accessible via User::getOptions
2758 * or User::setOptions.
2759 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2760 * These are usually legacy options, removed in newer versions.
2762 * The API (and possibly others) use this function to determine the possible
2763 * option types for validation purposes, so make sure to update this when a
2764 * new option kind is added.
2766 * @see User::getOptionKinds
2767 * @return array Option kinds
2769 public static function listOptionKinds() {
2770 return array(
2771 'registered',
2772 'registered-multiselect',
2773 'registered-checkmatrix',
2774 'userjs',
2775 'special',
2776 'unused'
2781 * Return an associative array mapping preferences keys to the kind of a preference they're
2782 * used for. Different kinds are handled differently when setting or reading preferences.
2784 * See User::listOptionKinds for the list of valid option types that can be provided.
2786 * @see User::listOptionKinds
2787 * @param IContextSource $context
2788 * @param array $options Assoc. array with options keys to check as keys.
2789 * Defaults to $this->mOptions.
2790 * @return array The key => kind mapping data
2792 public function getOptionKinds( IContextSource $context, $options = null ) {
2793 $this->loadOptions();
2794 if ( $options === null ) {
2795 $options = $this->mOptions;
2798 $prefs = Preferences::getPreferences( $this, $context );
2799 $mapping = array();
2801 // Pull out the "special" options, so they don't get converted as
2802 // multiselect or checkmatrix.
2803 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
2804 foreach ( $specialOptions as $name => $value ) {
2805 unset( $prefs[$name] );
2808 // Multiselect and checkmatrix options are stored in the database with
2809 // one key per option, each having a boolean value. Extract those keys.
2810 $multiselectOptions = array();
2811 foreach ( $prefs as $name => $info ) {
2812 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2813 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2814 $opts = HTMLFormField::flattenOptions( $info['options'] );
2815 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2817 foreach ( $opts as $value ) {
2818 $multiselectOptions["$prefix$value"] = true;
2821 unset( $prefs[$name] );
2824 $checkmatrixOptions = array();
2825 foreach ( $prefs as $name => $info ) {
2826 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2827 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2828 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2829 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2830 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2832 foreach ( $columns as $column ) {
2833 foreach ( $rows as $row ) {
2834 $checkmatrixOptions["$prefix$column-$row"] = true;
2838 unset( $prefs[$name] );
2842 // $value is ignored
2843 foreach ( $options as $key => $value ) {
2844 if ( isset( $prefs[$key] ) ) {
2845 $mapping[$key] = 'registered';
2846 } elseif ( isset( $multiselectOptions[$key] ) ) {
2847 $mapping[$key] = 'registered-multiselect';
2848 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2849 $mapping[$key] = 'registered-checkmatrix';
2850 } elseif ( isset( $specialOptions[$key] ) ) {
2851 $mapping[$key] = 'special';
2852 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2853 $mapping[$key] = 'userjs';
2854 } else {
2855 $mapping[$key] = 'unused';
2859 return $mapping;
2863 * Reset certain (or all) options to the site defaults
2865 * The optional parameter determines which kinds of preferences will be reset.
2866 * Supported values are everything that can be reported by getOptionKinds()
2867 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2869 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2870 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2871 * for backwards-compatibility.
2872 * @param IContextSource|null $context Context source used when $resetKinds
2873 * does not contain 'all', passed to getOptionKinds().
2874 * Defaults to RequestContext::getMain() when null.
2876 public function resetOptions(
2877 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2878 IContextSource $context = null
2880 $this->load();
2881 $defaultOptions = self::getDefaultOptions();
2883 if ( !is_array( $resetKinds ) ) {
2884 $resetKinds = array( $resetKinds );
2887 if ( in_array( 'all', $resetKinds ) ) {
2888 $newOptions = $defaultOptions;
2889 } else {
2890 if ( $context === null ) {
2891 $context = RequestContext::getMain();
2894 $optionKinds = $this->getOptionKinds( $context );
2895 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2896 $newOptions = array();
2898 // Use default values for the options that should be deleted, and
2899 // copy old values for the ones that shouldn't.
2900 foreach ( $this->mOptions as $key => $value ) {
2901 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2902 if ( array_key_exists( $key, $defaultOptions ) ) {
2903 $newOptions[$key] = $defaultOptions[$key];
2905 } else {
2906 $newOptions[$key] = $value;
2911 Hooks::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions, $resetKinds ) );
2913 $this->mOptions = $newOptions;
2914 $this->mOptionsLoaded = true;
2918 * Get the user's preferred date format.
2919 * @return string User's preferred date format
2921 public function getDatePreference() {
2922 // Important migration for old data rows
2923 if ( is_null( $this->mDatePreference ) ) {
2924 global $wgLang;
2925 $value = $this->getOption( 'date' );
2926 $map = $wgLang->getDatePreferenceMigrationMap();
2927 if ( isset( $map[$value] ) ) {
2928 $value = $map[$value];
2930 $this->mDatePreference = $value;
2932 return $this->mDatePreference;
2936 * Determine based on the wiki configuration and the user's options,
2937 * whether this user must be over HTTPS no matter what.
2939 * @return bool
2941 public function requiresHTTPS() {
2942 global $wgSecureLogin;
2943 if ( !$wgSecureLogin ) {
2944 return false;
2945 } else {
2946 $https = $this->getBoolOption( 'prefershttps' );
2947 Hooks::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2948 if ( $https ) {
2949 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2951 return $https;
2956 * Get the user preferred stub threshold
2958 * @return int
2960 public function getStubThreshold() {
2961 global $wgMaxArticleSize; # Maximum article size, in Kb
2962 $threshold = $this->getIntOption( 'stubthreshold' );
2963 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2964 // If they have set an impossible value, disable the preference
2965 // so we can use the parser cache again.
2966 $threshold = 0;
2968 return $threshold;
2972 * Get the permissions this user has.
2973 * @return array Array of String permission names
2975 public function getRights() {
2976 if ( is_null( $this->mRights ) ) {
2977 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2978 Hooks::run( 'UserGetRights', array( $this, &$this->mRights ) );
2979 // Force reindexation of rights when a hook has unset one of them
2980 $this->mRights = array_values( array_unique( $this->mRights ) );
2982 return $this->mRights;
2986 * Get the list of explicit group memberships this user has.
2987 * The implicit * and user groups are not included.
2988 * @return array Array of String internal group names
2990 public function getGroups() {
2991 $this->load();
2992 $this->loadGroups();
2993 return $this->mGroups;
2997 * Get the list of implicit group memberships this user has.
2998 * This includes all explicit groups, plus 'user' if logged in,
2999 * '*' for all accounts, and autopromoted groups
3000 * @param bool $recache Whether to avoid the cache
3001 * @return array Array of String internal group names
3003 public function getEffectiveGroups( $recache = false ) {
3004 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
3005 $this->mEffectiveGroups = array_unique( array_merge(
3006 $this->getGroups(), // explicit groups
3007 $this->getAutomaticGroups( $recache ) // implicit groups
3008 ) );
3009 // Hook for additional groups
3010 Hooks::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
3011 // Force reindexation of groups when a hook has unset one of them
3012 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
3014 return $this->mEffectiveGroups;
3018 * Get the list of implicit group memberships this user has.
3019 * This includes 'user' if logged in, '*' for all accounts,
3020 * and autopromoted groups
3021 * @param bool $recache Whether to avoid the cache
3022 * @return array Array of String internal group names
3024 public function getAutomaticGroups( $recache = false ) {
3025 if ( $recache || is_null( $this->mImplicitGroups ) ) {
3026 $this->mImplicitGroups = array( '*' );
3027 if ( $this->getId() ) {
3028 $this->mImplicitGroups[] = 'user';
3030 $this->mImplicitGroups = array_unique( array_merge(
3031 $this->mImplicitGroups,
3032 Autopromote::getAutopromoteGroups( $this )
3033 ) );
3035 if ( $recache ) {
3036 // Assure data consistency with rights/groups,
3037 // as getEffectiveGroups() depends on this function
3038 $this->mEffectiveGroups = null;
3041 return $this->mImplicitGroups;
3045 * Returns the groups the user has belonged to.
3047 * The user may still belong to the returned groups. Compare with getGroups().
3049 * The function will not return groups the user had belonged to before MW 1.17
3051 * @return array Names of the groups the user has belonged to.
3053 public function getFormerGroups() {
3054 $this->load();
3056 if ( is_null( $this->mFormerGroups ) ) {
3057 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
3058 ? wfGetDB( DB_MASTER )
3059 : wfGetDB( DB_SLAVE );
3060 $res = $db->select( 'user_former_groups',
3061 array( 'ufg_group' ),
3062 array( 'ufg_user' => $this->mId ),
3063 __METHOD__ );
3064 $this->mFormerGroups = array();
3065 foreach ( $res as $row ) {
3066 $this->mFormerGroups[] = $row->ufg_group;
3070 return $this->mFormerGroups;
3074 * Get the user's edit count.
3075 * @return int|null Null for anonymous users
3077 public function getEditCount() {
3078 if ( !$this->getId() ) {
3079 return null;
3082 if ( $this->mEditCount === null ) {
3083 /* Populate the count, if it has not been populated yet */
3084 $dbr = wfGetDB( DB_SLAVE );
3085 // check if the user_editcount field has been initialized
3086 $count = $dbr->selectField(
3087 'user', 'user_editcount',
3088 array( 'user_id' => $this->mId ),
3089 __METHOD__
3092 if ( $count === null ) {
3093 // it has not been initialized. do so.
3094 $count = $this->initEditCount();
3096 $this->mEditCount = $count;
3098 return (int)$this->mEditCount;
3102 * Add the user to the given group.
3103 * This takes immediate effect.
3104 * @param string $group Name of the group to add
3105 * @return bool
3107 public function addGroup( $group ) {
3108 $this->load();
3110 if ( !Hooks::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3111 return false;
3114 $dbw = wfGetDB( DB_MASTER );
3115 if ( $this->getId() ) {
3116 $dbw->insert( 'user_groups',
3117 array(
3118 'ug_user' => $this->getID(),
3119 'ug_group' => $group,
3121 __METHOD__,
3122 array( 'IGNORE' ) );
3125 $this->loadGroups();
3126 $this->mGroups[] = $group;
3127 // In case loadGroups was not called before, we now have the right twice.
3128 // Get rid of the duplicate.
3129 $this->mGroups = array_unique( $this->mGroups );
3131 // Refresh the groups caches, and clear the rights cache so it will be
3132 // refreshed on the next call to $this->getRights().
3133 $this->getEffectiveGroups( true );
3134 $this->mRights = null;
3136 $this->invalidateCache();
3138 return true;
3142 * Remove the user from the given group.
3143 * This takes immediate effect.
3144 * @param string $group Name of the group to remove
3145 * @return bool
3147 public function removeGroup( $group ) {
3148 $this->load();
3149 if ( !Hooks::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3150 return false;
3153 $dbw = wfGetDB( DB_MASTER );
3154 $dbw->delete( 'user_groups',
3155 array(
3156 'ug_user' => $this->getID(),
3157 'ug_group' => $group,
3158 ), __METHOD__
3160 // Remember that the user was in this group
3161 $dbw->insert( 'user_former_groups',
3162 array(
3163 'ufg_user' => $this->getID(),
3164 'ufg_group' => $group,
3166 __METHOD__,
3167 array( 'IGNORE' )
3170 $this->loadGroups();
3171 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
3173 // Refresh the groups caches, and clear the rights cache so it will be
3174 // refreshed on the next call to $this->getRights().
3175 $this->getEffectiveGroups( true );
3176 $this->mRights = null;
3178 $this->invalidateCache();
3180 return true;
3184 * Get whether the user is logged in
3185 * @return bool
3187 public function isLoggedIn() {
3188 return $this->getID() != 0;
3192 * Get whether the user is anonymous
3193 * @return bool
3195 public function isAnon() {
3196 return !$this->isLoggedIn();
3200 * Check if user is allowed to access a feature / make an action
3202 * @param string $permissions,... Permissions to test
3203 * @return bool True if user is allowed to perform *any* of the given actions
3205 public function isAllowedAny( /*...*/ ) {
3206 $permissions = func_get_args();
3207 foreach ( $permissions as $permission ) {
3208 if ( $this->isAllowed( $permission ) ) {
3209 return true;
3212 return false;
3217 * @param string $permissions,... Permissions to test
3218 * @return bool True if the user is allowed to perform *all* of the given actions
3220 public function isAllowedAll( /*...*/ ) {
3221 $permissions = func_get_args();
3222 foreach ( $permissions as $permission ) {
3223 if ( !$this->isAllowed( $permission ) ) {
3224 return false;
3227 return true;
3231 * Internal mechanics of testing a permission
3232 * @param string $action
3233 * @return bool
3235 public function isAllowed( $action = '' ) {
3236 if ( $action === '' ) {
3237 return true; // In the spirit of DWIM
3239 // Patrolling may not be enabled
3240 if ( $action === 'patrol' || $action === 'autopatrol' ) {
3241 global $wgUseRCPatrol, $wgUseNPPatrol;
3242 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3243 return false;
3246 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3247 // by misconfiguration: 0 == 'foo'
3248 return in_array( $action, $this->getRights(), true );
3252 * Check whether to enable recent changes patrol features for this user
3253 * @return bool True or false
3255 public function useRCPatrol() {
3256 global $wgUseRCPatrol;
3257 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3261 * Check whether to enable new pages patrol features for this user
3262 * @return bool True or false
3264 public function useNPPatrol() {
3265 global $wgUseRCPatrol, $wgUseNPPatrol;
3266 return (
3267 ( $wgUseRCPatrol || $wgUseNPPatrol )
3268 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3273 * Get the WebRequest object to use with this object
3275 * @return WebRequest
3277 public function getRequest() {
3278 if ( $this->mRequest ) {
3279 return $this->mRequest;
3280 } else {
3281 global $wgRequest;
3282 return $wgRequest;
3287 * Get the current skin, loading it if required
3288 * @return Skin The current skin
3289 * @todo FIXME: Need to check the old failback system [AV]
3290 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3292 public function getSkin() {
3293 wfDeprecated( __METHOD__, '1.18' );
3294 return RequestContext::getMain()->getSkin();
3298 * Get a WatchedItem for this user and $title.
3300 * @since 1.22 $checkRights parameter added
3301 * @param Title $title
3302 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3303 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3304 * @return WatchedItem
3306 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3307 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3309 if ( isset( $this->mWatchedItems[$key] ) ) {
3310 return $this->mWatchedItems[$key];
3313 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
3314 $this->mWatchedItems = array();
3317 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
3318 return $this->mWatchedItems[$key];
3322 * Check the watched status of an article.
3323 * @since 1.22 $checkRights parameter added
3324 * @param Title $title Title of the article to look at
3325 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3326 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3327 * @return bool
3329 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3330 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3334 * Watch an article.
3335 * @since 1.22 $checkRights parameter added
3336 * @param Title $title Title of the article to look at
3337 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3338 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3340 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3341 $this->getWatchedItem( $title, $checkRights )->addWatch();
3342 $this->invalidateCache();
3346 * Stop watching an article.
3347 * @since 1.22 $checkRights parameter added
3348 * @param Title $title Title of the article to look at
3349 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3350 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3352 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3353 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3354 $this->invalidateCache();
3358 * Clear the user's notification timestamp for the given title.
3359 * If e-notif e-mails are on, they will receive notification mails on
3360 * the next change of the page if it's watched etc.
3361 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3362 * @param Title $title Title of the article to look at
3363 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3365 public function clearNotification( &$title, $oldid = 0 ) {
3366 global $wgUseEnotif, $wgShowUpdatedMarker;
3368 // Do nothing if the database is locked to writes
3369 if ( wfReadOnly() ) {
3370 return;
3373 // Do nothing if not allowed to edit the watchlist
3374 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3375 return;
3378 // If we're working on user's talk page, we should update the talk page message indicator
3379 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3380 if ( !Hooks::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3381 return;
3384 $nextid = $oldid ? $title->getNextRevisionID( $oldid ) : null;
3386 if ( !$oldid || !$nextid ) {
3387 // If we're looking at the latest revision, we should definitely clear it
3388 $this->setNewtalk( false );
3389 } else {
3390 // Otherwise we should update its revision, if it's present
3391 if ( $this->getNewtalk() ) {
3392 // Naturally the other one won't clear by itself
3393 $this->setNewtalk( false );
3394 $this->setNewtalk( true, Revision::newFromId( $nextid ) );
3399 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3400 return;
3403 if ( $this->isAnon() ) {
3404 // Nothing else to do...
3405 return;
3408 // Only update the timestamp if the page is being watched.
3409 // The query to find out if it is watched is cached both in memcached and per-invocation,
3410 // and when it does have to be executed, it can be on a slave
3411 // If this is the user's newtalk page, we always update the timestamp
3412 $force = '';
3413 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3414 $force = 'force';
3417 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3418 $force, $oldid, WatchedItem::DEFERRED
3423 * Resets all of the given user's page-change notification timestamps.
3424 * If e-notif e-mails are on, they will receive notification mails on
3425 * the next change of any watched page.
3426 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3428 public function clearAllNotifications() {
3429 if ( wfReadOnly() ) {
3430 return;
3433 // Do nothing if not allowed to edit the watchlist
3434 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3435 return;
3438 global $wgUseEnotif, $wgShowUpdatedMarker;
3439 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3440 $this->setNewtalk( false );
3441 return;
3443 $id = $this->getId();
3444 if ( $id != 0 ) {
3445 $dbw = wfGetDB( DB_MASTER );
3446 $dbw->update( 'watchlist',
3447 array( /* SET */ 'wl_notificationtimestamp' => null ),
3448 array( /* WHERE */ 'wl_user' => $id ),
3449 __METHOD__
3451 // We also need to clear here the "you have new message" notification for the own user_talk page;
3452 // it's cleared one page view later in WikiPage::doViewUpdates().
3457 * Set a cookie on the user's client. Wrapper for
3458 * WebResponse::setCookie
3459 * @param string $name Name of the cookie to set
3460 * @param string $value Value to set
3461 * @param int $exp Expiration time, as a UNIX time value;
3462 * if 0 or not specified, use the default $wgCookieExpiration
3463 * @param bool $secure
3464 * true: Force setting the secure attribute when setting the cookie
3465 * false: Force NOT setting the secure attribute when setting the cookie
3466 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3467 * @param array $params Array of options sent passed to WebResponse::setcookie()
3468 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3469 * is passed.
3471 protected function setCookie(
3472 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3474 if ( $request === null ) {
3475 $request = $this->getRequest();
3477 $params['secure'] = $secure;
3478 $request->response()->setcookie( $name, $value, $exp, $params );
3482 * Clear a cookie on the user's client
3483 * @param string $name Name of the cookie to clear
3484 * @param bool $secure
3485 * true: Force setting the secure attribute when setting the cookie
3486 * false: Force NOT setting the secure attribute when setting the cookie
3487 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3488 * @param array $params Array of options sent passed to WebResponse::setcookie()
3490 protected function clearCookie( $name, $secure = null, $params = array() ) {
3491 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3495 * Set the default cookies for this session on the user's client.
3497 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3498 * is passed.
3499 * @param bool $secure Whether to force secure/insecure cookies or use default
3500 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3502 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3503 if ( $request === null ) {
3504 $request = $this->getRequest();
3507 $this->load();
3508 if ( 0 == $this->mId ) {
3509 return;
3511 if ( !$this->mToken ) {
3512 // When token is empty or NULL generate a new one and then save it to the database
3513 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3514 // Simply by setting every cell in the user_token column to NULL and letting them be
3515 // regenerated as users log back into the wiki.
3516 $this->setToken();
3517 if ( !wfReadOnly() ) {
3518 $this->saveSettings();
3521 $session = array(
3522 'wsUserID' => $this->mId,
3523 'wsToken' => $this->mToken,
3524 'wsUserName' => $this->getName()
3526 $cookies = array(
3527 'UserID' => $this->mId,
3528 'UserName' => $this->getName(),
3530 if ( $rememberMe ) {
3531 $cookies['Token'] = $this->mToken;
3532 } else {
3533 $cookies['Token'] = false;
3536 Hooks::run( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3538 foreach ( $session as $name => $value ) {
3539 $request->setSessionData( $name, $value );
3541 foreach ( $cookies as $name => $value ) {
3542 if ( $value === false ) {
3543 $this->clearCookie( $name );
3544 } else {
3545 $this->setCookie( $name, $value, 0, $secure, array(), $request );
3550 * If wpStickHTTPS was selected, also set an insecure cookie that
3551 * will cause the site to redirect the user to HTTPS, if they access
3552 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3553 * as the one set by centralauth (bug 53538). Also set it to session, or
3554 * standard time setting, based on if rememberme was set.
3556 if ( $request->getCheck( 'wpStickHTTPS' ) || $this->requiresHTTPS() ) {
3557 $this->setCookie(
3558 'forceHTTPS',
3559 'true',
3560 $rememberMe ? 0 : null,
3561 false,
3562 array( 'prefix' => '' ) // no prefix
3568 * Log this user out.
3570 public function logout() {
3571 if ( Hooks::run( 'UserLogout', array( &$this ) ) ) {
3572 $this->doLogout();
3577 * Clear the user's cookies and session, and reset the instance cache.
3578 * @see logout()
3580 public function doLogout() {
3581 $this->clearInstanceCache( 'defaults' );
3583 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3585 $this->clearCookie( 'UserID' );
3586 $this->clearCookie( 'Token' );
3587 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3589 // Remember when user logged out, to prevent seeing cached pages
3590 $this->setCookie( 'LoggedOut', time(), time() + 86400 );
3594 * Save this user's settings into the database.
3595 * @todo Only rarely do all these fields need to be set!
3597 public function saveSettings() {
3598 global $wgAuth;
3600 if ( wfReadOnly() ) {
3601 // @TODO: caller should deal with this instead!
3602 // This should really just be an exception.
3603 MWExceptionHandler::logException( new DBExpectedError(
3604 null,
3605 "Could not update user with ID '{$this->mId}'; DB is read-only."
3606 ) );
3607 return;
3610 $this->load();
3611 $this->loadPasswords();
3612 if ( 0 == $this->mId ) {
3613 return; // anon
3616 // Get a new user_touched that is higher than the old one.
3617 // This will be used for a CAS check as a last-resort safety
3618 // check against race conditions and slave lag.
3619 $oldTouched = $this->mTouched;
3620 $newTouched = $this->newTouchedTimestamp();
3622 if ( !$wgAuth->allowSetLocalPassword() ) {
3623 $this->mPassword = self::getPasswordFactory()->newFromCiphertext( null );
3626 $dbw = wfGetDB( DB_MASTER );
3627 $dbw->update( 'user',
3628 array( /* SET */
3629 'user_name' => $this->mName,
3630 'user_password' => $this->mPassword->toString(),
3631 'user_newpassword' => $this->mNewpassword->toString(),
3632 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3633 'user_real_name' => $this->mRealName,
3634 'user_email' => $this->mEmail,
3635 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3636 'user_touched' => $dbw->timestamp( $newTouched ),
3637 'user_token' => strval( $this->mToken ),
3638 'user_email_token' => $this->mEmailToken,
3639 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3640 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires ),
3641 ), array( /* WHERE */
3642 'user_id' => $this->mId,
3643 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3644 ), __METHOD__
3647 if ( !$dbw->affectedRows() ) {
3648 // Maybe the problem was a missed cache update; clear it to be safe
3649 $this->clearSharedCache();
3650 // User was changed in the meantime or loaded with stale data
3651 $from = ( $this->queryFlagsUsed & self::READ_LATEST ) ? 'master' : 'slave';
3652 MWExceptionHandler::logException( new MWException(
3653 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3654 "the version of the user to be saved is older than the current version."
3655 ) );
3657 return;
3660 $this->mTouched = $newTouched;
3661 $this->saveOptions();
3663 Hooks::run( 'UserSaveSettings', array( $this ) );
3664 $this->clearSharedCache();
3665 $this->getUserPage()->invalidateCache();
3667 // T95839: clear the cache again post-commit to reduce race conditions
3668 // where stale values are written back to the cache by other threads.
3669 // Note: this *still* doesn't deal with REPEATABLE-READ snapshot lag...
3670 $that = $this;
3671 $dbw->onTransactionIdle( function() use ( $that ) {
3672 $that->clearSharedCache();
3673 } );
3677 * If only this user's username is known, and it exists, return the user ID.
3678 * @return int
3680 public function idForName() {
3681 $s = trim( $this->getName() );
3682 if ( $s === '' ) {
3683 return 0;
3686 $dbr = wfGetDB( DB_SLAVE );
3687 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
3688 if ( $id === false ) {
3689 $id = 0;
3691 return $id;
3695 * Add a user to the database, return the user object
3697 * @param string $name Username to add
3698 * @param array $params Array of Strings Non-default parameters to save to
3699 * the database as user_* fields:
3700 * - password: The user's password hash. Password logins will be disabled
3701 * if this is omitted.
3702 * - newpassword: Hash for a temporary password that has been mailed to
3703 * the user.
3704 * - email: The user's email address.
3705 * - email_authenticated: The email authentication timestamp.
3706 * - real_name: The user's real name.
3707 * - options: An associative array of non-default options.
3708 * - token: Random authentication token. Do not set.
3709 * - registration: Registration timestamp. Do not set.
3711 * @return User|null User object, or null if the username already exists.
3713 public static function createNew( $name, $params = array() ) {
3714 $user = new User;
3715 $user->load();
3716 $user->loadPasswords();
3717 $user->setToken(); // init token
3718 if ( isset( $params['options'] ) ) {
3719 $user->mOptions = $params['options'] + (array)$user->mOptions;
3720 unset( $params['options'] );
3722 $dbw = wfGetDB( DB_MASTER );
3723 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3725 $fields = array(
3726 'user_id' => $seqVal,
3727 'user_name' => $name,
3728 'user_password' => $user->mPassword->toString(),
3729 'user_newpassword' => $user->mNewpassword->toString(),
3730 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3731 'user_email' => $user->mEmail,
3732 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3733 'user_real_name' => $user->mRealName,
3734 'user_token' => strval( $user->mToken ),
3735 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3736 'user_editcount' => 0,
3737 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3739 foreach ( $params as $name => $value ) {
3740 $fields["user_$name"] = $value;
3742 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3743 if ( $dbw->affectedRows() ) {
3744 $newUser = User::newFromId( $dbw->insertId() );
3745 } else {
3746 $newUser = null;
3748 return $newUser;
3752 * Add this existing user object to the database. If the user already
3753 * exists, a fatal status object is returned, and the user object is
3754 * initialised with the data from the database.
3756 * Previously, this function generated a DB error due to a key conflict
3757 * if the user already existed. Many extension callers use this function
3758 * in code along the lines of:
3760 * $user = User::newFromName( $name );
3761 * if ( !$user->isLoggedIn() ) {
3762 * $user->addToDatabase();
3764 * // do something with $user...
3766 * However, this was vulnerable to a race condition (bug 16020). By
3767 * initialising the user object if the user exists, we aim to support this
3768 * calling sequence as far as possible.
3770 * Note that if the user exists, this function will acquire a write lock,
3771 * so it is still advisable to make the call conditional on isLoggedIn(),
3772 * and to commit the transaction after calling.
3774 * @throws MWException
3775 * @return Status
3777 public function addToDatabase() {
3778 $this->load();
3779 $this->loadPasswords();
3780 if ( !$this->mToken ) {
3781 $this->setToken(); // init token
3784 $this->mTouched = $this->newTouchedTimestamp();
3786 $dbw = wfGetDB( DB_MASTER );
3787 $inWrite = $dbw->writesOrCallbacksPending();
3788 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3789 $dbw->insert( 'user',
3790 array(
3791 'user_id' => $seqVal,
3792 'user_name' => $this->mName,
3793 'user_password' => $this->mPassword->toString(),
3794 'user_newpassword' => $this->mNewpassword->toString(),
3795 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3796 'user_email' => $this->mEmail,
3797 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3798 'user_real_name' => $this->mRealName,
3799 'user_token' => strval( $this->mToken ),
3800 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3801 'user_editcount' => 0,
3802 'user_touched' => $dbw->timestamp( $this->mTouched ),
3803 ), __METHOD__,
3804 array( 'IGNORE' )
3806 if ( !$dbw->affectedRows() ) {
3807 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3808 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3809 if ( $inWrite ) {
3810 // Can't commit due to pending writes that may need atomicity.
3811 // This may cause some lock contention unlike the case below.
3812 $options = array( 'LOCK IN SHARE MODE' );
3813 $flags = self::READ_LOCKING;
3814 } else {
3815 // Often, this case happens early in views before any writes when
3816 // using CentralAuth. It's should be OK to commit and break the snapshot.
3817 $dbw->commit( __METHOD__, 'flush' );
3818 $options = array();
3819 $flags = self::READ_LATEST;
3821 $this->mId = $dbw->selectField( 'user', 'user_id',
3822 array( 'user_name' => $this->mName ), __METHOD__, $options );
3823 $loaded = false;
3824 if ( $this->mId ) {
3825 if ( $this->loadFromDatabase( $flags ) ) {
3826 $loaded = true;
3829 if ( !$loaded ) {
3830 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3831 "to insert user '{$this->mName}' row, but it was not present in select!" );
3833 return Status::newFatal( 'userexists' );
3835 $this->mId = $dbw->insertId();
3837 // Clear instance cache other than user table data, which is already accurate
3838 $this->clearInstanceCache();
3840 $this->saveOptions();
3841 return Status::newGood();
3845 * If this user is logged-in and blocked,
3846 * block any IP address they've successfully logged in from.
3847 * @return bool A block was spread
3849 public function spreadAnyEditBlock() {
3850 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3851 return $this->spreadBlock();
3853 return false;
3857 * If this (non-anonymous) user is blocked,
3858 * block the IP address they've successfully logged in from.
3859 * @return bool A block was spread
3861 protected function spreadBlock() {
3862 wfDebug( __METHOD__ . "()\n" );
3863 $this->load();
3864 if ( $this->mId == 0 ) {
3865 return false;
3868 $userblock = Block::newFromTarget( $this->getName() );
3869 if ( !$userblock ) {
3870 return false;
3873 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3877 * Get whether the user is explicitly blocked from account creation.
3878 * @return bool|Block
3880 public function isBlockedFromCreateAccount() {
3881 $this->getBlockedStatus();
3882 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3883 return $this->mBlock;
3886 # bug 13611: if the IP address the user is trying to create an account from is
3887 # blocked with createaccount disabled, prevent new account creation there even
3888 # when the user is logged in
3889 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3890 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3892 return $this->mBlockedFromCreateAccount instanceof Block
3893 && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3894 ? $this->mBlockedFromCreateAccount
3895 : false;
3899 * Get whether the user is blocked from using Special:Emailuser.
3900 * @return bool
3902 public function isBlockedFromEmailuser() {
3903 $this->getBlockedStatus();
3904 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3908 * Get whether the user is allowed to create an account.
3909 * @return bool
3911 public function isAllowedToCreateAccount() {
3912 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3916 * Get this user's personal page title.
3918 * @return Title User's personal page title
3920 public function getUserPage() {
3921 return Title::makeTitle( NS_USER, $this->getName() );
3925 * Get this user's talk page title.
3927 * @return Title User's talk page title
3929 public function getTalkPage() {
3930 $title = $this->getUserPage();
3931 return $title->getTalkPage();
3935 * Determine whether the user is a newbie. Newbies are either
3936 * anonymous IPs, or the most recently created accounts.
3937 * @return bool
3939 public function isNewbie() {
3940 return !$this->isAllowed( 'autoconfirmed' );
3944 * Check to see if the given clear-text password is one of the accepted passwords
3945 * @param string $password User password
3946 * @return bool True if the given password is correct, otherwise False
3948 public function checkPassword( $password ) {
3949 global $wgAuth, $wgLegacyEncoding;
3951 $this->loadPasswords();
3953 // Some passwords will give a fatal Status, which means there is
3954 // some sort of technical or security reason for this password to
3955 // be completely invalid and should never be checked (e.g., T64685)
3956 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
3957 return false;
3960 // Certain authentication plugins do NOT want to save
3961 // domain passwords in a mysql database, so we should
3962 // check this (in case $wgAuth->strict() is false).
3963 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3964 return true;
3965 } elseif ( $wgAuth->strict() ) {
3966 // Auth plugin doesn't allow local authentication
3967 return false;
3968 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3969 // Auth plugin doesn't allow local authentication for this user name
3970 return false;
3973 if ( !$this->mPassword->equals( $password ) ) {
3974 if ( $wgLegacyEncoding ) {
3975 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3976 // Check for this with iconv
3977 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3978 if ( $cp1252Password === $password || !$this->mPassword->equals( $cp1252Password ) ) {
3979 return false;
3981 } else {
3982 return false;
3986 $passwordFactory = self::getPasswordFactory();
3987 if ( $passwordFactory->needsUpdate( $this->mPassword ) && !wfReadOnly() ) {
3988 $this->mPassword = $passwordFactory->newFromPlaintext( $password );
3989 $this->saveSettings();
3992 return true;
3996 * Check if the given clear-text password matches the temporary password
3997 * sent by e-mail for password reset operations.
3999 * @param string $plaintext
4001 * @return bool True if matches, false otherwise
4003 public function checkTemporaryPassword( $plaintext ) {
4004 global $wgNewPasswordExpiry;
4006 $this->load();
4007 $this->loadPasswords();
4008 if ( $this->mNewpassword->equals( $plaintext ) ) {
4009 if ( is_null( $this->mNewpassTime ) ) {
4010 return true;
4012 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
4013 return ( time() < $expiry );
4014 } else {
4015 return false;
4020 * Alias for getEditToken.
4021 * @deprecated since 1.19, use getEditToken instead.
4023 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4024 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4025 * @return string The new edit token
4027 public function editToken( $salt = '', $request = null ) {
4028 wfDeprecated( __METHOD__, '1.19' );
4029 return $this->getEditToken( $salt, $request );
4033 * Internal implementation for self::getEditToken() and
4034 * self::matchEditToken().
4036 * @param string|array $salt
4037 * @param WebRequest $request
4038 * @param string|int $timestamp
4039 * @return string
4041 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
4042 if ( $this->isAnon() ) {
4043 return self::EDIT_TOKEN_SUFFIX;
4044 } else {
4045 $token = $request->getSessionData( 'wsEditToken' );
4046 if ( $token === null ) {
4047 $token = MWCryptRand::generateHex( 32 );
4048 $request->setSessionData( 'wsEditToken', $token );
4050 if ( is_array( $salt ) ) {
4051 $salt = implode( '|', $salt );
4053 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
4054 dechex( $timestamp ) .
4055 self::EDIT_TOKEN_SUFFIX;
4060 * Initialize (if necessary) and return a session token value
4061 * which can be used in edit forms to show that the user's
4062 * login credentials aren't being hijacked with a foreign form
4063 * submission.
4065 * @since 1.19
4067 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4068 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4069 * @return string The new edit token
4071 public function getEditToken( $salt = '', $request = null ) {
4072 return $this->getEditTokenAtTimestamp(
4073 $salt, $request ?: $this->getRequest(), wfTimestamp()
4078 * Generate a looking random token for various uses.
4080 * @return string The new random token
4081 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
4082 * wfRandomString for pseudo-randomness.
4084 public static function generateToken() {
4085 return MWCryptRand::generateHex( 32 );
4089 * Get the embedded timestamp from a token.
4090 * @param string $val Input token
4091 * @return int|null
4093 public static function getEditTokenTimestamp( $val ) {
4094 $suffixLen = strlen( self::EDIT_TOKEN_SUFFIX );
4095 if ( strlen( $val ) <= 32 + $suffixLen ) {
4096 return null;
4099 return hexdec( substr( $val, 32, -$suffixLen ) );
4103 * Check given value against the token value stored in the session.
4104 * A match should confirm that the form was submitted from the
4105 * user's own login session, not a form submission from a third-party
4106 * site.
4108 * @param string $val Input value to compare
4109 * @param string $salt Optional function-specific data for hashing
4110 * @param WebRequest|null $request Object to use or null to use $wgRequest
4111 * @param int $maxage Fail tokens older than this, in seconds
4112 * @return bool Whether the token matches
4114 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4115 if ( $this->isAnon() ) {
4116 return $val === self::EDIT_TOKEN_SUFFIX;
4119 $timestamp = self::getEditTokenTimestamp( $val );
4120 if ( $timestamp === null ) {
4121 return false;
4123 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
4124 // Expired token
4125 return false;
4128 $sessionToken = $this->getEditTokenAtTimestamp(
4129 $salt, $request ?: $this->getRequest(), $timestamp
4132 if ( $val != $sessionToken ) {
4133 wfDebug( "User::matchEditToken: broken session data\n" );
4136 return hash_equals( $sessionToken, $val );
4140 * Check given value against the token value stored in the session,
4141 * ignoring the suffix.
4143 * @param string $val Input value to compare
4144 * @param string $salt Optional function-specific data for hashing
4145 * @param WebRequest|null $request Object to use or null to use $wgRequest
4146 * @param int $maxage Fail tokens older than this, in seconds
4147 * @return bool Whether the token matches
4149 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4150 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self::EDIT_TOKEN_SUFFIX;
4151 return $this->matchEditToken( $val, $salt, $request, $maxage );
4155 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4156 * mail to the user's given address.
4158 * @param string $type Message to send, either "created", "changed" or "set"
4159 * @return Status
4161 public function sendConfirmationMail( $type = 'created' ) {
4162 global $wgLang;
4163 $expiration = null; // gets passed-by-ref and defined in next line.
4164 $token = $this->confirmationToken( $expiration );
4165 $url = $this->confirmationTokenUrl( $token );
4166 $invalidateURL = $this->invalidationTokenUrl( $token );
4167 $this->saveSettings();
4169 if ( $type == 'created' || $type === false ) {
4170 $message = 'confirmemail_body';
4171 } elseif ( $type === true ) {
4172 $message = 'confirmemail_body_changed';
4173 } else {
4174 // Messages: confirmemail_body_changed, confirmemail_body_set
4175 $message = 'confirmemail_body_' . $type;
4178 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4179 wfMessage( $message,
4180 $this->getRequest()->getIP(),
4181 $this->getName(),
4182 $url,
4183 $wgLang->timeanddate( $expiration, false ),
4184 $invalidateURL,
4185 $wgLang->date( $expiration, false ),
4186 $wgLang->time( $expiration, false ) )->text() );
4190 * Send an e-mail to this user's account. Does not check for
4191 * confirmed status or validity.
4193 * @param string $subject Message subject
4194 * @param string $body Message body
4195 * @param string $from Optional From address; if unspecified, default
4196 * $wgPasswordSender will be used.
4197 * @param string $replyto Reply-To address
4198 * @return Status
4200 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4201 if ( is_null( $from ) ) {
4202 global $wgPasswordSender;
4203 $sender = new MailAddress( $wgPasswordSender,
4204 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4205 } else {
4206 $sender = MailAddress::newFromUser( $from );
4209 $to = MailAddress::newFromUser( $this );
4210 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
4214 * Generate, store, and return a new e-mail confirmation code.
4215 * A hash (unsalted, since it's used as a key) is stored.
4217 * @note Call saveSettings() after calling this function to commit
4218 * this change to the database.
4220 * @param string &$expiration Accepts the expiration time
4221 * @return string New token
4223 protected function confirmationToken( &$expiration ) {
4224 global $wgUserEmailConfirmationTokenExpiry;
4225 $now = time();
4226 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
4227 $expiration = wfTimestamp( TS_MW, $expires );
4228 $this->load();
4229 $token = MWCryptRand::generateHex( 32 );
4230 $hash = md5( $token );
4231 $this->mEmailToken = $hash;
4232 $this->mEmailTokenExpires = $expiration;
4233 return $token;
4237 * Return a URL the user can use to confirm their email address.
4238 * @param string $token Accepts the email confirmation token
4239 * @return string New token URL
4241 protected function confirmationTokenUrl( $token ) {
4242 return $this->getTokenUrl( 'ConfirmEmail', $token );
4246 * Return a URL the user can use to invalidate their email address.
4247 * @param string $token Accepts the email confirmation token
4248 * @return string New token URL
4250 protected function invalidationTokenUrl( $token ) {
4251 return $this->getTokenUrl( 'InvalidateEmail', $token );
4255 * Internal function to format the e-mail validation/invalidation URLs.
4256 * This uses a quickie hack to use the
4257 * hardcoded English names of the Special: pages, for ASCII safety.
4259 * @note Since these URLs get dropped directly into emails, using the
4260 * short English names avoids insanely long URL-encoded links, which
4261 * also sometimes can get corrupted in some browsers/mailers
4262 * (bug 6957 with Gmail and Internet Explorer).
4264 * @param string $page Special page
4265 * @param string $token Token
4266 * @return string Formatted URL
4268 protected function getTokenUrl( $page, $token ) {
4269 // Hack to bypass localization of 'Special:'
4270 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
4271 return $title->getCanonicalURL();
4275 * Mark the e-mail address confirmed.
4277 * @note Call saveSettings() after calling this function to commit the change.
4279 * @return bool
4281 public function confirmEmail() {
4282 // Check if it's already confirmed, so we don't touch the database
4283 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4284 if ( !$this->isEmailConfirmed() ) {
4285 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4286 Hooks::run( 'ConfirmEmailComplete', array( $this ) );
4288 return true;
4292 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4293 * address if it was already confirmed.
4295 * @note Call saveSettings() after calling this function to commit the change.
4296 * @return bool Returns true
4298 public function invalidateEmail() {
4299 $this->load();
4300 $this->mEmailToken = null;
4301 $this->mEmailTokenExpires = null;
4302 $this->setEmailAuthenticationTimestamp( null );
4303 $this->mEmail = '';
4304 Hooks::run( 'InvalidateEmailComplete', array( $this ) );
4305 return true;
4309 * Set the e-mail authentication timestamp.
4310 * @param string $timestamp TS_MW timestamp
4312 public function setEmailAuthenticationTimestamp( $timestamp ) {
4313 $this->load();
4314 $this->mEmailAuthenticated = $timestamp;
4315 Hooks::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
4319 * Is this user allowed to send e-mails within limits of current
4320 * site configuration?
4321 * @return bool
4323 public function canSendEmail() {
4324 global $wgEnableEmail, $wgEnableUserEmail;
4325 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4326 return false;
4328 $canSend = $this->isEmailConfirmed();
4329 Hooks::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4330 return $canSend;
4334 * Is this user allowed to receive e-mails within limits of current
4335 * site configuration?
4336 * @return bool
4338 public function canReceiveEmail() {
4339 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4343 * Is this user's e-mail address valid-looking and confirmed within
4344 * limits of the current site configuration?
4346 * @note If $wgEmailAuthentication is on, this may require the user to have
4347 * confirmed their address by returning a code or using a password
4348 * sent to the address from the wiki.
4350 * @return bool
4352 public function isEmailConfirmed() {
4353 global $wgEmailAuthentication;
4354 $this->load();
4355 $confirmed = true;
4356 if ( Hooks::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4357 if ( $this->isAnon() ) {
4358 return false;
4360 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4361 return false;
4363 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4364 return false;
4366 return true;
4367 } else {
4368 return $confirmed;
4373 * Check whether there is an outstanding request for e-mail confirmation.
4374 * @return bool
4376 public function isEmailConfirmationPending() {
4377 global $wgEmailAuthentication;
4378 return $wgEmailAuthentication &&
4379 !$this->isEmailConfirmed() &&
4380 $this->mEmailToken &&
4381 $this->mEmailTokenExpires > wfTimestamp();
4385 * Get the timestamp of account creation.
4387 * @return string|bool|null Timestamp of account creation, false for
4388 * non-existent/anonymous user accounts, or null if existing account
4389 * but information is not in database.
4391 public function getRegistration() {
4392 if ( $this->isAnon() ) {
4393 return false;
4395 $this->load();
4396 return $this->mRegistration;
4400 * Get the timestamp of the first edit
4402 * @return string|bool Timestamp of first edit, or false for
4403 * non-existent/anonymous user accounts.
4405 public function getFirstEditTimestamp() {
4406 if ( $this->getId() == 0 ) {
4407 return false; // anons
4409 $dbr = wfGetDB( DB_SLAVE );
4410 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4411 array( 'rev_user' => $this->getId() ),
4412 __METHOD__,
4413 array( 'ORDER BY' => 'rev_timestamp ASC' )
4415 if ( !$time ) {
4416 return false; // no edits
4418 return wfTimestamp( TS_MW, $time );
4422 * Get the permissions associated with a given list of groups
4424 * @param array $groups Array of Strings List of internal group names
4425 * @return array Array of Strings List of permission key names for given groups combined
4427 public static function getGroupPermissions( $groups ) {
4428 global $wgGroupPermissions, $wgRevokePermissions;
4429 $rights = array();
4430 // grant every granted permission first
4431 foreach ( $groups as $group ) {
4432 if ( isset( $wgGroupPermissions[$group] ) ) {
4433 $rights = array_merge( $rights,
4434 // array_filter removes empty items
4435 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4438 // now revoke the revoked permissions
4439 foreach ( $groups as $group ) {
4440 if ( isset( $wgRevokePermissions[$group] ) ) {
4441 $rights = array_diff( $rights,
4442 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4445 return array_unique( $rights );
4449 * Get all the groups who have a given permission
4451 * @param string $role Role to check
4452 * @return array Array of Strings List of internal group names with the given permission
4454 public static function getGroupsWithPermission( $role ) {
4455 global $wgGroupPermissions;
4456 $allowedGroups = array();
4457 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4458 if ( self::groupHasPermission( $group, $role ) ) {
4459 $allowedGroups[] = $group;
4462 return $allowedGroups;
4466 * Check, if the given group has the given permission
4468 * If you're wanting to check whether all users have a permission, use
4469 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4470 * from anyone.
4472 * @since 1.21
4473 * @param string $group Group to check
4474 * @param string $role Role to check
4475 * @return bool
4477 public static function groupHasPermission( $group, $role ) {
4478 global $wgGroupPermissions, $wgRevokePermissions;
4479 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4480 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4484 * Check if all users have the given permission
4486 * @since 1.22
4487 * @param string $right Right to check
4488 * @return bool
4490 public static function isEveryoneAllowed( $right ) {
4491 global $wgGroupPermissions, $wgRevokePermissions;
4492 static $cache = array();
4494 // Use the cached results, except in unit tests which rely on
4495 // being able change the permission mid-request
4496 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4497 return $cache[$right];
4500 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4501 $cache[$right] = false;
4502 return false;
4505 // If it's revoked anywhere, then everyone doesn't have it
4506 foreach ( $wgRevokePermissions as $rights ) {
4507 if ( isset( $rights[$right] ) && $rights[$right] ) {
4508 $cache[$right] = false;
4509 return false;
4513 // Allow extensions (e.g. OAuth) to say false
4514 if ( !Hooks::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4515 $cache[$right] = false;
4516 return false;
4519 $cache[$right] = true;
4520 return true;
4524 * Get the localized descriptive name for a group, if it exists
4526 * @param string $group Internal group name
4527 * @return string Localized descriptive group name
4529 public static function getGroupName( $group ) {
4530 $msg = wfMessage( "group-$group" );
4531 return $msg->isBlank() ? $group : $msg->text();
4535 * Get the localized descriptive name for a member of a group, if it exists
4537 * @param string $group Internal group name
4538 * @param string $username Username for gender (since 1.19)
4539 * @return string Localized name for group member
4541 public static function getGroupMember( $group, $username = '#' ) {
4542 $msg = wfMessage( "group-$group-member", $username );
4543 return $msg->isBlank() ? $group : $msg->text();
4547 * Return the set of defined explicit groups.
4548 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4549 * are not included, as they are defined automatically, not in the database.
4550 * @return array Array of internal group names
4552 public static function getAllGroups() {
4553 global $wgGroupPermissions, $wgRevokePermissions;
4554 return array_diff(
4555 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4556 self::getImplicitGroups()
4561 * Get a list of all available permissions.
4562 * @return string[] Array of permission names
4564 public static function getAllRights() {
4565 if ( self::$mAllRights === false ) {
4566 global $wgAvailableRights;
4567 if ( count( $wgAvailableRights ) ) {
4568 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4569 } else {
4570 self::$mAllRights = self::$mCoreRights;
4572 Hooks::run( 'UserGetAllRights', array( &self::$mAllRights ) );
4574 return self::$mAllRights;
4578 * Get a list of implicit groups
4579 * @return array Array of Strings Array of internal group names
4581 public static function getImplicitGroups() {
4582 global $wgImplicitGroups;
4584 $groups = $wgImplicitGroups;
4585 # Deprecated, use $wgImplicitGroups instead
4586 Hooks::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4588 return $groups;
4592 * Get the title of a page describing a particular group
4594 * @param string $group Internal group name
4595 * @return Title|bool Title of the page if it exists, false otherwise
4597 public static function getGroupPage( $group ) {
4598 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4599 if ( $msg->exists() ) {
4600 $title = Title::newFromText( $msg->text() );
4601 if ( is_object( $title ) ) {
4602 return $title;
4605 return false;
4609 * Create a link to the group in HTML, if available;
4610 * else return the group name.
4612 * @param string $group Internal name of the group
4613 * @param string $text The text of the link
4614 * @return string HTML link to the group
4616 public static function makeGroupLinkHTML( $group, $text = '' ) {
4617 if ( $text == '' ) {
4618 $text = self::getGroupName( $group );
4620 $title = self::getGroupPage( $group );
4621 if ( $title ) {
4622 return Linker::link( $title, htmlspecialchars( $text ) );
4623 } else {
4624 return htmlspecialchars( $text );
4629 * Create a link to the group in Wikitext, if available;
4630 * else return the group name.
4632 * @param string $group Internal name of the group
4633 * @param string $text The text of the link
4634 * @return string Wikilink to the group
4636 public static function makeGroupLinkWiki( $group, $text = '' ) {
4637 if ( $text == '' ) {
4638 $text = self::getGroupName( $group );
4640 $title = self::getGroupPage( $group );
4641 if ( $title ) {
4642 $page = $title->getFullText();
4643 return "[[$page|$text]]";
4644 } else {
4645 return $text;
4650 * Returns an array of the groups that a particular group can add/remove.
4652 * @param string $group The group to check for whether it can add/remove
4653 * @return array Array( 'add' => array( addablegroups ),
4654 * 'remove' => array( removablegroups ),
4655 * 'add-self' => array( addablegroups to self),
4656 * 'remove-self' => array( removable groups from self) )
4658 public static function changeableByGroup( $group ) {
4659 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4661 $groups = array(
4662 'add' => array(),
4663 'remove' => array(),
4664 'add-self' => array(),
4665 'remove-self' => array()
4668 if ( empty( $wgAddGroups[$group] ) ) {
4669 // Don't add anything to $groups
4670 } elseif ( $wgAddGroups[$group] === true ) {
4671 // You get everything
4672 $groups['add'] = self::getAllGroups();
4673 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4674 $groups['add'] = $wgAddGroups[$group];
4677 // Same thing for remove
4678 if ( empty( $wgRemoveGroups[$group] ) ) {
4679 // Do nothing
4680 } elseif ( $wgRemoveGroups[$group] === true ) {
4681 $groups['remove'] = self::getAllGroups();
4682 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4683 $groups['remove'] = $wgRemoveGroups[$group];
4686 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4687 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4688 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4689 if ( is_int( $key ) ) {
4690 $wgGroupsAddToSelf['user'][] = $value;
4695 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4696 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4697 if ( is_int( $key ) ) {
4698 $wgGroupsRemoveFromSelf['user'][] = $value;
4703 // Now figure out what groups the user can add to him/herself
4704 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4705 // Do nothing
4706 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4707 // No idea WHY this would be used, but it's there
4708 $groups['add-self'] = User::getAllGroups();
4709 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4710 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4713 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4714 // Do nothing
4715 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4716 $groups['remove-self'] = User::getAllGroups();
4717 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4718 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4721 return $groups;
4725 * Returns an array of groups that this user can add and remove
4726 * @return array Array( 'add' => array( addablegroups ),
4727 * 'remove' => array( removablegroups ),
4728 * 'add-self' => array( addablegroups to self),
4729 * 'remove-self' => array( removable groups from self) )
4731 public function changeableGroups() {
4732 if ( $this->isAllowed( 'userrights' ) ) {
4733 // This group gives the right to modify everything (reverse-
4734 // compatibility with old "userrights lets you change
4735 // everything")
4736 // Using array_merge to make the groups reindexed
4737 $all = array_merge( User::getAllGroups() );
4738 return array(
4739 'add' => $all,
4740 'remove' => $all,
4741 'add-self' => array(),
4742 'remove-self' => array()
4746 // Okay, it's not so simple, we will have to go through the arrays
4747 $groups = array(
4748 'add' => array(),
4749 'remove' => array(),
4750 'add-self' => array(),
4751 'remove-self' => array()
4753 $addergroups = $this->getEffectiveGroups();
4755 foreach ( $addergroups as $addergroup ) {
4756 $groups = array_merge_recursive(
4757 $groups, $this->changeableByGroup( $addergroup )
4759 $groups['add'] = array_unique( $groups['add'] );
4760 $groups['remove'] = array_unique( $groups['remove'] );
4761 $groups['add-self'] = array_unique( $groups['add-self'] );
4762 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4764 return $groups;
4768 * Deferred version of incEditCountImmediate()
4770 public function incEditCount() {
4771 $that = $this;
4772 wfGetDB( DB_MASTER )->onTransactionPreCommitOrIdle( function() use ( $that ) {
4773 $that->incEditCountImmediate();
4774 } );
4778 * Increment the user's edit-count field.
4779 * Will have no effect for anonymous users.
4780 * @since 1.26
4782 public function incEditCountImmediate() {
4783 if ( $this->isAnon() ) {
4784 return;
4787 $dbw = wfGetDB( DB_MASTER );
4788 // No rows will be "affected" if user_editcount is NULL
4789 $dbw->update(
4790 'user',
4791 array( 'user_editcount=user_editcount+1' ),
4792 array( 'user_id' => $this->getId() ),
4793 __METHOD__
4795 // Lazy initialization check...
4796 if ( $dbw->affectedRows() == 0 ) {
4797 // Now here's a goddamn hack...
4798 $dbr = wfGetDB( DB_SLAVE );
4799 if ( $dbr !== $dbw ) {
4800 // If we actually have a slave server, the count is
4801 // at least one behind because the current transaction
4802 // has not been committed and replicated.
4803 $this->initEditCount( 1 );
4804 } else {
4805 // But if DB_SLAVE is selecting the master, then the
4806 // count we just read includes the revision that was
4807 // just added in the working transaction.
4808 $this->initEditCount();
4811 // Edit count in user cache too
4812 $this->invalidateCache();
4816 * Initialize user_editcount from data out of the revision table
4818 * @param int $add Edits to add to the count from the revision table
4819 * @return int Number of edits
4821 protected function initEditCount( $add = 0 ) {
4822 // Pull from a slave to be less cruel to servers
4823 // Accuracy isn't the point anyway here
4824 $dbr = wfGetDB( DB_SLAVE );
4825 $count = (int)$dbr->selectField(
4826 'revision',
4827 'COUNT(rev_user)',
4828 array( 'rev_user' => $this->getId() ),
4829 __METHOD__
4831 $count = $count + $add;
4833 $dbw = wfGetDB( DB_MASTER );
4834 $dbw->update(
4835 'user',
4836 array( 'user_editcount' => $count ),
4837 array( 'user_id' => $this->getId() ),
4838 __METHOD__
4841 return $count;
4845 * Get the description of a given right
4847 * @param string $right Right to query
4848 * @return string Localized description of the right
4850 public static function getRightDescription( $right ) {
4851 $key = "right-$right";
4852 $msg = wfMessage( $key );
4853 return $msg->isBlank() ? $right : $msg->text();
4857 * Make a new-style password hash
4859 * @param string $password Plain-text password
4860 * @param bool|string $salt Optional salt, may be random or the user ID.
4861 * If unspecified or false, will generate one automatically
4862 * @return string Password hash
4863 * @deprecated since 1.24, use Password class
4865 public static function crypt( $password, $salt = false ) {
4866 wfDeprecated( __METHOD__, '1.24' );
4867 $hash = self::getPasswordFactory()->newFromPlaintext( $password );
4868 return $hash->toString();
4872 * Compare a password hash with a plain-text password. Requires the user
4873 * ID if there's a chance that the hash is an old-style hash.
4875 * @param string $hash Password hash
4876 * @param string $password Plain-text password to compare
4877 * @param string|bool $userId User ID for old-style password salt
4879 * @return bool
4880 * @deprecated since 1.24, use Password class
4882 public static function comparePasswords( $hash, $password, $userId = false ) {
4883 wfDeprecated( __METHOD__, '1.24' );
4885 // Check for *really* old password hashes that don't even have a type
4886 // The old hash format was just an md5 hex hash, with no type information
4887 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4888 global $wgPasswordSalt;
4889 if ( $wgPasswordSalt ) {
4890 $password = ":B:{$userId}:{$hash}";
4891 } else {
4892 $password = ":A:{$hash}";
4896 $hash = self::getPasswordFactory()->newFromCiphertext( $hash );
4897 return $hash->equals( $password );
4901 * Add a newuser log entry for this user.
4902 * Before 1.19 the return value was always true.
4904 * @param string|bool $action Account creation type.
4905 * - String, one of the following values:
4906 * - 'create' for an anonymous user creating an account for himself.
4907 * This will force the action's performer to be the created user itself,
4908 * no matter the value of $wgUser
4909 * - 'create2' for a logged in user creating an account for someone else
4910 * - 'byemail' when the created user will receive its password by e-mail
4911 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4912 * - Boolean means whether the account was created by e-mail (deprecated):
4913 * - true will be converted to 'byemail'
4914 * - false will be converted to 'create' if this object is the same as
4915 * $wgUser and to 'create2' otherwise
4917 * @param string $reason User supplied reason
4919 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4921 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4922 global $wgUser, $wgNewUserLog;
4923 if ( empty( $wgNewUserLog ) ) {
4924 return true; // disabled
4927 if ( $action === true ) {
4928 $action = 'byemail';
4929 } elseif ( $action === false ) {
4930 if ( $this->equals( $wgUser ) ) {
4931 $action = 'create';
4932 } else {
4933 $action = 'create2';
4937 if ( $action === 'create' || $action === 'autocreate' ) {
4938 $performer = $this;
4939 } else {
4940 $performer = $wgUser;
4943 $logEntry = new ManualLogEntry( 'newusers', $action );
4944 $logEntry->setPerformer( $performer );
4945 $logEntry->setTarget( $this->getUserPage() );
4946 $logEntry->setComment( $reason );
4947 $logEntry->setParameters( array(
4948 '4::userid' => $this->getId(),
4949 ) );
4950 $logid = $logEntry->insert();
4952 if ( $action !== 'autocreate' ) {
4953 $logEntry->publish( $logid );
4956 return (int)$logid;
4960 * Add an autocreate newuser log entry for this user
4961 * Used by things like CentralAuth and perhaps other authplugins.
4962 * Consider calling addNewUserLogEntry() directly instead.
4964 * @return bool
4966 public function addNewUserLogEntryAutoCreate() {
4967 $this->addNewUserLogEntry( 'autocreate' );
4969 return true;
4973 * Load the user options either from cache, the database or an array
4975 * @param array $data Rows for the current user out of the user_properties table
4977 protected function loadOptions( $data = null ) {
4978 global $wgContLang;
4980 $this->load();
4982 if ( $this->mOptionsLoaded ) {
4983 return;
4986 $this->mOptions = self::getDefaultOptions();
4988 if ( !$this->getId() ) {
4989 // For unlogged-in users, load language/variant options from request.
4990 // There's no need to do it for logged-in users: they can set preferences,
4991 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4992 // so don't override user's choice (especially when the user chooses site default).
4993 $variant = $wgContLang->getDefaultVariant();
4994 $this->mOptions['variant'] = $variant;
4995 $this->mOptions['language'] = $variant;
4996 $this->mOptionsLoaded = true;
4997 return;
5000 // Maybe load from the object
5001 if ( !is_null( $this->mOptionOverrides ) ) {
5002 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5003 foreach ( $this->mOptionOverrides as $key => $value ) {
5004 $this->mOptions[$key] = $value;
5006 } else {
5007 if ( !is_array( $data ) ) {
5008 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5009 // Load from database
5010 $dbr = ( $this->queryFlagsUsed & self::READ_LATEST )
5011 ? wfGetDB( DB_MASTER )
5012 : wfGetDB( DB_SLAVE );
5014 $res = $dbr->select(
5015 'user_properties',
5016 array( 'up_property', 'up_value' ),
5017 array( 'up_user' => $this->getId() ),
5018 __METHOD__
5021 $this->mOptionOverrides = array();
5022 $data = array();
5023 foreach ( $res as $row ) {
5024 $data[$row->up_property] = $row->up_value;
5027 foreach ( $data as $property => $value ) {
5028 $this->mOptionOverrides[$property] = $value;
5029 $this->mOptions[$property] = $value;
5033 $this->mOptionsLoaded = true;
5035 Hooks::run( 'UserLoadOptions', array( $this, &$this->mOptions ) );
5039 * Saves the non-default options for this user, as previously set e.g. via
5040 * setOption(), in the database's "user_properties" (preferences) table.
5041 * Usually used via saveSettings().
5043 protected function saveOptions() {
5044 $this->loadOptions();
5046 // Not using getOptions(), to keep hidden preferences in database
5047 $saveOptions = $this->mOptions;
5049 // Allow hooks to abort, for instance to save to a global profile.
5050 // Reset options to default state before saving.
5051 if ( !Hooks::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5052 return;
5055 $userId = $this->getId();
5057 $insert_rows = array(); // all the new preference rows
5058 foreach ( $saveOptions as $key => $value ) {
5059 // Don't bother storing default values
5060 $defaultOption = self::getDefaultOption( $key );
5061 if ( ( $defaultOption === null && $value !== false && $value !== null )
5062 || $value != $defaultOption
5064 $insert_rows[] = array(
5065 'up_user' => $userId,
5066 'up_property' => $key,
5067 'up_value' => $value,
5072 $dbw = wfGetDB( DB_MASTER );
5074 $res = $dbw->select( 'user_properties',
5075 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__ );
5077 // Find prior rows that need to be removed or updated. These rows will
5078 // all be deleted (the later so that INSERT IGNORE applies the new values).
5079 $keysDelete = array();
5080 foreach ( $res as $row ) {
5081 if ( !isset( $saveOptions[$row->up_property] )
5082 || strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
5084 $keysDelete[] = $row->up_property;
5088 if ( count( $keysDelete ) ) {
5089 // Do the DELETE by PRIMARY KEY for prior rows.
5090 // In the past a very large portion of calls to this function are for setting
5091 // 'rememberpassword' for new accounts (a preference that has since been removed).
5092 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5093 // caused gap locks on [max user ID,+infinity) which caused high contention since
5094 // updates would pile up on each other as they are for higher (newer) user IDs.
5095 // It might not be necessary these days, but it shouldn't hurt either.
5096 $dbw->delete( 'user_properties',
5097 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__ );
5099 // Insert the new preference rows
5100 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
5104 * Lazily instantiate and return a factory object for making passwords
5106 * @return PasswordFactory
5108 public static function getPasswordFactory() {
5109 if ( self::$mPasswordFactory === null ) {
5110 self::$mPasswordFactory = new PasswordFactory();
5111 self::$mPasswordFactory->init( RequestContext::getMain()->getConfig() );
5114 return self::$mPasswordFactory;
5118 * Provide an array of HTML5 attributes to put on an input element
5119 * intended for the user to enter a new password. This may include
5120 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5122 * Do *not* use this when asking the user to enter his current password!
5123 * Regardless of configuration, users may have invalid passwords for whatever
5124 * reason (e.g., they were set before requirements were tightened up).
5125 * Only use it when asking for a new password, like on account creation or
5126 * ResetPass.
5128 * Obviously, you still need to do server-side checking.
5130 * NOTE: A combination of bugs in various browsers means that this function
5131 * actually just returns array() unconditionally at the moment. May as
5132 * well keep it around for when the browser bugs get fixed, though.
5134 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5136 * @return array Array of HTML attributes suitable for feeding to
5137 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5138 * That will get confused by the boolean attribute syntax used.)
5140 public static function passwordChangeInputAttribs() {
5141 global $wgMinimalPasswordLength;
5143 if ( $wgMinimalPasswordLength == 0 ) {
5144 return array();
5147 # Note that the pattern requirement will always be satisfied if the
5148 # input is empty, so we need required in all cases.
5150 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5151 # if e-mail confirmation is being used. Since HTML5 input validation
5152 # is b0rked anyway in some browsers, just return nothing. When it's
5153 # re-enabled, fix this code to not output required for e-mail
5154 # registration.
5155 #$ret = array( 'required' );
5156 $ret = array();
5158 # We can't actually do this right now, because Opera 9.6 will print out
5159 # the entered password visibly in its error message! When other
5160 # browsers add support for this attribute, or Opera fixes its support,
5161 # we can add support with a version check to avoid doing this on Opera
5162 # versions where it will be a problem. Reported to Opera as
5163 # DSK-262266, but they don't have a public bug tracker for us to follow.
5165 if ( $wgMinimalPasswordLength > 1 ) {
5166 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5167 $ret['title'] = wfMessage( 'passwordtooshort' )
5168 ->numParams( $wgMinimalPasswordLength )->text();
5172 return $ret;
5176 * Return the list of user fields that should be selected to create
5177 * a new user object.
5178 * @return array
5180 public static function selectFields() {
5181 return array(
5182 'user_id',
5183 'user_name',
5184 'user_real_name',
5185 'user_email',
5186 'user_touched',
5187 'user_token',
5188 'user_email_authenticated',
5189 'user_email_token',
5190 'user_email_token_expires',
5191 'user_registration',
5192 'user_editcount',
5197 * Factory function for fatal permission-denied errors
5199 * @since 1.22
5200 * @param string $permission User right required
5201 * @return Status
5203 static function newFatalPermissionDeniedStatus( $permission ) {
5204 global $wgLang;
5206 $groups = array_map(
5207 array( 'User', 'makeGroupLinkWiki' ),
5208 User::getGroupsWithPermission( $permission )
5211 if ( $groups ) {
5212 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5213 } else {
5214 return Status::newFatal( 'badaccess-group0' );
5219 * Checks if two user objects point to the same user.
5221 * @since 1.25
5222 * @param User $user
5223 * @return bool
5225 public function equals( User $user ) {
5226 return $this->getName() === $user->getName();