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()->addWatchBatchForUser(
3472 [ $title->getSubjectPage(), $title->getTalkPage() ]
3475 $this->invalidateCache();
3479 * Stop watching an article.
3480 * @since 1.22 $checkRights parameter added
3481 * @param Title $title Title of the article to look at
3482 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3483 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3485 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3486 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3487 WatchedItemStore
::getDefaultInstance()->removeWatch( $this, $title->getSubjectPage() );
3488 WatchedItemStore
::getDefaultInstance()->removeWatch( $this, $title->getTalkPage() );
3490 $this->invalidateCache();
3494 * Clear the user's notification timestamp for the given title.
3495 * If e-notif e-mails are on, they will receive notification mails on
3496 * the next change of the page if it's watched etc.
3497 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3498 * @param Title $title Title of the article to look at
3499 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3501 public function clearNotification( &$title, $oldid = 0 ) {
3502 global $wgUseEnotif, $wgShowUpdatedMarker;
3504 // Do nothing if the database is locked to writes
3505 if ( wfReadOnly() ) {
3509 // Do nothing if not allowed to edit the watchlist
3510 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3514 // If we're working on user's talk page, we should update the talk page message indicator
3515 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3516 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$this, $oldid ] ) ) {
3520 // Try to update the DB post-send and only if needed...
3521 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3522 if ( !$this->getNewtalk() ) {
3523 return; // no notifications to clear
3526 // Delete the last notifications (they stack up)
3527 $this->setNewtalk( false );
3529 // If there is a new, unseen, revision, use its timestamp
3531 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3534 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3539 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3543 if ( $this->isAnon() ) {
3544 // Nothing else to do...
3548 // Only update the timestamp if the page is being watched.
3549 // The query to find out if it is watched is cached both in memcached and per-invocation,
3550 // and when it does have to be executed, it can be on a slave
3551 // If this is the user's newtalk page, we always update the timestamp
3553 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3557 WatchedItemStore
::getDefaultInstance()
3558 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3562 * Resets all of the given user's page-change notification timestamps.
3563 * If e-notif e-mails are on, they will receive notification mails on
3564 * the next change of any watched page.
3565 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3567 public function clearAllNotifications() {
3568 if ( wfReadOnly() ) {
3572 // Do nothing if not allowed to edit the watchlist
3573 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3577 global $wgUseEnotif, $wgShowUpdatedMarker;
3578 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3579 $this->setNewtalk( false );
3582 $id = $this->getId();
3584 $dbw = wfGetDB( DB_MASTER
);
3585 $dbw->update( 'watchlist',
3586 [ /* SET */ 'wl_notificationtimestamp' => null ],
3587 [ /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3590 // We also need to clear here the "you have new message" notification for the own user_talk page;
3591 // it's cleared one page view later in WikiPage::doViewUpdates().
3596 * Set a cookie on the user's client. Wrapper for
3597 * WebResponse::setCookie
3598 * @deprecated since 1.27
3599 * @param string $name Name of the cookie to set
3600 * @param string $value Value to set
3601 * @param int $exp Expiration time, as a UNIX time value;
3602 * if 0 or not specified, use the default $wgCookieExpiration
3603 * @param bool $secure
3604 * true: Force setting the secure attribute when setting the cookie
3605 * false: Force NOT setting the secure attribute when setting the cookie
3606 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3607 * @param array $params Array of options sent passed to WebResponse::setcookie()
3608 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3611 protected function setCookie(
3612 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3614 wfDeprecated( __METHOD__
, '1.27' );
3615 if ( $request === null ) {
3616 $request = $this->getRequest();
3618 $params['secure'] = $secure;
3619 $request->response()->setCookie( $name, $value, $exp, $params );
3623 * Clear a cookie on the user's client
3624 * @deprecated since 1.27
3625 * @param string $name Name of the cookie to clear
3626 * @param bool $secure
3627 * true: Force setting the secure attribute when setting the cookie
3628 * false: Force NOT setting the secure attribute when setting the cookie
3629 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3630 * @param array $params Array of options sent passed to WebResponse::setcookie()
3632 protected function clearCookie( $name, $secure = null, $params = [] ) {
3633 wfDeprecated( __METHOD__
, '1.27' );
3634 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3638 * Set an extended login cookie on the user's client. The expiry of the cookie
3639 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3642 * @see User::setCookie
3644 * @deprecated since 1.27
3645 * @param string $name Name of the cookie to set
3646 * @param string $value Value to set
3647 * @param bool $secure
3648 * true: Force setting the secure attribute when setting the cookie
3649 * false: Force NOT setting the secure attribute when setting the cookie
3650 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3652 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3653 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3655 wfDeprecated( __METHOD__
, '1.27' );
3658 $exp +
= $wgExtendedLoginCookieExpiration !== null
3659 ?
$wgExtendedLoginCookieExpiration
3660 : $wgCookieExpiration;
3662 $this->setCookie( $name, $value, $exp, $secure );
3666 * Persist this user's session (e.g. set cookies)
3668 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3670 * @param bool $secure Whether to force secure/insecure cookies or use default
3671 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3673 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3675 if ( 0 == $this->mId
) {
3679 $session = $this->getRequest()->getSession();
3680 if ( $request && $session->getRequest() !== $request ) {
3681 $session = $session->sessionWithRequest( $request );
3683 $delay = $session->delaySave();
3685 if ( !$session->getUser()->equals( $this ) ) {
3686 if ( !$session->canSetUser() ) {
3687 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3688 ->warning( __METHOD__
.
3689 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3693 $session->setUser( $this );
3696 $session->setRememberUser( $rememberMe );
3697 if ( $secure !== null ) {
3698 $session->setForceHTTPS( $secure );
3701 $session->persist();
3703 ScopedCallback
::consume( $delay );
3707 * Log this user out.
3709 public function logout() {
3710 if ( Hooks
::run( 'UserLogout', [ &$this ] ) ) {
3716 * Clear the user's session, and reset the instance cache.
3719 public function doLogout() {
3720 $session = $this->getRequest()->getSession();
3721 if ( !$session->canSetUser() ) {
3722 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3723 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3724 } elseif ( !$session->getUser()->equals( $this ) ) {
3725 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3726 ->warning( __METHOD__
.
3727 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3729 // But we still may as well make this user object anon
3730 $this->clearInstanceCache( 'defaults' );
3732 $this->clearInstanceCache( 'defaults' );
3733 $delay = $session->delaySave();
3734 $session->unpersist(); // Clear cookies (T127436)
3735 $session->setLoggedOutTimestamp( time() );
3736 $session->setUser( new User
);
3737 $session->set( 'wsUserID', 0 ); // Other code expects this
3738 ScopedCallback
::consume( $delay );
3743 * Save this user's settings into the database.
3744 * @todo Only rarely do all these fields need to be set!
3746 public function saveSettings() {
3747 if ( wfReadOnly() ) {
3748 // @TODO: caller should deal with this instead!
3749 // This should really just be an exception.
3750 MWExceptionHandler
::logException( new DBExpectedError(
3752 "Could not update user with ID '{$this->mId}'; DB is read-only."
3758 if ( 0 == $this->mId
) {
3762 // Get a new user_touched that is higher than the old one.
3763 // This will be used for a CAS check as a last-resort safety
3764 // check against race conditions and slave lag.
3765 $oldTouched = $this->mTouched
;
3766 $newTouched = $this->newTouchedTimestamp();
3768 $dbw = wfGetDB( DB_MASTER
);
3769 $dbw->update( 'user',
3771 'user_name' => $this->mName
,
3772 'user_real_name' => $this->mRealName
,
3773 'user_email' => $this->mEmail
,
3774 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3775 'user_touched' => $dbw->timestamp( $newTouched ),
3776 'user_token' => strval( $this->mToken
),
3777 'user_email_token' => $this->mEmailToken
,
3778 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3780 'user_id' => $this->mId
,
3781 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3785 if ( !$dbw->affectedRows() ) {
3786 // Maybe the problem was a missed cache update; clear it to be safe
3787 $this->clearSharedCache( 'refresh' );
3788 // User was changed in the meantime or loaded with stale data
3789 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3790 throw new MWException(
3791 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3792 " the version of the user to be saved is older than the current version."
3796 $this->mTouched
= $newTouched;
3797 $this->saveOptions();
3799 Hooks
::run( 'UserSaveSettings', [ $this ] );
3800 $this->clearSharedCache();
3801 $this->getUserPage()->invalidateCache();
3805 * If only this user's username is known, and it exists, return the user ID.
3807 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3810 public function idForName( $flags = 0 ) {
3811 $s = trim( $this->getName() );
3816 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3817 ?
wfGetDB( DB_MASTER
)
3818 : wfGetDB( DB_SLAVE
);
3820 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3821 ?
[ 'LOCK IN SHARE MODE' ]
3824 $id = $db->selectField( 'user',
3825 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
3831 * Add a user to the database, return the user object
3833 * @param string $name Username to add
3834 * @param array $params Array of Strings Non-default parameters to save to
3835 * the database as user_* fields:
3836 * - email: The user's email address.
3837 * - email_authenticated: The email authentication timestamp.
3838 * - real_name: The user's real name.
3839 * - options: An associative array of non-default options.
3840 * - token: Random authentication token. Do not set.
3841 * - registration: Registration timestamp. Do not set.
3843 * @return User|null User object, or null if the username already exists.
3845 public static function createNew( $name, $params = [] ) {
3846 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
3847 if ( isset( $params[$field] ) ) {
3848 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3849 unset( $params[$field] );
3855 $user->setToken(); // init token
3856 if ( isset( $params['options'] ) ) {
3857 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3858 unset( $params['options'] );
3860 $dbw = wfGetDB( DB_MASTER
);
3861 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3863 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3866 'user_id' => $seqVal,
3867 'user_name' => $name,
3868 'user_password' => $noPass,
3869 'user_newpassword' => $noPass,
3870 'user_email' => $user->mEmail
,
3871 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3872 'user_real_name' => $user->mRealName
,
3873 'user_token' => strval( $user->mToken
),
3874 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3875 'user_editcount' => 0,
3876 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3878 foreach ( $params as $name => $value ) {
3879 $fields["user_$name"] = $value;
3881 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
3882 if ( $dbw->affectedRows() ) {
3883 $newUser = User
::newFromId( $dbw->insertId() );
3891 * Add this existing user object to the database. If the user already
3892 * exists, a fatal status object is returned, and the user object is
3893 * initialised with the data from the database.
3895 * Previously, this function generated a DB error due to a key conflict
3896 * if the user already existed. Many extension callers use this function
3897 * in code along the lines of:
3899 * $user = User::newFromName( $name );
3900 * if ( !$user->isLoggedIn() ) {
3901 * $user->addToDatabase();
3903 * // do something with $user...
3905 * However, this was vulnerable to a race condition (bug 16020). By
3906 * initialising the user object if the user exists, we aim to support this
3907 * calling sequence as far as possible.
3909 * Note that if the user exists, this function will acquire a write lock,
3910 * so it is still advisable to make the call conditional on isLoggedIn(),
3911 * and to commit the transaction after calling.
3913 * @throws MWException
3916 public function addToDatabase() {
3918 if ( !$this->mToken
) {
3919 $this->setToken(); // init token
3922 $this->mTouched
= $this->newTouchedTimestamp();
3924 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3926 $dbw = wfGetDB( DB_MASTER
);
3927 $inWrite = $dbw->writesOrCallbacksPending();
3928 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3929 $dbw->insert( 'user',
3931 'user_id' => $seqVal,
3932 'user_name' => $this->mName
,
3933 'user_password' => $noPass,
3934 'user_newpassword' => $noPass,
3935 'user_email' => $this->mEmail
,
3936 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3937 'user_real_name' => $this->mRealName
,
3938 'user_token' => strval( $this->mToken
),
3939 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3940 'user_editcount' => 0,
3941 'user_touched' => $dbw->timestamp( $this->mTouched
),
3945 if ( !$dbw->affectedRows() ) {
3946 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3947 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3949 // Can't commit due to pending writes that may need atomicity.
3950 // This may cause some lock contention unlike the case below.
3951 $options = [ 'LOCK IN SHARE MODE' ];
3952 $flags = self
::READ_LOCKING
;
3954 // Often, this case happens early in views before any writes when
3955 // using CentralAuth. It's should be OK to commit and break the snapshot.
3956 $dbw->commit( __METHOD__
, 'flush' );
3958 $flags = self
::READ_LATEST
;
3960 $this->mId
= $dbw->selectField( 'user', 'user_id',
3961 [ 'user_name' => $this->mName
], __METHOD__
, $options );
3964 if ( $this->loadFromDatabase( $flags ) ) {
3969 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3970 "to insert user '{$this->mName}' row, but it was not present in select!" );
3972 return Status
::newFatal( 'userexists' );
3974 $this->mId
= $dbw->insertId();
3975 self
::$idCacheByName[$this->mName
] = $this->mId
;
3977 // Clear instance cache other than user table data, which is already accurate
3978 $this->clearInstanceCache();
3980 $this->saveOptions();
3981 return Status
::newGood();
3985 * If this user is logged-in and blocked,
3986 * block any IP address they've successfully logged in from.
3987 * @return bool A block was spread
3989 public function spreadAnyEditBlock() {
3990 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3991 return $this->spreadBlock();
3998 * If this (non-anonymous) user is blocked,
3999 * block the IP address they've successfully logged in from.
4000 * @return bool A block was spread
4002 protected function spreadBlock() {
4003 wfDebug( __METHOD__
. "()\n" );
4005 if ( $this->mId
== 0 ) {
4009 $userblock = Block
::newFromTarget( $this->getName() );
4010 if ( !$userblock ) {
4014 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4018 * Get whether the user is explicitly blocked from account creation.
4019 * @return bool|Block
4021 public function isBlockedFromCreateAccount() {
4022 $this->getBlockedStatus();
4023 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4024 return $this->mBlock
;
4027 # bug 13611: if the IP address the user is trying to create an account from is
4028 # blocked with createaccount disabled, prevent new account creation there even
4029 # when the user is logged in
4030 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4031 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4033 return $this->mBlockedFromCreateAccount
instanceof Block
4034 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4035 ?
$this->mBlockedFromCreateAccount
4040 * Get whether the user is blocked from using Special:Emailuser.
4043 public function isBlockedFromEmailuser() {
4044 $this->getBlockedStatus();
4045 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4049 * Get whether the user is allowed to create an account.
4052 public function isAllowedToCreateAccount() {
4053 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4057 * Get this user's personal page title.
4059 * @return Title User's personal page title
4061 public function getUserPage() {
4062 return Title
::makeTitle( NS_USER
, $this->getName() );
4066 * Get this user's talk page title.
4068 * @return Title User's talk page title
4070 public function getTalkPage() {
4071 $title = $this->getUserPage();
4072 return $title->getTalkPage();
4076 * Determine whether the user is a newbie. Newbies are either
4077 * anonymous IPs, or the most recently created accounts.
4080 public function isNewbie() {
4081 return !$this->isAllowed( 'autoconfirmed' );
4085 * Check to see if the given clear-text password is one of the accepted passwords
4086 * @deprecated since 1.27. AuthManager is coming.
4087 * @param string $password User password
4088 * @return bool True if the given password is correct, otherwise False
4090 public function checkPassword( $password ) {
4091 global $wgAuth, $wgLegacyEncoding;
4095 // Some passwords will give a fatal Status, which means there is
4096 // some sort of technical or security reason for this password to
4097 // be completely invalid and should never be checked (e.g., T64685)
4098 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4102 // Certain authentication plugins do NOT want to save
4103 // domain passwords in a mysql database, so we should
4104 // check this (in case $wgAuth->strict() is false).
4105 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4107 } elseif ( $wgAuth->strict() ) {
4108 // Auth plugin doesn't allow local authentication
4110 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4111 // Auth plugin doesn't allow local authentication for this user name
4115 $passwordFactory = new PasswordFactory();
4116 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4117 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4118 ?
wfGetDB( DB_MASTER
)
4119 : wfGetDB( DB_SLAVE
);
4122 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4123 'user', 'user_password', [ 'user_id' => $this->getId() ], __METHOD__
4125 } catch ( PasswordError
$e ) {
4126 wfDebug( 'Invalid password hash found in database.' );
4127 $mPassword = PasswordFactory
::newInvalidPassword();
4130 if ( !$mPassword->equals( $password ) ) {
4131 if ( $wgLegacyEncoding ) {
4132 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4133 // Check for this with iconv
4134 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4135 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4143 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4144 $this->setPasswordInternal( $password );
4151 * Check if the given clear-text password matches the temporary password
4152 * sent by e-mail for password reset operations.
4154 * @deprecated since 1.27. AuthManager is coming.
4155 * @param string $plaintext
4156 * @return bool True if matches, false otherwise
4158 public function checkTemporaryPassword( $plaintext ) {
4159 global $wgNewPasswordExpiry;
4163 $passwordFactory = new PasswordFactory();
4164 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4165 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4166 ?
wfGetDB( DB_MASTER
)
4167 : wfGetDB( DB_SLAVE
);
4169 $row = $db->selectRow(
4171 [ 'user_newpassword', 'user_newpass_time' ],
4172 [ 'user_id' => $this->getId() ],
4176 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4177 } catch ( PasswordError
$e ) {
4178 wfDebug( 'Invalid password hash found in database.' );
4179 $newPassword = PasswordFactory
::newInvalidPassword();
4182 if ( $newPassword->equals( $plaintext ) ) {
4183 if ( is_null( $row->user_newpass_time
) ) {
4186 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4187 return ( time() < $expiry );
4194 * Initialize (if necessary) and return a session token value
4195 * which can be used in edit forms to show that the user's
4196 * login credentials aren't being hijacked with a foreign form
4200 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4201 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4202 * @return MediaWiki\\Session\\Token The new edit token
4204 public function getEditTokenObject( $salt = '', $request = null ) {
4205 if ( $this->isAnon() ) {
4206 return new LoggedOutEditToken();
4210 $request = $this->getRequest();
4212 return $request->getSession()->getToken( $salt );
4216 * Initialize (if necessary) and return a session token value
4217 * which can be used in edit forms to show that the user's
4218 * login credentials aren't being hijacked with a foreign form
4222 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4223 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4224 * @return string The new edit token
4226 public function getEditToken( $salt = '', $request = null ) {
4227 return $this->getEditTokenObject( $salt, $request )->toString();
4231 * Get the embedded timestamp from a token.
4232 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::getTimestamp instead.
4233 * @param string $val Input token
4236 public static function getEditTokenTimestamp( $val ) {
4237 wfDeprecated( __METHOD__
, '1.27' );
4238 return MediaWiki\Session\Token
::getTimestamp( $val );
4242 * Check given value against the token value stored in the session.
4243 * A match should confirm that the form was submitted from the
4244 * user's own login session, not a form submission from a third-party
4247 * @param string $val Input value to compare
4248 * @param string $salt Optional function-specific data for hashing
4249 * @param WebRequest|null $request Object to use or null to use $wgRequest
4250 * @param int $maxage Fail tokens older than this, in seconds
4251 * @return bool Whether the token matches
4253 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4254 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4258 * Check given value against the token value stored in the session,
4259 * ignoring the suffix.
4261 * @param string $val Input value to compare
4262 * @param string $salt Optional function-specific data for hashing
4263 * @param WebRequest|null $request Object to use or null to use $wgRequest
4264 * @param int $maxage Fail tokens older than this, in seconds
4265 * @return bool Whether the token matches
4267 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4268 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4269 return $this->matchEditToken( $val, $salt, $request, $maxage );
4273 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4274 * mail to the user's given address.
4276 * @param string $type Message to send, either "created", "changed" or "set"
4279 public function sendConfirmationMail( $type = 'created' ) {
4281 $expiration = null; // gets passed-by-ref and defined in next line.
4282 $token = $this->confirmationToken( $expiration );
4283 $url = $this->confirmationTokenUrl( $token );
4284 $invalidateURL = $this->invalidationTokenUrl( $token );
4285 $this->saveSettings();
4287 if ( $type == 'created' ||
$type === false ) {
4288 $message = 'confirmemail_body';
4289 } elseif ( $type === true ) {
4290 $message = 'confirmemail_body_changed';
4292 // Messages: confirmemail_body_changed, confirmemail_body_set
4293 $message = 'confirmemail_body_' . $type;
4296 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4297 wfMessage( $message,
4298 $this->getRequest()->getIP(),
4301 $wgLang->userTimeAndDate( $expiration, $this ),
4303 $wgLang->userDate( $expiration, $this ),
4304 $wgLang->userTime( $expiration, $this ) )->text() );
4308 * Send an e-mail to this user's account. Does not check for
4309 * confirmed status or validity.
4311 * @param string $subject Message subject
4312 * @param string $body Message body
4313 * @param User|null $from Optional sending user; if unspecified, default
4314 * $wgPasswordSender will be used.
4315 * @param string $replyto Reply-To address
4318 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4319 global $wgPasswordSender;
4321 if ( $from instanceof User
) {
4322 $sender = MailAddress
::newFromUser( $from );
4324 $sender = new MailAddress( $wgPasswordSender,
4325 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4327 $to = MailAddress
::newFromUser( $this );
4329 return UserMailer
::send( $to, $sender, $subject, $body, [
4330 'replyTo' => $replyto,
4335 * Generate, store, and return a new e-mail confirmation code.
4336 * A hash (unsalted, since it's used as a key) is stored.
4338 * @note Call saveSettings() after calling this function to commit
4339 * this change to the database.
4341 * @param string &$expiration Accepts the expiration time
4342 * @return string New token
4344 protected function confirmationToken( &$expiration ) {
4345 global $wgUserEmailConfirmationTokenExpiry;
4347 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4348 $expiration = wfTimestamp( TS_MW
, $expires );
4350 $token = MWCryptRand
::generateHex( 32 );
4351 $hash = md5( $token );
4352 $this->mEmailToken
= $hash;
4353 $this->mEmailTokenExpires
= $expiration;
4358 * Return a URL the user can use to confirm their email address.
4359 * @param string $token Accepts the email confirmation token
4360 * @return string New token URL
4362 protected function confirmationTokenUrl( $token ) {
4363 return $this->getTokenUrl( 'ConfirmEmail', $token );
4367 * Return a URL the user can use to invalidate their email address.
4368 * @param string $token Accepts the email confirmation token
4369 * @return string New token URL
4371 protected function invalidationTokenUrl( $token ) {
4372 return $this->getTokenUrl( 'InvalidateEmail', $token );
4376 * Internal function to format the e-mail validation/invalidation URLs.
4377 * This uses a quickie hack to use the
4378 * hardcoded English names of the Special: pages, for ASCII safety.
4380 * @note Since these URLs get dropped directly into emails, using the
4381 * short English names avoids insanely long URL-encoded links, which
4382 * also sometimes can get corrupted in some browsers/mailers
4383 * (bug 6957 with Gmail and Internet Explorer).
4385 * @param string $page Special page
4386 * @param string $token Token
4387 * @return string Formatted URL
4389 protected function getTokenUrl( $page, $token ) {
4390 // Hack to bypass localization of 'Special:'
4391 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4392 return $title->getCanonicalURL();
4396 * Mark the e-mail address confirmed.
4398 * @note Call saveSettings() after calling this function to commit the change.
4402 public function confirmEmail() {
4403 // Check if it's already confirmed, so we don't touch the database
4404 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4405 if ( !$this->isEmailConfirmed() ) {
4406 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4407 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4413 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4414 * address if it was already confirmed.
4416 * @note Call saveSettings() after calling this function to commit the change.
4417 * @return bool Returns true
4419 public function invalidateEmail() {
4421 $this->mEmailToken
= null;
4422 $this->mEmailTokenExpires
= null;
4423 $this->setEmailAuthenticationTimestamp( null );
4425 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4430 * Set the e-mail authentication timestamp.
4431 * @param string $timestamp TS_MW timestamp
4433 public function setEmailAuthenticationTimestamp( $timestamp ) {
4435 $this->mEmailAuthenticated
= $timestamp;
4436 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4440 * Is this user allowed to send e-mails within limits of current
4441 * site configuration?
4444 public function canSendEmail() {
4445 global $wgEnableEmail, $wgEnableUserEmail;
4446 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4449 $canSend = $this->isEmailConfirmed();
4450 Hooks
::run( 'UserCanSendEmail', [ &$this, &$canSend ] );
4455 * Is this user allowed to receive e-mails within limits of current
4456 * site configuration?
4459 public function canReceiveEmail() {
4460 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4464 * Is this user's e-mail address valid-looking and confirmed within
4465 * limits of the current site configuration?
4467 * @note If $wgEmailAuthentication is on, this may require the user to have
4468 * confirmed their address by returning a code or using a password
4469 * sent to the address from the wiki.
4473 public function isEmailConfirmed() {
4474 global $wgEmailAuthentication;
4477 if ( Hooks
::run( 'EmailConfirmed', [ &$this, &$confirmed ] ) ) {
4478 if ( $this->isAnon() ) {
4481 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4484 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4494 * Check whether there is an outstanding request for e-mail confirmation.
4497 public function isEmailConfirmationPending() {
4498 global $wgEmailAuthentication;
4499 return $wgEmailAuthentication &&
4500 !$this->isEmailConfirmed() &&
4501 $this->mEmailToken
&&
4502 $this->mEmailTokenExpires
> wfTimestamp();
4506 * Get the timestamp of account creation.
4508 * @return string|bool|null Timestamp of account creation, false for
4509 * non-existent/anonymous user accounts, or null if existing account
4510 * but information is not in database.
4512 public function getRegistration() {
4513 if ( $this->isAnon() ) {
4517 return $this->mRegistration
;
4521 * Get the timestamp of the first edit
4523 * @return string|bool Timestamp of first edit, or false for
4524 * non-existent/anonymous user accounts.
4526 public function getFirstEditTimestamp() {
4527 if ( $this->getId() == 0 ) {
4528 return false; // anons
4530 $dbr = wfGetDB( DB_SLAVE
);
4531 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4532 [ 'rev_user' => $this->getId() ],
4534 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4537 return false; // no edits
4539 return wfTimestamp( TS_MW
, $time );
4543 * Get the permissions associated with a given list of groups
4545 * @param array $groups Array of Strings List of internal group names
4546 * @return array Array of Strings List of permission key names for given groups combined
4548 public static function getGroupPermissions( $groups ) {
4549 global $wgGroupPermissions, $wgRevokePermissions;
4551 // grant every granted permission first
4552 foreach ( $groups as $group ) {
4553 if ( isset( $wgGroupPermissions[$group] ) ) {
4554 $rights = array_merge( $rights,
4555 // array_filter removes empty items
4556 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4559 // now revoke the revoked permissions
4560 foreach ( $groups as $group ) {
4561 if ( isset( $wgRevokePermissions[$group] ) ) {
4562 $rights = array_diff( $rights,
4563 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4566 return array_unique( $rights );
4570 * Get all the groups who have a given permission
4572 * @param string $role Role to check
4573 * @return array Array of Strings List of internal group names with the given permission
4575 public static function getGroupsWithPermission( $role ) {
4576 global $wgGroupPermissions;
4577 $allowedGroups = [];
4578 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4579 if ( self
::groupHasPermission( $group, $role ) ) {
4580 $allowedGroups[] = $group;
4583 return $allowedGroups;
4587 * Check, if the given group has the given permission
4589 * If you're wanting to check whether all users have a permission, use
4590 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4594 * @param string $group Group to check
4595 * @param string $role Role to check
4598 public static function groupHasPermission( $group, $role ) {
4599 global $wgGroupPermissions, $wgRevokePermissions;
4600 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4601 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4605 * Check if all users may be assumed to have the given permission
4607 * We generally assume so if the right is granted to '*' and isn't revoked
4608 * on any group. It doesn't attempt to take grants or other extension
4609 * limitations on rights into account in the general case, though, as that
4610 * would require it to always return false and defeat the purpose.
4611 * Specifically, session-based rights restrictions (such as OAuth or bot
4612 * passwords) are applied based on the current session.
4615 * @param string $right Right to check
4618 public static function isEveryoneAllowed( $right ) {
4619 global $wgGroupPermissions, $wgRevokePermissions;
4622 // Use the cached results, except in unit tests which rely on
4623 // being able change the permission mid-request
4624 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4625 return $cache[$right];
4628 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4629 $cache[$right] = false;
4633 // If it's revoked anywhere, then everyone doesn't have it
4634 foreach ( $wgRevokePermissions as $rights ) {
4635 if ( isset( $rights[$right] ) && $rights[$right] ) {
4636 $cache[$right] = false;
4641 // Remove any rights that aren't allowed to the global-session user,
4642 // unless there are no sessions for this endpoint.
4643 if ( !defined( 'MW_NO_SESSION' ) ) {
4644 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4645 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4646 $cache[$right] = false;
4651 // Allow extensions to say false
4652 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4653 $cache[$right] = false;
4657 $cache[$right] = true;
4662 * Get the localized descriptive name for a group, if it exists
4664 * @param string $group Internal group name
4665 * @return string Localized descriptive group name
4667 public static function getGroupName( $group ) {
4668 $msg = wfMessage( "group-$group" );
4669 return $msg->isBlank() ?
$group : $msg->text();
4673 * Get the localized descriptive name for a member of a group, if it exists
4675 * @param string $group Internal group name
4676 * @param string $username Username for gender (since 1.19)
4677 * @return string Localized name for group member
4679 public static function getGroupMember( $group, $username = '#' ) {
4680 $msg = wfMessage( "group-$group-member", $username );
4681 return $msg->isBlank() ?
$group : $msg->text();
4685 * Return the set of defined explicit groups.
4686 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4687 * are not included, as they are defined automatically, not in the database.
4688 * @return array Array of internal group names
4690 public static function getAllGroups() {
4691 global $wgGroupPermissions, $wgRevokePermissions;
4693 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4694 self
::getImplicitGroups()
4699 * Get a list of all available permissions.
4700 * @return string[] Array of permission names
4702 public static function getAllRights() {
4703 if ( self
::$mAllRights === false ) {
4704 global $wgAvailableRights;
4705 if ( count( $wgAvailableRights ) ) {
4706 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4708 self
::$mAllRights = self
::$mCoreRights;
4710 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4712 return self
::$mAllRights;
4716 * Get a list of implicit groups
4717 * @return array Array of Strings Array of internal group names
4719 public static function getImplicitGroups() {
4720 global $wgImplicitGroups;
4722 $groups = $wgImplicitGroups;
4723 # Deprecated, use $wgImplicitGroups instead
4724 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4730 * Get the title of a page describing a particular group
4732 * @param string $group Internal group name
4733 * @return Title|bool Title of the page if it exists, false otherwise
4735 public static function getGroupPage( $group ) {
4736 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4737 if ( $msg->exists() ) {
4738 $title = Title
::newFromText( $msg->text() );
4739 if ( is_object( $title ) ) {
4747 * Create a link to the group in HTML, if available;
4748 * else return the group name.
4750 * @param string $group Internal name of the group
4751 * @param string $text The text of the link
4752 * @return string HTML link to the group
4754 public static function makeGroupLinkHTML( $group, $text = '' ) {
4755 if ( $text == '' ) {
4756 $text = self
::getGroupName( $group );
4758 $title = self
::getGroupPage( $group );
4760 return Linker
::link( $title, htmlspecialchars( $text ) );
4762 return htmlspecialchars( $text );
4767 * Create a link to the group in Wikitext, if available;
4768 * else return the group name.
4770 * @param string $group Internal name of the group
4771 * @param string $text The text of the link
4772 * @return string Wikilink to the group
4774 public static function makeGroupLinkWiki( $group, $text = '' ) {
4775 if ( $text == '' ) {
4776 $text = self
::getGroupName( $group );
4778 $title = self
::getGroupPage( $group );
4780 $page = $title->getFullText();
4781 return "[[$page|$text]]";
4788 * Returns an array of the groups that a particular group can add/remove.
4790 * @param string $group The group to check for whether it can add/remove
4791 * @return array Array( 'add' => array( addablegroups ),
4792 * 'remove' => array( removablegroups ),
4793 * 'add-self' => array( addablegroups to self),
4794 * 'remove-self' => array( removable groups from self) )
4796 public static function changeableByGroup( $group ) {
4797 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4806 if ( empty( $wgAddGroups[$group] ) ) {
4807 // Don't add anything to $groups
4808 } elseif ( $wgAddGroups[$group] === true ) {
4809 // You get everything
4810 $groups['add'] = self
::getAllGroups();
4811 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4812 $groups['add'] = $wgAddGroups[$group];
4815 // Same thing for remove
4816 if ( empty( $wgRemoveGroups[$group] ) ) {
4818 } elseif ( $wgRemoveGroups[$group] === true ) {
4819 $groups['remove'] = self
::getAllGroups();
4820 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4821 $groups['remove'] = $wgRemoveGroups[$group];
4824 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4825 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4826 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4827 if ( is_int( $key ) ) {
4828 $wgGroupsAddToSelf['user'][] = $value;
4833 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4834 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4835 if ( is_int( $key ) ) {
4836 $wgGroupsRemoveFromSelf['user'][] = $value;
4841 // Now figure out what groups the user can add to him/herself
4842 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4844 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4845 // No idea WHY this would be used, but it's there
4846 $groups['add-self'] = User
::getAllGroups();
4847 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4848 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4851 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4853 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4854 $groups['remove-self'] = User
::getAllGroups();
4855 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4856 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4863 * Returns an array of groups that this user can add and remove
4864 * @return array Array( 'add' => array( addablegroups ),
4865 * 'remove' => array( removablegroups ),
4866 * 'add-self' => array( addablegroups to self),
4867 * 'remove-self' => array( removable groups from self) )
4869 public function changeableGroups() {
4870 if ( $this->isAllowed( 'userrights' ) ) {
4871 // This group gives the right to modify everything (reverse-
4872 // compatibility with old "userrights lets you change
4874 // Using array_merge to make the groups reindexed
4875 $all = array_merge( User
::getAllGroups() );
4884 // Okay, it's not so simple, we will have to go through the arrays
4891 $addergroups = $this->getEffectiveGroups();
4893 foreach ( $addergroups as $addergroup ) {
4894 $groups = array_merge_recursive(
4895 $groups, $this->changeableByGroup( $addergroup )
4897 $groups['add'] = array_unique( $groups['add'] );
4898 $groups['remove'] = array_unique( $groups['remove'] );
4899 $groups['add-self'] = array_unique( $groups['add-self'] );
4900 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4906 * Deferred version of incEditCountImmediate()
4908 public function incEditCount() {
4909 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() {
4910 $this->incEditCountImmediate();
4915 * Increment the user's edit-count field.
4916 * Will have no effect for anonymous users.
4919 public function incEditCountImmediate() {
4920 if ( $this->isAnon() ) {
4924 $dbw = wfGetDB( DB_MASTER
);
4925 // No rows will be "affected" if user_editcount is NULL
4928 [ 'user_editcount=user_editcount+1' ],
4929 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
4932 // Lazy initialization check...
4933 if ( $dbw->affectedRows() == 0 ) {
4934 // Now here's a goddamn hack...
4935 $dbr = wfGetDB( DB_SLAVE
);
4936 if ( $dbr !== $dbw ) {
4937 // If we actually have a slave server, the count is
4938 // at least one behind because the current transaction
4939 // has not been committed and replicated.
4940 $this->initEditCount( 1 );
4942 // But if DB_SLAVE is selecting the master, then the
4943 // count we just read includes the revision that was
4944 // just added in the working transaction.
4945 $this->initEditCount();
4948 // Edit count in user cache too
4949 $this->invalidateCache();
4953 * Initialize user_editcount from data out of the revision table
4955 * @param int $add Edits to add to the count from the revision table
4956 * @return int Number of edits
4958 protected function initEditCount( $add = 0 ) {
4959 // Pull from a slave to be less cruel to servers
4960 // Accuracy isn't the point anyway here
4961 $dbr = wfGetDB( DB_SLAVE
);
4962 $count = (int)$dbr->selectField(
4965 [ 'rev_user' => $this->getId() ],
4968 $count = $count +
$add;
4970 $dbw = wfGetDB( DB_MASTER
);
4973 [ 'user_editcount' => $count ],
4974 [ 'user_id' => $this->getId() ],
4982 * Get the description of a given right
4984 * @param string $right Right to query
4985 * @return string Localized description of the right
4987 public static function getRightDescription( $right ) {
4988 $key = "right-$right";
4989 $msg = wfMessage( $key );
4990 return $msg->isBlank() ?
$right : $msg->text();
4994 * Make a new-style password hash
4996 * @param string $password Plain-text password
4997 * @param bool|string $salt Optional salt, may be random or the user ID.
4998 * If unspecified or false, will generate one automatically
4999 * @return string Password hash
5000 * @deprecated since 1.24, use Password class
5002 public static function crypt( $password, $salt = false ) {
5003 wfDeprecated( __METHOD__
, '1.24' );
5004 $passwordFactory = new PasswordFactory();
5005 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5006 $hash = $passwordFactory->newFromPlaintext( $password );
5007 return $hash->toString();
5011 * Compare a password hash with a plain-text password. Requires the user
5012 * ID if there's a chance that the hash is an old-style hash.
5014 * @param string $hash Password hash
5015 * @param string $password Plain-text password to compare
5016 * @param string|bool $userId User ID for old-style password salt
5019 * @deprecated since 1.24, use Password class
5021 public static function comparePasswords( $hash, $password, $userId = false ) {
5022 wfDeprecated( __METHOD__
, '1.24' );
5024 // Check for *really* old password hashes that don't even have a type
5025 // The old hash format was just an md5 hex hash, with no type information
5026 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5027 global $wgPasswordSalt;
5028 if ( $wgPasswordSalt ) {
5029 $password = ":B:{$userId}:{$hash}";
5031 $password = ":A:{$hash}";
5035 $passwordFactory = new PasswordFactory();
5036 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5037 $hash = $passwordFactory->newFromCiphertext( $hash );
5038 return $hash->equals( $password );
5042 * Add a newuser log entry for this user.
5043 * Before 1.19 the return value was always true.
5045 * @param string|bool $action Account creation type.
5046 * - String, one of the following values:
5047 * - 'create' for an anonymous user creating an account for himself.
5048 * This will force the action's performer to be the created user itself,
5049 * no matter the value of $wgUser
5050 * - 'create2' for a logged in user creating an account for someone else
5051 * - 'byemail' when the created user will receive its password by e-mail
5052 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5053 * - Boolean means whether the account was created by e-mail (deprecated):
5054 * - true will be converted to 'byemail'
5055 * - false will be converted to 'create' if this object is the same as
5056 * $wgUser and to 'create2' otherwise
5058 * @param string $reason User supplied reason
5060 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
5062 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5063 global $wgUser, $wgNewUserLog;
5064 if ( empty( $wgNewUserLog ) ) {
5065 return true; // disabled
5068 if ( $action === true ) {
5069 $action = 'byemail';
5070 } elseif ( $action === false ) {
5071 if ( $this->equals( $wgUser ) ) {
5074 $action = 'create2';
5078 if ( $action === 'create' ||
$action === 'autocreate' ) {
5081 $performer = $wgUser;
5084 $logEntry = new ManualLogEntry( 'newusers', $action );
5085 $logEntry->setPerformer( $performer );
5086 $logEntry->setTarget( $this->getUserPage() );
5087 $logEntry->setComment( $reason );
5088 $logEntry->setParameters( [
5089 '4::userid' => $this->getId(),
5091 $logid = $logEntry->insert();
5093 if ( $action !== 'autocreate' ) {
5094 $logEntry->publish( $logid );
5101 * Add an autocreate newuser log entry for this user
5102 * Used by things like CentralAuth and perhaps other authplugins.
5103 * Consider calling addNewUserLogEntry() directly instead.
5107 public function addNewUserLogEntryAutoCreate() {
5108 $this->addNewUserLogEntry( 'autocreate' );
5114 * Load the user options either from cache, the database or an array
5116 * @param array $data Rows for the current user out of the user_properties table
5118 protected function loadOptions( $data = null ) {
5123 if ( $this->mOptionsLoaded
) {
5127 $this->mOptions
= self
::getDefaultOptions();
5129 if ( !$this->getId() ) {
5130 // For unlogged-in users, load language/variant options from request.
5131 // There's no need to do it for logged-in users: they can set preferences,
5132 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5133 // so don't override user's choice (especially when the user chooses site default).
5134 $variant = $wgContLang->getDefaultVariant();
5135 $this->mOptions
['variant'] = $variant;
5136 $this->mOptions
['language'] = $variant;
5137 $this->mOptionsLoaded
= true;
5141 // Maybe load from the object
5142 if ( !is_null( $this->mOptionOverrides
) ) {
5143 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5144 foreach ( $this->mOptionOverrides
as $key => $value ) {
5145 $this->mOptions
[$key] = $value;
5148 if ( !is_array( $data ) ) {
5149 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5150 // Load from database
5151 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5152 ?
wfGetDB( DB_MASTER
)
5153 : wfGetDB( DB_SLAVE
);
5155 $res = $dbr->select(
5157 [ 'up_property', 'up_value' ],
5158 [ 'up_user' => $this->getId() ],
5162 $this->mOptionOverrides
= [];
5164 foreach ( $res as $row ) {
5165 $data[$row->up_property
] = $row->up_value
;
5168 foreach ( $data as $property => $value ) {
5169 $this->mOptionOverrides
[$property] = $value;
5170 $this->mOptions
[$property] = $value;
5174 $this->mOptionsLoaded
= true;
5176 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5180 * Saves the non-default options for this user, as previously set e.g. via
5181 * setOption(), in the database's "user_properties" (preferences) table.
5182 * Usually used via saveSettings().
5184 protected function saveOptions() {
5185 $this->loadOptions();
5187 // Not using getOptions(), to keep hidden preferences in database
5188 $saveOptions = $this->mOptions
;
5190 // Allow hooks to abort, for instance to save to a global profile.
5191 // Reset options to default state before saving.
5192 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5196 $userId = $this->getId();
5198 $insert_rows = []; // all the new preference rows
5199 foreach ( $saveOptions as $key => $value ) {
5200 // Don't bother storing default values
5201 $defaultOption = self
::getDefaultOption( $key );
5202 if ( ( $defaultOption === null && $value !== false && $value !== null )
5203 ||
$value != $defaultOption
5206 'up_user' => $userId,
5207 'up_property' => $key,
5208 'up_value' => $value,
5213 $dbw = wfGetDB( DB_MASTER
);
5215 $res = $dbw->select( 'user_properties',
5216 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5218 // Find prior rows that need to be removed or updated. These rows will
5219 // all be deleted (the later so that INSERT IGNORE applies the new values).
5221 foreach ( $res as $row ) {
5222 if ( !isset( $saveOptions[$row->up_property
] )
5223 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5225 $keysDelete[] = $row->up_property
;
5229 if ( count( $keysDelete ) ) {
5230 // Do the DELETE by PRIMARY KEY for prior rows.
5231 // In the past a very large portion of calls to this function are for setting
5232 // 'rememberpassword' for new accounts (a preference that has since been removed).
5233 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5234 // caused gap locks on [max user ID,+infinity) which caused high contention since
5235 // updates would pile up on each other as they are for higher (newer) user IDs.
5236 // It might not be necessary these days, but it shouldn't hurt either.
5237 $dbw->delete( 'user_properties',
5238 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5240 // Insert the new preference rows
5241 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5245 * Lazily instantiate and return a factory object for making passwords
5247 * @deprecated since 1.27, create a PasswordFactory directly instead
5248 * @return PasswordFactory
5250 public static function getPasswordFactory() {
5251 wfDeprecated( __METHOD__
, '1.27' );
5252 $ret = new PasswordFactory();
5253 $ret->init( RequestContext
::getMain()->getConfig() );
5258 * Provide an array of HTML5 attributes to put on an input element
5259 * intended for the user to enter a new password. This may include
5260 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5262 * Do *not* use this when asking the user to enter his current password!
5263 * Regardless of configuration, users may have invalid passwords for whatever
5264 * reason (e.g., they were set before requirements were tightened up).
5265 * Only use it when asking for a new password, like on account creation or
5268 * Obviously, you still need to do server-side checking.
5270 * NOTE: A combination of bugs in various browsers means that this function
5271 * actually just returns array() unconditionally at the moment. May as
5272 * well keep it around for when the browser bugs get fixed, though.
5274 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5276 * @deprecated since 1.27
5277 * @return array Array of HTML attributes suitable for feeding to
5278 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5279 * That will get confused by the boolean attribute syntax used.)
5281 public static function passwordChangeInputAttribs() {
5282 global $wgMinimalPasswordLength;
5284 if ( $wgMinimalPasswordLength == 0 ) {
5288 # Note that the pattern requirement will always be satisfied if the
5289 # input is empty, so we need required in all cases.
5291 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5292 # if e-mail confirmation is being used. Since HTML5 input validation
5293 # is b0rked anyway in some browsers, just return nothing. When it's
5294 # re-enabled, fix this code to not output required for e-mail
5296 # $ret = array( 'required' );
5299 # We can't actually do this right now, because Opera 9.6 will print out
5300 # the entered password visibly in its error message! When other
5301 # browsers add support for this attribute, or Opera fixes its support,
5302 # we can add support with a version check to avoid doing this on Opera
5303 # versions where it will be a problem. Reported to Opera as
5304 # DSK-262266, but they don't have a public bug tracker for us to follow.
5306 if ( $wgMinimalPasswordLength > 1 ) {
5307 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5308 $ret['title'] = wfMessage( 'passwordtooshort' )
5309 ->numParams( $wgMinimalPasswordLength )->text();
5317 * Return the list of user fields that should be selected to create
5318 * a new user object.
5321 public static function selectFields() {
5329 'user_email_authenticated',
5331 'user_email_token_expires',
5332 'user_registration',
5338 * Factory function for fatal permission-denied errors
5341 * @param string $permission User right required
5344 static function newFatalPermissionDeniedStatus( $permission ) {
5347 $groups = array_map(
5348 [ 'User', 'makeGroupLinkWiki' ],
5349 User
::getGroupsWithPermission( $permission )
5353 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5355 return Status
::newFatal( 'badaccess-group0' );
5360 * Get a new instance of this user that was loaded from the master via a locking read
5362 * Use this instead of the main context User when updating that user. This avoids races
5363 * where that user was loaded from a slave or even the master but without proper locks.
5365 * @return User|null Returns null if the user was not found in the DB
5368 public function getInstanceForUpdate() {
5369 if ( !$this->getId() ) {
5370 return null; // anon
5373 $user = self
::newFromId( $this->getId() );
5374 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5382 * Checks if two user objects point to the same user.
5388 public function equals( User
$user ) {
5389 return $this->getName() === $user->getName();