Special case opus mime detction
[mediawiki.git] / includes / user / User.php
blobfed64c2a682e6ec8d37bc55fa5513ff8af94f958
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\MediaWikiServices;
24 use MediaWiki\Session\SessionManager;
25 use MediaWiki\Session\Token;
26 use MediaWiki\Auth\AuthManager;
27 use MediaWiki\Auth\AuthenticationResponse;
28 use MediaWiki\Auth\AuthenticationRequest;
29 use Wikimedia\ScopedCallback;
31 /**
32 * String Some punctuation to prevent editing from broken text-mangling proxies.
33 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
34 * @ingroup Constants
36 define( 'EDIT_TOKEN_SUFFIX', Token::SUFFIX );
38 /**
39 * The User object encapsulates all of the user-specific settings (user_id,
40 * name, rights, email address, options, last login time). Client
41 * classes use the getXXX() functions to access these fields. These functions
42 * do all the work of determining whether the user is logged in,
43 * whether the requested option can be satisfied from cookies or
44 * whether a database query is needed. Most of the settings needed
45 * for rendering normal pages are set in the cookie to minimize use
46 * of the database.
48 class User implements IDBAccessObject {
49 /**
50 * @const int Number of characters in user_token field.
52 const TOKEN_LENGTH = 32;
54 /**
55 * @const string An invalid value for user_token
57 const INVALID_TOKEN = '*** INVALID ***';
59 /**
60 * Global constant made accessible as class constants so that autoloader
61 * magic can be used.
62 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
64 const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
66 /**
67 * @const int Serialized record version.
69 const VERSION = 10;
71 /**
72 * Exclude user options that are set to their default value.
73 * @since 1.25
75 const GETOPTIONS_EXCLUDE_DEFAULTS = 1;
77 /**
78 * @since 1.27
80 const CHECK_USER_RIGHTS = true;
82 /**
83 * @since 1.27
85 const IGNORE_USER_RIGHTS = false;
87 /**
88 * Array of Strings List of member variables which are saved to the
89 * shared cache (memcached). Any operation which changes the
90 * corresponding database fields must call a cache-clearing function.
91 * @showinitializer
93 protected static $mCacheVars = [
94 // user table
95 'mId',
96 'mName',
97 'mRealName',
98 'mEmail',
99 'mTouched',
100 'mToken',
101 'mEmailAuthenticated',
102 'mEmailToken',
103 'mEmailTokenExpires',
104 'mRegistration',
105 'mEditCount',
106 // user_groups table
107 'mGroups',
108 // user_properties table
109 'mOptionOverrides',
113 * Array of Strings Core rights.
114 * Each of these should have a corresponding message of the form
115 * "right-$right".
116 * @showinitializer
118 protected static $mCoreRights = [
119 'apihighlimits',
120 'applychangetags',
121 'autoconfirmed',
122 'autocreateaccount',
123 'autopatrol',
124 'bigdelete',
125 'block',
126 'blockemail',
127 'bot',
128 'browsearchive',
129 'changetags',
130 'createaccount',
131 'createpage',
132 'createtalk',
133 'delete',
134 'deletechangetags',
135 'deletedhistory',
136 'deletedtext',
137 'deletelogentry',
138 'deleterevision',
139 'edit',
140 'editcontentmodel',
141 'editinterface',
142 'editprotected',
143 'editmyoptions',
144 'editmyprivateinfo',
145 'editmyusercss',
146 'editmyuserjs',
147 'editmywatchlist',
148 'editsemiprotected',
149 'editusercssjs', # deprecated
150 'editusercss',
151 'edituserjs',
152 'hideuser',
153 'import',
154 'importupload',
155 'ipblock-exempt',
156 'managechangetags',
157 'markbotedits',
158 'mergehistory',
159 'minoredit',
160 'move',
161 'movefile',
162 'move-categorypages',
163 'move-rootuserpages',
164 'move-subpages',
165 'nominornewtalk',
166 'noratelimit',
167 'override-export-depth',
168 'pagelang',
169 'patrol',
170 'patrolmarks',
171 'protect',
172 'purge',
173 'read',
174 'reupload',
175 'reupload-own',
176 'reupload-shared',
177 'rollback',
178 'sendemail',
179 'siteadmin',
180 'suppressionlog',
181 'suppressredirect',
182 'suppressrevision',
183 'unblockself',
184 'undelete',
185 'unwatchedpages',
186 'upload',
187 'upload_by_url',
188 'userrights',
189 'userrights-interwiki',
190 'viewmyprivateinfo',
191 'viewmywatchlist',
192 'viewsuppressed',
193 'writeapi',
197 * String Cached results of getAllRights()
199 protected static $mAllRights = false;
201 /** Cache variables */
202 // @{
203 /** @var int */
204 public $mId;
205 /** @var string */
206 public $mName;
207 /** @var string */
208 public $mRealName;
210 /** @var string */
211 public $mEmail;
212 /** @var string TS_MW timestamp from the DB */
213 public $mTouched;
214 /** @var string TS_MW timestamp from cache */
215 protected $mQuickTouched;
216 /** @var string */
217 protected $mToken;
218 /** @var string */
219 public $mEmailAuthenticated;
220 /** @var string */
221 protected $mEmailToken;
222 /** @var string */
223 protected $mEmailTokenExpires;
224 /** @var string */
225 protected $mRegistration;
226 /** @var int */
227 protected $mEditCount;
228 /** @var array */
229 public $mGroups;
230 /** @var array */
231 protected $mOptionOverrides;
232 // @}
235 * Bool Whether the cache variables have been loaded.
237 // @{
238 public $mOptionsLoaded;
241 * Array with already loaded items or true if all items have been loaded.
243 protected $mLoadedItems = [];
244 // @}
247 * String Initialization data source if mLoadedItems!==true. May be one of:
248 * - 'defaults' anonymous user initialised from class defaults
249 * - 'name' initialise from mName
250 * - 'id' initialise from mId
251 * - 'session' log in from session if possible
253 * Use the User::newFrom*() family of functions to set this.
255 public $mFrom;
258 * Lazy-initialized variables, invalidated with clearInstanceCache
260 protected $mNewtalk;
261 /** @var string */
262 protected $mDatePreference;
263 /** @var string */
264 public $mBlockedby;
265 /** @var string */
266 protected $mHash;
267 /** @var array */
268 public $mRights;
269 /** @var string */
270 protected $mBlockreason;
271 /** @var array */
272 protected $mEffectiveGroups;
273 /** @var array */
274 protected $mImplicitGroups;
275 /** @var array */
276 protected $mFormerGroups;
277 /** @var Block */
278 protected $mGlobalBlock;
279 /** @var bool */
280 protected $mLocked;
281 /** @var bool */
282 public $mHideName;
283 /** @var array */
284 public $mOptions;
287 * @var WebRequest
289 private $mRequest;
291 /** @var Block */
292 public $mBlock;
294 /** @var bool */
295 protected $mAllowUsertalk;
297 /** @var Block */
298 private $mBlockedFromCreateAccount = false;
300 /** @var integer User::READ_* constant bitfield used to load data */
301 protected $queryFlagsUsed = self::READ_NORMAL;
303 /** @var string Indicates type of block (used for eventlogging)
304 * Permitted values: 'cookie-block', 'proxy-block', 'openproxy-block', 'xff-block',
305 * 'config-block'
307 public $blockTrigger = false;
309 public static $idCacheByName = [];
312 * Lightweight constructor for an anonymous user.
313 * Use the User::newFrom* factory functions for other kinds of users.
315 * @see newFromName()
316 * @see newFromId()
317 * @see newFromConfirmationCode()
318 * @see newFromSession()
319 * @see newFromRow()
321 public function __construct() {
322 $this->clearInstanceCache( 'defaults' );
326 * @return string
328 public function __toString() {
329 return (string)$this->getName();
333 * Test if it's safe to load this User object.
335 * You should typically check this before using $wgUser or
336 * RequestContext::getUser in a method that might be called before the
337 * system has been fully initialized. If the object is unsafe, you should
338 * use an anonymous user:
339 * \code
340 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
341 * \endcode
343 * @since 1.27
344 * @return bool
346 public function isSafeToLoad() {
347 global $wgFullyInitialised;
349 // The user is safe to load if:
350 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
351 // * mLoadedItems === true (already loaded)
352 // * mFrom !== 'session' (sessions not involved at all)
354 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
355 $this->mLoadedItems === true || $this->mFrom !== 'session';
359 * Load the user table data for this object from the source given by mFrom.
361 * @param integer $flags User::READ_* constant bitfield
363 public function load( $flags = self::READ_NORMAL ) {
364 global $wgFullyInitialised;
366 if ( $this->mLoadedItems === true ) {
367 return;
370 // Set it now to avoid infinite recursion in accessors
371 $oldLoadedItems = $this->mLoadedItems;
372 $this->mLoadedItems = true;
373 $this->queryFlagsUsed = $flags;
375 // If this is called too early, things are likely to break.
376 if ( !$wgFullyInitialised && $this->mFrom === 'session' ) {
377 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
378 ->warning( 'User::loadFromSession called before the end of Setup.php', [
379 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
380 ] );
381 $this->loadDefaults();
382 $this->mLoadedItems = $oldLoadedItems;
383 return;
386 switch ( $this->mFrom ) {
387 case 'defaults':
388 $this->loadDefaults();
389 break;
390 case 'name':
391 // Make sure this thread sees its own changes
392 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
393 $flags |= self::READ_LATEST;
394 $this->queryFlagsUsed = $flags;
397 $this->mId = self::idFromName( $this->mName, $flags );
398 if ( !$this->mId ) {
399 // Nonexistent user placeholder object
400 $this->loadDefaults( $this->mName );
401 } else {
402 $this->loadFromId( $flags );
404 break;
405 case 'id':
406 $this->loadFromId( $flags );
407 break;
408 case 'session':
409 if ( !$this->loadFromSession() ) {
410 // Loading from session failed. Load defaults.
411 $this->loadDefaults();
413 Hooks::run( 'UserLoadAfterLoadFromSession', [ $this ] );
414 break;
415 default:
416 throw new UnexpectedValueException(
417 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
422 * Load user table data, given mId has already been set.
423 * @param integer $flags User::READ_* constant bitfield
424 * @return bool False if the ID does not exist, true otherwise
426 public function loadFromId( $flags = self::READ_NORMAL ) {
427 if ( $this->mId == 0 ) {
428 // Anonymous users are not in the database (don't need cache)
429 $this->loadDefaults();
430 return false;
433 // Try cache (unless this needs data from the master DB).
434 // NOTE: if this thread called saveSettings(), the cache was cleared.
435 $latest = DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST );
436 if ( $latest ) {
437 if ( !$this->loadFromDatabase( $flags ) ) {
438 // Can't load from ID
439 return false;
441 } else {
442 $this->loadFromCache();
445 $this->mLoadedItems = true;
446 $this->queryFlagsUsed = $flags;
448 return true;
452 * @since 1.27
453 * @param string $wikiId
454 * @param integer $userId
456 public static function purge( $wikiId, $userId ) {
457 $cache = ObjectCache::getMainWANInstance();
458 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
459 $cache->delete( $key );
463 * @since 1.27
464 * @param WANObjectCache $cache
465 * @return string
467 protected function getCacheKey( WANObjectCache $cache ) {
468 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId );
472 * Load user data from shared cache, given mId has already been set.
474 * @return bool True
475 * @since 1.25
477 protected function loadFromCache() {
478 $cache = ObjectCache::getMainWANInstance();
479 $data = $cache->getWithSetCallback(
480 $this->getCacheKey( $cache ),
481 $cache::TTL_HOUR,
482 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
483 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
484 wfDebug( "User: cache miss for user {$this->mId}\n" );
486 $this->loadFromDatabase( self::READ_NORMAL );
487 $this->loadGroups();
488 $this->loadOptions();
490 $data = [];
491 foreach ( self::$mCacheVars as $name ) {
492 $data[$name] = $this->$name;
495 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX, $this->mTouched ), $ttl );
497 return $data;
500 [ 'pcTTL' => $cache::TTL_PROC_LONG, 'version' => self::VERSION ]
503 // Restore from cache
504 foreach ( self::$mCacheVars as $name ) {
505 $this->$name = $data[$name];
508 return true;
511 /** @name newFrom*() static factory methods */
512 // @{
515 * Static factory method for creation from username.
517 * This is slightly less efficient than newFromId(), so use newFromId() if
518 * you have both an ID and a name handy.
520 * @param string $name Username, validated by Title::newFromText()
521 * @param string|bool $validate Validate username. Takes the same parameters as
522 * User::getCanonicalName(), except that true is accepted as an alias
523 * for 'valid', for BC.
525 * @return User|bool User object, or false if the username is invalid
526 * (e.g. if it contains illegal characters or is an IP address). If the
527 * username is not present in the database, the result will be a user object
528 * with a name, zero user ID and default settings.
530 public static function newFromName( $name, $validate = 'valid' ) {
531 if ( $validate === true ) {
532 $validate = 'valid';
534 $name = self::getCanonicalName( $name, $validate );
535 if ( $name === false ) {
536 return false;
537 } else {
538 // Create unloaded user object
539 $u = new User;
540 $u->mName = $name;
541 $u->mFrom = 'name';
542 $u->setItemLoaded( 'name' );
543 return $u;
548 * Static factory method for creation from a given user ID.
550 * @param int $id Valid user ID
551 * @return User The corresponding User object
553 public static function newFromId( $id ) {
554 $u = new User;
555 $u->mId = $id;
556 $u->mFrom = 'id';
557 $u->setItemLoaded( 'id' );
558 return $u;
562 * Factory method to fetch whichever user has a given email confirmation code.
563 * This code is generated when an account is created or its e-mail address
564 * has changed.
566 * If the code is invalid or has expired, returns NULL.
568 * @param string $code Confirmation code
569 * @param int $flags User::READ_* bitfield
570 * @return User|null
572 public static function newFromConfirmationCode( $code, $flags = 0 ) {
573 $db = ( $flags & self::READ_LATEST ) == self::READ_LATEST
574 ? wfGetDB( DB_MASTER )
575 : wfGetDB( DB_REPLICA );
577 $id = $db->selectField(
578 'user',
579 'user_id',
581 'user_email_token' => md5( $code ),
582 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
586 return $id ? User::newFromId( $id ) : null;
590 * Create a new user object using data from session. If the login
591 * credentials are invalid, the result is an anonymous user.
593 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
594 * @return User
596 public static function newFromSession( WebRequest $request = null ) {
597 $user = new User;
598 $user->mFrom = 'session';
599 $user->mRequest = $request;
600 return $user;
604 * Create a new user object from a user row.
605 * The row should have the following fields from the user table in it:
606 * - either user_name or user_id to load further data if needed (or both)
607 * - user_real_name
608 * - all other fields (email, etc.)
609 * It is useless to provide the remaining fields if either user_id,
610 * user_name and user_real_name are not provided because the whole row
611 * will be loaded once more from the database when accessing them.
613 * @param stdClass $row A row from the user table
614 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
615 * @return User
617 public static function newFromRow( $row, $data = null ) {
618 $user = new User;
619 $user->loadFromRow( $row, $data );
620 return $user;
624 * Static factory method for creation of a "system" user from username.
626 * A "system" user is an account that's used to attribute logged actions
627 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
628 * might include the 'Maintenance script' or 'Conversion script' accounts
629 * used by various scripts in the maintenance/ directory or accounts such
630 * as 'MediaWiki message delivery' used by the MassMessage extension.
632 * This can optionally create the user if it doesn't exist, and "steal" the
633 * account if it does exist.
635 * "Stealing" an existing user is intended to make it impossible for normal
636 * authentication processes to use the account, effectively disabling the
637 * account for normal use:
638 * - Email is invalidated, to prevent account recovery by emailing a
639 * temporary password and to disassociate the account from the existing
640 * human.
641 * - The token is set to a magic invalid value, to kill existing sessions
642 * and to prevent $this->setToken() calls from resetting the token to a
643 * valid value.
644 * - SessionManager is instructed to prevent new sessions for the user, to
645 * do things like deauthorizing OAuth consumers.
646 * - AuthManager is instructed to revoke access, to invalidate or remove
647 * passwords and other credentials.
649 * @param string $name Username
650 * @param array $options Options are:
651 * - validate: As for User::getCanonicalName(), default 'valid'
652 * - create: Whether to create the user if it doesn't already exist, default true
653 * - steal: Whether to "disable" the account for normal use if it already
654 * exists, default false
655 * @return User|null
656 * @since 1.27
658 public static function newSystemUser( $name, $options = [] ) {
659 $options += [
660 'validate' => 'valid',
661 'create' => true,
662 'steal' => false,
665 $name = self::getCanonicalName( $name, $options['validate'] );
666 if ( $name === false ) {
667 return null;
670 $fields = self::selectFields();
672 $dbw = wfGetDB( DB_MASTER );
673 $row = $dbw->selectRow(
674 'user',
675 $fields,
676 [ 'user_name' => $name ],
677 __METHOD__
679 if ( !$row ) {
680 // No user. Create it?
681 return $options['create'] ? self::createNew( $name, [ 'token' => self::INVALID_TOKEN ] ) : null;
683 $user = self::newFromRow( $row );
685 // A user is considered to exist as a non-system user if it can
686 // authenticate, or has an email set, or has a non-invalid token.
687 if ( $user->mEmail || $user->mToken !== self::INVALID_TOKEN ||
688 AuthManager::singleton()->userCanAuthenticate( $name )
690 // User exists. Steal it?
691 if ( !$options['steal'] ) {
692 return null;
695 AuthManager::singleton()->revokeAccessForUser( $name );
697 $user->invalidateEmail();
698 $user->mToken = self::INVALID_TOKEN;
699 $user->saveSettings();
700 SessionManager::singleton()->preventSessionsForUser( $user->getName() );
703 return $user;
706 // @}
709 * Get the username corresponding to a given user ID
710 * @param int $id User ID
711 * @return string|bool The corresponding username
713 public static function whoIs( $id ) {
714 return UserCache::singleton()->getProp( $id, 'name' );
718 * Get the real name of a user given their user ID
720 * @param int $id User ID
721 * @return string|bool The corresponding user's real name
723 public static function whoIsReal( $id ) {
724 return UserCache::singleton()->getProp( $id, 'real_name' );
728 * Get database id given a user name
729 * @param string $name Username
730 * @param integer $flags User::READ_* constant bitfield
731 * @return int|null The corresponding user's ID, or null if user is nonexistent
733 public static function idFromName( $name, $flags = self::READ_NORMAL ) {
734 $nt = Title::makeTitleSafe( NS_USER, $name );
735 if ( is_null( $nt ) ) {
736 // Illegal name
737 return null;
740 if ( !( $flags & self::READ_LATEST ) && isset( self::$idCacheByName[$name] ) ) {
741 return self::$idCacheByName[$name];
744 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
745 $db = wfGetDB( $index );
747 $s = $db->selectRow(
748 'user',
749 [ 'user_id' ],
750 [ 'user_name' => $nt->getText() ],
751 __METHOD__,
752 $options
755 if ( $s === false ) {
756 $result = null;
757 } else {
758 $result = $s->user_id;
761 self::$idCacheByName[$name] = $result;
763 if ( count( self::$idCacheByName ) > 1000 ) {
764 self::$idCacheByName = [];
767 return $result;
771 * Reset the cache used in idFromName(). For use in tests.
773 public static function resetIdByNameCache() {
774 self::$idCacheByName = [];
778 * Does the string match an anonymous IP address?
780 * This function exists for username validation, in order to reject
781 * usernames which are similar in form to IP addresses. Strings such
782 * as 300.300.300.300 will return true because it looks like an IP
783 * address, despite not being strictly valid.
785 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
786 * address because the usemod software would "cloak" anonymous IP
787 * addresses like this, if we allowed accounts like this to be created
788 * new users could get the old edits of these anonymous users.
790 * @param string $name Name to match
791 * @return bool
793 public static function isIP( $name ) {
794 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
795 || IP::isIPv6( $name );
799 * Is the input a valid username?
801 * Checks if the input is a valid username, we don't want an empty string,
802 * an IP address, anything that contains slashes (would mess up subpages),
803 * is longer than the maximum allowed username size or doesn't begin with
804 * a capital letter.
806 * @param string $name Name to match
807 * @return bool
809 public static function isValidUserName( $name ) {
810 global $wgContLang, $wgMaxNameChars;
812 if ( $name == ''
813 || User::isIP( $name )
814 || strpos( $name, '/' ) !== false
815 || strlen( $name ) > $wgMaxNameChars
816 || $name != $wgContLang->ucfirst( $name )
818 return false;
821 // Ensure that the name can't be misresolved as a different title,
822 // such as with extra namespace keys at the start.
823 $parsed = Title::newFromText( $name );
824 if ( is_null( $parsed )
825 || $parsed->getNamespace()
826 || strcmp( $name, $parsed->getPrefixedText() ) ) {
827 return false;
830 // Check an additional blacklist of troublemaker characters.
831 // Should these be merged into the title char list?
832 $unicodeBlacklist = '/[' .
833 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
834 '\x{00a0}' . # non-breaking space
835 '\x{2000}-\x{200f}' . # various whitespace
836 '\x{2028}-\x{202f}' . # breaks and control chars
837 '\x{3000}' . # ideographic space
838 '\x{e000}-\x{f8ff}' . # private use
839 ']/u';
840 if ( preg_match( $unicodeBlacklist, $name ) ) {
841 return false;
844 return true;
848 * Usernames which fail to pass this function will be blocked
849 * from user login and new account registrations, but may be used
850 * internally by batch processes.
852 * If an account already exists in this form, login will be blocked
853 * by a failure to pass this function.
855 * @param string $name Name to match
856 * @return bool
858 public static function isUsableName( $name ) {
859 global $wgReservedUsernames;
860 // Must be a valid username, obviously ;)
861 if ( !self::isValidUserName( $name ) ) {
862 return false;
865 static $reservedUsernames = false;
866 if ( !$reservedUsernames ) {
867 $reservedUsernames = $wgReservedUsernames;
868 Hooks::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
871 // Certain names may be reserved for batch processes.
872 foreach ( $reservedUsernames as $reserved ) {
873 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
874 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
876 if ( $reserved == $name ) {
877 return false;
880 return true;
884 * Return the users who are members of the given group(s). In case of multiple groups,
885 * users who are members of at least one of them are returned.
887 * @param string|array $groups A single group name or an array of group names
888 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
889 * records; larger values are ignored.
890 * @param int $after ID the user to start after
891 * @return UserArrayFromResult
893 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
894 if ( $groups === [] ) {
895 return UserArrayFromResult::newFromIDs( [] );
898 $groups = array_unique( (array)$groups );
899 $limit = min( 5000, $limit );
901 $conds = [ 'ug_group' => $groups ];
902 if ( $after !== null ) {
903 $conds[] = 'ug_user > ' . (int)$after;
906 $dbr = wfGetDB( DB_REPLICA );
907 $ids = $dbr->selectFieldValues(
908 'user_groups',
909 'ug_user',
910 $conds,
911 __METHOD__,
913 'DISTINCT' => true,
914 'ORDER BY' => 'ug_user',
915 'LIMIT' => $limit,
917 ) ?: [];
918 return UserArray::newFromIDs( $ids );
922 * Usernames which fail to pass this function will be blocked
923 * from new account registrations, but may be used internally
924 * either by batch processes or by user accounts which have
925 * already been created.
927 * Additional blacklisting may be added here rather than in
928 * isValidUserName() to avoid disrupting existing accounts.
930 * @param string $name String to match
931 * @return bool
933 public static function isCreatableName( $name ) {
934 global $wgInvalidUsernameCharacters;
936 // Ensure that the username isn't longer than 235 bytes, so that
937 // (at least for the builtin skins) user javascript and css files
938 // will work. (bug 23080)
939 if ( strlen( $name ) > 235 ) {
940 wfDebugLog( 'username', __METHOD__ .
941 ": '$name' invalid due to length" );
942 return false;
945 // Preg yells if you try to give it an empty string
946 if ( $wgInvalidUsernameCharacters !== '' ) {
947 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
948 wfDebugLog( 'username', __METHOD__ .
949 ": '$name' invalid due to wgInvalidUsernameCharacters" );
950 return false;
954 return self::isUsableName( $name );
958 * Is the input a valid password for this user?
960 * @param string $password Desired password
961 * @return bool
963 public function isValidPassword( $password ) {
964 // simple boolean wrapper for getPasswordValidity
965 return $this->getPasswordValidity( $password ) === true;
969 * Given unvalidated password input, return error message on failure.
971 * @param string $password Desired password
972 * @return bool|string|array True on success, string or array of error message on failure
974 public function getPasswordValidity( $password ) {
975 $result = $this->checkPasswordValidity( $password );
976 if ( $result->isGood() ) {
977 return true;
978 } else {
979 $messages = [];
980 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
981 $messages[] = $error['message'];
983 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
984 $messages[] = $warning['message'];
986 if ( count( $messages ) === 1 ) {
987 return $messages[0];
989 return $messages;
994 * Check if this is a valid password for this user
996 * Create a Status object based on the password's validity.
997 * The Status should be set to fatal if the user should not
998 * be allowed to log in, and should have any errors that
999 * would block changing the password.
1001 * If the return value of this is not OK, the password
1002 * should not be checked. If the return value is not Good,
1003 * the password can be checked, but the user should not be
1004 * able to set their password to this.
1006 * @param string $password Desired password
1007 * @return Status
1008 * @since 1.23
1010 public function checkPasswordValidity( $password ) {
1011 global $wgPasswordPolicy;
1013 $upp = new UserPasswordPolicy(
1014 $wgPasswordPolicy['policies'],
1015 $wgPasswordPolicy['checks']
1018 $status = Status::newGood();
1019 $result = false; // init $result to false for the internal checks
1021 if ( !Hooks::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1022 $status->error( $result );
1023 return $status;
1026 if ( $result === false ) {
1027 $status->merge( $upp->checkUserPassword( $this, $password ) );
1028 return $status;
1029 } elseif ( $result === true ) {
1030 return $status;
1031 } else {
1032 $status->error( $result );
1033 return $status; // the isValidPassword hook set a string $result and returned true
1038 * Given unvalidated user input, return a canonical username, or false if
1039 * the username is invalid.
1040 * @param string $name User input
1041 * @param string|bool $validate Type of validation to use:
1042 * - false No validation
1043 * - 'valid' Valid for batch processes
1044 * - 'usable' Valid for batch processes and login
1045 * - 'creatable' Valid for batch processes, login and account creation
1047 * @throws InvalidArgumentException
1048 * @return bool|string
1050 public static function getCanonicalName( $name, $validate = 'valid' ) {
1051 // Force usernames to capital
1052 global $wgContLang;
1053 $name = $wgContLang->ucfirst( $name );
1055 # Reject names containing '#'; these will be cleaned up
1056 # with title normalisation, but then it's too late to
1057 # check elsewhere
1058 if ( strpos( $name, '#' ) !== false ) {
1059 return false;
1062 // Clean up name according to title rules,
1063 // but only when validation is requested (bug 12654)
1064 $t = ( $validate !== false ) ?
1065 Title::newFromText( $name, NS_USER ) : Title::makeTitle( NS_USER, $name );
1066 // Check for invalid titles
1067 if ( is_null( $t ) || $t->getNamespace() !== NS_USER || $t->isExternal() ) {
1068 return false;
1071 // Reject various classes of invalid names
1072 $name = AuthManager::callLegacyAuthPlugin(
1073 'getCanonicalName', [ $t->getText() ], $t->getText()
1076 switch ( $validate ) {
1077 case false:
1078 break;
1079 case 'valid':
1080 if ( !User::isValidUserName( $name ) ) {
1081 $name = false;
1083 break;
1084 case 'usable':
1085 if ( !User::isUsableName( $name ) ) {
1086 $name = false;
1088 break;
1089 case 'creatable':
1090 if ( !User::isCreatableName( $name ) ) {
1091 $name = false;
1093 break;
1094 default:
1095 throw new InvalidArgumentException(
1096 'Invalid parameter value for $validate in ' . __METHOD__ );
1098 return $name;
1102 * Return a random password.
1104 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1105 * @return string New random password
1107 public static function randomPassword() {
1108 global $wgMinimalPasswordLength;
1109 return PasswordFactory::generateRandomPasswordString( $wgMinimalPasswordLength );
1113 * Set cached properties to default.
1115 * @note This no longer clears uncached lazy-initialised properties;
1116 * the constructor does that instead.
1118 * @param string|bool $name
1120 public function loadDefaults( $name = false ) {
1121 $this->mId = 0;
1122 $this->mName = $name;
1123 $this->mRealName = '';
1124 $this->mEmail = '';
1125 $this->mOptionOverrides = null;
1126 $this->mOptionsLoaded = false;
1128 $loggedOut = $this->mRequest && !defined( 'MW_NO_SESSION' )
1129 ? $this->mRequest->getSession()->getLoggedOutTimestamp() : 0;
1130 if ( $loggedOut !== 0 ) {
1131 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
1132 } else {
1133 $this->mTouched = '1'; # Allow any pages to be cached
1136 $this->mToken = null; // Don't run cryptographic functions till we need a token
1137 $this->mEmailAuthenticated = null;
1138 $this->mEmailToken = '';
1139 $this->mEmailTokenExpires = null;
1140 $this->mRegistration = wfTimestamp( TS_MW );
1141 $this->mGroups = [];
1143 Hooks::run( 'UserLoadDefaults', [ $this, $name ] );
1147 * Return whether an item has been loaded.
1149 * @param string $item Item to check. Current possibilities:
1150 * - id
1151 * - name
1152 * - realname
1153 * @param string $all 'all' to check if the whole object has been loaded
1154 * or any other string to check if only the item is available (e.g.
1155 * for optimisation)
1156 * @return bool
1158 public function isItemLoaded( $item, $all = 'all' ) {
1159 return ( $this->mLoadedItems === true && $all === 'all' ) ||
1160 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1164 * Set that an item has been loaded
1166 * @param string $item
1168 protected function setItemLoaded( $item ) {
1169 if ( is_array( $this->mLoadedItems ) ) {
1170 $this->mLoadedItems[$item] = true;
1175 * Load user data from the session.
1177 * @return bool True if the user is logged in, false otherwise.
1179 private function loadFromSession() {
1180 // Deprecated hook
1181 $result = null;
1182 Hooks::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1183 if ( $result !== null ) {
1184 return $result;
1187 // MediaWiki\Session\Session already did the necessary authentication of the user
1188 // returned here, so just use it if applicable.
1189 $session = $this->getRequest()->getSession();
1190 $user = $session->getUser();
1191 if ( $user->isLoggedIn() ) {
1192 $this->loadFromUserObject( $user );
1194 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1195 // every session load, because an autoblocked editor might not edit again from the same
1196 // IP address after being blocked.
1197 $config = RequestContext::getMain()->getConfig();
1198 if ( $config->get( 'CookieSetOnAutoblock' ) === true ) {
1199 $block = $this->getBlock();
1200 $shouldSetCookie = $this->getRequest()->getCookie( 'BlockID' ) === null
1201 && $block
1202 && $block->getType() === Block::TYPE_USER
1203 && $block->isAutoblocking();
1204 if ( $shouldSetCookie ) {
1205 wfDebug( __METHOD__ . ': User is autoblocked, setting cookie to track' );
1206 $block->setCookie( $this->getRequest()->response() );
1210 // Other code expects these to be set in the session, so set them.
1211 $session->set( 'wsUserID', $this->getId() );
1212 $session->set( 'wsUserName', $this->getName() );
1213 $session->set( 'wsToken', $this->getToken() );
1214 return true;
1216 return false;
1220 * Load user and user_group data from the database.
1221 * $this->mId must be set, this is how the user is identified.
1223 * @param integer $flags User::READ_* constant bitfield
1224 * @return bool True if the user exists, false if the user is anonymous
1226 public function loadFromDatabase( $flags = self::READ_LATEST ) {
1227 // Paranoia
1228 $this->mId = intval( $this->mId );
1230 if ( !$this->mId ) {
1231 // Anonymous users are not in the database
1232 $this->loadDefaults();
1233 return false;
1236 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
1237 $db = wfGetDB( $index );
1239 $s = $db->selectRow(
1240 'user',
1241 self::selectFields(),
1242 [ 'user_id' => $this->mId ],
1243 __METHOD__,
1244 $options
1247 $this->queryFlagsUsed = $flags;
1248 Hooks::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1250 if ( $s !== false ) {
1251 // Initialise user table data
1252 $this->loadFromRow( $s );
1253 $this->mGroups = null; // deferred
1254 $this->getEditCount(); // revalidation for nulls
1255 return true;
1256 } else {
1257 // Invalid user_id
1258 $this->mId = 0;
1259 $this->loadDefaults();
1260 return false;
1265 * Initialize this object from a row from the user table.
1267 * @param stdClass $row Row from the user table to load.
1268 * @param array $data Further user data to load into the object
1270 * user_groups Array with groups out of the user_groups table
1271 * user_properties Array with properties out of the user_properties table
1273 protected function loadFromRow( $row, $data = null ) {
1274 $all = true;
1276 $this->mGroups = null; // deferred
1278 if ( isset( $row->user_name ) ) {
1279 $this->mName = $row->user_name;
1280 $this->mFrom = 'name';
1281 $this->setItemLoaded( 'name' );
1282 } else {
1283 $all = false;
1286 if ( isset( $row->user_real_name ) ) {
1287 $this->mRealName = $row->user_real_name;
1288 $this->setItemLoaded( 'realname' );
1289 } else {
1290 $all = false;
1293 if ( isset( $row->user_id ) ) {
1294 $this->mId = intval( $row->user_id );
1295 $this->mFrom = 'id';
1296 $this->setItemLoaded( 'id' );
1297 } else {
1298 $all = false;
1301 if ( isset( $row->user_id ) && isset( $row->user_name ) ) {
1302 self::$idCacheByName[$row->user_name] = $row->user_id;
1305 if ( isset( $row->user_editcount ) ) {
1306 $this->mEditCount = $row->user_editcount;
1307 } else {
1308 $all = false;
1311 if ( isset( $row->user_touched ) ) {
1312 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1313 } else {
1314 $all = false;
1317 if ( isset( $row->user_token ) ) {
1318 // The definition for the column is binary(32), so trim the NULs
1319 // that appends. The previous definition was char(32), so trim
1320 // spaces too.
1321 $this->mToken = rtrim( $row->user_token, " \0" );
1322 if ( $this->mToken === '' ) {
1323 $this->mToken = null;
1325 } else {
1326 $all = false;
1329 if ( isset( $row->user_email ) ) {
1330 $this->mEmail = $row->user_email;
1331 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1332 $this->mEmailToken = $row->user_email_token;
1333 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1334 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1335 } else {
1336 $all = false;
1339 if ( $all ) {
1340 $this->mLoadedItems = true;
1343 if ( is_array( $data ) ) {
1344 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1345 $this->mGroups = $data['user_groups'];
1347 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1348 $this->loadOptions( $data['user_properties'] );
1354 * Load the data for this user object from another user object.
1356 * @param User $user
1358 protected function loadFromUserObject( $user ) {
1359 $user->load();
1360 foreach ( self::$mCacheVars as $var ) {
1361 $this->$var = $user->$var;
1366 * Load the groups from the database if they aren't already loaded.
1368 private function loadGroups() {
1369 if ( is_null( $this->mGroups ) ) {
1370 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
1371 ? wfGetDB( DB_MASTER )
1372 : wfGetDB( DB_REPLICA );
1373 $res = $db->select( 'user_groups',
1374 [ 'ug_group' ],
1375 [ 'ug_user' => $this->mId ],
1376 __METHOD__ );
1377 $this->mGroups = [];
1378 foreach ( $res as $row ) {
1379 $this->mGroups[] = $row->ug_group;
1385 * Add the user to the group if he/she meets given criteria.
1387 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1388 * possible to remove manually via Special:UserRights. In such case it
1389 * will not be re-added automatically. The user will also not lose the
1390 * group if they no longer meet the criteria.
1392 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1394 * @return array Array of groups the user has been promoted to.
1396 * @see $wgAutopromoteOnce
1398 public function addAutopromoteOnceGroups( $event ) {
1399 global $wgAutopromoteOnceLogInRC;
1401 if ( wfReadOnly() || !$this->getId() ) {
1402 return [];
1405 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1406 if ( !count( $toPromote ) ) {
1407 return [];
1410 if ( !$this->checkAndSetTouched() ) {
1411 return []; // raced out (bug T48834)
1414 $oldGroups = $this->getGroups(); // previous groups
1415 foreach ( $toPromote as $group ) {
1416 $this->addGroup( $group );
1418 // update groups in external authentication database
1419 Hooks::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1420 AuthManager::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1422 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1424 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1425 $logEntry->setPerformer( $this );
1426 $logEntry->setTarget( $this->getUserPage() );
1427 $logEntry->setParameters( [
1428 '4::oldgroups' => $oldGroups,
1429 '5::newgroups' => $newGroups,
1430 ] );
1431 $logid = $logEntry->insert();
1432 if ( $wgAutopromoteOnceLogInRC ) {
1433 $logEntry->publish( $logid );
1436 return $toPromote;
1440 * Builds update conditions. Additional conditions may be added to $conditions to
1441 * protected against race conditions using a compare-and-set (CAS) mechanism
1442 * based on comparing $this->mTouched with the user_touched field.
1444 * @param Database $db
1445 * @param array $conditions WHERE conditions for use with Database::update
1446 * @return array WHERE conditions for use with Database::update
1448 protected function makeUpdateConditions( Database $db, array $conditions ) {
1449 if ( $this->mTouched ) {
1450 // CAS check: only update if the row wasn't changed sicne it was loaded.
1451 $conditions['user_touched'] = $db->timestamp( $this->mTouched );
1454 return $conditions;
1458 * Bump user_touched if it didn't change since this object was loaded
1460 * On success, the mTouched field is updated.
1461 * The user serialization cache is always cleared.
1463 * @return bool Whether user_touched was actually updated
1464 * @since 1.26
1466 protected function checkAndSetTouched() {
1467 $this->load();
1469 if ( !$this->mId ) {
1470 return false; // anon
1473 // Get a new user_touched that is higher than the old one
1474 $newTouched = $this->newTouchedTimestamp();
1476 $dbw = wfGetDB( DB_MASTER );
1477 $dbw->update( 'user',
1478 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1479 $this->makeUpdateConditions( $dbw, [
1480 'user_id' => $this->mId,
1481 ] ),
1482 __METHOD__
1484 $success = ( $dbw->affectedRows() > 0 );
1486 if ( $success ) {
1487 $this->mTouched = $newTouched;
1488 $this->clearSharedCache();
1489 } else {
1490 // Clears on failure too since that is desired if the cache is stale
1491 $this->clearSharedCache( 'refresh' );
1494 return $success;
1498 * Clear various cached data stored in this object. The cache of the user table
1499 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1501 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1502 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1504 public function clearInstanceCache( $reloadFrom = false ) {
1505 $this->mNewtalk = -1;
1506 $this->mDatePreference = null;
1507 $this->mBlockedby = -1; # Unset
1508 $this->mHash = false;
1509 $this->mRights = null;
1510 $this->mEffectiveGroups = null;
1511 $this->mImplicitGroups = null;
1512 $this->mGroups = null;
1513 $this->mOptions = null;
1514 $this->mOptionsLoaded = false;
1515 $this->mEditCount = null;
1517 if ( $reloadFrom ) {
1518 $this->mLoadedItems = [];
1519 $this->mFrom = $reloadFrom;
1524 * Combine the language default options with any site-specific options
1525 * and add the default language variants.
1527 * @return array Array of String options
1529 public static function getDefaultOptions() {
1530 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1532 static $defOpt = null;
1533 static $defOptLang = null;
1535 if ( $defOpt !== null && $defOptLang === $wgContLang->getCode() ) {
1536 // $wgContLang does not change (and should not change) mid-request,
1537 // but the unit tests change it anyway, and expect this method to
1538 // return values relevant to the current $wgContLang.
1539 return $defOpt;
1542 $defOpt = $wgDefaultUserOptions;
1543 // Default language setting
1544 $defOptLang = $wgContLang->getCode();
1545 $defOpt['language'] = $defOptLang;
1546 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1547 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1550 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1551 // since extensions may change the set of searchable namespaces depending
1552 // on user groups/permissions.
1553 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1554 $defOpt['searchNs' . $nsnum] = (boolean)$val;
1556 $defOpt['skin'] = Skin::normalizeKey( $wgDefaultSkin );
1558 Hooks::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1560 return $defOpt;
1564 * Get a given default option value.
1566 * @param string $opt Name of option to retrieve
1567 * @return string Default option value
1569 public static function getDefaultOption( $opt ) {
1570 $defOpts = self::getDefaultOptions();
1571 if ( isset( $defOpts[$opt] ) ) {
1572 return $defOpts[$opt];
1573 } else {
1574 return null;
1579 * Get blocking information
1580 * @param bool $bFromSlave Whether to check the replica DB first.
1581 * To improve performance, non-critical checks are done against replica DBs.
1582 * Check when actually saving should be done against master.
1584 private function getBlockedStatus( $bFromSlave = true ) {
1585 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff, $wgSoftBlockRanges;
1587 if ( -1 != $this->mBlockedby ) {
1588 return;
1591 wfDebug( __METHOD__ . ": checking...\n" );
1593 // Initialize data...
1594 // Otherwise something ends up stomping on $this->mBlockedby when
1595 // things get lazy-loaded later, causing false positive block hits
1596 // due to -1 !== 0. Probably session-related... Nothing should be
1597 // overwriting mBlockedby, surely?
1598 $this->load();
1600 # We only need to worry about passing the IP address to the Block generator if the
1601 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1602 # know which IP address they're actually coming from
1603 $ip = null;
1604 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1605 // $wgUser->getName() only works after the end of Setup.php. Until
1606 // then, assume it's a logged-out user.
1607 $globalUserName = $wgUser->isSafeToLoad()
1608 ? $wgUser->getName()
1609 : IP::sanitizeIP( $wgUser->getRequest()->getIP() );
1610 if ( $this->getName() === $globalUserName ) {
1611 $ip = $this->getRequest()->getIP();
1615 // User/IP blocking
1616 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1618 // If no block has been found, check for a cookie indicating that the user is blocked.
1619 $blockCookieVal = (int)$this->getRequest()->getCookie( 'BlockID' );
1620 if ( !$block instanceof Block && $blockCookieVal > 0 ) {
1621 // Load the Block from the ID in the cookie.
1622 $tmpBlock = Block::newFromID( $blockCookieVal );
1623 if ( $tmpBlock instanceof Block ) {
1624 // Check the validity of the block.
1625 $blockIsValid = $tmpBlock->getType() == Block::TYPE_USER
1626 && !$tmpBlock->isExpired()
1627 && $tmpBlock->isAutoblocking();
1628 $config = RequestContext::getMain()->getConfig();
1629 $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true );
1630 if ( $blockIsValid && $useBlockCookie ) {
1631 // Use the block.
1632 $block = $tmpBlock;
1633 $this->blockTrigger = 'cookie-block';
1634 } else {
1635 // If the block is not valid, clear the block cookie (but don't delete it,
1636 // because it needs to be cleared from LocalStorage as well and an empty string
1637 // value is checked for in the mediawiki.user.blockcookie module).
1638 $tmpBlock->setCookie( $this->getRequest()->response(), true );
1643 // Proxy blocking
1644 if ( !$block instanceof Block && $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1645 // Local list
1646 if ( self::isLocallyBlockedProxy( $ip ) ) {
1647 $block = new Block( [
1648 'byText' => wfMessage( 'proxyblocker' )->text(),
1649 'reason' => wfMessage( 'proxyblockreason' )->text(),
1650 'address' => $ip,
1651 'systemBlock' => 'proxy',
1652 ] );
1653 $this->blockTrigger = 'proxy-block';
1654 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1655 $block = new Block( [
1656 'byText' => wfMessage( 'sorbs' )->text(),
1657 'reason' => wfMessage( 'sorbsreason' )->text(),
1658 'address' => $ip,
1659 'systemBlock' => 'dnsbl',
1660 ] );
1661 $this->blockTrigger = 'openproxy-block';
1665 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1666 if ( !$block instanceof Block
1667 && $wgApplyIpBlocksToXff
1668 && $ip !== null
1669 && !in_array( $ip, $wgProxyWhitelist )
1671 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1672 $xff = array_map( 'trim', explode( ',', $xff ) );
1673 $xff = array_diff( $xff, [ $ip ] );
1674 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1675 $block = Block::chooseBlock( $xffblocks, $xff );
1676 if ( $block instanceof Block ) {
1677 # Mangle the reason to alert the user that the block
1678 # originated from matching the X-Forwarded-For header.
1679 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1680 $this->blockTrigger = 'xff-block';
1684 if ( !$block instanceof Block
1685 && $ip !== null
1686 && $this->isAnon()
1687 && IP::isInRanges( $ip, $wgSoftBlockRanges )
1689 $block = new Block( [
1690 'address' => $ip,
1691 'byText' => 'MediaWiki default',
1692 'reason' => wfMessage( 'softblockrangesreason', $ip )->text(),
1693 'anonOnly' => true,
1694 'systemBlock' => 'wgSoftBlockRanges',
1695 ] );
1696 $this->blockTrigger = 'config-block';
1699 if ( $block instanceof Block ) {
1700 wfDebug( __METHOD__ . ": Found block.\n" );
1701 $this->mBlock = $block;
1702 $this->mBlockedby = $block->getByName();
1703 $this->mBlockreason = $block->mReason;
1704 $this->mHideName = $block->mHideName;
1705 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1706 } else {
1707 $this->mBlockedby = '';
1708 $this->mHideName = 0;
1709 $this->mAllowUsertalk = false;
1710 $this->blockTrigger = false;
1713 // Avoid PHP 7.1 warning of passing $this by reference
1714 $user = $this;
1715 // Extensions
1716 Hooks::run( 'GetBlockedStatus', [ &$user ] );
1720 * Whether the given IP is in a DNS blacklist.
1722 * @param string $ip IP to check
1723 * @param bool $checkWhitelist Whether to check the whitelist first
1724 * @return bool True if blacklisted.
1726 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1727 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1729 if ( !$wgEnableDnsBlacklist ) {
1730 return false;
1733 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1734 return false;
1737 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1741 * Whether the given IP is in a given DNS blacklist.
1743 * @param string $ip IP to check
1744 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1745 * @return bool True if blacklisted.
1747 public function inDnsBlacklist( $ip, $bases ) {
1748 $found = false;
1749 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1750 if ( IP::isIPv4( $ip ) ) {
1751 // Reverse IP, bug 21255
1752 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1754 foreach ( (array)$bases as $base ) {
1755 // Make hostname
1756 // If we have an access key, use that too (ProjectHoneypot, etc.)
1757 $basename = $base;
1758 if ( is_array( $base ) ) {
1759 if ( count( $base ) >= 2 ) {
1760 // Access key is 1, base URL is 0
1761 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1762 } else {
1763 $host = "$ipReversed.{$base[0]}";
1765 $basename = $base[0];
1766 } else {
1767 $host = "$ipReversed.$base";
1770 // Send query
1771 $ipList = gethostbynamel( $host );
1773 if ( $ipList ) {
1774 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1775 $found = true;
1776 break;
1777 } else {
1778 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1783 return $found;
1787 * Check if an IP address is in the local proxy list
1789 * @param string $ip
1791 * @return bool
1793 public static function isLocallyBlockedProxy( $ip ) {
1794 global $wgProxyList;
1796 if ( !$wgProxyList ) {
1797 return false;
1800 if ( !is_array( $wgProxyList ) ) {
1801 // Load values from the specified file
1802 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1805 if ( is_array( $wgProxyList ) ) {
1806 if (
1807 // Look for IP as value
1808 array_search( $ip, $wgProxyList ) !== false ||
1809 // Look for IP as key (for backwards-compatility)
1810 array_key_exists( $ip, $wgProxyList )
1812 return true;
1816 return false;
1820 * Is this user subject to rate limiting?
1822 * @return bool True if rate limited
1824 public function isPingLimitable() {
1825 global $wgRateLimitsExcludedIPs;
1826 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1827 // No other good way currently to disable rate limits
1828 // for specific IPs. :P
1829 // But this is a crappy hack and should die.
1830 return false;
1832 return !$this->isAllowed( 'noratelimit' );
1836 * Primitive rate limits: enforce maximum actions per time period
1837 * to put a brake on flooding.
1839 * The method generates both a generic profiling point and a per action one
1840 * (suffix being "-$action".
1842 * @note When using a shared cache like memcached, IP-address
1843 * last-hit counters will be shared across wikis.
1845 * @param string $action Action to enforce; 'edit' if unspecified
1846 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1847 * @return bool True if a rate limiter was tripped
1849 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1850 // Avoid PHP 7.1 warning of passing $this by reference
1851 $user = $this;
1852 // Call the 'PingLimiter' hook
1853 $result = false;
1854 if ( !Hooks::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
1855 return $result;
1858 global $wgRateLimits;
1859 if ( !isset( $wgRateLimits[$action] ) ) {
1860 return false;
1863 $limits = array_merge(
1864 [ '&can-bypass' => true ],
1865 $wgRateLimits[$action]
1868 // Some groups shouldn't trigger the ping limiter, ever
1869 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1870 return false;
1873 $keys = [];
1874 $id = $this->getId();
1875 $userLimit = false;
1876 $isNewbie = $this->isNewbie();
1878 if ( $id == 0 ) {
1879 // limits for anons
1880 if ( isset( $limits['anon'] ) ) {
1881 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1883 } else {
1884 // limits for logged-in users
1885 if ( isset( $limits['user'] ) ) {
1886 $userLimit = $limits['user'];
1888 // limits for newbie logged-in users
1889 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1890 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1894 // limits for anons and for newbie logged-in users
1895 if ( $isNewbie ) {
1896 // ip-based limits
1897 if ( isset( $limits['ip'] ) ) {
1898 $ip = $this->getRequest()->getIP();
1899 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1901 // subnet-based limits
1902 if ( isset( $limits['subnet'] ) ) {
1903 $ip = $this->getRequest()->getIP();
1904 $subnet = IP::getSubnet( $ip );
1905 if ( $subnet !== false ) {
1906 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1911 // Check for group-specific permissions
1912 // If more than one group applies, use the group with the highest limit ratio (max/period)
1913 foreach ( $this->getGroups() as $group ) {
1914 if ( isset( $limits[$group] ) ) {
1915 if ( $userLimit === false
1916 || $limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1918 $userLimit = $limits[$group];
1923 // Set the user limit key
1924 if ( $userLimit !== false ) {
1925 list( $max, $period ) = $userLimit;
1926 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1927 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1930 // ip-based limits for all ping-limitable users
1931 if ( isset( $limits['ip-all'] ) ) {
1932 $ip = $this->getRequest()->getIP();
1933 // ignore if user limit is more permissive
1934 if ( $isNewbie || $userLimit === false
1935 || $limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1936 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1940 // subnet-based limits for all ping-limitable users
1941 if ( isset( $limits['subnet-all'] ) ) {
1942 $ip = $this->getRequest()->getIP();
1943 $subnet = IP::getSubnet( $ip );
1944 if ( $subnet !== false ) {
1945 // ignore if user limit is more permissive
1946 if ( $isNewbie || $userLimit === false
1947 || $limits['ip-all'][0] / $limits['ip-all'][1]
1948 > $userLimit[0] / $userLimit[1] ) {
1949 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1954 $cache = ObjectCache::getLocalClusterInstance();
1956 $triggered = false;
1957 foreach ( $keys as $key => $limit ) {
1958 list( $max, $period ) = $limit;
1959 $summary = "(limit $max in {$period}s)";
1960 $count = $cache->get( $key );
1961 // Already pinged?
1962 if ( $count ) {
1963 if ( $count >= $max ) {
1964 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1965 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1966 $triggered = true;
1967 } else {
1968 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1970 } else {
1971 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1972 if ( $incrBy > 0 ) {
1973 $cache->add( $key, 0, intval( $period ) ); // first ping
1976 if ( $incrBy > 0 ) {
1977 $cache->incr( $key, $incrBy );
1981 return $triggered;
1985 * Check if user is blocked
1987 * @param bool $bFromSlave Whether to check the replica DB instead of
1988 * the master. Hacked from false due to horrible probs on site.
1989 * @return bool True if blocked, false otherwise
1991 public function isBlocked( $bFromSlave = true ) {
1992 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1996 * Get the block affecting the user, or null if the user is not blocked
1998 * @param bool $bFromSlave Whether to check the replica DB instead of the master
1999 * @return Block|null
2001 public function getBlock( $bFromSlave = true ) {
2002 $this->getBlockedStatus( $bFromSlave );
2003 return $this->mBlock instanceof Block ? $this->mBlock : null;
2007 * Check if user is blocked from editing a particular article
2009 * @param Title $title Title to check
2010 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2011 * @return bool
2013 public function isBlockedFrom( $title, $bFromSlave = false ) {
2014 global $wgBlockAllowsUTEdit;
2016 $blocked = $this->isBlocked( $bFromSlave );
2017 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
2018 // If a user's name is suppressed, they cannot make edits anywhere
2019 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
2020 && $title->getNamespace() == NS_USER_TALK ) {
2021 $blocked = false;
2022 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
2025 Hooks::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2027 return $blocked;
2031 * If user is blocked, return the name of the user who placed the block
2032 * @return string Name of blocker
2034 public function blockedBy() {
2035 $this->getBlockedStatus();
2036 return $this->mBlockedby;
2040 * If user is blocked, return the specified reason for the block
2041 * @return string Blocking reason
2043 public function blockedFor() {
2044 $this->getBlockedStatus();
2045 return $this->mBlockreason;
2049 * If user is blocked, return the ID for the block
2050 * @return int Block ID
2052 public function getBlockId() {
2053 $this->getBlockedStatus();
2054 return ( $this->mBlock ? $this->mBlock->getId() : false );
2058 * Check if user is blocked on all wikis.
2059 * Do not use for actual edit permission checks!
2060 * This is intended for quick UI checks.
2062 * @param string $ip IP address, uses current client if none given
2063 * @return bool True if blocked, false otherwise
2065 public function isBlockedGlobally( $ip = '' ) {
2066 return $this->getGlobalBlock( $ip ) instanceof Block;
2070 * Check if user is blocked on all wikis.
2071 * Do not use for actual edit permission checks!
2072 * This is intended for quick UI checks.
2074 * @param string $ip IP address, uses current client if none given
2075 * @return Block|null Block object if blocked, null otherwise
2076 * @throws FatalError
2077 * @throws MWException
2079 public function getGlobalBlock( $ip = '' ) {
2080 if ( $this->mGlobalBlock !== null ) {
2081 return $this->mGlobalBlock ?: null;
2083 // User is already an IP?
2084 if ( IP::isIPAddress( $this->getName() ) ) {
2085 $ip = $this->getName();
2086 } elseif ( !$ip ) {
2087 $ip = $this->getRequest()->getIP();
2089 // Avoid PHP 7.1 warning of passing $this by reference
2090 $user = $this;
2091 $blocked = false;
2092 $block = null;
2093 Hooks::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2095 if ( $blocked && $block === null ) {
2096 // back-compat: UserIsBlockedGlobally didn't have $block param first
2097 $block = new Block( [
2098 'address' => $ip,
2099 'systemBlock' => 'global-block'
2100 ] );
2103 $this->mGlobalBlock = $blocked ? $block : false;
2104 return $this->mGlobalBlock ?: null;
2108 * Check if user account is locked
2110 * @return bool True if locked, false otherwise
2112 public function isLocked() {
2113 if ( $this->mLocked !== null ) {
2114 return $this->mLocked;
2116 // Avoid PHP 7.1 warning of passing $this by reference
2117 $user = $this;
2118 $authUser = AuthManager::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2119 $this->mLocked = $authUser && $authUser->isLocked();
2120 Hooks::run( 'UserIsLocked', [ $this, &$this->mLocked ] );
2121 return $this->mLocked;
2125 * Check if user account is hidden
2127 * @return bool True if hidden, false otherwise
2129 public function isHidden() {
2130 if ( $this->mHideName !== null ) {
2131 return $this->mHideName;
2133 $this->getBlockedStatus();
2134 if ( !$this->mHideName ) {
2135 // Avoid PHP 7.1 warning of passing $this by reference
2136 $user = $this;
2137 $authUser = AuthManager::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2138 $this->mHideName = $authUser && $authUser->isHidden();
2139 Hooks::run( 'UserIsHidden', [ $this, &$this->mHideName ] );
2141 return $this->mHideName;
2145 * Get the user's ID.
2146 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2148 public function getId() {
2149 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
2150 // Special case, we know the user is anonymous
2151 return 0;
2152 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2153 // Don't load if this was initialized from an ID
2154 $this->load();
2157 return (int)$this->mId;
2161 * Set the user and reload all fields according to a given ID
2162 * @param int $v User ID to reload
2164 public function setId( $v ) {
2165 $this->mId = $v;
2166 $this->clearInstanceCache( 'id' );
2170 * Get the user name, or the IP of an anonymous user
2171 * @return string User's name or IP address
2173 public function getName() {
2174 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2175 // Special case optimisation
2176 return $this->mName;
2177 } else {
2178 $this->load();
2179 if ( $this->mName === false ) {
2180 // Clean up IPs
2181 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
2183 return $this->mName;
2188 * Set the user name.
2190 * This does not reload fields from the database according to the given
2191 * name. Rather, it is used to create a temporary "nonexistent user" for
2192 * later addition to the database. It can also be used to set the IP
2193 * address for an anonymous user to something other than the current
2194 * remote IP.
2196 * @note User::newFromName() has roughly the same function, when the named user
2197 * does not exist.
2198 * @param string $str New user name to set
2200 public function setName( $str ) {
2201 $this->load();
2202 $this->mName = $str;
2206 * Get the user's name escaped by underscores.
2207 * @return string Username escaped by underscores.
2209 public function getTitleKey() {
2210 return str_replace( ' ', '_', $this->getName() );
2214 * Check if the user has new messages.
2215 * @return bool True if the user has new messages
2217 public function getNewtalk() {
2218 $this->load();
2220 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2221 if ( $this->mNewtalk === -1 ) {
2222 $this->mNewtalk = false; # reset talk page status
2224 // Check memcached separately for anons, who have no
2225 // entire User object stored in there.
2226 if ( !$this->mId ) {
2227 global $wgDisableAnonTalk;
2228 if ( $wgDisableAnonTalk ) {
2229 // Anon newtalk disabled by configuration.
2230 $this->mNewtalk = false;
2231 } else {
2232 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName() );
2234 } else {
2235 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
2239 return (bool)$this->mNewtalk;
2243 * Return the data needed to construct links for new talk page message
2244 * alerts. If there are new messages, this will return an associative array
2245 * with the following data:
2246 * wiki: The database name of the wiki
2247 * link: Root-relative link to the user's talk page
2248 * rev: The last talk page revision that the user has seen or null. This
2249 * is useful for building diff links.
2250 * If there are no new messages, it returns an empty array.
2251 * @note This function was designed to accomodate multiple talk pages, but
2252 * currently only returns a single link and revision.
2253 * @return array
2255 public function getNewMessageLinks() {
2256 // Avoid PHP 7.1 warning of passing $this by reference
2257 $user = $this;
2258 $talks = [];
2259 if ( !Hooks::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2260 return $talks;
2261 } elseif ( !$this->getNewtalk() ) {
2262 return [];
2264 $utp = $this->getTalkPage();
2265 $dbr = wfGetDB( DB_REPLICA );
2266 // Get the "last viewed rev" timestamp from the oldest message notification
2267 $timestamp = $dbr->selectField( 'user_newtalk',
2268 'MIN(user_last_timestamp)',
2269 $this->isAnon() ? [ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2270 __METHOD__ );
2271 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2272 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2276 * Get the revision ID for the last talk page revision viewed by the talk
2277 * page owner.
2278 * @return int|null Revision ID or null
2280 public function getNewMessageRevisionId() {
2281 $newMessageRevisionId = null;
2282 $newMessageLinks = $this->getNewMessageLinks();
2283 if ( $newMessageLinks ) {
2284 // Note: getNewMessageLinks() never returns more than a single link
2285 // and it is always for the same wiki, but we double-check here in
2286 // case that changes some time in the future.
2287 if ( count( $newMessageLinks ) === 1
2288 && $newMessageLinks[0]['wiki'] === wfWikiID()
2289 && $newMessageLinks[0]['rev']
2291 /** @var Revision $newMessageRevision */
2292 $newMessageRevision = $newMessageLinks[0]['rev'];
2293 $newMessageRevisionId = $newMessageRevision->getId();
2296 return $newMessageRevisionId;
2300 * Internal uncached check for new messages
2302 * @see getNewtalk()
2303 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2304 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2305 * @return bool True if the user has new messages
2307 protected function checkNewtalk( $field, $id ) {
2308 $dbr = wfGetDB( DB_REPLICA );
2310 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__ );
2312 return $ok !== false;
2316 * Add or update the new messages flag
2317 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2318 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2319 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2320 * @return bool True if successful, false otherwise
2322 protected function updateNewtalk( $field, $id, $curRev = null ) {
2323 // Get timestamp of the talk page revision prior to the current one
2324 $prevRev = $curRev ? $curRev->getPrevious() : false;
2325 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2326 // Mark the user as having new messages since this revision
2327 $dbw = wfGetDB( DB_MASTER );
2328 $dbw->insert( 'user_newtalk',
2329 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2330 __METHOD__,
2331 'IGNORE' );
2332 if ( $dbw->affectedRows() ) {
2333 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2334 return true;
2335 } else {
2336 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2337 return false;
2342 * Clear the new messages flag for the given user
2343 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2344 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2345 * @return bool True if successful, false otherwise
2347 protected function deleteNewtalk( $field, $id ) {
2348 $dbw = wfGetDB( DB_MASTER );
2349 $dbw->delete( 'user_newtalk',
2350 [ $field => $id ],
2351 __METHOD__ );
2352 if ( $dbw->affectedRows() ) {
2353 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2354 return true;
2355 } else {
2356 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2357 return false;
2362 * Update the 'You have new messages!' status.
2363 * @param bool $val Whether the user has new messages
2364 * @param Revision $curRev New, as yet unseen revision of the user talk
2365 * page. Ignored if null or !$val.
2367 public function setNewtalk( $val, $curRev = null ) {
2368 if ( wfReadOnly() ) {
2369 return;
2372 $this->load();
2373 $this->mNewtalk = $val;
2375 if ( $this->isAnon() ) {
2376 $field = 'user_ip';
2377 $id = $this->getName();
2378 } else {
2379 $field = 'user_id';
2380 $id = $this->getId();
2383 if ( $val ) {
2384 $changed = $this->updateNewtalk( $field, $id, $curRev );
2385 } else {
2386 $changed = $this->deleteNewtalk( $field, $id );
2389 if ( $changed ) {
2390 $this->invalidateCache();
2395 * Generate a current or new-future timestamp to be stored in the
2396 * user_touched field when we update things.
2397 * @return string Timestamp in TS_MW format
2399 private function newTouchedTimestamp() {
2400 global $wgClockSkewFudge;
2402 $time = wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2403 if ( $this->mTouched && $time <= $this->mTouched ) {
2404 $time = wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $this->mTouched ) + 1 );
2407 return $time;
2411 * Clear user data from memcached
2413 * Use after applying updates to the database; caller's
2414 * responsibility to update user_touched if appropriate.
2416 * Called implicitly from invalidateCache() and saveSettings().
2418 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2420 public function clearSharedCache( $mode = 'changed' ) {
2421 if ( !$this->getId() ) {
2422 return;
2425 $cache = ObjectCache::getMainWANInstance();
2426 $key = $this->getCacheKey( $cache );
2427 if ( $mode === 'refresh' ) {
2428 $cache->delete( $key, 1 );
2429 } else {
2430 wfGetDB( DB_MASTER )->onTransactionPreCommitOrIdle(
2431 function() use ( $cache, $key ) {
2432 $cache->delete( $key );
2434 __METHOD__
2440 * Immediately touch the user data cache for this account
2442 * Calls touch() and removes account data from memcached
2444 public function invalidateCache() {
2445 $this->touch();
2446 $this->clearSharedCache();
2450 * Update the "touched" timestamp for the user
2452 * This is useful on various login/logout events when making sure that
2453 * a browser or proxy that has multiple tenants does not suffer cache
2454 * pollution where the new user sees the old users content. The value
2455 * of getTouched() is checked when determining 304 vs 200 responses.
2456 * Unlike invalidateCache(), this preserves the User object cache and
2457 * avoids database writes.
2459 * @since 1.25
2461 public function touch() {
2462 $id = $this->getId();
2463 if ( $id ) {
2464 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2465 ObjectCache::getMainWANInstance()->touchCheckKey( $key );
2466 $this->mQuickTouched = null;
2471 * Validate the cache for this account.
2472 * @param string $timestamp A timestamp in TS_MW format
2473 * @return bool
2475 public function validateCache( $timestamp ) {
2476 return ( $timestamp >= $this->getTouched() );
2480 * Get the user touched timestamp
2482 * Use this value only to validate caches via inequalities
2483 * such as in the case of HTTP If-Modified-Since response logic
2485 * @return string TS_MW Timestamp
2487 public function getTouched() {
2488 $this->load();
2490 if ( $this->mId ) {
2491 if ( $this->mQuickTouched === null ) {
2492 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId );
2493 $cache = ObjectCache::getMainWANInstance();
2495 $this->mQuickTouched = wfTimestamp( TS_MW, $cache->getCheckKeyTime( $key ) );
2498 return max( $this->mTouched, $this->mQuickTouched );
2501 return $this->mTouched;
2505 * Get the user_touched timestamp field (time of last DB updates)
2506 * @return string TS_MW Timestamp
2507 * @since 1.26
2509 public function getDBTouched() {
2510 $this->load();
2512 return $this->mTouched;
2516 * Set the password and reset the random token.
2517 * Calls through to authentication plugin if necessary;
2518 * will have no effect if the auth plugin refuses to
2519 * pass the change through or if the legal password
2520 * checks fail.
2522 * As a special case, setting the password to null
2523 * wipes it, so the account cannot be logged in until
2524 * a new password is set, for instance via e-mail.
2526 * @deprecated since 1.27, use AuthManager instead
2527 * @param string $str New password to set
2528 * @throws PasswordError On failure
2529 * @return bool
2531 public function setPassword( $str ) {
2532 return $this->setPasswordInternal( $str );
2536 * Set the password and reset the random token unconditionally.
2538 * @deprecated since 1.27, use AuthManager instead
2539 * @param string|null $str New password to set or null to set an invalid
2540 * password hash meaning that the user will not be able to log in
2541 * through the web interface.
2543 public function setInternalPassword( $str ) {
2544 $this->setPasswordInternal( $str );
2548 * Actually set the password and such
2549 * @since 1.27 cannot set a password for a user not in the database
2550 * @param string|null $str New password to set or null to set an invalid
2551 * password hash meaning that the user will not be able to log in
2552 * through the web interface.
2553 * @return bool Success
2555 private function setPasswordInternal( $str ) {
2556 $manager = AuthManager::singleton();
2558 // If the user doesn't exist yet, fail
2559 if ( !$manager->userExists( $this->getName() ) ) {
2560 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2563 $status = $this->changeAuthenticationData( [
2564 'username' => $this->getName(),
2565 'password' => $str,
2566 'retype' => $str,
2567 ] );
2568 if ( !$status->isGood() ) {
2569 \MediaWiki\Logger\LoggerFactory::getInstance( 'authentication' )
2570 ->info( __METHOD__ . ': Password change rejected: '
2571 . $status->getWikiText( null, null, 'en' ) );
2572 return false;
2575 $this->setOption( 'watchlisttoken', false );
2576 SessionManager::singleton()->invalidateSessionsForUser( $this );
2578 return true;
2582 * Changes credentials of the user.
2584 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2585 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2586 * e.g. when no provider handled the change.
2588 * @param array $data A set of authentication data in fieldname => value format. This is the
2589 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2590 * @return Status
2591 * @since 1.27
2593 public function changeAuthenticationData( array $data ) {
2594 $manager = AuthManager::singleton();
2595 $reqs = $manager->getAuthenticationRequests( AuthManager::ACTION_CHANGE, $this );
2596 $reqs = AuthenticationRequest::loadRequestsFromSubmission( $reqs, $data );
2598 $status = Status::newGood( 'ignored' );
2599 foreach ( $reqs as $req ) {
2600 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2602 if ( $status->getValue() === 'ignored' ) {
2603 $status->warning( 'authenticationdatachange-ignored' );
2606 if ( $status->isGood() ) {
2607 foreach ( $reqs as $req ) {
2608 $manager->changeAuthenticationData( $req );
2611 return $status;
2615 * Get the user's current token.
2616 * @param bool $forceCreation Force the generation of a new token if the
2617 * user doesn't have one (default=true for backwards compatibility).
2618 * @return string|null Token
2620 public function getToken( $forceCreation = true ) {
2621 global $wgAuthenticationTokenVersion;
2623 $this->load();
2624 if ( !$this->mToken && $forceCreation ) {
2625 $this->setToken();
2628 if ( !$this->mToken ) {
2629 // The user doesn't have a token, return null to indicate that.
2630 return null;
2631 } elseif ( $this->mToken === self::INVALID_TOKEN ) {
2632 // We return a random value here so existing token checks are very
2633 // likely to fail.
2634 return MWCryptRand::generateHex( self::TOKEN_LENGTH );
2635 } elseif ( $wgAuthenticationTokenVersion === null ) {
2636 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2637 return $this->mToken;
2638 } else {
2639 // $wgAuthenticationTokenVersion in use, so hmac it.
2640 $ret = MWCryptHash::hmac( $wgAuthenticationTokenVersion, $this->mToken, false );
2642 // The raw hash can be overly long. Shorten it up.
2643 $len = max( 32, self::TOKEN_LENGTH );
2644 if ( strlen( $ret ) < $len ) {
2645 // Should never happen, even md5 is 128 bits
2646 throw new \UnexpectedValueException( 'Hmac returned less than 128 bits' );
2648 return substr( $ret, -$len );
2653 * Set the random token (used for persistent authentication)
2654 * Called from loadDefaults() among other places.
2656 * @param string|bool $token If specified, set the token to this value
2658 public function setToken( $token = false ) {
2659 $this->load();
2660 if ( $this->mToken === self::INVALID_TOKEN ) {
2661 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
2662 ->debug( __METHOD__ . ": Ignoring attempt to set token for system user \"$this\"" );
2663 } elseif ( !$token ) {
2664 $this->mToken = MWCryptRand::generateHex( self::TOKEN_LENGTH );
2665 } else {
2666 $this->mToken = $token;
2671 * Set the password for a password reminder or new account email
2673 * @deprecated Removed in 1.27. Use PasswordReset instead.
2674 * @param string $str New password to set or null to set an invalid
2675 * password hash meaning that the user will not be able to use it
2676 * @param bool $throttle If true, reset the throttle timestamp to the present
2678 public function setNewpassword( $str, $throttle = true ) {
2679 throw new BadMethodCallException( __METHOD__ . ' has been removed in 1.27' );
2683 * Get the user's e-mail address
2684 * @return string User's email address
2686 public function getEmail() {
2687 $this->load();
2688 Hooks::run( 'UserGetEmail', [ $this, &$this->mEmail ] );
2689 return $this->mEmail;
2693 * Get the timestamp of the user's e-mail authentication
2694 * @return string TS_MW timestamp
2696 public function getEmailAuthenticationTimestamp() {
2697 $this->load();
2698 Hooks::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated ] );
2699 return $this->mEmailAuthenticated;
2703 * Set the user's e-mail address
2704 * @param string $str New e-mail address
2706 public function setEmail( $str ) {
2707 $this->load();
2708 if ( $str == $this->mEmail ) {
2709 return;
2711 $this->invalidateEmail();
2712 $this->mEmail = $str;
2713 Hooks::run( 'UserSetEmail', [ $this, &$this->mEmail ] );
2717 * Set the user's e-mail address and a confirmation mail if needed.
2719 * @since 1.20
2720 * @param string $str New e-mail address
2721 * @return Status
2723 public function setEmailWithConfirmation( $str ) {
2724 global $wgEnableEmail, $wgEmailAuthentication;
2726 if ( !$wgEnableEmail ) {
2727 return Status::newFatal( 'emaildisabled' );
2730 $oldaddr = $this->getEmail();
2731 if ( $str === $oldaddr ) {
2732 return Status::newGood( true );
2735 $type = $oldaddr != '' ? 'changed' : 'set';
2736 $notificationResult = null;
2738 if ( $wgEmailAuthentication ) {
2739 // Send the user an email notifying the user of the change in registered
2740 // email address on their previous email address
2741 if ( $type == 'changed' ) {
2742 $change = $str != '' ? 'changed' : 'removed';
2743 $notificationResult = $this->sendMail(
2744 wfMessage( 'notificationemail_subject_' . $change )->text(),
2745 wfMessage( 'notificationemail_body_' . $change,
2746 $this->getRequest()->getIP(),
2747 $this->getName(),
2748 $str )->text()
2753 $this->setEmail( $str );
2755 if ( $str !== '' && $wgEmailAuthentication ) {
2756 // Send a confirmation request to the new address if needed
2757 $result = $this->sendConfirmationMail( $type );
2759 if ( $notificationResult !== null ) {
2760 $result->merge( $notificationResult );
2763 if ( $result->isGood() ) {
2764 // Say to the caller that a confirmation and notification mail has been sent
2765 $result->value = 'eauth';
2767 } else {
2768 $result = Status::newGood( true );
2771 return $result;
2775 * Get the user's real name
2776 * @return string User's real name
2778 public function getRealName() {
2779 if ( !$this->isItemLoaded( 'realname' ) ) {
2780 $this->load();
2783 return $this->mRealName;
2787 * Set the user's real name
2788 * @param string $str New real name
2790 public function setRealName( $str ) {
2791 $this->load();
2792 $this->mRealName = $str;
2796 * Get the user's current setting for a given option.
2798 * @param string $oname The option to check
2799 * @param string $defaultOverride A default value returned if the option does not exist
2800 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2801 * @return string|null User's current value for the option
2802 * @see getBoolOption()
2803 * @see getIntOption()
2805 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2806 global $wgHiddenPrefs;
2807 $this->loadOptions();
2809 # We want 'disabled' preferences to always behave as the default value for
2810 # users, even if they have set the option explicitly in their settings (ie they
2811 # set it, and then it was disabled removing their ability to change it). But
2812 # we don't want to erase the preferences in the database in case the preference
2813 # is re-enabled again. So don't touch $mOptions, just override the returned value
2814 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2815 return self::getDefaultOption( $oname );
2818 if ( array_key_exists( $oname, $this->mOptions ) ) {
2819 return $this->mOptions[$oname];
2820 } else {
2821 return $defaultOverride;
2826 * Get all user's options
2828 * @param int $flags Bitwise combination of:
2829 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2830 * to the default value. (Since 1.25)
2831 * @return array
2833 public function getOptions( $flags = 0 ) {
2834 global $wgHiddenPrefs;
2835 $this->loadOptions();
2836 $options = $this->mOptions;
2838 # We want 'disabled' preferences to always behave as the default value for
2839 # users, even if they have set the option explicitly in their settings (ie they
2840 # set it, and then it was disabled removing their ability to change it). But
2841 # we don't want to erase the preferences in the database in case the preference
2842 # is re-enabled again. So don't touch $mOptions, just override the returned value
2843 foreach ( $wgHiddenPrefs as $pref ) {
2844 $default = self::getDefaultOption( $pref );
2845 if ( $default !== null ) {
2846 $options[$pref] = $default;
2850 if ( $flags & self::GETOPTIONS_EXCLUDE_DEFAULTS ) {
2851 $options = array_diff_assoc( $options, self::getDefaultOptions() );
2854 return $options;
2858 * Get the user's current setting for a given option, as a boolean value.
2860 * @param string $oname The option to check
2861 * @return bool User's current value for the option
2862 * @see getOption()
2864 public function getBoolOption( $oname ) {
2865 return (bool)$this->getOption( $oname );
2869 * Get the user's current setting for a given option, as an integer value.
2871 * @param string $oname The option to check
2872 * @param int $defaultOverride A default value returned if the option does not exist
2873 * @return int User's current value for the option
2874 * @see getOption()
2876 public function getIntOption( $oname, $defaultOverride = 0 ) {
2877 $val = $this->getOption( $oname );
2878 if ( $val == '' ) {
2879 $val = $defaultOverride;
2881 return intval( $val );
2885 * Set the given option for a user.
2887 * You need to call saveSettings() to actually write to the database.
2889 * @param string $oname The option to set
2890 * @param mixed $val New value to set
2892 public function setOption( $oname, $val ) {
2893 $this->loadOptions();
2895 // Explicitly NULL values should refer to defaults
2896 if ( is_null( $val ) ) {
2897 $val = self::getDefaultOption( $oname );
2900 $this->mOptions[$oname] = $val;
2904 * Get a token stored in the preferences (like the watchlist one),
2905 * resetting it if it's empty (and saving changes).
2907 * @param string $oname The option name to retrieve the token from
2908 * @return string|bool User's current value for the option, or false if this option is disabled.
2909 * @see resetTokenFromOption()
2910 * @see getOption()
2911 * @deprecated since 1.26 Applications should use the OAuth extension
2913 public function getTokenFromOption( $oname ) {
2914 global $wgHiddenPrefs;
2916 $id = $this->getId();
2917 if ( !$id || in_array( $oname, $wgHiddenPrefs ) ) {
2918 return false;
2921 $token = $this->getOption( $oname );
2922 if ( !$token ) {
2923 // Default to a value based on the user token to avoid space
2924 // wasted on storing tokens for all users. When this option
2925 // is set manually by the user, only then is it stored.
2926 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2929 return $token;
2933 * Reset a token stored in the preferences (like the watchlist one).
2934 * *Does not* save user's preferences (similarly to setOption()).
2936 * @param string $oname The option name to reset the token in
2937 * @return string|bool New token value, or false if this option is disabled.
2938 * @see getTokenFromOption()
2939 * @see setOption()
2941 public function resetTokenFromOption( $oname ) {
2942 global $wgHiddenPrefs;
2943 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2944 return false;
2947 $token = MWCryptRand::generateHex( 40 );
2948 $this->setOption( $oname, $token );
2949 return $token;
2953 * Return a list of the types of user options currently returned by
2954 * User::getOptionKinds().
2956 * Currently, the option kinds are:
2957 * - 'registered' - preferences which are registered in core MediaWiki or
2958 * by extensions using the UserGetDefaultOptions hook.
2959 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2960 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2961 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2962 * be used by user scripts.
2963 * - 'special' - "preferences" that are not accessible via User::getOptions
2964 * or User::setOptions.
2965 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2966 * These are usually legacy options, removed in newer versions.
2968 * The API (and possibly others) use this function to determine the possible
2969 * option types for validation purposes, so make sure to update this when a
2970 * new option kind is added.
2972 * @see User::getOptionKinds
2973 * @return array Option kinds
2975 public static function listOptionKinds() {
2976 return [
2977 'registered',
2978 'registered-multiselect',
2979 'registered-checkmatrix',
2980 'userjs',
2981 'special',
2982 'unused'
2987 * Return an associative array mapping preferences keys to the kind of a preference they're
2988 * used for. Different kinds are handled differently when setting or reading preferences.
2990 * See User::listOptionKinds for the list of valid option types that can be provided.
2992 * @see User::listOptionKinds
2993 * @param IContextSource $context
2994 * @param array $options Assoc. array with options keys to check as keys.
2995 * Defaults to $this->mOptions.
2996 * @return array The key => kind mapping data
2998 public function getOptionKinds( IContextSource $context, $options = null ) {
2999 $this->loadOptions();
3000 if ( $options === null ) {
3001 $options = $this->mOptions;
3004 $prefs = Preferences::getPreferences( $this, $context );
3005 $mapping = [];
3007 // Pull out the "special" options, so they don't get converted as
3008 // multiselect or checkmatrix.
3009 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
3010 foreach ( $specialOptions as $name => $value ) {
3011 unset( $prefs[$name] );
3014 // Multiselect and checkmatrix options are stored in the database with
3015 // one key per option, each having a boolean value. Extract those keys.
3016 $multiselectOptions = [];
3017 foreach ( $prefs as $name => $info ) {
3018 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3019 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
3020 $opts = HTMLFormField::flattenOptions( $info['options'] );
3021 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
3023 foreach ( $opts as $value ) {
3024 $multiselectOptions["$prefix$value"] = true;
3027 unset( $prefs[$name] );
3030 $checkmatrixOptions = [];
3031 foreach ( $prefs as $name => $info ) {
3032 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3033 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
3034 $columns = HTMLFormField::flattenOptions( $info['columns'] );
3035 $rows = HTMLFormField::flattenOptions( $info['rows'] );
3036 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
3038 foreach ( $columns as $column ) {
3039 foreach ( $rows as $row ) {
3040 $checkmatrixOptions["$prefix$column-$row"] = true;
3044 unset( $prefs[$name] );
3048 // $value is ignored
3049 foreach ( $options as $key => $value ) {
3050 if ( isset( $prefs[$key] ) ) {
3051 $mapping[$key] = 'registered';
3052 } elseif ( isset( $multiselectOptions[$key] ) ) {
3053 $mapping[$key] = 'registered-multiselect';
3054 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3055 $mapping[$key] = 'registered-checkmatrix';
3056 } elseif ( isset( $specialOptions[$key] ) ) {
3057 $mapping[$key] = 'special';
3058 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3059 $mapping[$key] = 'userjs';
3060 } else {
3061 $mapping[$key] = 'unused';
3065 return $mapping;
3069 * Reset certain (or all) options to the site defaults
3071 * The optional parameter determines which kinds of preferences will be reset.
3072 * Supported values are everything that can be reported by getOptionKinds()
3073 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3075 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3076 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3077 * for backwards-compatibility.
3078 * @param IContextSource|null $context Context source used when $resetKinds
3079 * does not contain 'all', passed to getOptionKinds().
3080 * Defaults to RequestContext::getMain() when null.
3082 public function resetOptions(
3083 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3084 IContextSource $context = null
3086 $this->load();
3087 $defaultOptions = self::getDefaultOptions();
3089 if ( !is_array( $resetKinds ) ) {
3090 $resetKinds = [ $resetKinds ];
3093 if ( in_array( 'all', $resetKinds ) ) {
3094 $newOptions = $defaultOptions;
3095 } else {
3096 if ( $context === null ) {
3097 $context = RequestContext::getMain();
3100 $optionKinds = $this->getOptionKinds( $context );
3101 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
3102 $newOptions = [];
3104 // Use default values for the options that should be deleted, and
3105 // copy old values for the ones that shouldn't.
3106 foreach ( $this->mOptions as $key => $value ) {
3107 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3108 if ( array_key_exists( $key, $defaultOptions ) ) {
3109 $newOptions[$key] = $defaultOptions[$key];
3111 } else {
3112 $newOptions[$key] = $value;
3117 Hooks::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions, $resetKinds ] );
3119 $this->mOptions = $newOptions;
3120 $this->mOptionsLoaded = true;
3124 * Get the user's preferred date format.
3125 * @return string User's preferred date format
3127 public function getDatePreference() {
3128 // Important migration for old data rows
3129 if ( is_null( $this->mDatePreference ) ) {
3130 global $wgLang;
3131 $value = $this->getOption( 'date' );
3132 $map = $wgLang->getDatePreferenceMigrationMap();
3133 if ( isset( $map[$value] ) ) {
3134 $value = $map[$value];
3136 $this->mDatePreference = $value;
3138 return $this->mDatePreference;
3142 * Determine based on the wiki configuration and the user's options,
3143 * whether this user must be over HTTPS no matter what.
3145 * @return bool
3147 public function requiresHTTPS() {
3148 global $wgSecureLogin;
3149 if ( !$wgSecureLogin ) {
3150 return false;
3151 } else {
3152 $https = $this->getBoolOption( 'prefershttps' );
3153 Hooks::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3154 if ( $https ) {
3155 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3157 return $https;
3162 * Get the user preferred stub threshold
3164 * @return int
3166 public function getStubThreshold() {
3167 global $wgMaxArticleSize; # Maximum article size, in Kb
3168 $threshold = $this->getIntOption( 'stubthreshold' );
3169 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3170 // If they have set an impossible value, disable the preference
3171 // so we can use the parser cache again.
3172 $threshold = 0;
3174 return $threshold;
3178 * Get the permissions this user has.
3179 * @return array Array of String permission names
3181 public function getRights() {
3182 if ( is_null( $this->mRights ) ) {
3183 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
3184 Hooks::run( 'UserGetRights', [ $this, &$this->mRights ] );
3186 // Deny any rights denied by the user's session, unless this
3187 // endpoint has no sessions.
3188 if ( !defined( 'MW_NO_SESSION' ) ) {
3189 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3190 if ( $allowedRights !== null ) {
3191 $this->mRights = array_intersect( $this->mRights, $allowedRights );
3195 // Force reindexation of rights when a hook has unset one of them
3196 $this->mRights = array_values( array_unique( $this->mRights ) );
3198 // If block disables login, we should also remove any
3199 // extra rights blocked users might have, in case the
3200 // blocked user has a pre-existing session (T129738).
3201 // This is checked here for cases where people only call
3202 // $user->isAllowed(). It is also checked in Title::checkUserBlock()
3203 // to give a better error message in the common case.
3204 $config = RequestContext::getMain()->getConfig();
3205 if (
3206 $this->isLoggedIn() &&
3207 $config->get( 'BlockDisablesLogin' ) &&
3208 $this->isBlocked()
3210 $anon = new User;
3211 $this->mRights = array_intersect( $this->mRights, $anon->getRights() );
3214 return $this->mRights;
3218 * Get the list of explicit group memberships this user has.
3219 * The implicit * and user groups are not included.
3220 * @return array Array of String internal group names
3222 public function getGroups() {
3223 $this->load();
3224 $this->loadGroups();
3225 return $this->mGroups;
3229 * Get the list of implicit group memberships this user has.
3230 * This includes all explicit groups, plus 'user' if logged in,
3231 * '*' for all accounts, and autopromoted groups
3232 * @param bool $recache Whether to avoid the cache
3233 * @return array Array of String internal group names
3235 public function getEffectiveGroups( $recache = false ) {
3236 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
3237 $this->mEffectiveGroups = array_unique( array_merge(
3238 $this->getGroups(), // explicit groups
3239 $this->getAutomaticGroups( $recache ) // implicit groups
3240 ) );
3241 // Avoid PHP 7.1 warning of passing $this by reference
3242 $user = $this;
3243 // Hook for additional groups
3244 Hooks::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups ] );
3245 // Force reindexation of groups when a hook has unset one of them
3246 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
3248 return $this->mEffectiveGroups;
3252 * Get the list of implicit group memberships this user has.
3253 * This includes 'user' if logged in, '*' for all accounts,
3254 * and autopromoted groups
3255 * @param bool $recache Whether to avoid the cache
3256 * @return array Array of String internal group names
3258 public function getAutomaticGroups( $recache = false ) {
3259 if ( $recache || is_null( $this->mImplicitGroups ) ) {
3260 $this->mImplicitGroups = [ '*' ];
3261 if ( $this->getId() ) {
3262 $this->mImplicitGroups[] = 'user';
3264 $this->mImplicitGroups = array_unique( array_merge(
3265 $this->mImplicitGroups,
3266 Autopromote::getAutopromoteGroups( $this )
3267 ) );
3269 if ( $recache ) {
3270 // Assure data consistency with rights/groups,
3271 // as getEffectiveGroups() depends on this function
3272 $this->mEffectiveGroups = null;
3275 return $this->mImplicitGroups;
3279 * Returns the groups the user has belonged to.
3281 * The user may still belong to the returned groups. Compare with getGroups().
3283 * The function will not return groups the user had belonged to before MW 1.17
3285 * @return array Names of the groups the user has belonged to.
3287 public function getFormerGroups() {
3288 $this->load();
3290 if ( is_null( $this->mFormerGroups ) ) {
3291 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
3292 ? wfGetDB( DB_MASTER )
3293 : wfGetDB( DB_REPLICA );
3294 $res = $db->select( 'user_former_groups',
3295 [ 'ufg_group' ],
3296 [ 'ufg_user' => $this->mId ],
3297 __METHOD__ );
3298 $this->mFormerGroups = [];
3299 foreach ( $res as $row ) {
3300 $this->mFormerGroups[] = $row->ufg_group;
3304 return $this->mFormerGroups;
3308 * Get the user's edit count.
3309 * @return int|null Null for anonymous users
3311 public function getEditCount() {
3312 if ( !$this->getId() ) {
3313 return null;
3316 if ( $this->mEditCount === null ) {
3317 /* Populate the count, if it has not been populated yet */
3318 $dbr = wfGetDB( DB_REPLICA );
3319 // check if the user_editcount field has been initialized
3320 $count = $dbr->selectField(
3321 'user', 'user_editcount',
3322 [ 'user_id' => $this->mId ],
3323 __METHOD__
3326 if ( $count === null ) {
3327 // it has not been initialized. do so.
3328 $count = $this->initEditCount();
3330 $this->mEditCount = $count;
3332 return (int)$this->mEditCount;
3336 * Add the user to the given group.
3337 * This takes immediate effect.
3338 * @param string $group Name of the group to add
3339 * @return bool
3341 public function addGroup( $group ) {
3342 $this->load();
3344 if ( !Hooks::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3345 return false;
3348 $dbw = wfGetDB( DB_MASTER );
3349 if ( $this->getId() ) {
3350 $dbw->insert( 'user_groups',
3352 'ug_user' => $this->getId(),
3353 'ug_group' => $group,
3355 __METHOD__,
3356 [ 'IGNORE' ] );
3359 $this->loadGroups();
3360 $this->mGroups[] = $group;
3361 // In case loadGroups was not called before, we now have the right twice.
3362 // Get rid of the duplicate.
3363 $this->mGroups = array_unique( $this->mGroups );
3365 // Refresh the groups caches, and clear the rights cache so it will be
3366 // refreshed on the next call to $this->getRights().
3367 $this->getEffectiveGroups( true );
3368 $this->mRights = null;
3370 $this->invalidateCache();
3372 return true;
3376 * Remove the user from the given group.
3377 * This takes immediate effect.
3378 * @param string $group Name of the group to remove
3379 * @return bool
3381 public function removeGroup( $group ) {
3382 $this->load();
3383 if ( !Hooks::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3384 return false;
3387 $dbw = wfGetDB( DB_MASTER );
3388 $dbw->delete( 'user_groups',
3390 'ug_user' => $this->getId(),
3391 'ug_group' => $group,
3392 ], __METHOD__
3394 // Remember that the user was in this group
3395 $dbw->insert( 'user_former_groups',
3397 'ufg_user' => $this->getId(),
3398 'ufg_group' => $group,
3400 __METHOD__,
3401 [ 'IGNORE' ]
3404 $this->loadGroups();
3405 $this->mGroups = array_diff( $this->mGroups, [ $group ] );
3407 // Refresh the groups caches, and clear the rights cache so it will be
3408 // refreshed on the next call to $this->getRights().
3409 $this->getEffectiveGroups( true );
3410 $this->mRights = null;
3412 $this->invalidateCache();
3414 return true;
3418 * Get whether the user is logged in
3419 * @return bool
3421 public function isLoggedIn() {
3422 return $this->getId() != 0;
3426 * Get whether the user is anonymous
3427 * @return bool
3429 public function isAnon() {
3430 return !$this->isLoggedIn();
3434 * @return bool Whether this user is flagged as being a bot role account
3435 * @since 1.28
3437 public function isBot() {
3438 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3439 return true;
3442 $isBot = false;
3443 Hooks::run( "UserIsBot", [ $this, &$isBot ] );
3445 return $isBot;
3449 * Check if user is allowed to access a feature / make an action
3451 * @param string ... Permissions to test
3452 * @return bool True if user is allowed to perform *any* of the given actions
3454 public function isAllowedAny() {
3455 $permissions = func_get_args();
3456 foreach ( $permissions as $permission ) {
3457 if ( $this->isAllowed( $permission ) ) {
3458 return true;
3461 return false;
3466 * @param string ... Permissions to test
3467 * @return bool True if the user is allowed to perform *all* of the given actions
3469 public function isAllowedAll() {
3470 $permissions = func_get_args();
3471 foreach ( $permissions as $permission ) {
3472 if ( !$this->isAllowed( $permission ) ) {
3473 return false;
3476 return true;
3480 * Internal mechanics of testing a permission
3481 * @param string $action
3482 * @return bool
3484 public function isAllowed( $action = '' ) {
3485 if ( $action === '' ) {
3486 return true; // In the spirit of DWIM
3488 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3489 // by misconfiguration: 0 == 'foo'
3490 return in_array( $action, $this->getRights(), true );
3494 * Check whether to enable recent changes patrol features for this user
3495 * @return bool True or false
3497 public function useRCPatrol() {
3498 global $wgUseRCPatrol;
3499 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3503 * Check whether to enable new pages patrol features for this user
3504 * @return bool True or false
3506 public function useNPPatrol() {
3507 global $wgUseRCPatrol, $wgUseNPPatrol;
3508 return (
3509 ( $wgUseRCPatrol || $wgUseNPPatrol )
3510 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3515 * Check whether to enable new files patrol features for this user
3516 * @return bool True or false
3518 public function useFilePatrol() {
3519 global $wgUseRCPatrol, $wgUseFilePatrol;
3520 return (
3521 ( $wgUseRCPatrol || $wgUseFilePatrol )
3522 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3527 * Get the WebRequest object to use with this object
3529 * @return WebRequest
3531 public function getRequest() {
3532 if ( $this->mRequest ) {
3533 return $this->mRequest;
3534 } else {
3535 global $wgRequest;
3536 return $wgRequest;
3541 * Check the watched status of an article.
3542 * @since 1.22 $checkRights parameter added
3543 * @param Title $title Title of the article to look at
3544 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3545 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3546 * @return bool
3548 public function isWatched( $title, $checkRights = self::CHECK_USER_RIGHTS ) {
3549 if ( $title->isWatchable() && ( !$checkRights || $this->isAllowed( 'viewmywatchlist' ) ) ) {
3550 return MediaWikiServices::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3552 return false;
3556 * Watch an article.
3557 * @since 1.22 $checkRights parameter added
3558 * @param Title $title Title of the article to look at
3559 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3560 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3562 public function addWatch( $title, $checkRights = self::CHECK_USER_RIGHTS ) {
3563 if ( !$checkRights || $this->isAllowed( 'editmywatchlist' ) ) {
3564 MediaWikiServices::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3565 $this,
3566 [ $title->getSubjectPage(), $title->getTalkPage() ]
3569 $this->invalidateCache();
3573 * Stop watching an article.
3574 * @since 1.22 $checkRights parameter added
3575 * @param Title $title Title of the article to look at
3576 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3577 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3579 public function removeWatch( $title, $checkRights = self::CHECK_USER_RIGHTS ) {
3580 if ( !$checkRights || $this->isAllowed( 'editmywatchlist' ) ) {
3581 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
3582 $store->removeWatch( $this, $title->getSubjectPage() );
3583 $store->removeWatch( $this, $title->getTalkPage() );
3585 $this->invalidateCache();
3589 * Clear the user's notification timestamp for the given title.
3590 * If e-notif e-mails are on, they will receive notification mails on
3591 * the next change of the page if it's watched etc.
3592 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3593 * @param Title $title Title of the article to look at
3594 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3596 public function clearNotification( &$title, $oldid = 0 ) {
3597 global $wgUseEnotif, $wgShowUpdatedMarker;
3599 // Do nothing if the database is locked to writes
3600 if ( wfReadOnly() ) {
3601 return;
3604 // Do nothing if not allowed to edit the watchlist
3605 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3606 return;
3609 // If we're working on user's talk page, we should update the talk page message indicator
3610 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3611 // Avoid PHP 7.1 warning of passing $this by reference
3612 $user = $this;
3613 if ( !Hooks::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3614 return;
3617 // Try to update the DB post-send and only if needed...
3618 DeferredUpdates::addCallableUpdate( function() use ( $title, $oldid ) {
3619 if ( !$this->getNewtalk() ) {
3620 return; // no notifications to clear
3623 // Delete the last notifications (they stack up)
3624 $this->setNewtalk( false );
3626 // If there is a new, unseen, revision, use its timestamp
3627 $nextid = $oldid
3628 ? $title->getNextRevisionID( $oldid, Title::GAID_FOR_UPDATE )
3629 : null;
3630 if ( $nextid ) {
3631 $this->setNewtalk( true, Revision::newFromId( $nextid ) );
3633 } );
3636 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3637 return;
3640 if ( $this->isAnon() ) {
3641 // Nothing else to do...
3642 return;
3645 // Only update the timestamp if the page is being watched.
3646 // The query to find out if it is watched is cached both in memcached and per-invocation,
3647 // and when it does have to be executed, it can be on a replica DB
3648 // If this is the user's newtalk page, we always update the timestamp
3649 $force = '';
3650 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3651 $force = 'force';
3654 MediaWikiServices::getInstance()->getWatchedItemStore()
3655 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3659 * Resets all of the given user's page-change notification timestamps.
3660 * If e-notif e-mails are on, they will receive notification mails on
3661 * the next change of any watched page.
3662 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3664 public function clearAllNotifications() {
3665 global $wgUseEnotif, $wgShowUpdatedMarker;
3666 // Do nothing if not allowed to edit the watchlist
3667 if ( wfReadOnly() || !$this->isAllowed( 'editmywatchlist' ) ) {
3668 return;
3671 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3672 $this->setNewtalk( false );
3673 return;
3676 $id = $this->getId();
3677 if ( !$id ) {
3678 return;
3681 $dbw = wfGetDB( DB_MASTER );
3682 $asOfTimes = array_unique( $dbw->selectFieldValues(
3683 'watchlist',
3684 'wl_notificationtimestamp',
3685 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3686 __METHOD__,
3687 [ 'ORDER BY' => 'wl_notificationtimestamp DESC', 'LIMIT' => 500 ]
3688 ) );
3689 if ( !$asOfTimes ) {
3690 return;
3692 // Immediately update the most recent touched rows, which hopefully covers what
3693 // the user sees on the watchlist page before pressing "mark all pages visited"....
3694 $dbw->update(
3695 'watchlist',
3696 [ 'wl_notificationtimestamp' => null ],
3697 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimes ],
3698 __METHOD__
3700 // ...and finish the older ones in a post-send update with lag checks...
3701 DeferredUpdates::addUpdate( new AutoCommitUpdate(
3702 $dbw,
3703 __METHOD__,
3704 function () use ( $dbw, $id ) {
3705 global $wgUpdateRowsPerQuery;
3707 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
3708 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ );
3709 $asOfTimes = array_unique( $dbw->selectFieldValues(
3710 'watchlist',
3711 'wl_notificationtimestamp',
3712 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3713 __METHOD__
3714 ) );
3715 foreach ( array_chunk( $asOfTimes, $wgUpdateRowsPerQuery ) as $asOfTimeBatch ) {
3716 $dbw->update(
3717 'watchlist',
3718 [ 'wl_notificationtimestamp' => null ],
3719 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimeBatch ],
3720 __METHOD__
3722 $lbFactory->commitAndWaitForReplication( __METHOD__, $ticket );
3725 ) );
3726 // We also need to clear here the "you have new message" notification for the own
3727 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3731 * Set a cookie on the user's client. Wrapper for
3732 * WebResponse::setCookie
3733 * @deprecated since 1.27
3734 * @param string $name Name of the cookie to set
3735 * @param string $value Value to set
3736 * @param int $exp Expiration time, as a UNIX time value;
3737 * if 0 or not specified, use the default $wgCookieExpiration
3738 * @param bool $secure
3739 * true: Force setting the secure attribute when setting the cookie
3740 * false: Force NOT setting the secure attribute when setting the cookie
3741 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3742 * @param array $params Array of options sent passed to WebResponse::setcookie()
3743 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3744 * is passed.
3746 protected function setCookie(
3747 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3749 wfDeprecated( __METHOD__, '1.27' );
3750 if ( $request === null ) {
3751 $request = $this->getRequest();
3753 $params['secure'] = $secure;
3754 $request->response()->setCookie( $name, $value, $exp, $params );
3758 * Clear a cookie on the user's client
3759 * @deprecated since 1.27
3760 * @param string $name Name of the cookie to clear
3761 * @param bool $secure
3762 * true: Force setting the secure attribute when setting the cookie
3763 * false: Force NOT setting the secure attribute when setting the cookie
3764 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3765 * @param array $params Array of options sent passed to WebResponse::setcookie()
3767 protected function clearCookie( $name, $secure = null, $params = [] ) {
3768 wfDeprecated( __METHOD__, '1.27' );
3769 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3773 * Set an extended login cookie on the user's client. The expiry of the cookie
3774 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3775 * variable.
3777 * @see User::setCookie
3779 * @deprecated since 1.27
3780 * @param string $name Name of the cookie to set
3781 * @param string $value Value to set
3782 * @param bool $secure
3783 * true: Force setting the secure attribute when setting the cookie
3784 * false: Force NOT setting the secure attribute when setting the cookie
3785 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3787 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3788 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3790 wfDeprecated( __METHOD__, '1.27' );
3792 $exp = time();
3793 $exp += $wgExtendedLoginCookieExpiration !== null
3794 ? $wgExtendedLoginCookieExpiration
3795 : $wgCookieExpiration;
3797 $this->setCookie( $name, $value, $exp, $secure );
3801 * Persist this user's session (e.g. set cookies)
3803 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3804 * is passed.
3805 * @param bool $secure Whether to force secure/insecure cookies or use default
3806 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3808 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3809 $this->load();
3810 if ( 0 == $this->mId ) {
3811 return;
3814 $session = $this->getRequest()->getSession();
3815 if ( $request && $session->getRequest() !== $request ) {
3816 $session = $session->sessionWithRequest( $request );
3818 $delay = $session->delaySave();
3820 if ( !$session->getUser()->equals( $this ) ) {
3821 if ( !$session->canSetUser() ) {
3822 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3823 ->warning( __METHOD__ .
3824 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3826 return;
3828 $session->setUser( $this );
3831 $session->setRememberUser( $rememberMe );
3832 if ( $secure !== null ) {
3833 $session->setForceHTTPS( $secure );
3836 $session->persist();
3838 ScopedCallback::consume( $delay );
3842 * Log this user out.
3844 public function logout() {
3845 // Avoid PHP 7.1 warning of passing $this by reference
3846 $user = $this;
3847 if ( Hooks::run( 'UserLogout', [ &$user ] ) ) {
3848 $this->doLogout();
3853 * Clear the user's session, and reset the instance cache.
3854 * @see logout()
3856 public function doLogout() {
3857 $session = $this->getRequest()->getSession();
3858 if ( !$session->canSetUser() ) {
3859 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3860 ->warning( __METHOD__ . ": Cannot log out of an immutable session" );
3861 $error = 'immutable';
3862 } elseif ( !$session->getUser()->equals( $this ) ) {
3863 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3864 ->warning( __METHOD__ .
3865 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3867 // But we still may as well make this user object anon
3868 $this->clearInstanceCache( 'defaults' );
3869 $error = 'wronguser';
3870 } else {
3871 $this->clearInstanceCache( 'defaults' );
3872 $delay = $session->delaySave();
3873 $session->unpersist(); // Clear cookies (T127436)
3874 $session->setLoggedOutTimestamp( time() );
3875 $session->setUser( new User );
3876 $session->set( 'wsUserID', 0 ); // Other code expects this
3877 $session->resetAllTokens();
3878 ScopedCallback::consume( $delay );
3879 $error = false;
3881 \MediaWiki\Logger\LoggerFactory::getInstance( 'authevents' )->info( 'Logout', [
3882 'event' => 'logout',
3883 'successful' => $error === false,
3884 'status' => $error ?: 'success',
3885 ] );
3889 * Save this user's settings into the database.
3890 * @todo Only rarely do all these fields need to be set!
3892 public function saveSettings() {
3893 if ( wfReadOnly() ) {
3894 // @TODO: caller should deal with this instead!
3895 // This should really just be an exception.
3896 MWExceptionHandler::logException( new DBExpectedError(
3897 null,
3898 "Could not update user with ID '{$this->mId}'; DB is read-only."
3899 ) );
3900 return;
3903 $this->load();
3904 if ( 0 == $this->mId ) {
3905 return; // anon
3908 // Get a new user_touched that is higher than the old one.
3909 // This will be used for a CAS check as a last-resort safety
3910 // check against race conditions and replica DB lag.
3911 $newTouched = $this->newTouchedTimestamp();
3913 $dbw = wfGetDB( DB_MASTER );
3914 $dbw->update( 'user',
3915 [ /* SET */
3916 'user_name' => $this->mName,
3917 'user_real_name' => $this->mRealName,
3918 'user_email' => $this->mEmail,
3919 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3920 'user_touched' => $dbw->timestamp( $newTouched ),
3921 'user_token' => strval( $this->mToken ),
3922 'user_email_token' => $this->mEmailToken,
3923 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3924 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
3925 'user_id' => $this->mId,
3926 ] ), __METHOD__
3929 if ( !$dbw->affectedRows() ) {
3930 // Maybe the problem was a missed cache update; clear it to be safe
3931 $this->clearSharedCache( 'refresh' );
3932 // User was changed in the meantime or loaded with stale data
3933 $from = ( $this->queryFlagsUsed & self::READ_LATEST ) ? 'master' : 'replica';
3934 throw new MWException(
3935 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3936 " the version of the user to be saved is older than the current version."
3940 $this->mTouched = $newTouched;
3941 $this->saveOptions();
3943 Hooks::run( 'UserSaveSettings', [ $this ] );
3944 $this->clearSharedCache();
3945 $this->getUserPage()->invalidateCache();
3949 * If only this user's username is known, and it exists, return the user ID.
3951 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3952 * @return int
3954 public function idForName( $flags = 0 ) {
3955 $s = trim( $this->getName() );
3956 if ( $s === '' ) {
3957 return 0;
3960 $db = ( ( $flags & self::READ_LATEST ) == self::READ_LATEST )
3961 ? wfGetDB( DB_MASTER )
3962 : wfGetDB( DB_REPLICA );
3964 $options = ( ( $flags & self::READ_LOCKING ) == self::READ_LOCKING )
3965 ? [ 'LOCK IN SHARE MODE' ]
3966 : [];
3968 $id = $db->selectField( 'user',
3969 'user_id', [ 'user_name' => $s ], __METHOD__, $options );
3971 return (int)$id;
3975 * Add a user to the database, return the user object
3977 * @param string $name Username to add
3978 * @param array $params Array of Strings Non-default parameters to save to
3979 * the database as user_* fields:
3980 * - email: The user's email address.
3981 * - email_authenticated: The email authentication timestamp.
3982 * - real_name: The user's real name.
3983 * - options: An associative array of non-default options.
3984 * - token: Random authentication token. Do not set.
3985 * - registration: Registration timestamp. Do not set.
3987 * @return User|null User object, or null if the username already exists.
3989 public static function createNew( $name, $params = [] ) {
3990 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
3991 if ( isset( $params[$field] ) ) {
3992 wfDeprecated( __METHOD__ . " with param '$field'", '1.27' );
3993 unset( $params[$field] );
3997 $user = new User;
3998 $user->load();
3999 $user->setToken(); // init token
4000 if ( isset( $params['options'] ) ) {
4001 $user->mOptions = $params['options'] + (array)$user->mOptions;
4002 unset( $params['options'] );
4004 $dbw = wfGetDB( DB_MASTER );
4005 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4007 $noPass = PasswordFactory::newInvalidPassword()->toString();
4009 $fields = [
4010 'user_id' => $seqVal,
4011 'user_name' => $name,
4012 'user_password' => $noPass,
4013 'user_newpassword' => $noPass,
4014 'user_email' => $user->mEmail,
4015 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
4016 'user_real_name' => $user->mRealName,
4017 'user_token' => strval( $user->mToken ),
4018 'user_registration' => $dbw->timestamp( $user->mRegistration ),
4019 'user_editcount' => 0,
4020 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4022 foreach ( $params as $name => $value ) {
4023 $fields["user_$name"] = $value;
4025 $dbw->insert( 'user', $fields, __METHOD__, [ 'IGNORE' ] );
4026 if ( $dbw->affectedRows() ) {
4027 $newUser = User::newFromId( $dbw->insertId() );
4028 } else {
4029 $newUser = null;
4031 return $newUser;
4035 * Add this existing user object to the database. If the user already
4036 * exists, a fatal status object is returned, and the user object is
4037 * initialised with the data from the database.
4039 * Previously, this function generated a DB error due to a key conflict
4040 * if the user already existed. Many extension callers use this function
4041 * in code along the lines of:
4043 * $user = User::newFromName( $name );
4044 * if ( !$user->isLoggedIn() ) {
4045 * $user->addToDatabase();
4047 * // do something with $user...
4049 * However, this was vulnerable to a race condition (bug 16020). By
4050 * initialising the user object if the user exists, we aim to support this
4051 * calling sequence as far as possible.
4053 * Note that if the user exists, this function will acquire a write lock,
4054 * so it is still advisable to make the call conditional on isLoggedIn(),
4055 * and to commit the transaction after calling.
4057 * @throws MWException
4058 * @return Status
4060 public function addToDatabase() {
4061 $this->load();
4062 if ( !$this->mToken ) {
4063 $this->setToken(); // init token
4066 $this->mTouched = $this->newTouchedTimestamp();
4068 $noPass = PasswordFactory::newInvalidPassword()->toString();
4070 $dbw = wfGetDB( DB_MASTER );
4071 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4072 $dbw->insert( 'user',
4074 'user_id' => $seqVal,
4075 'user_name' => $this->mName,
4076 'user_password' => $noPass,
4077 'user_newpassword' => $noPass,
4078 'user_email' => $this->mEmail,
4079 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
4080 'user_real_name' => $this->mRealName,
4081 'user_token' => strval( $this->mToken ),
4082 'user_registration' => $dbw->timestamp( $this->mRegistration ),
4083 'user_editcount' => 0,
4084 'user_touched' => $dbw->timestamp( $this->mTouched ),
4085 ], __METHOD__,
4086 [ 'IGNORE' ]
4088 if ( !$dbw->affectedRows() ) {
4089 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4090 $this->mId = $dbw->selectField(
4091 'user',
4092 'user_id',
4093 [ 'user_name' => $this->mName ],
4094 __METHOD__,
4095 [ 'LOCK IN SHARE MODE' ]
4097 $loaded = false;
4098 if ( $this->mId ) {
4099 if ( $this->loadFromDatabase( self::READ_LOCKING ) ) {
4100 $loaded = true;
4103 if ( !$loaded ) {
4104 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
4105 "to insert user '{$this->mName}' row, but it was not present in select!" );
4107 return Status::newFatal( 'userexists' );
4109 $this->mId = $dbw->insertId();
4110 self::$idCacheByName[$this->mName] = $this->mId;
4112 // Clear instance cache other than user table data, which is already accurate
4113 $this->clearInstanceCache();
4115 $this->saveOptions();
4116 return Status::newGood();
4120 * If this user is logged-in and blocked,
4121 * block any IP address they've successfully logged in from.
4122 * @return bool A block was spread
4124 public function spreadAnyEditBlock() {
4125 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4126 return $this->spreadBlock();
4129 return false;
4133 * If this (non-anonymous) user is blocked,
4134 * block the IP address they've successfully logged in from.
4135 * @return bool A block was spread
4137 protected function spreadBlock() {
4138 wfDebug( __METHOD__ . "()\n" );
4139 $this->load();
4140 if ( $this->mId == 0 ) {
4141 return false;
4144 $userblock = Block::newFromTarget( $this->getName() );
4145 if ( !$userblock ) {
4146 return false;
4149 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4153 * Get whether the user is explicitly blocked from account creation.
4154 * @return bool|Block
4156 public function isBlockedFromCreateAccount() {
4157 $this->getBlockedStatus();
4158 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
4159 return $this->mBlock;
4162 # bug 13611: if the IP address the user is trying to create an account from is
4163 # blocked with createaccount disabled, prevent new account creation there even
4164 # when the user is logged in
4165 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4166 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
4168 return $this->mBlockedFromCreateAccount instanceof Block
4169 && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
4170 ? $this->mBlockedFromCreateAccount
4171 : false;
4175 * Get whether the user is blocked from using Special:Emailuser.
4176 * @return bool
4178 public function isBlockedFromEmailuser() {
4179 $this->getBlockedStatus();
4180 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
4184 * Get whether the user is allowed to create an account.
4185 * @return bool
4187 public function isAllowedToCreateAccount() {
4188 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4192 * Get this user's personal page title.
4194 * @return Title User's personal page title
4196 public function getUserPage() {
4197 return Title::makeTitle( NS_USER, $this->getName() );
4201 * Get this user's talk page title.
4203 * @return Title User's talk page title
4205 public function getTalkPage() {
4206 $title = $this->getUserPage();
4207 return $title->getTalkPage();
4211 * Determine whether the user is a newbie. Newbies are either
4212 * anonymous IPs, or the most recently created accounts.
4213 * @return bool
4215 public function isNewbie() {
4216 return !$this->isAllowed( 'autoconfirmed' );
4220 * Check to see if the given clear-text password is one of the accepted passwords
4221 * @deprecated since 1.27, use AuthManager instead
4222 * @param string $password User password
4223 * @return bool True if the given password is correct, otherwise False
4225 public function checkPassword( $password ) {
4226 $manager = AuthManager::singleton();
4227 $reqs = AuthenticationRequest::loadRequestsFromSubmission(
4228 $manager->getAuthenticationRequests( AuthManager::ACTION_LOGIN ),
4230 'username' => $this->getName(),
4231 'password' => $password,
4234 $res = AuthManager::singleton()->beginAuthentication( $reqs, 'null:' );
4235 switch ( $res->status ) {
4236 case AuthenticationResponse::PASS:
4237 return true;
4238 case AuthenticationResponse::FAIL:
4239 // Hope it's not a PreAuthenticationProvider that failed...
4240 \MediaWiki\Logger\LoggerFactory::getInstance( 'authentication' )
4241 ->info( __METHOD__ . ': Authentication failed: ' . $res->message->plain() );
4242 return false;
4243 default:
4244 throw new BadMethodCallException(
4245 'AuthManager returned a response unsupported by ' . __METHOD__
4251 * Check if the given clear-text password matches the temporary password
4252 * sent by e-mail for password reset operations.
4254 * @deprecated since 1.27, use AuthManager instead
4255 * @param string $plaintext
4256 * @return bool True if matches, false otherwise
4258 public function checkTemporaryPassword( $plaintext ) {
4259 // Can't check the temporary password individually.
4260 return $this->checkPassword( $plaintext );
4264 * Initialize (if necessary) and return a session token value
4265 * which can be used in edit forms to show that the user's
4266 * login credentials aren't being hijacked with a foreign form
4267 * submission.
4269 * @since 1.27
4270 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4271 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4272 * @return MediaWiki\Session\Token The new edit token
4274 public function getEditTokenObject( $salt = '', $request = null ) {
4275 if ( $this->isAnon() ) {
4276 return new LoggedOutEditToken();
4279 if ( !$request ) {
4280 $request = $this->getRequest();
4282 return $request->getSession()->getToken( $salt );
4286 * Initialize (if necessary) and return a session token value
4287 * which can be used in edit forms to show that the user's
4288 * login credentials aren't being hijacked with a foreign form
4289 * submission.
4291 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4293 * @since 1.19
4294 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4295 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4296 * @return string The new edit token
4298 public function getEditToken( $salt = '', $request = null ) {
4299 return $this->getEditTokenObject( $salt, $request )->toString();
4303 * Get the embedded timestamp from a token.
4304 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4305 * @param string $val Input token
4306 * @return int|null
4308 public static function getEditTokenTimestamp( $val ) {
4309 wfDeprecated( __METHOD__, '1.27' );
4310 return MediaWiki\Session\Token::getTimestamp( $val );
4314 * Check given value against the token value stored in the session.
4315 * A match should confirm that the form was submitted from the
4316 * user's own login session, not a form submission from a third-party
4317 * site.
4319 * @param string $val Input value to compare
4320 * @param string $salt Optional function-specific data for hashing
4321 * @param WebRequest|null $request Object to use or null to use $wgRequest
4322 * @param int $maxage Fail tokens older than this, in seconds
4323 * @return bool Whether the token matches
4325 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4326 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4330 * Check given value against the token value stored in the session,
4331 * ignoring the suffix.
4333 * @param string $val Input value to compare
4334 * @param string $salt Optional function-specific data for hashing
4335 * @param WebRequest|null $request Object to use or null to use $wgRequest
4336 * @param int $maxage Fail tokens older than this, in seconds
4337 * @return bool Whether the token matches
4339 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4340 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token::SUFFIX;
4341 return $this->matchEditToken( $val, $salt, $request, $maxage );
4345 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4346 * mail to the user's given address.
4348 * @param string $type Message to send, either "created", "changed" or "set"
4349 * @return Status
4351 public function sendConfirmationMail( $type = 'created' ) {
4352 global $wgLang;
4353 $expiration = null; // gets passed-by-ref and defined in next line.
4354 $token = $this->confirmationToken( $expiration );
4355 $url = $this->confirmationTokenUrl( $token );
4356 $invalidateURL = $this->invalidationTokenUrl( $token );
4357 $this->saveSettings();
4359 if ( $type == 'created' || $type === false ) {
4360 $message = 'confirmemail_body';
4361 } elseif ( $type === true ) {
4362 $message = 'confirmemail_body_changed';
4363 } else {
4364 // Messages: confirmemail_body_changed, confirmemail_body_set
4365 $message = 'confirmemail_body_' . $type;
4368 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4369 wfMessage( $message,
4370 $this->getRequest()->getIP(),
4371 $this->getName(),
4372 $url,
4373 $wgLang->userTimeAndDate( $expiration, $this ),
4374 $invalidateURL,
4375 $wgLang->userDate( $expiration, $this ),
4376 $wgLang->userTime( $expiration, $this ) )->text() );
4380 * Send an e-mail to this user's account. Does not check for
4381 * confirmed status or validity.
4383 * @param string $subject Message subject
4384 * @param string $body Message body
4385 * @param User|null $from Optional sending user; if unspecified, default
4386 * $wgPasswordSender will be used.
4387 * @param string $replyto Reply-To address
4388 * @return Status
4390 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4391 global $wgPasswordSender;
4393 if ( $from instanceof User ) {
4394 $sender = MailAddress::newFromUser( $from );
4395 } else {
4396 $sender = new MailAddress( $wgPasswordSender,
4397 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4399 $to = MailAddress::newFromUser( $this );
4401 return UserMailer::send( $to, $sender, $subject, $body, [
4402 'replyTo' => $replyto,
4403 ] );
4407 * Generate, store, and return a new e-mail confirmation code.
4408 * A hash (unsalted, since it's used as a key) is stored.
4410 * @note Call saveSettings() after calling this function to commit
4411 * this change to the database.
4413 * @param string &$expiration Accepts the expiration time
4414 * @return string New token
4416 protected function confirmationToken( &$expiration ) {
4417 global $wgUserEmailConfirmationTokenExpiry;
4418 $now = time();
4419 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
4420 $expiration = wfTimestamp( TS_MW, $expires );
4421 $this->load();
4422 $token = MWCryptRand::generateHex( 32 );
4423 $hash = md5( $token );
4424 $this->mEmailToken = $hash;
4425 $this->mEmailTokenExpires = $expiration;
4426 return $token;
4430 * Return a URL the user can use to confirm their email address.
4431 * @param string $token Accepts the email confirmation token
4432 * @return string New token URL
4434 protected function confirmationTokenUrl( $token ) {
4435 return $this->getTokenUrl( 'ConfirmEmail', $token );
4439 * Return a URL the user can use to invalidate their email address.
4440 * @param string $token Accepts the email confirmation token
4441 * @return string New token URL
4443 protected function invalidationTokenUrl( $token ) {
4444 return $this->getTokenUrl( 'InvalidateEmail', $token );
4448 * Internal function to format the e-mail validation/invalidation URLs.
4449 * This uses a quickie hack to use the
4450 * hardcoded English names of the Special: pages, for ASCII safety.
4452 * @note Since these URLs get dropped directly into emails, using the
4453 * short English names avoids insanely long URL-encoded links, which
4454 * also sometimes can get corrupted in some browsers/mailers
4455 * (bug 6957 with Gmail and Internet Explorer).
4457 * @param string $page Special page
4458 * @param string $token Token
4459 * @return string Formatted URL
4461 protected function getTokenUrl( $page, $token ) {
4462 // Hack to bypass localization of 'Special:'
4463 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
4464 return $title->getCanonicalURL();
4468 * Mark the e-mail address confirmed.
4470 * @note Call saveSettings() after calling this function to commit the change.
4472 * @return bool
4474 public function confirmEmail() {
4475 // Check if it's already confirmed, so we don't touch the database
4476 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4477 if ( !$this->isEmailConfirmed() ) {
4478 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4479 Hooks::run( 'ConfirmEmailComplete', [ $this ] );
4481 return true;
4485 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4486 * address if it was already confirmed.
4488 * @note Call saveSettings() after calling this function to commit the change.
4489 * @return bool Returns true
4491 public function invalidateEmail() {
4492 $this->load();
4493 $this->mEmailToken = null;
4494 $this->mEmailTokenExpires = null;
4495 $this->setEmailAuthenticationTimestamp( null );
4496 $this->mEmail = '';
4497 Hooks::run( 'InvalidateEmailComplete', [ $this ] );
4498 return true;
4502 * Set the e-mail authentication timestamp.
4503 * @param string $timestamp TS_MW timestamp
4505 public function setEmailAuthenticationTimestamp( $timestamp ) {
4506 $this->load();
4507 $this->mEmailAuthenticated = $timestamp;
4508 Hooks::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated ] );
4512 * Is this user allowed to send e-mails within limits of current
4513 * site configuration?
4514 * @return bool
4516 public function canSendEmail() {
4517 global $wgEnableEmail, $wgEnableUserEmail;
4518 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4519 return false;
4521 $canSend = $this->isEmailConfirmed();
4522 // Avoid PHP 7.1 warning of passing $this by reference
4523 $user = $this;
4524 Hooks::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4525 return $canSend;
4529 * Is this user allowed to receive e-mails within limits of current
4530 * site configuration?
4531 * @return bool
4533 public function canReceiveEmail() {
4534 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4538 * Is this user's e-mail address valid-looking and confirmed within
4539 * limits of the current site configuration?
4541 * @note If $wgEmailAuthentication is on, this may require the user to have
4542 * confirmed their address by returning a code or using a password
4543 * sent to the address from the wiki.
4545 * @return bool
4547 public function isEmailConfirmed() {
4548 global $wgEmailAuthentication;
4549 $this->load();
4550 // Avoid PHP 7.1 warning of passing $this by reference
4551 $user = $this;
4552 $confirmed = true;
4553 if ( Hooks::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4554 if ( $this->isAnon() ) {
4555 return false;
4557 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4558 return false;
4560 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4561 return false;
4563 return true;
4564 } else {
4565 return $confirmed;
4570 * Check whether there is an outstanding request for e-mail confirmation.
4571 * @return bool
4573 public function isEmailConfirmationPending() {
4574 global $wgEmailAuthentication;
4575 return $wgEmailAuthentication &&
4576 !$this->isEmailConfirmed() &&
4577 $this->mEmailToken &&
4578 $this->mEmailTokenExpires > wfTimestamp();
4582 * Get the timestamp of account creation.
4584 * @return string|bool|null Timestamp of account creation, false for
4585 * non-existent/anonymous user accounts, or null if existing account
4586 * but information is not in database.
4588 public function getRegistration() {
4589 if ( $this->isAnon() ) {
4590 return false;
4592 $this->load();
4593 return $this->mRegistration;
4597 * Get the timestamp of the first edit
4599 * @return string|bool Timestamp of first edit, or false for
4600 * non-existent/anonymous user accounts.
4602 public function getFirstEditTimestamp() {
4603 if ( $this->getId() == 0 ) {
4604 return false; // anons
4606 $dbr = wfGetDB( DB_REPLICA );
4607 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4608 [ 'rev_user' => $this->getId() ],
4609 __METHOD__,
4610 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4612 if ( !$time ) {
4613 return false; // no edits
4615 return wfTimestamp( TS_MW, $time );
4619 * Get the permissions associated with a given list of groups
4621 * @param array $groups Array of Strings List of internal group names
4622 * @return array Array of Strings List of permission key names for given groups combined
4624 public static function getGroupPermissions( $groups ) {
4625 global $wgGroupPermissions, $wgRevokePermissions;
4626 $rights = [];
4627 // grant every granted permission first
4628 foreach ( $groups as $group ) {
4629 if ( isset( $wgGroupPermissions[$group] ) ) {
4630 $rights = array_merge( $rights,
4631 // array_filter removes empty items
4632 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4635 // now revoke the revoked permissions
4636 foreach ( $groups as $group ) {
4637 if ( isset( $wgRevokePermissions[$group] ) ) {
4638 $rights = array_diff( $rights,
4639 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4642 return array_unique( $rights );
4646 * Get all the groups who have a given permission
4648 * @param string $role Role to check
4649 * @return array Array of Strings List of internal group names with the given permission
4651 public static function getGroupsWithPermission( $role ) {
4652 global $wgGroupPermissions;
4653 $allowedGroups = [];
4654 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4655 if ( self::groupHasPermission( $group, $role ) ) {
4656 $allowedGroups[] = $group;
4659 return $allowedGroups;
4663 * Check, if the given group has the given permission
4665 * If you're wanting to check whether all users have a permission, use
4666 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4667 * from anyone.
4669 * @since 1.21
4670 * @param string $group Group to check
4671 * @param string $role Role to check
4672 * @return bool
4674 public static function groupHasPermission( $group, $role ) {
4675 global $wgGroupPermissions, $wgRevokePermissions;
4676 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4677 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4681 * Check if all users may be assumed to have the given permission
4683 * We generally assume so if the right is granted to '*' and isn't revoked
4684 * on any group. It doesn't attempt to take grants or other extension
4685 * limitations on rights into account in the general case, though, as that
4686 * would require it to always return false and defeat the purpose.
4687 * Specifically, session-based rights restrictions (such as OAuth or bot
4688 * passwords) are applied based on the current session.
4690 * @since 1.22
4691 * @param string $right Right to check
4692 * @return bool
4694 public static function isEveryoneAllowed( $right ) {
4695 global $wgGroupPermissions, $wgRevokePermissions;
4696 static $cache = [];
4698 // Use the cached results, except in unit tests which rely on
4699 // being able change the permission mid-request
4700 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4701 return $cache[$right];
4704 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4705 $cache[$right] = false;
4706 return false;
4709 // If it's revoked anywhere, then everyone doesn't have it
4710 foreach ( $wgRevokePermissions as $rights ) {
4711 if ( isset( $rights[$right] ) && $rights[$right] ) {
4712 $cache[$right] = false;
4713 return false;
4717 // Remove any rights that aren't allowed to the global-session user,
4718 // unless there are no sessions for this endpoint.
4719 if ( !defined( 'MW_NO_SESSION' ) ) {
4720 $allowedRights = SessionManager::getGlobalSession()->getAllowedUserRights();
4721 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4722 $cache[$right] = false;
4723 return false;
4727 // Allow extensions to say false
4728 if ( !Hooks::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4729 $cache[$right] = false;
4730 return false;
4733 $cache[$right] = true;
4734 return true;
4738 * Get the localized descriptive name for a group, if it exists
4740 * @param string $group Internal group name
4741 * @return string Localized descriptive group name
4743 public static function getGroupName( $group ) {
4744 $msg = wfMessage( "group-$group" );
4745 return $msg->isBlank() ? $group : $msg->text();
4749 * Get the localized descriptive name for a member of a group, if it exists
4751 * @param string $group Internal group name
4752 * @param string $username Username for gender (since 1.19)
4753 * @return string Localized name for group member
4755 public static function getGroupMember( $group, $username = '#' ) {
4756 $msg = wfMessage( "group-$group-member", $username );
4757 return $msg->isBlank() ? $group : $msg->text();
4761 * Return the set of defined explicit groups.
4762 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4763 * are not included, as they are defined automatically, not in the database.
4764 * @return array Array of internal group names
4766 public static function getAllGroups() {
4767 global $wgGroupPermissions, $wgRevokePermissions;
4768 return array_diff(
4769 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4770 self::getImplicitGroups()
4775 * Get a list of all available permissions.
4776 * @return string[] Array of permission names
4778 public static function getAllRights() {
4779 if ( self::$mAllRights === false ) {
4780 global $wgAvailableRights;
4781 if ( count( $wgAvailableRights ) ) {
4782 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4783 } else {
4784 self::$mAllRights = self::$mCoreRights;
4786 Hooks::run( 'UserGetAllRights', [ &self::$mAllRights ] );
4788 return self::$mAllRights;
4792 * Get a list of implicit groups
4793 * @return array Array of Strings Array of internal group names
4795 public static function getImplicitGroups() {
4796 global $wgImplicitGroups;
4798 $groups = $wgImplicitGroups;
4799 # Deprecated, use $wgImplicitGroups instead
4800 Hooks::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4802 return $groups;
4806 * Get the title of a page describing a particular group
4808 * @param string $group Internal group name
4809 * @return Title|bool Title of the page if it exists, false otherwise
4811 public static function getGroupPage( $group ) {
4812 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4813 if ( $msg->exists() ) {
4814 $title = Title::newFromText( $msg->text() );
4815 if ( is_object( $title ) ) {
4816 return $title;
4819 return false;
4823 * Create a link to the group in HTML, if available;
4824 * else return the group name.
4826 * @param string $group Internal name of the group
4827 * @param string $text The text of the link
4828 * @return string HTML link to the group
4830 public static function makeGroupLinkHTML( $group, $text = '' ) {
4831 if ( $text == '' ) {
4832 $text = self::getGroupName( $group );
4834 $title = self::getGroupPage( $group );
4835 if ( $title ) {
4836 return Linker::link( $title, htmlspecialchars( $text ) );
4837 } else {
4838 return htmlspecialchars( $text );
4843 * Create a link to the group in Wikitext, if available;
4844 * else return the group name.
4846 * @param string $group Internal name of the group
4847 * @param string $text The text of the link
4848 * @return string Wikilink to the group
4850 public static function makeGroupLinkWiki( $group, $text = '' ) {
4851 if ( $text == '' ) {
4852 $text = self::getGroupName( $group );
4854 $title = self::getGroupPage( $group );
4855 if ( $title ) {
4856 $page = $title->getFullText();
4857 return "[[$page|$text]]";
4858 } else {
4859 return $text;
4864 * Returns an array of the groups that a particular group can add/remove.
4866 * @param string $group The group to check for whether it can add/remove
4867 * @return array Array( 'add' => array( addablegroups ),
4868 * 'remove' => array( removablegroups ),
4869 * 'add-self' => array( addablegroups to self),
4870 * 'remove-self' => array( removable groups from self) )
4872 public static function changeableByGroup( $group ) {
4873 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4875 $groups = [
4876 'add' => [],
4877 'remove' => [],
4878 'add-self' => [],
4879 'remove-self' => []
4882 if ( empty( $wgAddGroups[$group] ) ) {
4883 // Don't add anything to $groups
4884 } elseif ( $wgAddGroups[$group] === true ) {
4885 // You get everything
4886 $groups['add'] = self::getAllGroups();
4887 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4888 $groups['add'] = $wgAddGroups[$group];
4891 // Same thing for remove
4892 if ( empty( $wgRemoveGroups[$group] ) ) {
4893 // Do nothing
4894 } elseif ( $wgRemoveGroups[$group] === true ) {
4895 $groups['remove'] = self::getAllGroups();
4896 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4897 $groups['remove'] = $wgRemoveGroups[$group];
4900 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4901 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4902 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4903 if ( is_int( $key ) ) {
4904 $wgGroupsAddToSelf['user'][] = $value;
4909 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4910 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4911 if ( is_int( $key ) ) {
4912 $wgGroupsRemoveFromSelf['user'][] = $value;
4917 // Now figure out what groups the user can add to him/herself
4918 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4919 // Do nothing
4920 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4921 // No idea WHY this would be used, but it's there
4922 $groups['add-self'] = User::getAllGroups();
4923 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4924 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4927 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4928 // Do nothing
4929 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4930 $groups['remove-self'] = User::getAllGroups();
4931 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4932 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4935 return $groups;
4939 * Returns an array of groups that this user can add and remove
4940 * @return array Array( 'add' => array( addablegroups ),
4941 * 'remove' => array( removablegroups ),
4942 * 'add-self' => array( addablegroups to self),
4943 * 'remove-self' => array( removable groups from self) )
4945 public function changeableGroups() {
4946 if ( $this->isAllowed( 'userrights' ) ) {
4947 // This group gives the right to modify everything (reverse-
4948 // compatibility with old "userrights lets you change
4949 // everything")
4950 // Using array_merge to make the groups reindexed
4951 $all = array_merge( User::getAllGroups() );
4952 return [
4953 'add' => $all,
4954 'remove' => $all,
4955 'add-self' => [],
4956 'remove-self' => []
4960 // Okay, it's not so simple, we will have to go through the arrays
4961 $groups = [
4962 'add' => [],
4963 'remove' => [],
4964 'add-self' => [],
4965 'remove-self' => []
4967 $addergroups = $this->getEffectiveGroups();
4969 foreach ( $addergroups as $addergroup ) {
4970 $groups = array_merge_recursive(
4971 $groups, $this->changeableByGroup( $addergroup )
4973 $groups['add'] = array_unique( $groups['add'] );
4974 $groups['remove'] = array_unique( $groups['remove'] );
4975 $groups['add-self'] = array_unique( $groups['add-self'] );
4976 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4978 return $groups;
4982 * Deferred version of incEditCountImmediate()
4984 public function incEditCount() {
4985 wfGetDB( DB_MASTER )->onTransactionPreCommitOrIdle(
4986 function () {
4987 $this->incEditCountImmediate();
4989 __METHOD__
4994 * Increment the user's edit-count field.
4995 * Will have no effect for anonymous users.
4996 * @since 1.26
4998 public function incEditCountImmediate() {
4999 if ( $this->isAnon() ) {
5000 return;
5003 $dbw = wfGetDB( DB_MASTER );
5004 // No rows will be "affected" if user_editcount is NULL
5005 $dbw->update(
5006 'user',
5007 [ 'user_editcount=user_editcount+1' ],
5008 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5009 __METHOD__
5011 // Lazy initialization check...
5012 if ( $dbw->affectedRows() == 0 ) {
5013 // Now here's a goddamn hack...
5014 $dbr = wfGetDB( DB_REPLICA );
5015 if ( $dbr !== $dbw ) {
5016 // If we actually have a replica DB server, the count is
5017 // at least one behind because the current transaction
5018 // has not been committed and replicated.
5019 $this->mEditCount = $this->initEditCount( 1 );
5020 } else {
5021 // But if DB_REPLICA is selecting the master, then the
5022 // count we just read includes the revision that was
5023 // just added in the working transaction.
5024 $this->mEditCount = $this->initEditCount();
5026 } else {
5027 if ( $this->mEditCount === null ) {
5028 $this->getEditCount();
5029 $dbr = wfGetDB( DB_REPLICA );
5030 $this->mEditCount += ( $dbr !== $dbw ) ? 1 : 0;
5031 } else {
5032 $this->mEditCount++;
5035 // Edit count in user cache too
5036 $this->invalidateCache();
5040 * Initialize user_editcount from data out of the revision table
5042 * @param int $add Edits to add to the count from the revision table
5043 * @return int Number of edits
5045 protected function initEditCount( $add = 0 ) {
5046 // Pull from a replica DB to be less cruel to servers
5047 // Accuracy isn't the point anyway here
5048 $dbr = wfGetDB( DB_REPLICA );
5049 $count = (int)$dbr->selectField(
5050 'revision',
5051 'COUNT(rev_user)',
5052 [ 'rev_user' => $this->getId() ],
5053 __METHOD__
5055 $count = $count + $add;
5057 $dbw = wfGetDB( DB_MASTER );
5058 $dbw->update(
5059 'user',
5060 [ 'user_editcount' => $count ],
5061 [ 'user_id' => $this->getId() ],
5062 __METHOD__
5065 return $count;
5069 * Get the description of a given right
5071 * @since 1.29
5072 * @param string $right Right to query
5073 * @return string Localized description of the right
5075 public static function getRightDescription( $right ) {
5076 $key = "right-$right";
5077 $msg = wfMessage( $key );
5078 return $msg->isDisabled() ? $right : $msg->text();
5082 * Get the name of a given grant
5084 * @since 1.29
5085 * @param string $grant Grant to query
5086 * @return string Localized name of the grant
5088 public static function getGrantName( $grant ) {
5089 $key = "grant-$grant";
5090 $msg = wfMessage( $key );
5091 return $msg->isDisabled() ? $grant : $msg->text();
5095 * Make a new-style password hash
5097 * @param string $password Plain-text password
5098 * @param bool|string $salt Optional salt, may be random or the user ID.
5099 * If unspecified or false, will generate one automatically
5100 * @return string Password hash
5101 * @deprecated since 1.24, use Password class
5103 public static function crypt( $password, $salt = false ) {
5104 wfDeprecated( __METHOD__, '1.24' );
5105 $passwordFactory = new PasswordFactory();
5106 $passwordFactory->init( RequestContext::getMain()->getConfig() );
5107 $hash = $passwordFactory->newFromPlaintext( $password );
5108 return $hash->toString();
5112 * Compare a password hash with a plain-text password. Requires the user
5113 * ID if there's a chance that the hash is an old-style hash.
5115 * @param string $hash Password hash
5116 * @param string $password Plain-text password to compare
5117 * @param string|bool $userId User ID for old-style password salt
5119 * @return bool
5120 * @deprecated since 1.24, use Password class
5122 public static function comparePasswords( $hash, $password, $userId = false ) {
5123 wfDeprecated( __METHOD__, '1.24' );
5125 // Check for *really* old password hashes that don't even have a type
5126 // The old hash format was just an md5 hex hash, with no type information
5127 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5128 global $wgPasswordSalt;
5129 if ( $wgPasswordSalt ) {
5130 $password = ":B:{$userId}:{$hash}";
5131 } else {
5132 $password = ":A:{$hash}";
5136 $passwordFactory = new PasswordFactory();
5137 $passwordFactory->init( RequestContext::getMain()->getConfig() );
5138 $hash = $passwordFactory->newFromCiphertext( $hash );
5139 return $hash->equals( $password );
5143 * Add a newuser log entry for this user.
5144 * Before 1.19 the return value was always true.
5146 * @deprecated since 1.27, AuthManager handles logging
5147 * @param string|bool $action Account creation type.
5148 * - String, one of the following values:
5149 * - 'create' for an anonymous user creating an account for himself.
5150 * This will force the action's performer to be the created user itself,
5151 * no matter the value of $wgUser
5152 * - 'create2' for a logged in user creating an account for someone else
5153 * - 'byemail' when the created user will receive its password by e-mail
5154 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5155 * - Boolean means whether the account was created by e-mail (deprecated):
5156 * - true will be converted to 'byemail'
5157 * - false will be converted to 'create' if this object is the same as
5158 * $wgUser and to 'create2' otherwise
5159 * @param string $reason User supplied reason
5160 * @return bool true
5162 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5163 return true; // disabled
5167 * Add an autocreate newuser log entry for this user
5168 * Used by things like CentralAuth and perhaps other authplugins.
5169 * Consider calling addNewUserLogEntry() directly instead.
5171 * @deprecated since 1.27, AuthManager handles logging
5172 * @return bool
5174 public function addNewUserLogEntryAutoCreate() {
5175 $this->addNewUserLogEntry( 'autocreate' );
5177 return true;
5181 * Load the user options either from cache, the database or an array
5183 * @param array $data Rows for the current user out of the user_properties table
5185 protected function loadOptions( $data = null ) {
5186 global $wgContLang;
5188 $this->load();
5190 if ( $this->mOptionsLoaded ) {
5191 return;
5194 $this->mOptions = self::getDefaultOptions();
5196 if ( !$this->getId() ) {
5197 // For unlogged-in users, load language/variant options from request.
5198 // There's no need to do it for logged-in users: they can set preferences,
5199 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5200 // so don't override user's choice (especially when the user chooses site default).
5201 $variant = $wgContLang->getDefaultVariant();
5202 $this->mOptions['variant'] = $variant;
5203 $this->mOptions['language'] = $variant;
5204 $this->mOptionsLoaded = true;
5205 return;
5208 // Maybe load from the object
5209 if ( !is_null( $this->mOptionOverrides ) ) {
5210 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5211 foreach ( $this->mOptionOverrides as $key => $value ) {
5212 $this->mOptions[$key] = $value;
5214 } else {
5215 if ( !is_array( $data ) ) {
5216 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5217 // Load from database
5218 $dbr = ( $this->queryFlagsUsed & self::READ_LATEST )
5219 ? wfGetDB( DB_MASTER )
5220 : wfGetDB( DB_REPLICA );
5222 $res = $dbr->select(
5223 'user_properties',
5224 [ 'up_property', 'up_value' ],
5225 [ 'up_user' => $this->getId() ],
5226 __METHOD__
5229 $this->mOptionOverrides = [];
5230 $data = [];
5231 foreach ( $res as $row ) {
5232 $data[$row->up_property] = $row->up_value;
5235 foreach ( $data as $property => $value ) {
5236 $this->mOptionOverrides[$property] = $value;
5237 $this->mOptions[$property] = $value;
5241 $this->mOptionsLoaded = true;
5243 Hooks::run( 'UserLoadOptions', [ $this, &$this->mOptions ] );
5247 * Saves the non-default options for this user, as previously set e.g. via
5248 * setOption(), in the database's "user_properties" (preferences) table.
5249 * Usually used via saveSettings().
5251 protected function saveOptions() {
5252 $this->loadOptions();
5254 // Not using getOptions(), to keep hidden preferences in database
5255 $saveOptions = $this->mOptions;
5257 // Allow hooks to abort, for instance to save to a global profile.
5258 // Reset options to default state before saving.
5259 if ( !Hooks::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5260 return;
5263 $userId = $this->getId();
5265 $insert_rows = []; // all the new preference rows
5266 foreach ( $saveOptions as $key => $value ) {
5267 // Don't bother storing default values
5268 $defaultOption = self::getDefaultOption( $key );
5269 if ( ( $defaultOption === null && $value !== false && $value !== null )
5270 || $value != $defaultOption
5272 $insert_rows[] = [
5273 'up_user' => $userId,
5274 'up_property' => $key,
5275 'up_value' => $value,
5280 $dbw = wfGetDB( DB_MASTER );
5282 $res = $dbw->select( 'user_properties',
5283 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__ );
5285 // Find prior rows that need to be removed or updated. These rows will
5286 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5287 $keysDelete = [];
5288 foreach ( $res as $row ) {
5289 if ( !isset( $saveOptions[$row->up_property] )
5290 || strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
5292 $keysDelete[] = $row->up_property;
5296 if ( count( $keysDelete ) ) {
5297 // Do the DELETE by PRIMARY KEY for prior rows.
5298 // In the past a very large portion of calls to this function are for setting
5299 // 'rememberpassword' for new accounts (a preference that has since been removed).
5300 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5301 // caused gap locks on [max user ID,+infinity) which caused high contention since
5302 // updates would pile up on each other as they are for higher (newer) user IDs.
5303 // It might not be necessary these days, but it shouldn't hurt either.
5304 $dbw->delete( 'user_properties',
5305 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__ );
5307 // Insert the new preference rows
5308 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, [ 'IGNORE' ] );
5312 * Lazily instantiate and return a factory object for making passwords
5314 * @deprecated since 1.27, create a PasswordFactory directly instead
5315 * @return PasswordFactory
5317 public static function getPasswordFactory() {
5318 wfDeprecated( __METHOD__, '1.27' );
5319 $ret = new PasswordFactory();
5320 $ret->init( RequestContext::getMain()->getConfig() );
5321 return $ret;
5325 * Provide an array of HTML5 attributes to put on an input element
5326 * intended for the user to enter a new password. This may include
5327 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5329 * Do *not* use this when asking the user to enter his current password!
5330 * Regardless of configuration, users may have invalid passwords for whatever
5331 * reason (e.g., they were set before requirements were tightened up).
5332 * Only use it when asking for a new password, like on account creation or
5333 * ResetPass.
5335 * Obviously, you still need to do server-side checking.
5337 * NOTE: A combination of bugs in various browsers means that this function
5338 * actually just returns array() unconditionally at the moment. May as
5339 * well keep it around for when the browser bugs get fixed, though.
5341 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5343 * @deprecated since 1.27
5344 * @return array Array of HTML attributes suitable for feeding to
5345 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5346 * That will get confused by the boolean attribute syntax used.)
5348 public static function passwordChangeInputAttribs() {
5349 global $wgMinimalPasswordLength;
5351 if ( $wgMinimalPasswordLength == 0 ) {
5352 return [];
5355 # Note that the pattern requirement will always be satisfied if the
5356 # input is empty, so we need required in all cases.
5358 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5359 # if e-mail confirmation is being used. Since HTML5 input validation
5360 # is b0rked anyway in some browsers, just return nothing. When it's
5361 # re-enabled, fix this code to not output required for e-mail
5362 # registration.
5363 # $ret = array( 'required' );
5364 $ret = [];
5366 # We can't actually do this right now, because Opera 9.6 will print out
5367 # the entered password visibly in its error message! When other
5368 # browsers add support for this attribute, or Opera fixes its support,
5369 # we can add support with a version check to avoid doing this on Opera
5370 # versions where it will be a problem. Reported to Opera as
5371 # DSK-262266, but they don't have a public bug tracker for us to follow.
5373 if ( $wgMinimalPasswordLength > 1 ) {
5374 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5375 $ret['title'] = wfMessage( 'passwordtooshort' )
5376 ->numParams( $wgMinimalPasswordLength )->text();
5380 return $ret;
5384 * Return the list of user fields that should be selected to create
5385 * a new user object.
5386 * @return array
5388 public static function selectFields() {
5389 return [
5390 'user_id',
5391 'user_name',
5392 'user_real_name',
5393 'user_email',
5394 'user_touched',
5395 'user_token',
5396 'user_email_authenticated',
5397 'user_email_token',
5398 'user_email_token_expires',
5399 'user_registration',
5400 'user_editcount',
5405 * Factory function for fatal permission-denied errors
5407 * @since 1.22
5408 * @param string $permission User right required
5409 * @return Status
5411 static function newFatalPermissionDeniedStatus( $permission ) {
5412 global $wgLang;
5414 $groups = array_map(
5415 [ 'User', 'makeGroupLinkWiki' ],
5416 User::getGroupsWithPermission( $permission )
5419 if ( $groups ) {
5420 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5421 } else {
5422 return Status::newFatal( 'badaccess-group0' );
5427 * Get a new instance of this user that was loaded from the master via a locking read
5429 * Use this instead of the main context User when updating that user. This avoids races
5430 * where that user was loaded from a replica DB or even the master but without proper locks.
5432 * @return User|null Returns null if the user was not found in the DB
5433 * @since 1.27
5435 public function getInstanceForUpdate() {
5436 if ( !$this->getId() ) {
5437 return null; // anon
5440 $user = self::newFromId( $this->getId() );
5441 if ( !$user->loadFromId( self::READ_EXCLUSIVE ) ) {
5442 return null;
5445 return $user;
5449 * Checks if two user objects point to the same user.
5451 * @since 1.25
5452 * @param User $user
5453 * @return bool
5455 public function equals( User $user ) {
5456 return $this->getName() === $user->getName();