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
23 use MediaWiki\Session\SessionManager
;
26 * String Some punctuation to prevent editing from broken text-mangling proxies.
27 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::SUFFIX
30 define( 'EDIT_TOKEN_SUFFIX', MediaWiki\Session\Token
::SUFFIX
);
33 * The User object encapsulates all of the user-specific settings (user_id,
34 * name, rights, email address, options, last login time). Client
35 * classes use the getXXX() functions to access these fields. These functions
36 * do all the work of determining whether the user is logged in,
37 * whether the requested option can be satisfied from cookies or
38 * whether a database query is needed. Most of the settings needed
39 * for rendering normal pages are set in the cookie to minimize use
42 class User
implements IDBAccessObject
{
44 * @const int Number of characters in user_token field.
46 const TOKEN_LENGTH
= 32;
49 * @const string An invalid value for user_token
51 const INVALID_TOKEN
= '*** INVALID ***';
54 * Global constant made accessible as class constants so that autoloader
56 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::SUFFIX
58 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
61 * @const int Serialized record version.
66 * Exclude user options that are set to their default value.
69 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
74 const CHECK_USER_RIGHTS
= true;
79 const IGNORE_USER_RIGHTS
= false;
82 * Array of Strings List of member variables which are saved to the
83 * shared cache (memcached). Any operation which changes the
84 * corresponding database fields must call a cache-clearing function.
87 protected static $mCacheVars = [
95 'mEmailAuthenticated',
102 // user_properties table
107 * Array of Strings Core rights.
108 * Each of these should have a corresponding message of the form
112 protected static $mCoreRights = [
142 'editusercssjs', # deprecated
155 'move-categorypages',
156 'move-rootuserpages',
160 'override-export-depth',
183 'userrights-interwiki',
191 * String Cached results of getAllRights()
193 protected static $mAllRights = false;
196 * An in-process cache for user data lookup
199 protected static $inProcessCache;
201 /** Cache variables */
212 /** @var string TS_MW timestamp from the DB */
214 /** @var string TS_MW timestamp from cache */
215 protected $mQuickTouched;
219 public $mEmailAuthenticated;
221 protected $mEmailToken;
223 protected $mEmailTokenExpires;
225 protected $mRegistration;
227 protected $mEditCount;
231 protected $mOptionOverrides;
235 * Bool Whether the cache variables have been loaded.
238 public $mOptionsLoaded;
241 * Array with already loaded items or true if all items have been loaded.
243 protected $mLoadedItems = [];
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.
258 * Lazy-initialized variables, invalidated with clearInstanceCache
262 protected $mDatePreference;
270 protected $mBlockreason;
272 protected $mEffectiveGroups;
274 protected $mImplicitGroups;
276 protected $mFormerGroups;
278 protected $mBlockedGlobally;
295 protected $mAllowUsertalk;
298 private $mBlockedFromCreateAccount = false;
300 /** @var integer User::READ_* constant bitfield used to load data */
301 protected $queryFlagsUsed = self
::READ_NORMAL
;
303 public static $idCacheByName = [];
306 * Lightweight constructor for an anonymous user.
307 * Use the User::newFrom* factory functions for other kinds of users.
311 * @see newFromConfirmationCode()
312 * @see newFromSession()
315 public function __construct() {
316 $this->clearInstanceCache( 'defaults' );
322 public function __toString() {
323 return $this->getName();
327 * Test if it's safe to load this User object.
329 * You should typically check this before using $wgUser or
330 * RequestContext::getUser in a method that might be called before the
331 * system has been fully initialized. If the object is unsafe, you should
332 * use an anonymous user:
334 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
340 public function isSafeToLoad() {
341 global $wgFullyInitialised;
343 // The user is safe to load if:
344 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
345 // * mLoadedItems === true (already loaded)
346 // * mFrom !== 'session' (sessions not involved at all)
348 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
349 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
353 * Load the user table data for this object from the source given by mFrom.
355 * @param integer $flags User::READ_* constant bitfield
357 public function load( $flags = self
::READ_NORMAL
) {
358 global $wgFullyInitialised;
360 if ( $this->mLoadedItems
=== true ) {
364 // Set it now to avoid infinite recursion in accessors
365 $oldLoadedItems = $this->mLoadedItems
;
366 $this->mLoadedItems
= true;
367 $this->queryFlagsUsed
= $flags;
369 // If this is called too early, things are likely to break.
370 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
371 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
372 ->warning( 'User::loadFromSession called before the end of Setup.php', [
373 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
375 $this->loadDefaults();
376 $this->mLoadedItems
= $oldLoadedItems;
380 switch ( $this->mFrom
) {
382 $this->loadDefaults();
385 // Make sure this thread sees its own changes
386 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
387 $flags |
= self
::READ_LATEST
;
388 $this->queryFlagsUsed
= $flags;
391 $this->mId
= self
::idFromName( $this->mName
, $flags );
393 // Nonexistent user placeholder object
394 $this->loadDefaults( $this->mName
);
396 $this->loadFromId( $flags );
400 $this->loadFromId( $flags );
403 if ( !$this->loadFromSession() ) {
404 // Loading from session failed. Load defaults.
405 $this->loadDefaults();
407 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
410 throw new UnexpectedValueException(
411 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
416 * Load user table data, given mId has already been set.
417 * @param integer $flags User::READ_* constant bitfield
418 * @return bool False if the ID does not exist, true otherwise
420 public function loadFromId( $flags = self
::READ_NORMAL
) {
421 if ( $this->mId
== 0 ) {
422 $this->loadDefaults();
426 // Try cache (unless this needs data from the master DB).
427 // NOTE: if this thread called saveSettings(), the cache was cleared.
428 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
429 if ( $latest ||
!$this->loadFromCache() ) {
430 wfDebug( "User: cache miss for user {$this->mId}\n" );
431 // Load from DB (make sure this thread sees its own changes)
432 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
433 $flags |
= self
::READ_LATEST
;
435 if ( !$this->loadFromDatabase( $flags ) ) {
436 // Can't load from ID, user is anonymous
439 $this->saveToCache();
442 $this->mLoadedItems
= true;
443 $this->queryFlagsUsed
= $flags;
450 * @param string $wikiId
451 * @param integer $userId
453 public static function purge( $wikiId, $userId ) {
454 $cache = ObjectCache
::getMainWANInstance();
455 $processCache = self
::getInProcessCache();
456 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
457 $cache->delete( $key );
458 $processCache->delete( $key );
463 * @param WANObjectCache $cache
466 protected function getCacheKey( WANObjectCache
$cache ) {
467 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
472 * @return HashBagOStuff
474 protected static function getInProcessCache() {
475 if ( !self
::$inProcessCache ) {
476 self
::$inProcessCache = new HashBagOStuff( ['maxKeys' => 10] );
478 return self
::$inProcessCache;
482 * Load user data from shared cache, given mId has already been set.
484 * @return bool false if the ID does not exist or data is invalid, true otherwise
487 protected function loadFromCache() {
488 if ( $this->mId
== 0 ) {
489 $this->loadDefaults();
493 $cache = ObjectCache
::getMainWANInstance();
494 $processCache = self
::getInProcessCache();
495 $key = $this->getCacheKey( $cache );
496 $data = $processCache->get( $key );
497 if ( !is_array( $data ) ) {
498 $data = $cache->get( $key );
499 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
503 $processCache->set( $key, $data );
505 wfDebug( "User: got user {$this->mId} from cache\n" );
507 // Restore from cache
508 foreach ( self
::$mCacheVars as $name ) {
509 $this->$name = $data[$name];
516 * Save user data to the shared cache
518 * This method should not be called outside the User class
520 public function saveToCache() {
523 $this->loadOptions();
525 if ( $this->isAnon() ) {
526 // Anonymous users are uncached
531 foreach ( self
::$mCacheVars as $name ) {
532 $data[$name] = $this->$name;
534 $data['mVersion'] = self
::VERSION
;
535 $opts = Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
537 $cache = ObjectCache
::getMainWANInstance();
538 $processCache = self
::getInProcessCache();
539 $key = $this->getCacheKey( $cache );
540 $cache->set( $key, $data, $cache::TTL_HOUR
, $opts );
541 $processCache->set( $key, $data );
544 /** @name newFrom*() static factory methods */
548 * Static factory method for creation from username.
550 * This is slightly less efficient than newFromId(), so use newFromId() if
551 * you have both an ID and a name handy.
553 * @param string $name Username, validated by Title::newFromText()
554 * @param string|bool $validate Validate username. Takes the same parameters as
555 * User::getCanonicalName(), except that true is accepted as an alias
556 * for 'valid', for BC.
558 * @return User|bool User object, or false if the username is invalid
559 * (e.g. if it contains illegal characters or is an IP address). If the
560 * username is not present in the database, the result will be a user object
561 * with a name, zero user ID and default settings.
563 public static function newFromName( $name, $validate = 'valid' ) {
564 if ( $validate === true ) {
567 $name = self
::getCanonicalName( $name, $validate );
568 if ( $name === false ) {
571 // Create unloaded user object
575 $u->setItemLoaded( 'name' );
581 * Static factory method for creation from a given user ID.
583 * @param int $id Valid user ID
584 * @return User The corresponding User object
586 public static function newFromId( $id ) {
590 $u->setItemLoaded( 'id' );
595 * Factory method to fetch whichever user has a given email confirmation code.
596 * This code is generated when an account is created or its e-mail address
599 * If the code is invalid or has expired, returns NULL.
601 * @param string $code Confirmation code
602 * @param int $flags User::READ_* bitfield
605 public static function newFromConfirmationCode( $code, $flags = 0 ) {
606 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
607 ?
wfGetDB( DB_MASTER
)
608 : wfGetDB( DB_SLAVE
);
610 $id = $db->selectField(
614 'user_email_token' => md5( $code ),
615 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
619 return $id ? User
::newFromId( $id ) : null;
623 * Create a new user object using data from session. If the login
624 * credentials are invalid, the result is an anonymous user.
626 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
629 public static function newFromSession( WebRequest
$request = null ) {
631 $user->mFrom
= 'session';
632 $user->mRequest
= $request;
637 * Create a new user object from a user row.
638 * The row should have the following fields from the user table in it:
639 * - either user_name or user_id to load further data if needed (or both)
641 * - all other fields (email, etc.)
642 * It is useless to provide the remaining fields if either user_id,
643 * user_name and user_real_name are not provided because the whole row
644 * will be loaded once more from the database when accessing them.
646 * @param stdClass $row A row from the user table
647 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
650 public static function newFromRow( $row, $data = null ) {
652 $user->loadFromRow( $row, $data );
657 * Static factory method for creation of a "system" user from username.
659 * A "system" user is an account that's used to attribute logged actions
660 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
661 * might include the 'Maintenance script' or 'Conversion script' accounts
662 * used by various scripts in the maintenance/ directory or accounts such
663 * as 'MediaWiki message delivery' used by the MassMessage extension.
665 * This can optionally create the user if it doesn't exist, and "steal" the
666 * account if it does exist.
668 * @param string $name Username
669 * @param array $options Options are:
670 * - validate: As for User::getCanonicalName(), default 'valid'
671 * - create: Whether to create the user if it doesn't already exist, default true
672 * - steal: Whether to reset the account's password and email if it
673 * already exists, default false
676 public static function newSystemUser( $name, $options = [] ) {
678 'validate' => 'valid',
683 $name = self
::getCanonicalName( $name, $options['validate'] );
684 if ( $name === false ) {
688 $dbw = wfGetDB( DB_MASTER
);
689 $row = $dbw->selectRow(
692 self
::selectFields(),
693 [ 'user_password', 'user_newpassword' ]
695 [ 'user_name' => $name ],
699 // No user. Create it?
700 return $options['create'] ? self
::createNew( $name ) : null;
702 $user = self
::newFromRow( $row );
704 // A user is considered to exist as a non-system user if it has a
705 // password set, or a temporary password set, or an email set, or a
706 // non-invalid token.
707 $passwordFactory = new PasswordFactory();
708 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
710 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
711 } catch ( PasswordError
$e ) {
712 wfDebug( 'Invalid password hash found in database.' );
713 $password = PasswordFactory
::newInvalidPassword();
716 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
717 } catch ( PasswordError
$e ) {
718 wfDebug( 'Invalid password hash found in database.' );
719 $newpassword = PasswordFactory
::newInvalidPassword();
721 if ( !$password instanceof InvalidPassword ||
!$newpassword instanceof InvalidPassword
722 ||
$user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN
724 // User exists. Steal it?
725 if ( !$options['steal'] ) {
729 $nopass = PasswordFactory
::newInvalidPassword()->toString();
734 'user_password' => $nopass,
735 'user_newpassword' => $nopass,
736 'user_newpass_time' => null,
738 [ 'user_id' => $user->getId() ],
741 $user->invalidateEmail();
742 $user->mToken
= self
::INVALID_TOKEN
;
743 $user->saveSettings();
744 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
753 * Get the username corresponding to a given user ID
754 * @param int $id User ID
755 * @return string|bool The corresponding username
757 public static function whoIs( $id ) {
758 return UserCache
::singleton()->getProp( $id, 'name' );
762 * Get the real name of a user given their user ID
764 * @param int $id User ID
765 * @return string|bool The corresponding user's real name
767 public static function whoIsReal( $id ) {
768 return UserCache
::singleton()->getProp( $id, 'real_name' );
772 * Get database id given a user name
773 * @param string $name Username
774 * @param integer $flags User::READ_* constant bitfield
775 * @return int|null The corresponding user's ID, or null if user is nonexistent
777 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
778 $nt = Title
::makeTitleSafe( NS_USER
, $name );
779 if ( is_null( $nt ) ) {
784 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
785 return self
::$idCacheByName[$name];
788 $db = ( $flags & self
::READ_LATEST
)
789 ?
wfGetDB( DB_MASTER
)
790 : wfGetDB( DB_SLAVE
);
795 [ 'user_name' => $nt->getText() ],
799 if ( $s === false ) {
802 $result = $s->user_id
;
805 self
::$idCacheByName[$name] = $result;
807 if ( count( self
::$idCacheByName ) > 1000 ) {
808 self
::$idCacheByName = [];
815 * Reset the cache used in idFromName(). For use in tests.
817 public static function resetIdByNameCache() {
818 self
::$idCacheByName = [];
822 * Does the string match an anonymous IPv4 address?
824 * This function exists for username validation, in order to reject
825 * usernames which are similar in form to IP addresses. Strings such
826 * as 300.300.300.300 will return true because it looks like an IP
827 * address, despite not being strictly valid.
829 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
830 * address because the usemod software would "cloak" anonymous IP
831 * addresses like this, if we allowed accounts like this to be created
832 * new users could get the old edits of these anonymous users.
834 * @param string $name Name to match
837 public static function isIP( $name ) {
838 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
839 || IP
::isIPv6( $name );
843 * Is the input a valid username?
845 * Checks if the input is a valid username, we don't want an empty string,
846 * an IP address, anything that contains slashes (would mess up subpages),
847 * is longer than the maximum allowed username size or doesn't begin with
850 * @param string $name Name to match
853 public static function isValidUserName( $name ) {
854 global $wgContLang, $wgMaxNameChars;
857 || User
::isIP( $name )
858 ||
strpos( $name, '/' ) !== false
859 ||
strlen( $name ) > $wgMaxNameChars
860 ||
$name != $wgContLang->ucfirst( $name )
865 // Ensure that the name can't be misresolved as a different title,
866 // such as with extra namespace keys at the start.
867 $parsed = Title
::newFromText( $name );
868 if ( is_null( $parsed )
869 ||
$parsed->getNamespace()
870 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
874 // Check an additional blacklist of troublemaker characters.
875 // Should these be merged into the title char list?
876 $unicodeBlacklist = '/[' .
877 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
878 '\x{00a0}' . # non-breaking space
879 '\x{2000}-\x{200f}' . # various whitespace
880 '\x{2028}-\x{202f}' . # breaks and control chars
881 '\x{3000}' . # ideographic space
882 '\x{e000}-\x{f8ff}' . # private use
884 if ( preg_match( $unicodeBlacklist, $name ) ) {
892 * Usernames which fail to pass this function will be blocked
893 * from user login and new account registrations, but may be used
894 * internally by batch processes.
896 * If an account already exists in this form, login will be blocked
897 * by a failure to pass this function.
899 * @param string $name Name to match
902 public static function isUsableName( $name ) {
903 global $wgReservedUsernames;
904 // Must be a valid username, obviously ;)
905 if ( !self
::isValidUserName( $name ) ) {
909 static $reservedUsernames = false;
910 if ( !$reservedUsernames ) {
911 $reservedUsernames = $wgReservedUsernames;
912 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
915 // Certain names may be reserved for batch processes.
916 foreach ( $reservedUsernames as $reserved ) {
917 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
918 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
920 if ( $reserved == $name ) {
928 * Usernames which fail to pass this function will be blocked
929 * from new account registrations, but may be used internally
930 * either by batch processes or by user accounts which have
931 * already been created.
933 * Additional blacklisting may be added here rather than in
934 * isValidUserName() to avoid disrupting existing accounts.
936 * @param string $name String to match
939 public static function isCreatableName( $name ) {
940 global $wgInvalidUsernameCharacters;
942 // Ensure that the username isn't longer than 235 bytes, so that
943 // (at least for the builtin skins) user javascript and css files
944 // will work. (bug 23080)
945 if ( strlen( $name ) > 235 ) {
946 wfDebugLog( 'username', __METHOD__
.
947 ": '$name' invalid due to length" );
951 // Preg yells if you try to give it an empty string
952 if ( $wgInvalidUsernameCharacters !== '' ) {
953 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
954 wfDebugLog( 'username', __METHOD__
.
955 ": '$name' invalid due to wgInvalidUsernameCharacters" );
960 return self
::isUsableName( $name );
964 * Is the input a valid password for this user?
966 * @param string $password Desired password
969 public function isValidPassword( $password ) {
970 // simple boolean wrapper for getPasswordValidity
971 return $this->getPasswordValidity( $password ) === true;
975 * Given unvalidated password input, return error message on failure.
977 * @param string $password Desired password
978 * @return bool|string|array True on success, string or array of error message on failure
980 public function getPasswordValidity( $password ) {
981 $result = $this->checkPasswordValidity( $password );
982 if ( $result->isGood() ) {
986 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
987 $messages[] = $error['message'];
989 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
990 $messages[] = $warning['message'];
992 if ( count( $messages ) === 1 ) {
1000 * Check if this is a valid password for this user
1002 * Create a Status object based on the password's validity.
1003 * The Status should be set to fatal if the user should not
1004 * be allowed to log in, and should have any errors that
1005 * would block changing the password.
1007 * If the return value of this is not OK, the password
1008 * should not be checked. If the return value is not Good,
1009 * the password can be checked, but the user should not be
1010 * able to set their password to this.
1012 * @param string $password Desired password
1013 * @param string $purpose one of 'login', 'create', 'reset'
1017 public function checkPasswordValidity( $password, $purpose = 'login' ) {
1018 global $wgPasswordPolicy;
1020 $upp = new UserPasswordPolicy(
1021 $wgPasswordPolicy['policies'],
1022 $wgPasswordPolicy['checks']
1025 $status = Status
::newGood();
1026 $result = false; // init $result to false for the internal checks
1028 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1029 $status->error( $result );
1033 if ( $result === false ) {
1034 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
1036 } elseif ( $result === true ) {
1039 $status->error( $result );
1040 return $status; // the isValidPassword hook set a string $result and returned true
1045 * Given unvalidated user input, return a canonical username, or false if
1046 * the username is invalid.
1047 * @param string $name User input
1048 * @param string|bool $validate Type of validation to use:
1049 * - false No validation
1050 * - 'valid' Valid for batch processes
1051 * - 'usable' Valid for batch processes and login
1052 * - 'creatable' Valid for batch processes, login and account creation
1054 * @throws InvalidArgumentException
1055 * @return bool|string
1057 public static function getCanonicalName( $name, $validate = 'valid' ) {
1058 // Force usernames to capital
1060 $name = $wgContLang->ucfirst( $name );
1062 # Reject names containing '#'; these will be cleaned up
1063 # with title normalisation, but then it's too late to
1065 if ( strpos( $name, '#' ) !== false ) {
1069 // Clean up name according to title rules,
1070 // but only when validation is requested (bug 12654)
1071 $t = ( $validate !== false ) ?
1072 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
1073 // Check for invalid titles
1074 if ( is_null( $t ) ) {
1078 // Reject various classes of invalid names
1080 $name = $wgAuth->getCanonicalName( $t->getText() );
1082 switch ( $validate ) {
1086 if ( !User
::isValidUserName( $name ) ) {
1091 if ( !User
::isUsableName( $name ) ) {
1096 if ( !User
::isCreatableName( $name ) ) {
1101 throw new InvalidArgumentException(
1102 'Invalid parameter value for $validate in ' . __METHOD__
);
1108 * Count the number of edits of a user
1110 * @param int $uid User ID to check
1111 * @return int The user's edit count
1113 * @deprecated since 1.21 in favour of User::getEditCount
1115 public static function edits( $uid ) {
1116 wfDeprecated( __METHOD__
, '1.21' );
1117 $user = self
::newFromId( $uid );
1118 return $user->getEditCount();
1122 * Return a random password.
1124 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1125 * @return string New random password
1127 public static function randomPassword() {
1128 global $wgMinimalPasswordLength;
1129 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1133 * Set cached properties to default.
1135 * @note This no longer clears uncached lazy-initialised properties;
1136 * the constructor does that instead.
1138 * @param string|bool $name
1140 public function loadDefaults( $name = false ) {
1142 $this->mName
= $name;
1143 $this->mRealName
= '';
1145 $this->mOptionOverrides
= null;
1146 $this->mOptionsLoaded
= false;
1148 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1149 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1150 if ( $loggedOut !== 0 ) {
1151 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1153 $this->mTouched
= '1'; # Allow any pages to be cached
1156 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1157 $this->mEmailAuthenticated
= null;
1158 $this->mEmailToken
= '';
1159 $this->mEmailTokenExpires
= null;
1160 $this->mRegistration
= wfTimestamp( TS_MW
);
1161 $this->mGroups
= [];
1163 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1167 * Return whether an item has been loaded.
1169 * @param string $item Item to check. Current possibilities:
1173 * @param string $all 'all' to check if the whole object has been loaded
1174 * or any other string to check if only the item is available (e.g.
1178 public function isItemLoaded( $item, $all = 'all' ) {
1179 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1180 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1184 * Set that an item has been loaded
1186 * @param string $item
1188 protected function setItemLoaded( $item ) {
1189 if ( is_array( $this->mLoadedItems
) ) {
1190 $this->mLoadedItems
[$item] = true;
1195 * Load user data from the session.
1197 * @return bool True if the user is logged in, false otherwise.
1199 private function loadFromSession() {
1202 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1203 if ( $result !== null ) {
1207 // MediaWiki\Session\Session already did the necessary authentication of the user
1208 // returned here, so just use it if applicable.
1209 $session = $this->getRequest()->getSession();
1210 $user = $session->getUser();
1211 if ( $user->isLoggedIn() ) {
1212 $this->loadFromUserObject( $user );
1213 // Other code expects these to be set in the session, so set them.
1214 $session->set( 'wsUserID', $this->getId() );
1215 $session->set( 'wsUserName', $this->getName() );
1216 $session->set( 'wsToken', $this->getToken() );
1224 * Load user and user_group data from the database.
1225 * $this->mId must be set, this is how the user is identified.
1227 * @param integer $flags User::READ_* constant bitfield
1228 * @return bool True if the user exists, false if the user is anonymous
1230 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1232 $this->mId
= intval( $this->mId
);
1235 if ( !$this->mId
) {
1236 $this->loadDefaults();
1240 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1241 $db = wfGetDB( $index );
1243 $s = $db->selectRow(
1245 self
::selectFields(),
1246 [ 'user_id' => $this->mId
],
1251 $this->queryFlagsUsed
= $flags;
1252 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1254 if ( $s !== false ) {
1255 // Initialise user table data
1256 $this->loadFromRow( $s );
1257 $this->mGroups
= null; // deferred
1258 $this->getEditCount(); // revalidation for nulls
1263 $this->loadDefaults();
1269 * Initialize this object from a row from the user table.
1271 * @param stdClass $row Row from the user table to load.
1272 * @param array $data Further user data to load into the object
1274 * user_groups Array with groups out of the user_groups table
1275 * user_properties Array with properties out of the user_properties table
1277 protected function loadFromRow( $row, $data = null ) {
1280 $this->mGroups
= null; // deferred
1282 if ( isset( $row->user_name
) ) {
1283 $this->mName
= $row->user_name
;
1284 $this->mFrom
= 'name';
1285 $this->setItemLoaded( 'name' );
1290 if ( isset( $row->user_real_name
) ) {
1291 $this->mRealName
= $row->user_real_name
;
1292 $this->setItemLoaded( 'realname' );
1297 if ( isset( $row->user_id
) ) {
1298 $this->mId
= intval( $row->user_id
);
1299 $this->mFrom
= 'id';
1300 $this->setItemLoaded( 'id' );
1305 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1306 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1309 if ( isset( $row->user_editcount
) ) {
1310 $this->mEditCount
= $row->user_editcount
;
1315 if ( isset( $row->user_touched
) ) {
1316 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1321 if ( isset( $row->user_token
) ) {
1322 // The definition for the column is binary(32), so trim the NULs
1323 // that appends. The previous definition was char(32), so trim
1325 $this->mToken
= rtrim( $row->user_token
, " \0" );
1326 if ( $this->mToken
=== '' ) {
1327 $this->mToken
= null;
1333 if ( isset( $row->user_email
) ) {
1334 $this->mEmail
= $row->user_email
;
1335 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1336 $this->mEmailToken
= $row->user_email_token
;
1337 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1338 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1344 $this->mLoadedItems
= true;
1347 if ( is_array( $data ) ) {
1348 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1349 $this->mGroups
= $data['user_groups'];
1351 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1352 $this->loadOptions( $data['user_properties'] );
1358 * Load the data for this user object from another user object.
1362 protected function loadFromUserObject( $user ) {
1364 $user->loadGroups();
1365 $user->loadOptions();
1366 foreach ( self
::$mCacheVars as $var ) {
1367 $this->$var = $user->$var;
1372 * Load the groups from the database if they aren't already loaded.
1374 private function loadGroups() {
1375 if ( is_null( $this->mGroups
) ) {
1376 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1377 ?
wfGetDB( DB_MASTER
)
1378 : wfGetDB( DB_SLAVE
);
1379 $res = $db->select( 'user_groups',
1381 [ 'ug_user' => $this->mId
],
1383 $this->mGroups
= [];
1384 foreach ( $res as $row ) {
1385 $this->mGroups
[] = $row->ug_group
;
1391 * Add the user to the group if he/she meets given criteria.
1393 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1394 * possible to remove manually via Special:UserRights. In such case it
1395 * will not be re-added automatically. The user will also not lose the
1396 * group if they no longer meet the criteria.
1398 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1400 * @return array Array of groups the user has been promoted to.
1402 * @see $wgAutopromoteOnce
1404 public function addAutopromoteOnceGroups( $event ) {
1405 global $wgAutopromoteOnceLogInRC, $wgAuth;
1407 if ( wfReadOnly() ||
!$this->getId() ) {
1411 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1412 if ( !count( $toPromote ) ) {
1416 if ( !$this->checkAndSetTouched() ) {
1417 return []; // raced out (bug T48834)
1420 $oldGroups = $this->getGroups(); // previous groups
1421 foreach ( $toPromote as $group ) {
1422 $this->addGroup( $group );
1424 // update groups in external authentication database
1425 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1426 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1428 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1430 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1431 $logEntry->setPerformer( $this );
1432 $logEntry->setTarget( $this->getUserPage() );
1433 $logEntry->setParameters( [
1434 '4::oldgroups' => $oldGroups,
1435 '5::newgroups' => $newGroups,
1437 $logid = $logEntry->insert();
1438 if ( $wgAutopromoteOnceLogInRC ) {
1439 $logEntry->publish( $logid );
1446 * Bump user_touched if it didn't change since this object was loaded
1448 * On success, the mTouched field is updated.
1449 * The user serialization cache is always cleared.
1451 * @return bool Whether user_touched was actually updated
1454 protected function checkAndSetTouched() {
1457 if ( !$this->mId
) {
1458 return false; // anon
1461 // Get a new user_touched that is higher than the old one
1462 $oldTouched = $this->mTouched
;
1463 $newTouched = $this->newTouchedTimestamp();
1465 $dbw = wfGetDB( DB_MASTER
);
1466 $dbw->update( 'user',
1467 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1469 'user_id' => $this->mId
,
1470 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1474 $success = ( $dbw->affectedRows() > 0 );
1477 $this->mTouched
= $newTouched;
1478 $this->clearSharedCache();
1480 // Clears on failure too since that is desired if the cache is stale
1481 $this->clearSharedCache( 'refresh' );
1488 * Clear various cached data stored in this object. The cache of the user table
1489 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1491 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1492 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1494 public function clearInstanceCache( $reloadFrom = false ) {
1495 $this->mNewtalk
= -1;
1496 $this->mDatePreference
= null;
1497 $this->mBlockedby
= -1; # Unset
1498 $this->mHash
= false;
1499 $this->mRights
= null;
1500 $this->mEffectiveGroups
= null;
1501 $this->mImplicitGroups
= null;
1502 $this->mGroups
= null;
1503 $this->mOptions
= null;
1504 $this->mOptionsLoaded
= false;
1505 $this->mEditCount
= null;
1507 if ( $reloadFrom ) {
1508 $this->mLoadedItems
= [];
1509 $this->mFrom
= $reloadFrom;
1514 * Combine the language default options with any site-specific options
1515 * and add the default language variants.
1517 * @return array Array of String options
1519 public static function getDefaultOptions() {
1520 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1522 static $defOpt = null;
1523 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1524 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1525 // mid-request and see that change reflected in the return value of this function.
1526 // Which is insane and would never happen during normal MW operation
1530 $defOpt = $wgDefaultUserOptions;
1531 // Default language setting
1532 $defOpt['language'] = $wgContLang->getCode();
1533 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1534 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1536 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1537 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1539 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1541 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1547 * Get a given default option value.
1549 * @param string $opt Name of option to retrieve
1550 * @return string Default option value
1552 public static function getDefaultOption( $opt ) {
1553 $defOpts = self
::getDefaultOptions();
1554 if ( isset( $defOpts[$opt] ) ) {
1555 return $defOpts[$opt];
1562 * Get blocking information
1563 * @param bool $bFromSlave Whether to check the slave database first.
1564 * To improve performance, non-critical checks are done against slaves.
1565 * Check when actually saving should be done against master.
1567 private function getBlockedStatus( $bFromSlave = true ) {
1568 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1570 if ( -1 != $this->mBlockedby
) {
1574 wfDebug( __METHOD__
. ": checking...\n" );
1576 // Initialize data...
1577 // Otherwise something ends up stomping on $this->mBlockedby when
1578 // things get lazy-loaded later, causing false positive block hits
1579 // due to -1 !== 0. Probably session-related... Nothing should be
1580 // overwriting mBlockedby, surely?
1583 # We only need to worry about passing the IP address to the Block generator if the
1584 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1585 # know which IP address they're actually coming from
1587 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1588 // $wgUser->getName() only works after the end of Setup.php. Until
1589 // then, assume it's a logged-out user.
1590 $globalUserName = $wgUser->isSafeToLoad()
1591 ?
$wgUser->getName()
1592 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1593 if ( $this->getName() === $globalUserName ) {
1594 $ip = $this->getRequest()->getIP();
1599 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1602 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1604 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1606 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1607 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1608 $block->setTarget( $ip );
1609 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1611 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1612 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1613 $block->setTarget( $ip );
1617 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1618 if ( !$block instanceof Block
1619 && $wgApplyIpBlocksToXff
1621 && !in_array( $ip, $wgProxyWhitelist )
1623 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1624 $xff = array_map( 'trim', explode( ',', $xff ) );
1625 $xff = array_diff( $xff, [ $ip ] );
1626 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1627 $block = Block
::chooseBlock( $xffblocks, $xff );
1628 if ( $block instanceof Block
) {
1629 # Mangle the reason to alert the user that the block
1630 # originated from matching the X-Forwarded-For header.
1631 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1635 if ( $block instanceof Block
) {
1636 wfDebug( __METHOD__
. ": Found block.\n" );
1637 $this->mBlock
= $block;
1638 $this->mBlockedby
= $block->getByName();
1639 $this->mBlockreason
= $block->mReason
;
1640 $this->mHideName
= $block->mHideName
;
1641 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1643 $this->mBlockedby
= '';
1644 $this->mHideName
= 0;
1645 $this->mAllowUsertalk
= false;
1649 Hooks
::run( 'GetBlockedStatus', [ &$this ] );
1654 * Whether the given IP is in a DNS blacklist.
1656 * @param string $ip IP to check
1657 * @param bool $checkWhitelist Whether to check the whitelist first
1658 * @return bool True if blacklisted.
1660 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1661 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1663 if ( !$wgEnableDnsBlacklist ) {
1667 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1671 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1675 * Whether the given IP is in a given DNS blacklist.
1677 * @param string $ip IP to check
1678 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1679 * @return bool True if blacklisted.
1681 public function inDnsBlacklist( $ip, $bases ) {
1684 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1685 if ( IP
::isIPv4( $ip ) ) {
1686 // Reverse IP, bug 21255
1687 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1689 foreach ( (array)$bases as $base ) {
1691 // If we have an access key, use that too (ProjectHoneypot, etc.)
1693 if ( is_array( $base ) ) {
1694 if ( count( $base ) >= 2 ) {
1695 // Access key is 1, base URL is 0
1696 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1698 $host = "$ipReversed.{$base[0]}";
1700 $basename = $base[0];
1702 $host = "$ipReversed.$base";
1706 $ipList = gethostbynamel( $host );
1709 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1713 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1722 * Check if an IP address is in the local proxy list
1728 public static function isLocallyBlockedProxy( $ip ) {
1729 global $wgProxyList;
1731 if ( !$wgProxyList ) {
1735 if ( !is_array( $wgProxyList ) ) {
1736 // Load from the specified file
1737 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1740 if ( !is_array( $wgProxyList ) ) {
1742 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1744 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1745 // Old-style flipped proxy list
1754 * Is this user subject to rate limiting?
1756 * @return bool True if rate limited
1758 public function isPingLimitable() {
1759 global $wgRateLimitsExcludedIPs;
1760 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1761 // No other good way currently to disable rate limits
1762 // for specific IPs. :P
1763 // But this is a crappy hack and should die.
1766 return !$this->isAllowed( 'noratelimit' );
1770 * Primitive rate limits: enforce maximum actions per time period
1771 * to put a brake on flooding.
1773 * The method generates both a generic profiling point and a per action one
1774 * (suffix being "-$action".
1776 * @note When using a shared cache like memcached, IP-address
1777 * last-hit counters will be shared across wikis.
1779 * @param string $action Action to enforce; 'edit' if unspecified
1780 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1781 * @return bool True if a rate limiter was tripped
1783 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1784 // Call the 'PingLimiter' hook
1786 if ( !Hooks
::run( 'PingLimiter', [ &$this, $action, &$result, $incrBy ] ) ) {
1790 global $wgRateLimits;
1791 if ( !isset( $wgRateLimits[$action] ) ) {
1795 // Some groups shouldn't trigger the ping limiter, ever
1796 if ( !$this->isPingLimitable() ) {
1800 $limits = $wgRateLimits[$action];
1802 $id = $this->getId();
1804 $isNewbie = $this->isNewbie();
1808 if ( isset( $limits['anon'] ) ) {
1809 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1812 // limits for logged-in users
1813 if ( isset( $limits['user'] ) ) {
1814 $userLimit = $limits['user'];
1816 // limits for newbie logged-in users
1817 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1818 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1822 // limits for anons and for newbie logged-in users
1825 if ( isset( $limits['ip'] ) ) {
1826 $ip = $this->getRequest()->getIP();
1827 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1829 // subnet-based limits
1830 if ( isset( $limits['subnet'] ) ) {
1831 $ip = $this->getRequest()->getIP();
1832 $subnet = IP
::getSubnet( $ip );
1833 if ( $subnet !== false ) {
1834 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1839 // Check for group-specific permissions
1840 // If more than one group applies, use the group with the highest limit ratio (max/period)
1841 foreach ( $this->getGroups() as $group ) {
1842 if ( isset( $limits[$group] ) ) {
1843 if ( $userLimit === false
1844 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1846 $userLimit = $limits[$group];
1851 // Set the user limit key
1852 if ( $userLimit !== false ) {
1853 list( $max, $period ) = $userLimit;
1854 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1855 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1858 // ip-based limits for all ping-limitable users
1859 if ( isset( $limits['ip-all'] ) ) {
1860 $ip = $this->getRequest()->getIP();
1861 // ignore if user limit is more permissive
1862 if ( $isNewbie ||
$userLimit === false
1863 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1864 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1868 // subnet-based limits for all ping-limitable users
1869 if ( isset( $limits['subnet-all'] ) ) {
1870 $ip = $this->getRequest()->getIP();
1871 $subnet = IP
::getSubnet( $ip );
1872 if ( $subnet !== false ) {
1873 // ignore if user limit is more permissive
1874 if ( $isNewbie ||
$userLimit === false
1875 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1876 > $userLimit[0] / $userLimit[1] ) {
1877 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1882 $cache = ObjectCache
::getLocalClusterInstance();
1885 foreach ( $keys as $key => $limit ) {
1886 list( $max, $period ) = $limit;
1887 $summary = "(limit $max in {$period}s)";
1888 $count = $cache->get( $key );
1891 if ( $count >= $max ) {
1892 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1893 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1896 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1899 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1900 if ( $incrBy > 0 ) {
1901 $cache->add( $key, 0, intval( $period ) ); // first ping
1904 if ( $incrBy > 0 ) {
1905 $cache->incr( $key, $incrBy );
1913 * Check if user is blocked
1915 * @param bool $bFromSlave Whether to check the slave database instead of
1916 * the master. Hacked from false due to horrible probs on site.
1917 * @return bool True if blocked, false otherwise
1919 public function isBlocked( $bFromSlave = true ) {
1920 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1924 * Get the block affecting the user, or null if the user is not blocked
1926 * @param bool $bFromSlave Whether to check the slave database instead of the master
1927 * @return Block|null
1929 public function getBlock( $bFromSlave = true ) {
1930 $this->getBlockedStatus( $bFromSlave );
1931 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1935 * Check if user is blocked from editing a particular article
1937 * @param Title $title Title to check
1938 * @param bool $bFromSlave Whether to check the slave database instead of the master
1941 public function isBlockedFrom( $title, $bFromSlave = false ) {
1942 global $wgBlockAllowsUTEdit;
1944 $blocked = $this->isBlocked( $bFromSlave );
1945 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1946 // If a user's name is suppressed, they cannot make edits anywhere
1947 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1948 && $title->getNamespace() == NS_USER_TALK
) {
1950 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1953 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
1959 * If user is blocked, return the name of the user who placed the block
1960 * @return string Name of blocker
1962 public function blockedBy() {
1963 $this->getBlockedStatus();
1964 return $this->mBlockedby
;
1968 * If user is blocked, return the specified reason for the block
1969 * @return string Blocking reason
1971 public function blockedFor() {
1972 $this->getBlockedStatus();
1973 return $this->mBlockreason
;
1977 * If user is blocked, return the ID for the block
1978 * @return int Block ID
1980 public function getBlockId() {
1981 $this->getBlockedStatus();
1982 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1986 * Check if user is blocked on all wikis.
1987 * Do not use for actual edit permission checks!
1988 * This is intended for quick UI checks.
1990 * @param string $ip IP address, uses current client if none given
1991 * @return bool True if blocked, false otherwise
1993 public function isBlockedGlobally( $ip = '' ) {
1994 if ( $this->mBlockedGlobally
!== null ) {
1995 return $this->mBlockedGlobally
;
1997 // User is already an IP?
1998 if ( IP
::isIPAddress( $this->getName() ) ) {
1999 $ip = $this->getName();
2001 $ip = $this->getRequest()->getIP();
2004 Hooks
::run( 'UserIsBlockedGlobally', [ &$this, $ip, &$blocked ] );
2005 $this->mBlockedGlobally
= (bool)$blocked;
2006 return $this->mBlockedGlobally
;
2010 * Check if user account is locked
2012 * @return bool True if locked, false otherwise
2014 public function isLocked() {
2015 if ( $this->mLocked
!== null ) {
2016 return $this->mLocked
;
2019 $authUser = $wgAuth->getUserInstance( $this );
2020 $this->mLocked
= (bool)$authUser->isLocked();
2021 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2022 return $this->mLocked
;
2026 * Check if user account is hidden
2028 * @return bool True if hidden, false otherwise
2030 public function isHidden() {
2031 if ( $this->mHideName
!== null ) {
2032 return $this->mHideName
;
2034 $this->getBlockedStatus();
2035 if ( !$this->mHideName
) {
2037 $authUser = $wgAuth->getUserInstance( $this );
2038 $this->mHideName
= (bool)$authUser->isHidden();
2039 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2041 return $this->mHideName
;
2045 * Get the user's ID.
2046 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2048 public function getId() {
2049 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2050 // Special case, we know the user is anonymous
2052 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2053 // Don't load if this was initialized from an ID
2057 return (int)$this->mId
;
2061 * Set the user and reload all fields according to a given ID
2062 * @param int $v User ID to reload
2064 public function setId( $v ) {
2066 $this->clearInstanceCache( 'id' );
2070 * Get the user name, or the IP of an anonymous user
2071 * @return string User's name or IP address
2073 public function getName() {
2074 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2075 // Special case optimisation
2076 return $this->mName
;
2079 if ( $this->mName
=== false ) {
2081 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2083 return $this->mName
;
2088 * Set the user name.
2090 * This does not reload fields from the database according to the given
2091 * name. Rather, it is used to create a temporary "nonexistent user" for
2092 * later addition to the database. It can also be used to set the IP
2093 * address for an anonymous user to something other than the current
2096 * @note User::newFromName() has roughly the same function, when the named user
2098 * @param string $str New user name to set
2100 public function setName( $str ) {
2102 $this->mName
= $str;
2106 * Get the user's name escaped by underscores.
2107 * @return string Username escaped by underscores.
2109 public function getTitleKey() {
2110 return str_replace( ' ', '_', $this->getName() );
2114 * Check if the user has new messages.
2115 * @return bool True if the user has new messages
2117 public function getNewtalk() {
2120 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2121 if ( $this->mNewtalk
=== -1 ) {
2122 $this->mNewtalk
= false; # reset talk page status
2124 // Check memcached separately for anons, who have no
2125 // entire User object stored in there.
2126 if ( !$this->mId
) {
2127 global $wgDisableAnonTalk;
2128 if ( $wgDisableAnonTalk ) {
2129 // Anon newtalk disabled by configuration.
2130 $this->mNewtalk
= false;
2132 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2135 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2139 return (bool)$this->mNewtalk
;
2143 * Return the data needed to construct links for new talk page message
2144 * alerts. If there are new messages, this will return an associative array
2145 * with the following data:
2146 * wiki: The database name of the wiki
2147 * link: Root-relative link to the user's talk page
2148 * rev: The last talk page revision that the user has seen or null. This
2149 * is useful for building diff links.
2150 * If there are no new messages, it returns an empty array.
2151 * @note This function was designed to accomodate multiple talk pages, but
2152 * currently only returns a single link and revision.
2155 public function getNewMessageLinks() {
2157 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$this, &$talks ] ) ) {
2159 } elseif ( !$this->getNewtalk() ) {
2162 $utp = $this->getTalkPage();
2163 $dbr = wfGetDB( DB_SLAVE
);
2164 // Get the "last viewed rev" timestamp from the oldest message notification
2165 $timestamp = $dbr->selectField( 'user_newtalk',
2166 'MIN(user_last_timestamp)',
2167 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2169 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2170 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2174 * Get the revision ID for the last talk page revision viewed by the talk
2176 * @return int|null Revision ID or null
2178 public function getNewMessageRevisionId() {
2179 $newMessageRevisionId = null;
2180 $newMessageLinks = $this->getNewMessageLinks();
2181 if ( $newMessageLinks ) {
2182 // Note: getNewMessageLinks() never returns more than a single link
2183 // and it is always for the same wiki, but we double-check here in
2184 // case that changes some time in the future.
2185 if ( count( $newMessageLinks ) === 1
2186 && $newMessageLinks[0]['wiki'] === wfWikiID()
2187 && $newMessageLinks[0]['rev']
2189 /** @var Revision $newMessageRevision */
2190 $newMessageRevision = $newMessageLinks[0]['rev'];
2191 $newMessageRevisionId = $newMessageRevision->getId();
2194 return $newMessageRevisionId;
2198 * Internal uncached check for new messages
2201 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2202 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2203 * @return bool True if the user has new messages
2205 protected function checkNewtalk( $field, $id ) {
2206 $dbr = wfGetDB( DB_SLAVE
);
2208 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2210 return $ok !== false;
2214 * Add or update the new messages flag
2215 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2216 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2217 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2218 * @return bool True if successful, false otherwise
2220 protected function updateNewtalk( $field, $id, $curRev = null ) {
2221 // Get timestamp of the talk page revision prior to the current one
2222 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2223 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2224 // Mark the user as having new messages since this revision
2225 $dbw = wfGetDB( DB_MASTER
);
2226 $dbw->insert( 'user_newtalk',
2227 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2230 if ( $dbw->affectedRows() ) {
2231 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2234 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2240 * Clear the new messages flag for the given user
2241 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2242 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2243 * @return bool True if successful, false otherwise
2245 protected function deleteNewtalk( $field, $id ) {
2246 $dbw = wfGetDB( DB_MASTER
);
2247 $dbw->delete( 'user_newtalk',
2250 if ( $dbw->affectedRows() ) {
2251 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2254 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2260 * Update the 'You have new messages!' status.
2261 * @param bool $val Whether the user has new messages
2262 * @param Revision $curRev New, as yet unseen revision of the user talk
2263 * page. Ignored if null or !$val.
2265 public function setNewtalk( $val, $curRev = null ) {
2266 if ( wfReadOnly() ) {
2271 $this->mNewtalk
= $val;
2273 if ( $this->isAnon() ) {
2275 $id = $this->getName();
2278 $id = $this->getId();
2282 $changed = $this->updateNewtalk( $field, $id, $curRev );
2284 $changed = $this->deleteNewtalk( $field, $id );
2288 $this->invalidateCache();
2293 * Generate a current or new-future timestamp to be stored in the
2294 * user_touched field when we update things.
2295 * @return string Timestamp in TS_MW format
2297 private function newTouchedTimestamp() {
2298 global $wgClockSkewFudge;
2300 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2301 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2302 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2309 * Clear user data from memcached
2311 * Use after applying updates to the database; caller's
2312 * responsibility to update user_touched if appropriate.
2314 * Called implicitly from invalidateCache() and saveSettings().
2316 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2318 public function clearSharedCache( $mode = 'changed' ) {
2319 if ( !$this->getId() ) {
2323 $cache = ObjectCache
::getMainWANInstance();
2324 $processCache = self
::getInProcessCache();
2325 $key = $this->getCacheKey( $cache );
2326 if ( $mode === 'refresh' ) {
2327 $cache->delete( $key, 1 );
2328 $processCache->delete( $key );
2330 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2331 function() use ( $cache, $processCache, $key ) {
2332 $cache->delete( $key );
2333 $processCache->delete( $key );
2340 * Immediately touch the user data cache for this account
2342 * Calls touch() and removes account data from memcached
2344 public function invalidateCache() {
2346 $this->clearSharedCache();
2350 * Update the "touched" timestamp for the user
2352 * This is useful on various login/logout events when making sure that
2353 * a browser or proxy that has multiple tenants does not suffer cache
2354 * pollution where the new user sees the old users content. The value
2355 * of getTouched() is checked when determining 304 vs 200 responses.
2356 * Unlike invalidateCache(), this preserves the User object cache and
2357 * avoids database writes.
2361 public function touch() {
2362 $id = $this->getId();
2364 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2365 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2366 $this->mQuickTouched
= null;
2371 * Validate the cache for this account.
2372 * @param string $timestamp A timestamp in TS_MW format
2375 public function validateCache( $timestamp ) {
2376 return ( $timestamp >= $this->getTouched() );
2380 * Get the user touched timestamp
2382 * Use this value only to validate caches via inequalities
2383 * such as in the case of HTTP If-Modified-Since response logic
2385 * @return string TS_MW Timestamp
2387 public function getTouched() {
2391 if ( $this->mQuickTouched
=== null ) {
2392 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2393 $cache = ObjectCache
::getMainWANInstance();
2395 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2398 return max( $this->mTouched
, $this->mQuickTouched
);
2401 return $this->mTouched
;
2405 * Get the user_touched timestamp field (time of last DB updates)
2406 * @return string TS_MW Timestamp
2409 public function getDBTouched() {
2412 return $this->mTouched
;
2416 * @deprecated Removed in 1.27.
2420 public function getPassword() {
2421 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2425 * @deprecated Removed in 1.27.
2429 public function getTemporaryPassword() {
2430 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2434 * Set the password and reset the random token.
2435 * Calls through to authentication plugin if necessary;
2436 * will have no effect if the auth plugin refuses to
2437 * pass the change through or if the legal password
2440 * As a special case, setting the password to null
2441 * wipes it, so the account cannot be logged in until
2442 * a new password is set, for instance via e-mail.
2444 * @deprecated since 1.27. AuthManager is coming.
2445 * @param string $str New password to set
2446 * @throws PasswordError On failure
2449 public function setPassword( $str ) {
2452 if ( $str !== null ) {
2453 if ( !$wgAuth->allowPasswordChange() ) {
2454 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2457 $status = $this->checkPasswordValidity( $str );
2458 if ( !$status->isGood() ) {
2459 throw new PasswordError( $status->getMessage()->text() );
2463 if ( !$wgAuth->setPassword( $this, $str ) ) {
2464 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2468 $this->setOption( 'watchlisttoken', false );
2469 $this->setPasswordInternal( $str );
2475 * Set the password and reset the random token unconditionally.
2477 * @deprecated since 1.27. AuthManager is coming.
2478 * @param string|null $str New password to set or null to set an invalid
2479 * password hash meaning that the user will not be able to log in
2480 * through the web interface.
2482 public function setInternalPassword( $str ) {
2485 if ( $wgAuth->allowSetLocalPassword() ) {
2487 $this->setOption( 'watchlisttoken', false );
2488 $this->setPasswordInternal( $str );
2493 * Actually set the password and such
2494 * @since 1.27 cannot set a password for a user not in the database
2495 * @param string|null $str New password to set or null to set an invalid
2496 * password hash meaning that the user will not be able to log in
2497 * through the web interface.
2499 private function setPasswordInternal( $str ) {
2500 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2502 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2505 $passwordFactory = new PasswordFactory();
2506 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2507 $dbw = wfGetDB( DB_MASTER
);
2511 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2512 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2513 'user_newpass_time' => $dbw->timestampOrNull( null ),
2521 // When the main password is changed, invalidate all bot passwords too
2522 BotPassword
::invalidateAllPasswordsForUser( $this->getName() );
2526 * Get the user's current token.
2527 * @param bool $forceCreation Force the generation of a new token if the
2528 * user doesn't have one (default=true for backwards compatibility).
2529 * @return string|null Token
2531 public function getToken( $forceCreation = true ) {
2532 global $wgAuthenticationTokenVersion;
2535 if ( !$this->mToken
&& $forceCreation ) {
2539 if ( !$this->mToken
) {
2540 // The user doesn't have a token, return null to indicate that.
2542 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2543 // We return a random value here so existing token checks are very
2545 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2546 } elseif ( $wgAuthenticationTokenVersion === null ) {
2547 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2548 return $this->mToken
;
2550 // $wgAuthenticationTokenVersion in use, so hmac it.
2551 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2553 // The raw hash can be overly long. Shorten it up.
2554 $len = max( 32, self
::TOKEN_LENGTH
);
2555 if ( strlen( $ret ) < $len ) {
2556 // Should never happen, even md5 is 128 bits
2557 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2559 return substr( $ret, -$len );
2564 * Set the random token (used for persistent authentication)
2565 * Called from loadDefaults() among other places.
2567 * @param string|bool $token If specified, set the token to this value
2569 public function setToken( $token = false ) {
2571 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2572 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2573 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2574 } elseif ( !$token ) {
2575 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2577 $this->mToken
= $token;
2582 * Set the password for a password reminder or new account email
2584 * @deprecated since 1.27, AuthManager is coming
2585 * @param string $str New password to set or null to set an invalid
2586 * password hash meaning that the user will not be able to use it
2587 * @param bool $throttle If true, reset the throttle timestamp to the present
2589 public function setNewpassword( $str, $throttle = true ) {
2590 $id = $this->getId();
2592 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2595 $dbw = wfGetDB( DB_MASTER
);
2597 $passwordFactory = new PasswordFactory();
2598 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2600 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2603 if ( $str === null ) {
2604 $update['user_newpass_time'] = null;
2605 } elseif ( $throttle ) {
2606 $update['user_newpass_time'] = $dbw->timestamp();
2609 $dbw->update( 'user', $update, [ 'user_id' => $id ], __METHOD__
);
2613 * Has password reminder email been sent within the last
2614 * $wgPasswordReminderResendTime hours?
2617 public function isPasswordReminderThrottled() {
2618 global $wgPasswordReminderResendTime;
2620 if ( !$wgPasswordReminderResendTime ) {
2626 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2627 ?
wfGetDB( DB_MASTER
)
2628 : wfGetDB( DB_SLAVE
);
2629 $newpassTime = $db->selectField(
2631 'user_newpass_time',
2632 [ 'user_id' => $this->getId() ],
2636 if ( $newpassTime === null ) {
2639 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2640 return time() < $expiry;
2644 * Get the user's e-mail address
2645 * @return string User's email address
2647 public function getEmail() {
2649 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2650 return $this->mEmail
;
2654 * Get the timestamp of the user's e-mail authentication
2655 * @return string TS_MW timestamp
2657 public function getEmailAuthenticationTimestamp() {
2659 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2660 return $this->mEmailAuthenticated
;
2664 * Set the user's e-mail address
2665 * @param string $str New e-mail address
2667 public function setEmail( $str ) {
2669 if ( $str == $this->mEmail
) {
2672 $this->invalidateEmail();
2673 $this->mEmail
= $str;
2674 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2678 * Set the user's e-mail address and a confirmation mail if needed.
2681 * @param string $str New e-mail address
2684 public function setEmailWithConfirmation( $str ) {
2685 global $wgEnableEmail, $wgEmailAuthentication;
2687 if ( !$wgEnableEmail ) {
2688 return Status
::newFatal( 'emaildisabled' );
2691 $oldaddr = $this->getEmail();
2692 if ( $str === $oldaddr ) {
2693 return Status
::newGood( true );
2696 $this->setEmail( $str );
2698 if ( $str !== '' && $wgEmailAuthentication ) {
2699 // Send a confirmation request to the new address if needed
2700 $type = $oldaddr != '' ?
'changed' : 'set';
2701 $result = $this->sendConfirmationMail( $type );
2702 if ( $result->isGood() ) {
2703 // Say to the caller that a confirmation mail has been sent
2704 $result->value
= 'eauth';
2707 $result = Status
::newGood( true );
2714 * Get the user's real name
2715 * @return string User's real name
2717 public function getRealName() {
2718 if ( !$this->isItemLoaded( 'realname' ) ) {
2722 return $this->mRealName
;
2726 * Set the user's real name
2727 * @param string $str New real name
2729 public function setRealName( $str ) {
2731 $this->mRealName
= $str;
2735 * Get the user's current setting for a given option.
2737 * @param string $oname The option to check
2738 * @param string $defaultOverride A default value returned if the option does not exist
2739 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2740 * @return string User's current value for the option
2741 * @see getBoolOption()
2742 * @see getIntOption()
2744 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2745 global $wgHiddenPrefs;
2746 $this->loadOptions();
2748 # We want 'disabled' preferences to always behave as the default value for
2749 # users, even if they have set the option explicitly in their settings (ie they
2750 # set it, and then it was disabled removing their ability to change it). But
2751 # we don't want to erase the preferences in the database in case the preference
2752 # is re-enabled again. So don't touch $mOptions, just override the returned value
2753 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2754 return self
::getDefaultOption( $oname );
2757 if ( array_key_exists( $oname, $this->mOptions
) ) {
2758 return $this->mOptions
[$oname];
2760 return $defaultOverride;
2765 * Get all user's options
2767 * @param int $flags Bitwise combination of:
2768 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2769 * to the default value. (Since 1.25)
2772 public function getOptions( $flags = 0 ) {
2773 global $wgHiddenPrefs;
2774 $this->loadOptions();
2775 $options = $this->mOptions
;
2777 # We want 'disabled' preferences to always behave as the default value for
2778 # users, even if they have set the option explicitly in their settings (ie they
2779 # set it, and then it was disabled removing their ability to change it). But
2780 # we don't want to erase the preferences in the database in case the preference
2781 # is re-enabled again. So don't touch $mOptions, just override the returned value
2782 foreach ( $wgHiddenPrefs as $pref ) {
2783 $default = self
::getDefaultOption( $pref );
2784 if ( $default !== null ) {
2785 $options[$pref] = $default;
2789 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2790 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2797 * Get the user's current setting for a given option, as a boolean value.
2799 * @param string $oname The option to check
2800 * @return bool User's current value for the option
2803 public function getBoolOption( $oname ) {
2804 return (bool)$this->getOption( $oname );
2808 * Get the user's current setting for a given option, as an integer value.
2810 * @param string $oname The option to check
2811 * @param int $defaultOverride A default value returned if the option does not exist
2812 * @return int User's current value for the option
2815 public function getIntOption( $oname, $defaultOverride = 0 ) {
2816 $val = $this->getOption( $oname );
2818 $val = $defaultOverride;
2820 return intval( $val );
2824 * Set the given option for a user.
2826 * You need to call saveSettings() to actually write to the database.
2828 * @param string $oname The option to set
2829 * @param mixed $val New value to set
2831 public function setOption( $oname, $val ) {
2832 $this->loadOptions();
2834 // Explicitly NULL values should refer to defaults
2835 if ( is_null( $val ) ) {
2836 $val = self
::getDefaultOption( $oname );
2839 $this->mOptions
[$oname] = $val;
2843 * Get a token stored in the preferences (like the watchlist one),
2844 * resetting it if it's empty (and saving changes).
2846 * @param string $oname The option name to retrieve the token from
2847 * @return string|bool User's current value for the option, or false if this option is disabled.
2848 * @see resetTokenFromOption()
2850 * @deprecated 1.26 Applications should use the OAuth extension
2852 public function getTokenFromOption( $oname ) {
2853 global $wgHiddenPrefs;
2855 $id = $this->getId();
2856 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2860 $token = $this->getOption( $oname );
2862 // Default to a value based on the user token to avoid space
2863 // wasted on storing tokens for all users. When this option
2864 // is set manually by the user, only then is it stored.
2865 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2872 * Reset a token stored in the preferences (like the watchlist one).
2873 * *Does not* save user's preferences (similarly to setOption()).
2875 * @param string $oname The option name to reset the token in
2876 * @return string|bool New token value, or false if this option is disabled.
2877 * @see getTokenFromOption()
2880 public function resetTokenFromOption( $oname ) {
2881 global $wgHiddenPrefs;
2882 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2886 $token = MWCryptRand
::generateHex( 40 );
2887 $this->setOption( $oname, $token );
2892 * Return a list of the types of user options currently returned by
2893 * User::getOptionKinds().
2895 * Currently, the option kinds are:
2896 * - 'registered' - preferences which are registered in core MediaWiki or
2897 * by extensions using the UserGetDefaultOptions hook.
2898 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2899 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2900 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2901 * be used by user scripts.
2902 * - 'special' - "preferences" that are not accessible via User::getOptions
2903 * or User::setOptions.
2904 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2905 * These are usually legacy options, removed in newer versions.
2907 * The API (and possibly others) use this function to determine the possible
2908 * option types for validation purposes, so make sure to update this when a
2909 * new option kind is added.
2911 * @see User::getOptionKinds
2912 * @return array Option kinds
2914 public static function listOptionKinds() {
2917 'registered-multiselect',
2918 'registered-checkmatrix',
2926 * Return an associative array mapping preferences keys to the kind of a preference they're
2927 * used for. Different kinds are handled differently when setting or reading preferences.
2929 * See User::listOptionKinds for the list of valid option types that can be provided.
2931 * @see User::listOptionKinds
2932 * @param IContextSource $context
2933 * @param array $options Assoc. array with options keys to check as keys.
2934 * Defaults to $this->mOptions.
2935 * @return array The key => kind mapping data
2937 public function getOptionKinds( IContextSource
$context, $options = null ) {
2938 $this->loadOptions();
2939 if ( $options === null ) {
2940 $options = $this->mOptions
;
2943 $prefs = Preferences
::getPreferences( $this, $context );
2946 // Pull out the "special" options, so they don't get converted as
2947 // multiselect or checkmatrix.
2948 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2949 foreach ( $specialOptions as $name => $value ) {
2950 unset( $prefs[$name] );
2953 // Multiselect and checkmatrix options are stored in the database with
2954 // one key per option, each having a boolean value. Extract those keys.
2955 $multiselectOptions = [];
2956 foreach ( $prefs as $name => $info ) {
2957 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2958 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2959 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2960 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2962 foreach ( $opts as $value ) {
2963 $multiselectOptions["$prefix$value"] = true;
2966 unset( $prefs[$name] );
2969 $checkmatrixOptions = [];
2970 foreach ( $prefs as $name => $info ) {
2971 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2972 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2973 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2974 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2975 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2977 foreach ( $columns as $column ) {
2978 foreach ( $rows as $row ) {
2979 $checkmatrixOptions["$prefix$column-$row"] = true;
2983 unset( $prefs[$name] );
2987 // $value is ignored
2988 foreach ( $options as $key => $value ) {
2989 if ( isset( $prefs[$key] ) ) {
2990 $mapping[$key] = 'registered';
2991 } elseif ( isset( $multiselectOptions[$key] ) ) {
2992 $mapping[$key] = 'registered-multiselect';
2993 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2994 $mapping[$key] = 'registered-checkmatrix';
2995 } elseif ( isset( $specialOptions[$key] ) ) {
2996 $mapping[$key] = 'special';
2997 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2998 $mapping[$key] = 'userjs';
3000 $mapping[$key] = 'unused';
3008 * Reset certain (or all) options to the site defaults
3010 * The optional parameter determines which kinds of preferences will be reset.
3011 * Supported values are everything that can be reported by getOptionKinds()
3012 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3014 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3015 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3016 * for backwards-compatibility.
3017 * @param IContextSource|null $context Context source used when $resetKinds
3018 * does not contain 'all', passed to getOptionKinds().
3019 * Defaults to RequestContext::getMain() when null.
3021 public function resetOptions(
3022 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3023 IContextSource
$context = null
3026 $defaultOptions = self
::getDefaultOptions();
3028 if ( !is_array( $resetKinds ) ) {
3029 $resetKinds = [ $resetKinds ];
3032 if ( in_array( 'all', $resetKinds ) ) {
3033 $newOptions = $defaultOptions;
3035 if ( $context === null ) {
3036 $context = RequestContext
::getMain();
3039 $optionKinds = $this->getOptionKinds( $context );
3040 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3043 // Use default values for the options that should be deleted, and
3044 // copy old values for the ones that shouldn't.
3045 foreach ( $this->mOptions
as $key => $value ) {
3046 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3047 if ( array_key_exists( $key, $defaultOptions ) ) {
3048 $newOptions[$key] = $defaultOptions[$key];
3051 $newOptions[$key] = $value;
3056 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3058 $this->mOptions
= $newOptions;
3059 $this->mOptionsLoaded
= true;
3063 * Get the user's preferred date format.
3064 * @return string User's preferred date format
3066 public function getDatePreference() {
3067 // Important migration for old data rows
3068 if ( is_null( $this->mDatePreference
) ) {
3070 $value = $this->getOption( 'date' );
3071 $map = $wgLang->getDatePreferenceMigrationMap();
3072 if ( isset( $map[$value] ) ) {
3073 $value = $map[$value];
3075 $this->mDatePreference
= $value;
3077 return $this->mDatePreference
;
3081 * Determine based on the wiki configuration and the user's options,
3082 * whether this user must be over HTTPS no matter what.
3086 public function requiresHTTPS() {
3087 global $wgSecureLogin;
3088 if ( !$wgSecureLogin ) {
3091 $https = $this->getBoolOption( 'prefershttps' );
3092 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3094 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3101 * Get the user preferred stub threshold
3105 public function getStubThreshold() {
3106 global $wgMaxArticleSize; # Maximum article size, in Kb
3107 $threshold = $this->getIntOption( 'stubthreshold' );
3108 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3109 // If they have set an impossible value, disable the preference
3110 // so we can use the parser cache again.
3117 * Get the permissions this user has.
3118 * @return array Array of String permission names
3120 public function getRights() {
3121 if ( is_null( $this->mRights
) ) {
3122 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3124 // Deny any rights denied by the user's session, unless this
3125 // endpoint has no sessions.
3126 if ( !defined( 'MW_NO_SESSION' ) ) {
3127 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3128 if ( $allowedRights !== null ) {
3129 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3133 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3134 // Force reindexation of rights when a hook has unset one of them
3135 $this->mRights
= array_values( array_unique( $this->mRights
) );
3137 return $this->mRights
;
3141 * Get the list of explicit group memberships this user has.
3142 * The implicit * and user groups are not included.
3143 * @return array Array of String internal group names
3145 public function getGroups() {
3147 $this->loadGroups();
3148 return $this->mGroups
;
3152 * Get the list of implicit group memberships this user has.
3153 * This includes all explicit groups, plus 'user' if logged in,
3154 * '*' for all accounts, and autopromoted groups
3155 * @param bool $recache Whether to avoid the cache
3156 * @return array Array of String internal group names
3158 public function getEffectiveGroups( $recache = false ) {
3159 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3160 $this->mEffectiveGroups
= array_unique( array_merge(
3161 $this->getGroups(), // explicit groups
3162 $this->getAutomaticGroups( $recache ) // implicit groups
3164 // Hook for additional groups
3165 Hooks
::run( 'UserEffectiveGroups', [ &$this, &$this->mEffectiveGroups
] );
3166 // Force reindexation of groups when a hook has unset one of them
3167 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3169 return $this->mEffectiveGroups
;
3173 * Get the list of implicit group memberships this user has.
3174 * This includes 'user' if logged in, '*' for all accounts,
3175 * and autopromoted groups
3176 * @param bool $recache Whether to avoid the cache
3177 * @return array Array of String internal group names
3179 public function getAutomaticGroups( $recache = false ) {
3180 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3181 $this->mImplicitGroups
= [ '*' ];
3182 if ( $this->getId() ) {
3183 $this->mImplicitGroups
[] = 'user';
3185 $this->mImplicitGroups
= array_unique( array_merge(
3186 $this->mImplicitGroups
,
3187 Autopromote
::getAutopromoteGroups( $this )
3191 // Assure data consistency with rights/groups,
3192 // as getEffectiveGroups() depends on this function
3193 $this->mEffectiveGroups
= null;
3196 return $this->mImplicitGroups
;
3200 * Returns the groups the user has belonged to.
3202 * The user may still belong to the returned groups. Compare with getGroups().
3204 * The function will not return groups the user had belonged to before MW 1.17
3206 * @return array Names of the groups the user has belonged to.
3208 public function getFormerGroups() {
3211 if ( is_null( $this->mFormerGroups
) ) {
3212 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3213 ?
wfGetDB( DB_MASTER
)
3214 : wfGetDB( DB_SLAVE
);
3215 $res = $db->select( 'user_former_groups',
3217 [ 'ufg_user' => $this->mId
],
3219 $this->mFormerGroups
= [];
3220 foreach ( $res as $row ) {
3221 $this->mFormerGroups
[] = $row->ufg_group
;
3225 return $this->mFormerGroups
;
3229 * Get the user's edit count.
3230 * @return int|null Null for anonymous users
3232 public function getEditCount() {
3233 if ( !$this->getId() ) {
3237 if ( $this->mEditCount
=== null ) {
3238 /* Populate the count, if it has not been populated yet */
3239 $dbr = wfGetDB( DB_SLAVE
);
3240 // check if the user_editcount field has been initialized
3241 $count = $dbr->selectField(
3242 'user', 'user_editcount',
3243 [ 'user_id' => $this->mId
],
3247 if ( $count === null ) {
3248 // it has not been initialized. do so.
3249 $count = $this->initEditCount();
3251 $this->mEditCount
= $count;
3253 return (int)$this->mEditCount
;
3257 * Add the user to the given group.
3258 * This takes immediate effect.
3259 * @param string $group Name of the group to add
3262 public function addGroup( $group ) {
3265 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3269 $dbw = wfGetDB( DB_MASTER
);
3270 if ( $this->getId() ) {
3271 $dbw->insert( 'user_groups',
3273 'ug_user' => $this->getId(),
3274 'ug_group' => $group,
3280 $this->loadGroups();
3281 $this->mGroups
[] = $group;
3282 // In case loadGroups was not called before, we now have the right twice.
3283 // Get rid of the duplicate.
3284 $this->mGroups
= array_unique( $this->mGroups
);
3286 // Refresh the groups caches, and clear the rights cache so it will be
3287 // refreshed on the next call to $this->getRights().
3288 $this->getEffectiveGroups( true );
3289 $this->mRights
= null;
3291 $this->invalidateCache();
3297 * Remove the user from the given group.
3298 * This takes immediate effect.
3299 * @param string $group Name of the group to remove
3302 public function removeGroup( $group ) {
3304 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3308 $dbw = wfGetDB( DB_MASTER
);
3309 $dbw->delete( 'user_groups',
3311 'ug_user' => $this->getId(),
3312 'ug_group' => $group,
3315 // Remember that the user was in this group
3316 $dbw->insert( 'user_former_groups',
3318 'ufg_user' => $this->getId(),
3319 'ufg_group' => $group,
3325 $this->loadGroups();
3326 $this->mGroups
= array_diff( $this->mGroups
, [ $group ] );
3328 // Refresh the groups caches, and clear the rights cache so it will be
3329 // refreshed on the next call to $this->getRights().
3330 $this->getEffectiveGroups( true );
3331 $this->mRights
= null;
3333 $this->invalidateCache();
3339 * Get whether the user is logged in
3342 public function isLoggedIn() {
3343 return $this->getId() != 0;
3347 * Get whether the user is anonymous
3350 public function isAnon() {
3351 return !$this->isLoggedIn();
3355 * Check if user is allowed to access a feature / make an action
3357 * @param string ... Permissions to test
3358 * @return bool True if user is allowed to perform *any* of the given actions
3360 public function isAllowedAny() {
3361 $permissions = func_get_args();
3362 foreach ( $permissions as $permission ) {
3363 if ( $this->isAllowed( $permission ) ) {
3372 * @param string ... Permissions to test
3373 * @return bool True if the user is allowed to perform *all* of the given actions
3375 public function isAllowedAll() {
3376 $permissions = func_get_args();
3377 foreach ( $permissions as $permission ) {
3378 if ( !$this->isAllowed( $permission ) ) {
3386 * Internal mechanics of testing a permission
3387 * @param string $action
3390 public function isAllowed( $action = '' ) {
3391 if ( $action === '' ) {
3392 return true; // In the spirit of DWIM
3394 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3395 // by misconfiguration: 0 == 'foo'
3396 return in_array( $action, $this->getRights(), true );
3400 * Check whether to enable recent changes patrol features for this user
3401 * @return bool True or false
3403 public function useRCPatrol() {
3404 global $wgUseRCPatrol;
3405 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3409 * Check whether to enable new pages patrol features for this user
3410 * @return bool True or false
3412 public function useNPPatrol() {
3413 global $wgUseRCPatrol, $wgUseNPPatrol;
3415 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3416 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3421 * Check whether to enable new files patrol features for this user
3422 * @return bool True or false
3424 public function useFilePatrol() {
3425 global $wgUseRCPatrol, $wgUseFilePatrol;
3427 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3428 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3433 * Get the WebRequest object to use with this object
3435 * @return WebRequest
3437 public function getRequest() {
3438 if ( $this->mRequest
) {
3439 return $this->mRequest
;
3447 * Check the watched status of an article.
3448 * @since 1.22 $checkRights parameter added
3449 * @param Title $title Title of the article to look at
3450 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3451 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3454 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3455 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3456 return WatchedItemStore
::getDefaultInstance()->isWatched( $this, $title );
3463 * @since 1.22 $checkRights parameter added
3464 * @param Title $title Title of the article to look at
3465 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3466 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3468 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3469 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3470 WatchedItemStore
::getDefaultInstance()->addWatchBatch( [
3471 [ $this, $title->getSubjectPage() ],
3472 [ $this, $title->getTalkPage() ],
3476 $this->invalidateCache();
3480 * Stop watching an article.
3481 * @since 1.22 $checkRights parameter added
3482 * @param Title $title Title of the article to look at
3483 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3484 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3486 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3487 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3488 WatchedItemStore
::getDefaultInstance()->removeWatch( $this, $title->getSubjectPage() );
3489 WatchedItemStore
::getDefaultInstance()->removeWatch( $this, $title->getTalkPage() );
3491 $this->invalidateCache();
3495 * Clear the user's notification timestamp for the given title.
3496 * If e-notif e-mails are on, they will receive notification mails on
3497 * the next change of the page if it's watched etc.
3498 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3499 * @param Title $title Title of the article to look at
3500 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3502 public function clearNotification( &$title, $oldid = 0 ) {
3503 global $wgUseEnotif, $wgShowUpdatedMarker;
3505 // Do nothing if the database is locked to writes
3506 if ( wfReadOnly() ) {
3510 // Do nothing if not allowed to edit the watchlist
3511 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3515 // If we're working on user's talk page, we should update the talk page message indicator
3516 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3517 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$this, $oldid ] ) ) {
3521 // Try to update the DB post-send and only if needed...
3522 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3523 if ( !$this->getNewtalk() ) {
3524 return; // no notifications to clear
3527 // Delete the last notifications (they stack up)
3528 $this->setNewtalk( false );
3530 // If there is a new, unseen, revision, use its timestamp
3532 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3535 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3540 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3544 if ( $this->isAnon() ) {
3545 // Nothing else to do...
3549 // Only update the timestamp if the page is being watched.
3550 // The query to find out if it is watched is cached both in memcached and per-invocation,
3551 // and when it does have to be executed, it can be on a slave
3552 // If this is the user's newtalk page, we always update the timestamp
3554 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3558 WatchedItemStore
::getDefaultInstance()
3559 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3563 * Resets all of the given user's page-change notification timestamps.
3564 * If e-notif e-mails are on, they will receive notification mails on
3565 * the next change of any watched page.
3566 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3568 public function clearAllNotifications() {
3569 if ( wfReadOnly() ) {
3573 // Do nothing if not allowed to edit the watchlist
3574 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3578 global $wgUseEnotif, $wgShowUpdatedMarker;
3579 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3580 $this->setNewtalk( false );
3583 $id = $this->getId();
3585 $dbw = wfGetDB( DB_MASTER
);
3586 $dbw->update( 'watchlist',
3587 [ /* SET */ 'wl_notificationtimestamp' => null ],
3588 [ /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3591 // We also need to clear here the "you have new message" notification for the own user_talk page;
3592 // it's cleared one page view later in WikiPage::doViewUpdates().
3597 * Set a cookie on the user's client. Wrapper for
3598 * WebResponse::setCookie
3599 * @deprecated since 1.27
3600 * @param string $name Name of the cookie to set
3601 * @param string $value Value to set
3602 * @param int $exp Expiration time, as a UNIX time value;
3603 * if 0 or not specified, use the default $wgCookieExpiration
3604 * @param bool $secure
3605 * true: Force setting the secure attribute when setting the cookie
3606 * false: Force NOT setting the secure attribute when setting the cookie
3607 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3608 * @param array $params Array of options sent passed to WebResponse::setcookie()
3609 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3612 protected function setCookie(
3613 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3615 wfDeprecated( __METHOD__
, '1.27' );
3616 if ( $request === null ) {
3617 $request = $this->getRequest();
3619 $params['secure'] = $secure;
3620 $request->response()->setCookie( $name, $value, $exp, $params );
3624 * Clear a cookie on the user's client
3625 * @deprecated since 1.27
3626 * @param string $name Name of the cookie to clear
3627 * @param bool $secure
3628 * true: Force setting the secure attribute when setting the cookie
3629 * false: Force NOT setting the secure attribute when setting the cookie
3630 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3631 * @param array $params Array of options sent passed to WebResponse::setcookie()
3633 protected function clearCookie( $name, $secure = null, $params = [] ) {
3634 wfDeprecated( __METHOD__
, '1.27' );
3635 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3639 * Set an extended login cookie on the user's client. The expiry of the cookie
3640 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3643 * @see User::setCookie
3645 * @deprecated since 1.27
3646 * @param string $name Name of the cookie to set
3647 * @param string $value Value to set
3648 * @param bool $secure
3649 * true: Force setting the secure attribute when setting the cookie
3650 * false: Force NOT setting the secure attribute when setting the cookie
3651 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3653 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3654 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3656 wfDeprecated( __METHOD__
, '1.27' );
3659 $exp +
= $wgExtendedLoginCookieExpiration !== null
3660 ?
$wgExtendedLoginCookieExpiration
3661 : $wgCookieExpiration;
3663 $this->setCookie( $name, $value, $exp, $secure );
3667 * Persist this user's session (e.g. set cookies)
3669 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3671 * @param bool $secure Whether to force secure/insecure cookies or use default
3672 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3674 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3676 if ( 0 == $this->mId
) {
3680 $session = $this->getRequest()->getSession();
3681 if ( $request && $session->getRequest() !== $request ) {
3682 $session = $session->sessionWithRequest( $request );
3684 $delay = $session->delaySave();
3686 if ( !$session->getUser()->equals( $this ) ) {
3687 if ( !$session->canSetUser() ) {
3688 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3689 ->warning( __METHOD__
.
3690 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3694 $session->setUser( $this );
3697 $session->setRememberUser( $rememberMe );
3698 if ( $secure !== null ) {
3699 $session->setForceHTTPS( $secure );
3702 $session->persist();
3704 ScopedCallback
::consume( $delay );
3708 * Log this user out.
3710 public function logout() {
3711 if ( Hooks
::run( 'UserLogout', [ &$this ] ) ) {
3717 * Clear the user's session, and reset the instance cache.
3720 public function doLogout() {
3721 $session = $this->getRequest()->getSession();
3722 if ( !$session->canSetUser() ) {
3723 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3724 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3725 } elseif ( !$session->getUser()->equals( $this ) ) {
3726 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3727 ->warning( __METHOD__
.
3728 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3730 // But we still may as well make this user object anon
3731 $this->clearInstanceCache( 'defaults' );
3733 $this->clearInstanceCache( 'defaults' );
3734 $delay = $session->delaySave();
3735 $session->unpersist(); // Clear cookies (T127436)
3736 $session->setLoggedOutTimestamp( time() );
3737 $session->setUser( new User
);
3738 $session->set( 'wsUserID', 0 ); // Other code expects this
3739 ScopedCallback
::consume( $delay );
3744 * Save this user's settings into the database.
3745 * @todo Only rarely do all these fields need to be set!
3747 public function saveSettings() {
3748 if ( wfReadOnly() ) {
3749 // @TODO: caller should deal with this instead!
3750 // This should really just be an exception.
3751 MWExceptionHandler
::logException( new DBExpectedError(
3753 "Could not update user with ID '{$this->mId}'; DB is read-only."
3759 if ( 0 == $this->mId
) {
3763 // Get a new user_touched that is higher than the old one.
3764 // This will be used for a CAS check as a last-resort safety
3765 // check against race conditions and slave lag.
3766 $oldTouched = $this->mTouched
;
3767 $newTouched = $this->newTouchedTimestamp();
3769 $dbw = wfGetDB( DB_MASTER
);
3770 $dbw->update( 'user',
3772 'user_name' => $this->mName
,
3773 'user_real_name' => $this->mRealName
,
3774 'user_email' => $this->mEmail
,
3775 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3776 'user_touched' => $dbw->timestamp( $newTouched ),
3777 'user_token' => strval( $this->mToken
),
3778 'user_email_token' => $this->mEmailToken
,
3779 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3781 'user_id' => $this->mId
,
3782 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3786 if ( !$dbw->affectedRows() ) {
3787 // Maybe the problem was a missed cache update; clear it to be safe
3788 $this->clearSharedCache( 'refresh' );
3789 // User was changed in the meantime or loaded with stale data
3790 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3791 throw new MWException(
3792 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3793 " the version of the user to be saved is older than the current version."
3797 $this->mTouched
= $newTouched;
3798 $this->saveOptions();
3800 Hooks
::run( 'UserSaveSettings', [ $this ] );
3801 $this->clearSharedCache();
3802 $this->getUserPage()->invalidateCache();
3806 * If only this user's username is known, and it exists, return the user ID.
3808 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3811 public function idForName( $flags = 0 ) {
3812 $s = trim( $this->getName() );
3817 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3818 ?
wfGetDB( DB_MASTER
)
3819 : wfGetDB( DB_SLAVE
);
3821 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3822 ?
[ 'LOCK IN SHARE MODE' ]
3825 $id = $db->selectField( 'user',
3826 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
3832 * Add a user to the database, return the user object
3834 * @param string $name Username to add
3835 * @param array $params Array of Strings Non-default parameters to save to
3836 * the database as user_* fields:
3837 * - email: The user's email address.
3838 * - email_authenticated: The email authentication timestamp.
3839 * - real_name: The user's real name.
3840 * - options: An associative array of non-default options.
3841 * - token: Random authentication token. Do not set.
3842 * - registration: Registration timestamp. Do not set.
3844 * @return User|null User object, or null if the username already exists.
3846 public static function createNew( $name, $params = [] ) {
3847 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
3848 if ( isset( $params[$field] ) ) {
3849 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3850 unset( $params[$field] );
3856 $user->setToken(); // init token
3857 if ( isset( $params['options'] ) ) {
3858 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3859 unset( $params['options'] );
3861 $dbw = wfGetDB( DB_MASTER
);
3862 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3864 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3867 'user_id' => $seqVal,
3868 'user_name' => $name,
3869 'user_password' => $noPass,
3870 'user_newpassword' => $noPass,
3871 'user_email' => $user->mEmail
,
3872 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3873 'user_real_name' => $user->mRealName
,
3874 'user_token' => strval( $user->mToken
),
3875 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3876 'user_editcount' => 0,
3877 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3879 foreach ( $params as $name => $value ) {
3880 $fields["user_$name"] = $value;
3882 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
3883 if ( $dbw->affectedRows() ) {
3884 $newUser = User
::newFromId( $dbw->insertId() );
3892 * Add this existing user object to the database. If the user already
3893 * exists, a fatal status object is returned, and the user object is
3894 * initialised with the data from the database.
3896 * Previously, this function generated a DB error due to a key conflict
3897 * if the user already existed. Many extension callers use this function
3898 * in code along the lines of:
3900 * $user = User::newFromName( $name );
3901 * if ( !$user->isLoggedIn() ) {
3902 * $user->addToDatabase();
3904 * // do something with $user...
3906 * However, this was vulnerable to a race condition (bug 16020). By
3907 * initialising the user object if the user exists, we aim to support this
3908 * calling sequence as far as possible.
3910 * Note that if the user exists, this function will acquire a write lock,
3911 * so it is still advisable to make the call conditional on isLoggedIn(),
3912 * and to commit the transaction after calling.
3914 * @throws MWException
3917 public function addToDatabase() {
3919 if ( !$this->mToken
) {
3920 $this->setToken(); // init token
3923 $this->mTouched
= $this->newTouchedTimestamp();
3925 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3927 $dbw = wfGetDB( DB_MASTER
);
3928 $inWrite = $dbw->writesOrCallbacksPending();
3929 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3930 $dbw->insert( 'user',
3932 'user_id' => $seqVal,
3933 'user_name' => $this->mName
,
3934 'user_password' => $noPass,
3935 'user_newpassword' => $noPass,
3936 'user_email' => $this->mEmail
,
3937 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3938 'user_real_name' => $this->mRealName
,
3939 'user_token' => strval( $this->mToken
),
3940 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3941 'user_editcount' => 0,
3942 'user_touched' => $dbw->timestamp( $this->mTouched
),
3946 if ( !$dbw->affectedRows() ) {
3947 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3948 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3950 // Can't commit due to pending writes that may need atomicity.
3951 // This may cause some lock contention unlike the case below.
3952 $options = [ 'LOCK IN SHARE MODE' ];
3953 $flags = self
::READ_LOCKING
;
3955 // Often, this case happens early in views before any writes when
3956 // using CentralAuth. It's should be OK to commit and break the snapshot.
3957 $dbw->commit( __METHOD__
, 'flush' );
3959 $flags = self
::READ_LATEST
;
3961 $this->mId
= $dbw->selectField( 'user', 'user_id',
3962 [ 'user_name' => $this->mName
], __METHOD__
, $options );
3965 if ( $this->loadFromDatabase( $flags ) ) {
3970 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3971 "to insert user '{$this->mName}' row, but it was not present in select!" );
3973 return Status
::newFatal( 'userexists' );
3975 $this->mId
= $dbw->insertId();
3976 self
::$idCacheByName[$this->mName
] = $this->mId
;
3978 // Clear instance cache other than user table data, which is already accurate
3979 $this->clearInstanceCache();
3981 $this->saveOptions();
3982 return Status
::newGood();
3986 * If this user is logged-in and blocked,
3987 * block any IP address they've successfully logged in from.
3988 * @return bool A block was spread
3990 public function spreadAnyEditBlock() {
3991 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3992 return $this->spreadBlock();
3999 * If this (non-anonymous) user is blocked,
4000 * block the IP address they've successfully logged in from.
4001 * @return bool A block was spread
4003 protected function spreadBlock() {
4004 wfDebug( __METHOD__
. "()\n" );
4006 if ( $this->mId
== 0 ) {
4010 $userblock = Block
::newFromTarget( $this->getName() );
4011 if ( !$userblock ) {
4015 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4019 * Get whether the user is explicitly blocked from account creation.
4020 * @return bool|Block
4022 public function isBlockedFromCreateAccount() {
4023 $this->getBlockedStatus();
4024 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4025 return $this->mBlock
;
4028 # bug 13611: if the IP address the user is trying to create an account from is
4029 # blocked with createaccount disabled, prevent new account creation there even
4030 # when the user is logged in
4031 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4032 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4034 return $this->mBlockedFromCreateAccount
instanceof Block
4035 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4036 ?
$this->mBlockedFromCreateAccount
4041 * Get whether the user is blocked from using Special:Emailuser.
4044 public function isBlockedFromEmailuser() {
4045 $this->getBlockedStatus();
4046 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4050 * Get whether the user is allowed to create an account.
4053 public function isAllowedToCreateAccount() {
4054 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4058 * Get this user's personal page title.
4060 * @return Title User's personal page title
4062 public function getUserPage() {
4063 return Title
::makeTitle( NS_USER
, $this->getName() );
4067 * Get this user's talk page title.
4069 * @return Title User's talk page title
4071 public function getTalkPage() {
4072 $title = $this->getUserPage();
4073 return $title->getTalkPage();
4077 * Determine whether the user is a newbie. Newbies are either
4078 * anonymous IPs, or the most recently created accounts.
4081 public function isNewbie() {
4082 return !$this->isAllowed( 'autoconfirmed' );
4086 * Check to see if the given clear-text password is one of the accepted passwords
4087 * @deprecated since 1.27. AuthManager is coming.
4088 * @param string $password User password
4089 * @return bool True if the given password is correct, otherwise False
4091 public function checkPassword( $password ) {
4092 global $wgAuth, $wgLegacyEncoding;
4096 // Some passwords will give a fatal Status, which means there is
4097 // some sort of technical or security reason for this password to
4098 // be completely invalid and should never be checked (e.g., T64685)
4099 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4103 // Certain authentication plugins do NOT want to save
4104 // domain passwords in a mysql database, so we should
4105 // check this (in case $wgAuth->strict() is false).
4106 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4108 } elseif ( $wgAuth->strict() ) {
4109 // Auth plugin doesn't allow local authentication
4111 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4112 // Auth plugin doesn't allow local authentication for this user name
4116 $passwordFactory = new PasswordFactory();
4117 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4118 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4119 ?
wfGetDB( DB_MASTER
)
4120 : wfGetDB( DB_SLAVE
);
4123 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4124 'user', 'user_password', [ 'user_id' => $this->getId() ], __METHOD__
4126 } catch ( PasswordError
$e ) {
4127 wfDebug( 'Invalid password hash found in database.' );
4128 $mPassword = PasswordFactory
::newInvalidPassword();
4131 if ( !$mPassword->equals( $password ) ) {
4132 if ( $wgLegacyEncoding ) {
4133 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4134 // Check for this with iconv
4135 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4136 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4144 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4145 $this->setPasswordInternal( $password );
4152 * Check if the given clear-text password matches the temporary password
4153 * sent by e-mail for password reset operations.
4155 * @deprecated since 1.27. AuthManager is coming.
4156 * @param string $plaintext
4157 * @return bool True if matches, false otherwise
4159 public function checkTemporaryPassword( $plaintext ) {
4160 global $wgNewPasswordExpiry;
4164 $passwordFactory = new PasswordFactory();
4165 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4166 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4167 ?
wfGetDB( DB_MASTER
)
4168 : wfGetDB( DB_SLAVE
);
4170 $row = $db->selectRow(
4172 [ 'user_newpassword', 'user_newpass_time' ],
4173 [ 'user_id' => $this->getId() ],
4177 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4178 } catch ( PasswordError
$e ) {
4179 wfDebug( 'Invalid password hash found in database.' );
4180 $newPassword = PasswordFactory
::newInvalidPassword();
4183 if ( $newPassword->equals( $plaintext ) ) {
4184 if ( is_null( $row->user_newpass_time
) ) {
4187 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4188 return ( time() < $expiry );
4195 * Initialize (if necessary) and return a session token value
4196 * which can be used in edit forms to show that the user's
4197 * login credentials aren't being hijacked with a foreign form
4201 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4202 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4203 * @return MediaWiki\\Session\\Token The new edit token
4205 public function getEditTokenObject( $salt = '', $request = null ) {
4206 if ( $this->isAnon() ) {
4207 return new LoggedOutEditToken();
4211 $request = $this->getRequest();
4213 return $request->getSession()->getToken( $salt );
4217 * Initialize (if necessary) and return a session token value
4218 * which can be used in edit forms to show that the user's
4219 * login credentials aren't being hijacked with a foreign form
4223 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4224 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4225 * @return string The new edit token
4227 public function getEditToken( $salt = '', $request = null ) {
4228 return $this->getEditTokenObject( $salt, $request )->toString();
4232 * Get the embedded timestamp from a token.
4233 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::getTimestamp instead.
4234 * @param string $val Input token
4237 public static function getEditTokenTimestamp( $val ) {
4238 wfDeprecated( __METHOD__
, '1.27' );
4239 return MediaWiki\Session\Token
::getTimestamp( $val );
4243 * Check given value against the token value stored in the session.
4244 * A match should confirm that the form was submitted from the
4245 * user's own login session, not a form submission from a third-party
4248 * @param string $val Input value to compare
4249 * @param string $salt Optional function-specific data for hashing
4250 * @param WebRequest|null $request Object to use or null to use $wgRequest
4251 * @param int $maxage Fail tokens older than this, in seconds
4252 * @return bool Whether the token matches
4254 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4255 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4259 * Check given value against the token value stored in the session,
4260 * ignoring the suffix.
4262 * @param string $val Input value to compare
4263 * @param string $salt Optional function-specific data for hashing
4264 * @param WebRequest|null $request Object to use or null to use $wgRequest
4265 * @param int $maxage Fail tokens older than this, in seconds
4266 * @return bool Whether the token matches
4268 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4269 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4270 return $this->matchEditToken( $val, $salt, $request, $maxage );
4274 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4275 * mail to the user's given address.
4277 * @param string $type Message to send, either "created", "changed" or "set"
4280 public function sendConfirmationMail( $type = 'created' ) {
4282 $expiration = null; // gets passed-by-ref and defined in next line.
4283 $token = $this->confirmationToken( $expiration );
4284 $url = $this->confirmationTokenUrl( $token );
4285 $invalidateURL = $this->invalidationTokenUrl( $token );
4286 $this->saveSettings();
4288 if ( $type == 'created' ||
$type === false ) {
4289 $message = 'confirmemail_body';
4290 } elseif ( $type === true ) {
4291 $message = 'confirmemail_body_changed';
4293 // Messages: confirmemail_body_changed, confirmemail_body_set
4294 $message = 'confirmemail_body_' . $type;
4297 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4298 wfMessage( $message,
4299 $this->getRequest()->getIP(),
4302 $wgLang->userTimeAndDate( $expiration, $this ),
4304 $wgLang->userDate( $expiration, $this ),
4305 $wgLang->userTime( $expiration, $this ) )->text() );
4309 * Send an e-mail to this user's account. Does not check for
4310 * confirmed status or validity.
4312 * @param string $subject Message subject
4313 * @param string $body Message body
4314 * @param User|null $from Optional sending user; if unspecified, default
4315 * $wgPasswordSender will be used.
4316 * @param string $replyto Reply-To address
4319 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4320 global $wgPasswordSender;
4322 if ( $from instanceof User
) {
4323 $sender = MailAddress
::newFromUser( $from );
4325 $sender = new MailAddress( $wgPasswordSender,
4326 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4328 $to = MailAddress
::newFromUser( $this );
4330 return UserMailer
::send( $to, $sender, $subject, $body, [
4331 'replyTo' => $replyto,
4336 * Generate, store, and return a new e-mail confirmation code.
4337 * A hash (unsalted, since it's used as a key) is stored.
4339 * @note Call saveSettings() after calling this function to commit
4340 * this change to the database.
4342 * @param string &$expiration Accepts the expiration time
4343 * @return string New token
4345 protected function confirmationToken( &$expiration ) {
4346 global $wgUserEmailConfirmationTokenExpiry;
4348 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4349 $expiration = wfTimestamp( TS_MW
, $expires );
4351 $token = MWCryptRand
::generateHex( 32 );
4352 $hash = md5( $token );
4353 $this->mEmailToken
= $hash;
4354 $this->mEmailTokenExpires
= $expiration;
4359 * Return a URL the user can use to confirm their email address.
4360 * @param string $token Accepts the email confirmation token
4361 * @return string New token URL
4363 protected function confirmationTokenUrl( $token ) {
4364 return $this->getTokenUrl( 'ConfirmEmail', $token );
4368 * Return a URL the user can use to invalidate their email address.
4369 * @param string $token Accepts the email confirmation token
4370 * @return string New token URL
4372 protected function invalidationTokenUrl( $token ) {
4373 return $this->getTokenUrl( 'InvalidateEmail', $token );
4377 * Internal function to format the e-mail validation/invalidation URLs.
4378 * This uses a quickie hack to use the
4379 * hardcoded English names of the Special: pages, for ASCII safety.
4381 * @note Since these URLs get dropped directly into emails, using the
4382 * short English names avoids insanely long URL-encoded links, which
4383 * also sometimes can get corrupted in some browsers/mailers
4384 * (bug 6957 with Gmail and Internet Explorer).
4386 * @param string $page Special page
4387 * @param string $token Token
4388 * @return string Formatted URL
4390 protected function getTokenUrl( $page, $token ) {
4391 // Hack to bypass localization of 'Special:'
4392 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4393 return $title->getCanonicalURL();
4397 * Mark the e-mail address confirmed.
4399 * @note Call saveSettings() after calling this function to commit the change.
4403 public function confirmEmail() {
4404 // Check if it's already confirmed, so we don't touch the database
4405 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4406 if ( !$this->isEmailConfirmed() ) {
4407 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4408 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4414 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4415 * address if it was already confirmed.
4417 * @note Call saveSettings() after calling this function to commit the change.
4418 * @return bool Returns true
4420 public function invalidateEmail() {
4422 $this->mEmailToken
= null;
4423 $this->mEmailTokenExpires
= null;
4424 $this->setEmailAuthenticationTimestamp( null );
4426 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4431 * Set the e-mail authentication timestamp.
4432 * @param string $timestamp TS_MW timestamp
4434 public function setEmailAuthenticationTimestamp( $timestamp ) {
4436 $this->mEmailAuthenticated
= $timestamp;
4437 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4441 * Is this user allowed to send e-mails within limits of current
4442 * site configuration?
4445 public function canSendEmail() {
4446 global $wgEnableEmail, $wgEnableUserEmail;
4447 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4450 $canSend = $this->isEmailConfirmed();
4451 Hooks
::run( 'UserCanSendEmail', [ &$this, &$canSend ] );
4456 * Is this user allowed to receive e-mails within limits of current
4457 * site configuration?
4460 public function canReceiveEmail() {
4461 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4465 * Is this user's e-mail address valid-looking and confirmed within
4466 * limits of the current site configuration?
4468 * @note If $wgEmailAuthentication is on, this may require the user to have
4469 * confirmed their address by returning a code or using a password
4470 * sent to the address from the wiki.
4474 public function isEmailConfirmed() {
4475 global $wgEmailAuthentication;
4478 if ( Hooks
::run( 'EmailConfirmed', [ &$this, &$confirmed ] ) ) {
4479 if ( $this->isAnon() ) {
4482 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4485 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4495 * Check whether there is an outstanding request for e-mail confirmation.
4498 public function isEmailConfirmationPending() {
4499 global $wgEmailAuthentication;
4500 return $wgEmailAuthentication &&
4501 !$this->isEmailConfirmed() &&
4502 $this->mEmailToken
&&
4503 $this->mEmailTokenExpires
> wfTimestamp();
4507 * Get the timestamp of account creation.
4509 * @return string|bool|null Timestamp of account creation, false for
4510 * non-existent/anonymous user accounts, or null if existing account
4511 * but information is not in database.
4513 public function getRegistration() {
4514 if ( $this->isAnon() ) {
4518 return $this->mRegistration
;
4522 * Get the timestamp of the first edit
4524 * @return string|bool Timestamp of first edit, or false for
4525 * non-existent/anonymous user accounts.
4527 public function getFirstEditTimestamp() {
4528 if ( $this->getId() == 0 ) {
4529 return false; // anons
4531 $dbr = wfGetDB( DB_SLAVE
);
4532 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4533 [ 'rev_user' => $this->getId() ],
4535 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4538 return false; // no edits
4540 return wfTimestamp( TS_MW
, $time );
4544 * Get the permissions associated with a given list of groups
4546 * @param array $groups Array of Strings List of internal group names
4547 * @return array Array of Strings List of permission key names for given groups combined
4549 public static function getGroupPermissions( $groups ) {
4550 global $wgGroupPermissions, $wgRevokePermissions;
4552 // grant every granted permission first
4553 foreach ( $groups as $group ) {
4554 if ( isset( $wgGroupPermissions[$group] ) ) {
4555 $rights = array_merge( $rights,
4556 // array_filter removes empty items
4557 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4560 // now revoke the revoked permissions
4561 foreach ( $groups as $group ) {
4562 if ( isset( $wgRevokePermissions[$group] ) ) {
4563 $rights = array_diff( $rights,
4564 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4567 return array_unique( $rights );
4571 * Get all the groups who have a given permission
4573 * @param string $role Role to check
4574 * @return array Array of Strings List of internal group names with the given permission
4576 public static function getGroupsWithPermission( $role ) {
4577 global $wgGroupPermissions;
4578 $allowedGroups = [];
4579 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4580 if ( self
::groupHasPermission( $group, $role ) ) {
4581 $allowedGroups[] = $group;
4584 return $allowedGroups;
4588 * Check, if the given group has the given permission
4590 * If you're wanting to check whether all users have a permission, use
4591 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4595 * @param string $group Group to check
4596 * @param string $role Role to check
4599 public static function groupHasPermission( $group, $role ) {
4600 global $wgGroupPermissions, $wgRevokePermissions;
4601 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4602 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4606 * Check if all users may be assumed to have the given permission
4608 * We generally assume so if the right is granted to '*' and isn't revoked
4609 * on any group. It doesn't attempt to take grants or other extension
4610 * limitations on rights into account in the general case, though, as that
4611 * would require it to always return false and defeat the purpose.
4612 * Specifically, session-based rights restrictions (such as OAuth or bot
4613 * passwords) are applied based on the current session.
4616 * @param string $right Right to check
4619 public static function isEveryoneAllowed( $right ) {
4620 global $wgGroupPermissions, $wgRevokePermissions;
4623 // Use the cached results, except in unit tests which rely on
4624 // being able change the permission mid-request
4625 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4626 return $cache[$right];
4629 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4630 $cache[$right] = false;
4634 // If it's revoked anywhere, then everyone doesn't have it
4635 foreach ( $wgRevokePermissions as $rights ) {
4636 if ( isset( $rights[$right] ) && $rights[$right] ) {
4637 $cache[$right] = false;
4642 // Remove any rights that aren't allowed to the global-session user,
4643 // unless there are no sessions for this endpoint.
4644 if ( !defined( 'MW_NO_SESSION' ) ) {
4645 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4646 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4647 $cache[$right] = false;
4652 // Allow extensions to say false
4653 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4654 $cache[$right] = false;
4658 $cache[$right] = true;
4663 * Get the localized descriptive name for a group, if it exists
4665 * @param string $group Internal group name
4666 * @return string Localized descriptive group name
4668 public static function getGroupName( $group ) {
4669 $msg = wfMessage( "group-$group" );
4670 return $msg->isBlank() ?
$group : $msg->text();
4674 * Get the localized descriptive name for a member of a group, if it exists
4676 * @param string $group Internal group name
4677 * @param string $username Username for gender (since 1.19)
4678 * @return string Localized name for group member
4680 public static function getGroupMember( $group, $username = '#' ) {
4681 $msg = wfMessage( "group-$group-member", $username );
4682 return $msg->isBlank() ?
$group : $msg->text();
4686 * Return the set of defined explicit groups.
4687 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4688 * are not included, as they are defined automatically, not in the database.
4689 * @return array Array of internal group names
4691 public static function getAllGroups() {
4692 global $wgGroupPermissions, $wgRevokePermissions;
4694 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4695 self
::getImplicitGroups()
4700 * Get a list of all available permissions.
4701 * @return string[] Array of permission names
4703 public static function getAllRights() {
4704 if ( self
::$mAllRights === false ) {
4705 global $wgAvailableRights;
4706 if ( count( $wgAvailableRights ) ) {
4707 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4709 self
::$mAllRights = self
::$mCoreRights;
4711 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4713 return self
::$mAllRights;
4717 * Get a list of implicit groups
4718 * @return array Array of Strings Array of internal group names
4720 public static function getImplicitGroups() {
4721 global $wgImplicitGroups;
4723 $groups = $wgImplicitGroups;
4724 # Deprecated, use $wgImplicitGroups instead
4725 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4731 * Get the title of a page describing a particular group
4733 * @param string $group Internal group name
4734 * @return Title|bool Title of the page if it exists, false otherwise
4736 public static function getGroupPage( $group ) {
4737 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4738 if ( $msg->exists() ) {
4739 $title = Title
::newFromText( $msg->text() );
4740 if ( is_object( $title ) ) {
4748 * Create a link to the group in HTML, if available;
4749 * else return the group name.
4751 * @param string $group Internal name of the group
4752 * @param string $text The text of the link
4753 * @return string HTML link to the group
4755 public static function makeGroupLinkHTML( $group, $text = '' ) {
4756 if ( $text == '' ) {
4757 $text = self
::getGroupName( $group );
4759 $title = self
::getGroupPage( $group );
4761 return Linker
::link( $title, htmlspecialchars( $text ) );
4763 return htmlspecialchars( $text );
4768 * Create a link to the group in Wikitext, if available;
4769 * else return the group name.
4771 * @param string $group Internal name of the group
4772 * @param string $text The text of the link
4773 * @return string Wikilink to the group
4775 public static function makeGroupLinkWiki( $group, $text = '' ) {
4776 if ( $text == '' ) {
4777 $text = self
::getGroupName( $group );
4779 $title = self
::getGroupPage( $group );
4781 $page = $title->getFullText();
4782 return "[[$page|$text]]";
4789 * Returns an array of the groups that a particular group can add/remove.
4791 * @param string $group The group to check for whether it can add/remove
4792 * @return array Array( 'add' => array( addablegroups ),
4793 * 'remove' => array( removablegroups ),
4794 * 'add-self' => array( addablegroups to self),
4795 * 'remove-self' => array( removable groups from self) )
4797 public static function changeableByGroup( $group ) {
4798 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4807 if ( empty( $wgAddGroups[$group] ) ) {
4808 // Don't add anything to $groups
4809 } elseif ( $wgAddGroups[$group] === true ) {
4810 // You get everything
4811 $groups['add'] = self
::getAllGroups();
4812 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4813 $groups['add'] = $wgAddGroups[$group];
4816 // Same thing for remove
4817 if ( empty( $wgRemoveGroups[$group] ) ) {
4819 } elseif ( $wgRemoveGroups[$group] === true ) {
4820 $groups['remove'] = self
::getAllGroups();
4821 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4822 $groups['remove'] = $wgRemoveGroups[$group];
4825 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4826 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4827 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4828 if ( is_int( $key ) ) {
4829 $wgGroupsAddToSelf['user'][] = $value;
4834 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4835 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4836 if ( is_int( $key ) ) {
4837 $wgGroupsRemoveFromSelf['user'][] = $value;
4842 // Now figure out what groups the user can add to him/herself
4843 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4845 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4846 // No idea WHY this would be used, but it's there
4847 $groups['add-self'] = User
::getAllGroups();
4848 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4849 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4852 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4854 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4855 $groups['remove-self'] = User
::getAllGroups();
4856 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4857 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4864 * Returns an array of groups that this user can add and remove
4865 * @return array Array( 'add' => array( addablegroups ),
4866 * 'remove' => array( removablegroups ),
4867 * 'add-self' => array( addablegroups to self),
4868 * 'remove-self' => array( removable groups from self) )
4870 public function changeableGroups() {
4871 if ( $this->isAllowed( 'userrights' ) ) {
4872 // This group gives the right to modify everything (reverse-
4873 // compatibility with old "userrights lets you change
4875 // Using array_merge to make the groups reindexed
4876 $all = array_merge( User
::getAllGroups() );
4885 // Okay, it's not so simple, we will have to go through the arrays
4892 $addergroups = $this->getEffectiveGroups();
4894 foreach ( $addergroups as $addergroup ) {
4895 $groups = array_merge_recursive(
4896 $groups, $this->changeableByGroup( $addergroup )
4898 $groups['add'] = array_unique( $groups['add'] );
4899 $groups['remove'] = array_unique( $groups['remove'] );
4900 $groups['add-self'] = array_unique( $groups['add-self'] );
4901 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4907 * Deferred version of incEditCountImmediate()
4909 public function incEditCount() {
4910 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() {
4911 $this->incEditCountImmediate();
4916 * Increment the user's edit-count field.
4917 * Will have no effect for anonymous users.
4920 public function incEditCountImmediate() {
4921 if ( $this->isAnon() ) {
4925 $dbw = wfGetDB( DB_MASTER
);
4926 // No rows will be "affected" if user_editcount is NULL
4929 [ 'user_editcount=user_editcount+1' ],
4930 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
4933 // Lazy initialization check...
4934 if ( $dbw->affectedRows() == 0 ) {
4935 // Now here's a goddamn hack...
4936 $dbr = wfGetDB( DB_SLAVE
);
4937 if ( $dbr !== $dbw ) {
4938 // If we actually have a slave server, the count is
4939 // at least one behind because the current transaction
4940 // has not been committed and replicated.
4941 $this->initEditCount( 1 );
4943 // But if DB_SLAVE is selecting the master, then the
4944 // count we just read includes the revision that was
4945 // just added in the working transaction.
4946 $this->initEditCount();
4949 // Edit count in user cache too
4950 $this->invalidateCache();
4954 * Initialize user_editcount from data out of the revision table
4956 * @param int $add Edits to add to the count from the revision table
4957 * @return int Number of edits
4959 protected function initEditCount( $add = 0 ) {
4960 // Pull from a slave to be less cruel to servers
4961 // Accuracy isn't the point anyway here
4962 $dbr = wfGetDB( DB_SLAVE
);
4963 $count = (int)$dbr->selectField(
4966 [ 'rev_user' => $this->getId() ],
4969 $count = $count +
$add;
4971 $dbw = wfGetDB( DB_MASTER
);
4974 [ 'user_editcount' => $count ],
4975 [ 'user_id' => $this->getId() ],
4983 * Get the description of a given right
4985 * @param string $right Right to query
4986 * @return string Localized description of the right
4988 public static function getRightDescription( $right ) {
4989 $key = "right-$right";
4990 $msg = wfMessage( $key );
4991 return $msg->isBlank() ?
$right : $msg->text();
4995 * Make a new-style password hash
4997 * @param string $password Plain-text password
4998 * @param bool|string $salt Optional salt, may be random or the user ID.
4999 * If unspecified or false, will generate one automatically
5000 * @return string Password hash
5001 * @deprecated since 1.24, use Password class
5003 public static function crypt( $password, $salt = false ) {
5004 wfDeprecated( __METHOD__
, '1.24' );
5005 $passwordFactory = new PasswordFactory();
5006 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5007 $hash = $passwordFactory->newFromPlaintext( $password );
5008 return $hash->toString();
5012 * Compare a password hash with a plain-text password. Requires the user
5013 * ID if there's a chance that the hash is an old-style hash.
5015 * @param string $hash Password hash
5016 * @param string $password Plain-text password to compare
5017 * @param string|bool $userId User ID for old-style password salt
5020 * @deprecated since 1.24, use Password class
5022 public static function comparePasswords( $hash, $password, $userId = false ) {
5023 wfDeprecated( __METHOD__
, '1.24' );
5025 // Check for *really* old password hashes that don't even have a type
5026 // The old hash format was just an md5 hex hash, with no type information
5027 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5028 global $wgPasswordSalt;
5029 if ( $wgPasswordSalt ) {
5030 $password = ":B:{$userId}:{$hash}";
5032 $password = ":A:{$hash}";
5036 $passwordFactory = new PasswordFactory();
5037 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5038 $hash = $passwordFactory->newFromCiphertext( $hash );
5039 return $hash->equals( $password );
5043 * Add a newuser log entry for this user.
5044 * Before 1.19 the return value was always true.
5046 * @param string|bool $action Account creation type.
5047 * - String, one of the following values:
5048 * - 'create' for an anonymous user creating an account for himself.
5049 * This will force the action's performer to be the created user itself,
5050 * no matter the value of $wgUser
5051 * - 'create2' for a logged in user creating an account for someone else
5052 * - 'byemail' when the created user will receive its password by e-mail
5053 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5054 * - Boolean means whether the account was created by e-mail (deprecated):
5055 * - true will be converted to 'byemail'
5056 * - false will be converted to 'create' if this object is the same as
5057 * $wgUser and to 'create2' otherwise
5059 * @param string $reason User supplied reason
5061 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
5063 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5064 global $wgUser, $wgNewUserLog;
5065 if ( empty( $wgNewUserLog ) ) {
5066 return true; // disabled
5069 if ( $action === true ) {
5070 $action = 'byemail';
5071 } elseif ( $action === false ) {
5072 if ( $this->equals( $wgUser ) ) {
5075 $action = 'create2';
5079 if ( $action === 'create' ||
$action === 'autocreate' ) {
5082 $performer = $wgUser;
5085 $logEntry = new ManualLogEntry( 'newusers', $action );
5086 $logEntry->setPerformer( $performer );
5087 $logEntry->setTarget( $this->getUserPage() );
5088 $logEntry->setComment( $reason );
5089 $logEntry->setParameters( [
5090 '4::userid' => $this->getId(),
5092 $logid = $logEntry->insert();
5094 if ( $action !== 'autocreate' ) {
5095 $logEntry->publish( $logid );
5102 * Add an autocreate newuser log entry for this user
5103 * Used by things like CentralAuth and perhaps other authplugins.
5104 * Consider calling addNewUserLogEntry() directly instead.
5108 public function addNewUserLogEntryAutoCreate() {
5109 $this->addNewUserLogEntry( 'autocreate' );
5115 * Load the user options either from cache, the database or an array
5117 * @param array $data Rows for the current user out of the user_properties table
5119 protected function loadOptions( $data = null ) {
5124 if ( $this->mOptionsLoaded
) {
5128 $this->mOptions
= self
::getDefaultOptions();
5130 if ( !$this->getId() ) {
5131 // For unlogged-in users, load language/variant options from request.
5132 // There's no need to do it for logged-in users: they can set preferences,
5133 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5134 // so don't override user's choice (especially when the user chooses site default).
5135 $variant = $wgContLang->getDefaultVariant();
5136 $this->mOptions
['variant'] = $variant;
5137 $this->mOptions
['language'] = $variant;
5138 $this->mOptionsLoaded
= true;
5142 // Maybe load from the object
5143 if ( !is_null( $this->mOptionOverrides
) ) {
5144 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5145 foreach ( $this->mOptionOverrides
as $key => $value ) {
5146 $this->mOptions
[$key] = $value;
5149 if ( !is_array( $data ) ) {
5150 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5151 // Load from database
5152 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5153 ?
wfGetDB( DB_MASTER
)
5154 : wfGetDB( DB_SLAVE
);
5156 $res = $dbr->select(
5158 [ 'up_property', 'up_value' ],
5159 [ 'up_user' => $this->getId() ],
5163 $this->mOptionOverrides
= [];
5165 foreach ( $res as $row ) {
5166 $data[$row->up_property
] = $row->up_value
;
5169 foreach ( $data as $property => $value ) {
5170 $this->mOptionOverrides
[$property] = $value;
5171 $this->mOptions
[$property] = $value;
5175 $this->mOptionsLoaded
= true;
5177 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5181 * Saves the non-default options for this user, as previously set e.g. via
5182 * setOption(), in the database's "user_properties" (preferences) table.
5183 * Usually used via saveSettings().
5185 protected function saveOptions() {
5186 $this->loadOptions();
5188 // Not using getOptions(), to keep hidden preferences in database
5189 $saveOptions = $this->mOptions
;
5191 // Allow hooks to abort, for instance to save to a global profile.
5192 // Reset options to default state before saving.
5193 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5197 $userId = $this->getId();
5199 $insert_rows = []; // all the new preference rows
5200 foreach ( $saveOptions as $key => $value ) {
5201 // Don't bother storing default values
5202 $defaultOption = self
::getDefaultOption( $key );
5203 if ( ( $defaultOption === null && $value !== false && $value !== null )
5204 ||
$value != $defaultOption
5207 'up_user' => $userId,
5208 'up_property' => $key,
5209 'up_value' => $value,
5214 $dbw = wfGetDB( DB_MASTER
);
5216 $res = $dbw->select( 'user_properties',
5217 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5219 // Find prior rows that need to be removed or updated. These rows will
5220 // all be deleted (the later so that INSERT IGNORE applies the new values).
5222 foreach ( $res as $row ) {
5223 if ( !isset( $saveOptions[$row->up_property
] )
5224 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5226 $keysDelete[] = $row->up_property
;
5230 if ( count( $keysDelete ) ) {
5231 // Do the DELETE by PRIMARY KEY for prior rows.
5232 // In the past a very large portion of calls to this function are for setting
5233 // 'rememberpassword' for new accounts (a preference that has since been removed).
5234 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5235 // caused gap locks on [max user ID,+infinity) which caused high contention since
5236 // updates would pile up on each other as they are for higher (newer) user IDs.
5237 // It might not be necessary these days, but it shouldn't hurt either.
5238 $dbw->delete( 'user_properties',
5239 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5241 // Insert the new preference rows
5242 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5246 * Lazily instantiate and return a factory object for making passwords
5248 * @deprecated since 1.27, create a PasswordFactory directly instead
5249 * @return PasswordFactory
5251 public static function getPasswordFactory() {
5252 wfDeprecated( __METHOD__
, '1.27' );
5253 $ret = new PasswordFactory();
5254 $ret->init( RequestContext
::getMain()->getConfig() );
5259 * Provide an array of HTML5 attributes to put on an input element
5260 * intended for the user to enter a new password. This may include
5261 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5263 * Do *not* use this when asking the user to enter his current password!
5264 * Regardless of configuration, users may have invalid passwords for whatever
5265 * reason (e.g., they were set before requirements were tightened up).
5266 * Only use it when asking for a new password, like on account creation or
5269 * Obviously, you still need to do server-side checking.
5271 * NOTE: A combination of bugs in various browsers means that this function
5272 * actually just returns array() unconditionally at the moment. May as
5273 * well keep it around for when the browser bugs get fixed, though.
5275 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5277 * @deprecated since 1.27
5278 * @return array Array of HTML attributes suitable for feeding to
5279 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5280 * That will get confused by the boolean attribute syntax used.)
5282 public static function passwordChangeInputAttribs() {
5283 global $wgMinimalPasswordLength;
5285 if ( $wgMinimalPasswordLength == 0 ) {
5289 # Note that the pattern requirement will always be satisfied if the
5290 # input is empty, so we need required in all cases.
5292 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5293 # if e-mail confirmation is being used. Since HTML5 input validation
5294 # is b0rked anyway in some browsers, just return nothing. When it's
5295 # re-enabled, fix this code to not output required for e-mail
5297 # $ret = array( 'required' );
5300 # We can't actually do this right now, because Opera 9.6 will print out
5301 # the entered password visibly in its error message! When other
5302 # browsers add support for this attribute, or Opera fixes its support,
5303 # we can add support with a version check to avoid doing this on Opera
5304 # versions where it will be a problem. Reported to Opera as
5305 # DSK-262266, but they don't have a public bug tracker for us to follow.
5307 if ( $wgMinimalPasswordLength > 1 ) {
5308 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5309 $ret['title'] = wfMessage( 'passwordtooshort' )
5310 ->numParams( $wgMinimalPasswordLength )->text();
5318 * Return the list of user fields that should be selected to create
5319 * a new user object.
5322 public static function selectFields() {
5330 'user_email_authenticated',
5332 'user_email_token_expires',
5333 'user_registration',
5339 * Factory function for fatal permission-denied errors
5342 * @param string $permission User right required
5345 static function newFatalPermissionDeniedStatus( $permission ) {
5348 $groups = array_map(
5349 [ 'User', 'makeGroupLinkWiki' ],
5350 User
::getGroupsWithPermission( $permission )
5354 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5356 return Status
::newFatal( 'badaccess-group0' );
5361 * Get a new instance of this user that was loaded from the master via a locking read
5363 * Use this instead of the main context User when updating that user. This avoids races
5364 * where that user was loaded from a slave or even the master but without proper locks.
5366 * @return User|null Returns null if the user was not found in the DB
5369 public function getInstanceForUpdate() {
5370 if ( !$this->getId() ) {
5371 return null; // anon
5374 $user = self
::newFromId( $this->getId() );
5375 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5383 * Checks if two user objects point to the same user.
5389 public function equals( User
$user ) {
5390 return $this->getName() === $user->getName();