Implement extension registration from an extension.json file
[mediawiki.git] / includes / User.php
blob62f7ec0cf08021a31a813ccc33eb77e3ffd89f6e
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 'autoconfirmed',
106 'autopatrol',
107 'bigdelete',
108 'block',
109 'blockemail',
110 'bot',
111 'browsearchive',
112 'createaccount',
113 'createpage',
114 'createtalk',
115 'delete',
116 'deletedhistory',
117 'deletedtext',
118 'deletelogentry',
119 'deleterevision',
120 'edit',
121 'editcontentmodel',
122 'editinterface',
123 'editprotected',
124 'editmyoptions',
125 'editmyprivateinfo',
126 'editmyusercss',
127 'editmyuserjs',
128 'editmywatchlist',
129 'editsemiprotected',
130 'editusercssjs', #deprecated
131 'editusercss',
132 'edituserjs',
133 'hideuser',
134 'import',
135 'importupload',
136 'ipblock-exempt',
137 'markbotedits',
138 'mergehistory',
139 'minoredit',
140 'move',
141 'movefile',
142 'move-categorypages',
143 'move-rootuserpages',
144 'move-subpages',
145 'nominornewtalk',
146 'noratelimit',
147 'override-export-depth',
148 'pagelang',
149 'passwordreset',
150 'patrol',
151 'patrolmarks',
152 'protect',
153 'proxyunbannable',
154 'purge',
155 'read',
156 'reupload',
157 'reupload-own',
158 'reupload-shared',
159 'rollback',
160 'sendemail',
161 'siteadmin',
162 'suppressionlog',
163 'suppressredirect',
164 'suppressrevision',
165 'unblockself',
166 'undelete',
167 'unwatchedpages',
168 'upload',
169 'upload_by_url',
170 'userrights',
171 'userrights-interwiki',
172 'viewmyprivateinfo',
173 'viewmywatchlist',
174 'viewsuppressed',
175 'writeapi',
179 * String Cached results of getAllRights()
181 protected static $mAllRights = false;
183 /** @name Cache variables */
184 //@{
185 public $mId;
187 public $mName;
189 public $mRealName;
192 * @todo Make this actually private
193 * @private
195 public $mPassword;
198 * @todo Make this actually private
199 * @private
201 public $mNewpassword;
203 public $mNewpassTime;
205 public $mEmail;
207 public $mTouched;
209 protected $mToken;
211 public $mEmailAuthenticated;
213 protected $mEmailToken;
215 protected $mEmailTokenExpires;
217 protected $mRegistration;
219 protected $mEditCount;
221 public $mGroups;
223 protected $mOptionOverrides;
225 protected $mPasswordExpires;
226 //@}
229 * Bool Whether the cache variables have been loaded.
231 //@{
232 public $mOptionsLoaded;
235 * Array with already loaded items or true if all items have been loaded.
237 protected $mLoadedItems = array();
238 //@}
241 * String Initialization data source if mLoadedItems!==true. May be one of:
242 * - 'defaults' anonymous user initialised from class defaults
243 * - 'name' initialise from mName
244 * - 'id' initialise from mId
245 * - 'session' log in from cookies or session if possible
247 * Use the User::newFrom*() family of functions to set this.
249 public $mFrom;
252 * Lazy-initialized variables, invalidated with clearInstanceCache
254 protected $mNewtalk;
256 protected $mDatePreference;
258 public $mBlockedby;
260 protected $mHash;
262 public $mRights;
264 protected $mBlockreason;
266 protected $mEffectiveGroups;
268 protected $mImplicitGroups;
270 protected $mFormerGroups;
272 protected $mBlockedGlobally;
274 protected $mLocked;
276 public $mHideName;
278 public $mOptions;
281 * @var WebRequest
283 private $mRequest;
285 /** @var Block */
286 public $mBlock;
288 /** @var bool */
289 protected $mAllowUsertalk;
291 /** @var Block */
292 private $mBlockedFromCreateAccount = false;
294 /** @var array */
295 private $mWatchedItems = array();
297 public static $idCacheByName = array();
300 * Lightweight constructor for an anonymous user.
301 * Use the User::newFrom* factory functions for other kinds of users.
303 * @see newFromName()
304 * @see newFromId()
305 * @see newFromConfirmationCode()
306 * @see newFromSession()
307 * @see newFromRow()
309 public function __construct() {
310 $this->clearInstanceCache( 'defaults' );
314 * @return string
316 public function __toString() {
317 return $this->getName();
321 * Load the user table data for this object from the source given by mFrom.
323 public function load() {
324 if ( $this->mLoadedItems === true ) {
325 return;
328 // Set it now to avoid infinite recursion in accessors
329 $this->mLoadedItems = true;
331 switch ( $this->mFrom ) {
332 case 'defaults':
333 $this->loadDefaults();
334 break;
335 case 'name':
336 $this->mId = self::idFromName( $this->mName );
337 if ( !$this->mId ) {
338 // Nonexistent user placeholder object
339 $this->loadDefaults( $this->mName );
340 } else {
341 $this->loadFromId();
343 break;
344 case 'id':
345 $this->loadFromId();
346 break;
347 case 'session':
348 if ( !$this->loadFromSession() ) {
349 // Loading from session failed. Load defaults.
350 $this->loadDefaults();
352 Hooks::run( 'UserLoadAfterLoadFromSession', array( $this ) );
353 break;
354 default:
355 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
360 * Load user table data, given mId has already been set.
361 * @return bool False if the ID does not exist, true otherwise
363 public function loadFromId() {
364 if ( $this->mId == 0 ) {
365 $this->loadDefaults();
366 return false;
369 // Try cache
370 $cache = $this->loadFromCache();
371 if ( !$cache ) {
372 wfDebug( "User: cache miss for user {$this->mId}\n" );
373 // Load from DB
374 if ( !$this->loadFromDatabase() ) {
375 // Can't load from ID, user is anonymous
376 return false;
378 $this->saveToCache();
381 $this->mLoadedItems = true;
383 return true;
387 * Load user data from shared cache, given mId has already been set.
389 * @return bool false if the ID does not exist or data is invalid, true otherwise
390 * @since 1.25
392 public function loadFromCache() {
393 global $wgMemc;
395 if ( $this->mId == 0 ) {
396 $this->loadDefaults();
397 return false;
400 $key = wfMemcKey( 'user', 'id', $this->mId );
401 $data = $wgMemc->get( $key );
402 if ( !is_array( $data ) || $data['mVersion'] < self::VERSION ) {
403 // Object is expired
404 return false;
407 wfDebug( "User: got user {$this->mId} from cache\n" );
409 // Restore from cache
410 foreach ( self::$mCacheVars as $name ) {
411 $this->$name = $data[$name];
414 return true;
418 * Save user data to the shared cache
420 public function saveToCache() {
421 $this->load();
422 $this->loadGroups();
423 $this->loadOptions();
424 if ( $this->isAnon() ) {
425 // Anonymous users are uncached
426 return;
428 $data = array();
429 foreach ( self::$mCacheVars as $name ) {
430 $data[$name] = $this->$name;
432 $data['mVersion'] = self::VERSION;
433 $key = wfMemcKey( 'user', 'id', $this->mId );
434 global $wgMemc;
435 $wgMemc->set( $key, $data );
438 /** @name newFrom*() static factory methods */
439 //@{
442 * Static factory method for creation from username.
444 * This is slightly less efficient than newFromId(), so use newFromId() if
445 * you have both an ID and a name handy.
447 * @param string $name Username, validated by Title::newFromText()
448 * @param string|bool $validate Validate username. Takes the same parameters as
449 * User::getCanonicalName(), except that true is accepted as an alias
450 * for 'valid', for BC.
452 * @return User|bool User object, or false if the username is invalid
453 * (e.g. if it contains illegal characters or is an IP address). If the
454 * username is not present in the database, the result will be a user object
455 * with a name, zero user ID and default settings.
457 public static function newFromName( $name, $validate = 'valid' ) {
458 if ( $validate === true ) {
459 $validate = 'valid';
461 $name = self::getCanonicalName( $name, $validate );
462 if ( $name === false ) {
463 return false;
464 } else {
465 // Create unloaded user object
466 $u = new User;
467 $u->mName = $name;
468 $u->mFrom = 'name';
469 $u->setItemLoaded( 'name' );
470 return $u;
475 * Static factory method for creation from a given user ID.
477 * @param int $id Valid user ID
478 * @return User The corresponding User object
480 public static function newFromId( $id ) {
481 $u = new User;
482 $u->mId = $id;
483 $u->mFrom = 'id';
484 $u->setItemLoaded( 'id' );
485 return $u;
489 * Factory method to fetch whichever user has a given email confirmation code.
490 * This code is generated when an account is created or its e-mail address
491 * has changed.
493 * If the code is invalid or has expired, returns NULL.
495 * @param string $code Confirmation code
496 * @return User|null
498 public static function newFromConfirmationCode( $code ) {
499 $dbr = wfGetDB( DB_SLAVE );
500 $id = $dbr->selectField( 'user', 'user_id', array(
501 'user_email_token' => md5( $code ),
502 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
503 ) );
504 if ( $id !== false ) {
505 return User::newFromId( $id );
506 } else {
507 return null;
512 * Create a new user object using data from session or cookies. If the
513 * login credentials are invalid, the result is an anonymous user.
515 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
516 * @return User
518 public static function newFromSession( WebRequest $request = null ) {
519 $user = new User;
520 $user->mFrom = 'session';
521 $user->mRequest = $request;
522 return $user;
526 * Create a new user object from a user row.
527 * The row should have the following fields from the user table in it:
528 * - either user_name or user_id to load further data if needed (or both)
529 * - user_real_name
530 * - all other fields (email, password, etc.)
531 * It is useless to provide the remaining fields if either user_id,
532 * user_name and user_real_name are not provided because the whole row
533 * will be loaded once more from the database when accessing them.
535 * @param stdClass $row A row from the user table
536 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
537 * @return User
539 public static function newFromRow( $row, $data = null ) {
540 $user = new User;
541 $user->loadFromRow( $row, $data );
542 return $user;
545 //@}
548 * Get the username corresponding to a given user ID
549 * @param int $id User ID
550 * @return string|bool The corresponding username
552 public static function whoIs( $id ) {
553 return UserCache::singleton()->getProp( $id, 'name' );
557 * Get the real name of a user given their user ID
559 * @param int $id User ID
560 * @return string|bool The corresponding user's real name
562 public static function whoIsReal( $id ) {
563 return UserCache::singleton()->getProp( $id, 'real_name' );
567 * Get database id given a user name
568 * @param string $name Username
569 * @return int|null The corresponding user's ID, or null if user is nonexistent
571 public static function idFromName( $name ) {
572 $nt = Title::makeTitleSafe( NS_USER, $name );
573 if ( is_null( $nt ) ) {
574 // Illegal name
575 return null;
578 if ( isset( self::$idCacheByName[$name] ) ) {
579 return self::$idCacheByName[$name];
582 $dbr = wfGetDB( DB_SLAVE );
583 $s = $dbr->selectRow(
584 'user',
585 array( 'user_id' ),
586 array( 'user_name' => $nt->getText() ),
587 __METHOD__
590 if ( $s === false ) {
591 $result = null;
592 } else {
593 $result = $s->user_id;
596 self::$idCacheByName[$name] = $result;
598 if ( count( self::$idCacheByName ) > 1000 ) {
599 self::$idCacheByName = array();
602 return $result;
606 * Reset the cache used in idFromName(). For use in tests.
608 public static function resetIdByNameCache() {
609 self::$idCacheByName = array();
613 * Does the string match an anonymous IPv4 address?
615 * This function exists for username validation, in order to reject
616 * usernames which are similar in form to IP addresses. Strings such
617 * as 300.300.300.300 will return true because it looks like an IP
618 * address, despite not being strictly valid.
620 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
621 * address because the usemod software would "cloak" anonymous IP
622 * addresses like this, if we allowed accounts like this to be created
623 * new users could get the old edits of these anonymous users.
625 * @param string $name Name to match
626 * @return bool
628 public static function isIP( $name ) {
629 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
630 || IP::isIPv6( $name );
634 * Is the input a valid username?
636 * Checks if the input is a valid username, we don't want an empty string,
637 * an IP address, anything that contains slashes (would mess up subpages),
638 * is longer than the maximum allowed username size or doesn't begin with
639 * a capital letter.
641 * @param string $name Name to match
642 * @return bool
644 public static function isValidUserName( $name ) {
645 global $wgContLang, $wgMaxNameChars;
647 if ( $name == ''
648 || User::isIP( $name )
649 || strpos( $name, '/' ) !== false
650 || strlen( $name ) > $wgMaxNameChars
651 || $name != $wgContLang->ucfirst( $name )
653 wfDebugLog( 'username', __METHOD__ .
654 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
655 return false;
658 // Ensure that the name can't be misresolved as a different title,
659 // such as with extra namespace keys at the start.
660 $parsed = Title::newFromText( $name );
661 if ( is_null( $parsed )
662 || $parsed->getNamespace()
663 || strcmp( $name, $parsed->getPrefixedText() ) ) {
664 wfDebugLog( 'username', __METHOD__ .
665 ": '$name' invalid due to ambiguous prefixes" );
666 return false;
669 // Check an additional blacklist of troublemaker characters.
670 // Should these be merged into the title char list?
671 $unicodeBlacklist = '/[' .
672 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
673 '\x{00a0}' . # non-breaking space
674 '\x{2000}-\x{200f}' . # various whitespace
675 '\x{2028}-\x{202f}' . # breaks and control chars
676 '\x{3000}' . # ideographic space
677 '\x{e000}-\x{f8ff}' . # private use
678 ']/u';
679 if ( preg_match( $unicodeBlacklist, $name ) ) {
680 wfDebugLog( 'username', __METHOD__ .
681 ": '$name' invalid due to blacklisted characters" );
682 return false;
685 return true;
689 * Usernames which fail to pass this function will be blocked
690 * from user login and new account registrations, but may be used
691 * internally by batch processes.
693 * If an account already exists in this form, login will be blocked
694 * by a failure to pass this function.
696 * @param string $name Name to match
697 * @return bool
699 public static function isUsableName( $name ) {
700 global $wgReservedUsernames;
701 // Must be a valid username, obviously ;)
702 if ( !self::isValidUserName( $name ) ) {
703 return false;
706 static $reservedUsernames = false;
707 if ( !$reservedUsernames ) {
708 $reservedUsernames = $wgReservedUsernames;
709 Hooks::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
712 // Certain names may be reserved for batch processes.
713 foreach ( $reservedUsernames as $reserved ) {
714 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
715 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
717 if ( $reserved == $name ) {
718 return false;
721 return true;
725 * Usernames which fail to pass this function will be blocked
726 * from new account registrations, but may be used internally
727 * either by batch processes or by user accounts which have
728 * already been created.
730 * Additional blacklisting may be added here rather than in
731 * isValidUserName() to avoid disrupting existing accounts.
733 * @param string $name String to match
734 * @return bool
736 public static function isCreatableName( $name ) {
737 global $wgInvalidUsernameCharacters;
739 // Ensure that the username isn't longer than 235 bytes, so that
740 // (at least for the builtin skins) user javascript and css files
741 // will work. (bug 23080)
742 if ( strlen( $name ) > 235 ) {
743 wfDebugLog( 'username', __METHOD__ .
744 ": '$name' invalid due to length" );
745 return false;
748 // Preg yells if you try to give it an empty string
749 if ( $wgInvalidUsernameCharacters !== '' ) {
750 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
751 wfDebugLog( 'username', __METHOD__ .
752 ": '$name' invalid due to wgInvalidUsernameCharacters" );
753 return false;
757 return self::isUsableName( $name );
761 * Is the input a valid password for this user?
763 * @param string $password Desired password
764 * @return bool
766 public function isValidPassword( $password ) {
767 //simple boolean wrapper for getPasswordValidity
768 return $this->getPasswordValidity( $password ) === true;
773 * Given unvalidated password input, return error message on failure.
775 * @param string $password Desired password
776 * @return bool|string|array True on success, string or array of error message on failure
778 public function getPasswordValidity( $password ) {
779 $result = $this->checkPasswordValidity( $password );
780 if ( $result->isGood() ) {
781 return true;
782 } else {
783 $messages = array();
784 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
785 $messages[] = $error['message'];
787 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
788 $messages[] = $warning['message'];
790 if ( count( $messages ) === 1 ) {
791 return $messages[0];
793 return $messages;
798 * Check if this is a valid password for this user. Status will be good if
799 * the password is valid, or have an array of error messages if not.
801 * @param string $password Desired password
802 * @return Status
803 * @since 1.23
805 public function checkPasswordValidity( $password ) {
806 global $wgMinimalPasswordLength, $wgContLang;
808 static $blockedLogins = array(
809 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
810 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
813 $status = Status::newGood();
815 $result = false; //init $result to false for the internal checks
817 if ( !Hooks::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
818 $status->error( $result );
819 return $status;
822 if ( $result === false ) {
823 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
824 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
825 return $status;
826 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) {
827 $status->error( 'password-name-match' );
828 return $status;
829 } elseif ( isset( $blockedLogins[$this->getName()] )
830 && $password == $blockedLogins[$this->getName()]
832 $status->error( 'password-login-forbidden' );
833 return $status;
834 } else {
835 //it seems weird returning a Good status here, but this is because of the
836 //initialization of $result to false above. If the hook is never run or it
837 //doesn't modify $result, then we will likely get down into this if with
838 //a valid password.
839 return $status;
841 } elseif ( $result === true ) {
842 return $status;
843 } else {
844 $status->error( $result );
845 return $status; //the isValidPassword hook set a string $result and returned true
850 * Expire a user's password
851 * @since 1.23
852 * @param int $ts Optional timestamp to convert, default 0 for the current time
854 public function expirePassword( $ts = 0 ) {
855 $this->loadPasswords();
856 $timestamp = wfTimestamp( TS_MW, $ts );
857 $this->mPasswordExpires = $timestamp;
858 $this->saveSettings();
862 * Clear the password expiration for a user
863 * @since 1.23
864 * @param bool $load Ensure user object is loaded first
866 public function resetPasswordExpiration( $load = true ) {
867 global $wgPasswordExpirationDays;
868 if ( $load ) {
869 $this->load();
871 $newExpire = null;
872 if ( $wgPasswordExpirationDays ) {
873 $newExpire = wfTimestamp(
874 TS_MW,
875 time() + ( $wgPasswordExpirationDays * 24 * 3600 )
878 // Give extensions a chance to force an expiration
879 Hooks::run( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
880 $this->mPasswordExpires = $newExpire;
884 * Check if the user's password is expired.
885 * TODO: Put this and password length into a PasswordPolicy object
886 * @since 1.23
887 * @return string|bool The expiration type, or false if not expired
888 * hard: A password change is required to login
889 * soft: Allow login, but encourage password change
890 * false: Password is not expired
892 public function getPasswordExpired() {
893 global $wgPasswordExpireGrace;
894 $expired = false;
895 $now = wfTimestamp();
896 $expiration = $this->getPasswordExpireDate();
897 $expUnix = wfTimestamp( TS_UNIX, $expiration );
898 if ( $expiration !== null && $expUnix < $now ) {
899 $expired = ( $expUnix + $wgPasswordExpireGrace < $now ) ? 'hard' : 'soft';
901 return $expired;
905 * Get this user's password expiration date. Since this may be using
906 * the cached User object, we assume that whatever mechanism is setting
907 * the expiration date is also expiring the User cache.
908 * @since 1.23
909 * @return string|bool The datestamp of the expiration, or null if not set
911 public function getPasswordExpireDate() {
912 $this->load();
913 return $this->mPasswordExpires;
917 * Given unvalidated user input, return a canonical username, or false if
918 * the username is invalid.
919 * @param string $name User input
920 * @param string|bool $validate Type of validation to use:
921 * - false No validation
922 * - 'valid' Valid for batch processes
923 * - 'usable' Valid for batch processes and login
924 * - 'creatable' Valid for batch processes, login and account creation
926 * @throws MWException
927 * @return bool|string
929 public static function getCanonicalName( $name, $validate = 'valid' ) {
930 // Force usernames to capital
931 global $wgContLang;
932 $name = $wgContLang->ucfirst( $name );
934 # Reject names containing '#'; these will be cleaned up
935 # with title normalisation, but then it's too late to
936 # check elsewhere
937 if ( strpos( $name, '#' ) !== false ) {
938 return false;
941 // Clean up name according to title rules,
942 // but only when validation is requested (bug 12654)
943 $t = ( $validate !== false ) ?
944 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
945 // Check for invalid titles
946 if ( is_null( $t ) ) {
947 return false;
950 // Reject various classes of invalid names
951 global $wgAuth;
952 $name = $wgAuth->getCanonicalName( $t->getText() );
954 switch ( $validate ) {
955 case false:
956 break;
957 case 'valid':
958 if ( !User::isValidUserName( $name ) ) {
959 $name = false;
961 break;
962 case 'usable':
963 if ( !User::isUsableName( $name ) ) {
964 $name = false;
966 break;
967 case 'creatable':
968 if ( !User::isCreatableName( $name ) ) {
969 $name = false;
971 break;
972 default:
973 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
975 return $name;
979 * Count the number of edits of a user
981 * @param int $uid User ID to check
982 * @return int The user's edit count
984 * @deprecated since 1.21 in favour of User::getEditCount
986 public static function edits( $uid ) {
987 wfDeprecated( __METHOD__, '1.21' );
988 $user = self::newFromId( $uid );
989 return $user->getEditCount();
993 * Return a random password.
995 * @return string New random password
997 public static function randomPassword() {
998 global $wgMinimalPasswordLength;
999 // Decide the final password length based on our min password length,
1000 // stopping at a minimum of 10 chars.
1001 $length = max( 10, $wgMinimalPasswordLength );
1002 // Multiply by 1.25 to get the number of hex characters we need
1003 $length = $length * 1.25;
1004 // Generate random hex chars
1005 $hex = MWCryptRand::generateHex( $length );
1006 // Convert from base 16 to base 32 to get a proper password like string
1007 return wfBaseConvert( $hex, 16, 32 );
1011 * Set cached properties to default.
1013 * @note This no longer clears uncached lazy-initialised properties;
1014 * the constructor does that instead.
1016 * @param string|bool $name
1018 public function loadDefaults( $name = false ) {
1020 $passwordFactory = self::getPasswordFactory();
1022 $this->mId = 0;
1023 $this->mName = $name;
1024 $this->mRealName = '';
1025 $this->mPassword = $passwordFactory->newFromCiphertext( null );
1026 $this->mNewpassword = $passwordFactory->newFromCiphertext( null );
1027 $this->mNewpassTime = null;
1028 $this->mEmail = '';
1029 $this->mOptionOverrides = null;
1030 $this->mOptionsLoaded = false;
1032 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1033 if ( $loggedOut !== null ) {
1034 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
1035 } else {
1036 $this->mTouched = '1'; # Allow any pages to be cached
1039 $this->mToken = null; // Don't run cryptographic functions till we need a token
1040 $this->mEmailAuthenticated = null;
1041 $this->mEmailToken = '';
1042 $this->mEmailTokenExpires = null;
1043 $this->mPasswordExpires = null;
1044 $this->resetPasswordExpiration( false );
1045 $this->mRegistration = wfTimestamp( TS_MW );
1046 $this->mGroups = array();
1048 Hooks::run( 'UserLoadDefaults', array( $this, $name ) );
1053 * Return whether an item has been loaded.
1055 * @param string $item Item to check. Current possibilities:
1056 * - id
1057 * - name
1058 * - realname
1059 * @param string $all 'all' to check if the whole object has been loaded
1060 * or any other string to check if only the item is available (e.g.
1061 * for optimisation)
1062 * @return bool
1064 public function isItemLoaded( $item, $all = 'all' ) {
1065 return ( $this->mLoadedItems === true && $all === 'all' ) ||
1066 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1070 * Set that an item has been loaded
1072 * @param string $item
1074 protected function setItemLoaded( $item ) {
1075 if ( is_array( $this->mLoadedItems ) ) {
1076 $this->mLoadedItems[$item] = true;
1081 * Load user data from the session or login cookie.
1082 * @return bool True if the user is logged in, false otherwise.
1084 private function loadFromSession() {
1085 $result = null;
1086 Hooks::run( 'UserLoadFromSession', array( $this, &$result ) );
1087 if ( $result !== null ) {
1088 return $result;
1091 $request = $this->getRequest();
1093 $cookieId = $request->getCookie( 'UserID' );
1094 $sessId = $request->getSessionData( 'wsUserID' );
1096 if ( $cookieId !== null ) {
1097 $sId = intval( $cookieId );
1098 if ( $sessId !== null && $cookieId != $sessId ) {
1099 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1100 cookie user ID ($sId) don't match!" );
1101 return false;
1103 $request->setSessionData( 'wsUserID', $sId );
1104 } elseif ( $sessId !== null && $sessId != 0 ) {
1105 $sId = $sessId;
1106 } else {
1107 return false;
1110 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1111 $sName = $request->getSessionData( 'wsUserName' );
1112 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1113 $sName = $request->getCookie( 'UserName' );
1114 $request->setSessionData( 'wsUserName', $sName );
1115 } else {
1116 return false;
1119 $proposedUser = User::newFromId( $sId );
1120 if ( !$proposedUser->isLoggedIn() ) {
1121 // Not a valid ID
1122 return false;
1125 global $wgBlockDisablesLogin;
1126 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1127 // User blocked and we've disabled blocked user logins
1128 return false;
1131 if ( $request->getSessionData( 'wsToken' ) ) {
1132 $passwordCorrect =
1133 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1134 $from = 'session';
1135 } elseif ( $request->getCookie( 'Token' ) ) {
1136 # Get the token from DB/cache and clean it up to remove garbage padding.
1137 # This deals with historical problems with bugs and the default column value.
1138 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1139 // Make comparison in constant time (bug 61346)
1140 $passwordCorrect = strlen( $token )
1141 && hash_equals( $token, $request->getCookie( 'Token' ) );
1142 $from = 'cookie';
1143 } else {
1144 // No session or persistent login cookie
1145 return false;
1148 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1149 $this->loadFromUserObject( $proposedUser );
1150 $request->setSessionData( 'wsToken', $this->mToken );
1151 wfDebug( "User: logged in from $from\n" );
1152 return true;
1153 } else {
1154 // Invalid credentials
1155 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1156 return false;
1161 * Load user and user_group data from the database.
1162 * $this->mId must be set, this is how the user is identified.
1164 * @param int $flags Supports User::READ_LOCKING
1165 * @return bool True if the user exists, false if the user is anonymous
1167 public function loadFromDatabase( $flags = 0 ) {
1168 // Paranoia
1169 $this->mId = intval( $this->mId );
1171 // Anonymous user
1172 if ( !$this->mId ) {
1173 $this->loadDefaults();
1174 return false;
1177 $dbr = wfGetDB( DB_MASTER );
1178 $s = $dbr->selectRow(
1179 'user',
1180 self::selectFields(),
1181 array( 'user_id' => $this->mId ),
1182 __METHOD__,
1183 ( $flags & self::READ_LOCKING == self::READ_LOCKING )
1184 ? array( 'LOCK IN SHARE MODE' )
1185 : array()
1188 Hooks::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1190 if ( $s !== false ) {
1191 // Initialise user table data
1192 $this->loadFromRow( $s );
1193 $this->mGroups = null; // deferred
1194 $this->getEditCount(); // revalidation for nulls
1195 return true;
1196 } else {
1197 // Invalid user_id
1198 $this->mId = 0;
1199 $this->loadDefaults();
1200 return false;
1205 * Initialize this object from a row from the user table.
1207 * @param stdClass $row Row from the user table to load.
1208 * @param array $data Further user data to load into the object
1210 * user_groups Array with groups out of the user_groups table
1211 * user_properties Array with properties out of the user_properties table
1213 public function loadFromRow( $row, $data = null ) {
1214 $all = true;
1215 $passwordFactory = self::getPasswordFactory();
1217 $this->mGroups = null; // deferred
1219 if ( isset( $row->user_name ) ) {
1220 $this->mName = $row->user_name;
1221 $this->mFrom = 'name';
1222 $this->setItemLoaded( 'name' );
1223 } else {
1224 $all = false;
1227 if ( isset( $row->user_real_name ) ) {
1228 $this->mRealName = $row->user_real_name;
1229 $this->setItemLoaded( 'realname' );
1230 } else {
1231 $all = false;
1234 if ( isset( $row->user_id ) ) {
1235 $this->mId = intval( $row->user_id );
1236 $this->mFrom = 'id';
1237 $this->setItemLoaded( 'id' );
1238 } else {
1239 $all = false;
1242 if ( isset( $row->user_editcount ) ) {
1243 $this->mEditCount = $row->user_editcount;
1244 } else {
1245 $all = false;
1248 if ( isset( $row->user_password ) ) {
1249 // Check for *really* old password hashes that don't even have a type
1250 // The old hash format was just an md5 hex hash, with no type information
1251 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) {
1252 $row->user_password = ":A:{$this->mId}:{$row->user_password}";
1255 try {
1256 $this->mPassword = $passwordFactory->newFromCiphertext( $row->user_password );
1257 } catch ( PasswordError $e ) {
1258 wfDebug( 'Invalid password hash found in database.' );
1259 $this->mPassword = $passwordFactory->newFromCiphertext( null );
1262 try {
1263 $this->mNewpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword );
1264 } catch ( PasswordError $e ) {
1265 wfDebug( 'Invalid password hash found in database.' );
1266 $this->mNewpassword = $passwordFactory->newFromCiphertext( null );
1269 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
1270 $this->mPasswordExpires = wfTimestampOrNull( TS_MW, $row->user_password_expires );
1273 if ( isset( $row->user_email ) ) {
1274 $this->mEmail = $row->user_email;
1275 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1276 $this->mToken = $row->user_token;
1277 if ( $this->mToken == '' ) {
1278 $this->mToken = null;
1280 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1281 $this->mEmailToken = $row->user_email_token;
1282 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1283 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1284 } else {
1285 $all = false;
1288 if ( $all ) {
1289 $this->mLoadedItems = true;
1292 if ( is_array( $data ) ) {
1293 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1294 $this->mGroups = $data['user_groups'];
1296 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1297 $this->loadOptions( $data['user_properties'] );
1303 * Load the data for this user object from another user object.
1305 * @param User $user
1307 protected function loadFromUserObject( $user ) {
1308 $user->load();
1309 $user->loadGroups();
1310 $user->loadOptions();
1311 foreach ( self::$mCacheVars as $var ) {
1312 $this->$var = $user->$var;
1317 * Load the groups from the database if they aren't already loaded.
1319 private function loadGroups() {
1320 if ( is_null( $this->mGroups ) ) {
1321 $dbr = wfGetDB( DB_MASTER );
1322 $res = $dbr->select( 'user_groups',
1323 array( 'ug_group' ),
1324 array( 'ug_user' => $this->mId ),
1325 __METHOD__ );
1326 $this->mGroups = array();
1327 foreach ( $res as $row ) {
1328 $this->mGroups[] = $row->ug_group;
1334 * Load the user's password hashes from the database
1336 * This is usually called in a scenario where the actual User object was
1337 * loaded from the cache, and then password comparison needs to be performed.
1338 * Password hashes are not stored in memcached.
1340 * @since 1.24
1342 private function loadPasswords() {
1343 if ( $this->getId() !== 0 && ( $this->mPassword === null || $this->mNewpassword === null ) ) {
1344 $this->loadFromRow( wfGetDB( DB_MASTER )->selectRow(
1345 'user',
1346 array( 'user_password', 'user_newpassword', 'user_newpass_time', 'user_password_expires' ),
1347 array( 'user_id' => $this->getId() ),
1348 __METHOD__
1349 ) );
1354 * Add the user to the group if he/she meets given criteria.
1356 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1357 * possible to remove manually via Special:UserRights. In such case it
1358 * will not be re-added automatically. The user will also not lose the
1359 * group if they no longer meet the criteria.
1361 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1363 * @return array Array of groups the user has been promoted to.
1365 * @see $wgAutopromoteOnce
1367 public function addAutopromoteOnceGroups( $event ) {
1368 global $wgAutopromoteOnceLogInRC, $wgAuth;
1370 $toPromote = array();
1371 if ( $this->getId() ) {
1372 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1373 if ( count( $toPromote ) ) {
1374 $oldGroups = $this->getGroups(); // previous groups
1376 foreach ( $toPromote as $group ) {
1377 $this->addGroup( $group );
1379 // update groups in external authentication database
1380 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1382 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1384 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1385 $logEntry->setPerformer( $this );
1386 $logEntry->setTarget( $this->getUserPage() );
1387 $logEntry->setParameters( array(
1388 '4::oldgroups' => $oldGroups,
1389 '5::newgroups' => $newGroups,
1390 ) );
1391 $logid = $logEntry->insert();
1392 if ( $wgAutopromoteOnceLogInRC ) {
1393 $logEntry->publish( $logid );
1397 return $toPromote;
1401 * Clear various cached data stored in this object. The cache of the user table
1402 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1404 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1405 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1407 public function clearInstanceCache( $reloadFrom = false ) {
1408 $this->mNewtalk = -1;
1409 $this->mDatePreference = null;
1410 $this->mBlockedby = -1; # Unset
1411 $this->mHash = false;
1412 $this->mRights = null;
1413 $this->mEffectiveGroups = null;
1414 $this->mImplicitGroups = null;
1415 $this->mGroups = null;
1416 $this->mOptions = null;
1417 $this->mOptionsLoaded = false;
1418 $this->mEditCount = null;
1420 if ( $reloadFrom ) {
1421 $this->mLoadedItems = array();
1422 $this->mFrom = $reloadFrom;
1427 * Combine the language default options with any site-specific options
1428 * and add the default language variants.
1430 * @return array Array of String options
1432 public static function getDefaultOptions() {
1433 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1435 static $defOpt = null;
1436 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1437 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1438 // mid-request and see that change reflected in the return value of this function.
1439 // Which is insane and would never happen during normal MW operation
1440 return $defOpt;
1443 $defOpt = $wgDefaultUserOptions;
1444 // Default language setting
1445 $defOpt['language'] = $wgContLang->getCode();
1446 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1447 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1449 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1450 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1452 $defOpt['skin'] = Skin::normalizeKey( $wgDefaultSkin );
1454 Hooks::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1456 return $defOpt;
1460 * Get a given default option value.
1462 * @param string $opt Name of option to retrieve
1463 * @return string Default option value
1465 public static function getDefaultOption( $opt ) {
1466 $defOpts = self::getDefaultOptions();
1467 if ( isset( $defOpts[$opt] ) ) {
1468 return $defOpts[$opt];
1469 } else {
1470 return null;
1475 * Get blocking information
1476 * @param bool $bFromSlave Whether to check the slave database first.
1477 * To improve performance, non-critical checks are done against slaves.
1478 * Check when actually saving should be done against master.
1480 private function getBlockedStatus( $bFromSlave = true ) {
1481 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1483 if ( -1 != $this->mBlockedby ) {
1484 return;
1487 wfDebug( __METHOD__ . ": checking...\n" );
1489 // Initialize data...
1490 // Otherwise something ends up stomping on $this->mBlockedby when
1491 // things get lazy-loaded later, causing false positive block hits
1492 // due to -1 !== 0. Probably session-related... Nothing should be
1493 // overwriting mBlockedby, surely?
1494 $this->load();
1496 # We only need to worry about passing the IP address to the Block generator if the
1497 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1498 # know which IP address they're actually coming from
1499 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1500 $ip = $this->getRequest()->getIP();
1501 } else {
1502 $ip = null;
1505 // User/IP blocking
1506 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1508 // Proxy blocking
1509 if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1510 && !in_array( $ip, $wgProxyWhitelist )
1512 // Local list
1513 if ( self::isLocallyBlockedProxy( $ip ) ) {
1514 $block = new Block;
1515 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1516 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1517 $block->setTarget( $ip );
1518 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1519 $block = new Block;
1520 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1521 $block->mReason = wfMessage( 'sorbsreason' )->text();
1522 $block->setTarget( $ip );
1526 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1527 if ( !$block instanceof Block
1528 && $wgApplyIpBlocksToXff
1529 && $ip !== null
1530 && !$this->isAllowed( 'proxyunbannable' )
1531 && !in_array( $ip, $wgProxyWhitelist )
1533 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1534 $xff = array_map( 'trim', explode( ',', $xff ) );
1535 $xff = array_diff( $xff, array( $ip ) );
1536 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1537 $block = Block::chooseBlock( $xffblocks, $xff );
1538 if ( $block instanceof Block ) {
1539 # Mangle the reason to alert the user that the block
1540 # originated from matching the X-Forwarded-For header.
1541 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1545 if ( $block instanceof Block ) {
1546 wfDebug( __METHOD__ . ": Found block.\n" );
1547 $this->mBlock = $block;
1548 $this->mBlockedby = $block->getByName();
1549 $this->mBlockreason = $block->mReason;
1550 $this->mHideName = $block->mHideName;
1551 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1552 } else {
1553 $this->mBlockedby = '';
1554 $this->mHideName = 0;
1555 $this->mAllowUsertalk = false;
1558 // Extensions
1559 Hooks::run( 'GetBlockedStatus', array( &$this ) );
1564 * Whether the given IP is in a DNS blacklist.
1566 * @param string $ip IP to check
1567 * @param bool $checkWhitelist Whether to check the whitelist first
1568 * @return bool True if blacklisted.
1570 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1571 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1573 if ( !$wgEnableDnsBlacklist ) {
1574 return false;
1577 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1578 return false;
1581 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1585 * Whether the given IP is in a given DNS blacklist.
1587 * @param string $ip IP to check
1588 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1589 * @return bool True if blacklisted.
1591 public function inDnsBlacklist( $ip, $bases ) {
1593 $found = false;
1594 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1595 if ( IP::isIPv4( $ip ) ) {
1596 // Reverse IP, bug 21255
1597 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1599 foreach ( (array)$bases as $base ) {
1600 // Make hostname
1601 // If we have an access key, use that too (ProjectHoneypot, etc.)
1602 if ( is_array( $base ) ) {
1603 if ( count( $base ) >= 2 ) {
1604 // Access key is 1, base URL is 0
1605 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1606 } else {
1607 $host = "$ipReversed.{$base[0]}";
1609 } else {
1610 $host = "$ipReversed.$base";
1613 // Send query
1614 $ipList = gethostbynamel( $host );
1616 if ( $ipList ) {
1617 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1618 $found = true;
1619 break;
1620 } else {
1621 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1626 return $found;
1630 * Check if an IP address is in the local proxy list
1632 * @param string $ip
1634 * @return bool
1636 public static function isLocallyBlockedProxy( $ip ) {
1637 global $wgProxyList;
1639 if ( !$wgProxyList ) {
1640 return false;
1643 if ( !is_array( $wgProxyList ) ) {
1644 // Load from the specified file
1645 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1648 if ( !is_array( $wgProxyList ) ) {
1649 $ret = false;
1650 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1651 $ret = true;
1652 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1653 // Old-style flipped proxy list
1654 $ret = true;
1655 } else {
1656 $ret = false;
1658 return $ret;
1662 * Is this user subject to rate limiting?
1664 * @return bool True if rate limited
1666 public function isPingLimitable() {
1667 global $wgRateLimitsExcludedIPs;
1668 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1669 // No other good way currently to disable rate limits
1670 // for specific IPs. :P
1671 // But this is a crappy hack and should die.
1672 return false;
1674 return !$this->isAllowed( 'noratelimit' );
1678 * Primitive rate limits: enforce maximum actions per time period
1679 * to put a brake on flooding.
1681 * The method generates both a generic profiling point and a per action one
1682 * (suffix being "-$action".
1684 * @note When using a shared cache like memcached, IP-address
1685 * last-hit counters will be shared across wikis.
1687 * @param string $action Action to enforce; 'edit' if unspecified
1688 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1689 * @return bool True if a rate limiter was tripped
1691 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1692 // Call the 'PingLimiter' hook
1693 $result = false;
1694 if ( !Hooks::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1695 return $result;
1698 global $wgRateLimits;
1699 if ( !isset( $wgRateLimits[$action] ) ) {
1700 return false;
1703 // Some groups shouldn't trigger the ping limiter, ever
1704 if ( !$this->isPingLimitable() ) {
1705 return false;
1708 global $wgMemc;
1709 wfProfileIn( __METHOD__ . '-' . $action );
1711 $limits = $wgRateLimits[$action];
1712 $keys = array();
1713 $id = $this->getId();
1714 $userLimit = false;
1716 if ( isset( $limits['anon'] ) && $id == 0 ) {
1717 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1720 if ( isset( $limits['user'] ) && $id != 0 ) {
1721 $userLimit = $limits['user'];
1723 if ( $this->isNewbie() ) {
1724 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1725 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1727 if ( isset( $limits['ip'] ) ) {
1728 $ip = $this->getRequest()->getIP();
1729 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1731 if ( isset( $limits['subnet'] ) ) {
1732 $ip = $this->getRequest()->getIP();
1733 $matches = array();
1734 $subnet = false;
1735 if ( IP::isIPv6( $ip ) ) {
1736 $parts = IP::parseRange( "$ip/64" );
1737 $subnet = $parts[0];
1738 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1739 // IPv4
1740 $subnet = $matches[1];
1742 if ( $subnet !== false ) {
1743 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1747 // Check for group-specific permissions
1748 // If more than one group applies, use the group with the highest limit
1749 foreach ( $this->getGroups() as $group ) {
1750 if ( isset( $limits[$group] ) ) {
1751 if ( $userLimit === false
1752 || $limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1754 $userLimit = $limits[$group];
1758 // Set the user limit key
1759 if ( $userLimit !== false ) {
1760 list( $max, $period ) = $userLimit;
1761 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1762 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1765 $triggered = false;
1766 foreach ( $keys as $key => $limit ) {
1767 list( $max, $period ) = $limit;
1768 $summary = "(limit $max in {$period}s)";
1769 $count = $wgMemc->get( $key );
1770 // Already pinged?
1771 if ( $count ) {
1772 if ( $count >= $max ) {
1773 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1774 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1775 $triggered = true;
1776 } else {
1777 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1779 } else {
1780 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1781 if ( $incrBy > 0 ) {
1782 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1785 if ( $incrBy > 0 ) {
1786 $wgMemc->incr( $key, $incrBy );
1790 wfProfileOut( __METHOD__ . '-' . $action );
1791 return $triggered;
1795 * Check if user is blocked
1797 * @param bool $bFromSlave Whether to check the slave database instead of
1798 * the master. Hacked from false due to horrible probs on site.
1799 * @return bool True if blocked, false otherwise
1801 public function isBlocked( $bFromSlave = true ) {
1802 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1806 * Get the block affecting the user, or null if the user is not blocked
1808 * @param bool $bFromSlave Whether to check the slave database instead of the master
1809 * @return Block|null
1811 public function getBlock( $bFromSlave = true ) {
1812 $this->getBlockedStatus( $bFromSlave );
1813 return $this->mBlock instanceof Block ? $this->mBlock : null;
1817 * Check if user is blocked from editing a particular article
1819 * @param Title $title Title to check
1820 * @param bool $bFromSlave Whether to check the slave database instead of the master
1821 * @return bool
1823 public function isBlockedFrom( $title, $bFromSlave = false ) {
1824 global $wgBlockAllowsUTEdit;
1826 $blocked = $this->isBlocked( $bFromSlave );
1827 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1828 // If a user's name is suppressed, they cannot make edits anywhere
1829 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
1830 && $title->getNamespace() == NS_USER_TALK ) {
1831 $blocked = false;
1832 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1835 Hooks::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1837 return $blocked;
1841 * If user is blocked, return the name of the user who placed the block
1842 * @return string Name of blocker
1844 public function blockedBy() {
1845 $this->getBlockedStatus();
1846 return $this->mBlockedby;
1850 * If user is blocked, return the specified reason for the block
1851 * @return string Blocking reason
1853 public function blockedFor() {
1854 $this->getBlockedStatus();
1855 return $this->mBlockreason;
1859 * If user is blocked, return the ID for the block
1860 * @return int Block ID
1862 public function getBlockId() {
1863 $this->getBlockedStatus();
1864 return ( $this->mBlock ? $this->mBlock->getId() : false );
1868 * Check if user is blocked on all wikis.
1869 * Do not use for actual edit permission checks!
1870 * This is intended for quick UI checks.
1872 * @param string $ip IP address, uses current client if none given
1873 * @return bool True if blocked, false otherwise
1875 public function isBlockedGlobally( $ip = '' ) {
1876 if ( $this->mBlockedGlobally !== null ) {
1877 return $this->mBlockedGlobally;
1879 // User is already an IP?
1880 if ( IP::isIPAddress( $this->getName() ) ) {
1881 $ip = $this->getName();
1882 } elseif ( !$ip ) {
1883 $ip = $this->getRequest()->getIP();
1885 $blocked = false;
1886 Hooks::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1887 $this->mBlockedGlobally = (bool)$blocked;
1888 return $this->mBlockedGlobally;
1892 * Check if user account is locked
1894 * @return bool True if locked, false otherwise
1896 public function isLocked() {
1897 if ( $this->mLocked !== null ) {
1898 return $this->mLocked;
1900 global $wgAuth;
1901 $authUser = $wgAuth->getUserInstance( $this );
1902 $this->mLocked = (bool)$authUser->isLocked();
1903 return $this->mLocked;
1907 * Check if user account is hidden
1909 * @return bool True if hidden, false otherwise
1911 public function isHidden() {
1912 if ( $this->mHideName !== null ) {
1913 return $this->mHideName;
1915 $this->getBlockedStatus();
1916 if ( !$this->mHideName ) {
1917 global $wgAuth;
1918 $authUser = $wgAuth->getUserInstance( $this );
1919 $this->mHideName = (bool)$authUser->isHidden();
1921 return $this->mHideName;
1925 * Get the user's ID.
1926 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1928 public function getId() {
1929 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
1930 // Special case, we know the user is anonymous
1931 return 0;
1932 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1933 // Don't load if this was initialized from an ID
1934 $this->load();
1936 return $this->mId;
1940 * Set the user and reload all fields according to a given ID
1941 * @param int $v User ID to reload
1943 public function setId( $v ) {
1944 $this->mId = $v;
1945 $this->clearInstanceCache( 'id' );
1949 * Get the user name, or the IP of an anonymous user
1950 * @return string User's name or IP address
1952 public function getName() {
1953 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1954 // Special case optimisation
1955 return $this->mName;
1956 } else {
1957 $this->load();
1958 if ( $this->mName === false ) {
1959 // Clean up IPs
1960 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
1962 return $this->mName;
1967 * Set the user name.
1969 * This does not reload fields from the database according to the given
1970 * name. Rather, it is used to create a temporary "nonexistent user" for
1971 * later addition to the database. It can also be used to set the IP
1972 * address for an anonymous user to something other than the current
1973 * remote IP.
1975 * @note User::newFromName() has roughly the same function, when the named user
1976 * does not exist.
1977 * @param string $str New user name to set
1979 public function setName( $str ) {
1980 $this->load();
1981 $this->mName = $str;
1985 * Get the user's name escaped by underscores.
1986 * @return string Username escaped by underscores.
1988 public function getTitleKey() {
1989 return str_replace( ' ', '_', $this->getName() );
1993 * Check if the user has new messages.
1994 * @return bool True if the user has new messages
1996 public function getNewtalk() {
1997 $this->load();
1999 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2000 if ( $this->mNewtalk === -1 ) {
2001 $this->mNewtalk = false; # reset talk page status
2003 // Check memcached separately for anons, who have no
2004 // entire User object stored in there.
2005 if ( !$this->mId ) {
2006 global $wgDisableAnonTalk;
2007 if ( $wgDisableAnonTalk ) {
2008 // Anon newtalk disabled by configuration.
2009 $this->mNewtalk = false;
2010 } else {
2011 global $wgMemc;
2012 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
2013 $newtalk = $wgMemc->get( $key );
2014 if ( strval( $newtalk ) !== '' ) {
2015 $this->mNewtalk = (bool)$newtalk;
2016 } else {
2017 // Since we are caching this, make sure it is up to date by getting it
2018 // from the master
2019 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
2020 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
2023 } else {
2024 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
2028 return (bool)$this->mNewtalk;
2032 * Return the data needed to construct links for new talk page message
2033 * alerts. If there are new messages, this will return an associative array
2034 * with the following data:
2035 * wiki: The database name of the wiki
2036 * link: Root-relative link to the user's talk page
2037 * rev: The last talk page revision that the user has seen or null. This
2038 * is useful for building diff links.
2039 * If there are no new messages, it returns an empty array.
2040 * @note This function was designed to accomodate multiple talk pages, but
2041 * currently only returns a single link and revision.
2042 * @return array
2044 public function getNewMessageLinks() {
2045 $talks = array();
2046 if ( !Hooks::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2047 return $talks;
2048 } elseif ( !$this->getNewtalk() ) {
2049 return array();
2051 $utp = $this->getTalkPage();
2052 $dbr = wfGetDB( DB_SLAVE );
2053 // Get the "last viewed rev" timestamp from the oldest message notification
2054 $timestamp = $dbr->selectField( 'user_newtalk',
2055 'MIN(user_last_timestamp)',
2056 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2057 __METHOD__ );
2058 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2059 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2063 * Get the revision ID for the last talk page revision viewed by the talk
2064 * page owner.
2065 * @return int|null Revision ID or null
2067 public function getNewMessageRevisionId() {
2068 $newMessageRevisionId = null;
2069 $newMessageLinks = $this->getNewMessageLinks();
2070 if ( $newMessageLinks ) {
2071 // Note: getNewMessageLinks() never returns more than a single link
2072 // and it is always for the same wiki, but we double-check here in
2073 // case that changes some time in the future.
2074 if ( count( $newMessageLinks ) === 1
2075 && $newMessageLinks[0]['wiki'] === wfWikiID()
2076 && $newMessageLinks[0]['rev']
2078 $newMessageRevision = $newMessageLinks[0]['rev'];
2079 $newMessageRevisionId = $newMessageRevision->getId();
2082 return $newMessageRevisionId;
2086 * Internal uncached check for new messages
2088 * @see getNewtalk()
2089 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2090 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2091 * @param bool $fromMaster True to fetch from the master, false for a slave
2092 * @return bool True if the user has new messages
2094 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2095 if ( $fromMaster ) {
2096 $db = wfGetDB( DB_MASTER );
2097 } else {
2098 $db = wfGetDB( DB_SLAVE );
2100 $ok = $db->selectField( 'user_newtalk', $field,
2101 array( $field => $id ), __METHOD__ );
2102 return $ok !== false;
2106 * Add or update the new messages flag
2107 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2108 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2109 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2110 * @return bool True if successful, false otherwise
2112 protected function updateNewtalk( $field, $id, $curRev = null ) {
2113 // Get timestamp of the talk page revision prior to the current one
2114 $prevRev = $curRev ? $curRev->getPrevious() : false;
2115 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2116 // Mark the user as having new messages since this revision
2117 $dbw = wfGetDB( DB_MASTER );
2118 $dbw->insert( 'user_newtalk',
2119 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2120 __METHOD__,
2121 'IGNORE' );
2122 if ( $dbw->affectedRows() ) {
2123 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2124 return true;
2125 } else {
2126 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2127 return false;
2132 * Clear the new messages flag for the given user
2133 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2134 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2135 * @return bool True if successful, false otherwise
2137 protected function deleteNewtalk( $field, $id ) {
2138 $dbw = wfGetDB( DB_MASTER );
2139 $dbw->delete( 'user_newtalk',
2140 array( $field => $id ),
2141 __METHOD__ );
2142 if ( $dbw->affectedRows() ) {
2143 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2144 return true;
2145 } else {
2146 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2147 return false;
2152 * Update the 'You have new messages!' status.
2153 * @param bool $val Whether the user has new messages
2154 * @param Revision $curRev New, as yet unseen revision of the user talk
2155 * page. Ignored if null or !$val.
2157 public function setNewtalk( $val, $curRev = null ) {
2158 if ( wfReadOnly() ) {
2159 return;
2162 $this->load();
2163 $this->mNewtalk = $val;
2165 if ( $this->isAnon() ) {
2166 $field = 'user_ip';
2167 $id = $this->getName();
2168 } else {
2169 $field = 'user_id';
2170 $id = $this->getId();
2172 global $wgMemc;
2174 if ( $val ) {
2175 $changed = $this->updateNewtalk( $field, $id, $curRev );
2176 } else {
2177 $changed = $this->deleteNewtalk( $field, $id );
2180 if ( $this->isAnon() ) {
2181 // Anons have a separate memcached space, since
2182 // user records aren't kept for them.
2183 $key = wfMemcKey( 'newtalk', 'ip', $id );
2184 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
2186 if ( $changed ) {
2187 $this->invalidateCache();
2192 * Generate a current or new-future timestamp to be stored in the
2193 * user_touched field when we update things.
2194 * @return string Timestamp in TS_MW format
2196 private static function newTouchedTimestamp() {
2197 global $wgClockSkewFudge;
2198 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2202 * Clear user data from memcached.
2203 * Use after applying fun updates to the database; caller's
2204 * responsibility to update user_touched if appropriate.
2206 * Called implicitly from invalidateCache() and saveSettings().
2208 public function clearSharedCache() {
2209 $this->load();
2210 if ( $this->mId ) {
2211 global $wgMemc;
2212 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
2217 * Immediately touch the user data cache for this account.
2218 * Updates user_touched field, and removes account data from memcached
2219 * for reload on the next hit.
2221 public function invalidateCache() {
2222 if ( wfReadOnly() ) {
2223 return;
2225 $this->load();
2226 if ( $this->mId ) {
2227 $this->mTouched = self::newTouchedTimestamp();
2229 $dbw = wfGetDB( DB_MASTER );
2230 $userid = $this->mId;
2231 $touched = $this->mTouched;
2232 $method = __METHOD__;
2233 $dbw->onTransactionIdle( function () use ( $dbw, $userid, $touched, $method ) {
2234 // Prevent contention slams by checking user_touched first
2235 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2236 $needsPurge = $dbw->selectField( 'user', '1',
2237 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2238 if ( $needsPurge ) {
2239 $dbw->update( 'user',
2240 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2241 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2242 $method
2245 } );
2246 $this->clearSharedCache();
2251 * Validate the cache for this account.
2252 * @param string $timestamp A timestamp in TS_MW format
2253 * @return bool
2255 public function validateCache( $timestamp ) {
2256 $this->load();
2257 return ( $timestamp >= $this->mTouched );
2261 * Get the user touched timestamp
2262 * @return string Timestamp
2264 public function getTouched() {
2265 $this->load();
2266 return $this->mTouched;
2270 * @return Password
2271 * @since 1.24
2273 public function getPassword() {
2274 $this->loadPasswords();
2276 return $this->mPassword;
2280 * @return Password
2281 * @since 1.24
2283 public function getTemporaryPassword() {
2284 $this->loadPasswords();
2286 return $this->mNewpassword;
2290 * Set the password and reset the random token.
2291 * Calls through to authentication plugin if necessary;
2292 * will have no effect if the auth plugin refuses to
2293 * pass the change through or if the legal password
2294 * checks fail.
2296 * As a special case, setting the password to null
2297 * wipes it, so the account cannot be logged in until
2298 * a new password is set, for instance via e-mail.
2300 * @param string $str New password to set
2301 * @throws PasswordError On failure
2303 * @return bool
2305 public function setPassword( $str ) {
2306 global $wgAuth;
2308 $this->loadPasswords();
2310 if ( $str !== null ) {
2311 if ( !$wgAuth->allowPasswordChange() ) {
2312 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2315 if ( !$this->isValidPassword( $str ) ) {
2316 global $wgMinimalPasswordLength;
2317 $valid = $this->getPasswordValidity( $str );
2318 if ( is_array( $valid ) ) {
2319 $message = array_shift( $valid );
2320 $params = $valid;
2321 } else {
2322 $message = $valid;
2323 $params = array( $wgMinimalPasswordLength );
2325 throw new PasswordError( wfMessage( $message, $params )->text() );
2329 if ( !$wgAuth->setPassword( $this, $str ) ) {
2330 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2333 $this->setInternalPassword( $str );
2335 return true;
2339 * Set the password and reset the random token unconditionally.
2341 * @param string|null $str New password to set or null to set an invalid
2342 * password hash meaning that the user will not be able to log in
2343 * through the web interface.
2345 public function setInternalPassword( $str ) {
2346 $this->setToken();
2348 $passwordFactory = self::getPasswordFactory();
2349 $this->mPassword = $passwordFactory->newFromPlaintext( $str );
2351 $this->mNewpassword = $passwordFactory->newFromCiphertext( null );
2352 $this->mNewpassTime = null;
2356 * Get the user's current token.
2357 * @param bool $forceCreation Force the generation of a new token if the
2358 * user doesn't have one (default=true for backwards compatibility).
2359 * @return string Token
2361 public function getToken( $forceCreation = true ) {
2362 $this->load();
2363 if ( !$this->mToken && $forceCreation ) {
2364 $this->setToken();
2366 return $this->mToken;
2370 * Set the random token (used for persistent authentication)
2371 * Called from loadDefaults() among other places.
2373 * @param string|bool $token If specified, set the token to this value
2375 public function setToken( $token = false ) {
2376 $this->load();
2377 if ( !$token ) {
2378 $this->mToken = MWCryptRand::generateHex( self::TOKEN_LENGTH );
2379 } else {
2380 $this->mToken = $token;
2385 * Set the password for a password reminder or new account email
2387 * @param string $str New password to set or null to set an invalid
2388 * password hash meaning that the user will not be able to use it
2389 * @param bool $throttle If true, reset the throttle timestamp to the present
2391 public function setNewpassword( $str, $throttle = true ) {
2392 $this->loadPasswords();
2394 $this->mNewpassword = self::getPasswordFactory()->newFromPlaintext( $str );
2395 if ( $str === null ) {
2396 $this->mNewpassTime = null;
2397 } elseif ( $throttle ) {
2398 $this->mNewpassTime = wfTimestampNow();
2403 * Has password reminder email been sent within the last
2404 * $wgPasswordReminderResendTime hours?
2405 * @return bool
2407 public function isPasswordReminderThrottled() {
2408 global $wgPasswordReminderResendTime;
2409 $this->load();
2410 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
2411 return false;
2413 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
2414 return time() < $expiry;
2418 * Get the user's e-mail address
2419 * @return string User's email address
2421 public function getEmail() {
2422 $this->load();
2423 Hooks::run( 'UserGetEmail', array( $this, &$this->mEmail ) );
2424 return $this->mEmail;
2428 * Get the timestamp of the user's e-mail authentication
2429 * @return string TS_MW timestamp
2431 public function getEmailAuthenticationTimestamp() {
2432 $this->load();
2433 Hooks::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2434 return $this->mEmailAuthenticated;
2438 * Set the user's e-mail address
2439 * @param string $str New e-mail address
2441 public function setEmail( $str ) {
2442 $this->load();
2443 if ( $str == $this->mEmail ) {
2444 return;
2446 $this->invalidateEmail();
2447 $this->mEmail = $str;
2448 Hooks::run( 'UserSetEmail', array( $this, &$this->mEmail ) );
2452 * Set the user's e-mail address and a confirmation mail if needed.
2454 * @since 1.20
2455 * @param string $str New e-mail address
2456 * @return Status
2458 public function setEmailWithConfirmation( $str ) {
2459 global $wgEnableEmail, $wgEmailAuthentication;
2461 if ( !$wgEnableEmail ) {
2462 return Status::newFatal( 'emaildisabled' );
2465 $oldaddr = $this->getEmail();
2466 if ( $str === $oldaddr ) {
2467 return Status::newGood( true );
2470 $this->setEmail( $str );
2472 if ( $str !== '' && $wgEmailAuthentication ) {
2473 // Send a confirmation request to the new address if needed
2474 $type = $oldaddr != '' ? 'changed' : 'set';
2475 $result = $this->sendConfirmationMail( $type );
2476 if ( $result->isGood() ) {
2477 // Say to the caller that a confirmation mail has been sent
2478 $result->value = 'eauth';
2480 } else {
2481 $result = Status::newGood( true );
2484 return $result;
2488 * Get the user's real name
2489 * @return string User's real name
2491 public function getRealName() {
2492 if ( !$this->isItemLoaded( 'realname' ) ) {
2493 $this->load();
2496 return $this->mRealName;
2500 * Set the user's real name
2501 * @param string $str New real name
2503 public function setRealName( $str ) {
2504 $this->load();
2505 $this->mRealName = $str;
2509 * Get the user's current setting for a given option.
2511 * @param string $oname The option to check
2512 * @param string $defaultOverride A default value returned if the option does not exist
2513 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2514 * @return string User's current value for the option
2515 * @see getBoolOption()
2516 * @see getIntOption()
2518 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2519 global $wgHiddenPrefs;
2520 $this->loadOptions();
2522 # We want 'disabled' preferences to always behave as the default value for
2523 # users, even if they have set the option explicitly in their settings (ie they
2524 # set it, and then it was disabled removing their ability to change it). But
2525 # we don't want to erase the preferences in the database in case the preference
2526 # is re-enabled again. So don't touch $mOptions, just override the returned value
2527 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2528 return self::getDefaultOption( $oname );
2531 if ( array_key_exists( $oname, $this->mOptions ) ) {
2532 return $this->mOptions[$oname];
2533 } else {
2534 return $defaultOverride;
2539 * Get all user's options
2541 * @param int $flags Bitwise combination of:
2542 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2543 * to the default value. (Since 1.25)
2544 * @return array
2546 public function getOptions( $flags = 0 ) {
2547 global $wgHiddenPrefs;
2548 $this->loadOptions();
2549 $options = $this->mOptions;
2551 # We want 'disabled' preferences to always behave as the default value for
2552 # users, even if they have set the option explicitly in their settings (ie they
2553 # set it, and then it was disabled removing their ability to change it). But
2554 # we don't want to erase the preferences in the database in case the preference
2555 # is re-enabled again. So don't touch $mOptions, just override the returned value
2556 foreach ( $wgHiddenPrefs as $pref ) {
2557 $default = self::getDefaultOption( $pref );
2558 if ( $default !== null ) {
2559 $options[$pref] = $default;
2563 if ( $flags & self::GETOPTIONS_EXCLUDE_DEFAULTS ) {
2564 $options = array_diff_assoc( $options, self::getDefaultOptions() );
2567 return $options;
2571 * Get the user's current setting for a given option, as a boolean value.
2573 * @param string $oname The option to check
2574 * @return bool User's current value for the option
2575 * @see getOption()
2577 public function getBoolOption( $oname ) {
2578 return (bool)$this->getOption( $oname );
2582 * Get the user's current setting for a given option, as an integer value.
2584 * @param string $oname The option to check
2585 * @param int $defaultOverride A default value returned if the option does not exist
2586 * @return int User's current value for the option
2587 * @see getOption()
2589 public function getIntOption( $oname, $defaultOverride = 0 ) {
2590 $val = $this->getOption( $oname );
2591 if ( $val == '' ) {
2592 $val = $defaultOverride;
2594 return intval( $val );
2598 * Set the given option for a user.
2600 * You need to call saveSettings() to actually write to the database.
2602 * @param string $oname The option to set
2603 * @param mixed $val New value to set
2605 public function setOption( $oname, $val ) {
2606 $this->loadOptions();
2608 // Explicitly NULL values should refer to defaults
2609 if ( is_null( $val ) ) {
2610 $val = self::getDefaultOption( $oname );
2613 $this->mOptions[$oname] = $val;
2617 * Get a token stored in the preferences (like the watchlist one),
2618 * resetting it if it's empty (and saving changes).
2620 * @param string $oname The option name to retrieve the token from
2621 * @return string|bool User's current value for the option, or false if this option is disabled.
2622 * @see resetTokenFromOption()
2623 * @see getOption()
2625 public function getTokenFromOption( $oname ) {
2626 global $wgHiddenPrefs;
2627 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2628 return false;
2631 $token = $this->getOption( $oname );
2632 if ( !$token ) {
2633 $token = $this->resetTokenFromOption( $oname );
2634 $this->saveSettings();
2636 return $token;
2640 * Reset a token stored in the preferences (like the watchlist one).
2641 * *Does not* save user's preferences (similarly to setOption()).
2643 * @param string $oname The option name to reset the token in
2644 * @return string|bool New token value, or false if this option is disabled.
2645 * @see getTokenFromOption()
2646 * @see setOption()
2648 public function resetTokenFromOption( $oname ) {
2649 global $wgHiddenPrefs;
2650 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2651 return false;
2654 $token = MWCryptRand::generateHex( 40 );
2655 $this->setOption( $oname, $token );
2656 return $token;
2660 * Return a list of the types of user options currently returned by
2661 * User::getOptionKinds().
2663 * Currently, the option kinds are:
2664 * - 'registered' - preferences which are registered in core MediaWiki or
2665 * by extensions using the UserGetDefaultOptions hook.
2666 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2667 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2668 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2669 * be used by user scripts.
2670 * - 'special' - "preferences" that are not accessible via User::getOptions
2671 * or User::setOptions.
2672 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2673 * These are usually legacy options, removed in newer versions.
2675 * The API (and possibly others) use this function to determine the possible
2676 * option types for validation purposes, so make sure to update this when a
2677 * new option kind is added.
2679 * @see User::getOptionKinds
2680 * @return array Option kinds
2682 public static function listOptionKinds() {
2683 return array(
2684 'registered',
2685 'registered-multiselect',
2686 'registered-checkmatrix',
2687 'userjs',
2688 'special',
2689 'unused'
2694 * Return an associative array mapping preferences keys to the kind of a preference they're
2695 * used for. Different kinds are handled differently when setting or reading preferences.
2697 * See User::listOptionKinds for the list of valid option types that can be provided.
2699 * @see User::listOptionKinds
2700 * @param IContextSource $context
2701 * @param array $options Assoc. array with options keys to check as keys.
2702 * Defaults to $this->mOptions.
2703 * @return array The key => kind mapping data
2705 public function getOptionKinds( IContextSource $context, $options = null ) {
2706 $this->loadOptions();
2707 if ( $options === null ) {
2708 $options = $this->mOptions;
2711 $prefs = Preferences::getPreferences( $this, $context );
2712 $mapping = array();
2714 // Pull out the "special" options, so they don't get converted as
2715 // multiselect or checkmatrix.
2716 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
2717 foreach ( $specialOptions as $name => $value ) {
2718 unset( $prefs[$name] );
2721 // Multiselect and checkmatrix options are stored in the database with
2722 // one key per option, each having a boolean value. Extract those keys.
2723 $multiselectOptions = array();
2724 foreach ( $prefs as $name => $info ) {
2725 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2726 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2727 $opts = HTMLFormField::flattenOptions( $info['options'] );
2728 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2730 foreach ( $opts as $value ) {
2731 $multiselectOptions["$prefix$value"] = true;
2734 unset( $prefs[$name] );
2737 $checkmatrixOptions = array();
2738 foreach ( $prefs as $name => $info ) {
2739 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2740 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2741 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2742 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2743 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2745 foreach ( $columns as $column ) {
2746 foreach ( $rows as $row ) {
2747 $checkmatrixOptions["$prefix$column-$row"] = true;
2751 unset( $prefs[$name] );
2755 // $value is ignored
2756 foreach ( $options as $key => $value ) {
2757 if ( isset( $prefs[$key] ) ) {
2758 $mapping[$key] = 'registered';
2759 } elseif ( isset( $multiselectOptions[$key] ) ) {
2760 $mapping[$key] = 'registered-multiselect';
2761 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2762 $mapping[$key] = 'registered-checkmatrix';
2763 } elseif ( isset( $specialOptions[$key] ) ) {
2764 $mapping[$key] = 'special';
2765 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2766 $mapping[$key] = 'userjs';
2767 } else {
2768 $mapping[$key] = 'unused';
2772 return $mapping;
2776 * Reset certain (or all) options to the site defaults
2778 * The optional parameter determines which kinds of preferences will be reset.
2779 * Supported values are everything that can be reported by getOptionKinds()
2780 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2782 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2783 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2784 * for backwards-compatibility.
2785 * @param IContextSource|null $context Context source used when $resetKinds
2786 * does not contain 'all', passed to getOptionKinds().
2787 * Defaults to RequestContext::getMain() when null.
2789 public function resetOptions(
2790 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2791 IContextSource $context = null
2793 $this->load();
2794 $defaultOptions = self::getDefaultOptions();
2796 if ( !is_array( $resetKinds ) ) {
2797 $resetKinds = array( $resetKinds );
2800 if ( in_array( 'all', $resetKinds ) ) {
2801 $newOptions = $defaultOptions;
2802 } else {
2803 if ( $context === null ) {
2804 $context = RequestContext::getMain();
2807 $optionKinds = $this->getOptionKinds( $context );
2808 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2809 $newOptions = array();
2811 // Use default values for the options that should be deleted, and
2812 // copy old values for the ones that shouldn't.
2813 foreach ( $this->mOptions as $key => $value ) {
2814 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2815 if ( array_key_exists( $key, $defaultOptions ) ) {
2816 $newOptions[$key] = $defaultOptions[$key];
2818 } else {
2819 $newOptions[$key] = $value;
2824 Hooks::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions, $resetKinds ) );
2826 $this->mOptions = $newOptions;
2827 $this->mOptionsLoaded = true;
2831 * Get the user's preferred date format.
2832 * @return string User's preferred date format
2834 public function getDatePreference() {
2835 // Important migration for old data rows
2836 if ( is_null( $this->mDatePreference ) ) {
2837 global $wgLang;
2838 $value = $this->getOption( 'date' );
2839 $map = $wgLang->getDatePreferenceMigrationMap();
2840 if ( isset( $map[$value] ) ) {
2841 $value = $map[$value];
2843 $this->mDatePreference = $value;
2845 return $this->mDatePreference;
2849 * Determine based on the wiki configuration and the user's options,
2850 * whether this user must be over HTTPS no matter what.
2852 * @return bool
2854 public function requiresHTTPS() {
2855 global $wgSecureLogin;
2856 if ( !$wgSecureLogin ) {
2857 return false;
2858 } else {
2859 $https = $this->getBoolOption( 'prefershttps' );
2860 Hooks::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2861 if ( $https ) {
2862 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2864 return $https;
2869 * Get the user preferred stub threshold
2871 * @return int
2873 public function getStubThreshold() {
2874 global $wgMaxArticleSize; # Maximum article size, in Kb
2875 $threshold = $this->getIntOption( 'stubthreshold' );
2876 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2877 // If they have set an impossible value, disable the preference
2878 // so we can use the parser cache again.
2879 $threshold = 0;
2881 return $threshold;
2885 * Get the permissions this user has.
2886 * @return array Array of String permission names
2888 public function getRights() {
2889 if ( is_null( $this->mRights ) ) {
2890 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2891 Hooks::run( 'UserGetRights', array( $this, &$this->mRights ) );
2892 // Force reindexation of rights when a hook has unset one of them
2893 $this->mRights = array_values( array_unique( $this->mRights ) );
2895 return $this->mRights;
2899 * Get the list of explicit group memberships this user has.
2900 * The implicit * and user groups are not included.
2901 * @return array Array of String internal group names
2903 public function getGroups() {
2904 $this->load();
2905 $this->loadGroups();
2906 return $this->mGroups;
2910 * Get the list of implicit group memberships this user has.
2911 * This includes all explicit groups, plus 'user' if logged in,
2912 * '*' for all accounts, and autopromoted groups
2913 * @param bool $recache Whether to avoid the cache
2914 * @return array Array of String internal group names
2916 public function getEffectiveGroups( $recache = false ) {
2917 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2918 $this->mEffectiveGroups = array_unique( array_merge(
2919 $this->getGroups(), // explicit groups
2920 $this->getAutomaticGroups( $recache ) // implicit groups
2921 ) );
2922 // Hook for additional groups
2923 Hooks::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2924 // Force reindexation of groups when a hook has unset one of them
2925 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
2927 return $this->mEffectiveGroups;
2931 * Get the list of implicit group memberships this user has.
2932 * This includes 'user' if logged in, '*' for all accounts,
2933 * and autopromoted groups
2934 * @param bool $recache Whether to avoid the cache
2935 * @return array Array of String internal group names
2937 public function getAutomaticGroups( $recache = false ) {
2938 if ( $recache || is_null( $this->mImplicitGroups ) ) {
2939 $this->mImplicitGroups = array( '*' );
2940 if ( $this->getId() ) {
2941 $this->mImplicitGroups[] = 'user';
2943 $this->mImplicitGroups = array_unique( array_merge(
2944 $this->mImplicitGroups,
2945 Autopromote::getAutopromoteGroups( $this )
2946 ) );
2948 if ( $recache ) {
2949 // Assure data consistency with rights/groups,
2950 // as getEffectiveGroups() depends on this function
2951 $this->mEffectiveGroups = null;
2954 return $this->mImplicitGroups;
2958 * Returns the groups the user has belonged to.
2960 * The user may still belong to the returned groups. Compare with getGroups().
2962 * The function will not return groups the user had belonged to before MW 1.17
2964 * @return array Names of the groups the user has belonged to.
2966 public function getFormerGroups() {
2967 if ( is_null( $this->mFormerGroups ) ) {
2968 $dbr = wfGetDB( DB_MASTER );
2969 $res = $dbr->select( 'user_former_groups',
2970 array( 'ufg_group' ),
2971 array( 'ufg_user' => $this->mId ),
2972 __METHOD__ );
2973 $this->mFormerGroups = array();
2974 foreach ( $res as $row ) {
2975 $this->mFormerGroups[] = $row->ufg_group;
2978 return $this->mFormerGroups;
2982 * Get the user's edit count.
2983 * @return int|null Null for anonymous users
2985 public function getEditCount() {
2986 if ( !$this->getId() ) {
2987 return null;
2990 if ( $this->mEditCount === null ) {
2991 /* Populate the count, if it has not been populated yet */
2992 $dbr = wfGetDB( DB_SLAVE );
2993 // check if the user_editcount field has been initialized
2994 $count = $dbr->selectField(
2995 'user', 'user_editcount',
2996 array( 'user_id' => $this->mId ),
2997 __METHOD__
3000 if ( $count === null ) {
3001 // it has not been initialized. do so.
3002 $count = $this->initEditCount();
3004 $this->mEditCount = $count;
3006 return (int)$this->mEditCount;
3010 * Add the user to the given group.
3011 * This takes immediate effect.
3012 * @param string $group Name of the group to add
3014 public function addGroup( $group ) {
3015 if ( Hooks::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3016 $dbw = wfGetDB( DB_MASTER );
3017 if ( $this->getId() ) {
3018 $dbw->insert( 'user_groups',
3019 array(
3020 'ug_user' => $this->getID(),
3021 'ug_group' => $group,
3023 __METHOD__,
3024 array( 'IGNORE' ) );
3027 $this->loadGroups();
3028 $this->mGroups[] = $group;
3029 // In case loadGroups was not called before, we now have the right twice.
3030 // Get rid of the duplicate.
3031 $this->mGroups = array_unique( $this->mGroups );
3033 // Refresh the groups caches, and clear the rights cache so it will be
3034 // refreshed on the next call to $this->getRights().
3035 $this->getEffectiveGroups( true );
3036 $this->mRights = null;
3038 $this->invalidateCache();
3042 * Remove the user from the given group.
3043 * This takes immediate effect.
3044 * @param string $group Name of the group to remove
3046 public function removeGroup( $group ) {
3047 $this->load();
3048 if ( Hooks::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3049 $dbw = wfGetDB( DB_MASTER );
3050 $dbw->delete( 'user_groups',
3051 array(
3052 'ug_user' => $this->getID(),
3053 'ug_group' => $group,
3054 ), __METHOD__ );
3055 // Remember that the user was in this group
3056 $dbw->insert( 'user_former_groups',
3057 array(
3058 'ufg_user' => $this->getID(),
3059 'ufg_group' => $group,
3061 __METHOD__,
3062 array( 'IGNORE' ) );
3064 $this->loadGroups();
3065 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
3067 // Refresh the groups caches, and clear the rights cache so it will be
3068 // refreshed on the next call to $this->getRights().
3069 $this->getEffectiveGroups( true );
3070 $this->mRights = null;
3072 $this->invalidateCache();
3076 * Get whether the user is logged in
3077 * @return bool
3079 public function isLoggedIn() {
3080 return $this->getID() != 0;
3084 * Get whether the user is anonymous
3085 * @return bool
3087 public function isAnon() {
3088 return !$this->isLoggedIn();
3092 * Check if user is allowed to access a feature / make an action
3094 * @param string $permissions,... Permissions to test
3095 * @return bool True if user is allowed to perform *any* of the given actions
3097 public function isAllowedAny( /*...*/ ) {
3098 $permissions = func_get_args();
3099 foreach ( $permissions as $permission ) {
3100 if ( $this->isAllowed( $permission ) ) {
3101 return true;
3104 return false;
3109 * @param string $permissions,... Permissions to test
3110 * @return bool True if the user is allowed to perform *all* of the given actions
3112 public function isAllowedAll( /*...*/ ) {
3113 $permissions = func_get_args();
3114 foreach ( $permissions as $permission ) {
3115 if ( !$this->isAllowed( $permission ) ) {
3116 return false;
3119 return true;
3123 * Internal mechanics of testing a permission
3124 * @param string $action
3125 * @return bool
3127 public function isAllowed( $action = '' ) {
3128 if ( $action === '' ) {
3129 return true; // In the spirit of DWIM
3131 // Patrolling may not be enabled
3132 if ( $action === 'patrol' || $action === 'autopatrol' ) {
3133 global $wgUseRCPatrol, $wgUseNPPatrol;
3134 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3135 return false;
3138 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3139 // by misconfiguration: 0 == 'foo'
3140 return in_array( $action, $this->getRights(), true );
3144 * Check whether to enable recent changes patrol features for this user
3145 * @return bool True or false
3147 public function useRCPatrol() {
3148 global $wgUseRCPatrol;
3149 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3153 * Check whether to enable new pages patrol features for this user
3154 * @return bool True or false
3156 public function useNPPatrol() {
3157 global $wgUseRCPatrol, $wgUseNPPatrol;
3158 return (
3159 ( $wgUseRCPatrol || $wgUseNPPatrol )
3160 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3165 * Get the WebRequest object to use with this object
3167 * @return WebRequest
3169 public function getRequest() {
3170 if ( $this->mRequest ) {
3171 return $this->mRequest;
3172 } else {
3173 global $wgRequest;
3174 return $wgRequest;
3179 * Get the current skin, loading it if required
3180 * @return Skin The current skin
3181 * @todo FIXME: Need to check the old failback system [AV]
3182 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3184 public function getSkin() {
3185 wfDeprecated( __METHOD__, '1.18' );
3186 return RequestContext::getMain()->getSkin();
3190 * Get a WatchedItem for this user and $title.
3192 * @since 1.22 $checkRights parameter added
3193 * @param Title $title
3194 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3195 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3196 * @return WatchedItem
3198 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3199 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3201 if ( isset( $this->mWatchedItems[$key] ) ) {
3202 return $this->mWatchedItems[$key];
3205 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
3206 $this->mWatchedItems = array();
3209 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
3210 return $this->mWatchedItems[$key];
3214 * Check the watched status of an article.
3215 * @since 1.22 $checkRights parameter added
3216 * @param Title $title Title of the article to look at
3217 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3218 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3219 * @return bool
3221 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3222 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3226 * Watch an article.
3227 * @since 1.22 $checkRights parameter added
3228 * @param Title $title Title of the article to look at
3229 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3230 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3232 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3233 $this->getWatchedItem( $title, $checkRights )->addWatch();
3234 $this->invalidateCache();
3238 * Stop watching an article.
3239 * @since 1.22 $checkRights parameter added
3240 * @param Title $title Title of the article to look at
3241 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3242 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3244 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3245 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3246 $this->invalidateCache();
3250 * Clear the user's notification timestamp for the given title.
3251 * If e-notif e-mails are on, they will receive notification mails on
3252 * the next change of the page if it's watched etc.
3253 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3254 * @param Title $title Title of the article to look at
3255 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3257 public function clearNotification( &$title, $oldid = 0 ) {
3258 global $wgUseEnotif, $wgShowUpdatedMarker;
3260 // Do nothing if the database is locked to writes
3261 if ( wfReadOnly() ) {
3262 return;
3265 // Do nothing if not allowed to edit the watchlist
3266 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3267 return;
3270 // If we're working on user's talk page, we should update the talk page message indicator
3271 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3272 if ( !Hooks::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3273 return;
3276 $nextid = $oldid ? $title->getNextRevisionID( $oldid ) : null;
3278 if ( !$oldid || !$nextid ) {
3279 // If we're looking at the latest revision, we should definitely clear it
3280 $this->setNewtalk( false );
3281 } else {
3282 // Otherwise we should update its revision, if it's present
3283 if ( $this->getNewtalk() ) {
3284 // Naturally the other one won't clear by itself
3285 $this->setNewtalk( false );
3286 $this->setNewtalk( true, Revision::newFromId( $nextid ) );
3291 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3292 return;
3295 if ( $this->isAnon() ) {
3296 // Nothing else to do...
3297 return;
3300 // Only update the timestamp if the page is being watched.
3301 // The query to find out if it is watched is cached both in memcached and per-invocation,
3302 // and when it does have to be executed, it can be on a slave
3303 // If this is the user's newtalk page, we always update the timestamp
3304 $force = '';
3305 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3306 $force = 'force';
3309 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3313 * Resets all of the given user's page-change notification timestamps.
3314 * If e-notif e-mails are on, they will receive notification mails on
3315 * the next change of any watched page.
3316 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3318 public function clearAllNotifications() {
3319 if ( wfReadOnly() ) {
3320 return;
3323 // Do nothing if not allowed to edit the watchlist
3324 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3325 return;
3328 global $wgUseEnotif, $wgShowUpdatedMarker;
3329 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3330 $this->setNewtalk( false );
3331 return;
3333 $id = $this->getId();
3334 if ( $id != 0 ) {
3335 $dbw = wfGetDB( DB_MASTER );
3336 $dbw->update( 'watchlist',
3337 array( /* SET */ 'wl_notificationtimestamp' => null ),
3338 array( /* WHERE */ 'wl_user' => $id ),
3339 __METHOD__
3341 // We also need to clear here the "you have new message" notification for the own user_talk page;
3342 // it's cleared one page view later in WikiPage::doViewUpdates().
3347 * Set a cookie on the user's client. Wrapper for
3348 * WebResponse::setCookie
3349 * @param string $name Name of the cookie to set
3350 * @param string $value Value to set
3351 * @param int $exp Expiration time, as a UNIX time value;
3352 * if 0 or not specified, use the default $wgCookieExpiration
3353 * @param bool $secure
3354 * true: Force setting the secure attribute when setting the cookie
3355 * false: Force NOT setting the secure attribute when setting the cookie
3356 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3357 * @param array $params Array of options sent passed to WebResponse::setcookie()
3359 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3360 $params['secure'] = $secure;
3361 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3365 * Clear a cookie on the user's client
3366 * @param string $name Name of the cookie to clear
3367 * @param bool $secure
3368 * true: Force setting the secure attribute when setting the cookie
3369 * false: Force NOT setting the secure attribute when setting the cookie
3370 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3371 * @param array $params Array of options sent passed to WebResponse::setcookie()
3373 protected function clearCookie( $name, $secure = null, $params = array() ) {
3374 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3378 * Set the default cookies for this session on the user's client.
3380 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3381 * is passed.
3382 * @param bool $secure Whether to force secure/insecure cookies or use default
3383 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3385 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3386 if ( $request === null ) {
3387 $request = $this->getRequest();
3390 $this->load();
3391 if ( 0 == $this->mId ) {
3392 return;
3394 if ( !$this->mToken ) {
3395 // When token is empty or NULL generate a new one and then save it to the database
3396 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3397 // Simply by setting every cell in the user_token column to NULL and letting them be
3398 // regenerated as users log back into the wiki.
3399 $this->setToken();
3400 $this->saveSettings();
3402 $session = array(
3403 'wsUserID' => $this->mId,
3404 'wsToken' => $this->mToken,
3405 'wsUserName' => $this->getName()
3407 $cookies = array(
3408 'UserID' => $this->mId,
3409 'UserName' => $this->getName(),
3411 if ( $rememberMe ) {
3412 $cookies['Token'] = $this->mToken;
3413 } else {
3414 $cookies['Token'] = false;
3417 Hooks::run( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3419 foreach ( $session as $name => $value ) {
3420 $request->setSessionData( $name, $value );
3422 foreach ( $cookies as $name => $value ) {
3423 if ( $value === false ) {
3424 $this->clearCookie( $name );
3425 } else {
3426 $this->setCookie( $name, $value, 0, $secure );
3431 * If wpStickHTTPS was selected, also set an insecure cookie that
3432 * will cause the site to redirect the user to HTTPS, if they access
3433 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3434 * as the one set by centralauth (bug 53538). Also set it to session, or
3435 * standard time setting, based on if rememberme was set.
3437 if ( $request->getCheck( 'wpStickHTTPS' ) || $this->requiresHTTPS() ) {
3438 $this->setCookie(
3439 'forceHTTPS',
3440 'true',
3441 $rememberMe ? 0 : null,
3442 false,
3443 array( 'prefix' => '' ) // no prefix
3449 * Log this user out.
3451 public function logout() {
3452 if ( Hooks::run( 'UserLogout', array( &$this ) ) ) {
3453 $this->doLogout();
3458 * Clear the user's cookies and session, and reset the instance cache.
3459 * @see logout()
3461 public function doLogout() {
3462 $this->clearInstanceCache( 'defaults' );
3464 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3466 $this->clearCookie( 'UserID' );
3467 $this->clearCookie( 'Token' );
3468 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3470 // Remember when user logged out, to prevent seeing cached pages
3471 $this->setCookie( 'LoggedOut', time(), time() + 86400 );
3475 * Save this user's settings into the database.
3476 * @todo Only rarely do all these fields need to be set!
3478 public function saveSettings() {
3479 global $wgAuth;
3481 $this->load();
3482 $this->loadPasswords();
3483 if ( wfReadOnly() ) {
3484 return;
3486 if ( 0 == $this->mId ) {
3487 return;
3490 $this->mTouched = self::newTouchedTimestamp();
3491 if ( !$wgAuth->allowSetLocalPassword() ) {
3492 $this->mPassword = self::getPasswordFactory()->newFromCiphertext( null );
3495 $dbw = wfGetDB( DB_MASTER );
3496 $dbw->update( 'user',
3497 array( /* SET */
3498 'user_name' => $this->mName,
3499 'user_password' => $this->mPassword->toString(),
3500 'user_newpassword' => $this->mNewpassword->toString(),
3501 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3502 'user_real_name' => $this->mRealName,
3503 'user_email' => $this->mEmail,
3504 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3505 'user_touched' => $dbw->timestamp( $this->mTouched ),
3506 'user_token' => strval( $this->mToken ),
3507 'user_email_token' => $this->mEmailToken,
3508 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3509 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires ),
3510 ), array( /* WHERE */
3511 'user_id' => $this->mId
3512 ), __METHOD__
3515 $this->saveOptions();
3517 Hooks::run( 'UserSaveSettings', array( $this ) );
3518 $this->clearSharedCache();
3519 $this->getUserPage()->invalidateCache();
3523 * If only this user's username is known, and it exists, return the user ID.
3524 * @return int
3526 public function idForName() {
3527 $s = trim( $this->getName() );
3528 if ( $s === '' ) {
3529 return 0;
3532 $dbr = wfGetDB( DB_SLAVE );
3533 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
3534 if ( $id === false ) {
3535 $id = 0;
3537 return $id;
3541 * Add a user to the database, return the user object
3543 * @param string $name Username to add
3544 * @param array $params Array of Strings Non-default parameters to save to
3545 * the database as user_* fields:
3546 * - password: The user's password hash. Password logins will be disabled
3547 * if this is omitted.
3548 * - newpassword: Hash for a temporary password that has been mailed to
3549 * the user.
3550 * - email: The user's email address.
3551 * - email_authenticated: The email authentication timestamp.
3552 * - real_name: The user's real name.
3553 * - options: An associative array of non-default options.
3554 * - token: Random authentication token. Do not set.
3555 * - registration: Registration timestamp. Do not set.
3557 * @return User|null User object, or null if the username already exists.
3559 public static function createNew( $name, $params = array() ) {
3560 $user = new User;
3561 $user->load();
3562 $user->loadPasswords();
3563 $user->setToken(); // init token
3564 if ( isset( $params['options'] ) ) {
3565 $user->mOptions = $params['options'] + (array)$user->mOptions;
3566 unset( $params['options'] );
3568 $dbw = wfGetDB( DB_MASTER );
3569 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3571 $fields = array(
3572 'user_id' => $seqVal,
3573 'user_name' => $name,
3574 'user_password' => $user->mPassword->toString(),
3575 'user_newpassword' => $user->mNewpassword->toString(),
3576 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3577 'user_email' => $user->mEmail,
3578 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3579 'user_real_name' => $user->mRealName,
3580 'user_token' => strval( $user->mToken ),
3581 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3582 'user_editcount' => 0,
3583 'user_touched' => $dbw->timestamp( self::newTouchedTimestamp() ),
3585 foreach ( $params as $name => $value ) {
3586 $fields["user_$name"] = $value;
3588 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3589 if ( $dbw->affectedRows() ) {
3590 $newUser = User::newFromId( $dbw->insertId() );
3591 } else {
3592 $newUser = null;
3594 return $newUser;
3598 * Add this existing user object to the database. If the user already
3599 * exists, a fatal status object is returned, and the user object is
3600 * initialised with the data from the database.
3602 * Previously, this function generated a DB error due to a key conflict
3603 * if the user already existed. Many extension callers use this function
3604 * in code along the lines of:
3606 * $user = User::newFromName( $name );
3607 * if ( !$user->isLoggedIn() ) {
3608 * $user->addToDatabase();
3610 * // do something with $user...
3612 * However, this was vulnerable to a race condition (bug 16020). By
3613 * initialising the user object if the user exists, we aim to support this
3614 * calling sequence as far as possible.
3616 * Note that if the user exists, this function will acquire a write lock,
3617 * so it is still advisable to make the call conditional on isLoggedIn(),
3618 * and to commit the transaction after calling.
3620 * @throws MWException
3621 * @return Status
3623 public function addToDatabase() {
3624 $this->load();
3625 $this->loadPasswords();
3626 if ( !$this->mToken ) {
3627 $this->setToken(); // init token
3630 $this->mTouched = self::newTouchedTimestamp();
3632 $dbw = wfGetDB( DB_MASTER );
3633 $inWrite = $dbw->writesOrCallbacksPending();
3634 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3635 $dbw->insert( 'user',
3636 array(
3637 'user_id' => $seqVal,
3638 'user_name' => $this->mName,
3639 'user_password' => $this->mPassword->toString(),
3640 'user_newpassword' => $this->mNewpassword->toString(),
3641 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3642 'user_email' => $this->mEmail,
3643 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3644 'user_real_name' => $this->mRealName,
3645 'user_token' => strval( $this->mToken ),
3646 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3647 'user_editcount' => 0,
3648 'user_touched' => $dbw->timestamp( $this->mTouched ),
3649 ), __METHOD__,
3650 array( 'IGNORE' )
3652 if ( !$dbw->affectedRows() ) {
3653 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3654 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3655 if ( $inWrite ) {
3656 // Can't commit due to pending writes that may need atomicity.
3657 // This may cause some lock contention unlike the case below.
3658 $options = array( 'LOCK IN SHARE MODE' );
3659 $flags = self::READ_LOCKING;
3660 } else {
3661 // Often, this case happens early in views before any writes when
3662 // using CentralAuth. It's should be OK to commit and break the snapshot.
3663 $dbw->commit( __METHOD__, 'flush' );
3664 $options = array();
3665 $flags = 0;
3667 $this->mId = $dbw->selectField( 'user', 'user_id',
3668 array( 'user_name' => $this->mName ), __METHOD__, $options );
3669 $loaded = false;
3670 if ( $this->mId ) {
3671 if ( $this->loadFromDatabase( $flags ) ) {
3672 $loaded = true;
3675 if ( !$loaded ) {
3676 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3677 "to insert user '{$this->mName}' row, but it was not present in select!" );
3679 return Status::newFatal( 'userexists' );
3681 $this->mId = $dbw->insertId();
3683 // Clear instance cache other than user table data, which is already accurate
3684 $this->clearInstanceCache();
3686 $this->saveOptions();
3687 return Status::newGood();
3691 * If this user is logged-in and blocked,
3692 * block any IP address they've successfully logged in from.
3693 * @return bool A block was spread
3695 public function spreadAnyEditBlock() {
3696 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3697 return $this->spreadBlock();
3699 return false;
3703 * If this (non-anonymous) user is blocked,
3704 * block the IP address they've successfully logged in from.
3705 * @return bool A block was spread
3707 protected function spreadBlock() {
3708 wfDebug( __METHOD__ . "()\n" );
3709 $this->load();
3710 if ( $this->mId == 0 ) {
3711 return false;
3714 $userblock = Block::newFromTarget( $this->getName() );
3715 if ( !$userblock ) {
3716 return false;
3719 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3723 * Get whether the user is explicitly blocked from account creation.
3724 * @return bool|Block
3726 public function isBlockedFromCreateAccount() {
3727 $this->getBlockedStatus();
3728 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3729 return $this->mBlock;
3732 # bug 13611: if the IP address the user is trying to create an account from is
3733 # blocked with createaccount disabled, prevent new account creation there even
3734 # when the user is logged in
3735 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3736 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3738 return $this->mBlockedFromCreateAccount instanceof Block
3739 && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3740 ? $this->mBlockedFromCreateAccount
3741 : false;
3745 * Get whether the user is blocked from using Special:Emailuser.
3746 * @return bool
3748 public function isBlockedFromEmailuser() {
3749 $this->getBlockedStatus();
3750 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3754 * Get whether the user is allowed to create an account.
3755 * @return bool
3757 public function isAllowedToCreateAccount() {
3758 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3762 * Get this user's personal page title.
3764 * @return Title User's personal page title
3766 public function getUserPage() {
3767 return Title::makeTitle( NS_USER, $this->getName() );
3771 * Get this user's talk page title.
3773 * @return Title User's talk page title
3775 public function getTalkPage() {
3776 $title = $this->getUserPage();
3777 return $title->getTalkPage();
3781 * Determine whether the user is a newbie. Newbies are either
3782 * anonymous IPs, or the most recently created accounts.
3783 * @return bool
3785 public function isNewbie() {
3786 return !$this->isAllowed( 'autoconfirmed' );
3790 * Check to see if the given clear-text password is one of the accepted passwords
3791 * @param string $password User password
3792 * @return bool True if the given password is correct, otherwise False
3794 public function checkPassword( $password ) {
3795 global $wgAuth, $wgLegacyEncoding;
3798 $this->loadPasswords();
3800 // Certain authentication plugins do NOT want to save
3801 // domain passwords in a mysql database, so we should
3802 // check this (in case $wgAuth->strict() is false).
3803 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3804 return true;
3805 } elseif ( $wgAuth->strict() ) {
3806 // Auth plugin doesn't allow local authentication
3807 return false;
3808 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3809 // Auth plugin doesn't allow local authentication for this user name
3810 return false;
3813 if ( !$this->mPassword->equals( $password ) ) {
3814 if ( $wgLegacyEncoding ) {
3815 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3816 // Check for this with iconv
3817 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3818 if ( $cp1252Password === $password || !$this->mPassword->equals( $cp1252Password ) ) {
3819 return false;
3821 } else {
3822 return false;
3826 $passwordFactory = self::getPasswordFactory();
3827 if ( $passwordFactory->needsUpdate( $this->mPassword ) ) {
3828 $this->mPassword = $passwordFactory->newFromPlaintext( $password );
3829 $this->saveSettings();
3832 return true;
3836 * Check if the given clear-text password matches the temporary password
3837 * sent by e-mail for password reset operations.
3839 * @param string $plaintext
3841 * @return bool True if matches, false otherwise
3843 public function checkTemporaryPassword( $plaintext ) {
3844 global $wgNewPasswordExpiry;
3846 $this->load();
3847 $this->loadPasswords();
3848 if ( $this->mNewpassword->equals( $plaintext ) ) {
3849 if ( is_null( $this->mNewpassTime ) ) {
3850 return true;
3852 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
3853 return ( time() < $expiry );
3854 } else {
3855 return false;
3860 * Alias for getEditToken.
3861 * @deprecated since 1.19, use getEditToken instead.
3863 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3864 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3865 * @return string The new edit token
3867 public function editToken( $salt = '', $request = null ) {
3868 wfDeprecated( __METHOD__, '1.19' );
3869 return $this->getEditToken( $salt, $request );
3873 * Internal implementation for self::getEditToken() and
3874 * self::matchEditToken().
3876 * @param string|array $salt
3877 * @param WebRequest $request
3878 * @param string|int $timestamp
3879 * @return string
3881 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
3882 if ( $this->isAnon() ) {
3883 return self::EDIT_TOKEN_SUFFIX;
3884 } else {
3885 $token = $request->getSessionData( 'wsEditToken' );
3886 if ( $token === null ) {
3887 $token = MWCryptRand::generateHex( 32 );
3888 $request->setSessionData( 'wsEditToken', $token );
3890 if ( is_array( $salt ) ) {
3891 $salt = implode( '|', $salt );
3893 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
3894 dechex( $timestamp ) .
3895 self::EDIT_TOKEN_SUFFIX;
3900 * Initialize (if necessary) and return a session token value
3901 * which can be used in edit forms to show that the user's
3902 * login credentials aren't being hijacked with a foreign form
3903 * submission.
3905 * @since 1.19
3907 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3908 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3909 * @return string The new edit token
3911 public function getEditToken( $salt = '', $request = null ) {
3912 return $this->getEditTokenAtTimestamp(
3913 $salt, $request ?: $this->getRequest(), wfTimestamp()
3918 * Generate a looking random token for various uses.
3920 * @return string The new random token
3921 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
3922 * wfRandomString for pseudo-randomness.
3924 public static function generateToken() {
3925 return MWCryptRand::generateHex( 32 );
3929 * Check given value against the token value stored in the session.
3930 * A match should confirm that the form was submitted from the
3931 * user's own login session, not a form submission from a third-party
3932 * site.
3934 * @param string $val Input value to compare
3935 * @param string $salt Optional function-specific data for hashing
3936 * @param WebRequest|null $request Object to use or null to use $wgRequest
3937 * @param int $maxage Fail tokens older than this, in seconds
3938 * @return bool Whether the token matches
3940 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
3941 if ( $this->isAnon() ) {
3942 return $val === self::EDIT_TOKEN_SUFFIX;
3945 $suffixLen = strlen( self::EDIT_TOKEN_SUFFIX );
3946 if ( strlen( $val ) <= 32 + $suffixLen ) {
3947 return false;
3950 $timestamp = hexdec( substr( $val, 32, -$suffixLen ) );
3951 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
3952 // Expired token
3953 return false;
3956 $sessionToken = $this->getEditTokenAtTimestamp(
3957 $salt, $request ?: $this->getRequest(), $timestamp
3960 if ( $val != $sessionToken ) {
3961 wfDebug( "User::matchEditToken: broken session data\n" );
3964 return hash_equals( $sessionToken, $val );
3968 * Check given value against the token value stored in the session,
3969 * ignoring the suffix.
3971 * @param string $val Input value to compare
3972 * @param string $salt Optional function-specific data for hashing
3973 * @param WebRequest|null $request Object to use or null to use $wgRequest
3974 * @param int $maxage Fail tokens older than this, in seconds
3975 * @return bool Whether the token matches
3977 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
3978 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self::EDIT_TOKEN_SUFFIX;
3979 return $this->matchEditToken( $val, $salt, $request, $maxage );
3983 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3984 * mail to the user's given address.
3986 * @param string $type Message to send, either "created", "changed" or "set"
3987 * @return Status
3989 public function sendConfirmationMail( $type = 'created' ) {
3990 global $wgLang;
3991 $expiration = null; // gets passed-by-ref and defined in next line.
3992 $token = $this->confirmationToken( $expiration );
3993 $url = $this->confirmationTokenUrl( $token );
3994 $invalidateURL = $this->invalidationTokenUrl( $token );
3995 $this->saveSettings();
3997 if ( $type == 'created' || $type === false ) {
3998 $message = 'confirmemail_body';
3999 } elseif ( $type === true ) {
4000 $message = 'confirmemail_body_changed';
4001 } else {
4002 // Messages: confirmemail_body_changed, confirmemail_body_set
4003 $message = 'confirmemail_body_' . $type;
4006 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4007 wfMessage( $message,
4008 $this->getRequest()->getIP(),
4009 $this->getName(),
4010 $url,
4011 $wgLang->timeanddate( $expiration, false ),
4012 $invalidateURL,
4013 $wgLang->date( $expiration, false ),
4014 $wgLang->time( $expiration, false ) )->text() );
4018 * Send an e-mail to this user's account. Does not check for
4019 * confirmed status or validity.
4021 * @param string $subject Message subject
4022 * @param string $body Message body
4023 * @param string $from Optional From address; if unspecified, default
4024 * $wgPasswordSender will be used.
4025 * @param string $replyto Reply-To address
4026 * @return Status
4028 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4029 if ( is_null( $from ) ) {
4030 global $wgPasswordSender;
4031 $sender = new MailAddress( $wgPasswordSender,
4032 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4033 } else {
4034 $sender = MailAddress::newFromUser( $from );
4037 $to = MailAddress::newFromUser( $this );
4038 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
4042 * Generate, store, and return a new e-mail confirmation code.
4043 * A hash (unsalted, since it's used as a key) is stored.
4045 * @note Call saveSettings() after calling this function to commit
4046 * this change to the database.
4048 * @param string &$expiration Accepts the expiration time
4049 * @return string New token
4051 protected function confirmationToken( &$expiration ) {
4052 global $wgUserEmailConfirmationTokenExpiry;
4053 $now = time();
4054 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
4055 $expiration = wfTimestamp( TS_MW, $expires );
4056 $this->load();
4057 $token = MWCryptRand::generateHex( 32 );
4058 $hash = md5( $token );
4059 $this->mEmailToken = $hash;
4060 $this->mEmailTokenExpires = $expiration;
4061 return $token;
4065 * Return a URL the user can use to confirm their email address.
4066 * @param string $token Accepts the email confirmation token
4067 * @return string New token URL
4069 protected function confirmationTokenUrl( $token ) {
4070 return $this->getTokenUrl( 'ConfirmEmail', $token );
4074 * Return a URL the user can use to invalidate their email address.
4075 * @param string $token Accepts the email confirmation token
4076 * @return string New token URL
4078 protected function invalidationTokenUrl( $token ) {
4079 return $this->getTokenUrl( 'InvalidateEmail', $token );
4083 * Internal function to format the e-mail validation/invalidation URLs.
4084 * This uses a quickie hack to use the
4085 * hardcoded English names of the Special: pages, for ASCII safety.
4087 * @note Since these URLs get dropped directly into emails, using the
4088 * short English names avoids insanely long URL-encoded links, which
4089 * also sometimes can get corrupted in some browsers/mailers
4090 * (bug 6957 with Gmail and Internet Explorer).
4092 * @param string $page Special page
4093 * @param string $token Token
4094 * @return string Formatted URL
4096 protected function getTokenUrl( $page, $token ) {
4097 // Hack to bypass localization of 'Special:'
4098 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
4099 return $title->getCanonicalURL();
4103 * Mark the e-mail address confirmed.
4105 * @note Call saveSettings() after calling this function to commit the change.
4107 * @return bool
4109 public function confirmEmail() {
4110 // Check if it's already confirmed, so we don't touch the database
4111 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4112 if ( !$this->isEmailConfirmed() ) {
4113 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4114 Hooks::run( 'ConfirmEmailComplete', array( $this ) );
4116 return true;
4120 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4121 * address if it was already confirmed.
4123 * @note Call saveSettings() after calling this function to commit the change.
4124 * @return bool Returns true
4126 public function invalidateEmail() {
4127 $this->load();
4128 $this->mEmailToken = null;
4129 $this->mEmailTokenExpires = null;
4130 $this->setEmailAuthenticationTimestamp( null );
4131 $this->mEmail = '';
4132 Hooks::run( 'InvalidateEmailComplete', array( $this ) );
4133 return true;
4137 * Set the e-mail authentication timestamp.
4138 * @param string $timestamp TS_MW timestamp
4140 public function setEmailAuthenticationTimestamp( $timestamp ) {
4141 $this->load();
4142 $this->mEmailAuthenticated = $timestamp;
4143 Hooks::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
4147 * Is this user allowed to send e-mails within limits of current
4148 * site configuration?
4149 * @return bool
4151 public function canSendEmail() {
4152 global $wgEnableEmail, $wgEnableUserEmail;
4153 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4154 return false;
4156 $canSend = $this->isEmailConfirmed();
4157 Hooks::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4158 return $canSend;
4162 * Is this user allowed to receive e-mails within limits of current
4163 * site configuration?
4164 * @return bool
4166 public function canReceiveEmail() {
4167 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4171 * Is this user's e-mail address valid-looking and confirmed within
4172 * limits of the current site configuration?
4174 * @note If $wgEmailAuthentication is on, this may require the user to have
4175 * confirmed their address by returning a code or using a password
4176 * sent to the address from the wiki.
4178 * @return bool
4180 public function isEmailConfirmed() {
4181 global $wgEmailAuthentication;
4182 $this->load();
4183 $confirmed = true;
4184 if ( Hooks::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4185 if ( $this->isAnon() ) {
4186 return false;
4188 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4189 return false;
4191 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4192 return false;
4194 return true;
4195 } else {
4196 return $confirmed;
4201 * Check whether there is an outstanding request for e-mail confirmation.
4202 * @return bool
4204 public function isEmailConfirmationPending() {
4205 global $wgEmailAuthentication;
4206 return $wgEmailAuthentication &&
4207 !$this->isEmailConfirmed() &&
4208 $this->mEmailToken &&
4209 $this->mEmailTokenExpires > wfTimestamp();
4213 * Get the timestamp of account creation.
4215 * @return string|bool|null Timestamp of account creation, false for
4216 * non-existent/anonymous user accounts, or null if existing account
4217 * but information is not in database.
4219 public function getRegistration() {
4220 if ( $this->isAnon() ) {
4221 return false;
4223 $this->load();
4224 return $this->mRegistration;
4228 * Get the timestamp of the first edit
4230 * @return string|bool Timestamp of first edit, or false for
4231 * non-existent/anonymous user accounts.
4233 public function getFirstEditTimestamp() {
4234 if ( $this->getId() == 0 ) {
4235 return false; // anons
4237 $dbr = wfGetDB( DB_SLAVE );
4238 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4239 array( 'rev_user' => $this->getId() ),
4240 __METHOD__,
4241 array( 'ORDER BY' => 'rev_timestamp ASC' )
4243 if ( !$time ) {
4244 return false; // no edits
4246 return wfTimestamp( TS_MW, $time );
4250 * Get the permissions associated with a given list of groups
4252 * @param array $groups Array of Strings List of internal group names
4253 * @return array Array of Strings List of permission key names for given groups combined
4255 public static function getGroupPermissions( $groups ) {
4256 global $wgGroupPermissions, $wgRevokePermissions;
4257 $rights = array();
4258 // grant every granted permission first
4259 foreach ( $groups as $group ) {
4260 if ( isset( $wgGroupPermissions[$group] ) ) {
4261 $rights = array_merge( $rights,
4262 // array_filter removes empty items
4263 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4266 // now revoke the revoked permissions
4267 foreach ( $groups as $group ) {
4268 if ( isset( $wgRevokePermissions[$group] ) ) {
4269 $rights = array_diff( $rights,
4270 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4273 return array_unique( $rights );
4277 * Get all the groups who have a given permission
4279 * @param string $role Role to check
4280 * @return array Array of Strings List of internal group names with the given permission
4282 public static function getGroupsWithPermission( $role ) {
4283 global $wgGroupPermissions;
4284 $allowedGroups = array();
4285 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4286 if ( self::groupHasPermission( $group, $role ) ) {
4287 $allowedGroups[] = $group;
4290 return $allowedGroups;
4294 * Check, if the given group has the given permission
4296 * If you're wanting to check whether all users have a permission, use
4297 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4298 * from anyone.
4300 * @since 1.21
4301 * @param string $group Group to check
4302 * @param string $role Role to check
4303 * @return bool
4305 public static function groupHasPermission( $group, $role ) {
4306 global $wgGroupPermissions, $wgRevokePermissions;
4307 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4308 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4312 * Check if all users have the given permission
4314 * @since 1.22
4315 * @param string $right Right to check
4316 * @return bool
4318 public static function isEveryoneAllowed( $right ) {
4319 global $wgGroupPermissions, $wgRevokePermissions;
4320 static $cache = array();
4322 // Use the cached results, except in unit tests which rely on
4323 // being able change the permission mid-request
4324 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4325 return $cache[$right];
4328 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4329 $cache[$right] = false;
4330 return false;
4333 // If it's revoked anywhere, then everyone doesn't have it
4334 foreach ( $wgRevokePermissions as $rights ) {
4335 if ( isset( $rights[$right] ) && $rights[$right] ) {
4336 $cache[$right] = false;
4337 return false;
4341 // Allow extensions (e.g. OAuth) to say false
4342 if ( !Hooks::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4343 $cache[$right] = false;
4344 return false;
4347 $cache[$right] = true;
4348 return true;
4352 * Get the localized descriptive name for a group, if it exists
4354 * @param string $group Internal group name
4355 * @return string Localized descriptive group name
4357 public static function getGroupName( $group ) {
4358 $msg = wfMessage( "group-$group" );
4359 return $msg->isBlank() ? $group : $msg->text();
4363 * Get the localized descriptive name for a member of a group, if it exists
4365 * @param string $group Internal group name
4366 * @param string $username Username for gender (since 1.19)
4367 * @return string Localized name for group member
4369 public static function getGroupMember( $group, $username = '#' ) {
4370 $msg = wfMessage( "group-$group-member", $username );
4371 return $msg->isBlank() ? $group : $msg->text();
4375 * Return the set of defined explicit groups.
4376 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4377 * are not included, as they are defined automatically, not in the database.
4378 * @return array Array of internal group names
4380 public static function getAllGroups() {
4381 global $wgGroupPermissions, $wgRevokePermissions;
4382 return array_diff(
4383 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4384 self::getImplicitGroups()
4389 * Get a list of all available permissions.
4390 * @return array Array of permission names
4392 public static function getAllRights() {
4393 if ( self::$mAllRights === false ) {
4394 global $wgAvailableRights;
4395 if ( count( $wgAvailableRights ) ) {
4396 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4397 } else {
4398 self::$mAllRights = self::$mCoreRights;
4400 Hooks::run( 'UserGetAllRights', array( &self::$mAllRights ) );
4402 return self::$mAllRights;
4406 * Get a list of implicit groups
4407 * @return array Array of Strings Array of internal group names
4409 public static function getImplicitGroups() {
4410 global $wgImplicitGroups;
4412 $groups = $wgImplicitGroups;
4413 # Deprecated, use $wgImplicitGroups instead
4414 Hooks::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4416 return $groups;
4420 * Get the title of a page describing a particular group
4422 * @param string $group Internal group name
4423 * @return Title|bool Title of the page if it exists, false otherwise
4425 public static function getGroupPage( $group ) {
4426 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4427 if ( $msg->exists() ) {
4428 $title = Title::newFromText( $msg->text() );
4429 if ( is_object( $title ) ) {
4430 return $title;
4433 return false;
4437 * Create a link to the group in HTML, if available;
4438 * else return the group name.
4440 * @param string $group Internal name of the group
4441 * @param string $text The text of the link
4442 * @return string HTML link to the group
4444 public static function makeGroupLinkHTML( $group, $text = '' ) {
4445 if ( $text == '' ) {
4446 $text = self::getGroupName( $group );
4448 $title = self::getGroupPage( $group );
4449 if ( $title ) {
4450 return Linker::link( $title, htmlspecialchars( $text ) );
4451 } else {
4452 return htmlspecialchars( $text );
4457 * Create a link to the group in Wikitext, if available;
4458 * else return the group name.
4460 * @param string $group Internal name of the group
4461 * @param string $text The text of the link
4462 * @return string Wikilink to the group
4464 public static function makeGroupLinkWiki( $group, $text = '' ) {
4465 if ( $text == '' ) {
4466 $text = self::getGroupName( $group );
4468 $title = self::getGroupPage( $group );
4469 if ( $title ) {
4470 $page = $title->getFullText();
4471 return "[[$page|$text]]";
4472 } else {
4473 return $text;
4478 * Returns an array of the groups that a particular group can add/remove.
4480 * @param string $group The group to check for whether it can add/remove
4481 * @return array Array( 'add' => array( addablegroups ),
4482 * 'remove' => array( removablegroups ),
4483 * 'add-self' => array( addablegroups to self),
4484 * 'remove-self' => array( removable groups from self) )
4486 public static function changeableByGroup( $group ) {
4487 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4489 $groups = array(
4490 'add' => array(),
4491 'remove' => array(),
4492 'add-self' => array(),
4493 'remove-self' => array()
4496 if ( empty( $wgAddGroups[$group] ) ) {
4497 // Don't add anything to $groups
4498 } elseif ( $wgAddGroups[$group] === true ) {
4499 // You get everything
4500 $groups['add'] = self::getAllGroups();
4501 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4502 $groups['add'] = $wgAddGroups[$group];
4505 // Same thing for remove
4506 if ( empty( $wgRemoveGroups[$group] ) ) {
4507 // Do nothing
4508 } elseif ( $wgRemoveGroups[$group] === true ) {
4509 $groups['remove'] = self::getAllGroups();
4510 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4511 $groups['remove'] = $wgRemoveGroups[$group];
4514 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4515 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4516 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4517 if ( is_int( $key ) ) {
4518 $wgGroupsAddToSelf['user'][] = $value;
4523 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4524 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4525 if ( is_int( $key ) ) {
4526 $wgGroupsRemoveFromSelf['user'][] = $value;
4531 // Now figure out what groups the user can add to him/herself
4532 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4533 // Do nothing
4534 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4535 // No idea WHY this would be used, but it's there
4536 $groups['add-self'] = User::getAllGroups();
4537 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4538 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4541 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4542 // Do nothing
4543 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4544 $groups['remove-self'] = User::getAllGroups();
4545 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4546 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4549 return $groups;
4553 * Returns an array of groups that this user can add and remove
4554 * @return array Array( 'add' => array( addablegroups ),
4555 * 'remove' => array( removablegroups ),
4556 * 'add-self' => array( addablegroups to self),
4557 * 'remove-self' => array( removable groups from self) )
4559 public function changeableGroups() {
4560 if ( $this->isAllowed( 'userrights' ) ) {
4561 // This group gives the right to modify everything (reverse-
4562 // compatibility with old "userrights lets you change
4563 // everything")
4564 // Using array_merge to make the groups reindexed
4565 $all = array_merge( User::getAllGroups() );
4566 return array(
4567 'add' => $all,
4568 'remove' => $all,
4569 'add-self' => array(),
4570 'remove-self' => array()
4574 // Okay, it's not so simple, we will have to go through the arrays
4575 $groups = array(
4576 'add' => array(),
4577 'remove' => array(),
4578 'add-self' => array(),
4579 'remove-self' => array()
4581 $addergroups = $this->getEffectiveGroups();
4583 foreach ( $addergroups as $addergroup ) {
4584 $groups = array_merge_recursive(
4585 $groups, $this->changeableByGroup( $addergroup )
4587 $groups['add'] = array_unique( $groups['add'] );
4588 $groups['remove'] = array_unique( $groups['remove'] );
4589 $groups['add-self'] = array_unique( $groups['add-self'] );
4590 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4592 return $groups;
4596 * Increment the user's edit-count field.
4597 * Will have no effect for anonymous users.
4599 public function incEditCount() {
4600 if ( !$this->isAnon() ) {
4601 $dbw = wfGetDB( DB_MASTER );
4602 $dbw->update(
4603 'user',
4604 array( 'user_editcount=user_editcount+1' ),
4605 array( 'user_id' => $this->getId() ),
4606 __METHOD__
4609 // Lazy initialization check...
4610 if ( $dbw->affectedRows() == 0 ) {
4611 // Now here's a goddamn hack...
4612 $dbr = wfGetDB( DB_SLAVE );
4613 if ( $dbr !== $dbw ) {
4614 // If we actually have a slave server, the count is
4615 // at least one behind because the current transaction
4616 // has not been committed and replicated.
4617 $this->initEditCount( 1 );
4618 } else {
4619 // But if DB_SLAVE is selecting the master, then the
4620 // count we just read includes the revision that was
4621 // just added in the working transaction.
4622 $this->initEditCount();
4626 // edit count in user cache too
4627 $this->invalidateCache();
4631 * Initialize user_editcount from data out of the revision table
4633 * @param int $add Edits to add to the count from the revision table
4634 * @return int Number of edits
4636 protected function initEditCount( $add = 0 ) {
4637 // Pull from a slave to be less cruel to servers
4638 // Accuracy isn't the point anyway here
4639 $dbr = wfGetDB( DB_SLAVE );
4640 $count = (int)$dbr->selectField(
4641 'revision',
4642 'COUNT(rev_user)',
4643 array( 'rev_user' => $this->getId() ),
4644 __METHOD__
4646 $count = $count + $add;
4648 $dbw = wfGetDB( DB_MASTER );
4649 $dbw->update(
4650 'user',
4651 array( 'user_editcount' => $count ),
4652 array( 'user_id' => $this->getId() ),
4653 __METHOD__
4656 return $count;
4660 * Get the description of a given right
4662 * @param string $right Right to query
4663 * @return string Localized description of the right
4665 public static function getRightDescription( $right ) {
4666 $key = "right-$right";
4667 $msg = wfMessage( $key );
4668 return $msg->isBlank() ? $right : $msg->text();
4672 * Make a new-style password hash
4674 * @param string $password Plain-text password
4675 * @param bool|string $salt Optional salt, may be random or the user ID.
4676 * If unspecified or false, will generate one automatically
4677 * @return string Password hash
4678 * @deprecated since 1.24, use Password class
4680 public static function crypt( $password, $salt = false ) {
4681 wfDeprecated( __METHOD__, '1.24' );
4682 $hash = self::getPasswordFactory()->newFromPlaintext( $password );
4683 return $hash->toString();
4687 * Compare a password hash with a plain-text password. Requires the user
4688 * ID if there's a chance that the hash is an old-style hash.
4690 * @param string $hash Password hash
4691 * @param string $password Plain-text password to compare
4692 * @param string|bool $userId User ID for old-style password salt
4694 * @return bool
4695 * @deprecated since 1.24, use Password class
4697 public static function comparePasswords( $hash, $password, $userId = false ) {
4698 wfDeprecated( __METHOD__, '1.24' );
4700 // Check for *really* old password hashes that don't even have a type
4701 // The old hash format was just an md5 hex hash, with no type information
4702 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4703 global $wgPasswordSalt;
4704 if ( $wgPasswordSalt ) {
4705 $password = ":B:{$userId}:{$hash}";
4706 } else {
4707 $password = ":A:{$hash}";
4711 $hash = self::getPasswordFactory()->newFromCiphertext( $hash );
4712 return $hash->equals( $password );
4716 * Add a newuser log entry for this user.
4717 * Before 1.19 the return value was always true.
4719 * @param string|bool $action Account creation type.
4720 * - String, one of the following values:
4721 * - 'create' for an anonymous user creating an account for himself.
4722 * This will force the action's performer to be the created user itself,
4723 * no matter the value of $wgUser
4724 * - 'create2' for a logged in user creating an account for someone else
4725 * - 'byemail' when the created user will receive its password by e-mail
4726 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4727 * - Boolean means whether the account was created by e-mail (deprecated):
4728 * - true will be converted to 'byemail'
4729 * - false will be converted to 'create' if this object is the same as
4730 * $wgUser and to 'create2' otherwise
4732 * @param string $reason User supplied reason
4734 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4736 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4737 global $wgUser, $wgNewUserLog;
4738 if ( empty( $wgNewUserLog ) ) {
4739 return true; // disabled
4742 if ( $action === true ) {
4743 $action = 'byemail';
4744 } elseif ( $action === false ) {
4745 if ( $this->getName() == $wgUser->getName() ) {
4746 $action = 'create';
4747 } else {
4748 $action = 'create2';
4752 if ( $action === 'create' || $action === 'autocreate' ) {
4753 $performer = $this;
4754 } else {
4755 $performer = $wgUser;
4758 $logEntry = new ManualLogEntry( 'newusers', $action );
4759 $logEntry->setPerformer( $performer );
4760 $logEntry->setTarget( $this->getUserPage() );
4761 $logEntry->setComment( $reason );
4762 $logEntry->setParameters( array(
4763 '4::userid' => $this->getId(),
4764 ) );
4765 $logid = $logEntry->insert();
4767 if ( $action !== 'autocreate' ) {
4768 $logEntry->publish( $logid );
4771 return (int)$logid;
4775 * Add an autocreate newuser log entry for this user
4776 * Used by things like CentralAuth and perhaps other authplugins.
4777 * Consider calling addNewUserLogEntry() directly instead.
4779 * @return bool
4781 public function addNewUserLogEntryAutoCreate() {
4782 $this->addNewUserLogEntry( 'autocreate' );
4784 return true;
4788 * Load the user options either from cache, the database or an array
4790 * @param array $data Rows for the current user out of the user_properties table
4792 protected function loadOptions( $data = null ) {
4793 global $wgContLang;
4795 $this->load();
4797 if ( $this->mOptionsLoaded ) {
4798 return;
4801 $this->mOptions = self::getDefaultOptions();
4803 if ( !$this->getId() ) {
4804 // For unlogged-in users, load language/variant options from request.
4805 // There's no need to do it for logged-in users: they can set preferences,
4806 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4807 // so don't override user's choice (especially when the user chooses site default).
4808 $variant = $wgContLang->getDefaultVariant();
4809 $this->mOptions['variant'] = $variant;
4810 $this->mOptions['language'] = $variant;
4811 $this->mOptionsLoaded = true;
4812 return;
4815 // Maybe load from the object
4816 if ( !is_null( $this->mOptionOverrides ) ) {
4817 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4818 foreach ( $this->mOptionOverrides as $key => $value ) {
4819 $this->mOptions[$key] = $value;
4821 } else {
4822 if ( !is_array( $data ) ) {
4823 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4824 // Load from database
4825 $dbr = wfGetDB( DB_SLAVE );
4827 $res = $dbr->select(
4828 'user_properties',
4829 array( 'up_property', 'up_value' ),
4830 array( 'up_user' => $this->getId() ),
4831 __METHOD__
4834 $this->mOptionOverrides = array();
4835 $data = array();
4836 foreach ( $res as $row ) {
4837 $data[$row->up_property] = $row->up_value;
4840 foreach ( $data as $property => $value ) {
4841 $this->mOptionOverrides[$property] = $value;
4842 $this->mOptions[$property] = $value;
4846 $this->mOptionsLoaded = true;
4848 Hooks::run( 'UserLoadOptions', array( $this, &$this->mOptions ) );
4852 * Saves the non-default options for this user, as previously set e.g. via
4853 * setOption(), in the database's "user_properties" (preferences) table.
4854 * Usually used via saveSettings().
4856 protected function saveOptions() {
4857 $this->loadOptions();
4859 // Not using getOptions(), to keep hidden preferences in database
4860 $saveOptions = $this->mOptions;
4862 // Allow hooks to abort, for instance to save to a global profile.
4863 // Reset options to default state before saving.
4864 if ( !Hooks::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4865 return;
4868 $userId = $this->getId();
4870 $insert_rows = array(); // all the new preference rows
4871 foreach ( $saveOptions as $key => $value ) {
4872 // Don't bother storing default values
4873 $defaultOption = self::getDefaultOption( $key );
4874 if ( ( $defaultOption === null && $value !== false && $value !== null )
4875 || $value != $defaultOption
4877 $insert_rows[] = array(
4878 'up_user' => $userId,
4879 'up_property' => $key,
4880 'up_value' => $value,
4885 $dbw = wfGetDB( DB_MASTER );
4887 $res = $dbw->select( 'user_properties',
4888 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__ );
4890 // Find prior rows that need to be removed or updated. These rows will
4891 // all be deleted (the later so that INSERT IGNORE applies the new values).
4892 $keysDelete = array();
4893 foreach ( $res as $row ) {
4894 if ( !isset( $saveOptions[$row->up_property] )
4895 || strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
4897 $keysDelete[] = $row->up_property;
4901 if ( count( $keysDelete ) ) {
4902 // Do the DELETE by PRIMARY KEY for prior rows.
4903 // In the past a very large portion of calls to this function are for setting
4904 // 'rememberpassword' for new accounts (a preference that has since been removed).
4905 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4906 // caused gap locks on [max user ID,+infinity) which caused high contention since
4907 // updates would pile up on each other as they are for higher (newer) user IDs.
4908 // It might not be necessary these days, but it shouldn't hurt either.
4909 $dbw->delete( 'user_properties',
4910 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__ );
4912 // Insert the new preference rows
4913 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
4917 * Lazily instantiate and return a factory object for making passwords
4919 * @return PasswordFactory
4921 public static function getPasswordFactory() {
4922 if ( self::$mPasswordFactory === null ) {
4923 self::$mPasswordFactory = new PasswordFactory();
4924 self::$mPasswordFactory->init( RequestContext::getMain()->getConfig() );
4927 return self::$mPasswordFactory;
4931 * Provide an array of HTML5 attributes to put on an input element
4932 * intended for the user to enter a new password. This may include
4933 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4935 * Do *not* use this when asking the user to enter his current password!
4936 * Regardless of configuration, users may have invalid passwords for whatever
4937 * reason (e.g., they were set before requirements were tightened up).
4938 * Only use it when asking for a new password, like on account creation or
4939 * ResetPass.
4941 * Obviously, you still need to do server-side checking.
4943 * NOTE: A combination of bugs in various browsers means that this function
4944 * actually just returns array() unconditionally at the moment. May as
4945 * well keep it around for when the browser bugs get fixed, though.
4947 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4949 * @return array Array of HTML attributes suitable for feeding to
4950 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4951 * That will get confused by the boolean attribute syntax used.)
4953 public static function passwordChangeInputAttribs() {
4954 global $wgMinimalPasswordLength;
4956 if ( $wgMinimalPasswordLength == 0 ) {
4957 return array();
4960 # Note that the pattern requirement will always be satisfied if the
4961 # input is empty, so we need required in all cases.
4963 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4964 # if e-mail confirmation is being used. Since HTML5 input validation
4965 # is b0rked anyway in some browsers, just return nothing. When it's
4966 # re-enabled, fix this code to not output required for e-mail
4967 # registration.
4968 #$ret = array( 'required' );
4969 $ret = array();
4971 # We can't actually do this right now, because Opera 9.6 will print out
4972 # the entered password visibly in its error message! When other
4973 # browsers add support for this attribute, or Opera fixes its support,
4974 # we can add support with a version check to avoid doing this on Opera
4975 # versions where it will be a problem. Reported to Opera as
4976 # DSK-262266, but they don't have a public bug tracker for us to follow.
4978 if ( $wgMinimalPasswordLength > 1 ) {
4979 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4980 $ret['title'] = wfMessage( 'passwordtooshort' )
4981 ->numParams( $wgMinimalPasswordLength )->text();
4985 return $ret;
4989 * Return the list of user fields that should be selected to create
4990 * a new user object.
4991 * @return array
4993 public static function selectFields() {
4994 return array(
4995 'user_id',
4996 'user_name',
4997 'user_real_name',
4998 'user_email',
4999 'user_touched',
5000 'user_token',
5001 'user_email_authenticated',
5002 'user_email_token',
5003 'user_email_token_expires',
5004 'user_registration',
5005 'user_editcount',
5010 * Factory function for fatal permission-denied errors
5012 * @since 1.22
5013 * @param string $permission User right required
5014 * @return Status
5016 static function newFatalPermissionDeniedStatus( $permission ) {
5017 global $wgLang;
5019 $groups = array_map(
5020 array( 'User', 'makeGroupLinkWiki' ),
5021 User::getGroupsWithPermission( $permission )
5024 if ( $groups ) {
5025 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5026 } else {
5027 return Status::newFatal( 'badaccess-group0' );