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.
29 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
32 * The User object encapsulates all of the user-specific settings (user_id,
33 * name, rights, email address, options, last login time). Client
34 * classes use the getXXX() functions to access these fields. These functions
35 * do all the work of determining whether the user is logged in,
36 * whether the requested option can be satisfied from cookies or
37 * whether a database query is needed. Most of the settings needed
38 * for rendering normal pages are set in the cookie to minimize use
41 class User
implements IDBAccessObject
{
43 * @const int Number of characters in user_token field.
45 const TOKEN_LENGTH
= 32;
48 * Global constant made accessible as class constants so that autoloader
51 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
54 * @const int Serialized record version.
59 * Maximum items in $mWatchedItems
61 const MAX_WATCHED_ITEMS_CACHE
= 100;
64 * Exclude user options that are set to their default value.
67 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
70 * Array of Strings List of member variables which are saved to the
71 * shared cache (memcached). Any operation which changes the
72 * corresponding database fields must call a cache-clearing function.
75 protected static $mCacheVars = array(
83 'mEmailAuthenticated',
90 // user_properties table
95 * Array of Strings Core rights.
96 * Each of these should have a corresponding message of the form
100 protected static $mCoreRights = array(
130 'editusercssjs', # deprecated
143 'move-categorypages',
144 'move-rootuserpages',
148 'override-export-depth',
171 'userrights-interwiki',
179 * String Cached results of getAllRights()
181 protected static $mAllRights = false;
183 /** Cache variables */
193 /** @var string TS_MW timestamp from the DB */
195 /** @var string TS_MW timestamp from cache */
196 protected $mQuickTouched;
200 public $mEmailAuthenticated;
202 protected $mEmailToken;
204 protected $mEmailTokenExpires;
206 protected $mRegistration;
208 protected $mEditCount;
212 protected $mOptionOverrides;
216 * Bool Whether the cache variables have been loaded.
219 public $mOptionsLoaded;
222 * Array with already loaded items or true if all items have been loaded.
224 protected $mLoadedItems = array();
228 * String Initialization data source if mLoadedItems!==true. May be one of:
229 * - 'defaults' anonymous user initialised from class defaults
230 * - 'name' initialise from mName
231 * - 'id' initialise from mId
232 * - 'session' log in from session if possible
234 * Use the User::newFrom*() family of functions to set this.
239 * Lazy-initialized variables, invalidated with clearInstanceCache
243 protected $mDatePreference;
251 protected $mBlockreason;
253 protected $mEffectiveGroups;
255 protected $mImplicitGroups;
257 protected $mFormerGroups;
259 protected $mBlockedGlobally;
276 protected $mAllowUsertalk;
279 private $mBlockedFromCreateAccount = false;
282 private $mWatchedItems = array();
284 /** @var integer User::READ_* constant bitfield used to load data */
285 protected $queryFlagsUsed = self
::READ_NORMAL
;
287 public static $idCacheByName = array();
290 * Lightweight constructor for an anonymous user.
291 * Use the User::newFrom* factory functions for other kinds of users.
295 * @see newFromConfirmationCode()
296 * @see newFromSession()
299 public function __construct() {
300 $this->clearInstanceCache( 'defaults' );
306 public function __toString() {
307 return $this->getName();
311 * Load the user table data for this object from the source given by mFrom.
313 * @param integer $flags User::READ_* constant bitfield
315 public function load( $flags = self
::READ_NORMAL
) {
316 global $wgFullyInitialised;
318 if ( $this->mLoadedItems
=== true ) {
322 // Set it now to avoid infinite recursion in accessors
323 $oldLoadedItems = $this->mLoadedItems
;
324 $this->mLoadedItems
= true;
325 $this->queryFlagsUsed
= $flags;
327 // If this is called too early, things are likely to break.
328 if ( $this->mFrom
=== 'session' && empty( $wgFullyInitialised ) ) {
329 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
330 ->warning( 'User::loadFromSession called before the end of Setup.php', array(
331 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
333 $this->loadDefaults();
334 $this->mLoadedItems
= $oldLoadedItems;
338 switch ( $this->mFrom
) {
340 $this->loadDefaults();
343 // Make sure this thread sees its own changes
344 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
345 $flags |
= self
::READ_LATEST
;
346 $this->queryFlagsUsed
= $flags;
349 $this->mId
= self
::idFromName( $this->mName
, $flags );
351 // Nonexistent user placeholder object
352 $this->loadDefaults( $this->mName
);
354 $this->loadFromId( $flags );
358 $this->loadFromId( $flags );
361 if ( !$this->loadFromSession() ) {
362 // Loading from session failed. Load defaults.
363 $this->loadDefaults();
365 Hooks
::run( 'UserLoadAfterLoadFromSession', array( $this ) );
368 throw new UnexpectedValueException(
369 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
374 * Load user table data, given mId has already been set.
375 * @param integer $flags User::READ_* constant bitfield
376 * @return bool False if the ID does not exist, true otherwise
378 public function loadFromId( $flags = self
::READ_NORMAL
) {
379 if ( $this->mId
== 0 ) {
380 $this->loadDefaults();
384 // Try cache (unless this needs data from the master DB).
385 // NOTE: if this thread called saveSettings(), the cache was cleared.
386 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
387 if ( $latest ||
!$this->loadFromCache() ) {
388 wfDebug( "User: cache miss for user {$this->mId}\n" );
389 // Load from DB (make sure this thread sees its own changes)
390 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
391 $flags |
= self
::READ_LATEST
;
393 if ( !$this->loadFromDatabase( $flags ) ) {
394 // Can't load from ID, user is anonymous
397 $this->saveToCache();
400 $this->mLoadedItems
= true;
401 $this->queryFlagsUsed
= $flags;
408 * @param string $wikiId
409 * @param integer $userId
411 public static function purge( $wikiId, $userId ) {
412 $cache = ObjectCache
::getMainWANInstance();
413 $cache->delete( $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId ) );
418 * @param WANObjectCache $cache
421 protected function getCacheKey( WANObjectCache
$cache ) {
422 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
426 * Load user data from shared cache, given mId has already been set.
428 * @return bool false if the ID does not exist or data is invalid, true otherwise
431 protected function loadFromCache() {
432 if ( $this->mId
== 0 ) {
433 $this->loadDefaults();
437 $cache = ObjectCache
::getMainWANInstance();
438 $data = $cache->get( $this->getCacheKey( $cache ) );
439 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
444 wfDebug( "User: got user {$this->mId} from cache\n" );
446 // Restore from cache
447 foreach ( self
::$mCacheVars as $name ) {
448 $this->$name = $data[$name];
455 * Save user data to the shared cache
457 * This method should not be called outside the User class
459 public function saveToCache() {
462 $this->loadOptions();
464 if ( $this->isAnon() ) {
465 // Anonymous users are uncached
470 foreach ( self
::$mCacheVars as $name ) {
471 $data[$name] = $this->$name;
473 $data['mVersion'] = self
::VERSION
;
474 $opts = Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
476 $cache = ObjectCache
::getMainWANInstance();
477 $key = $this->getCacheKey( $cache );
478 $cache->set( $key, $data, $cache::TTL_HOUR
, $opts );
481 /** @name newFrom*() static factory methods */
485 * Static factory method for creation from username.
487 * This is slightly less efficient than newFromId(), so use newFromId() if
488 * you have both an ID and a name handy.
490 * @param string $name Username, validated by Title::newFromText()
491 * @param string|bool $validate Validate username. Takes the same parameters as
492 * User::getCanonicalName(), except that true is accepted as an alias
493 * for 'valid', for BC.
495 * @return User|bool User object, or false if the username is invalid
496 * (e.g. if it contains illegal characters or is an IP address). If the
497 * username is not present in the database, the result will be a user object
498 * with a name, zero user ID and default settings.
500 public static function newFromName( $name, $validate = 'valid' ) {
501 if ( $validate === true ) {
504 $name = self
::getCanonicalName( $name, $validate );
505 if ( $name === false ) {
508 // Create unloaded user object
512 $u->setItemLoaded( 'name' );
518 * Static factory method for creation from a given user ID.
520 * @param int $id Valid user ID
521 * @return User The corresponding User object
523 public static function newFromId( $id ) {
527 $u->setItemLoaded( 'id' );
532 * Factory method to fetch whichever user has a given email confirmation code.
533 * This code is generated when an account is created or its e-mail address
536 * If the code is invalid or has expired, returns NULL.
538 * @param string $code Confirmation code
539 * @param int $flags User::READ_* bitfield
542 public static function newFromConfirmationCode( $code, $flags = 0 ) {
543 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
544 ?
wfGetDB( DB_MASTER
)
545 : wfGetDB( DB_SLAVE
);
547 $id = $db->selectField(
551 'user_email_token' => md5( $code ),
552 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
556 return $id ? User
::newFromId( $id ) : null;
560 * Create a new user object using data from session. If the login
561 * credentials are invalid, the result is an anonymous user.
563 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
566 public static function newFromSession( WebRequest
$request = null ) {
568 $user->mFrom
= 'session';
569 $user->mRequest
= $request;
574 * Create a new user object from a user row.
575 * The row should have the following fields from the user table in it:
576 * - either user_name or user_id to load further data if needed (or both)
578 * - all other fields (email, etc.)
579 * It is useless to provide the remaining fields if either user_id,
580 * user_name and user_real_name are not provided because the whole row
581 * will be loaded once more from the database when accessing them.
583 * @param stdClass $row A row from the user table
584 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
587 public static function newFromRow( $row, $data = null ) {
589 $user->loadFromRow( $row, $data );
594 * Static factory method for creation of a "system" user from username.
596 * A "system" user is an account that's used to attribute logged actions
597 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
598 * might include the 'Maintenance script' or 'Conversion script' accounts
599 * used by various scripts in the maintenance/ directory or accounts such
600 * as 'MediaWiki message delivery' used by the MassMessage extension.
602 * This can optionally create the user if it doesn't exist, and "steal" the
603 * account if it does exist.
605 * @param string $name Username
606 * @param array $options Options are:
607 * - validate: As for User::getCanonicalName(), default 'valid'
608 * - create: Whether to create the user if it doesn't already exist, default true
609 * - steal: Whether to reset the account's password and email if it
610 * already exists, default false
613 public static function newSystemUser( $name, $options = array() ) {
615 'validate' => 'valid',
620 $name = self
::getCanonicalName( $name, $options['validate'] );
621 if ( $name === false ) {
625 $dbw = wfGetDB( DB_MASTER
);
626 $row = $dbw->selectRow(
629 self
::selectFields(),
630 array( 'user_password', 'user_newpassword' )
632 array( 'user_name' => $name ),
636 // No user. Create it?
637 return $options['create'] ? self
::createNew( $name ) : null;
639 $user = self
::newFromRow( $row );
641 // A user is considered to exist as a non-system user if it has a
642 // password set, or a temporary password set, or an email set.
643 $passwordFactory = new PasswordFactory();
644 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
646 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
647 } catch ( PasswordError
$e ) {
648 wfDebug( 'Invalid password hash found in database.' );
649 $password = PasswordFactory
::newInvalidPassword();
652 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
653 } catch ( PasswordError
$e ) {
654 wfDebug( 'Invalid password hash found in database.' );
655 $newpassword = PasswordFactory
::newInvalidPassword();
657 if ( !$password instanceof InvalidPassword ||
!$newpassword instanceof InvalidPassword
660 // User exists. Steal it?
661 if ( !$options['steal'] ) {
665 $nopass = PasswordFactory
::newInvalidPassword()->toString();
670 'user_password' => $nopass,
671 'user_newpassword' => $nopass,
672 'user_newpass_time' => null,
674 array( 'user_id' => $user->getId() ),
677 $user->invalidateEmail();
678 $user->saveSettings();
681 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
689 * Get the username corresponding to a given user ID
690 * @param int $id User ID
691 * @return string|bool The corresponding username
693 public static function whoIs( $id ) {
694 return UserCache
::singleton()->getProp( $id, 'name' );
698 * Get the real name of a user given their user ID
700 * @param int $id User ID
701 * @return string|bool The corresponding user's real name
703 public static function whoIsReal( $id ) {
704 return UserCache
::singleton()->getProp( $id, 'real_name' );
708 * Get database id given a user name
709 * @param string $name Username
710 * @param integer $flags User::READ_* constant bitfield
711 * @return int|null The corresponding user's ID, or null if user is nonexistent
713 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
714 $nt = Title
::makeTitleSafe( NS_USER
, $name );
715 if ( is_null( $nt ) ) {
720 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
721 return self
::$idCacheByName[$name];
724 $db = ( $flags & self
::READ_LATEST
)
725 ?
wfGetDB( DB_MASTER
)
726 : wfGetDB( DB_SLAVE
);
731 array( 'user_name' => $nt->getText() ),
735 if ( $s === false ) {
738 $result = $s->user_id
;
741 self
::$idCacheByName[$name] = $result;
743 if ( count( self
::$idCacheByName ) > 1000 ) {
744 self
::$idCacheByName = array();
751 * Reset the cache used in idFromName(). For use in tests.
753 public static function resetIdByNameCache() {
754 self
::$idCacheByName = array();
758 * Does the string match an anonymous IPv4 address?
760 * This function exists for username validation, in order to reject
761 * usernames which are similar in form to IP addresses. Strings such
762 * as 300.300.300.300 will return true because it looks like an IP
763 * address, despite not being strictly valid.
765 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
766 * address because the usemod software would "cloak" anonymous IP
767 * addresses like this, if we allowed accounts like this to be created
768 * new users could get the old edits of these anonymous users.
770 * @param string $name Name to match
773 public static function isIP( $name ) {
774 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
775 || IP
::isIPv6( $name );
779 * Is the input a valid username?
781 * Checks if the input is a valid username, we don't want an empty string,
782 * an IP address, anything that contains slashes (would mess up subpages),
783 * is longer than the maximum allowed username size or doesn't begin with
786 * @param string $name Name to match
789 public static function isValidUserName( $name ) {
790 global $wgContLang, $wgMaxNameChars;
793 || User
::isIP( $name )
794 ||
strpos( $name, '/' ) !== false
795 ||
strlen( $name ) > $wgMaxNameChars
796 ||
$name != $wgContLang->ucfirst( $name )
798 wfDebugLog( 'username', __METHOD__
.
799 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
803 // Ensure that the name can't be misresolved as a different title,
804 // such as with extra namespace keys at the start.
805 $parsed = Title
::newFromText( $name );
806 if ( is_null( $parsed )
807 ||
$parsed->getNamespace()
808 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
809 wfDebugLog( 'username', __METHOD__
.
810 ": '$name' invalid due to ambiguous prefixes" );
814 // Check an additional blacklist of troublemaker characters.
815 // Should these be merged into the title char list?
816 $unicodeBlacklist = '/[' .
817 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
818 '\x{00a0}' . # non-breaking space
819 '\x{2000}-\x{200f}' . # various whitespace
820 '\x{2028}-\x{202f}' . # breaks and control chars
821 '\x{3000}' . # ideographic space
822 '\x{e000}-\x{f8ff}' . # private use
824 if ( preg_match( $unicodeBlacklist, $name ) ) {
825 wfDebugLog( 'username', __METHOD__
.
826 ": '$name' invalid due to blacklisted characters" );
834 * Usernames which fail to pass this function will be blocked
835 * from user login and new account registrations, but may be used
836 * internally by batch processes.
838 * If an account already exists in this form, login will be blocked
839 * by a failure to pass this function.
841 * @param string $name Name to match
844 public static function isUsableName( $name ) {
845 global $wgReservedUsernames;
846 // Must be a valid username, obviously ;)
847 if ( !self
::isValidUserName( $name ) ) {
851 static $reservedUsernames = false;
852 if ( !$reservedUsernames ) {
853 $reservedUsernames = $wgReservedUsernames;
854 Hooks
::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
857 // Certain names may be reserved for batch processes.
858 foreach ( $reservedUsernames as $reserved ) {
859 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
860 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
862 if ( $reserved == $name ) {
870 * Usernames which fail to pass this function will be blocked
871 * from new account registrations, but may be used internally
872 * either by batch processes or by user accounts which have
873 * already been created.
875 * Additional blacklisting may be added here rather than in
876 * isValidUserName() to avoid disrupting existing accounts.
878 * @param string $name String to match
881 public static function isCreatableName( $name ) {
882 global $wgInvalidUsernameCharacters;
884 // Ensure that the username isn't longer than 235 bytes, so that
885 // (at least for the builtin skins) user javascript and css files
886 // will work. (bug 23080)
887 if ( strlen( $name ) > 235 ) {
888 wfDebugLog( 'username', __METHOD__
.
889 ": '$name' invalid due to length" );
893 // Preg yells if you try to give it an empty string
894 if ( $wgInvalidUsernameCharacters !== '' ) {
895 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
896 wfDebugLog( 'username', __METHOD__
.
897 ": '$name' invalid due to wgInvalidUsernameCharacters" );
902 return self
::isUsableName( $name );
906 * Is the input a valid password for this user?
908 * @param string $password Desired password
911 public function isValidPassword( $password ) {
912 // simple boolean wrapper for getPasswordValidity
913 return $this->getPasswordValidity( $password ) === true;
917 * Given unvalidated password input, return error message on failure.
919 * @param string $password Desired password
920 * @return bool|string|array True on success, string or array of error message on failure
922 public function getPasswordValidity( $password ) {
923 $result = $this->checkPasswordValidity( $password );
924 if ( $result->isGood() ) {
928 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
929 $messages[] = $error['message'];
931 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
932 $messages[] = $warning['message'];
934 if ( count( $messages ) === 1 ) {
942 * Check if this is a valid password for this user
944 * Create a Status object based on the password's validity.
945 * The Status should be set to fatal if the user should not
946 * be allowed to log in, and should have any errors that
947 * would block changing the password.
949 * If the return value of this is not OK, the password
950 * should not be checked. If the return value is not Good,
951 * the password can be checked, but the user should not be
952 * able to set their password to this.
954 * @param string $password Desired password
955 * @param string $purpose one of 'login', 'create', 'reset'
959 public function checkPasswordValidity( $password, $purpose = 'login' ) {
960 global $wgPasswordPolicy;
962 $upp = new UserPasswordPolicy(
963 $wgPasswordPolicy['policies'],
964 $wgPasswordPolicy['checks']
967 $status = Status
::newGood();
968 $result = false; // init $result to false for the internal checks
970 if ( !Hooks
::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
971 $status->error( $result );
975 if ( $result === false ) {
976 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
978 } elseif ( $result === true ) {
981 $status->error( $result );
982 return $status; // the isValidPassword hook set a string $result and returned true
987 * Given unvalidated user input, return a canonical username, or false if
988 * the username is invalid.
989 * @param string $name User input
990 * @param string|bool $validate Type of validation to use:
991 * - false No validation
992 * - 'valid' Valid for batch processes
993 * - 'usable' Valid for batch processes and login
994 * - 'creatable' Valid for batch processes, login and account creation
996 * @throws InvalidArgumentException
997 * @return bool|string
999 public static function getCanonicalName( $name, $validate = 'valid' ) {
1000 // Force usernames to capital
1002 $name = $wgContLang->ucfirst( $name );
1004 # Reject names containing '#'; these will be cleaned up
1005 # with title normalisation, but then it's too late to
1007 if ( strpos( $name, '#' ) !== false ) {
1011 // Clean up name according to title rules,
1012 // but only when validation is requested (bug 12654)
1013 $t = ( $validate !== false ) ?
1014 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
1015 // Check for invalid titles
1016 if ( is_null( $t ) ) {
1020 // Reject various classes of invalid names
1022 $name = $wgAuth->getCanonicalName( $t->getText() );
1024 switch ( $validate ) {
1028 if ( !User
::isValidUserName( $name ) ) {
1033 if ( !User
::isUsableName( $name ) ) {
1038 if ( !User
::isCreatableName( $name ) ) {
1043 throw new InvalidArgumentException(
1044 'Invalid parameter value for $validate in ' . __METHOD__
);
1050 * Count the number of edits of a user
1052 * @param int $uid User ID to check
1053 * @return int The user's edit count
1055 * @deprecated since 1.21 in favour of User::getEditCount
1057 public static function edits( $uid ) {
1058 wfDeprecated( __METHOD__
, '1.21' );
1059 $user = self
::newFromId( $uid );
1060 return $user->getEditCount();
1064 * Return a random password.
1066 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1067 * @return string New random password
1069 public static function randomPassword() {
1070 global $wgMinimalPasswordLength;
1071 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1075 * Set cached properties to default.
1077 * @note This no longer clears uncached lazy-initialised properties;
1078 * the constructor does that instead.
1080 * @param string|bool $name
1082 public function loadDefaults( $name = false ) {
1084 $this->mName
= $name;
1085 $this->mRealName
= '';
1087 $this->mOptionOverrides
= null;
1088 $this->mOptionsLoaded
= false;
1090 $loggedOut = $this->mRequest ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1091 if ( $loggedOut !== 0 ) {
1092 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1094 $this->mTouched
= '1'; # Allow any pages to be cached
1097 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1098 $this->mEmailAuthenticated
= null;
1099 $this->mEmailToken
= '';
1100 $this->mEmailTokenExpires
= null;
1101 $this->mRegistration
= wfTimestamp( TS_MW
);
1102 $this->mGroups
= array();
1104 Hooks
::run( 'UserLoadDefaults', array( $this, $name ) );
1108 * Return whether an item has been loaded.
1110 * @param string $item Item to check. Current possibilities:
1114 * @param string $all 'all' to check if the whole object has been loaded
1115 * or any other string to check if only the item is available (e.g.
1119 public function isItemLoaded( $item, $all = 'all' ) {
1120 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1121 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1125 * Set that an item has been loaded
1127 * @param string $item
1129 protected function setItemLoaded( $item ) {
1130 if ( is_array( $this->mLoadedItems
) ) {
1131 $this->mLoadedItems
[$item] = true;
1136 * Load user data from the session.
1138 * @return bool True if the user is logged in, false otherwise.
1140 private function loadFromSession() {
1143 Hooks
::run( 'UserLoadFromSession', array( $this, &$result ), '1.27' );
1144 if ( $result !== null ) {
1148 // MediaWiki\Session\Session already did the necessary authentication of the user
1149 // returned here, so just use it if applicable.
1150 $session = $this->getRequest()->getSession();
1151 $user = $session->getUser();
1152 if ( $user->isLoggedIn() ) {
1153 $this->loadFromUserObject( $user );
1154 // Other code expects these to be set in the session, so set them.
1155 $session->set( 'wsUserID', $this->getId() );
1156 $session->set( 'wsUserName', $this->getName() );
1157 $session->set( 'wsToken', $this->mToken
);
1165 * Load user and user_group data from the database.
1166 * $this->mId must be set, this is how the user is identified.
1168 * @param integer $flags User::READ_* constant bitfield
1169 * @return bool True if the user exists, false if the user is anonymous
1171 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1173 $this->mId
= intval( $this->mId
);
1176 if ( !$this->mId
) {
1177 $this->loadDefaults();
1181 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1182 $db = wfGetDB( $index );
1184 $s = $db->selectRow(
1186 self
::selectFields(),
1187 array( 'user_id' => $this->mId
),
1192 $this->queryFlagsUsed
= $flags;
1193 Hooks
::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1195 if ( $s !== false ) {
1196 // Initialise user table data
1197 $this->loadFromRow( $s );
1198 $this->mGroups
= null; // deferred
1199 $this->getEditCount(); // revalidation for nulls
1204 $this->loadDefaults();
1210 * Initialize this object from a row from the user table.
1212 * @param stdClass $row Row from the user table to load.
1213 * @param array $data Further user data to load into the object
1215 * user_groups Array with groups out of the user_groups table
1216 * user_properties Array with properties out of the user_properties table
1218 protected function loadFromRow( $row, $data = null ) {
1221 $this->mGroups
= null; // deferred
1223 if ( isset( $row->user_name
) ) {
1224 $this->mName
= $row->user_name
;
1225 $this->mFrom
= 'name';
1226 $this->setItemLoaded( 'name' );
1231 if ( isset( $row->user_real_name
) ) {
1232 $this->mRealName
= $row->user_real_name
;
1233 $this->setItemLoaded( 'realname' );
1238 if ( isset( $row->user_id
) ) {
1239 $this->mId
= intval( $row->user_id
);
1240 $this->mFrom
= 'id';
1241 $this->setItemLoaded( 'id' );
1246 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1247 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1250 if ( isset( $row->user_editcount
) ) {
1251 $this->mEditCount
= $row->user_editcount
;
1256 if ( isset( $row->user_touched
) ) {
1257 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1262 if ( isset( $row->user_email
) ) {
1263 $this->mEmail
= $row->user_email
;
1264 $this->mToken
= $row->user_token
;
1265 if ( $this->mToken
== '' ) {
1266 $this->mToken
= null;
1268 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1269 $this->mEmailToken
= $row->user_email_token
;
1270 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1271 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1277 $this->mLoadedItems
= true;
1280 if ( is_array( $data ) ) {
1281 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1282 $this->mGroups
= $data['user_groups'];
1284 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1285 $this->loadOptions( $data['user_properties'] );
1291 * Load the data for this user object from another user object.
1295 protected function loadFromUserObject( $user ) {
1297 $user->loadGroups();
1298 $user->loadOptions();
1299 foreach ( self
::$mCacheVars as $var ) {
1300 $this->$var = $user->$var;
1305 * Load the groups from the database if they aren't already loaded.
1307 private function loadGroups() {
1308 if ( is_null( $this->mGroups
) ) {
1309 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1310 ?
wfGetDB( DB_MASTER
)
1311 : wfGetDB( DB_SLAVE
);
1312 $res = $db->select( 'user_groups',
1313 array( 'ug_group' ),
1314 array( 'ug_user' => $this->mId
),
1316 $this->mGroups
= array();
1317 foreach ( $res as $row ) {
1318 $this->mGroups
[] = $row->ug_group
;
1324 * Add the user to the group if he/she meets given criteria.
1326 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1327 * possible to remove manually via Special:UserRights. In such case it
1328 * will not be re-added automatically. The user will also not lose the
1329 * group if they no longer meet the criteria.
1331 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1333 * @return array Array of groups the user has been promoted to.
1335 * @see $wgAutopromoteOnce
1337 public function addAutopromoteOnceGroups( $event ) {
1338 global $wgAutopromoteOnceLogInRC, $wgAuth;
1340 if ( wfReadOnly() ||
!$this->getId() ) {
1344 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1345 if ( !count( $toPromote ) ) {
1349 if ( !$this->checkAndSetTouched() ) {
1350 return array(); // raced out (bug T48834)
1353 $oldGroups = $this->getGroups(); // previous groups
1354 foreach ( $toPromote as $group ) {
1355 $this->addGroup( $group );
1357 // update groups in external authentication database
1358 Hooks
::run( 'UserGroupsChanged', array( $this, $toPromote, array(), false ) );
1359 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1361 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1363 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1364 $logEntry->setPerformer( $this );
1365 $logEntry->setTarget( $this->getUserPage() );
1366 $logEntry->setParameters( array(
1367 '4::oldgroups' => $oldGroups,
1368 '5::newgroups' => $newGroups,
1370 $logid = $logEntry->insert();
1371 if ( $wgAutopromoteOnceLogInRC ) {
1372 $logEntry->publish( $logid );
1379 * Bump user_touched if it didn't change since this object was loaded
1381 * On success, the mTouched field is updated.
1382 * The user serialization cache is always cleared.
1384 * @return bool Whether user_touched was actually updated
1387 protected function checkAndSetTouched() {
1390 if ( !$this->mId
) {
1391 return false; // anon
1394 // Get a new user_touched that is higher than the old one
1395 $oldTouched = $this->mTouched
;
1396 $newTouched = $this->newTouchedTimestamp();
1398 $dbw = wfGetDB( DB_MASTER
);
1399 $dbw->update( 'user',
1400 array( 'user_touched' => $dbw->timestamp( $newTouched ) ),
1402 'user_id' => $this->mId
,
1403 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1407 $success = ( $dbw->affectedRows() > 0 );
1410 $this->mTouched
= $newTouched;
1411 $this->clearSharedCache();
1413 // Clears on failure too since that is desired if the cache is stale
1414 $this->clearSharedCache( 'refresh' );
1421 * Clear various cached data stored in this object. The cache of the user table
1422 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1424 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1425 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1427 public function clearInstanceCache( $reloadFrom = false ) {
1428 $this->mNewtalk
= -1;
1429 $this->mDatePreference
= null;
1430 $this->mBlockedby
= -1; # Unset
1431 $this->mHash
= false;
1432 $this->mRights
= null;
1433 $this->mEffectiveGroups
= null;
1434 $this->mImplicitGroups
= null;
1435 $this->mGroups
= null;
1436 $this->mOptions
= null;
1437 $this->mOptionsLoaded
= false;
1438 $this->mEditCount
= null;
1440 if ( $reloadFrom ) {
1441 $this->mLoadedItems
= array();
1442 $this->mFrom
= $reloadFrom;
1447 * Combine the language default options with any site-specific options
1448 * and add the default language variants.
1450 * @return array Array of String options
1452 public static function getDefaultOptions() {
1453 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1455 static $defOpt = null;
1456 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1457 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1458 // mid-request and see that change reflected in the return value of this function.
1459 // Which is insane and would never happen during normal MW operation
1463 $defOpt = $wgDefaultUserOptions;
1464 // Default language setting
1465 $defOpt['language'] = $wgContLang->getCode();
1466 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1467 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1469 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1470 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1472 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1474 Hooks
::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1480 * Get a given default option value.
1482 * @param string $opt Name of option to retrieve
1483 * @return string Default option value
1485 public static function getDefaultOption( $opt ) {
1486 $defOpts = self
::getDefaultOptions();
1487 if ( isset( $defOpts[$opt] ) ) {
1488 return $defOpts[$opt];
1495 * Get blocking information
1496 * @param bool $bFromSlave Whether to check the slave database first.
1497 * To improve performance, non-critical checks are done against slaves.
1498 * Check when actually saving should be done against master.
1500 private function getBlockedStatus( $bFromSlave = true ) {
1501 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1503 if ( -1 != $this->mBlockedby
) {
1507 wfDebug( __METHOD__
. ": checking...\n" );
1509 // Initialize data...
1510 // Otherwise something ends up stomping on $this->mBlockedby when
1511 // things get lazy-loaded later, causing false positive block hits
1512 // due to -1 !== 0. Probably session-related... Nothing should be
1513 // overwriting mBlockedby, surely?
1516 # We only need to worry about passing the IP address to the Block generator if the
1517 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1518 # know which IP address they're actually coming from
1519 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->equals( $wgUser ) ) {
1520 $ip = $this->getRequest()->getIP();
1526 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1529 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1531 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1533 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1534 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1535 $block->setTarget( $ip );
1536 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1538 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1539 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1540 $block->setTarget( $ip );
1544 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1545 if ( !$block instanceof Block
1546 && $wgApplyIpBlocksToXff
1548 && !in_array( $ip, $wgProxyWhitelist )
1550 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1551 $xff = array_map( 'trim', explode( ',', $xff ) );
1552 $xff = array_diff( $xff, array( $ip ) );
1553 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1554 $block = Block
::chooseBlock( $xffblocks, $xff );
1555 if ( $block instanceof Block
) {
1556 # Mangle the reason to alert the user that the block
1557 # originated from matching the X-Forwarded-For header.
1558 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1562 if ( $block instanceof Block
) {
1563 wfDebug( __METHOD__
. ": Found block.\n" );
1564 $this->mBlock
= $block;
1565 $this->mBlockedby
= $block->getByName();
1566 $this->mBlockreason
= $block->mReason
;
1567 $this->mHideName
= $block->mHideName
;
1568 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1570 $this->mBlockedby
= '';
1571 $this->mHideName
= 0;
1572 $this->mAllowUsertalk
= false;
1576 Hooks
::run( 'GetBlockedStatus', array( &$this ) );
1581 * Whether the given IP is in a DNS blacklist.
1583 * @param string $ip IP to check
1584 * @param bool $checkWhitelist Whether to check the whitelist first
1585 * @return bool True if blacklisted.
1587 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1588 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1590 if ( !$wgEnableDnsBlacklist ) {
1594 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1598 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1602 * Whether the given IP is in a given DNS blacklist.
1604 * @param string $ip IP to check
1605 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1606 * @return bool True if blacklisted.
1608 public function inDnsBlacklist( $ip, $bases ) {
1611 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1612 if ( IP
::isIPv4( $ip ) ) {
1613 // Reverse IP, bug 21255
1614 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1616 foreach ( (array)$bases as $base ) {
1618 // If we have an access key, use that too (ProjectHoneypot, etc.)
1620 if ( is_array( $base ) ) {
1621 if ( count( $base ) >= 2 ) {
1622 // Access key is 1, base URL is 0
1623 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1625 $host = "$ipReversed.{$base[0]}";
1627 $basename = $base[0];
1629 $host = "$ipReversed.$base";
1633 $ipList = gethostbynamel( $host );
1636 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1640 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1649 * Check if an IP address is in the local proxy list
1655 public static function isLocallyBlockedProxy( $ip ) {
1656 global $wgProxyList;
1658 if ( !$wgProxyList ) {
1662 if ( !is_array( $wgProxyList ) ) {
1663 // Load from the specified file
1664 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1667 if ( !is_array( $wgProxyList ) ) {
1669 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1671 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1672 // Old-style flipped proxy list
1681 * Is this user subject to rate limiting?
1683 * @return bool True if rate limited
1685 public function isPingLimitable() {
1686 global $wgRateLimitsExcludedIPs;
1687 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1688 // No other good way currently to disable rate limits
1689 // for specific IPs. :P
1690 // But this is a crappy hack and should die.
1693 return !$this->isAllowed( 'noratelimit' );
1697 * Primitive rate limits: enforce maximum actions per time period
1698 * to put a brake on flooding.
1700 * The method generates both a generic profiling point and a per action one
1701 * (suffix being "-$action".
1703 * @note When using a shared cache like memcached, IP-address
1704 * last-hit counters will be shared across wikis.
1706 * @param string $action Action to enforce; 'edit' if unspecified
1707 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1708 * @return bool True if a rate limiter was tripped
1710 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1711 // Call the 'PingLimiter' hook
1713 if ( !Hooks
::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1717 global $wgRateLimits;
1718 if ( !isset( $wgRateLimits[$action] ) ) {
1722 // Some groups shouldn't trigger the ping limiter, ever
1723 if ( !$this->isPingLimitable() ) {
1727 $limits = $wgRateLimits[$action];
1729 $id = $this->getId();
1732 if ( isset( $limits['anon'] ) && $id == 0 ) {
1733 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1736 if ( isset( $limits['user'] ) && $id != 0 ) {
1737 $userLimit = $limits['user'];
1739 if ( $this->isNewbie() ) {
1740 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1741 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1743 if ( isset( $limits['ip'] ) ) {
1744 $ip = $this->getRequest()->getIP();
1745 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1747 if ( isset( $limits['subnet'] ) ) {
1748 $ip = $this->getRequest()->getIP();
1751 if ( IP
::isIPv6( $ip ) ) {
1752 $parts = IP
::parseRange( "$ip/64" );
1753 $subnet = $parts[0];
1754 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1756 $subnet = $matches[1];
1758 if ( $subnet !== false ) {
1759 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1763 // Check for group-specific permissions
1764 // If more than one group applies, use the group with the highest limit
1765 foreach ( $this->getGroups() as $group ) {
1766 if ( isset( $limits[$group] ) ) {
1767 if ( $userLimit === false
1768 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1770 $userLimit = $limits[$group];
1774 // Set the user limit key
1775 if ( $userLimit !== false ) {
1776 list( $max, $period ) = $userLimit;
1777 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1778 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1781 $cache = ObjectCache
::getLocalClusterInstance();
1784 foreach ( $keys as $key => $limit ) {
1785 list( $max, $period ) = $limit;
1786 $summary = "(limit $max in {$period}s)";
1787 $count = $cache->get( $key );
1790 if ( $count >= $max ) {
1791 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1792 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1795 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1798 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1799 if ( $incrBy > 0 ) {
1800 $cache->add( $key, 0, intval( $period ) ); // first ping
1803 if ( $incrBy > 0 ) {
1804 $cache->incr( $key, $incrBy );
1812 * Check if user is blocked
1814 * @param bool $bFromSlave Whether to check the slave database instead of
1815 * the master. Hacked from false due to horrible probs on site.
1816 * @return bool True if blocked, false otherwise
1818 public function isBlocked( $bFromSlave = true ) {
1819 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1823 * Get the block affecting the user, or null if the user is not blocked
1825 * @param bool $bFromSlave Whether to check the slave database instead of the master
1826 * @return Block|null
1828 public function getBlock( $bFromSlave = true ) {
1829 $this->getBlockedStatus( $bFromSlave );
1830 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1834 * Check if user is blocked from editing a particular article
1836 * @param Title $title Title to check
1837 * @param bool $bFromSlave Whether to check the slave database instead of the master
1840 public function isBlockedFrom( $title, $bFromSlave = false ) {
1841 global $wgBlockAllowsUTEdit;
1843 $blocked = $this->isBlocked( $bFromSlave );
1844 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1845 // If a user's name is suppressed, they cannot make edits anywhere
1846 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1847 && $title->getNamespace() == NS_USER_TALK
) {
1849 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1852 Hooks
::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1858 * If user is blocked, return the name of the user who placed the block
1859 * @return string Name of blocker
1861 public function blockedBy() {
1862 $this->getBlockedStatus();
1863 return $this->mBlockedby
;
1867 * If user is blocked, return the specified reason for the block
1868 * @return string Blocking reason
1870 public function blockedFor() {
1871 $this->getBlockedStatus();
1872 return $this->mBlockreason
;
1876 * If user is blocked, return the ID for the block
1877 * @return int Block ID
1879 public function getBlockId() {
1880 $this->getBlockedStatus();
1881 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1885 * Check if user is blocked on all wikis.
1886 * Do not use for actual edit permission checks!
1887 * This is intended for quick UI checks.
1889 * @param string $ip IP address, uses current client if none given
1890 * @return bool True if blocked, false otherwise
1892 public function isBlockedGlobally( $ip = '' ) {
1893 if ( $this->mBlockedGlobally
!== null ) {
1894 return $this->mBlockedGlobally
;
1896 // User is already an IP?
1897 if ( IP
::isIPAddress( $this->getName() ) ) {
1898 $ip = $this->getName();
1900 $ip = $this->getRequest()->getIP();
1903 Hooks
::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1904 $this->mBlockedGlobally
= (bool)$blocked;
1905 return $this->mBlockedGlobally
;
1909 * Check if user account is locked
1911 * @return bool True if locked, false otherwise
1913 public function isLocked() {
1914 if ( $this->mLocked
!== null ) {
1915 return $this->mLocked
;
1918 $authUser = $wgAuth->getUserInstance( $this );
1919 $this->mLocked
= (bool)$authUser->isLocked();
1920 Hooks
::run( 'UserIsLocked', array( $this, &$this->mLocked
) );
1921 return $this->mLocked
;
1925 * Check if user account is hidden
1927 * @return bool True if hidden, false otherwise
1929 public function isHidden() {
1930 if ( $this->mHideName
!== null ) {
1931 return $this->mHideName
;
1933 $this->getBlockedStatus();
1934 if ( !$this->mHideName
) {
1936 $authUser = $wgAuth->getUserInstance( $this );
1937 $this->mHideName
= (bool)$authUser->isHidden();
1938 Hooks
::run( 'UserIsHidden', array( $this, &$this->mHideName
) );
1940 return $this->mHideName
;
1944 * Get the user's ID.
1945 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1947 public function getId() {
1948 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1949 // Special case, we know the user is anonymous
1951 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1952 // Don't load if this was initialized from an ID
1959 * Set the user and reload all fields according to a given ID
1960 * @param int $v User ID to reload
1962 public function setId( $v ) {
1964 $this->clearInstanceCache( 'id' );
1968 * Get the user name, or the IP of an anonymous user
1969 * @return string User's name or IP address
1971 public function getName() {
1972 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1973 // Special case optimisation
1974 return $this->mName
;
1977 if ( $this->mName
=== false ) {
1979 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1981 return $this->mName
;
1986 * Set the user name.
1988 * This does not reload fields from the database according to the given
1989 * name. Rather, it is used to create a temporary "nonexistent user" for
1990 * later addition to the database. It can also be used to set the IP
1991 * address for an anonymous user to something other than the current
1994 * @note User::newFromName() has roughly the same function, when the named user
1996 * @param string $str New user name to set
1998 public function setName( $str ) {
2000 $this->mName
= $str;
2004 * Get the user's name escaped by underscores.
2005 * @return string Username escaped by underscores.
2007 public function getTitleKey() {
2008 return str_replace( ' ', '_', $this->getName() );
2012 * Check if the user has new messages.
2013 * @return bool True if the user has new messages
2015 public function getNewtalk() {
2018 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2019 if ( $this->mNewtalk
=== -1 ) {
2020 $this->mNewtalk
= false; # reset talk page status
2022 // Check memcached separately for anons, who have no
2023 // entire User object stored in there.
2024 if ( !$this->mId
) {
2025 global $wgDisableAnonTalk;
2026 if ( $wgDisableAnonTalk ) {
2027 // Anon newtalk disabled by configuration.
2028 $this->mNewtalk
= false;
2030 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2033 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2037 return (bool)$this->mNewtalk
;
2041 * Return the data needed to construct links for new talk page message
2042 * alerts. If there are new messages, this will return an associative array
2043 * with the following data:
2044 * wiki: The database name of the wiki
2045 * link: Root-relative link to the user's talk page
2046 * rev: The last talk page revision that the user has seen or null. This
2047 * is useful for building diff links.
2048 * If there are no new messages, it returns an empty array.
2049 * @note This function was designed to accomodate multiple talk pages, but
2050 * currently only returns a single link and revision.
2053 public function getNewMessageLinks() {
2055 if ( !Hooks
::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2057 } elseif ( !$this->getNewtalk() ) {
2060 $utp = $this->getTalkPage();
2061 $dbr = wfGetDB( DB_SLAVE
);
2062 // Get the "last viewed rev" timestamp from the oldest message notification
2063 $timestamp = $dbr->selectField( 'user_newtalk',
2064 'MIN(user_last_timestamp)',
2065 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2067 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2068 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2072 * Get the revision ID for the last talk page revision viewed by the talk
2074 * @return int|null Revision ID or null
2076 public function getNewMessageRevisionId() {
2077 $newMessageRevisionId = null;
2078 $newMessageLinks = $this->getNewMessageLinks();
2079 if ( $newMessageLinks ) {
2080 // Note: getNewMessageLinks() never returns more than a single link
2081 // and it is always for the same wiki, but we double-check here in
2082 // case that changes some time in the future.
2083 if ( count( $newMessageLinks ) === 1
2084 && $newMessageLinks[0]['wiki'] === wfWikiID()
2085 && $newMessageLinks[0]['rev']
2087 /** @var Revision $newMessageRevision */
2088 $newMessageRevision = $newMessageLinks[0]['rev'];
2089 $newMessageRevisionId = $newMessageRevision->getId();
2092 return $newMessageRevisionId;
2096 * Internal uncached check for new messages
2099 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2100 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2101 * @return bool True if the user has new messages
2103 protected function checkNewtalk( $field, $id ) {
2104 $dbr = wfGetDB( DB_SLAVE
);
2106 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__
);
2108 return $ok !== false;
2112 * Add or update the new messages flag
2113 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2114 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2115 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2116 * @return bool True if successful, false otherwise
2118 protected function updateNewtalk( $field, $id, $curRev = null ) {
2119 // Get timestamp of the talk page revision prior to the current one
2120 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2121 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2122 // Mark the user as having new messages since this revision
2123 $dbw = wfGetDB( DB_MASTER
);
2124 $dbw->insert( 'user_newtalk',
2125 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2128 if ( $dbw->affectedRows() ) {
2129 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2132 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2138 * Clear the new messages flag for the given user
2139 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2140 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2141 * @return bool True if successful, false otherwise
2143 protected function deleteNewtalk( $field, $id ) {
2144 $dbw = wfGetDB( DB_MASTER
);
2145 $dbw->delete( 'user_newtalk',
2146 array( $field => $id ),
2148 if ( $dbw->affectedRows() ) {
2149 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2152 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2158 * Update the 'You have new messages!' status.
2159 * @param bool $val Whether the user has new messages
2160 * @param Revision $curRev New, as yet unseen revision of the user talk
2161 * page. Ignored if null or !$val.
2163 public function setNewtalk( $val, $curRev = null ) {
2164 if ( wfReadOnly() ) {
2169 $this->mNewtalk
= $val;
2171 if ( $this->isAnon() ) {
2173 $id = $this->getName();
2176 $id = $this->getId();
2180 $changed = $this->updateNewtalk( $field, $id, $curRev );
2182 $changed = $this->deleteNewtalk( $field, $id );
2186 $this->invalidateCache();
2191 * Generate a current or new-future timestamp to be stored in the
2192 * user_touched field when we update things.
2193 * @return string Timestamp in TS_MW format
2195 private function newTouchedTimestamp() {
2196 global $wgClockSkewFudge;
2198 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2199 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2200 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2207 * Clear user data from memcached
2209 * Use after applying updates to the database; caller's
2210 * responsibility to update user_touched if appropriate.
2212 * Called implicitly from invalidateCache() and saveSettings().
2214 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2216 public function clearSharedCache( $mode = 'changed' ) {
2217 if ( !$this->getId() ) {
2221 $cache = ObjectCache
::getMainWANInstance();
2222 $key = $this->getCacheKey( $cache );
2223 if ( $mode === 'refresh' ) {
2224 $cache->delete( $key, 1 );
2226 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
2227 $cache->delete( $key );
2233 * Immediately touch the user data cache for this account
2235 * Calls touch() and removes account data from memcached
2237 public function invalidateCache() {
2239 $this->clearSharedCache();
2243 * Update the "touched" timestamp for the user
2245 * This is useful on various login/logout events when making sure that
2246 * a browser or proxy that has multiple tenants does not suffer cache
2247 * pollution where the new user sees the old users content. The value
2248 * of getTouched() is checked when determining 304 vs 200 responses.
2249 * Unlike invalidateCache(), this preserves the User object cache and
2250 * avoids database writes.
2254 public function touch() {
2255 $id = $this->getId();
2257 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2258 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2259 $this->mQuickTouched
= null;
2264 * Validate the cache for this account.
2265 * @param string $timestamp A timestamp in TS_MW format
2268 public function validateCache( $timestamp ) {
2269 return ( $timestamp >= $this->getTouched() );
2273 * Get the user touched timestamp
2275 * Use this value only to validate caches via inequalities
2276 * such as in the case of HTTP If-Modified-Since response logic
2278 * @return string TS_MW Timestamp
2280 public function getTouched() {
2284 if ( $this->mQuickTouched
=== null ) {
2285 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2286 $cache = ObjectCache
::getMainWANInstance();
2288 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2291 return max( $this->mTouched
, $this->mQuickTouched
);
2294 return $this->mTouched
;
2298 * Get the user_touched timestamp field (time of last DB updates)
2299 * @return string TS_MW Timestamp
2302 public function getDBTouched() {
2305 return $this->mTouched
;
2309 * @deprecated Removed in 1.27.
2313 public function getPassword() {
2314 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2318 * @deprecated Removed in 1.27.
2322 public function getTemporaryPassword() {
2323 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2327 * Set the password and reset the random token.
2328 * Calls through to authentication plugin if necessary;
2329 * will have no effect if the auth plugin refuses to
2330 * pass the change through or if the legal password
2333 * As a special case, setting the password to null
2334 * wipes it, so the account cannot be logged in until
2335 * a new password is set, for instance via e-mail.
2337 * @deprecated since 1.27. AuthManager is coming.
2338 * @param string $str New password to set
2339 * @throws PasswordError On failure
2342 public function setPassword( $str ) {
2345 if ( $str !== null ) {
2346 if ( !$wgAuth->allowPasswordChange() ) {
2347 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2350 $status = $this->checkPasswordValidity( $str );
2351 if ( !$status->isGood() ) {
2352 throw new PasswordError( $status->getMessage()->text() );
2356 if ( !$wgAuth->setPassword( $this, $str ) ) {
2357 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2361 $this->setOption( 'watchlisttoken', false );
2362 $this->setPasswordInternal( $str );
2368 * Set the password and reset the random token unconditionally.
2370 * @deprecated since 1.27. AuthManager is coming.
2371 * @param string|null $str New password to set or null to set an invalid
2372 * password hash meaning that the user will not be able to log in
2373 * through the web interface.
2375 public function setInternalPassword( $str ) {
2378 if ( $wgAuth->allowSetLocalPassword() ) {
2380 $this->setOption( 'watchlisttoken', false );
2381 $this->setPasswordInternal( $str );
2386 * Actually set the password and such
2387 * @since 1.27 cannot set a password for a user not in the database
2388 * @param string|null $str New password to set or null to set an invalid
2389 * password hash meaning that the user will not be able to log in
2390 * through the web interface.
2392 private function setPasswordInternal( $str ) {
2393 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2395 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2398 $passwordFactory = new PasswordFactory();
2399 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2400 $dbw = wfGetDB( DB_MASTER
);
2404 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2405 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2406 'user_newpass_time' => $dbw->timestampOrNull( null ),
2414 // When the main password is changed, invalidate all bot passwords too
2415 BotPassword
::invalidateAllPasswordsForUser( $this->getName() );
2419 * Get the user's current token.
2420 * @param bool $forceCreation Force the generation of a new token if the
2421 * user doesn't have one (default=true for backwards compatibility).
2422 * @return string Token
2424 public function getToken( $forceCreation = true ) {
2426 if ( !$this->mToken
&& $forceCreation ) {
2429 return $this->mToken
;
2433 * Set the random token (used for persistent authentication)
2434 * Called from loadDefaults() among other places.
2436 * @param string|bool $token If specified, set the token to this value
2438 public function setToken( $token = false ) {
2441 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2443 $this->mToken
= $token;
2448 * Set the password for a password reminder or new account email
2450 * @deprecated since 1.27, AuthManager is coming
2451 * @param string $str New password to set or null to set an invalid
2452 * password hash meaning that the user will not be able to use it
2453 * @param bool $throttle If true, reset the throttle timestamp to the present
2455 public function setNewpassword( $str, $throttle = true ) {
2456 $id = $this->getId();
2458 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2461 $dbw = wfGetDB( DB_MASTER
);
2463 $passwordFactory = new PasswordFactory();
2464 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2466 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2469 if ( $str === null ) {
2470 $update['user_newpass_time'] = null;
2471 } elseif ( $throttle ) {
2472 $update['user_newpass_time'] = $dbw->timestamp();
2475 $dbw->update( 'user', $update, array( 'user_id' => $id ), __METHOD__
);
2479 * Has password reminder email been sent within the last
2480 * $wgPasswordReminderResendTime hours?
2483 public function isPasswordReminderThrottled() {
2484 global $wgPasswordReminderResendTime;
2486 if ( !$wgPasswordReminderResendTime ) {
2492 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2493 ?
wfGetDB( DB_MASTER
)
2494 : wfGetDB( DB_SLAVE
);
2495 $newpassTime = $db->selectField(
2497 'user_newpass_time',
2498 array( 'user_id' => $this->getId() ),
2502 if ( $newpassTime === null ) {
2505 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2506 return time() < $expiry;
2510 * Get the user's e-mail address
2511 * @return string User's email address
2513 public function getEmail() {
2515 Hooks
::run( 'UserGetEmail', array( $this, &$this->mEmail
) );
2516 return $this->mEmail
;
2520 * Get the timestamp of the user's e-mail authentication
2521 * @return string TS_MW timestamp
2523 public function getEmailAuthenticationTimestamp() {
2525 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2526 return $this->mEmailAuthenticated
;
2530 * Set the user's e-mail address
2531 * @param string $str New e-mail address
2533 public function setEmail( $str ) {
2535 if ( $str == $this->mEmail
) {
2538 $this->invalidateEmail();
2539 $this->mEmail
= $str;
2540 Hooks
::run( 'UserSetEmail', array( $this, &$this->mEmail
) );
2544 * Set the user's e-mail address and a confirmation mail if needed.
2547 * @param string $str New e-mail address
2550 public function setEmailWithConfirmation( $str ) {
2551 global $wgEnableEmail, $wgEmailAuthentication;
2553 if ( !$wgEnableEmail ) {
2554 return Status
::newFatal( 'emaildisabled' );
2557 $oldaddr = $this->getEmail();
2558 if ( $str === $oldaddr ) {
2559 return Status
::newGood( true );
2562 $this->setEmail( $str );
2564 if ( $str !== '' && $wgEmailAuthentication ) {
2565 // Send a confirmation request to the new address if needed
2566 $type = $oldaddr != '' ?
'changed' : 'set';
2567 $result = $this->sendConfirmationMail( $type );
2568 if ( $result->isGood() ) {
2569 // Say to the caller that a confirmation mail has been sent
2570 $result->value
= 'eauth';
2573 $result = Status
::newGood( true );
2580 * Get the user's real name
2581 * @return string User's real name
2583 public function getRealName() {
2584 if ( !$this->isItemLoaded( 'realname' ) ) {
2588 return $this->mRealName
;
2592 * Set the user's real name
2593 * @param string $str New real name
2595 public function setRealName( $str ) {
2597 $this->mRealName
= $str;
2601 * Get the user's current setting for a given option.
2603 * @param string $oname The option to check
2604 * @param string $defaultOverride A default value returned if the option does not exist
2605 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2606 * @return string User's current value for the option
2607 * @see getBoolOption()
2608 * @see getIntOption()
2610 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2611 global $wgHiddenPrefs;
2612 $this->loadOptions();
2614 # We want 'disabled' preferences to always behave as the default value for
2615 # users, even if they have set the option explicitly in their settings (ie they
2616 # set it, and then it was disabled removing their ability to change it). But
2617 # we don't want to erase the preferences in the database in case the preference
2618 # is re-enabled again. So don't touch $mOptions, just override the returned value
2619 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2620 return self
::getDefaultOption( $oname );
2623 if ( array_key_exists( $oname, $this->mOptions
) ) {
2624 return $this->mOptions
[$oname];
2626 return $defaultOverride;
2631 * Get all user's options
2633 * @param int $flags Bitwise combination of:
2634 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2635 * to the default value. (Since 1.25)
2638 public function getOptions( $flags = 0 ) {
2639 global $wgHiddenPrefs;
2640 $this->loadOptions();
2641 $options = $this->mOptions
;
2643 # We want 'disabled' preferences to always behave as the default value for
2644 # users, even if they have set the option explicitly in their settings (ie they
2645 # set it, and then it was disabled removing their ability to change it). But
2646 # we don't want to erase the preferences in the database in case the preference
2647 # is re-enabled again. So don't touch $mOptions, just override the returned value
2648 foreach ( $wgHiddenPrefs as $pref ) {
2649 $default = self
::getDefaultOption( $pref );
2650 if ( $default !== null ) {
2651 $options[$pref] = $default;
2655 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2656 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2663 * Get the user's current setting for a given option, as a boolean value.
2665 * @param string $oname The option to check
2666 * @return bool User's current value for the option
2669 public function getBoolOption( $oname ) {
2670 return (bool)$this->getOption( $oname );
2674 * Get the user's current setting for a given option, as an integer value.
2676 * @param string $oname The option to check
2677 * @param int $defaultOverride A default value returned if the option does not exist
2678 * @return int User's current value for the option
2681 public function getIntOption( $oname, $defaultOverride = 0 ) {
2682 $val = $this->getOption( $oname );
2684 $val = $defaultOverride;
2686 return intval( $val );
2690 * Set the given option for a user.
2692 * You need to call saveSettings() to actually write to the database.
2694 * @param string $oname The option to set
2695 * @param mixed $val New value to set
2697 public function setOption( $oname, $val ) {
2698 $this->loadOptions();
2700 // Explicitly NULL values should refer to defaults
2701 if ( is_null( $val ) ) {
2702 $val = self
::getDefaultOption( $oname );
2705 $this->mOptions
[$oname] = $val;
2709 * Get a token stored in the preferences (like the watchlist one),
2710 * resetting it if it's empty (and saving changes).
2712 * @param string $oname The option name to retrieve the token from
2713 * @return string|bool User's current value for the option, or false if this option is disabled.
2714 * @see resetTokenFromOption()
2716 * @deprecated 1.26 Applications should use the OAuth extension
2718 public function getTokenFromOption( $oname ) {
2719 global $wgHiddenPrefs;
2721 $id = $this->getId();
2722 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2726 $token = $this->getOption( $oname );
2728 // Default to a value based on the user token to avoid space
2729 // wasted on storing tokens for all users. When this option
2730 // is set manually by the user, only then is it stored.
2731 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2738 * Reset a token stored in the preferences (like the watchlist one).
2739 * *Does not* save user's preferences (similarly to setOption()).
2741 * @param string $oname The option name to reset the token in
2742 * @return string|bool New token value, or false if this option is disabled.
2743 * @see getTokenFromOption()
2746 public function resetTokenFromOption( $oname ) {
2747 global $wgHiddenPrefs;
2748 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2752 $token = MWCryptRand
::generateHex( 40 );
2753 $this->setOption( $oname, $token );
2758 * Return a list of the types of user options currently returned by
2759 * User::getOptionKinds().
2761 * Currently, the option kinds are:
2762 * - 'registered' - preferences which are registered in core MediaWiki or
2763 * by extensions using the UserGetDefaultOptions hook.
2764 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2765 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2766 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2767 * be used by user scripts.
2768 * - 'special' - "preferences" that are not accessible via User::getOptions
2769 * or User::setOptions.
2770 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2771 * These are usually legacy options, removed in newer versions.
2773 * The API (and possibly others) use this function to determine the possible
2774 * option types for validation purposes, so make sure to update this when a
2775 * new option kind is added.
2777 * @see User::getOptionKinds
2778 * @return array Option kinds
2780 public static function listOptionKinds() {
2783 'registered-multiselect',
2784 'registered-checkmatrix',
2792 * Return an associative array mapping preferences keys to the kind of a preference they're
2793 * used for. Different kinds are handled differently when setting or reading preferences.
2795 * See User::listOptionKinds for the list of valid option types that can be provided.
2797 * @see User::listOptionKinds
2798 * @param IContextSource $context
2799 * @param array $options Assoc. array with options keys to check as keys.
2800 * Defaults to $this->mOptions.
2801 * @return array The key => kind mapping data
2803 public function getOptionKinds( IContextSource
$context, $options = null ) {
2804 $this->loadOptions();
2805 if ( $options === null ) {
2806 $options = $this->mOptions
;
2809 $prefs = Preferences
::getPreferences( $this, $context );
2812 // Pull out the "special" options, so they don't get converted as
2813 // multiselect or checkmatrix.
2814 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2815 foreach ( $specialOptions as $name => $value ) {
2816 unset( $prefs[$name] );
2819 // Multiselect and checkmatrix options are stored in the database with
2820 // one key per option, each having a boolean value. Extract those keys.
2821 $multiselectOptions = array();
2822 foreach ( $prefs as $name => $info ) {
2823 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2824 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2825 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2826 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2828 foreach ( $opts as $value ) {
2829 $multiselectOptions["$prefix$value"] = true;
2832 unset( $prefs[$name] );
2835 $checkmatrixOptions = array();
2836 foreach ( $prefs as $name => $info ) {
2837 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2838 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2839 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2840 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2841 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2843 foreach ( $columns as $column ) {
2844 foreach ( $rows as $row ) {
2845 $checkmatrixOptions["$prefix$column-$row"] = true;
2849 unset( $prefs[$name] );
2853 // $value is ignored
2854 foreach ( $options as $key => $value ) {
2855 if ( isset( $prefs[$key] ) ) {
2856 $mapping[$key] = 'registered';
2857 } elseif ( isset( $multiselectOptions[$key] ) ) {
2858 $mapping[$key] = 'registered-multiselect';
2859 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2860 $mapping[$key] = 'registered-checkmatrix';
2861 } elseif ( isset( $specialOptions[$key] ) ) {
2862 $mapping[$key] = 'special';
2863 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2864 $mapping[$key] = 'userjs';
2866 $mapping[$key] = 'unused';
2874 * Reset certain (or all) options to the site defaults
2876 * The optional parameter determines which kinds of preferences will be reset.
2877 * Supported values are everything that can be reported by getOptionKinds()
2878 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2880 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2881 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2882 * for backwards-compatibility.
2883 * @param IContextSource|null $context Context source used when $resetKinds
2884 * does not contain 'all', passed to getOptionKinds().
2885 * Defaults to RequestContext::getMain() when null.
2887 public function resetOptions(
2888 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2889 IContextSource
$context = null
2892 $defaultOptions = self
::getDefaultOptions();
2894 if ( !is_array( $resetKinds ) ) {
2895 $resetKinds = array( $resetKinds );
2898 if ( in_array( 'all', $resetKinds ) ) {
2899 $newOptions = $defaultOptions;
2901 if ( $context === null ) {
2902 $context = RequestContext
::getMain();
2905 $optionKinds = $this->getOptionKinds( $context );
2906 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2907 $newOptions = array();
2909 // Use default values for the options that should be deleted, and
2910 // copy old values for the ones that shouldn't.
2911 foreach ( $this->mOptions
as $key => $value ) {
2912 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2913 if ( array_key_exists( $key, $defaultOptions ) ) {
2914 $newOptions[$key] = $defaultOptions[$key];
2917 $newOptions[$key] = $value;
2922 Hooks
::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2924 $this->mOptions
= $newOptions;
2925 $this->mOptionsLoaded
= true;
2929 * Get the user's preferred date format.
2930 * @return string User's preferred date format
2932 public function getDatePreference() {
2933 // Important migration for old data rows
2934 if ( is_null( $this->mDatePreference
) ) {
2936 $value = $this->getOption( 'date' );
2937 $map = $wgLang->getDatePreferenceMigrationMap();
2938 if ( isset( $map[$value] ) ) {
2939 $value = $map[$value];
2941 $this->mDatePreference
= $value;
2943 return $this->mDatePreference
;
2947 * Determine based on the wiki configuration and the user's options,
2948 * whether this user must be over HTTPS no matter what.
2952 public function requiresHTTPS() {
2953 global $wgSecureLogin;
2954 if ( !$wgSecureLogin ) {
2957 $https = $this->getBoolOption( 'prefershttps' );
2958 Hooks
::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2960 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2967 * Get the user preferred stub threshold
2971 public function getStubThreshold() {
2972 global $wgMaxArticleSize; # Maximum article size, in Kb
2973 $threshold = $this->getIntOption( 'stubthreshold' );
2974 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2975 // If they have set an impossible value, disable the preference
2976 // so we can use the parser cache again.
2983 * Get the permissions this user has.
2984 * @return array Array of String permission names
2986 public function getRights() {
2987 if ( is_null( $this->mRights
) ) {
2988 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2990 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
2991 if ( $allowedRights !== null ) {
2992 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
2995 Hooks
::run( 'UserGetRights', array( $this, &$this->mRights
) );
2996 // Force reindexation of rights when a hook has unset one of them
2997 $this->mRights
= array_values( array_unique( $this->mRights
) );
2999 return $this->mRights
;
3003 * Get the list of explicit group memberships this user has.
3004 * The implicit * and user groups are not included.
3005 * @return array Array of String internal group names
3007 public function getGroups() {
3009 $this->loadGroups();
3010 return $this->mGroups
;
3014 * Get the list of implicit group memberships this user has.
3015 * This includes all explicit groups, plus 'user' if logged in,
3016 * '*' for all accounts, and autopromoted groups
3017 * @param bool $recache Whether to avoid the cache
3018 * @return array Array of String internal group names
3020 public function getEffectiveGroups( $recache = false ) {
3021 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3022 $this->mEffectiveGroups
= array_unique( array_merge(
3023 $this->getGroups(), // explicit groups
3024 $this->getAutomaticGroups( $recache ) // implicit groups
3026 // Hook for additional groups
3027 Hooks
::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
3028 // Force reindexation of groups when a hook has unset one of them
3029 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3031 return $this->mEffectiveGroups
;
3035 * Get the list of implicit group memberships this user has.
3036 * This includes 'user' if logged in, '*' for all accounts,
3037 * and autopromoted groups
3038 * @param bool $recache Whether to avoid the cache
3039 * @return array Array of String internal group names
3041 public function getAutomaticGroups( $recache = false ) {
3042 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3043 $this->mImplicitGroups
= array( '*' );
3044 if ( $this->getId() ) {
3045 $this->mImplicitGroups
[] = 'user';
3047 $this->mImplicitGroups
= array_unique( array_merge(
3048 $this->mImplicitGroups
,
3049 Autopromote
::getAutopromoteGroups( $this )
3053 // Assure data consistency with rights/groups,
3054 // as getEffectiveGroups() depends on this function
3055 $this->mEffectiveGroups
= null;
3058 return $this->mImplicitGroups
;
3062 * Returns the groups the user has belonged to.
3064 * The user may still belong to the returned groups. Compare with getGroups().
3066 * The function will not return groups the user had belonged to before MW 1.17
3068 * @return array Names of the groups the user has belonged to.
3070 public function getFormerGroups() {
3073 if ( is_null( $this->mFormerGroups
) ) {
3074 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3075 ?
wfGetDB( DB_MASTER
)
3076 : wfGetDB( DB_SLAVE
);
3077 $res = $db->select( 'user_former_groups',
3078 array( 'ufg_group' ),
3079 array( 'ufg_user' => $this->mId
),
3081 $this->mFormerGroups
= array();
3082 foreach ( $res as $row ) {
3083 $this->mFormerGroups
[] = $row->ufg_group
;
3087 return $this->mFormerGroups
;
3091 * Get the user's edit count.
3092 * @return int|null Null for anonymous users
3094 public function getEditCount() {
3095 if ( !$this->getId() ) {
3099 if ( $this->mEditCount
=== null ) {
3100 /* Populate the count, if it has not been populated yet */
3101 $dbr = wfGetDB( DB_SLAVE
);
3102 // check if the user_editcount field has been initialized
3103 $count = $dbr->selectField(
3104 'user', 'user_editcount',
3105 array( 'user_id' => $this->mId
),
3109 if ( $count === null ) {
3110 // it has not been initialized. do so.
3111 $count = $this->initEditCount();
3113 $this->mEditCount
= $count;
3115 return (int)$this->mEditCount
;
3119 * Add the user to the given group.
3120 * This takes immediate effect.
3121 * @param string $group Name of the group to add
3124 public function addGroup( $group ) {
3127 if ( !Hooks
::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3131 $dbw = wfGetDB( DB_MASTER
);
3132 if ( $this->getId() ) {
3133 $dbw->insert( 'user_groups',
3135 'ug_user' => $this->getID(),
3136 'ug_group' => $group,
3139 array( 'IGNORE' ) );
3142 $this->loadGroups();
3143 $this->mGroups
[] = $group;
3144 // In case loadGroups was not called before, we now have the right twice.
3145 // Get rid of the duplicate.
3146 $this->mGroups
= array_unique( $this->mGroups
);
3148 // Refresh the groups caches, and clear the rights cache so it will be
3149 // refreshed on the next call to $this->getRights().
3150 $this->getEffectiveGroups( true );
3151 $this->mRights
= null;
3153 $this->invalidateCache();
3159 * Remove the user from the given group.
3160 * This takes immediate effect.
3161 * @param string $group Name of the group to remove
3164 public function removeGroup( $group ) {
3166 if ( !Hooks
::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3170 $dbw = wfGetDB( DB_MASTER
);
3171 $dbw->delete( 'user_groups',
3173 'ug_user' => $this->getID(),
3174 'ug_group' => $group,
3177 // Remember that the user was in this group
3178 $dbw->insert( 'user_former_groups',
3180 'ufg_user' => $this->getID(),
3181 'ufg_group' => $group,
3187 $this->loadGroups();
3188 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3190 // Refresh the groups caches, and clear the rights cache so it will be
3191 // refreshed on the next call to $this->getRights().
3192 $this->getEffectiveGroups( true );
3193 $this->mRights
= null;
3195 $this->invalidateCache();
3201 * Get whether the user is logged in
3204 public function isLoggedIn() {
3205 return $this->getID() != 0;
3209 * Get whether the user is anonymous
3212 public function isAnon() {
3213 return !$this->isLoggedIn();
3217 * Check if user is allowed to access a feature / make an action
3219 * @param string ... Permissions to test
3220 * @return bool True if user is allowed to perform *any* of the given actions
3222 public function isAllowedAny() {
3223 $permissions = func_get_args();
3224 foreach ( $permissions as $permission ) {
3225 if ( $this->isAllowed( $permission ) ) {
3234 * @param string ... Permissions to test
3235 * @return bool True if the user is allowed to perform *all* of the given actions
3237 public function isAllowedAll() {
3238 $permissions = func_get_args();
3239 foreach ( $permissions as $permission ) {
3240 if ( !$this->isAllowed( $permission ) ) {
3248 * Internal mechanics of testing a permission
3249 * @param string $action
3252 public function isAllowed( $action = '' ) {
3253 if ( $action === '' ) {
3254 return true; // In the spirit of DWIM
3256 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3257 // by misconfiguration: 0 == 'foo'
3258 return in_array( $action, $this->getRights(), true );
3262 * Check whether to enable recent changes patrol features for this user
3263 * @return bool True or false
3265 public function useRCPatrol() {
3266 global $wgUseRCPatrol;
3267 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3271 * Check whether to enable new pages patrol features for this user
3272 * @return bool True or false
3274 public function useNPPatrol() {
3275 global $wgUseRCPatrol, $wgUseNPPatrol;
3277 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3278 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3283 * Check whether to enable new files patrol features for this user
3284 * @return bool True or false
3286 public function useFilePatrol() {
3287 global $wgUseRCPatrol, $wgUseFilePatrol;
3289 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3290 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3295 * Get the WebRequest object to use with this object
3297 * @return WebRequest
3299 public function getRequest() {
3300 if ( $this->mRequest
) {
3301 return $this->mRequest
;
3309 * Get a WatchedItem for this user and $title.
3311 * @since 1.22 $checkRights parameter added
3312 * @param Title $title
3313 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3314 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3315 * @return WatchedItem
3317 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3318 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3320 if ( isset( $this->mWatchedItems
[$key] ) ) {
3321 return $this->mWatchedItems
[$key];
3324 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3325 $this->mWatchedItems
= array();
3328 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3329 return $this->mWatchedItems
[$key];
3333 * Check the watched status of an article.
3334 * @since 1.22 $checkRights parameter added
3335 * @param Title $title Title of the article to look at
3336 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3337 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3340 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3341 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3346 * @since 1.22 $checkRights parameter added
3347 * @param Title $title Title of the article to look at
3348 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3349 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3351 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3352 $this->getWatchedItem( $title, $checkRights )->addWatch();
3353 $this->invalidateCache();
3357 * Stop watching an article.
3358 * @since 1.22 $checkRights parameter added
3359 * @param Title $title Title of the article to look at
3360 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3361 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3363 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3364 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3365 $this->invalidateCache();
3369 * Clear the user's notification timestamp for the given title.
3370 * If e-notif e-mails are on, they will receive notification mails on
3371 * the next change of the page if it's watched etc.
3372 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3373 * @param Title $title Title of the article to look at
3374 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3376 public function clearNotification( &$title, $oldid = 0 ) {
3377 global $wgUseEnotif, $wgShowUpdatedMarker;
3379 // Do nothing if the database is locked to writes
3380 if ( wfReadOnly() ) {
3384 // Do nothing if not allowed to edit the watchlist
3385 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3389 // If we're working on user's talk page, we should update the talk page message indicator
3390 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3391 if ( !Hooks
::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3396 // Try to update the DB post-send and only if needed...
3397 DeferredUpdates
::addCallableUpdate( function() use ( $that, $title, $oldid ) {
3398 if ( !$that->getNewtalk() ) {
3399 return; // no notifications to clear
3402 // Delete the last notifications (they stack up)
3403 $that->setNewtalk( false );
3405 // If there is a new, unseen, revision, use its timestamp
3407 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3410 $that->setNewtalk( true, Revision
::newFromId( $nextid ) );
3415 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3419 if ( $this->isAnon() ) {
3420 // Nothing else to do...
3424 // Only update the timestamp if the page is being watched.
3425 // The query to find out if it is watched is cached both in memcached and per-invocation,
3426 // and when it does have to be executed, it can be on a slave
3427 // If this is the user's newtalk page, we always update the timestamp
3429 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3433 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3434 $force, $oldid, WatchedItem
::DEFERRED
3439 * Resets all of the given user's page-change notification timestamps.
3440 * If e-notif e-mails are on, they will receive notification mails on
3441 * the next change of any watched page.
3442 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3444 public function clearAllNotifications() {
3445 if ( wfReadOnly() ) {
3449 // Do nothing if not allowed to edit the watchlist
3450 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3454 global $wgUseEnotif, $wgShowUpdatedMarker;
3455 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3456 $this->setNewtalk( false );
3459 $id = $this->getId();
3461 $dbw = wfGetDB( DB_MASTER
);
3462 $dbw->update( 'watchlist',
3463 array( /* SET */ 'wl_notificationtimestamp' => null ),
3464 array( /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ),
3467 // We also need to clear here the "you have new message" notification for the own user_talk page;
3468 // it's cleared one page view later in WikiPage::doViewUpdates().
3473 * Set a cookie on the user's client. Wrapper for
3474 * WebResponse::setCookie
3475 * @deprecated since 1.27
3476 * @param string $name Name of the cookie to set
3477 * @param string $value Value to set
3478 * @param int $exp Expiration time, as a UNIX time value;
3479 * if 0 or not specified, use the default $wgCookieExpiration
3480 * @param bool $secure
3481 * true: Force setting the secure attribute when setting the cookie
3482 * false: Force NOT setting the secure attribute when setting the cookie
3483 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3484 * @param array $params Array of options sent passed to WebResponse::setcookie()
3485 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3488 protected function setCookie(
3489 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3491 wfDeprecated( __METHOD__
, '1.27' );
3492 if ( $request === null ) {
3493 $request = $this->getRequest();
3495 $params['secure'] = $secure;
3496 $request->response()->setCookie( $name, $value, $exp, $params );
3500 * Clear a cookie on the user's client
3501 * @deprecated since 1.27
3502 * @param string $name Name of the cookie to clear
3503 * @param bool $secure
3504 * true: Force setting the secure attribute when setting the cookie
3505 * false: Force NOT setting the secure attribute when setting the cookie
3506 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3507 * @param array $params Array of options sent passed to WebResponse::setcookie()
3509 protected function clearCookie( $name, $secure = null, $params = array() ) {
3510 wfDeprecated( __METHOD__
, '1.27' );
3511 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3515 * Set an extended login cookie on the user's client. The expiry of the cookie
3516 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3519 * @see User::setCookie
3521 * @deprecated since 1.27
3522 * @param string $name Name of the cookie to set
3523 * @param string $value Value to set
3524 * @param bool $secure
3525 * true: Force setting the secure attribute when setting the cookie
3526 * false: Force NOT setting the secure attribute when setting the cookie
3527 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3529 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3530 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3532 wfDeprecated( __METHOD__
, '1.27' );
3535 $exp +
= $wgExtendedLoginCookieExpiration !== null
3536 ?
$wgExtendedLoginCookieExpiration
3537 : $wgCookieExpiration;
3539 $this->setCookie( $name, $value, $exp, $secure );
3543 * Persist this user's session (e.g. set cookies)
3545 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3547 * @param bool $secure Whether to force secure/insecure cookies or use default
3548 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3550 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3552 if ( 0 == $this->mId
) {
3556 $session = $this->getRequest()->getSession();
3557 if ( $request && $session->getRequest() !== $request ) {
3558 $session = $session->sessionWithRequest( $request );
3560 $delay = $session->delaySave();
3562 if ( !$session->getUser()->equals( $this ) ) {
3563 if ( !$session->canSetUser() ) {
3564 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3565 ->warning( __METHOD__
.
3566 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3570 $session->setUser( $this );
3573 $session->setRememberUser( $rememberMe );
3574 if ( $secure !== null ) {
3575 $session->setForceHTTPS( $secure );
3578 $session->persist();
3580 ScopedCallback
::consume( $delay );
3584 * Log this user out.
3586 public function logout() {
3587 if ( Hooks
::run( 'UserLogout', array( &$this ) ) ) {
3593 * Clear the user's session, and reset the instance cache.
3596 public function doLogout() {
3597 $session = $this->getRequest()->getSession();
3598 if ( !$session->canSetUser() ) {
3599 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3600 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3601 } elseif ( !$session->getUser()->equals( $this ) ) {
3602 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3603 ->warning( __METHOD__
.
3604 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3606 // But we still may as well make this user object anon
3607 $this->clearInstanceCache( 'defaults' );
3609 $this->clearInstanceCache( 'defaults' );
3610 $delay = $session->delaySave();
3611 $session->setLoggedOutTimestamp( time() );
3612 $session->setUser( new User
);
3613 $session->set( 'wsUserID', 0 ); // Other code expects this
3614 ScopedCallback
::consume( $delay );
3619 * Save this user's settings into the database.
3620 * @todo Only rarely do all these fields need to be set!
3622 public function saveSettings() {
3623 if ( wfReadOnly() ) {
3624 // @TODO: caller should deal with this instead!
3625 // This should really just be an exception.
3626 MWExceptionHandler
::logException( new DBExpectedError(
3628 "Could not update user with ID '{$this->mId}'; DB is read-only."
3634 if ( 0 == $this->mId
) {
3638 // Get a new user_touched that is higher than the old one.
3639 // This will be used for a CAS check as a last-resort safety
3640 // check against race conditions and slave lag.
3641 $oldTouched = $this->mTouched
;
3642 $newTouched = $this->newTouchedTimestamp();
3644 $dbw = wfGetDB( DB_MASTER
);
3645 $dbw->update( 'user',
3647 'user_name' => $this->mName
,
3648 'user_real_name' => $this->mRealName
,
3649 'user_email' => $this->mEmail
,
3650 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3651 'user_touched' => $dbw->timestamp( $newTouched ),
3652 'user_token' => strval( $this->mToken
),
3653 'user_email_token' => $this->mEmailToken
,
3654 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3655 ), array( /* WHERE */
3656 'user_id' => $this->mId
,
3657 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3661 if ( !$dbw->affectedRows() ) {
3662 // Maybe the problem was a missed cache update; clear it to be safe
3663 $this->clearSharedCache( 'refresh' );
3664 // User was changed in the meantime or loaded with stale data
3665 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3666 throw new MWException(
3667 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3668 " the version of the user to be saved is older than the current version."
3672 $this->mTouched
= $newTouched;
3673 $this->saveOptions();
3675 Hooks
::run( 'UserSaveSettings', array( $this ) );
3676 $this->clearSharedCache();
3677 $this->getUserPage()->invalidateCache();
3681 * If only this user's username is known, and it exists, return the user ID.
3683 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3686 public function idForName( $flags = 0 ) {
3687 $s = trim( $this->getName() );
3692 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3693 ?
wfGetDB( DB_MASTER
)
3694 : wfGetDB( DB_SLAVE
);
3696 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3697 ?
array( 'LOCK IN SHARE MODE' )
3700 $id = $db->selectField( 'user',
3701 'user_id', array( 'user_name' => $s ), __METHOD__
, $options );
3707 * Add a user to the database, return the user object
3709 * @param string $name Username to add
3710 * @param array $params Array of Strings Non-default parameters to save to
3711 * the database as user_* fields:
3712 * - email: The user's email address.
3713 * - email_authenticated: The email authentication timestamp.
3714 * - real_name: The user's real name.
3715 * - options: An associative array of non-default options.
3716 * - token: Random authentication token. Do not set.
3717 * - registration: Registration timestamp. Do not set.
3719 * @return User|null User object, or null if the username already exists.
3721 public static function createNew( $name, $params = array() ) {
3722 foreach ( array( 'password', 'newpassword', 'newpass_time', 'password_expires' ) as $field ) {
3723 if ( isset( $params[$field] ) ) {
3724 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3725 unset( $params[$field] );
3731 $user->setToken(); // init token
3732 if ( isset( $params['options'] ) ) {
3733 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3734 unset( $params['options'] );
3736 $dbw = wfGetDB( DB_MASTER
);
3737 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3739 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3742 'user_id' => $seqVal,
3743 'user_name' => $name,
3744 'user_password' => $noPass,
3745 'user_newpassword' => $noPass,
3746 'user_email' => $user->mEmail
,
3747 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3748 'user_real_name' => $user->mRealName
,
3749 'user_token' => strval( $user->mToken
),
3750 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3751 'user_editcount' => 0,
3752 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3754 foreach ( $params as $name => $value ) {
3755 $fields["user_$name"] = $value;
3757 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3758 if ( $dbw->affectedRows() ) {
3759 $newUser = User
::newFromId( $dbw->insertId() );
3767 * Add this existing user object to the database. If the user already
3768 * exists, a fatal status object is returned, and the user object is
3769 * initialised with the data from the database.
3771 * Previously, this function generated a DB error due to a key conflict
3772 * if the user already existed. Many extension callers use this function
3773 * in code along the lines of:
3775 * $user = User::newFromName( $name );
3776 * if ( !$user->isLoggedIn() ) {
3777 * $user->addToDatabase();
3779 * // do something with $user...
3781 * However, this was vulnerable to a race condition (bug 16020). By
3782 * initialising the user object if the user exists, we aim to support this
3783 * calling sequence as far as possible.
3785 * Note that if the user exists, this function will acquire a write lock,
3786 * so it is still advisable to make the call conditional on isLoggedIn(),
3787 * and to commit the transaction after calling.
3789 * @throws MWException
3792 public function addToDatabase() {
3794 if ( !$this->mToken
) {
3795 $this->setToken(); // init token
3798 $this->mTouched
= $this->newTouchedTimestamp();
3800 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3802 $dbw = wfGetDB( DB_MASTER
);
3803 $inWrite = $dbw->writesOrCallbacksPending();
3804 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3805 $dbw->insert( 'user',
3807 'user_id' => $seqVal,
3808 'user_name' => $this->mName
,
3809 'user_password' => $noPass,
3810 'user_newpassword' => $noPass,
3811 'user_email' => $this->mEmail
,
3812 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3813 'user_real_name' => $this->mRealName
,
3814 'user_token' => strval( $this->mToken
),
3815 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3816 'user_editcount' => 0,
3817 'user_touched' => $dbw->timestamp( $this->mTouched
),
3821 if ( !$dbw->affectedRows() ) {
3822 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3823 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3825 // Can't commit due to pending writes that may need atomicity.
3826 // This may cause some lock contention unlike the case below.
3827 $options = array( 'LOCK IN SHARE MODE' );
3828 $flags = self
::READ_LOCKING
;
3830 // Often, this case happens early in views before any writes when
3831 // using CentralAuth. It's should be OK to commit and break the snapshot.
3832 $dbw->commit( __METHOD__
, 'flush' );
3834 $flags = self
::READ_LATEST
;
3836 $this->mId
= $dbw->selectField( 'user', 'user_id',
3837 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3840 if ( $this->loadFromDatabase( $flags ) ) {
3845 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3846 "to insert user '{$this->mName}' row, but it was not present in select!" );
3848 return Status
::newFatal( 'userexists' );
3850 $this->mId
= $dbw->insertId();
3851 self
::$idCacheByName[$this->mName
] = $this->mId
;
3853 // Clear instance cache other than user table data, which is already accurate
3854 $this->clearInstanceCache();
3856 $this->saveOptions();
3857 return Status
::newGood();
3861 * If this user is logged-in and blocked,
3862 * block any IP address they've successfully logged in from.
3863 * @return bool A block was spread
3865 public function spreadAnyEditBlock() {
3866 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3867 return $this->spreadBlock();
3873 * If this (non-anonymous) user is blocked,
3874 * block the IP address they've successfully logged in from.
3875 * @return bool A block was spread
3877 protected function spreadBlock() {
3878 wfDebug( __METHOD__
. "()\n" );
3880 if ( $this->mId
== 0 ) {
3884 $userblock = Block
::newFromTarget( $this->getName() );
3885 if ( !$userblock ) {
3889 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3893 * Get whether the user is explicitly blocked from account creation.
3894 * @return bool|Block
3896 public function isBlockedFromCreateAccount() {
3897 $this->getBlockedStatus();
3898 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3899 return $this->mBlock
;
3902 # bug 13611: if the IP address the user is trying to create an account from is
3903 # blocked with createaccount disabled, prevent new account creation there even
3904 # when the user is logged in
3905 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3906 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3908 return $this->mBlockedFromCreateAccount
instanceof Block
3909 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3910 ?
$this->mBlockedFromCreateAccount
3915 * Get whether the user is blocked from using Special:Emailuser.
3918 public function isBlockedFromEmailuser() {
3919 $this->getBlockedStatus();
3920 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3924 * Get whether the user is allowed to create an account.
3927 public function isAllowedToCreateAccount() {
3928 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3932 * Get this user's personal page title.
3934 * @return Title User's personal page title
3936 public function getUserPage() {
3937 return Title
::makeTitle( NS_USER
, $this->getName() );
3941 * Get this user's talk page title.
3943 * @return Title User's talk page title
3945 public function getTalkPage() {
3946 $title = $this->getUserPage();
3947 return $title->getTalkPage();
3951 * Determine whether the user is a newbie. Newbies are either
3952 * anonymous IPs, or the most recently created accounts.
3955 public function isNewbie() {
3956 return !$this->isAllowed( 'autoconfirmed' );
3960 * Check to see if the given clear-text password is one of the accepted passwords
3961 * @deprecated since 1.27. AuthManager is coming.
3962 * @param string $password User password
3963 * @return bool True if the given password is correct, otherwise False
3965 public function checkPassword( $password ) {
3966 global $wgAuth, $wgLegacyEncoding;
3970 // Some passwords will give a fatal Status, which means there is
3971 // some sort of technical or security reason for this password to
3972 // be completely invalid and should never be checked (e.g., T64685)
3973 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
3977 // Certain authentication plugins do NOT want to save
3978 // domain passwords in a mysql database, so we should
3979 // check this (in case $wgAuth->strict() is false).
3980 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3982 } elseif ( $wgAuth->strict() ) {
3983 // Auth plugin doesn't allow local authentication
3985 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3986 // Auth plugin doesn't allow local authentication for this user name
3990 $passwordFactory = new PasswordFactory();
3991 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
3992 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3993 ?
wfGetDB( DB_MASTER
)
3994 : wfGetDB( DB_SLAVE
);
3997 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
3998 'user', 'user_password', array( 'user_id' => $this->getId() ), __METHOD__
4000 } catch ( PasswordError
$e ) {
4001 wfDebug( 'Invalid password hash found in database.' );
4002 $mPassword = PasswordFactory
::newInvalidPassword();
4005 if ( !$mPassword->equals( $password ) ) {
4006 if ( $wgLegacyEncoding ) {
4007 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4008 // Check for this with iconv
4009 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4010 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4018 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4019 $this->setPasswordInternal( $password );
4026 * Check if the given clear-text password matches the temporary password
4027 * sent by e-mail for password reset operations.
4029 * @deprecated since 1.27. AuthManager is coming.
4030 * @param string $plaintext
4031 * @return bool True if matches, false otherwise
4033 public function checkTemporaryPassword( $plaintext ) {
4034 global $wgNewPasswordExpiry;
4038 $passwordFactory = new PasswordFactory();
4039 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4040 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4041 ?
wfGetDB( DB_MASTER
)
4042 : wfGetDB( DB_SLAVE
);
4044 $row = $db->selectRow(
4046 array( 'user_newpassword', 'user_newpass_time' ),
4047 array( 'user_id' => $this->getId() ),
4051 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4052 } catch ( PasswordError
$e ) {
4053 wfDebug( 'Invalid password hash found in database.' );
4054 $newPassword = PasswordFactory
::newInvalidPassword();
4057 if ( $newPassword->equals( $plaintext ) ) {
4058 if ( is_null( $row->user_newpass_time
) ) {
4061 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4062 return ( time() < $expiry );
4069 * Internal implementation for self::getEditToken() and
4070 * self::matchEditToken().
4072 * @param string|array $salt
4073 * @param WebRequest $request
4074 * @param string|int $timestamp
4077 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
4078 if ( $this->isAnon() ) {
4079 return self
::EDIT_TOKEN_SUFFIX
;
4081 $token = $request->getSessionData( 'wsEditToken' );
4082 if ( $token === null ) {
4083 $token = MWCryptRand
::generateHex( 32 );
4084 $request->setSessionData( 'wsEditToken', $token );
4086 if ( is_array( $salt ) ) {
4087 $salt = implode( '|', $salt );
4089 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
4090 dechex( $timestamp ) .
4091 self
::EDIT_TOKEN_SUFFIX
;
4096 * Initialize (if necessary) and return a session token value
4097 * which can be used in edit forms to show that the user's
4098 * login credentials aren't being hijacked with a foreign form
4103 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4104 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4105 * @return string The new edit token
4107 public function getEditToken( $salt = '', $request = null ) {
4108 return $this->getEditTokenAtTimestamp(
4109 $salt, $request ?
: $this->getRequest(), wfTimestamp()
4114 * Get the embedded timestamp from a token.
4115 * @param string $val Input token
4118 public static function getEditTokenTimestamp( $val ) {
4119 $suffixLen = strlen( self
::EDIT_TOKEN_SUFFIX
);
4120 if ( strlen( $val ) <= 32 +
$suffixLen ) {
4124 return hexdec( substr( $val, 32, -$suffixLen ) );
4128 * Check given value against the token value stored in the session.
4129 * A match should confirm that the form was submitted from the
4130 * user's own login session, not a form submission from a third-party
4133 * @param string $val Input value to compare
4134 * @param string $salt Optional function-specific data for hashing
4135 * @param WebRequest|null $request Object to use or null to use $wgRequest
4136 * @param int $maxage Fail tokens older than this, in seconds
4137 * @return bool Whether the token matches
4139 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4140 if ( $this->isAnon() ) {
4141 return $val === self
::EDIT_TOKEN_SUFFIX
;
4144 $timestamp = self
::getEditTokenTimestamp( $val );
4145 if ( $timestamp === null ) {
4148 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
4153 $sessionToken = $this->getEditTokenAtTimestamp(
4154 $salt, $request ?
: $this->getRequest(), $timestamp
4157 if ( !hash_equals( $sessionToken, $val ) ) {
4158 wfDebug( "User::matchEditToken: broken session data\n" );
4161 return hash_equals( $sessionToken, $val );
4165 * Check given value against the token value stored in the session,
4166 * ignoring the suffix.
4168 * @param string $val Input value to compare
4169 * @param string $salt Optional function-specific data for hashing
4170 * @param WebRequest|null $request Object to use or null to use $wgRequest
4171 * @param int $maxage Fail tokens older than this, in seconds
4172 * @return bool Whether the token matches
4174 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4175 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4176 return $this->matchEditToken( $val, $salt, $request, $maxage );
4180 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4181 * mail to the user's given address.
4183 * @param string $type Message to send, either "created", "changed" or "set"
4186 public function sendConfirmationMail( $type = 'created' ) {
4188 $expiration = null; // gets passed-by-ref and defined in next line.
4189 $token = $this->confirmationToken( $expiration );
4190 $url = $this->confirmationTokenUrl( $token );
4191 $invalidateURL = $this->invalidationTokenUrl( $token );
4192 $this->saveSettings();
4194 if ( $type == 'created' ||
$type === false ) {
4195 $message = 'confirmemail_body';
4196 } elseif ( $type === true ) {
4197 $message = 'confirmemail_body_changed';
4199 // Messages: confirmemail_body_changed, confirmemail_body_set
4200 $message = 'confirmemail_body_' . $type;
4203 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4204 wfMessage( $message,
4205 $this->getRequest()->getIP(),
4208 $wgLang->userTimeAndDate( $expiration, $this ),
4210 $wgLang->userDate( $expiration, $this ),
4211 $wgLang->userTime( $expiration, $this ) )->text() );
4215 * Send an e-mail to this user's account. Does not check for
4216 * confirmed status or validity.
4218 * @param string $subject Message subject
4219 * @param string $body Message body
4220 * @param User|null $from Optional sending user; if unspecified, default
4221 * $wgPasswordSender will be used.
4222 * @param string $replyto Reply-To address
4225 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4226 global $wgPasswordSender;
4228 if ( $from instanceof User
) {
4229 $sender = MailAddress
::newFromUser( $from );
4231 $sender = new MailAddress( $wgPasswordSender,
4232 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4234 $to = MailAddress
::newFromUser( $this );
4236 return UserMailer
::send( $to, $sender, $subject, $body, array(
4237 'replyTo' => $replyto,
4242 * Generate, store, and return a new e-mail confirmation code.
4243 * A hash (unsalted, since it's used as a key) is stored.
4245 * @note Call saveSettings() after calling this function to commit
4246 * this change to the database.
4248 * @param string &$expiration Accepts the expiration time
4249 * @return string New token
4251 protected function confirmationToken( &$expiration ) {
4252 global $wgUserEmailConfirmationTokenExpiry;
4254 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4255 $expiration = wfTimestamp( TS_MW
, $expires );
4257 $token = MWCryptRand
::generateHex( 32 );
4258 $hash = md5( $token );
4259 $this->mEmailToken
= $hash;
4260 $this->mEmailTokenExpires
= $expiration;
4265 * Return a URL the user can use to confirm their email address.
4266 * @param string $token Accepts the email confirmation token
4267 * @return string New token URL
4269 protected function confirmationTokenUrl( $token ) {
4270 return $this->getTokenUrl( 'ConfirmEmail', $token );
4274 * Return a URL the user can use to invalidate their email address.
4275 * @param string $token Accepts the email confirmation token
4276 * @return string New token URL
4278 protected function invalidationTokenUrl( $token ) {
4279 return $this->getTokenUrl( 'InvalidateEmail', $token );
4283 * Internal function to format the e-mail validation/invalidation URLs.
4284 * This uses a quickie hack to use the
4285 * hardcoded English names of the Special: pages, for ASCII safety.
4287 * @note Since these URLs get dropped directly into emails, using the
4288 * short English names avoids insanely long URL-encoded links, which
4289 * also sometimes can get corrupted in some browsers/mailers
4290 * (bug 6957 with Gmail and Internet Explorer).
4292 * @param string $page Special page
4293 * @param string $token Token
4294 * @return string Formatted URL
4296 protected function getTokenUrl( $page, $token ) {
4297 // Hack to bypass localization of 'Special:'
4298 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4299 return $title->getCanonicalURL();
4303 * Mark the e-mail address confirmed.
4305 * @note Call saveSettings() after calling this function to commit the change.
4309 public function confirmEmail() {
4310 // Check if it's already confirmed, so we don't touch the database
4311 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4312 if ( !$this->isEmailConfirmed() ) {
4313 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4314 Hooks
::run( 'ConfirmEmailComplete', array( $this ) );
4320 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4321 * address if it was already confirmed.
4323 * @note Call saveSettings() after calling this function to commit the change.
4324 * @return bool Returns true
4326 public function invalidateEmail() {
4328 $this->mEmailToken
= null;
4329 $this->mEmailTokenExpires
= null;
4330 $this->setEmailAuthenticationTimestamp( null );
4332 Hooks
::run( 'InvalidateEmailComplete', array( $this ) );
4337 * Set the e-mail authentication timestamp.
4338 * @param string $timestamp TS_MW timestamp
4340 public function setEmailAuthenticationTimestamp( $timestamp ) {
4342 $this->mEmailAuthenticated
= $timestamp;
4343 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4347 * Is this user allowed to send e-mails within limits of current
4348 * site configuration?
4351 public function canSendEmail() {
4352 global $wgEnableEmail, $wgEnableUserEmail;
4353 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4356 $canSend = $this->isEmailConfirmed();
4357 Hooks
::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4362 * Is this user allowed to receive e-mails within limits of current
4363 * site configuration?
4366 public function canReceiveEmail() {
4367 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4371 * Is this user's e-mail address valid-looking and confirmed within
4372 * limits of the current site configuration?
4374 * @note If $wgEmailAuthentication is on, this may require the user to have
4375 * confirmed their address by returning a code or using a password
4376 * sent to the address from the wiki.
4380 public function isEmailConfirmed() {
4381 global $wgEmailAuthentication;
4384 if ( Hooks
::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4385 if ( $this->isAnon() ) {
4388 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4391 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4401 * Check whether there is an outstanding request for e-mail confirmation.
4404 public function isEmailConfirmationPending() {
4405 global $wgEmailAuthentication;
4406 return $wgEmailAuthentication &&
4407 !$this->isEmailConfirmed() &&
4408 $this->mEmailToken
&&
4409 $this->mEmailTokenExpires
> wfTimestamp();
4413 * Get the timestamp of account creation.
4415 * @return string|bool|null Timestamp of account creation, false for
4416 * non-existent/anonymous user accounts, or null if existing account
4417 * but information is not in database.
4419 public function getRegistration() {
4420 if ( $this->isAnon() ) {
4424 return $this->mRegistration
;
4428 * Get the timestamp of the first edit
4430 * @return string|bool Timestamp of first edit, or false for
4431 * non-existent/anonymous user accounts.
4433 public function getFirstEditTimestamp() {
4434 if ( $this->getId() == 0 ) {
4435 return false; // anons
4437 $dbr = wfGetDB( DB_SLAVE
);
4438 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4439 array( 'rev_user' => $this->getId() ),
4441 array( 'ORDER BY' => 'rev_timestamp ASC' )
4444 return false; // no edits
4446 return wfTimestamp( TS_MW
, $time );
4450 * Get the permissions associated with a given list of groups
4452 * @param array $groups Array of Strings List of internal group names
4453 * @return array Array of Strings List of permission key names for given groups combined
4455 public static function getGroupPermissions( $groups ) {
4456 global $wgGroupPermissions, $wgRevokePermissions;
4458 // grant every granted permission first
4459 foreach ( $groups as $group ) {
4460 if ( isset( $wgGroupPermissions[$group] ) ) {
4461 $rights = array_merge( $rights,
4462 // array_filter removes empty items
4463 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4466 // now revoke the revoked permissions
4467 foreach ( $groups as $group ) {
4468 if ( isset( $wgRevokePermissions[$group] ) ) {
4469 $rights = array_diff( $rights,
4470 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4473 return array_unique( $rights );
4477 * Get all the groups who have a given permission
4479 * @param string $role Role to check
4480 * @return array Array of Strings List of internal group names with the given permission
4482 public static function getGroupsWithPermission( $role ) {
4483 global $wgGroupPermissions;
4484 $allowedGroups = array();
4485 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4486 if ( self
::groupHasPermission( $group, $role ) ) {
4487 $allowedGroups[] = $group;
4490 return $allowedGroups;
4494 * Check, if the given group has the given permission
4496 * If you're wanting to check whether all users have a permission, use
4497 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4501 * @param string $group Group to check
4502 * @param string $role Role to check
4505 public static function groupHasPermission( $group, $role ) {
4506 global $wgGroupPermissions, $wgRevokePermissions;
4507 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4508 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4512 * Check if all users may be assumed to have the given permission
4514 * We generally assume so if the right is granted to '*' and isn't revoked
4515 * on any group. It doesn't attempt to take grants or other extension
4516 * limitations on rights into account in the general case, though, as that
4517 * would require it to always return false and defeat the purpose.
4518 * Specifically, session-based rights restrictions (such as OAuth or bot
4519 * passwords) are applied based on the current session.
4522 * @param string $right Right to check
4525 public static function isEveryoneAllowed( $right ) {
4526 global $wgGroupPermissions, $wgRevokePermissions;
4527 static $cache = array();
4529 // Use the cached results, except in unit tests which rely on
4530 // being able change the permission mid-request
4531 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4532 return $cache[$right];
4535 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4536 $cache[$right] = false;
4540 // If it's revoked anywhere, then everyone doesn't have it
4541 foreach ( $wgRevokePermissions as $rights ) {
4542 if ( isset( $rights[$right] ) && $rights[$right] ) {
4543 $cache[$right] = false;
4548 // Remove any rights that aren't allowed to the global-session user
4549 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4550 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4551 $cache[$right] = false;
4555 // Allow extensions to say false
4556 if ( !Hooks
::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4557 $cache[$right] = false;
4561 $cache[$right] = true;
4566 * Get the localized descriptive name for a group, if it exists
4568 * @param string $group Internal group name
4569 * @return string Localized descriptive group name
4571 public static function getGroupName( $group ) {
4572 $msg = wfMessage( "group-$group" );
4573 return $msg->isBlank() ?
$group : $msg->text();
4577 * Get the localized descriptive name for a member of a group, if it exists
4579 * @param string $group Internal group name
4580 * @param string $username Username for gender (since 1.19)
4581 * @return string Localized name for group member
4583 public static function getGroupMember( $group, $username = '#' ) {
4584 $msg = wfMessage( "group-$group-member", $username );
4585 return $msg->isBlank() ?
$group : $msg->text();
4589 * Return the set of defined explicit groups.
4590 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4591 * are not included, as they are defined automatically, not in the database.
4592 * @return array Array of internal group names
4594 public static function getAllGroups() {
4595 global $wgGroupPermissions, $wgRevokePermissions;
4597 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4598 self
::getImplicitGroups()
4603 * Get a list of all available permissions.
4604 * @return string[] Array of permission names
4606 public static function getAllRights() {
4607 if ( self
::$mAllRights === false ) {
4608 global $wgAvailableRights;
4609 if ( count( $wgAvailableRights ) ) {
4610 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4612 self
::$mAllRights = self
::$mCoreRights;
4614 Hooks
::run( 'UserGetAllRights', array( &self
::$mAllRights ) );
4616 return self
::$mAllRights;
4620 * Get a list of implicit groups
4621 * @return array Array of Strings Array of internal group names
4623 public static function getImplicitGroups() {
4624 global $wgImplicitGroups;
4626 $groups = $wgImplicitGroups;
4627 # Deprecated, use $wgImplicitGroups instead
4628 Hooks
::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4634 * Get the title of a page describing a particular group
4636 * @param string $group Internal group name
4637 * @return Title|bool Title of the page if it exists, false otherwise
4639 public static function getGroupPage( $group ) {
4640 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4641 if ( $msg->exists() ) {
4642 $title = Title
::newFromText( $msg->text() );
4643 if ( is_object( $title ) ) {
4651 * Create a link to the group in HTML, if available;
4652 * else return the group name.
4654 * @param string $group Internal name of the group
4655 * @param string $text The text of the link
4656 * @return string HTML link to the group
4658 public static function makeGroupLinkHTML( $group, $text = '' ) {
4659 if ( $text == '' ) {
4660 $text = self
::getGroupName( $group );
4662 $title = self
::getGroupPage( $group );
4664 return Linker
::link( $title, htmlspecialchars( $text ) );
4666 return htmlspecialchars( $text );
4671 * Create a link to the group in Wikitext, if available;
4672 * else return the group name.
4674 * @param string $group Internal name of the group
4675 * @param string $text The text of the link
4676 * @return string Wikilink to the group
4678 public static function makeGroupLinkWiki( $group, $text = '' ) {
4679 if ( $text == '' ) {
4680 $text = self
::getGroupName( $group );
4682 $title = self
::getGroupPage( $group );
4684 $page = $title->getFullText();
4685 return "[[$page|$text]]";
4692 * Returns an array of the groups that a particular group can add/remove.
4694 * @param string $group The group to check for whether it can add/remove
4695 * @return array Array( 'add' => array( addablegroups ),
4696 * 'remove' => array( removablegroups ),
4697 * 'add-self' => array( addablegroups to self),
4698 * 'remove-self' => array( removable groups from self) )
4700 public static function changeableByGroup( $group ) {
4701 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4705 'remove' => array(),
4706 'add-self' => array(),
4707 'remove-self' => array()
4710 if ( empty( $wgAddGroups[$group] ) ) {
4711 // Don't add anything to $groups
4712 } elseif ( $wgAddGroups[$group] === true ) {
4713 // You get everything
4714 $groups['add'] = self
::getAllGroups();
4715 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4716 $groups['add'] = $wgAddGroups[$group];
4719 // Same thing for remove
4720 if ( empty( $wgRemoveGroups[$group] ) ) {
4722 } elseif ( $wgRemoveGroups[$group] === true ) {
4723 $groups['remove'] = self
::getAllGroups();
4724 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4725 $groups['remove'] = $wgRemoveGroups[$group];
4728 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4729 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4730 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4731 if ( is_int( $key ) ) {
4732 $wgGroupsAddToSelf['user'][] = $value;
4737 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4738 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4739 if ( is_int( $key ) ) {
4740 $wgGroupsRemoveFromSelf['user'][] = $value;
4745 // Now figure out what groups the user can add to him/herself
4746 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4748 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4749 // No idea WHY this would be used, but it's there
4750 $groups['add-self'] = User
::getAllGroups();
4751 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4752 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4755 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4757 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4758 $groups['remove-self'] = User
::getAllGroups();
4759 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4760 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4767 * Returns an array of groups that this user can add and remove
4768 * @return array Array( 'add' => array( addablegroups ),
4769 * 'remove' => array( removablegroups ),
4770 * 'add-self' => array( addablegroups to self),
4771 * 'remove-self' => array( removable groups from self) )
4773 public function changeableGroups() {
4774 if ( $this->isAllowed( 'userrights' ) ) {
4775 // This group gives the right to modify everything (reverse-
4776 // compatibility with old "userrights lets you change
4778 // Using array_merge to make the groups reindexed
4779 $all = array_merge( User
::getAllGroups() );
4783 'add-self' => array(),
4784 'remove-self' => array()
4788 // Okay, it's not so simple, we will have to go through the arrays
4791 'remove' => array(),
4792 'add-self' => array(),
4793 'remove-self' => array()
4795 $addergroups = $this->getEffectiveGroups();
4797 foreach ( $addergroups as $addergroup ) {
4798 $groups = array_merge_recursive(
4799 $groups, $this->changeableByGroup( $addergroup )
4801 $groups['add'] = array_unique( $groups['add'] );
4802 $groups['remove'] = array_unique( $groups['remove'] );
4803 $groups['add-self'] = array_unique( $groups['add-self'] );
4804 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4810 * Deferred version of incEditCountImmediate()
4812 public function incEditCount() {
4814 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $that ) {
4815 $that->incEditCountImmediate();
4820 * Increment the user's edit-count field.
4821 * Will have no effect for anonymous users.
4824 public function incEditCountImmediate() {
4825 if ( $this->isAnon() ) {
4829 $dbw = wfGetDB( DB_MASTER
);
4830 // No rows will be "affected" if user_editcount is NULL
4833 array( 'user_editcount=user_editcount+1' ),
4834 array( 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ),
4837 // Lazy initialization check...
4838 if ( $dbw->affectedRows() == 0 ) {
4839 // Now here's a goddamn hack...
4840 $dbr = wfGetDB( DB_SLAVE
);
4841 if ( $dbr !== $dbw ) {
4842 // If we actually have a slave server, the count is
4843 // at least one behind because the current transaction
4844 // has not been committed and replicated.
4845 $this->initEditCount( 1 );
4847 // But if DB_SLAVE is selecting the master, then the
4848 // count we just read includes the revision that was
4849 // just added in the working transaction.
4850 $this->initEditCount();
4853 // Edit count in user cache too
4854 $this->invalidateCache();
4858 * Initialize user_editcount from data out of the revision table
4860 * @param int $add Edits to add to the count from the revision table
4861 * @return int Number of edits
4863 protected function initEditCount( $add = 0 ) {
4864 // Pull from a slave to be less cruel to servers
4865 // Accuracy isn't the point anyway here
4866 $dbr = wfGetDB( DB_SLAVE
);
4867 $count = (int)$dbr->selectField(
4870 array( 'rev_user' => $this->getId() ),
4873 $count = $count +
$add;
4875 $dbw = wfGetDB( DB_MASTER
);
4878 array( 'user_editcount' => $count ),
4879 array( 'user_id' => $this->getId() ),
4887 * Get the description of a given right
4889 * @param string $right Right to query
4890 * @return string Localized description of the right
4892 public static function getRightDescription( $right ) {
4893 $key = "right-$right";
4894 $msg = wfMessage( $key );
4895 return $msg->isBlank() ?
$right : $msg->text();
4899 * Make a new-style password hash
4901 * @param string $password Plain-text password
4902 * @param bool|string $salt Optional salt, may be random or the user ID.
4903 * If unspecified or false, will generate one automatically
4904 * @return string Password hash
4905 * @deprecated since 1.24, use Password class
4907 public static function crypt( $password, $salt = false ) {
4908 wfDeprecated( __METHOD__
, '1.24' );
4909 $passwordFactory = new PasswordFactory();
4910 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4911 $hash = $passwordFactory->newFromPlaintext( $password );
4912 return $hash->toString();
4916 * Compare a password hash with a plain-text password. Requires the user
4917 * ID if there's a chance that the hash is an old-style hash.
4919 * @param string $hash Password hash
4920 * @param string $password Plain-text password to compare
4921 * @param string|bool $userId User ID for old-style password salt
4924 * @deprecated since 1.24, use Password class
4926 public static function comparePasswords( $hash, $password, $userId = false ) {
4927 wfDeprecated( __METHOD__
, '1.24' );
4929 // Check for *really* old password hashes that don't even have a type
4930 // The old hash format was just an md5 hex hash, with no type information
4931 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4932 global $wgPasswordSalt;
4933 if ( $wgPasswordSalt ) {
4934 $password = ":B:{$userId}:{$hash}";
4936 $password = ":A:{$hash}";
4940 $passwordFactory = new PasswordFactory();
4941 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4942 $hash = $passwordFactory->newFromCiphertext( $hash );
4943 return $hash->equals( $password );
4947 * Add a newuser log entry for this user.
4948 * Before 1.19 the return value was always true.
4950 * @param string|bool $action Account creation type.
4951 * - String, one of the following values:
4952 * - 'create' for an anonymous user creating an account for himself.
4953 * This will force the action's performer to be the created user itself,
4954 * no matter the value of $wgUser
4955 * - 'create2' for a logged in user creating an account for someone else
4956 * - 'byemail' when the created user will receive its password by e-mail
4957 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4958 * - Boolean means whether the account was created by e-mail (deprecated):
4959 * - true will be converted to 'byemail'
4960 * - false will be converted to 'create' if this object is the same as
4961 * $wgUser and to 'create2' otherwise
4963 * @param string $reason User supplied reason
4965 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4967 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4968 global $wgUser, $wgNewUserLog;
4969 if ( empty( $wgNewUserLog ) ) {
4970 return true; // disabled
4973 if ( $action === true ) {
4974 $action = 'byemail';
4975 } elseif ( $action === false ) {
4976 if ( $this->equals( $wgUser ) ) {
4979 $action = 'create2';
4983 if ( $action === 'create' ||
$action === 'autocreate' ) {
4986 $performer = $wgUser;
4989 $logEntry = new ManualLogEntry( 'newusers', $action );
4990 $logEntry->setPerformer( $performer );
4991 $logEntry->setTarget( $this->getUserPage() );
4992 $logEntry->setComment( $reason );
4993 $logEntry->setParameters( array(
4994 '4::userid' => $this->getId(),
4996 $logid = $logEntry->insert();
4998 if ( $action !== 'autocreate' ) {
4999 $logEntry->publish( $logid );
5006 * Add an autocreate newuser log entry for this user
5007 * Used by things like CentralAuth and perhaps other authplugins.
5008 * Consider calling addNewUserLogEntry() directly instead.
5012 public function addNewUserLogEntryAutoCreate() {
5013 $this->addNewUserLogEntry( 'autocreate' );
5019 * Load the user options either from cache, the database or an array
5021 * @param array $data Rows for the current user out of the user_properties table
5023 protected function loadOptions( $data = null ) {
5028 if ( $this->mOptionsLoaded
) {
5032 $this->mOptions
= self
::getDefaultOptions();
5034 if ( !$this->getId() ) {
5035 // For unlogged-in users, load language/variant options from request.
5036 // There's no need to do it for logged-in users: they can set preferences,
5037 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5038 // so don't override user's choice (especially when the user chooses site default).
5039 $variant = $wgContLang->getDefaultVariant();
5040 $this->mOptions
['variant'] = $variant;
5041 $this->mOptions
['language'] = $variant;
5042 $this->mOptionsLoaded
= true;
5046 // Maybe load from the object
5047 if ( !is_null( $this->mOptionOverrides
) ) {
5048 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5049 foreach ( $this->mOptionOverrides
as $key => $value ) {
5050 $this->mOptions
[$key] = $value;
5053 if ( !is_array( $data ) ) {
5054 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5055 // Load from database
5056 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5057 ?
wfGetDB( DB_MASTER
)
5058 : wfGetDB( DB_SLAVE
);
5060 $res = $dbr->select(
5062 array( 'up_property', 'up_value' ),
5063 array( 'up_user' => $this->getId() ),
5067 $this->mOptionOverrides
= array();
5069 foreach ( $res as $row ) {
5070 $data[$row->up_property
] = $row->up_value
;
5073 foreach ( $data as $property => $value ) {
5074 $this->mOptionOverrides
[$property] = $value;
5075 $this->mOptions
[$property] = $value;
5079 $this->mOptionsLoaded
= true;
5081 Hooks
::run( 'UserLoadOptions', array( $this, &$this->mOptions
) );
5085 * Saves the non-default options for this user, as previously set e.g. via
5086 * setOption(), in the database's "user_properties" (preferences) table.
5087 * Usually used via saveSettings().
5089 protected function saveOptions() {
5090 $this->loadOptions();
5092 // Not using getOptions(), to keep hidden preferences in database
5093 $saveOptions = $this->mOptions
;
5095 // Allow hooks to abort, for instance to save to a global profile.
5096 // Reset options to default state before saving.
5097 if ( !Hooks
::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5101 $userId = $this->getId();
5103 $insert_rows = array(); // all the new preference rows
5104 foreach ( $saveOptions as $key => $value ) {
5105 // Don't bother storing default values
5106 $defaultOption = self
::getDefaultOption( $key );
5107 if ( ( $defaultOption === null && $value !== false && $value !== null )
5108 ||
$value != $defaultOption
5110 $insert_rows[] = array(
5111 'up_user' => $userId,
5112 'up_property' => $key,
5113 'up_value' => $value,
5118 $dbw = wfGetDB( DB_MASTER
);
5120 $res = $dbw->select( 'user_properties',
5121 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
5123 // Find prior rows that need to be removed or updated. These rows will
5124 // all be deleted (the later so that INSERT IGNORE applies the new values).
5125 $keysDelete = array();
5126 foreach ( $res as $row ) {
5127 if ( !isset( $saveOptions[$row->up_property
] )
5128 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5130 $keysDelete[] = $row->up_property
;
5134 if ( count( $keysDelete ) ) {
5135 // Do the DELETE by PRIMARY KEY for prior rows.
5136 // In the past a very large portion of calls to this function are for setting
5137 // 'rememberpassword' for new accounts (a preference that has since been removed).
5138 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5139 // caused gap locks on [max user ID,+infinity) which caused high contention since
5140 // updates would pile up on each other as they are for higher (newer) user IDs.
5141 // It might not be necessary these days, but it shouldn't hurt either.
5142 $dbw->delete( 'user_properties',
5143 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
5145 // Insert the new preference rows
5146 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
5150 * Lazily instantiate and return a factory object for making passwords
5152 * @deprecated since 1.27, create a PasswordFactory directly instead
5153 * @return PasswordFactory
5155 public static function getPasswordFactory() {
5156 wfDeprecated( __METHOD__
, '1.27' );
5157 $ret = new PasswordFactory();
5158 $ret->init( RequestContext
::getMain()->getConfig() );
5163 * Provide an array of HTML5 attributes to put on an input element
5164 * intended for the user to enter a new password. This may include
5165 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5167 * Do *not* use this when asking the user to enter his current password!
5168 * Regardless of configuration, users may have invalid passwords for whatever
5169 * reason (e.g., they were set before requirements were tightened up).
5170 * Only use it when asking for a new password, like on account creation or
5173 * Obviously, you still need to do server-side checking.
5175 * NOTE: A combination of bugs in various browsers means that this function
5176 * actually just returns array() unconditionally at the moment. May as
5177 * well keep it around for when the browser bugs get fixed, though.
5179 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5181 * @deprecated since 1.27
5182 * @return array Array of HTML attributes suitable for feeding to
5183 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5184 * That will get confused by the boolean attribute syntax used.)
5186 public static function passwordChangeInputAttribs() {
5187 global $wgMinimalPasswordLength;
5189 if ( $wgMinimalPasswordLength == 0 ) {
5193 # Note that the pattern requirement will always be satisfied if the
5194 # input is empty, so we need required in all cases.
5196 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5197 # if e-mail confirmation is being used. Since HTML5 input validation
5198 # is b0rked anyway in some browsers, just return nothing. When it's
5199 # re-enabled, fix this code to not output required for e-mail
5201 # $ret = array( 'required' );
5204 # We can't actually do this right now, because Opera 9.6 will print out
5205 # the entered password visibly in its error message! When other
5206 # browsers add support for this attribute, or Opera fixes its support,
5207 # we can add support with a version check to avoid doing this on Opera
5208 # versions where it will be a problem. Reported to Opera as
5209 # DSK-262266, but they don't have a public bug tracker for us to follow.
5211 if ( $wgMinimalPasswordLength > 1 ) {
5212 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5213 $ret['title'] = wfMessage( 'passwordtooshort' )
5214 ->numParams( $wgMinimalPasswordLength )->text();
5222 * Return the list of user fields that should be selected to create
5223 * a new user object.
5226 public static function selectFields() {
5234 'user_email_authenticated',
5236 'user_email_token_expires',
5237 'user_registration',
5243 * Factory function for fatal permission-denied errors
5246 * @param string $permission User right required
5249 static function newFatalPermissionDeniedStatus( $permission ) {
5252 $groups = array_map(
5253 array( 'User', 'makeGroupLinkWiki' ),
5254 User
::getGroupsWithPermission( $permission )
5258 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5260 return Status
::newFatal( 'badaccess-group0' );
5265 * Get a new instance of this user that was loaded from the master via a locking read
5267 * Use this instead of the main context User when updating that user. This avoids races
5268 * where that user was loaded from a slave or even the master but without proper locks.
5270 * @return User|null Returns null if the user was not found in the DB
5273 public function getInstanceForUpdate() {
5274 if ( !$this->getId() ) {
5275 return null; // anon
5278 $user = self
::newFromId( $this->getId() );
5279 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5287 * Checks if two user objects point to the same user.
5293 public function equals( User
$user ) {
5294 return $this->getName() === $user->getName();