Unpersist the session on logout
[mediawiki.git] / includes / user / User.php
blob1f9e88204677d9fdcbe7140ea06a8b27fb73fd48
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 use MediaWiki\Session\SessionManager;
25 /**
26 * String Some punctuation to prevent editing from broken text-mangling proxies.
27 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::SUFFIX
28 * @ingroup Constants
30 define( 'EDIT_TOKEN_SUFFIX', MediaWiki\Session\Token::SUFFIX );
32 /**
33 * The User object encapsulates all of the user-specific settings (user_id,
34 * name, rights, email address, options, last login time). Client
35 * classes use the getXXX() functions to access these fields. These functions
36 * do all the work of determining whether the user is logged in,
37 * whether the requested option can be satisfied from cookies or
38 * whether a database query is needed. Most of the settings needed
39 * for rendering normal pages are set in the cookie to minimize use
40 * of the database.
42 class User implements IDBAccessObject {
43 /**
44 * @const int Number of characters in user_token field.
46 const TOKEN_LENGTH = 32;
48 /**
49 * @const string An invalid value for user_token
51 const INVALID_TOKEN = '*** INVALID ***';
53 /**
54 * Global constant made accessible as class constants so that autoloader
55 * magic can be used.
56 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::SUFFIX
58 const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
60 /**
61 * @const int Serialized record version.
63 const VERSION = 10;
65 /**
66 * Maximum items in $mWatchedItems
68 const MAX_WATCHED_ITEMS_CACHE = 100;
70 /**
71 * Exclude user options that are set to their default value.
72 * @since 1.25
74 const GETOPTIONS_EXCLUDE_DEFAULTS = 1;
76 /**
77 * Array of Strings List of member variables which are saved to the
78 * shared cache (memcached). Any operation which changes the
79 * corresponding database fields must call a cache-clearing function.
80 * @showinitializer
82 protected static $mCacheVars = [
83 // user table
84 'mId',
85 'mName',
86 'mRealName',
87 'mEmail',
88 'mTouched',
89 'mToken',
90 'mEmailAuthenticated',
91 'mEmailToken',
92 'mEmailTokenExpires',
93 'mRegistration',
94 'mEditCount',
95 // user_groups table
96 'mGroups',
97 // user_properties table
98 'mOptionOverrides',
102 * Array of Strings Core rights.
103 * Each of these should have a corresponding message of the form
104 * "right-$right".
105 * @showinitializer
107 protected static $mCoreRights = [
108 'apihighlimits',
109 'applychangetags',
110 'autoconfirmed',
111 'autocreateaccount',
112 'autopatrol',
113 'bigdelete',
114 'block',
115 'blockemail',
116 'bot',
117 'browsearchive',
118 'changetags',
119 'createaccount',
120 'createpage',
121 'createtalk',
122 'delete',
123 'deletedhistory',
124 'deletedtext',
125 'deletelogentry',
126 'deleterevision',
127 'edit',
128 'editcontentmodel',
129 'editinterface',
130 'editprotected',
131 'editmyoptions',
132 'editmyprivateinfo',
133 'editmyusercss',
134 'editmyuserjs',
135 'editmywatchlist',
136 'editsemiprotected',
137 'editusercssjs', # deprecated
138 'editusercss',
139 'edituserjs',
140 'hideuser',
141 'import',
142 'importupload',
143 'ipblock-exempt',
144 'managechangetags',
145 'markbotedits',
146 'mergehistory',
147 'minoredit',
148 'move',
149 'movefile',
150 'move-categorypages',
151 'move-rootuserpages',
152 'move-subpages',
153 'nominornewtalk',
154 'noratelimit',
155 'override-export-depth',
156 'pagelang',
157 'passwordreset',
158 'patrol',
159 'patrolmarks',
160 'protect',
161 'purge',
162 'read',
163 'reupload',
164 'reupload-own',
165 'reupload-shared',
166 'rollback',
167 'sendemail',
168 'siteadmin',
169 'suppressionlog',
170 'suppressredirect',
171 'suppressrevision',
172 'unblockself',
173 'undelete',
174 'unwatchedpages',
175 'upload',
176 'upload_by_url',
177 'userrights',
178 'userrights-interwiki',
179 'viewmyprivateinfo',
180 'viewmywatchlist',
181 'viewsuppressed',
182 'writeapi',
186 * String Cached results of getAllRights()
188 protected static $mAllRights = false;
190 /** Cache variables */
191 // @{
192 public $mId;
193 /** @var string */
194 public $mName;
195 /** @var string */
196 public $mRealName;
198 /** @var string */
199 public $mEmail;
200 /** @var string TS_MW timestamp from the DB */
201 public $mTouched;
202 /** @var string TS_MW timestamp from cache */
203 protected $mQuickTouched;
204 /** @var string */
205 protected $mToken;
206 /** @var string */
207 public $mEmailAuthenticated;
208 /** @var string */
209 protected $mEmailToken;
210 /** @var string */
211 protected $mEmailTokenExpires;
212 /** @var string */
213 protected $mRegistration;
214 /** @var int */
215 protected $mEditCount;
216 /** @var array */
217 public $mGroups;
218 /** @var array */
219 protected $mOptionOverrides;
220 // @}
223 * Bool Whether the cache variables have been loaded.
225 // @{
226 public $mOptionsLoaded;
229 * Array with already loaded items or true if all items have been loaded.
231 protected $mLoadedItems = [];
232 // @}
235 * String Initialization data source if mLoadedItems!==true. May be one of:
236 * - 'defaults' anonymous user initialised from class defaults
237 * - 'name' initialise from mName
238 * - 'id' initialise from mId
239 * - 'session' log in from session if possible
241 * Use the User::newFrom*() family of functions to set this.
243 public $mFrom;
246 * Lazy-initialized variables, invalidated with clearInstanceCache
248 protected $mNewtalk;
249 /** @var string */
250 protected $mDatePreference;
251 /** @var string */
252 public $mBlockedby;
253 /** @var string */
254 protected $mHash;
255 /** @var array */
256 public $mRights;
257 /** @var string */
258 protected $mBlockreason;
259 /** @var array */
260 protected $mEffectiveGroups;
261 /** @var array */
262 protected $mImplicitGroups;
263 /** @var array */
264 protected $mFormerGroups;
265 /** @var bool */
266 protected $mBlockedGlobally;
267 /** @var bool */
268 protected $mLocked;
269 /** @var bool */
270 public $mHideName;
271 /** @var array */
272 public $mOptions;
275 * @var WebRequest
277 private $mRequest;
279 /** @var Block */
280 public $mBlock;
282 /** @var bool */
283 protected $mAllowUsertalk;
285 /** @var Block */
286 private $mBlockedFromCreateAccount = false;
288 /** @var array */
289 private $mWatchedItems = [];
291 /** @var integer User::READ_* constant bitfield used to load data */
292 protected $queryFlagsUsed = self::READ_NORMAL;
294 public static $idCacheByName = [];
297 * Lightweight constructor for an anonymous user.
298 * Use the User::newFrom* factory functions for other kinds of users.
300 * @see newFromName()
301 * @see newFromId()
302 * @see newFromConfirmationCode()
303 * @see newFromSession()
304 * @see newFromRow()
306 public function __construct() {
307 $this->clearInstanceCache( 'defaults' );
311 * @return string
313 public function __toString() {
314 return $this->getName();
318 * Test if it's safe to load this User object.
320 * You should typically check this before using $wgUser or
321 * RequestContext::getUser in a method that might be called before the
322 * system has been fully initialized. If the object is unsafe, you should
323 * use an anonymous user:
324 * \code
325 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
326 * \endcode
328 * @since 1.27
329 * @return bool
331 public function isSafeToLoad() {
332 global $wgFullyInitialised;
334 // The user is safe to load if:
335 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
336 // * mLoadedItems === true (already loaded)
337 // * mFrom !== 'session' (sessions not involved at all)
339 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
340 $this->mLoadedItems === true || $this->mFrom !== 'session';
344 * Load the user table data for this object from the source given by mFrom.
346 * @param integer $flags User::READ_* constant bitfield
348 public function load( $flags = self::READ_NORMAL ) {
349 global $wgFullyInitialised;
351 if ( $this->mLoadedItems === true ) {
352 return;
355 // Set it now to avoid infinite recursion in accessors
356 $oldLoadedItems = $this->mLoadedItems;
357 $this->mLoadedItems = true;
358 $this->queryFlagsUsed = $flags;
360 // If this is called too early, things are likely to break.
361 if ( !$wgFullyInitialised && $this->mFrom === 'session' ) {
362 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
363 ->warning( 'User::loadFromSession called before the end of Setup.php', [
364 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
365 ] );
366 $this->loadDefaults();
367 $this->mLoadedItems = $oldLoadedItems;
368 return;
371 switch ( $this->mFrom ) {
372 case 'defaults':
373 $this->loadDefaults();
374 break;
375 case 'name':
376 // Make sure this thread sees its own changes
377 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
378 $flags |= self::READ_LATEST;
379 $this->queryFlagsUsed = $flags;
382 $this->mId = self::idFromName( $this->mName, $flags );
383 if ( !$this->mId ) {
384 // Nonexistent user placeholder object
385 $this->loadDefaults( $this->mName );
386 } else {
387 $this->loadFromId( $flags );
389 break;
390 case 'id':
391 $this->loadFromId( $flags );
392 break;
393 case 'session':
394 if ( !$this->loadFromSession() ) {
395 // Loading from session failed. Load defaults.
396 $this->loadDefaults();
398 Hooks::run( 'UserLoadAfterLoadFromSession', [ $this ] );
399 break;
400 default:
401 throw new UnexpectedValueException(
402 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
407 * Load user table data, given mId has already been set.
408 * @param integer $flags User::READ_* constant bitfield
409 * @return bool False if the ID does not exist, true otherwise
411 public function loadFromId( $flags = self::READ_NORMAL ) {
412 if ( $this->mId == 0 ) {
413 $this->loadDefaults();
414 return false;
417 // Try cache (unless this needs data from the master DB).
418 // NOTE: if this thread called saveSettings(), the cache was cleared.
419 $latest = DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST );
420 if ( $latest || !$this->loadFromCache() ) {
421 wfDebug( "User: cache miss for user {$this->mId}\n" );
422 // Load from DB (make sure this thread sees its own changes)
423 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
424 $flags |= self::READ_LATEST;
426 if ( !$this->loadFromDatabase( $flags ) ) {
427 // Can't load from ID, user is anonymous
428 return false;
430 $this->saveToCache();
433 $this->mLoadedItems = true;
434 $this->queryFlagsUsed = $flags;
436 return true;
440 * @since 1.27
441 * @param string $wikiId
442 * @param integer $userId
444 public static function purge( $wikiId, $userId ) {
445 $cache = ObjectCache::getMainWANInstance();
446 $cache->delete( $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId ) );
450 * @since 1.27
451 * @param WANObjectCache $cache
452 * @return string
454 protected function getCacheKey( WANObjectCache $cache ) {
455 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId );
459 * Load user data from shared cache, given mId has already been set.
461 * @return bool false if the ID does not exist or data is invalid, true otherwise
462 * @since 1.25
464 protected function loadFromCache() {
465 if ( $this->mId == 0 ) {
466 $this->loadDefaults();
467 return false;
470 $cache = ObjectCache::getMainWANInstance();
471 $key = $this->getCacheKey( $cache );
473 $processCache = ObjectCache::getLocalServerInstance( 'hash' );
474 $data = $processCache->get( $key );
475 if ( !is_array( $data ) ) {
476 $data = $cache->get( $key );
477 if ( !is_array( $data ) || $data['mVersion'] < self::VERSION ) {
478 // Object is expired
479 return false;
481 $processCache->set( $key, $data );
483 wfDebug( "User: got user {$this->mId} from cache\n" );
485 // Restore from cache
486 foreach ( self::$mCacheVars as $name ) {
487 $this->$name = $data[$name];
490 return true;
494 * Save user data to the shared cache
496 * This method should not be called outside the User class
498 public function saveToCache() {
499 $this->load();
500 $this->loadGroups();
501 $this->loadOptions();
503 if ( $this->isAnon() ) {
504 // Anonymous users are uncached
505 return;
508 $data = [];
509 foreach ( self::$mCacheVars as $name ) {
510 $data[$name] = $this->$name;
512 $data['mVersion'] = self::VERSION;
513 $opts = Database::getCacheSetOptions( wfGetDB( DB_SLAVE ) );
515 $cache = ObjectCache::getMainWANInstance();
516 $key = $this->getCacheKey( $cache );
517 $cache->set( $key, $data, $cache::TTL_HOUR, $opts );
520 /** @name newFrom*() static factory methods */
521 // @{
524 * Static factory method for creation from username.
526 * This is slightly less efficient than newFromId(), so use newFromId() if
527 * you have both an ID and a name handy.
529 * @param string $name Username, validated by Title::newFromText()
530 * @param string|bool $validate Validate username. Takes the same parameters as
531 * User::getCanonicalName(), except that true is accepted as an alias
532 * for 'valid', for BC.
534 * @return User|bool User object, or false if the username is invalid
535 * (e.g. if it contains illegal characters or is an IP address). If the
536 * username is not present in the database, the result will be a user object
537 * with a name, zero user ID and default settings.
539 public static function newFromName( $name, $validate = 'valid' ) {
540 if ( $validate === true ) {
541 $validate = 'valid';
543 $name = self::getCanonicalName( $name, $validate );
544 if ( $name === false ) {
545 return false;
546 } else {
547 // Create unloaded user object
548 $u = new User;
549 $u->mName = $name;
550 $u->mFrom = 'name';
551 $u->setItemLoaded( 'name' );
552 return $u;
557 * Static factory method for creation from a given user ID.
559 * @param int $id Valid user ID
560 * @return User The corresponding User object
562 public static function newFromId( $id ) {
563 $u = new User;
564 $u->mId = $id;
565 $u->mFrom = 'id';
566 $u->setItemLoaded( 'id' );
567 return $u;
571 * Factory method to fetch whichever user has a given email confirmation code.
572 * This code is generated when an account is created or its e-mail address
573 * has changed.
575 * If the code is invalid or has expired, returns NULL.
577 * @param string $code Confirmation code
578 * @param int $flags User::READ_* bitfield
579 * @return User|null
581 public static function newFromConfirmationCode( $code, $flags = 0 ) {
582 $db = ( $flags & self::READ_LATEST ) == self::READ_LATEST
583 ? wfGetDB( DB_MASTER )
584 : wfGetDB( DB_SLAVE );
586 $id = $db->selectField(
587 'user',
588 'user_id',
590 'user_email_token' => md5( $code ),
591 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
595 return $id ? User::newFromId( $id ) : null;
599 * Create a new user object using data from session. If the login
600 * credentials are invalid, the result is an anonymous user.
602 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
603 * @return User
605 public static function newFromSession( WebRequest $request = null ) {
606 $user = new User;
607 $user->mFrom = 'session';
608 $user->mRequest = $request;
609 return $user;
613 * Create a new user object from a user row.
614 * The row should have the following fields from the user table in it:
615 * - either user_name or user_id to load further data if needed (or both)
616 * - user_real_name
617 * - all other fields (email, etc.)
618 * It is useless to provide the remaining fields if either user_id,
619 * user_name and user_real_name are not provided because the whole row
620 * will be loaded once more from the database when accessing them.
622 * @param stdClass $row A row from the user table
623 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
624 * @return User
626 public static function newFromRow( $row, $data = null ) {
627 $user = new User;
628 $user->loadFromRow( $row, $data );
629 return $user;
633 * Static factory method for creation of a "system" user from username.
635 * A "system" user is an account that's used to attribute logged actions
636 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
637 * might include the 'Maintenance script' or 'Conversion script' accounts
638 * used by various scripts in the maintenance/ directory or accounts such
639 * as 'MediaWiki message delivery' used by the MassMessage extension.
641 * This can optionally create the user if it doesn't exist, and "steal" the
642 * account if it does exist.
644 * @param string $name Username
645 * @param array $options Options are:
646 * - validate: As for User::getCanonicalName(), default 'valid'
647 * - create: Whether to create the user if it doesn't already exist, default true
648 * - steal: Whether to reset the account's password and email if it
649 * already exists, default false
650 * @return User|null
652 public static function newSystemUser( $name, $options = [] ) {
653 $options += [
654 'validate' => 'valid',
655 'create' => true,
656 'steal' => false,
659 $name = self::getCanonicalName( $name, $options['validate'] );
660 if ( $name === false ) {
661 return null;
664 $dbw = wfGetDB( DB_MASTER );
665 $row = $dbw->selectRow(
666 'user',
667 array_merge(
668 self::selectFields(),
669 [ 'user_password', 'user_newpassword' ]
671 [ 'user_name' => $name ],
672 __METHOD__
674 if ( !$row ) {
675 // No user. Create it?
676 return $options['create'] ? self::createNew( $name ) : null;
678 $user = self::newFromRow( $row );
680 // A user is considered to exist as a non-system user if it has a
681 // password set, or a temporary password set, or an email set, or a
682 // non-invalid token.
683 $passwordFactory = new PasswordFactory();
684 $passwordFactory->init( RequestContext::getMain()->getConfig() );
685 try {
686 $password = $passwordFactory->newFromCiphertext( $row->user_password );
687 } catch ( PasswordError $e ) {
688 wfDebug( 'Invalid password hash found in database.' );
689 $password = PasswordFactory::newInvalidPassword();
691 try {
692 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword );
693 } catch ( PasswordError $e ) {
694 wfDebug( 'Invalid password hash found in database.' );
695 $newpassword = PasswordFactory::newInvalidPassword();
697 if ( !$password instanceof InvalidPassword || !$newpassword instanceof InvalidPassword
698 || $user->mEmail || $user->mToken !== self::INVALID_TOKEN
700 // User exists. Steal it?
701 if ( !$options['steal'] ) {
702 return null;
705 $nopass = PasswordFactory::newInvalidPassword()->toString();
707 $dbw->update(
708 'user',
710 'user_password' => $nopass,
711 'user_newpassword' => $nopass,
712 'user_newpass_time' => null,
714 [ 'user_id' => $user->getId() ],
715 __METHOD__
717 $user->invalidateEmail();
718 $user->mToken = self::INVALID_TOKEN;
719 $user->saveSettings();
720 SessionManager::singleton()->preventSessionsForUser( $user->getName() );
723 return $user;
726 // @}
729 * Get the username corresponding to a given user ID
730 * @param int $id User ID
731 * @return string|bool The corresponding username
733 public static function whoIs( $id ) {
734 return UserCache::singleton()->getProp( $id, 'name' );
738 * Get the real name of a user given their user ID
740 * @param int $id User ID
741 * @return string|bool The corresponding user's real name
743 public static function whoIsReal( $id ) {
744 return UserCache::singleton()->getProp( $id, 'real_name' );
748 * Get database id given a user name
749 * @param string $name Username
750 * @param integer $flags User::READ_* constant bitfield
751 * @return int|null The corresponding user's ID, or null if user is nonexistent
753 public static function idFromName( $name, $flags = self::READ_NORMAL ) {
754 $nt = Title::makeTitleSafe( NS_USER, $name );
755 if ( is_null( $nt ) ) {
756 // Illegal name
757 return null;
760 if ( !( $flags & self::READ_LATEST ) && isset( self::$idCacheByName[$name] ) ) {
761 return self::$idCacheByName[$name];
764 $db = ( $flags & self::READ_LATEST )
765 ? wfGetDB( DB_MASTER )
766 : wfGetDB( DB_SLAVE );
768 $s = $db->selectRow(
769 'user',
770 [ 'user_id' ],
771 [ 'user_name' => $nt->getText() ],
772 __METHOD__
775 if ( $s === false ) {
776 $result = null;
777 } else {
778 $result = $s->user_id;
781 self::$idCacheByName[$name] = $result;
783 if ( count( self::$idCacheByName ) > 1000 ) {
784 self::$idCacheByName = [];
787 return $result;
791 * Reset the cache used in idFromName(). For use in tests.
793 public static function resetIdByNameCache() {
794 self::$idCacheByName = [];
798 * Does the string match an anonymous IPv4 address?
800 * This function exists for username validation, in order to reject
801 * usernames which are similar in form to IP addresses. Strings such
802 * as 300.300.300.300 will return true because it looks like an IP
803 * address, despite not being strictly valid.
805 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
806 * address because the usemod software would "cloak" anonymous IP
807 * addresses like this, if we allowed accounts like this to be created
808 * new users could get the old edits of these anonymous users.
810 * @param string $name Name to match
811 * @return bool
813 public static function isIP( $name ) {
814 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
815 || IP::isIPv6( $name );
819 * Is the input a valid username?
821 * Checks if the input is a valid username, we don't want an empty string,
822 * an IP address, anything that contains slashes (would mess up subpages),
823 * is longer than the maximum allowed username size or doesn't begin with
824 * a capital letter.
826 * @param string $name Name to match
827 * @return bool
829 public static function isValidUserName( $name ) {
830 global $wgContLang, $wgMaxNameChars;
832 if ( $name == ''
833 || User::isIP( $name )
834 || strpos( $name, '/' ) !== false
835 || strlen( $name ) > $wgMaxNameChars
836 || $name != $wgContLang->ucfirst( $name )
838 wfDebugLog( 'username', __METHOD__ .
839 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
840 return false;
843 // Ensure that the name can't be misresolved as a different title,
844 // such as with extra namespace keys at the start.
845 $parsed = Title::newFromText( $name );
846 if ( is_null( $parsed )
847 || $parsed->getNamespace()
848 || strcmp( $name, $parsed->getPrefixedText() ) ) {
849 wfDebugLog( 'username', __METHOD__ .
850 ": '$name' invalid due to ambiguous prefixes" );
851 return false;
854 // Check an additional blacklist of troublemaker characters.
855 // Should these be merged into the title char list?
856 $unicodeBlacklist = '/[' .
857 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
858 '\x{00a0}' . # non-breaking space
859 '\x{2000}-\x{200f}' . # various whitespace
860 '\x{2028}-\x{202f}' . # breaks and control chars
861 '\x{3000}' . # ideographic space
862 '\x{e000}-\x{f8ff}' . # private use
863 ']/u';
864 if ( preg_match( $unicodeBlacklist, $name ) ) {
865 wfDebugLog( 'username', __METHOD__ .
866 ": '$name' invalid due to blacklisted characters" );
867 return false;
870 return true;
874 * Usernames which fail to pass this function will be blocked
875 * from user login and new account registrations, but may be used
876 * internally by batch processes.
878 * If an account already exists in this form, login will be blocked
879 * by a failure to pass this function.
881 * @param string $name Name to match
882 * @return bool
884 public static function isUsableName( $name ) {
885 global $wgReservedUsernames;
886 // Must be a valid username, obviously ;)
887 if ( !self::isValidUserName( $name ) ) {
888 return false;
891 static $reservedUsernames = false;
892 if ( !$reservedUsernames ) {
893 $reservedUsernames = $wgReservedUsernames;
894 Hooks::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
897 // Certain names may be reserved for batch processes.
898 foreach ( $reservedUsernames as $reserved ) {
899 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
900 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
902 if ( $reserved == $name ) {
903 return false;
906 return true;
910 * Usernames which fail to pass this function will be blocked
911 * from new account registrations, but may be used internally
912 * either by batch processes or by user accounts which have
913 * already been created.
915 * Additional blacklisting may be added here rather than in
916 * isValidUserName() to avoid disrupting existing accounts.
918 * @param string $name String to match
919 * @return bool
921 public static function isCreatableName( $name ) {
922 global $wgInvalidUsernameCharacters;
924 // Ensure that the username isn't longer than 235 bytes, so that
925 // (at least for the builtin skins) user javascript and css files
926 // will work. (bug 23080)
927 if ( strlen( $name ) > 235 ) {
928 wfDebugLog( 'username', __METHOD__ .
929 ": '$name' invalid due to length" );
930 return false;
933 // Preg yells if you try to give it an empty string
934 if ( $wgInvalidUsernameCharacters !== '' ) {
935 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
936 wfDebugLog( 'username', __METHOD__ .
937 ": '$name' invalid due to wgInvalidUsernameCharacters" );
938 return false;
942 return self::isUsableName( $name );
946 * Is the input a valid password for this user?
948 * @param string $password Desired password
949 * @return bool
951 public function isValidPassword( $password ) {
952 // simple boolean wrapper for getPasswordValidity
953 return $this->getPasswordValidity( $password ) === true;
957 * Given unvalidated password input, return error message on failure.
959 * @param string $password Desired password
960 * @return bool|string|array True on success, string or array of error message on failure
962 public function getPasswordValidity( $password ) {
963 $result = $this->checkPasswordValidity( $password );
964 if ( $result->isGood() ) {
965 return true;
966 } else {
967 $messages = [];
968 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
969 $messages[] = $error['message'];
971 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
972 $messages[] = $warning['message'];
974 if ( count( $messages ) === 1 ) {
975 return $messages[0];
977 return $messages;
982 * Check if this is a valid password for this user
984 * Create a Status object based on the password's validity.
985 * The Status should be set to fatal if the user should not
986 * be allowed to log in, and should have any errors that
987 * would block changing the password.
989 * If the return value of this is not OK, the password
990 * should not be checked. If the return value is not Good,
991 * the password can be checked, but the user should not be
992 * able to set their password to this.
994 * @param string $password Desired password
995 * @param string $purpose one of 'login', 'create', 'reset'
996 * @return Status
997 * @since 1.23
999 public function checkPasswordValidity( $password, $purpose = 'login' ) {
1000 global $wgPasswordPolicy;
1002 $upp = new UserPasswordPolicy(
1003 $wgPasswordPolicy['policies'],
1004 $wgPasswordPolicy['checks']
1007 $status = Status::newGood();
1008 $result = false; // init $result to false for the internal checks
1010 if ( !Hooks::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1011 $status->error( $result );
1012 return $status;
1015 if ( $result === false ) {
1016 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
1017 return $status;
1018 } elseif ( $result === true ) {
1019 return $status;
1020 } else {
1021 $status->error( $result );
1022 return $status; // the isValidPassword hook set a string $result and returned true
1027 * Given unvalidated user input, return a canonical username, or false if
1028 * the username is invalid.
1029 * @param string $name User input
1030 * @param string|bool $validate Type of validation to use:
1031 * - false No validation
1032 * - 'valid' Valid for batch processes
1033 * - 'usable' Valid for batch processes and login
1034 * - 'creatable' Valid for batch processes, login and account creation
1036 * @throws InvalidArgumentException
1037 * @return bool|string
1039 public static function getCanonicalName( $name, $validate = 'valid' ) {
1040 // Force usernames to capital
1041 global $wgContLang;
1042 $name = $wgContLang->ucfirst( $name );
1044 # Reject names containing '#'; these will be cleaned up
1045 # with title normalisation, but then it's too late to
1046 # check elsewhere
1047 if ( strpos( $name, '#' ) !== false ) {
1048 return false;
1051 // Clean up name according to title rules,
1052 // but only when validation is requested (bug 12654)
1053 $t = ( $validate !== false ) ?
1054 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
1055 // Check for invalid titles
1056 if ( is_null( $t ) ) {
1057 return false;
1060 // Reject various classes of invalid names
1061 global $wgAuth;
1062 $name = $wgAuth->getCanonicalName( $t->getText() );
1064 switch ( $validate ) {
1065 case false:
1066 break;
1067 case 'valid':
1068 if ( !User::isValidUserName( $name ) ) {
1069 $name = false;
1071 break;
1072 case 'usable':
1073 if ( !User::isUsableName( $name ) ) {
1074 $name = false;
1076 break;
1077 case 'creatable':
1078 if ( !User::isCreatableName( $name ) ) {
1079 $name = false;
1081 break;
1082 default:
1083 throw new InvalidArgumentException(
1084 'Invalid parameter value for $validate in ' . __METHOD__ );
1086 return $name;
1090 * Count the number of edits of a user
1092 * @param int $uid User ID to check
1093 * @return int The user's edit count
1095 * @deprecated since 1.21 in favour of User::getEditCount
1097 public static function edits( $uid ) {
1098 wfDeprecated( __METHOD__, '1.21' );
1099 $user = self::newFromId( $uid );
1100 return $user->getEditCount();
1104 * Return a random password.
1106 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1107 * @return string New random password
1109 public static function randomPassword() {
1110 global $wgMinimalPasswordLength;
1111 return PasswordFactory::generateRandomPasswordString( $wgMinimalPasswordLength );
1115 * Set cached properties to default.
1117 * @note This no longer clears uncached lazy-initialised properties;
1118 * the constructor does that instead.
1120 * @param string|bool $name
1122 public function loadDefaults( $name = false ) {
1123 $this->mId = 0;
1124 $this->mName = $name;
1125 $this->mRealName = '';
1126 $this->mEmail = '';
1127 $this->mOptionOverrides = null;
1128 $this->mOptionsLoaded = false;
1130 $loggedOut = $this->mRequest && !defined( 'MW_NO_SESSION' )
1131 ? $this->mRequest->getSession()->getLoggedOutTimestamp() : 0;
1132 if ( $loggedOut !== 0 ) {
1133 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
1134 } else {
1135 $this->mTouched = '1'; # Allow any pages to be cached
1138 $this->mToken = null; // Don't run cryptographic functions till we need a token
1139 $this->mEmailAuthenticated = null;
1140 $this->mEmailToken = '';
1141 $this->mEmailTokenExpires = null;
1142 $this->mRegistration = wfTimestamp( TS_MW );
1143 $this->mGroups = [];
1145 Hooks::run( 'UserLoadDefaults', [ $this, $name ] );
1149 * Return whether an item has been loaded.
1151 * @param string $item Item to check. Current possibilities:
1152 * - id
1153 * - name
1154 * - realname
1155 * @param string $all 'all' to check if the whole object has been loaded
1156 * or any other string to check if only the item is available (e.g.
1157 * for optimisation)
1158 * @return bool
1160 public function isItemLoaded( $item, $all = 'all' ) {
1161 return ( $this->mLoadedItems === true && $all === 'all' ) ||
1162 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1166 * Set that an item has been loaded
1168 * @param string $item
1170 protected function setItemLoaded( $item ) {
1171 if ( is_array( $this->mLoadedItems ) ) {
1172 $this->mLoadedItems[$item] = true;
1177 * Load user data from the session.
1179 * @return bool True if the user is logged in, false otherwise.
1181 private function loadFromSession() {
1182 // Deprecated hook
1183 $result = null;
1184 Hooks::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1185 if ( $result !== null ) {
1186 return $result;
1189 // MediaWiki\Session\Session already did the necessary authentication of the user
1190 // returned here, so just use it if applicable.
1191 $session = $this->getRequest()->getSession();
1192 $user = $session->getUser();
1193 if ( $user->isLoggedIn() ) {
1194 $this->loadFromUserObject( $user );
1195 // Other code expects these to be set in the session, so set them.
1196 $session->set( 'wsUserID', $this->getId() );
1197 $session->set( 'wsUserName', $this->getName() );
1198 $session->set( 'wsToken', $this->getToken() );
1199 return true;
1202 return false;
1206 * Load user and user_group data from the database.
1207 * $this->mId must be set, this is how the user is identified.
1209 * @param integer $flags User::READ_* constant bitfield
1210 * @return bool True if the user exists, false if the user is anonymous
1212 public function loadFromDatabase( $flags = self::READ_LATEST ) {
1213 // Paranoia
1214 $this->mId = intval( $this->mId );
1216 // Anonymous user
1217 if ( !$this->mId ) {
1218 $this->loadDefaults();
1219 return false;
1222 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
1223 $db = wfGetDB( $index );
1225 $s = $db->selectRow(
1226 'user',
1227 self::selectFields(),
1228 [ 'user_id' => $this->mId ],
1229 __METHOD__,
1230 $options
1233 $this->queryFlagsUsed = $flags;
1234 Hooks::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1236 if ( $s !== false ) {
1237 // Initialise user table data
1238 $this->loadFromRow( $s );
1239 $this->mGroups = null; // deferred
1240 $this->getEditCount(); // revalidation for nulls
1241 return true;
1242 } else {
1243 // Invalid user_id
1244 $this->mId = 0;
1245 $this->loadDefaults();
1246 return false;
1251 * Initialize this object from a row from the user table.
1253 * @param stdClass $row Row from the user table to load.
1254 * @param array $data Further user data to load into the object
1256 * user_groups Array with groups out of the user_groups table
1257 * user_properties Array with properties out of the user_properties table
1259 protected function loadFromRow( $row, $data = null ) {
1260 $all = true;
1262 $this->mGroups = null; // deferred
1264 if ( isset( $row->user_name ) ) {
1265 $this->mName = $row->user_name;
1266 $this->mFrom = 'name';
1267 $this->setItemLoaded( 'name' );
1268 } else {
1269 $all = false;
1272 if ( isset( $row->user_real_name ) ) {
1273 $this->mRealName = $row->user_real_name;
1274 $this->setItemLoaded( 'realname' );
1275 } else {
1276 $all = false;
1279 if ( isset( $row->user_id ) ) {
1280 $this->mId = intval( $row->user_id );
1281 $this->mFrom = 'id';
1282 $this->setItemLoaded( 'id' );
1283 } else {
1284 $all = false;
1287 if ( isset( $row->user_id ) && isset( $row->user_name ) ) {
1288 self::$idCacheByName[$row->user_name] = $row->user_id;
1291 if ( isset( $row->user_editcount ) ) {
1292 $this->mEditCount = $row->user_editcount;
1293 } else {
1294 $all = false;
1297 if ( isset( $row->user_touched ) ) {
1298 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1299 } else {
1300 $all = false;
1303 if ( isset( $row->user_token ) ) {
1304 // The definition for the column is binary(32), so trim the NULs
1305 // that appends. The previous definition was char(32), so trim
1306 // spaces too.
1307 $this->mToken = rtrim( $row->user_token, " \0" );
1308 if ( $this->mToken === '' ) {
1309 $this->mToken = null;
1311 } else {
1312 $all = false;
1315 if ( isset( $row->user_email ) ) {
1316 $this->mEmail = $row->user_email;
1317 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1318 $this->mEmailToken = $row->user_email_token;
1319 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1320 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1321 } else {
1322 $all = false;
1325 if ( $all ) {
1326 $this->mLoadedItems = true;
1329 if ( is_array( $data ) ) {
1330 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1331 $this->mGroups = $data['user_groups'];
1333 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1334 $this->loadOptions( $data['user_properties'] );
1340 * Load the data for this user object from another user object.
1342 * @param User $user
1344 protected function loadFromUserObject( $user ) {
1345 $user->load();
1346 $user->loadGroups();
1347 $user->loadOptions();
1348 foreach ( self::$mCacheVars as $var ) {
1349 $this->$var = $user->$var;
1354 * Load the groups from the database if they aren't already loaded.
1356 private function loadGroups() {
1357 if ( is_null( $this->mGroups ) ) {
1358 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
1359 ? wfGetDB( DB_MASTER )
1360 : wfGetDB( DB_SLAVE );
1361 $res = $db->select( 'user_groups',
1362 [ 'ug_group' ],
1363 [ 'ug_user' => $this->mId ],
1364 __METHOD__ );
1365 $this->mGroups = [];
1366 foreach ( $res as $row ) {
1367 $this->mGroups[] = $row->ug_group;
1373 * Add the user to the group if he/she meets given criteria.
1375 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1376 * possible to remove manually via Special:UserRights. In such case it
1377 * will not be re-added automatically. The user will also not lose the
1378 * group if they no longer meet the criteria.
1380 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1382 * @return array Array of groups the user has been promoted to.
1384 * @see $wgAutopromoteOnce
1386 public function addAutopromoteOnceGroups( $event ) {
1387 global $wgAutopromoteOnceLogInRC, $wgAuth;
1389 if ( wfReadOnly() || !$this->getId() ) {
1390 return [];
1393 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1394 if ( !count( $toPromote ) ) {
1395 return [];
1398 if ( !$this->checkAndSetTouched() ) {
1399 return []; // raced out (bug T48834)
1402 $oldGroups = $this->getGroups(); // previous groups
1403 foreach ( $toPromote as $group ) {
1404 $this->addGroup( $group );
1406 // update groups in external authentication database
1407 Hooks::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1408 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1410 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1412 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1413 $logEntry->setPerformer( $this );
1414 $logEntry->setTarget( $this->getUserPage() );
1415 $logEntry->setParameters( [
1416 '4::oldgroups' => $oldGroups,
1417 '5::newgroups' => $newGroups,
1418 ] );
1419 $logid = $logEntry->insert();
1420 if ( $wgAutopromoteOnceLogInRC ) {
1421 $logEntry->publish( $logid );
1424 return $toPromote;
1428 * Bump user_touched if it didn't change since this object was loaded
1430 * On success, the mTouched field is updated.
1431 * The user serialization cache is always cleared.
1433 * @return bool Whether user_touched was actually updated
1434 * @since 1.26
1436 protected function checkAndSetTouched() {
1437 $this->load();
1439 if ( !$this->mId ) {
1440 return false; // anon
1443 // Get a new user_touched that is higher than the old one
1444 $oldTouched = $this->mTouched;
1445 $newTouched = $this->newTouchedTimestamp();
1447 $dbw = wfGetDB( DB_MASTER );
1448 $dbw->update( 'user',
1449 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1451 'user_id' => $this->mId,
1452 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1454 __METHOD__
1456 $success = ( $dbw->affectedRows() > 0 );
1458 if ( $success ) {
1459 $this->mTouched = $newTouched;
1460 $this->clearSharedCache();
1461 } else {
1462 // Clears on failure too since that is desired if the cache is stale
1463 $this->clearSharedCache( 'refresh' );
1466 return $success;
1470 * Clear various cached data stored in this object. The cache of the user table
1471 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1473 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1474 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1476 public function clearInstanceCache( $reloadFrom = false ) {
1477 $this->mNewtalk = -1;
1478 $this->mDatePreference = null;
1479 $this->mBlockedby = -1; # Unset
1480 $this->mHash = false;
1481 $this->mRights = null;
1482 $this->mEffectiveGroups = null;
1483 $this->mImplicitGroups = null;
1484 $this->mGroups = null;
1485 $this->mOptions = null;
1486 $this->mOptionsLoaded = false;
1487 $this->mEditCount = null;
1489 if ( $reloadFrom ) {
1490 $this->mLoadedItems = [];
1491 $this->mFrom = $reloadFrom;
1496 * Combine the language default options with any site-specific options
1497 * and add the default language variants.
1499 * @return array Array of String options
1501 public static function getDefaultOptions() {
1502 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1504 static $defOpt = null;
1505 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1506 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1507 // mid-request and see that change reflected in the return value of this function.
1508 // Which is insane and would never happen during normal MW operation
1509 return $defOpt;
1512 $defOpt = $wgDefaultUserOptions;
1513 // Default language setting
1514 $defOpt['language'] = $wgContLang->getCode();
1515 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1516 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1518 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1519 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1521 $defOpt['skin'] = Skin::normalizeKey( $wgDefaultSkin );
1523 Hooks::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1525 return $defOpt;
1529 * Get a given default option value.
1531 * @param string $opt Name of option to retrieve
1532 * @return string Default option value
1534 public static function getDefaultOption( $opt ) {
1535 $defOpts = self::getDefaultOptions();
1536 if ( isset( $defOpts[$opt] ) ) {
1537 return $defOpts[$opt];
1538 } else {
1539 return null;
1544 * Get blocking information
1545 * @param bool $bFromSlave Whether to check the slave database first.
1546 * To improve performance, non-critical checks are done against slaves.
1547 * Check when actually saving should be done against master.
1549 private function getBlockedStatus( $bFromSlave = true ) {
1550 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1552 if ( -1 != $this->mBlockedby ) {
1553 return;
1556 wfDebug( __METHOD__ . ": checking...\n" );
1558 // Initialize data...
1559 // Otherwise something ends up stomping on $this->mBlockedby when
1560 // things get lazy-loaded later, causing false positive block hits
1561 // due to -1 !== 0. Probably session-related... Nothing should be
1562 // overwriting mBlockedby, surely?
1563 $this->load();
1565 # We only need to worry about passing the IP address to the Block generator if the
1566 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1567 # know which IP address they're actually coming from
1568 $ip = null;
1569 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1570 // $wgUser->getName() only works after the end of Setup.php. Until
1571 // then, assume it's a logged-out user.
1572 $globalUserName = $wgUser->isSafeToLoad()
1573 ? $wgUser->getName()
1574 : IP::sanitizeIP( $wgUser->getRequest()->getIP() );
1575 if ( $this->getName() === $globalUserName ) {
1576 $ip = $this->getRequest()->getIP();
1580 // User/IP blocking
1581 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1583 // Proxy blocking
1584 if ( !$block instanceof Block && $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1585 // Local list
1586 if ( self::isLocallyBlockedProxy( $ip ) ) {
1587 $block = new Block;
1588 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1589 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1590 $block->setTarget( $ip );
1591 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1592 $block = new Block;
1593 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1594 $block->mReason = wfMessage( 'sorbsreason' )->text();
1595 $block->setTarget( $ip );
1599 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1600 if ( !$block instanceof Block
1601 && $wgApplyIpBlocksToXff
1602 && $ip !== null
1603 && !in_array( $ip, $wgProxyWhitelist )
1605 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1606 $xff = array_map( 'trim', explode( ',', $xff ) );
1607 $xff = array_diff( $xff, [ $ip ] );
1608 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1609 $block = Block::chooseBlock( $xffblocks, $xff );
1610 if ( $block instanceof Block ) {
1611 # Mangle the reason to alert the user that the block
1612 # originated from matching the X-Forwarded-For header.
1613 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1617 if ( $block instanceof Block ) {
1618 wfDebug( __METHOD__ . ": Found block.\n" );
1619 $this->mBlock = $block;
1620 $this->mBlockedby = $block->getByName();
1621 $this->mBlockreason = $block->mReason;
1622 $this->mHideName = $block->mHideName;
1623 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1624 } else {
1625 $this->mBlockedby = '';
1626 $this->mHideName = 0;
1627 $this->mAllowUsertalk = false;
1630 // Extensions
1631 Hooks::run( 'GetBlockedStatus', [ &$this ] );
1636 * Whether the given IP is in a DNS blacklist.
1638 * @param string $ip IP to check
1639 * @param bool $checkWhitelist Whether to check the whitelist first
1640 * @return bool True if blacklisted.
1642 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1643 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1645 if ( !$wgEnableDnsBlacklist ) {
1646 return false;
1649 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1650 return false;
1653 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1657 * Whether the given IP is in a given DNS blacklist.
1659 * @param string $ip IP to check
1660 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1661 * @return bool True if blacklisted.
1663 public function inDnsBlacklist( $ip, $bases ) {
1665 $found = false;
1666 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1667 if ( IP::isIPv4( $ip ) ) {
1668 // Reverse IP, bug 21255
1669 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1671 foreach ( (array)$bases as $base ) {
1672 // Make hostname
1673 // If we have an access key, use that too (ProjectHoneypot, etc.)
1674 $basename = $base;
1675 if ( is_array( $base ) ) {
1676 if ( count( $base ) >= 2 ) {
1677 // Access key is 1, base URL is 0
1678 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1679 } else {
1680 $host = "$ipReversed.{$base[0]}";
1682 $basename = $base[0];
1683 } else {
1684 $host = "$ipReversed.$base";
1687 // Send query
1688 $ipList = gethostbynamel( $host );
1690 if ( $ipList ) {
1691 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1692 $found = true;
1693 break;
1694 } else {
1695 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1700 return $found;
1704 * Check if an IP address is in the local proxy list
1706 * @param string $ip
1708 * @return bool
1710 public static function isLocallyBlockedProxy( $ip ) {
1711 global $wgProxyList;
1713 if ( !$wgProxyList ) {
1714 return false;
1717 if ( !is_array( $wgProxyList ) ) {
1718 // Load from the specified file
1719 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1722 if ( !is_array( $wgProxyList ) ) {
1723 $ret = false;
1724 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1725 $ret = true;
1726 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1727 // Old-style flipped proxy list
1728 $ret = true;
1729 } else {
1730 $ret = false;
1732 return $ret;
1736 * Is this user subject to rate limiting?
1738 * @return bool True if rate limited
1740 public function isPingLimitable() {
1741 global $wgRateLimitsExcludedIPs;
1742 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1743 // No other good way currently to disable rate limits
1744 // for specific IPs. :P
1745 // But this is a crappy hack and should die.
1746 return false;
1748 return !$this->isAllowed( 'noratelimit' );
1752 * Primitive rate limits: enforce maximum actions per time period
1753 * to put a brake on flooding.
1755 * The method generates both a generic profiling point and a per action one
1756 * (suffix being "-$action".
1758 * @note When using a shared cache like memcached, IP-address
1759 * last-hit counters will be shared across wikis.
1761 * @param string $action Action to enforce; 'edit' if unspecified
1762 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1763 * @return bool True if a rate limiter was tripped
1765 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1766 // Call the 'PingLimiter' hook
1767 $result = false;
1768 if ( !Hooks::run( 'PingLimiter', [ &$this, $action, &$result, $incrBy ] ) ) {
1769 return $result;
1772 global $wgRateLimits;
1773 if ( !isset( $wgRateLimits[$action] ) ) {
1774 return false;
1777 // Some groups shouldn't trigger the ping limiter, ever
1778 if ( !$this->isPingLimitable() ) {
1779 return false;
1782 $limits = $wgRateLimits[$action];
1783 $keys = [];
1784 $id = $this->getId();
1785 $userLimit = false;
1786 $isNewbie = $this->isNewbie();
1788 if ( $id == 0 ) {
1789 // limits for anons
1790 if ( isset( $limits['anon'] ) ) {
1791 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1793 } else {
1794 // limits for logged-in users
1795 if ( isset( $limits['user'] ) ) {
1796 $userLimit = $limits['user'];
1798 // limits for newbie logged-in users
1799 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1800 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1804 // limits for anons and for newbie logged-in users
1805 if ( $isNewbie ) {
1806 // ip-based limits
1807 if ( isset( $limits['ip'] ) ) {
1808 $ip = $this->getRequest()->getIP();
1809 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1811 // subnet-based limits
1812 if ( isset( $limits['subnet'] ) ) {
1813 $ip = $this->getRequest()->getIP();
1814 $subnet = IP::getSubnet( $ip );
1815 if ( $subnet !== false ) {
1816 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1821 // Check for group-specific permissions
1822 // If more than one group applies, use the group with the highest limit ratio (max/period)
1823 foreach ( $this->getGroups() as $group ) {
1824 if ( isset( $limits[$group] ) ) {
1825 if ( $userLimit === false
1826 || $limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1828 $userLimit = $limits[$group];
1833 // Set the user limit key
1834 if ( $userLimit !== false ) {
1835 list( $max, $period ) = $userLimit;
1836 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1837 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1840 // ip-based limits for all ping-limitable users
1841 if ( isset( $limits['ip-all'] ) ) {
1842 $ip = $this->getRequest()->getIP();
1843 // ignore if user limit is more permissive
1844 if ( $isNewbie || $userLimit === false
1845 || $limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1846 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1850 // subnet-based limits for all ping-limitable users
1851 if ( isset( $limits['subnet-all'] ) ) {
1852 $ip = $this->getRequest()->getIP();
1853 $subnet = IP::getSubnet( $ip );
1854 if ( $subnet !== false ) {
1855 // ignore if user limit is more permissive
1856 if ( $isNewbie || $userLimit === false
1857 || $limits['ip-all'][0] / $limits['ip-all'][1]
1858 > $userLimit[0] / $userLimit[1] ) {
1859 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1864 $cache = ObjectCache::getLocalClusterInstance();
1866 $triggered = false;
1867 foreach ( $keys as $key => $limit ) {
1868 list( $max, $period ) = $limit;
1869 $summary = "(limit $max in {$period}s)";
1870 $count = $cache->get( $key );
1871 // Already pinged?
1872 if ( $count ) {
1873 if ( $count >= $max ) {
1874 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1875 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1876 $triggered = true;
1877 } else {
1878 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1880 } else {
1881 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1882 if ( $incrBy > 0 ) {
1883 $cache->add( $key, 0, intval( $period ) ); // first ping
1886 if ( $incrBy > 0 ) {
1887 $cache->incr( $key, $incrBy );
1891 return $triggered;
1895 * Check if user is blocked
1897 * @param bool $bFromSlave Whether to check the slave database instead of
1898 * the master. Hacked from false due to horrible probs on site.
1899 * @return bool True if blocked, false otherwise
1901 public function isBlocked( $bFromSlave = true ) {
1902 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1906 * Get the block affecting the user, or null if the user is not blocked
1908 * @param bool $bFromSlave Whether to check the slave database instead of the master
1909 * @return Block|null
1911 public function getBlock( $bFromSlave = true ) {
1912 $this->getBlockedStatus( $bFromSlave );
1913 return $this->mBlock instanceof Block ? $this->mBlock : null;
1917 * Check if user is blocked from editing a particular article
1919 * @param Title $title Title to check
1920 * @param bool $bFromSlave Whether to check the slave database instead of the master
1921 * @return bool
1923 public function isBlockedFrom( $title, $bFromSlave = false ) {
1924 global $wgBlockAllowsUTEdit;
1926 $blocked = $this->isBlocked( $bFromSlave );
1927 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1928 // If a user's name is suppressed, they cannot make edits anywhere
1929 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
1930 && $title->getNamespace() == NS_USER_TALK ) {
1931 $blocked = false;
1932 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1935 Hooks::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
1937 return $blocked;
1941 * If user is blocked, return the name of the user who placed the block
1942 * @return string Name of blocker
1944 public function blockedBy() {
1945 $this->getBlockedStatus();
1946 return $this->mBlockedby;
1950 * If user is blocked, return the specified reason for the block
1951 * @return string Blocking reason
1953 public function blockedFor() {
1954 $this->getBlockedStatus();
1955 return $this->mBlockreason;
1959 * If user is blocked, return the ID for the block
1960 * @return int Block ID
1962 public function getBlockId() {
1963 $this->getBlockedStatus();
1964 return ( $this->mBlock ? $this->mBlock->getId() : false );
1968 * Check if user is blocked on all wikis.
1969 * Do not use for actual edit permission checks!
1970 * This is intended for quick UI checks.
1972 * @param string $ip IP address, uses current client if none given
1973 * @return bool True if blocked, false otherwise
1975 public function isBlockedGlobally( $ip = '' ) {
1976 if ( $this->mBlockedGlobally !== null ) {
1977 return $this->mBlockedGlobally;
1979 // User is already an IP?
1980 if ( IP::isIPAddress( $this->getName() ) ) {
1981 $ip = $this->getName();
1982 } elseif ( !$ip ) {
1983 $ip = $this->getRequest()->getIP();
1985 $blocked = false;
1986 Hooks::run( 'UserIsBlockedGlobally', [ &$this, $ip, &$blocked ] );
1987 $this->mBlockedGlobally = (bool)$blocked;
1988 return $this->mBlockedGlobally;
1992 * Check if user account is locked
1994 * @return bool True if locked, false otherwise
1996 public function isLocked() {
1997 if ( $this->mLocked !== null ) {
1998 return $this->mLocked;
2000 global $wgAuth;
2001 $authUser = $wgAuth->getUserInstance( $this );
2002 $this->mLocked = (bool)$authUser->isLocked();
2003 Hooks::run( 'UserIsLocked', [ $this, &$this->mLocked ] );
2004 return $this->mLocked;
2008 * Check if user account is hidden
2010 * @return bool True if hidden, false otherwise
2012 public function isHidden() {
2013 if ( $this->mHideName !== null ) {
2014 return $this->mHideName;
2016 $this->getBlockedStatus();
2017 if ( !$this->mHideName ) {
2018 global $wgAuth;
2019 $authUser = $wgAuth->getUserInstance( $this );
2020 $this->mHideName = (bool)$authUser->isHidden();
2021 Hooks::run( 'UserIsHidden', [ $this, &$this->mHideName ] );
2023 return $this->mHideName;
2027 * Get the user's ID.
2028 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2030 public function getId() {
2031 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
2032 // Special case, we know the user is anonymous
2033 return 0;
2034 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2035 // Don't load if this was initialized from an ID
2036 $this->load();
2038 return $this->mId;
2042 * Set the user and reload all fields according to a given ID
2043 * @param int $v User ID to reload
2045 public function setId( $v ) {
2046 $this->mId = $v;
2047 $this->clearInstanceCache( 'id' );
2051 * Get the user name, or the IP of an anonymous user
2052 * @return string User's name or IP address
2054 public function getName() {
2055 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2056 // Special case optimisation
2057 return $this->mName;
2058 } else {
2059 $this->load();
2060 if ( $this->mName === false ) {
2061 // Clean up IPs
2062 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
2064 return $this->mName;
2069 * Set the user name.
2071 * This does not reload fields from the database according to the given
2072 * name. Rather, it is used to create a temporary "nonexistent user" for
2073 * later addition to the database. It can also be used to set the IP
2074 * address for an anonymous user to something other than the current
2075 * remote IP.
2077 * @note User::newFromName() has roughly the same function, when the named user
2078 * does not exist.
2079 * @param string $str New user name to set
2081 public function setName( $str ) {
2082 $this->load();
2083 $this->mName = $str;
2087 * Get the user's name escaped by underscores.
2088 * @return string Username escaped by underscores.
2090 public function getTitleKey() {
2091 return str_replace( ' ', '_', $this->getName() );
2095 * Check if the user has new messages.
2096 * @return bool True if the user has new messages
2098 public function getNewtalk() {
2099 $this->load();
2101 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2102 if ( $this->mNewtalk === -1 ) {
2103 $this->mNewtalk = false; # reset talk page status
2105 // Check memcached separately for anons, who have no
2106 // entire User object stored in there.
2107 if ( !$this->mId ) {
2108 global $wgDisableAnonTalk;
2109 if ( $wgDisableAnonTalk ) {
2110 // Anon newtalk disabled by configuration.
2111 $this->mNewtalk = false;
2112 } else {
2113 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName() );
2115 } else {
2116 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
2120 return (bool)$this->mNewtalk;
2124 * Return the data needed to construct links for new talk page message
2125 * alerts. If there are new messages, this will return an associative array
2126 * with the following data:
2127 * wiki: The database name of the wiki
2128 * link: Root-relative link to the user's talk page
2129 * rev: The last talk page revision that the user has seen or null. This
2130 * is useful for building diff links.
2131 * If there are no new messages, it returns an empty array.
2132 * @note This function was designed to accomodate multiple talk pages, but
2133 * currently only returns a single link and revision.
2134 * @return array
2136 public function getNewMessageLinks() {
2137 $talks = [];
2138 if ( !Hooks::run( 'UserRetrieveNewTalks', [ &$this, &$talks ] ) ) {
2139 return $talks;
2140 } elseif ( !$this->getNewtalk() ) {
2141 return [];
2143 $utp = $this->getTalkPage();
2144 $dbr = wfGetDB( DB_SLAVE );
2145 // Get the "last viewed rev" timestamp from the oldest message notification
2146 $timestamp = $dbr->selectField( 'user_newtalk',
2147 'MIN(user_last_timestamp)',
2148 $this->isAnon() ? [ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getID() ],
2149 __METHOD__ );
2150 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2151 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2155 * Get the revision ID for the last talk page revision viewed by the talk
2156 * page owner.
2157 * @return int|null Revision ID or null
2159 public function getNewMessageRevisionId() {
2160 $newMessageRevisionId = null;
2161 $newMessageLinks = $this->getNewMessageLinks();
2162 if ( $newMessageLinks ) {
2163 // Note: getNewMessageLinks() never returns more than a single link
2164 // and it is always for the same wiki, but we double-check here in
2165 // case that changes some time in the future.
2166 if ( count( $newMessageLinks ) === 1
2167 && $newMessageLinks[0]['wiki'] === wfWikiID()
2168 && $newMessageLinks[0]['rev']
2170 /** @var Revision $newMessageRevision */
2171 $newMessageRevision = $newMessageLinks[0]['rev'];
2172 $newMessageRevisionId = $newMessageRevision->getId();
2175 return $newMessageRevisionId;
2179 * Internal uncached check for new messages
2181 * @see getNewtalk()
2182 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2183 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2184 * @return bool True if the user has new messages
2186 protected function checkNewtalk( $field, $id ) {
2187 $dbr = wfGetDB( DB_SLAVE );
2189 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__ );
2191 return $ok !== false;
2195 * Add or update the new messages flag
2196 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2197 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2198 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2199 * @return bool True if successful, false otherwise
2201 protected function updateNewtalk( $field, $id, $curRev = null ) {
2202 // Get timestamp of the talk page revision prior to the current one
2203 $prevRev = $curRev ? $curRev->getPrevious() : false;
2204 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2205 // Mark the user as having new messages since this revision
2206 $dbw = wfGetDB( DB_MASTER );
2207 $dbw->insert( 'user_newtalk',
2208 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2209 __METHOD__,
2210 'IGNORE' );
2211 if ( $dbw->affectedRows() ) {
2212 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2213 return true;
2214 } else {
2215 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2216 return false;
2221 * Clear the new messages flag for the given user
2222 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2223 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2224 * @return bool True if successful, false otherwise
2226 protected function deleteNewtalk( $field, $id ) {
2227 $dbw = wfGetDB( DB_MASTER );
2228 $dbw->delete( 'user_newtalk',
2229 [ $field => $id ],
2230 __METHOD__ );
2231 if ( $dbw->affectedRows() ) {
2232 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2233 return true;
2234 } else {
2235 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2236 return false;
2241 * Update the 'You have new messages!' status.
2242 * @param bool $val Whether the user has new messages
2243 * @param Revision $curRev New, as yet unseen revision of the user talk
2244 * page. Ignored if null or !$val.
2246 public function setNewtalk( $val, $curRev = null ) {
2247 if ( wfReadOnly() ) {
2248 return;
2251 $this->load();
2252 $this->mNewtalk = $val;
2254 if ( $this->isAnon() ) {
2255 $field = 'user_ip';
2256 $id = $this->getName();
2257 } else {
2258 $field = 'user_id';
2259 $id = $this->getId();
2262 if ( $val ) {
2263 $changed = $this->updateNewtalk( $field, $id, $curRev );
2264 } else {
2265 $changed = $this->deleteNewtalk( $field, $id );
2268 if ( $changed ) {
2269 $this->invalidateCache();
2274 * Generate a current or new-future timestamp to be stored in the
2275 * user_touched field when we update things.
2276 * @return string Timestamp in TS_MW format
2278 private function newTouchedTimestamp() {
2279 global $wgClockSkewFudge;
2281 $time = wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2282 if ( $this->mTouched && $time <= $this->mTouched ) {
2283 $time = wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $this->mTouched ) + 1 );
2286 return $time;
2290 * Clear user data from memcached
2292 * Use after applying updates to the database; caller's
2293 * responsibility to update user_touched if appropriate.
2295 * Called implicitly from invalidateCache() and saveSettings().
2297 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2299 public function clearSharedCache( $mode = 'changed' ) {
2300 if ( !$this->getId() ) {
2301 return;
2304 $cache = ObjectCache::getMainWANInstance();
2305 $key = $this->getCacheKey( $cache );
2306 if ( $mode === 'refresh' ) {
2307 $cache->delete( $key, 1 );
2308 } else {
2309 wfGetDB( DB_MASTER )->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
2310 $cache->delete( $key );
2311 } );
2316 * Immediately touch the user data cache for this account
2318 * Calls touch() and removes account data from memcached
2320 public function invalidateCache() {
2321 $this->touch();
2322 $this->clearSharedCache();
2326 * Update the "touched" timestamp for the user
2328 * This is useful on various login/logout events when making sure that
2329 * a browser or proxy that has multiple tenants does not suffer cache
2330 * pollution where the new user sees the old users content. The value
2331 * of getTouched() is checked when determining 304 vs 200 responses.
2332 * Unlike invalidateCache(), this preserves the User object cache and
2333 * avoids database writes.
2335 * @since 1.25
2337 public function touch() {
2338 $id = $this->getId();
2339 if ( $id ) {
2340 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2341 ObjectCache::getMainWANInstance()->touchCheckKey( $key );
2342 $this->mQuickTouched = null;
2347 * Validate the cache for this account.
2348 * @param string $timestamp A timestamp in TS_MW format
2349 * @return bool
2351 public function validateCache( $timestamp ) {
2352 return ( $timestamp >= $this->getTouched() );
2356 * Get the user touched timestamp
2358 * Use this value only to validate caches via inequalities
2359 * such as in the case of HTTP If-Modified-Since response logic
2361 * @return string TS_MW Timestamp
2363 public function getTouched() {
2364 $this->load();
2366 if ( $this->mId ) {
2367 if ( $this->mQuickTouched === null ) {
2368 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId );
2369 $cache = ObjectCache::getMainWANInstance();
2371 $this->mQuickTouched = wfTimestamp( TS_MW, $cache->getCheckKeyTime( $key ) );
2374 return max( $this->mTouched, $this->mQuickTouched );
2377 return $this->mTouched;
2381 * Get the user_touched timestamp field (time of last DB updates)
2382 * @return string TS_MW Timestamp
2383 * @since 1.26
2385 public function getDBTouched() {
2386 $this->load();
2388 return $this->mTouched;
2392 * @deprecated Removed in 1.27.
2393 * @return Password
2394 * @since 1.24
2396 public function getPassword() {
2397 throw new BadMethodCallException( __METHOD__ . ' has been removed in 1.27' );
2401 * @deprecated Removed in 1.27.
2402 * @return Password
2403 * @since 1.24
2405 public function getTemporaryPassword() {
2406 throw new BadMethodCallException( __METHOD__ . ' has been removed in 1.27' );
2410 * Set the password and reset the random token.
2411 * Calls through to authentication plugin if necessary;
2412 * will have no effect if the auth plugin refuses to
2413 * pass the change through or if the legal password
2414 * checks fail.
2416 * As a special case, setting the password to null
2417 * wipes it, so the account cannot be logged in until
2418 * a new password is set, for instance via e-mail.
2420 * @deprecated since 1.27. AuthManager is coming.
2421 * @param string $str New password to set
2422 * @throws PasswordError On failure
2423 * @return bool
2425 public function setPassword( $str ) {
2426 global $wgAuth;
2428 if ( $str !== null ) {
2429 if ( !$wgAuth->allowPasswordChange() ) {
2430 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2433 $status = $this->checkPasswordValidity( $str );
2434 if ( !$status->isGood() ) {
2435 throw new PasswordError( $status->getMessage()->text() );
2439 if ( !$wgAuth->setPassword( $this, $str ) ) {
2440 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2443 $this->setToken();
2444 $this->setOption( 'watchlisttoken', false );
2445 $this->setPasswordInternal( $str );
2447 return true;
2451 * Set the password and reset the random token unconditionally.
2453 * @deprecated since 1.27. AuthManager is coming.
2454 * @param string|null $str New password to set or null to set an invalid
2455 * password hash meaning that the user will not be able to log in
2456 * through the web interface.
2458 public function setInternalPassword( $str ) {
2459 global $wgAuth;
2461 if ( $wgAuth->allowSetLocalPassword() ) {
2462 $this->setToken();
2463 $this->setOption( 'watchlisttoken', false );
2464 $this->setPasswordInternal( $str );
2469 * Actually set the password and such
2470 * @since 1.27 cannot set a password for a user not in the database
2471 * @param string|null $str New password to set or null to set an invalid
2472 * password hash meaning that the user will not be able to log in
2473 * through the web interface.
2475 private function setPasswordInternal( $str ) {
2476 $id = self::idFromName( $this->getName(), self::READ_LATEST );
2477 if ( $id == 0 ) {
2478 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2481 $passwordFactory = new PasswordFactory();
2482 $passwordFactory->init( RequestContext::getMain()->getConfig() );
2483 $dbw = wfGetDB( DB_MASTER );
2484 $dbw->update(
2485 'user',
2487 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2488 'user_newpassword' => PasswordFactory::newInvalidPassword()->toString(),
2489 'user_newpass_time' => $dbw->timestampOrNull( null ),
2492 'user_id' => $id,
2494 __METHOD__
2497 // When the main password is changed, invalidate all bot passwords too
2498 BotPassword::invalidateAllPasswordsForUser( $this->getName() );
2502 * Get the user's current token.
2503 * @param bool $forceCreation Force the generation of a new token if the
2504 * user doesn't have one (default=true for backwards compatibility).
2505 * @return string|null Token
2507 public function getToken( $forceCreation = true ) {
2508 global $wgAuthenticationTokenVersion;
2510 $this->load();
2511 if ( !$this->mToken && $forceCreation ) {
2512 $this->setToken();
2515 if ( !$this->mToken ) {
2516 // The user doesn't have a token, return null to indicate that.
2517 return null;
2518 } elseif ( $this->mToken === self::INVALID_TOKEN ) {
2519 // We return a random value here so existing token checks are very
2520 // likely to fail.
2521 return MWCryptRand::generateHex( self::TOKEN_LENGTH );
2522 } elseif ( $wgAuthenticationTokenVersion === null ) {
2523 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2524 return $this->mToken;
2525 } else {
2526 // $wgAuthenticationTokenVersion in use, so hmac it.
2527 $ret = MWCryptHash::hmac( $wgAuthenticationTokenVersion, $this->mToken, false );
2529 // The raw hash can be overly long. Shorten it up.
2530 $len = max( 32, self::TOKEN_LENGTH );
2531 if ( strlen( $ret ) < $len ) {
2532 // Should never happen, even md5 is 128 bits
2533 throw new \UnexpectedValueException( 'Hmac returned less than 128 bits' );
2535 return substr( $ret, -$len );
2540 * Set the random token (used for persistent authentication)
2541 * Called from loadDefaults() among other places.
2543 * @param string|bool $token If specified, set the token to this value
2545 public function setToken( $token = false ) {
2546 $this->load();
2547 if ( $this->mToken === self::INVALID_TOKEN ) {
2548 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
2549 ->debug( __METHOD__ . ": Ignoring attempt to set token for system user \"$this\"" );
2550 } elseif ( !$token ) {
2551 $this->mToken = MWCryptRand::generateHex( self::TOKEN_LENGTH );
2552 } else {
2553 $this->mToken = $token;
2558 * Set the password for a password reminder or new account email
2560 * @deprecated since 1.27, AuthManager is coming
2561 * @param string $str New password to set or null to set an invalid
2562 * password hash meaning that the user will not be able to use it
2563 * @param bool $throttle If true, reset the throttle timestamp to the present
2565 public function setNewpassword( $str, $throttle = true ) {
2566 $id = $this->getId();
2567 if ( $id == 0 ) {
2568 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2571 $dbw = wfGetDB( DB_MASTER );
2573 $passwordFactory = new PasswordFactory();
2574 $passwordFactory->init( RequestContext::getMain()->getConfig() );
2575 $update = [
2576 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2579 if ( $str === null ) {
2580 $update['user_newpass_time'] = null;
2581 } elseif ( $throttle ) {
2582 $update['user_newpass_time'] = $dbw->timestamp();
2585 $dbw->update( 'user', $update, [ 'user_id' => $id ], __METHOD__ );
2589 * Has password reminder email been sent within the last
2590 * $wgPasswordReminderResendTime hours?
2591 * @return bool
2593 public function isPasswordReminderThrottled() {
2594 global $wgPasswordReminderResendTime;
2596 if ( !$wgPasswordReminderResendTime ) {
2597 return false;
2600 $this->load();
2602 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
2603 ? wfGetDB( DB_MASTER )
2604 : wfGetDB( DB_SLAVE );
2605 $newpassTime = $db->selectField(
2606 'user',
2607 'user_newpass_time',
2608 [ 'user_id' => $this->getId() ],
2609 __METHOD__
2612 if ( $newpassTime === null ) {
2613 return false;
2615 $expiry = wfTimestamp( TS_UNIX, $newpassTime ) + $wgPasswordReminderResendTime * 3600;
2616 return time() < $expiry;
2620 * Get the user's e-mail address
2621 * @return string User's email address
2623 public function getEmail() {
2624 $this->load();
2625 Hooks::run( 'UserGetEmail', [ $this, &$this->mEmail ] );
2626 return $this->mEmail;
2630 * Get the timestamp of the user's e-mail authentication
2631 * @return string TS_MW timestamp
2633 public function getEmailAuthenticationTimestamp() {
2634 $this->load();
2635 Hooks::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated ] );
2636 return $this->mEmailAuthenticated;
2640 * Set the user's e-mail address
2641 * @param string $str New e-mail address
2643 public function setEmail( $str ) {
2644 $this->load();
2645 if ( $str == $this->mEmail ) {
2646 return;
2648 $this->invalidateEmail();
2649 $this->mEmail = $str;
2650 Hooks::run( 'UserSetEmail', [ $this, &$this->mEmail ] );
2654 * Set the user's e-mail address and a confirmation mail if needed.
2656 * @since 1.20
2657 * @param string $str New e-mail address
2658 * @return Status
2660 public function setEmailWithConfirmation( $str ) {
2661 global $wgEnableEmail, $wgEmailAuthentication;
2663 if ( !$wgEnableEmail ) {
2664 return Status::newFatal( 'emaildisabled' );
2667 $oldaddr = $this->getEmail();
2668 if ( $str === $oldaddr ) {
2669 return Status::newGood( true );
2672 $this->setEmail( $str );
2674 if ( $str !== '' && $wgEmailAuthentication ) {
2675 // Send a confirmation request to the new address if needed
2676 $type = $oldaddr != '' ? 'changed' : 'set';
2677 $result = $this->sendConfirmationMail( $type );
2678 if ( $result->isGood() ) {
2679 // Say to the caller that a confirmation mail has been sent
2680 $result->value = 'eauth';
2682 } else {
2683 $result = Status::newGood( true );
2686 return $result;
2690 * Get the user's real name
2691 * @return string User's real name
2693 public function getRealName() {
2694 if ( !$this->isItemLoaded( 'realname' ) ) {
2695 $this->load();
2698 return $this->mRealName;
2702 * Set the user's real name
2703 * @param string $str New real name
2705 public function setRealName( $str ) {
2706 $this->load();
2707 $this->mRealName = $str;
2711 * Get the user's current setting for a given option.
2713 * @param string $oname The option to check
2714 * @param string $defaultOverride A default value returned if the option does not exist
2715 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2716 * @return string User's current value for the option
2717 * @see getBoolOption()
2718 * @see getIntOption()
2720 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2721 global $wgHiddenPrefs;
2722 $this->loadOptions();
2724 # We want 'disabled' preferences to always behave as the default value for
2725 # users, even if they have set the option explicitly in their settings (ie they
2726 # set it, and then it was disabled removing their ability to change it). But
2727 # we don't want to erase the preferences in the database in case the preference
2728 # is re-enabled again. So don't touch $mOptions, just override the returned value
2729 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2730 return self::getDefaultOption( $oname );
2733 if ( array_key_exists( $oname, $this->mOptions ) ) {
2734 return $this->mOptions[$oname];
2735 } else {
2736 return $defaultOverride;
2741 * Get all user's options
2743 * @param int $flags Bitwise combination of:
2744 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2745 * to the default value. (Since 1.25)
2746 * @return array
2748 public function getOptions( $flags = 0 ) {
2749 global $wgHiddenPrefs;
2750 $this->loadOptions();
2751 $options = $this->mOptions;
2753 # We want 'disabled' preferences to always behave as the default value for
2754 # users, even if they have set the option explicitly in their settings (ie they
2755 # set it, and then it was disabled removing their ability to change it). But
2756 # we don't want to erase the preferences in the database in case the preference
2757 # is re-enabled again. So don't touch $mOptions, just override the returned value
2758 foreach ( $wgHiddenPrefs as $pref ) {
2759 $default = self::getDefaultOption( $pref );
2760 if ( $default !== null ) {
2761 $options[$pref] = $default;
2765 if ( $flags & self::GETOPTIONS_EXCLUDE_DEFAULTS ) {
2766 $options = array_diff_assoc( $options, self::getDefaultOptions() );
2769 return $options;
2773 * Get the user's current setting for a given option, as a boolean value.
2775 * @param string $oname The option to check
2776 * @return bool User's current value for the option
2777 * @see getOption()
2779 public function getBoolOption( $oname ) {
2780 return (bool)$this->getOption( $oname );
2784 * Get the user's current setting for a given option, as an integer value.
2786 * @param string $oname The option to check
2787 * @param int $defaultOverride A default value returned if the option does not exist
2788 * @return int User's current value for the option
2789 * @see getOption()
2791 public function getIntOption( $oname, $defaultOverride = 0 ) {
2792 $val = $this->getOption( $oname );
2793 if ( $val == '' ) {
2794 $val = $defaultOverride;
2796 return intval( $val );
2800 * Set the given option for a user.
2802 * You need to call saveSettings() to actually write to the database.
2804 * @param string $oname The option to set
2805 * @param mixed $val New value to set
2807 public function setOption( $oname, $val ) {
2808 $this->loadOptions();
2810 // Explicitly NULL values should refer to defaults
2811 if ( is_null( $val ) ) {
2812 $val = self::getDefaultOption( $oname );
2815 $this->mOptions[$oname] = $val;
2819 * Get a token stored in the preferences (like the watchlist one),
2820 * resetting it if it's empty (and saving changes).
2822 * @param string $oname The option name to retrieve the token from
2823 * @return string|bool User's current value for the option, or false if this option is disabled.
2824 * @see resetTokenFromOption()
2825 * @see getOption()
2826 * @deprecated 1.26 Applications should use the OAuth extension
2828 public function getTokenFromOption( $oname ) {
2829 global $wgHiddenPrefs;
2831 $id = $this->getId();
2832 if ( !$id || in_array( $oname, $wgHiddenPrefs ) ) {
2833 return false;
2836 $token = $this->getOption( $oname );
2837 if ( !$token ) {
2838 // Default to a value based on the user token to avoid space
2839 // wasted on storing tokens for all users. When this option
2840 // is set manually by the user, only then is it stored.
2841 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2844 return $token;
2848 * Reset a token stored in the preferences (like the watchlist one).
2849 * *Does not* save user's preferences (similarly to setOption()).
2851 * @param string $oname The option name to reset the token in
2852 * @return string|bool New token value, or false if this option is disabled.
2853 * @see getTokenFromOption()
2854 * @see setOption()
2856 public function resetTokenFromOption( $oname ) {
2857 global $wgHiddenPrefs;
2858 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2859 return false;
2862 $token = MWCryptRand::generateHex( 40 );
2863 $this->setOption( $oname, $token );
2864 return $token;
2868 * Return a list of the types of user options currently returned by
2869 * User::getOptionKinds().
2871 * Currently, the option kinds are:
2872 * - 'registered' - preferences which are registered in core MediaWiki or
2873 * by extensions using the UserGetDefaultOptions hook.
2874 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2875 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2876 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2877 * be used by user scripts.
2878 * - 'special' - "preferences" that are not accessible via User::getOptions
2879 * or User::setOptions.
2880 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2881 * These are usually legacy options, removed in newer versions.
2883 * The API (and possibly others) use this function to determine the possible
2884 * option types for validation purposes, so make sure to update this when a
2885 * new option kind is added.
2887 * @see User::getOptionKinds
2888 * @return array Option kinds
2890 public static function listOptionKinds() {
2891 return [
2892 'registered',
2893 'registered-multiselect',
2894 'registered-checkmatrix',
2895 'userjs',
2896 'special',
2897 'unused'
2902 * Return an associative array mapping preferences keys to the kind of a preference they're
2903 * used for. Different kinds are handled differently when setting or reading preferences.
2905 * See User::listOptionKinds for the list of valid option types that can be provided.
2907 * @see User::listOptionKinds
2908 * @param IContextSource $context
2909 * @param array $options Assoc. array with options keys to check as keys.
2910 * Defaults to $this->mOptions.
2911 * @return array The key => kind mapping data
2913 public function getOptionKinds( IContextSource $context, $options = null ) {
2914 $this->loadOptions();
2915 if ( $options === null ) {
2916 $options = $this->mOptions;
2919 $prefs = Preferences::getPreferences( $this, $context );
2920 $mapping = [];
2922 // Pull out the "special" options, so they don't get converted as
2923 // multiselect or checkmatrix.
2924 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
2925 foreach ( $specialOptions as $name => $value ) {
2926 unset( $prefs[$name] );
2929 // Multiselect and checkmatrix options are stored in the database with
2930 // one key per option, each having a boolean value. Extract those keys.
2931 $multiselectOptions = [];
2932 foreach ( $prefs as $name => $info ) {
2933 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2934 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2935 $opts = HTMLFormField::flattenOptions( $info['options'] );
2936 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2938 foreach ( $opts as $value ) {
2939 $multiselectOptions["$prefix$value"] = true;
2942 unset( $prefs[$name] );
2945 $checkmatrixOptions = [];
2946 foreach ( $prefs as $name => $info ) {
2947 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2948 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2949 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2950 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2951 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2953 foreach ( $columns as $column ) {
2954 foreach ( $rows as $row ) {
2955 $checkmatrixOptions["$prefix$column-$row"] = true;
2959 unset( $prefs[$name] );
2963 // $value is ignored
2964 foreach ( $options as $key => $value ) {
2965 if ( isset( $prefs[$key] ) ) {
2966 $mapping[$key] = 'registered';
2967 } elseif ( isset( $multiselectOptions[$key] ) ) {
2968 $mapping[$key] = 'registered-multiselect';
2969 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2970 $mapping[$key] = 'registered-checkmatrix';
2971 } elseif ( isset( $specialOptions[$key] ) ) {
2972 $mapping[$key] = 'special';
2973 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2974 $mapping[$key] = 'userjs';
2975 } else {
2976 $mapping[$key] = 'unused';
2980 return $mapping;
2984 * Reset certain (or all) options to the site defaults
2986 * The optional parameter determines which kinds of preferences will be reset.
2987 * Supported values are everything that can be reported by getOptionKinds()
2988 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2990 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2991 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2992 * for backwards-compatibility.
2993 * @param IContextSource|null $context Context source used when $resetKinds
2994 * does not contain 'all', passed to getOptionKinds().
2995 * Defaults to RequestContext::getMain() when null.
2997 public function resetOptions(
2998 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
2999 IContextSource $context = null
3001 $this->load();
3002 $defaultOptions = self::getDefaultOptions();
3004 if ( !is_array( $resetKinds ) ) {
3005 $resetKinds = [ $resetKinds ];
3008 if ( in_array( 'all', $resetKinds ) ) {
3009 $newOptions = $defaultOptions;
3010 } else {
3011 if ( $context === null ) {
3012 $context = RequestContext::getMain();
3015 $optionKinds = $this->getOptionKinds( $context );
3016 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
3017 $newOptions = [];
3019 // Use default values for the options that should be deleted, and
3020 // copy old values for the ones that shouldn't.
3021 foreach ( $this->mOptions as $key => $value ) {
3022 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3023 if ( array_key_exists( $key, $defaultOptions ) ) {
3024 $newOptions[$key] = $defaultOptions[$key];
3026 } else {
3027 $newOptions[$key] = $value;
3032 Hooks::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions, $resetKinds ] );
3034 $this->mOptions = $newOptions;
3035 $this->mOptionsLoaded = true;
3039 * Get the user's preferred date format.
3040 * @return string User's preferred date format
3042 public function getDatePreference() {
3043 // Important migration for old data rows
3044 if ( is_null( $this->mDatePreference ) ) {
3045 global $wgLang;
3046 $value = $this->getOption( 'date' );
3047 $map = $wgLang->getDatePreferenceMigrationMap();
3048 if ( isset( $map[$value] ) ) {
3049 $value = $map[$value];
3051 $this->mDatePreference = $value;
3053 return $this->mDatePreference;
3057 * Determine based on the wiki configuration and the user's options,
3058 * whether this user must be over HTTPS no matter what.
3060 * @return bool
3062 public function requiresHTTPS() {
3063 global $wgSecureLogin;
3064 if ( !$wgSecureLogin ) {
3065 return false;
3066 } else {
3067 $https = $this->getBoolOption( 'prefershttps' );
3068 Hooks::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3069 if ( $https ) {
3070 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3072 return $https;
3077 * Get the user preferred stub threshold
3079 * @return int
3081 public function getStubThreshold() {
3082 global $wgMaxArticleSize; # Maximum article size, in Kb
3083 $threshold = $this->getIntOption( 'stubthreshold' );
3084 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3085 // If they have set an impossible value, disable the preference
3086 // so we can use the parser cache again.
3087 $threshold = 0;
3089 return $threshold;
3093 * Get the permissions this user has.
3094 * @return array Array of String permission names
3096 public function getRights() {
3097 if ( is_null( $this->mRights ) ) {
3098 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
3100 // Deny any rights denied by the user's session, unless this
3101 // endpoint has no sessions.
3102 if ( !defined( 'MW_NO_SESSION' ) ) {
3103 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3104 if ( $allowedRights !== null ) {
3105 $this->mRights = array_intersect( $this->mRights, $allowedRights );
3109 Hooks::run( 'UserGetRights', [ $this, &$this->mRights ] );
3110 // Force reindexation of rights when a hook has unset one of them
3111 $this->mRights = array_values( array_unique( $this->mRights ) );
3113 return $this->mRights;
3117 * Get the list of explicit group memberships this user has.
3118 * The implicit * and user groups are not included.
3119 * @return array Array of String internal group names
3121 public function getGroups() {
3122 $this->load();
3123 $this->loadGroups();
3124 return $this->mGroups;
3128 * Get the list of implicit group memberships this user has.
3129 * This includes all explicit groups, plus 'user' if logged in,
3130 * '*' for all accounts, and autopromoted groups
3131 * @param bool $recache Whether to avoid the cache
3132 * @return array Array of String internal group names
3134 public function getEffectiveGroups( $recache = false ) {
3135 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
3136 $this->mEffectiveGroups = array_unique( array_merge(
3137 $this->getGroups(), // explicit groups
3138 $this->getAutomaticGroups( $recache ) // implicit groups
3139 ) );
3140 // Hook for additional groups
3141 Hooks::run( 'UserEffectiveGroups', [ &$this, &$this->mEffectiveGroups ] );
3142 // Force reindexation of groups when a hook has unset one of them
3143 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
3145 return $this->mEffectiveGroups;
3149 * Get the list of implicit group memberships this user has.
3150 * This includes 'user' if logged in, '*' for all accounts,
3151 * and autopromoted groups
3152 * @param bool $recache Whether to avoid the cache
3153 * @return array Array of String internal group names
3155 public function getAutomaticGroups( $recache = false ) {
3156 if ( $recache || is_null( $this->mImplicitGroups ) ) {
3157 $this->mImplicitGroups = [ '*' ];
3158 if ( $this->getId() ) {
3159 $this->mImplicitGroups[] = 'user';
3161 $this->mImplicitGroups = array_unique( array_merge(
3162 $this->mImplicitGroups,
3163 Autopromote::getAutopromoteGroups( $this )
3164 ) );
3166 if ( $recache ) {
3167 // Assure data consistency with rights/groups,
3168 // as getEffectiveGroups() depends on this function
3169 $this->mEffectiveGroups = null;
3172 return $this->mImplicitGroups;
3176 * Returns the groups the user has belonged to.
3178 * The user may still belong to the returned groups. Compare with getGroups().
3180 * The function will not return groups the user had belonged to before MW 1.17
3182 * @return array Names of the groups the user has belonged to.
3184 public function getFormerGroups() {
3185 $this->load();
3187 if ( is_null( $this->mFormerGroups ) ) {
3188 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
3189 ? wfGetDB( DB_MASTER )
3190 : wfGetDB( DB_SLAVE );
3191 $res = $db->select( 'user_former_groups',
3192 [ 'ufg_group' ],
3193 [ 'ufg_user' => $this->mId ],
3194 __METHOD__ );
3195 $this->mFormerGroups = [];
3196 foreach ( $res as $row ) {
3197 $this->mFormerGroups[] = $row->ufg_group;
3201 return $this->mFormerGroups;
3205 * Get the user's edit count.
3206 * @return int|null Null for anonymous users
3208 public function getEditCount() {
3209 if ( !$this->getId() ) {
3210 return null;
3213 if ( $this->mEditCount === null ) {
3214 /* Populate the count, if it has not been populated yet */
3215 $dbr = wfGetDB( DB_SLAVE );
3216 // check if the user_editcount field has been initialized
3217 $count = $dbr->selectField(
3218 'user', 'user_editcount',
3219 [ 'user_id' => $this->mId ],
3220 __METHOD__
3223 if ( $count === null ) {
3224 // it has not been initialized. do so.
3225 $count = $this->initEditCount();
3227 $this->mEditCount = $count;
3229 return (int)$this->mEditCount;
3233 * Add the user to the given group.
3234 * This takes immediate effect.
3235 * @param string $group Name of the group to add
3236 * @return bool
3238 public function addGroup( $group ) {
3239 $this->load();
3241 if ( !Hooks::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3242 return false;
3245 $dbw = wfGetDB( DB_MASTER );
3246 if ( $this->getId() ) {
3247 $dbw->insert( 'user_groups',
3249 'ug_user' => $this->getID(),
3250 'ug_group' => $group,
3252 __METHOD__,
3253 [ 'IGNORE' ] );
3256 $this->loadGroups();
3257 $this->mGroups[] = $group;
3258 // In case loadGroups was not called before, we now have the right twice.
3259 // Get rid of the duplicate.
3260 $this->mGroups = array_unique( $this->mGroups );
3262 // Refresh the groups caches, and clear the rights cache so it will be
3263 // refreshed on the next call to $this->getRights().
3264 $this->getEffectiveGroups( true );
3265 $this->mRights = null;
3267 $this->invalidateCache();
3269 return true;
3273 * Remove the user from the given group.
3274 * This takes immediate effect.
3275 * @param string $group Name of the group to remove
3276 * @return bool
3278 public function removeGroup( $group ) {
3279 $this->load();
3280 if ( !Hooks::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3281 return false;
3284 $dbw = wfGetDB( DB_MASTER );
3285 $dbw->delete( 'user_groups',
3287 'ug_user' => $this->getID(),
3288 'ug_group' => $group,
3289 ], __METHOD__
3291 // Remember that the user was in this group
3292 $dbw->insert( 'user_former_groups',
3294 'ufg_user' => $this->getID(),
3295 'ufg_group' => $group,
3297 __METHOD__,
3298 [ 'IGNORE' ]
3301 $this->loadGroups();
3302 $this->mGroups = array_diff( $this->mGroups, [ $group ] );
3304 // Refresh the groups caches, and clear the rights cache so it will be
3305 // refreshed on the next call to $this->getRights().
3306 $this->getEffectiveGroups( true );
3307 $this->mRights = null;
3309 $this->invalidateCache();
3311 return true;
3315 * Get whether the user is logged in
3316 * @return bool
3318 public function isLoggedIn() {
3319 return $this->getID() != 0;
3323 * Get whether the user is anonymous
3324 * @return bool
3326 public function isAnon() {
3327 return !$this->isLoggedIn();
3331 * Check if user is allowed to access a feature / make an action
3333 * @param string ... Permissions to test
3334 * @return bool True if user is allowed to perform *any* of the given actions
3336 public function isAllowedAny() {
3337 $permissions = func_get_args();
3338 foreach ( $permissions as $permission ) {
3339 if ( $this->isAllowed( $permission ) ) {
3340 return true;
3343 return false;
3348 * @param string ... Permissions to test
3349 * @return bool True if the user is allowed to perform *all* of the given actions
3351 public function isAllowedAll() {
3352 $permissions = func_get_args();
3353 foreach ( $permissions as $permission ) {
3354 if ( !$this->isAllowed( $permission ) ) {
3355 return false;
3358 return true;
3362 * Internal mechanics of testing a permission
3363 * @param string $action
3364 * @return bool
3366 public function isAllowed( $action = '' ) {
3367 if ( $action === '' ) {
3368 return true; // In the spirit of DWIM
3370 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3371 // by misconfiguration: 0 == 'foo'
3372 return in_array( $action, $this->getRights(), true );
3376 * Check whether to enable recent changes patrol features for this user
3377 * @return bool True or false
3379 public function useRCPatrol() {
3380 global $wgUseRCPatrol;
3381 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3385 * Check whether to enable new pages patrol features for this user
3386 * @return bool True or false
3388 public function useNPPatrol() {
3389 global $wgUseRCPatrol, $wgUseNPPatrol;
3390 return (
3391 ( $wgUseRCPatrol || $wgUseNPPatrol )
3392 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3397 * Check whether to enable new files patrol features for this user
3398 * @return bool True or false
3400 public function useFilePatrol() {
3401 global $wgUseRCPatrol, $wgUseFilePatrol;
3402 return (
3403 ( $wgUseRCPatrol || $wgUseFilePatrol )
3404 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3409 * Get the WebRequest object to use with this object
3411 * @return WebRequest
3413 public function getRequest() {
3414 if ( $this->mRequest ) {
3415 return $this->mRequest;
3416 } else {
3417 global $wgRequest;
3418 return $wgRequest;
3423 * Get a WatchedItem for this user and $title.
3425 * @since 1.22 $checkRights parameter added
3426 * @param Title $title
3427 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3428 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3429 * @return WatchedItem
3431 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3432 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3434 if ( isset( $this->mWatchedItems[$key] ) ) {
3435 return $this->mWatchedItems[$key];
3438 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
3439 $this->mWatchedItems = [];
3442 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
3443 return $this->mWatchedItems[$key];
3447 * Check the watched status of an article.
3448 * @since 1.22 $checkRights parameter added
3449 * @param Title $title Title of the article to look at
3450 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3451 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3452 * @return bool
3454 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3455 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3459 * Watch an article.
3460 * @since 1.22 $checkRights parameter added
3461 * @param Title $title Title of the article to look at
3462 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3463 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3465 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3466 $this->getWatchedItem( $title, $checkRights )->addWatch();
3467 $this->invalidateCache();
3471 * Stop watching an article.
3472 * @since 1.22 $checkRights parameter added
3473 * @param Title $title Title of the article to look at
3474 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3475 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3477 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3478 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3479 $this->invalidateCache();
3483 * Clear the user's notification timestamp for the given title.
3484 * If e-notif e-mails are on, they will receive notification mails on
3485 * the next change of the page if it's watched etc.
3486 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3487 * @param Title $title Title of the article to look at
3488 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3490 public function clearNotification( &$title, $oldid = 0 ) {
3491 global $wgUseEnotif, $wgShowUpdatedMarker;
3493 // Do nothing if the database is locked to writes
3494 if ( wfReadOnly() ) {
3495 return;
3498 // Do nothing if not allowed to edit the watchlist
3499 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3500 return;
3503 // If we're working on user's talk page, we should update the talk page message indicator
3504 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3505 if ( !Hooks::run( 'UserClearNewTalkNotification', [ &$this, $oldid ] ) ) {
3506 return;
3509 // Try to update the DB post-send and only if needed...
3510 DeferredUpdates::addCallableUpdate( function() use ( $title, $oldid ) {
3511 if ( !$this->getNewtalk() ) {
3512 return; // no notifications to clear
3515 // Delete the last notifications (they stack up)
3516 $this->setNewtalk( false );
3518 // If there is a new, unseen, revision, use its timestamp
3519 $nextid = $oldid
3520 ? $title->getNextRevisionID( $oldid, Title::GAID_FOR_UPDATE )
3521 : null;
3522 if ( $nextid ) {
3523 $this->setNewtalk( true, Revision::newFromId( $nextid ) );
3525 } );
3528 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3529 return;
3532 if ( $this->isAnon() ) {
3533 // Nothing else to do...
3534 return;
3537 // Only update the timestamp if the page is being watched.
3538 // The query to find out if it is watched is cached both in memcached and per-invocation,
3539 // and when it does have to be executed, it can be on a slave
3540 // If this is the user's newtalk page, we always update the timestamp
3541 $force = '';
3542 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3543 $force = 'force';
3546 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3547 $force, $oldid
3552 * Resets all of the given user's page-change notification timestamps.
3553 * If e-notif e-mails are on, they will receive notification mails on
3554 * the next change of any watched page.
3555 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3557 public function clearAllNotifications() {
3558 if ( wfReadOnly() ) {
3559 return;
3562 // Do nothing if not allowed to edit the watchlist
3563 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3564 return;
3567 global $wgUseEnotif, $wgShowUpdatedMarker;
3568 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3569 $this->setNewtalk( false );
3570 return;
3572 $id = $this->getId();
3573 if ( $id != 0 ) {
3574 $dbw = wfGetDB( DB_MASTER );
3575 $dbw->update( 'watchlist',
3576 [ /* SET */ 'wl_notificationtimestamp' => null ],
3577 [ /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3578 __METHOD__
3580 // We also need to clear here the "you have new message" notification for the own user_talk page;
3581 // it's cleared one page view later in WikiPage::doViewUpdates().
3586 * Set a cookie on the user's client. Wrapper for
3587 * WebResponse::setCookie
3588 * @deprecated since 1.27
3589 * @param string $name Name of the cookie to set
3590 * @param string $value Value to set
3591 * @param int $exp Expiration time, as a UNIX time value;
3592 * if 0 or not specified, use the default $wgCookieExpiration
3593 * @param bool $secure
3594 * true: Force setting the secure attribute when setting the cookie
3595 * false: Force NOT setting the secure attribute when setting the cookie
3596 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3597 * @param array $params Array of options sent passed to WebResponse::setcookie()
3598 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3599 * is passed.
3601 protected function setCookie(
3602 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3604 wfDeprecated( __METHOD__, '1.27' );
3605 if ( $request === null ) {
3606 $request = $this->getRequest();
3608 $params['secure'] = $secure;
3609 $request->response()->setCookie( $name, $value, $exp, $params );
3613 * Clear a cookie on the user's client
3614 * @deprecated since 1.27
3615 * @param string $name Name of the cookie to clear
3616 * @param bool $secure
3617 * true: Force setting the secure attribute when setting the cookie
3618 * false: Force NOT setting the secure attribute when setting the cookie
3619 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3620 * @param array $params Array of options sent passed to WebResponse::setcookie()
3622 protected function clearCookie( $name, $secure = null, $params = [] ) {
3623 wfDeprecated( __METHOD__, '1.27' );
3624 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3628 * Set an extended login cookie on the user's client. The expiry of the cookie
3629 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3630 * variable.
3632 * @see User::setCookie
3634 * @deprecated since 1.27
3635 * @param string $name Name of the cookie to set
3636 * @param string $value Value to set
3637 * @param bool $secure
3638 * true: Force setting the secure attribute when setting the cookie
3639 * false: Force NOT setting the secure attribute when setting the cookie
3640 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3642 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3643 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3645 wfDeprecated( __METHOD__, '1.27' );
3647 $exp = time();
3648 $exp += $wgExtendedLoginCookieExpiration !== null
3649 ? $wgExtendedLoginCookieExpiration
3650 : $wgCookieExpiration;
3652 $this->setCookie( $name, $value, $exp, $secure );
3656 * Persist this user's session (e.g. set cookies)
3658 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3659 * is passed.
3660 * @param bool $secure Whether to force secure/insecure cookies or use default
3661 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3663 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3664 $this->load();
3665 if ( 0 == $this->mId ) {
3666 return;
3669 $session = $this->getRequest()->getSession();
3670 if ( $request && $session->getRequest() !== $request ) {
3671 $session = $session->sessionWithRequest( $request );
3673 $delay = $session->delaySave();
3675 if ( !$session->getUser()->equals( $this ) ) {
3676 if ( !$session->canSetUser() ) {
3677 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3678 ->warning( __METHOD__ .
3679 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3681 return;
3683 $session->setUser( $this );
3686 $session->setRememberUser( $rememberMe );
3687 if ( $secure !== null ) {
3688 $session->setForceHTTPS( $secure );
3691 $session->persist();
3693 ScopedCallback::consume( $delay );
3697 * Log this user out.
3699 public function logout() {
3700 if ( Hooks::run( 'UserLogout', [ &$this ] ) ) {
3701 $this->doLogout();
3706 * Clear the user's session, and reset the instance cache.
3707 * @see logout()
3709 public function doLogout() {
3710 $session = $this->getRequest()->getSession();
3711 if ( !$session->canSetUser() ) {
3712 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3713 ->warning( __METHOD__ . ": Cannot log out of an immutable session" );
3714 } elseif ( !$session->getUser()->equals( $this ) ) {
3715 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3716 ->warning( __METHOD__ .
3717 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3719 // But we still may as well make this user object anon
3720 $this->clearInstanceCache( 'defaults' );
3721 } else {
3722 $this->clearInstanceCache( 'defaults' );
3723 $delay = $session->delaySave();
3724 $session->unpersist(); // Clear cookies (T127436)
3725 $session->setLoggedOutTimestamp( time() );
3726 $session->setUser( new User );
3727 $session->set( 'wsUserID', 0 ); // Other code expects this
3728 ScopedCallback::consume( $delay );
3733 * Save this user's settings into the database.
3734 * @todo Only rarely do all these fields need to be set!
3736 public function saveSettings() {
3737 if ( wfReadOnly() ) {
3738 // @TODO: caller should deal with this instead!
3739 // This should really just be an exception.
3740 MWExceptionHandler::logException( new DBExpectedError(
3741 null,
3742 "Could not update user with ID '{$this->mId}'; DB is read-only."
3743 ) );
3744 return;
3747 $this->load();
3748 if ( 0 == $this->mId ) {
3749 return; // anon
3752 // Get a new user_touched that is higher than the old one.
3753 // This will be used for a CAS check as a last-resort safety
3754 // check against race conditions and slave lag.
3755 $oldTouched = $this->mTouched;
3756 $newTouched = $this->newTouchedTimestamp();
3758 $dbw = wfGetDB( DB_MASTER );
3759 $dbw->update( 'user',
3760 [ /* SET */
3761 'user_name' => $this->mName,
3762 'user_real_name' => $this->mRealName,
3763 'user_email' => $this->mEmail,
3764 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3765 'user_touched' => $dbw->timestamp( $newTouched ),
3766 'user_token' => strval( $this->mToken ),
3767 'user_email_token' => $this->mEmailToken,
3768 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3769 ], [ /* WHERE */
3770 'user_id' => $this->mId,
3771 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3772 ], __METHOD__
3775 if ( !$dbw->affectedRows() ) {
3776 // Maybe the problem was a missed cache update; clear it to be safe
3777 $this->clearSharedCache( 'refresh' );
3778 // User was changed in the meantime or loaded with stale data
3779 $from = ( $this->queryFlagsUsed & self::READ_LATEST ) ? 'master' : 'slave';
3780 throw new MWException(
3781 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3782 " the version of the user to be saved is older than the current version."
3786 $this->mTouched = $newTouched;
3787 $this->saveOptions();
3789 Hooks::run( 'UserSaveSettings', [ $this ] );
3790 $this->clearSharedCache();
3791 $this->getUserPage()->invalidateCache();
3795 * If only this user's username is known, and it exists, return the user ID.
3797 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3798 * @return int
3800 public function idForName( $flags = 0 ) {
3801 $s = trim( $this->getName() );
3802 if ( $s === '' ) {
3803 return 0;
3806 $db = ( ( $flags & self::READ_LATEST ) == self::READ_LATEST )
3807 ? wfGetDB( DB_MASTER )
3808 : wfGetDB( DB_SLAVE );
3810 $options = ( ( $flags & self::READ_LOCKING ) == self::READ_LOCKING )
3811 ? [ 'LOCK IN SHARE MODE' ]
3812 : [];
3814 $id = $db->selectField( 'user',
3815 'user_id', [ 'user_name' => $s ], __METHOD__, $options );
3817 return (int)$id;
3821 * Add a user to the database, return the user object
3823 * @param string $name Username to add
3824 * @param array $params Array of Strings Non-default parameters to save to
3825 * the database as user_* fields:
3826 * - email: The user's email address.
3827 * - email_authenticated: The email authentication timestamp.
3828 * - real_name: The user's real name.
3829 * - options: An associative array of non-default options.
3830 * - token: Random authentication token. Do not set.
3831 * - registration: Registration timestamp. Do not set.
3833 * @return User|null User object, or null if the username already exists.
3835 public static function createNew( $name, $params = [] ) {
3836 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
3837 if ( isset( $params[$field] ) ) {
3838 wfDeprecated( __METHOD__ . " with param '$field'", '1.27' );
3839 unset( $params[$field] );
3843 $user = new User;
3844 $user->load();
3845 $user->setToken(); // init token
3846 if ( isset( $params['options'] ) ) {
3847 $user->mOptions = $params['options'] + (array)$user->mOptions;
3848 unset( $params['options'] );
3850 $dbw = wfGetDB( DB_MASTER );
3851 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3853 $noPass = PasswordFactory::newInvalidPassword()->toString();
3855 $fields = [
3856 'user_id' => $seqVal,
3857 'user_name' => $name,
3858 'user_password' => $noPass,
3859 'user_newpassword' => $noPass,
3860 'user_email' => $user->mEmail,
3861 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3862 'user_real_name' => $user->mRealName,
3863 'user_token' => strval( $user->mToken ),
3864 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3865 'user_editcount' => 0,
3866 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3868 foreach ( $params as $name => $value ) {
3869 $fields["user_$name"] = $value;
3871 $dbw->insert( 'user', $fields, __METHOD__, [ 'IGNORE' ] );
3872 if ( $dbw->affectedRows() ) {
3873 $newUser = User::newFromId( $dbw->insertId() );
3874 } else {
3875 $newUser = null;
3877 return $newUser;
3881 * Add this existing user object to the database. If the user already
3882 * exists, a fatal status object is returned, and the user object is
3883 * initialised with the data from the database.
3885 * Previously, this function generated a DB error due to a key conflict
3886 * if the user already existed. Many extension callers use this function
3887 * in code along the lines of:
3889 * $user = User::newFromName( $name );
3890 * if ( !$user->isLoggedIn() ) {
3891 * $user->addToDatabase();
3893 * // do something with $user...
3895 * However, this was vulnerable to a race condition (bug 16020). By
3896 * initialising the user object if the user exists, we aim to support this
3897 * calling sequence as far as possible.
3899 * Note that if the user exists, this function will acquire a write lock,
3900 * so it is still advisable to make the call conditional on isLoggedIn(),
3901 * and to commit the transaction after calling.
3903 * @throws MWException
3904 * @return Status
3906 public function addToDatabase() {
3907 $this->load();
3908 if ( !$this->mToken ) {
3909 $this->setToken(); // init token
3912 $this->mTouched = $this->newTouchedTimestamp();
3914 $noPass = PasswordFactory::newInvalidPassword()->toString();
3916 $dbw = wfGetDB( DB_MASTER );
3917 $inWrite = $dbw->writesOrCallbacksPending();
3918 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3919 $dbw->insert( 'user',
3921 'user_id' => $seqVal,
3922 'user_name' => $this->mName,
3923 'user_password' => $noPass,
3924 'user_newpassword' => $noPass,
3925 'user_email' => $this->mEmail,
3926 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3927 'user_real_name' => $this->mRealName,
3928 'user_token' => strval( $this->mToken ),
3929 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3930 'user_editcount' => 0,
3931 'user_touched' => $dbw->timestamp( $this->mTouched ),
3932 ], __METHOD__,
3933 [ 'IGNORE' ]
3935 if ( !$dbw->affectedRows() ) {
3936 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3937 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3938 if ( $inWrite ) {
3939 // Can't commit due to pending writes that may need atomicity.
3940 // This may cause some lock contention unlike the case below.
3941 $options = [ 'LOCK IN SHARE MODE' ];
3942 $flags = self::READ_LOCKING;
3943 } else {
3944 // Often, this case happens early in views before any writes when
3945 // using CentralAuth. It's should be OK to commit and break the snapshot.
3946 $dbw->commit( __METHOD__, 'flush' );
3947 $options = [];
3948 $flags = self::READ_LATEST;
3950 $this->mId = $dbw->selectField( 'user', 'user_id',
3951 [ 'user_name' => $this->mName ], __METHOD__, $options );
3952 $loaded = false;
3953 if ( $this->mId ) {
3954 if ( $this->loadFromDatabase( $flags ) ) {
3955 $loaded = true;
3958 if ( !$loaded ) {
3959 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3960 "to insert user '{$this->mName}' row, but it was not present in select!" );
3962 return Status::newFatal( 'userexists' );
3964 $this->mId = $dbw->insertId();
3965 self::$idCacheByName[$this->mName] = $this->mId;
3967 // Clear instance cache other than user table data, which is already accurate
3968 $this->clearInstanceCache();
3970 $this->saveOptions();
3971 return Status::newGood();
3975 * If this user is logged-in and blocked,
3976 * block any IP address they've successfully logged in from.
3977 * @return bool A block was spread
3979 public function spreadAnyEditBlock() {
3980 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3981 return $this->spreadBlock();
3983 return false;
3987 * If this (non-anonymous) user is blocked,
3988 * block the IP address they've successfully logged in from.
3989 * @return bool A block was spread
3991 protected function spreadBlock() {
3992 wfDebug( __METHOD__ . "()\n" );
3993 $this->load();
3994 if ( $this->mId == 0 ) {
3995 return false;
3998 $userblock = Block::newFromTarget( $this->getName() );
3999 if ( !$userblock ) {
4000 return false;
4003 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4007 * Get whether the user is explicitly blocked from account creation.
4008 * @return bool|Block
4010 public function isBlockedFromCreateAccount() {
4011 $this->getBlockedStatus();
4012 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
4013 return $this->mBlock;
4016 # bug 13611: if the IP address the user is trying to create an account from is
4017 # blocked with createaccount disabled, prevent new account creation there even
4018 # when the user is logged in
4019 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4020 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
4022 return $this->mBlockedFromCreateAccount instanceof Block
4023 && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
4024 ? $this->mBlockedFromCreateAccount
4025 : false;
4029 * Get whether the user is blocked from using Special:Emailuser.
4030 * @return bool
4032 public function isBlockedFromEmailuser() {
4033 $this->getBlockedStatus();
4034 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
4038 * Get whether the user is allowed to create an account.
4039 * @return bool
4041 public function isAllowedToCreateAccount() {
4042 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4046 * Get this user's personal page title.
4048 * @return Title User's personal page title
4050 public function getUserPage() {
4051 return Title::makeTitle( NS_USER, $this->getName() );
4055 * Get this user's talk page title.
4057 * @return Title User's talk page title
4059 public function getTalkPage() {
4060 $title = $this->getUserPage();
4061 return $title->getTalkPage();
4065 * Determine whether the user is a newbie. Newbies are either
4066 * anonymous IPs, or the most recently created accounts.
4067 * @return bool
4069 public function isNewbie() {
4070 return !$this->isAllowed( 'autoconfirmed' );
4074 * Check to see if the given clear-text password is one of the accepted passwords
4075 * @deprecated since 1.27. AuthManager is coming.
4076 * @param string $password User password
4077 * @return bool True if the given password is correct, otherwise False
4079 public function checkPassword( $password ) {
4080 global $wgAuth, $wgLegacyEncoding;
4082 $this->load();
4084 // Some passwords will give a fatal Status, which means there is
4085 // some sort of technical or security reason for this password to
4086 // be completely invalid and should never be checked (e.g., T64685)
4087 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4088 return false;
4091 // Certain authentication plugins do NOT want to save
4092 // domain passwords in a mysql database, so we should
4093 // check this (in case $wgAuth->strict() is false).
4094 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4095 return true;
4096 } elseif ( $wgAuth->strict() ) {
4097 // Auth plugin doesn't allow local authentication
4098 return false;
4099 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4100 // Auth plugin doesn't allow local authentication for this user name
4101 return false;
4104 $passwordFactory = new PasswordFactory();
4105 $passwordFactory->init( RequestContext::getMain()->getConfig() );
4106 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
4107 ? wfGetDB( DB_MASTER )
4108 : wfGetDB( DB_SLAVE );
4110 try {
4111 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4112 'user', 'user_password', [ 'user_id' => $this->getId() ], __METHOD__
4113 ) );
4114 } catch ( PasswordError $e ) {
4115 wfDebug( 'Invalid password hash found in database.' );
4116 $mPassword = PasswordFactory::newInvalidPassword();
4119 if ( !$mPassword->equals( $password ) ) {
4120 if ( $wgLegacyEncoding ) {
4121 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4122 // Check for this with iconv
4123 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4124 if ( $cp1252Password === $password || !$mPassword->equals( $cp1252Password ) ) {
4125 return false;
4127 } else {
4128 return false;
4132 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4133 $this->setPasswordInternal( $password );
4136 return true;
4140 * Check if the given clear-text password matches the temporary password
4141 * sent by e-mail for password reset operations.
4143 * @deprecated since 1.27. AuthManager is coming.
4144 * @param string $plaintext
4145 * @return bool True if matches, false otherwise
4147 public function checkTemporaryPassword( $plaintext ) {
4148 global $wgNewPasswordExpiry;
4150 $this->load();
4152 $passwordFactory = new PasswordFactory();
4153 $passwordFactory->init( RequestContext::getMain()->getConfig() );
4154 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
4155 ? wfGetDB( DB_MASTER )
4156 : wfGetDB( DB_SLAVE );
4158 $row = $db->selectRow(
4159 'user',
4160 [ 'user_newpassword', 'user_newpass_time' ],
4161 [ 'user_id' => $this->getId() ],
4162 __METHOD__
4164 try {
4165 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword );
4166 } catch ( PasswordError $e ) {
4167 wfDebug( 'Invalid password hash found in database.' );
4168 $newPassword = PasswordFactory::newInvalidPassword();
4171 if ( $newPassword->equals( $plaintext ) ) {
4172 if ( is_null( $row->user_newpass_time ) ) {
4173 return true;
4175 $expiry = wfTimestamp( TS_UNIX, $row->user_newpass_time ) + $wgNewPasswordExpiry;
4176 return ( time() < $expiry );
4177 } else {
4178 return false;
4183 * Initialize (if necessary) and return a session token value
4184 * which can be used in edit forms to show that the user's
4185 * login credentials aren't being hijacked with a foreign form
4186 * submission.
4188 * @since 1.27
4189 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4190 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4191 * @return MediaWiki\\Session\\Token The new edit token
4193 public function getEditTokenObject( $salt = '', $request = null ) {
4194 if ( $this->isAnon() ) {
4195 return new LoggedOutEditToken();
4198 if ( !$request ) {
4199 $request = $this->getRequest();
4201 return $request->getSession()->getToken( $salt );
4205 * Initialize (if necessary) and return a session token value
4206 * which can be used in edit forms to show that the user's
4207 * login credentials aren't being hijacked with a foreign form
4208 * submission.
4210 * @since 1.19
4211 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4212 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4213 * @return string The new edit token
4215 public function getEditToken( $salt = '', $request = null ) {
4216 return $this->getEditTokenObject( $salt, $request )->toString();
4220 * Get the embedded timestamp from a token.
4221 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::getTimestamp instead.
4222 * @param string $val Input token
4223 * @return int|null
4225 public static function getEditTokenTimestamp( $val ) {
4226 wfDeprecated( __METHOD__, '1.27' );
4227 return MediaWiki\Session\Token::getTimestamp( $val );
4231 * Check given value against the token value stored in the session.
4232 * A match should confirm that the form was submitted from the
4233 * user's own login session, not a form submission from a third-party
4234 * site.
4236 * @param string $val Input value to compare
4237 * @param string $salt Optional function-specific data for hashing
4238 * @param WebRequest|null $request Object to use or null to use $wgRequest
4239 * @param int $maxage Fail tokens older than this, in seconds
4240 * @return bool Whether the token matches
4242 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4243 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4247 * Check given value against the token value stored in the session,
4248 * ignoring the suffix.
4250 * @param string $val Input value to compare
4251 * @param string $salt Optional function-specific data for hashing
4252 * @param WebRequest|null $request Object to use or null to use $wgRequest
4253 * @param int $maxage Fail tokens older than this, in seconds
4254 * @return bool Whether the token matches
4256 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4257 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self::EDIT_TOKEN_SUFFIX;
4258 return $this->matchEditToken( $val, $salt, $request, $maxage );
4262 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4263 * mail to the user's given address.
4265 * @param string $type Message to send, either "created", "changed" or "set"
4266 * @return Status
4268 public function sendConfirmationMail( $type = 'created' ) {
4269 global $wgLang;
4270 $expiration = null; // gets passed-by-ref and defined in next line.
4271 $token = $this->confirmationToken( $expiration );
4272 $url = $this->confirmationTokenUrl( $token );
4273 $invalidateURL = $this->invalidationTokenUrl( $token );
4274 $this->saveSettings();
4276 if ( $type == 'created' || $type === false ) {
4277 $message = 'confirmemail_body';
4278 } elseif ( $type === true ) {
4279 $message = 'confirmemail_body_changed';
4280 } else {
4281 // Messages: confirmemail_body_changed, confirmemail_body_set
4282 $message = 'confirmemail_body_' . $type;
4285 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4286 wfMessage( $message,
4287 $this->getRequest()->getIP(),
4288 $this->getName(),
4289 $url,
4290 $wgLang->userTimeAndDate( $expiration, $this ),
4291 $invalidateURL,
4292 $wgLang->userDate( $expiration, $this ),
4293 $wgLang->userTime( $expiration, $this ) )->text() );
4297 * Send an e-mail to this user's account. Does not check for
4298 * confirmed status or validity.
4300 * @param string $subject Message subject
4301 * @param string $body Message body
4302 * @param User|null $from Optional sending user; if unspecified, default
4303 * $wgPasswordSender will be used.
4304 * @param string $replyto Reply-To address
4305 * @return Status
4307 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4308 global $wgPasswordSender;
4310 if ( $from instanceof User ) {
4311 $sender = MailAddress::newFromUser( $from );
4312 } else {
4313 $sender = new MailAddress( $wgPasswordSender,
4314 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4316 $to = MailAddress::newFromUser( $this );
4318 return UserMailer::send( $to, $sender, $subject, $body, [
4319 'replyTo' => $replyto,
4320 ] );
4324 * Generate, store, and return a new e-mail confirmation code.
4325 * A hash (unsalted, since it's used as a key) is stored.
4327 * @note Call saveSettings() after calling this function to commit
4328 * this change to the database.
4330 * @param string &$expiration Accepts the expiration time
4331 * @return string New token
4333 protected function confirmationToken( &$expiration ) {
4334 global $wgUserEmailConfirmationTokenExpiry;
4335 $now = time();
4336 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
4337 $expiration = wfTimestamp( TS_MW, $expires );
4338 $this->load();
4339 $token = MWCryptRand::generateHex( 32 );
4340 $hash = md5( $token );
4341 $this->mEmailToken = $hash;
4342 $this->mEmailTokenExpires = $expiration;
4343 return $token;
4347 * Return a URL the user can use to confirm their email address.
4348 * @param string $token Accepts the email confirmation token
4349 * @return string New token URL
4351 protected function confirmationTokenUrl( $token ) {
4352 return $this->getTokenUrl( 'ConfirmEmail', $token );
4356 * Return a URL the user can use to invalidate their email address.
4357 * @param string $token Accepts the email confirmation token
4358 * @return string New token URL
4360 protected function invalidationTokenUrl( $token ) {
4361 return $this->getTokenUrl( 'InvalidateEmail', $token );
4365 * Internal function to format the e-mail validation/invalidation URLs.
4366 * This uses a quickie hack to use the
4367 * hardcoded English names of the Special: pages, for ASCII safety.
4369 * @note Since these URLs get dropped directly into emails, using the
4370 * short English names avoids insanely long URL-encoded links, which
4371 * also sometimes can get corrupted in some browsers/mailers
4372 * (bug 6957 with Gmail and Internet Explorer).
4374 * @param string $page Special page
4375 * @param string $token Token
4376 * @return string Formatted URL
4378 protected function getTokenUrl( $page, $token ) {
4379 // Hack to bypass localization of 'Special:'
4380 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
4381 return $title->getCanonicalURL();
4385 * Mark the e-mail address confirmed.
4387 * @note Call saveSettings() after calling this function to commit the change.
4389 * @return bool
4391 public function confirmEmail() {
4392 // Check if it's already confirmed, so we don't touch the database
4393 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4394 if ( !$this->isEmailConfirmed() ) {
4395 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4396 Hooks::run( 'ConfirmEmailComplete', [ $this ] );
4398 return true;
4402 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4403 * address if it was already confirmed.
4405 * @note Call saveSettings() after calling this function to commit the change.
4406 * @return bool Returns true
4408 public function invalidateEmail() {
4409 $this->load();
4410 $this->mEmailToken = null;
4411 $this->mEmailTokenExpires = null;
4412 $this->setEmailAuthenticationTimestamp( null );
4413 $this->mEmail = '';
4414 Hooks::run( 'InvalidateEmailComplete', [ $this ] );
4415 return true;
4419 * Set the e-mail authentication timestamp.
4420 * @param string $timestamp TS_MW timestamp
4422 public function setEmailAuthenticationTimestamp( $timestamp ) {
4423 $this->load();
4424 $this->mEmailAuthenticated = $timestamp;
4425 Hooks::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated ] );
4429 * Is this user allowed to send e-mails within limits of current
4430 * site configuration?
4431 * @return bool
4433 public function canSendEmail() {
4434 global $wgEnableEmail, $wgEnableUserEmail;
4435 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4436 return false;
4438 $canSend = $this->isEmailConfirmed();
4439 Hooks::run( 'UserCanSendEmail', [ &$this, &$canSend ] );
4440 return $canSend;
4444 * Is this user allowed to receive e-mails within limits of current
4445 * site configuration?
4446 * @return bool
4448 public function canReceiveEmail() {
4449 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4453 * Is this user's e-mail address valid-looking and confirmed within
4454 * limits of the current site configuration?
4456 * @note If $wgEmailAuthentication is on, this may require the user to have
4457 * confirmed their address by returning a code or using a password
4458 * sent to the address from the wiki.
4460 * @return bool
4462 public function isEmailConfirmed() {
4463 global $wgEmailAuthentication;
4464 $this->load();
4465 $confirmed = true;
4466 if ( Hooks::run( 'EmailConfirmed', [ &$this, &$confirmed ] ) ) {
4467 if ( $this->isAnon() ) {
4468 return false;
4470 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4471 return false;
4473 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4474 return false;
4476 return true;
4477 } else {
4478 return $confirmed;
4483 * Check whether there is an outstanding request for e-mail confirmation.
4484 * @return bool
4486 public function isEmailConfirmationPending() {
4487 global $wgEmailAuthentication;
4488 return $wgEmailAuthentication &&
4489 !$this->isEmailConfirmed() &&
4490 $this->mEmailToken &&
4491 $this->mEmailTokenExpires > wfTimestamp();
4495 * Get the timestamp of account creation.
4497 * @return string|bool|null Timestamp of account creation, false for
4498 * non-existent/anonymous user accounts, or null if existing account
4499 * but information is not in database.
4501 public function getRegistration() {
4502 if ( $this->isAnon() ) {
4503 return false;
4505 $this->load();
4506 return $this->mRegistration;
4510 * Get the timestamp of the first edit
4512 * @return string|bool Timestamp of first edit, or false for
4513 * non-existent/anonymous user accounts.
4515 public function getFirstEditTimestamp() {
4516 if ( $this->getId() == 0 ) {
4517 return false; // anons
4519 $dbr = wfGetDB( DB_SLAVE );
4520 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4521 [ 'rev_user' => $this->getId() ],
4522 __METHOD__,
4523 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4525 if ( !$time ) {
4526 return false; // no edits
4528 return wfTimestamp( TS_MW, $time );
4532 * Get the permissions associated with a given list of groups
4534 * @param array $groups Array of Strings List of internal group names
4535 * @return array Array of Strings List of permission key names for given groups combined
4537 public static function getGroupPermissions( $groups ) {
4538 global $wgGroupPermissions, $wgRevokePermissions;
4539 $rights = [];
4540 // grant every granted permission first
4541 foreach ( $groups as $group ) {
4542 if ( isset( $wgGroupPermissions[$group] ) ) {
4543 $rights = array_merge( $rights,
4544 // array_filter removes empty items
4545 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4548 // now revoke the revoked permissions
4549 foreach ( $groups as $group ) {
4550 if ( isset( $wgRevokePermissions[$group] ) ) {
4551 $rights = array_diff( $rights,
4552 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4555 return array_unique( $rights );
4559 * Get all the groups who have a given permission
4561 * @param string $role Role to check
4562 * @return array Array of Strings List of internal group names with the given permission
4564 public static function getGroupsWithPermission( $role ) {
4565 global $wgGroupPermissions;
4566 $allowedGroups = [];
4567 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4568 if ( self::groupHasPermission( $group, $role ) ) {
4569 $allowedGroups[] = $group;
4572 return $allowedGroups;
4576 * Check, if the given group has the given permission
4578 * If you're wanting to check whether all users have a permission, use
4579 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4580 * from anyone.
4582 * @since 1.21
4583 * @param string $group Group to check
4584 * @param string $role Role to check
4585 * @return bool
4587 public static function groupHasPermission( $group, $role ) {
4588 global $wgGroupPermissions, $wgRevokePermissions;
4589 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4590 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4594 * Check if all users may be assumed to have the given permission
4596 * We generally assume so if the right is granted to '*' and isn't revoked
4597 * on any group. It doesn't attempt to take grants or other extension
4598 * limitations on rights into account in the general case, though, as that
4599 * would require it to always return false and defeat the purpose.
4600 * Specifically, session-based rights restrictions (such as OAuth or bot
4601 * passwords) are applied based on the current session.
4603 * @since 1.22
4604 * @param string $right Right to check
4605 * @return bool
4607 public static function isEveryoneAllowed( $right ) {
4608 global $wgGroupPermissions, $wgRevokePermissions;
4609 static $cache = [];
4611 // Use the cached results, except in unit tests which rely on
4612 // being able change the permission mid-request
4613 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4614 return $cache[$right];
4617 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4618 $cache[$right] = false;
4619 return false;
4622 // If it's revoked anywhere, then everyone doesn't have it
4623 foreach ( $wgRevokePermissions as $rights ) {
4624 if ( isset( $rights[$right] ) && $rights[$right] ) {
4625 $cache[$right] = false;
4626 return false;
4630 // Remove any rights that aren't allowed to the global-session user,
4631 // unless there are no sessions for this endpoint.
4632 if ( !defined( 'MW_NO_SESSION' ) ) {
4633 $allowedRights = SessionManager::getGlobalSession()->getAllowedUserRights();
4634 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4635 $cache[$right] = false;
4636 return false;
4640 // Allow extensions to say false
4641 if ( !Hooks::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4642 $cache[$right] = false;
4643 return false;
4646 $cache[$right] = true;
4647 return true;
4651 * Get the localized descriptive name for a group, if it exists
4653 * @param string $group Internal group name
4654 * @return string Localized descriptive group name
4656 public static function getGroupName( $group ) {
4657 $msg = wfMessage( "group-$group" );
4658 return $msg->isBlank() ? $group : $msg->text();
4662 * Get the localized descriptive name for a member of a group, if it exists
4664 * @param string $group Internal group name
4665 * @param string $username Username for gender (since 1.19)
4666 * @return string Localized name for group member
4668 public static function getGroupMember( $group, $username = '#' ) {
4669 $msg = wfMessage( "group-$group-member", $username );
4670 return $msg->isBlank() ? $group : $msg->text();
4674 * Return the set of defined explicit groups.
4675 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4676 * are not included, as they are defined automatically, not in the database.
4677 * @return array Array of internal group names
4679 public static function getAllGroups() {
4680 global $wgGroupPermissions, $wgRevokePermissions;
4681 return array_diff(
4682 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4683 self::getImplicitGroups()
4688 * Get a list of all available permissions.
4689 * @return string[] Array of permission names
4691 public static function getAllRights() {
4692 if ( self::$mAllRights === false ) {
4693 global $wgAvailableRights;
4694 if ( count( $wgAvailableRights ) ) {
4695 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4696 } else {
4697 self::$mAllRights = self::$mCoreRights;
4699 Hooks::run( 'UserGetAllRights', [ &self::$mAllRights ] );
4701 return self::$mAllRights;
4705 * Get a list of implicit groups
4706 * @return array Array of Strings Array of internal group names
4708 public static function getImplicitGroups() {
4709 global $wgImplicitGroups;
4711 $groups = $wgImplicitGroups;
4712 # Deprecated, use $wgImplicitGroups instead
4713 Hooks::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4715 return $groups;
4719 * Get the title of a page describing a particular group
4721 * @param string $group Internal group name
4722 * @return Title|bool Title of the page if it exists, false otherwise
4724 public static function getGroupPage( $group ) {
4725 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4726 if ( $msg->exists() ) {
4727 $title = Title::newFromText( $msg->text() );
4728 if ( is_object( $title ) ) {
4729 return $title;
4732 return false;
4736 * Create a link to the group in HTML, if available;
4737 * else return the group name.
4739 * @param string $group Internal name of the group
4740 * @param string $text The text of the link
4741 * @return string HTML link to the group
4743 public static function makeGroupLinkHTML( $group, $text = '' ) {
4744 if ( $text == '' ) {
4745 $text = self::getGroupName( $group );
4747 $title = self::getGroupPage( $group );
4748 if ( $title ) {
4749 return Linker::link( $title, htmlspecialchars( $text ) );
4750 } else {
4751 return htmlspecialchars( $text );
4756 * Create a link to the group in Wikitext, if available;
4757 * else return the group name.
4759 * @param string $group Internal name of the group
4760 * @param string $text The text of the link
4761 * @return string Wikilink to the group
4763 public static function makeGroupLinkWiki( $group, $text = '' ) {
4764 if ( $text == '' ) {
4765 $text = self::getGroupName( $group );
4767 $title = self::getGroupPage( $group );
4768 if ( $title ) {
4769 $page = $title->getFullText();
4770 return "[[$page|$text]]";
4771 } else {
4772 return $text;
4777 * Returns an array of the groups that a particular group can add/remove.
4779 * @param string $group The group to check for whether it can add/remove
4780 * @return array Array( 'add' => array( addablegroups ),
4781 * 'remove' => array( removablegroups ),
4782 * 'add-self' => array( addablegroups to self),
4783 * 'remove-self' => array( removable groups from self) )
4785 public static function changeableByGroup( $group ) {
4786 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4788 $groups = [
4789 'add' => [],
4790 'remove' => [],
4791 'add-self' => [],
4792 'remove-self' => []
4795 if ( empty( $wgAddGroups[$group] ) ) {
4796 // Don't add anything to $groups
4797 } elseif ( $wgAddGroups[$group] === true ) {
4798 // You get everything
4799 $groups['add'] = self::getAllGroups();
4800 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4801 $groups['add'] = $wgAddGroups[$group];
4804 // Same thing for remove
4805 if ( empty( $wgRemoveGroups[$group] ) ) {
4806 // Do nothing
4807 } elseif ( $wgRemoveGroups[$group] === true ) {
4808 $groups['remove'] = self::getAllGroups();
4809 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4810 $groups['remove'] = $wgRemoveGroups[$group];
4813 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4814 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4815 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4816 if ( is_int( $key ) ) {
4817 $wgGroupsAddToSelf['user'][] = $value;
4822 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4823 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4824 if ( is_int( $key ) ) {
4825 $wgGroupsRemoveFromSelf['user'][] = $value;
4830 // Now figure out what groups the user can add to him/herself
4831 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4832 // Do nothing
4833 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4834 // No idea WHY this would be used, but it's there
4835 $groups['add-self'] = User::getAllGroups();
4836 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4837 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4840 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4841 // Do nothing
4842 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4843 $groups['remove-self'] = User::getAllGroups();
4844 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4845 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4848 return $groups;
4852 * Returns an array of groups that this user can add and remove
4853 * @return array Array( 'add' => array( addablegroups ),
4854 * 'remove' => array( removablegroups ),
4855 * 'add-self' => array( addablegroups to self),
4856 * 'remove-self' => array( removable groups from self) )
4858 public function changeableGroups() {
4859 if ( $this->isAllowed( 'userrights' ) ) {
4860 // This group gives the right to modify everything (reverse-
4861 // compatibility with old "userrights lets you change
4862 // everything")
4863 // Using array_merge to make the groups reindexed
4864 $all = array_merge( User::getAllGroups() );
4865 return [
4866 'add' => $all,
4867 'remove' => $all,
4868 'add-self' => [],
4869 'remove-self' => []
4873 // Okay, it's not so simple, we will have to go through the arrays
4874 $groups = [
4875 'add' => [],
4876 'remove' => [],
4877 'add-self' => [],
4878 'remove-self' => []
4880 $addergroups = $this->getEffectiveGroups();
4882 foreach ( $addergroups as $addergroup ) {
4883 $groups = array_merge_recursive(
4884 $groups, $this->changeableByGroup( $addergroup )
4886 $groups['add'] = array_unique( $groups['add'] );
4887 $groups['remove'] = array_unique( $groups['remove'] );
4888 $groups['add-self'] = array_unique( $groups['add-self'] );
4889 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4891 return $groups;
4895 * Deferred version of incEditCountImmediate()
4897 public function incEditCount() {
4898 wfGetDB( DB_MASTER )->onTransactionPreCommitOrIdle( function() {
4899 $this->incEditCountImmediate();
4900 } );
4904 * Increment the user's edit-count field.
4905 * Will have no effect for anonymous users.
4906 * @since 1.26
4908 public function incEditCountImmediate() {
4909 if ( $this->isAnon() ) {
4910 return;
4913 $dbw = wfGetDB( DB_MASTER );
4914 // No rows will be "affected" if user_editcount is NULL
4915 $dbw->update(
4916 'user',
4917 [ 'user_editcount=user_editcount+1' ],
4918 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
4919 __METHOD__
4921 // Lazy initialization check...
4922 if ( $dbw->affectedRows() == 0 ) {
4923 // Now here's a goddamn hack...
4924 $dbr = wfGetDB( DB_SLAVE );
4925 if ( $dbr !== $dbw ) {
4926 // If we actually have a slave server, the count is
4927 // at least one behind because the current transaction
4928 // has not been committed and replicated.
4929 $this->initEditCount( 1 );
4930 } else {
4931 // But if DB_SLAVE is selecting the master, then the
4932 // count we just read includes the revision that was
4933 // just added in the working transaction.
4934 $this->initEditCount();
4937 // Edit count in user cache too
4938 $this->invalidateCache();
4942 * Initialize user_editcount from data out of the revision table
4944 * @param int $add Edits to add to the count from the revision table
4945 * @return int Number of edits
4947 protected function initEditCount( $add = 0 ) {
4948 // Pull from a slave to be less cruel to servers
4949 // Accuracy isn't the point anyway here
4950 $dbr = wfGetDB( DB_SLAVE );
4951 $count = (int)$dbr->selectField(
4952 'revision',
4953 'COUNT(rev_user)',
4954 [ 'rev_user' => $this->getId() ],
4955 __METHOD__
4957 $count = $count + $add;
4959 $dbw = wfGetDB( DB_MASTER );
4960 $dbw->update(
4961 'user',
4962 [ 'user_editcount' => $count ],
4963 [ 'user_id' => $this->getId() ],
4964 __METHOD__
4967 return $count;
4971 * Get the description of a given right
4973 * @param string $right Right to query
4974 * @return string Localized description of the right
4976 public static function getRightDescription( $right ) {
4977 $key = "right-$right";
4978 $msg = wfMessage( $key );
4979 return $msg->isBlank() ? $right : $msg->text();
4983 * Make a new-style password hash
4985 * @param string $password Plain-text password
4986 * @param bool|string $salt Optional salt, may be random or the user ID.
4987 * If unspecified or false, will generate one automatically
4988 * @return string Password hash
4989 * @deprecated since 1.24, use Password class
4991 public static function crypt( $password, $salt = false ) {
4992 wfDeprecated( __METHOD__, '1.24' );
4993 $passwordFactory = new PasswordFactory();
4994 $passwordFactory->init( RequestContext::getMain()->getConfig() );
4995 $hash = $passwordFactory->newFromPlaintext( $password );
4996 return $hash->toString();
5000 * Compare a password hash with a plain-text password. Requires the user
5001 * ID if there's a chance that the hash is an old-style hash.
5003 * @param string $hash Password hash
5004 * @param string $password Plain-text password to compare
5005 * @param string|bool $userId User ID for old-style password salt
5007 * @return bool
5008 * @deprecated since 1.24, use Password class
5010 public static function comparePasswords( $hash, $password, $userId = false ) {
5011 wfDeprecated( __METHOD__, '1.24' );
5013 // Check for *really* old password hashes that don't even have a type
5014 // The old hash format was just an md5 hex hash, with no type information
5015 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5016 global $wgPasswordSalt;
5017 if ( $wgPasswordSalt ) {
5018 $password = ":B:{$userId}:{$hash}";
5019 } else {
5020 $password = ":A:{$hash}";
5024 $passwordFactory = new PasswordFactory();
5025 $passwordFactory->init( RequestContext::getMain()->getConfig() );
5026 $hash = $passwordFactory->newFromCiphertext( $hash );
5027 return $hash->equals( $password );
5031 * Add a newuser log entry for this user.
5032 * Before 1.19 the return value was always true.
5034 * @param string|bool $action Account creation type.
5035 * - String, one of the following values:
5036 * - 'create' for an anonymous user creating an account for himself.
5037 * This will force the action's performer to be the created user itself,
5038 * no matter the value of $wgUser
5039 * - 'create2' for a logged in user creating an account for someone else
5040 * - 'byemail' when the created user will receive its password by e-mail
5041 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5042 * - Boolean means whether the account was created by e-mail (deprecated):
5043 * - true will be converted to 'byemail'
5044 * - false will be converted to 'create' if this object is the same as
5045 * $wgUser and to 'create2' otherwise
5047 * @param string $reason User supplied reason
5049 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
5051 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5052 global $wgUser, $wgNewUserLog;
5053 if ( empty( $wgNewUserLog ) ) {
5054 return true; // disabled
5057 if ( $action === true ) {
5058 $action = 'byemail';
5059 } elseif ( $action === false ) {
5060 if ( $this->equals( $wgUser ) ) {
5061 $action = 'create';
5062 } else {
5063 $action = 'create2';
5067 if ( $action === 'create' || $action === 'autocreate' ) {
5068 $performer = $this;
5069 } else {
5070 $performer = $wgUser;
5073 $logEntry = new ManualLogEntry( 'newusers', $action );
5074 $logEntry->setPerformer( $performer );
5075 $logEntry->setTarget( $this->getUserPage() );
5076 $logEntry->setComment( $reason );
5077 $logEntry->setParameters( [
5078 '4::userid' => $this->getId(),
5079 ] );
5080 $logid = $logEntry->insert();
5082 if ( $action !== 'autocreate' ) {
5083 $logEntry->publish( $logid );
5086 return (int)$logid;
5090 * Add an autocreate newuser log entry for this user
5091 * Used by things like CentralAuth and perhaps other authplugins.
5092 * Consider calling addNewUserLogEntry() directly instead.
5094 * @return bool
5096 public function addNewUserLogEntryAutoCreate() {
5097 $this->addNewUserLogEntry( 'autocreate' );
5099 return true;
5103 * Load the user options either from cache, the database or an array
5105 * @param array $data Rows for the current user out of the user_properties table
5107 protected function loadOptions( $data = null ) {
5108 global $wgContLang;
5110 $this->load();
5112 if ( $this->mOptionsLoaded ) {
5113 return;
5116 $this->mOptions = self::getDefaultOptions();
5118 if ( !$this->getId() ) {
5119 // For unlogged-in users, load language/variant options from request.
5120 // There's no need to do it for logged-in users: they can set preferences,
5121 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5122 // so don't override user's choice (especially when the user chooses site default).
5123 $variant = $wgContLang->getDefaultVariant();
5124 $this->mOptions['variant'] = $variant;
5125 $this->mOptions['language'] = $variant;
5126 $this->mOptionsLoaded = true;
5127 return;
5130 // Maybe load from the object
5131 if ( !is_null( $this->mOptionOverrides ) ) {
5132 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5133 foreach ( $this->mOptionOverrides as $key => $value ) {
5134 $this->mOptions[$key] = $value;
5136 } else {
5137 if ( !is_array( $data ) ) {
5138 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5139 // Load from database
5140 $dbr = ( $this->queryFlagsUsed & self::READ_LATEST )
5141 ? wfGetDB( DB_MASTER )
5142 : wfGetDB( DB_SLAVE );
5144 $res = $dbr->select(
5145 'user_properties',
5146 [ 'up_property', 'up_value' ],
5147 [ 'up_user' => $this->getId() ],
5148 __METHOD__
5151 $this->mOptionOverrides = [];
5152 $data = [];
5153 foreach ( $res as $row ) {
5154 $data[$row->up_property] = $row->up_value;
5157 foreach ( $data as $property => $value ) {
5158 $this->mOptionOverrides[$property] = $value;
5159 $this->mOptions[$property] = $value;
5163 $this->mOptionsLoaded = true;
5165 Hooks::run( 'UserLoadOptions', [ $this, &$this->mOptions ] );
5169 * Saves the non-default options for this user, as previously set e.g. via
5170 * setOption(), in the database's "user_properties" (preferences) table.
5171 * Usually used via saveSettings().
5173 protected function saveOptions() {
5174 $this->loadOptions();
5176 // Not using getOptions(), to keep hidden preferences in database
5177 $saveOptions = $this->mOptions;
5179 // Allow hooks to abort, for instance to save to a global profile.
5180 // Reset options to default state before saving.
5181 if ( !Hooks::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5182 return;
5185 $userId = $this->getId();
5187 $insert_rows = []; // all the new preference rows
5188 foreach ( $saveOptions as $key => $value ) {
5189 // Don't bother storing default values
5190 $defaultOption = self::getDefaultOption( $key );
5191 if ( ( $defaultOption === null && $value !== false && $value !== null )
5192 || $value != $defaultOption
5194 $insert_rows[] = [
5195 'up_user' => $userId,
5196 'up_property' => $key,
5197 'up_value' => $value,
5202 $dbw = wfGetDB( DB_MASTER );
5204 $res = $dbw->select( 'user_properties',
5205 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__ );
5207 // Find prior rows that need to be removed or updated. These rows will
5208 // all be deleted (the later so that INSERT IGNORE applies the new values).
5209 $keysDelete = [];
5210 foreach ( $res as $row ) {
5211 if ( !isset( $saveOptions[$row->up_property] )
5212 || strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
5214 $keysDelete[] = $row->up_property;
5218 if ( count( $keysDelete ) ) {
5219 // Do the DELETE by PRIMARY KEY for prior rows.
5220 // In the past a very large portion of calls to this function are for setting
5221 // 'rememberpassword' for new accounts (a preference that has since been removed).
5222 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5223 // caused gap locks on [max user ID,+infinity) which caused high contention since
5224 // updates would pile up on each other as they are for higher (newer) user IDs.
5225 // It might not be necessary these days, but it shouldn't hurt either.
5226 $dbw->delete( 'user_properties',
5227 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__ );
5229 // Insert the new preference rows
5230 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, [ 'IGNORE' ] );
5234 * Lazily instantiate and return a factory object for making passwords
5236 * @deprecated since 1.27, create a PasswordFactory directly instead
5237 * @return PasswordFactory
5239 public static function getPasswordFactory() {
5240 wfDeprecated( __METHOD__, '1.27' );
5241 $ret = new PasswordFactory();
5242 $ret->init( RequestContext::getMain()->getConfig() );
5243 return $ret;
5247 * Provide an array of HTML5 attributes to put on an input element
5248 * intended for the user to enter a new password. This may include
5249 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5251 * Do *not* use this when asking the user to enter his current password!
5252 * Regardless of configuration, users may have invalid passwords for whatever
5253 * reason (e.g., they were set before requirements were tightened up).
5254 * Only use it when asking for a new password, like on account creation or
5255 * ResetPass.
5257 * Obviously, you still need to do server-side checking.
5259 * NOTE: A combination of bugs in various browsers means that this function
5260 * actually just returns array() unconditionally at the moment. May as
5261 * well keep it around for when the browser bugs get fixed, though.
5263 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5265 * @deprecated since 1.27
5266 * @return array Array of HTML attributes suitable for feeding to
5267 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5268 * That will get confused by the boolean attribute syntax used.)
5270 public static function passwordChangeInputAttribs() {
5271 global $wgMinimalPasswordLength;
5273 if ( $wgMinimalPasswordLength == 0 ) {
5274 return [];
5277 # Note that the pattern requirement will always be satisfied if the
5278 # input is empty, so we need required in all cases.
5280 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5281 # if e-mail confirmation is being used. Since HTML5 input validation
5282 # is b0rked anyway in some browsers, just return nothing. When it's
5283 # re-enabled, fix this code to not output required for e-mail
5284 # registration.
5285 # $ret = array( 'required' );
5286 $ret = [];
5288 # We can't actually do this right now, because Opera 9.6 will print out
5289 # the entered password visibly in its error message! When other
5290 # browsers add support for this attribute, or Opera fixes its support,
5291 # we can add support with a version check to avoid doing this on Opera
5292 # versions where it will be a problem. Reported to Opera as
5293 # DSK-262266, but they don't have a public bug tracker for us to follow.
5295 if ( $wgMinimalPasswordLength > 1 ) {
5296 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5297 $ret['title'] = wfMessage( 'passwordtooshort' )
5298 ->numParams( $wgMinimalPasswordLength )->text();
5302 return $ret;
5306 * Return the list of user fields that should be selected to create
5307 * a new user object.
5308 * @return array
5310 public static function selectFields() {
5311 return [
5312 'user_id',
5313 'user_name',
5314 'user_real_name',
5315 'user_email',
5316 'user_touched',
5317 'user_token',
5318 'user_email_authenticated',
5319 'user_email_token',
5320 'user_email_token_expires',
5321 'user_registration',
5322 'user_editcount',
5327 * Factory function for fatal permission-denied errors
5329 * @since 1.22
5330 * @param string $permission User right required
5331 * @return Status
5333 static function newFatalPermissionDeniedStatus( $permission ) {
5334 global $wgLang;
5336 $groups = array_map(
5337 [ 'User', 'makeGroupLinkWiki' ],
5338 User::getGroupsWithPermission( $permission )
5341 if ( $groups ) {
5342 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5343 } else {
5344 return Status::newFatal( 'badaccess-group0' );
5349 * Get a new instance of this user that was loaded from the master via a locking read
5351 * Use this instead of the main context User when updating that user. This avoids races
5352 * where that user was loaded from a slave or even the master but without proper locks.
5354 * @return User|null Returns null if the user was not found in the DB
5355 * @since 1.27
5357 public function getInstanceForUpdate() {
5358 if ( !$this->getId() ) {
5359 return null; // anon
5362 $user = self::newFromId( $this->getId() );
5363 if ( !$user->loadFromId( self::READ_EXCLUSIVE ) ) {
5364 return null;
5367 return $user;
5371 * Checks if two user objects point to the same user.
5373 * @since 1.25
5374 * @param User $user
5375 * @return bool
5377 public function equals( User $user ) {
5378 return $this->getName() === $user->getName();