3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Session\SessionManager
;
26 * String Some punctuation to prevent editing from broken text-mangling proxies.
27 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::SUFFIX
30 define( 'EDIT_TOKEN_SUFFIX', MediaWiki\Session\Token
::SUFFIX
);
33 * The User object encapsulates all of the user-specific settings (user_id,
34 * name, rights, email address, options, last login time). Client
35 * classes use the getXXX() functions to access these fields. These functions
36 * do all the work of determining whether the user is logged in,
37 * whether the requested option can be satisfied from cookies or
38 * whether a database query is needed. Most of the settings needed
39 * for rendering normal pages are set in the cookie to minimize use
42 class User
implements IDBAccessObject
{
44 * @const int Number of characters in user_token field.
46 const TOKEN_LENGTH
= 32;
49 * Global constant made accessible as class constants so that autoloader
51 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::SUFFIX
53 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
56 * @const int Serialized record version.
61 * Maximum items in $mWatchedItems
63 const MAX_WATCHED_ITEMS_CACHE
= 100;
66 * Exclude user options that are set to their default value.
69 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
72 * Array of Strings List of member variables which are saved to the
73 * shared cache (memcached). Any operation which changes the
74 * corresponding database fields must call a cache-clearing function.
77 protected static $mCacheVars = array(
85 'mEmailAuthenticated',
92 // user_properties table
97 * Array of Strings Core rights.
98 * Each of these should have a corresponding message of the form
102 protected static $mCoreRights = array(
132 'editusercssjs', # deprecated
145 'move-categorypages',
146 'move-rootuserpages',
150 'override-export-depth',
173 'userrights-interwiki',
181 * String Cached results of getAllRights()
183 protected static $mAllRights = false;
185 /** Cache variables */
195 /** @var string TS_MW timestamp from the DB */
197 /** @var string TS_MW timestamp from cache */
198 protected $mQuickTouched;
202 public $mEmailAuthenticated;
204 protected $mEmailToken;
206 protected $mEmailTokenExpires;
208 protected $mRegistration;
210 protected $mEditCount;
214 protected $mOptionOverrides;
218 * Bool Whether the cache variables have been loaded.
221 public $mOptionsLoaded;
224 * Array with already loaded items or true if all items have been loaded.
226 protected $mLoadedItems = array();
230 * String Initialization data source if mLoadedItems!==true. May be one of:
231 * - 'defaults' anonymous user initialised from class defaults
232 * - 'name' initialise from mName
233 * - 'id' initialise from mId
234 * - 'session' log in from session if possible
236 * Use the User::newFrom*() family of functions to set this.
241 * Lazy-initialized variables, invalidated with clearInstanceCache
245 protected $mDatePreference;
253 protected $mBlockreason;
255 protected $mEffectiveGroups;
257 protected $mImplicitGroups;
259 protected $mFormerGroups;
261 protected $mBlockedGlobally;
278 protected $mAllowUsertalk;
281 private $mBlockedFromCreateAccount = false;
284 private $mWatchedItems = array();
286 /** @var integer User::READ_* constant bitfield used to load data */
287 protected $queryFlagsUsed = self
::READ_NORMAL
;
289 public static $idCacheByName = array();
292 * Lightweight constructor for an anonymous user.
293 * Use the User::newFrom* factory functions for other kinds of users.
297 * @see newFromConfirmationCode()
298 * @see newFromSession()
301 public function __construct() {
302 $this->clearInstanceCache( 'defaults' );
308 public function __toString() {
309 return $this->getName();
313 * Test if it's safe to load this User object
316 public function isSafeToLoad() {
317 global $wgFullyInitialised;
318 return $wgFullyInitialised ||
$this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
322 * Load the user table data for this object from the source given by mFrom.
324 * @param integer $flags User::READ_* constant bitfield
326 public function load( $flags = self
::READ_NORMAL
) {
327 global $wgFullyInitialised;
329 if ( $this->mLoadedItems
=== true ) {
333 // Set it now to avoid infinite recursion in accessors
334 $oldLoadedItems = $this->mLoadedItems
;
335 $this->mLoadedItems
= true;
336 $this->queryFlagsUsed
= $flags;
338 // If this is called too early, things are likely to break.
339 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
340 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
341 ->warning( 'User::loadFromSession called before the end of Setup.php', array(
342 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
344 $this->loadDefaults();
345 $this->mLoadedItems
= $oldLoadedItems;
349 switch ( $this->mFrom
) {
351 $this->loadDefaults();
354 // Make sure this thread sees its own changes
355 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
356 $flags |
= self
::READ_LATEST
;
357 $this->queryFlagsUsed
= $flags;
360 $this->mId
= self
::idFromName( $this->mName
, $flags );
362 // Nonexistent user placeholder object
363 $this->loadDefaults( $this->mName
);
365 $this->loadFromId( $flags );
369 $this->loadFromId( $flags );
372 if ( !$this->loadFromSession() ) {
373 // Loading from session failed. Load defaults.
374 $this->loadDefaults();
376 Hooks
::run( 'UserLoadAfterLoadFromSession', array( $this ) );
379 throw new UnexpectedValueException(
380 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
385 * Load user table data, given mId has already been set.
386 * @param integer $flags User::READ_* constant bitfield
387 * @return bool False if the ID does not exist, true otherwise
389 public function loadFromId( $flags = self
::READ_NORMAL
) {
390 if ( $this->mId
== 0 ) {
391 $this->loadDefaults();
395 // Try cache (unless this needs data from the master DB).
396 // NOTE: if this thread called saveSettings(), the cache was cleared.
397 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
398 if ( $latest ||
!$this->loadFromCache() ) {
399 wfDebug( "User: cache miss for user {$this->mId}\n" );
400 // Load from DB (make sure this thread sees its own changes)
401 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
402 $flags |
= self
::READ_LATEST
;
404 if ( !$this->loadFromDatabase( $flags ) ) {
405 // Can't load from ID, user is anonymous
408 $this->saveToCache();
411 $this->mLoadedItems
= true;
412 $this->queryFlagsUsed
= $flags;
419 * @param string $wikiId
420 * @param integer $userId
422 public static function purge( $wikiId, $userId ) {
423 $cache = ObjectCache
::getMainWANInstance();
424 $cache->delete( $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId ) );
429 * @param WANObjectCache $cache
432 protected function getCacheKey( WANObjectCache
$cache ) {
433 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
437 * Load user data from shared cache, given mId has already been set.
439 * @return bool false if the ID does not exist or data is invalid, true otherwise
442 protected function loadFromCache() {
443 if ( $this->mId
== 0 ) {
444 $this->loadDefaults();
448 $cache = ObjectCache
::getMainWANInstance();
449 $data = $cache->get( $this->getCacheKey( $cache ) );
450 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
455 wfDebug( "User: got user {$this->mId} from cache\n" );
457 // Restore from cache
458 foreach ( self
::$mCacheVars as $name ) {
459 $this->$name = $data[$name];
466 * Save user data to the shared cache
468 * This method should not be called outside the User class
470 public function saveToCache() {
473 $this->loadOptions();
475 if ( $this->isAnon() ) {
476 // Anonymous users are uncached
481 foreach ( self
::$mCacheVars as $name ) {
482 $data[$name] = $this->$name;
484 $data['mVersion'] = self
::VERSION
;
485 $opts = Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
487 $cache = ObjectCache
::getMainWANInstance();
488 $key = $this->getCacheKey( $cache );
489 $cache->set( $key, $data, $cache::TTL_HOUR
, $opts );
492 /** @name newFrom*() static factory methods */
496 * Static factory method for creation from username.
498 * This is slightly less efficient than newFromId(), so use newFromId() if
499 * you have both an ID and a name handy.
501 * @param string $name Username, validated by Title::newFromText()
502 * @param string|bool $validate Validate username. Takes the same parameters as
503 * User::getCanonicalName(), except that true is accepted as an alias
504 * for 'valid', for BC.
506 * @return User|bool User object, or false if the username is invalid
507 * (e.g. if it contains illegal characters or is an IP address). If the
508 * username is not present in the database, the result will be a user object
509 * with a name, zero user ID and default settings.
511 public static function newFromName( $name, $validate = 'valid' ) {
512 if ( $validate === true ) {
515 $name = self
::getCanonicalName( $name, $validate );
516 if ( $name === false ) {
519 // Create unloaded user object
523 $u->setItemLoaded( 'name' );
529 * Static factory method for creation from a given user ID.
531 * @param int $id Valid user ID
532 * @return User The corresponding User object
534 public static function newFromId( $id ) {
538 $u->setItemLoaded( 'id' );
543 * Factory method to fetch whichever user has a given email confirmation code.
544 * This code is generated when an account is created or its e-mail address
547 * If the code is invalid or has expired, returns NULL.
549 * @param string $code Confirmation code
550 * @param int $flags User::READ_* bitfield
553 public static function newFromConfirmationCode( $code, $flags = 0 ) {
554 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
555 ?
wfGetDB( DB_MASTER
)
556 : wfGetDB( DB_SLAVE
);
558 $id = $db->selectField(
562 'user_email_token' => md5( $code ),
563 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
567 return $id ? User
::newFromId( $id ) : null;
571 * Create a new user object using data from session. If the login
572 * credentials are invalid, the result is an anonymous user.
574 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
577 public static function newFromSession( WebRequest
$request = null ) {
579 $user->mFrom
= 'session';
580 $user->mRequest
= $request;
585 * Create a new user object from a user row.
586 * The row should have the following fields from the user table in it:
587 * - either user_name or user_id to load further data if needed (or both)
589 * - all other fields (email, etc.)
590 * It is useless to provide the remaining fields if either user_id,
591 * user_name and user_real_name are not provided because the whole row
592 * will be loaded once more from the database when accessing them.
594 * @param stdClass $row A row from the user table
595 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
598 public static function newFromRow( $row, $data = null ) {
600 $user->loadFromRow( $row, $data );
605 * Static factory method for creation of a "system" user from username.
607 * A "system" user is an account that's used to attribute logged actions
608 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
609 * might include the 'Maintenance script' or 'Conversion script' accounts
610 * used by various scripts in the maintenance/ directory or accounts such
611 * as 'MediaWiki message delivery' used by the MassMessage extension.
613 * This can optionally create the user if it doesn't exist, and "steal" the
614 * account if it does exist.
616 * @param string $name Username
617 * @param array $options Options are:
618 * - validate: As for User::getCanonicalName(), default 'valid'
619 * - create: Whether to create the user if it doesn't already exist, default true
620 * - steal: Whether to reset the account's password and email if it
621 * already exists, default false
624 public static function newSystemUser( $name, $options = array() ) {
626 'validate' => 'valid',
631 $name = self
::getCanonicalName( $name, $options['validate'] );
632 if ( $name === false ) {
636 $dbw = wfGetDB( DB_MASTER
);
637 $row = $dbw->selectRow(
640 self
::selectFields(),
641 array( 'user_password', 'user_newpassword' )
643 array( 'user_name' => $name ),
647 // No user. Create it?
648 return $options['create'] ? self
::createNew( $name ) : null;
650 $user = self
::newFromRow( $row );
652 // A user is considered to exist as a non-system user if it has a
653 // password set, or a temporary password set, or an email set.
654 $passwordFactory = new PasswordFactory();
655 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
657 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
658 } catch ( PasswordError
$e ) {
659 wfDebug( 'Invalid password hash found in database.' );
660 $password = PasswordFactory
::newInvalidPassword();
663 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
664 } catch ( PasswordError
$e ) {
665 wfDebug( 'Invalid password hash found in database.' );
666 $newpassword = PasswordFactory
::newInvalidPassword();
668 if ( !$password instanceof InvalidPassword ||
!$newpassword instanceof InvalidPassword
671 // User exists. Steal it?
672 if ( !$options['steal'] ) {
676 $nopass = PasswordFactory
::newInvalidPassword()->toString();
681 'user_password' => $nopass,
682 'user_newpassword' => $nopass,
683 'user_newpass_time' => null,
685 array( 'user_id' => $user->getId() ),
688 $user->invalidateEmail();
689 $user->saveSettings();
692 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
700 * Get the username corresponding to a given user ID
701 * @param int $id User ID
702 * @return string|bool The corresponding username
704 public static function whoIs( $id ) {
705 return UserCache
::singleton()->getProp( $id, 'name' );
709 * Get the real name of a user given their user ID
711 * @param int $id User ID
712 * @return string|bool The corresponding user's real name
714 public static function whoIsReal( $id ) {
715 return UserCache
::singleton()->getProp( $id, 'real_name' );
719 * Get database id given a user name
720 * @param string $name Username
721 * @param integer $flags User::READ_* constant bitfield
722 * @return int|null The corresponding user's ID, or null if user is nonexistent
724 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
725 $nt = Title
::makeTitleSafe( NS_USER
, $name );
726 if ( is_null( $nt ) ) {
731 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
732 return self
::$idCacheByName[$name];
735 $db = ( $flags & self
::READ_LATEST
)
736 ?
wfGetDB( DB_MASTER
)
737 : wfGetDB( DB_SLAVE
);
742 array( 'user_name' => $nt->getText() ),
746 if ( $s === false ) {
749 $result = $s->user_id
;
752 self
::$idCacheByName[$name] = $result;
754 if ( count( self
::$idCacheByName ) > 1000 ) {
755 self
::$idCacheByName = array();
762 * Reset the cache used in idFromName(). For use in tests.
764 public static function resetIdByNameCache() {
765 self
::$idCacheByName = array();
769 * Does the string match an anonymous IPv4 address?
771 * This function exists for username validation, in order to reject
772 * usernames which are similar in form to IP addresses. Strings such
773 * as 300.300.300.300 will return true because it looks like an IP
774 * address, despite not being strictly valid.
776 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
777 * address because the usemod software would "cloak" anonymous IP
778 * addresses like this, if we allowed accounts like this to be created
779 * new users could get the old edits of these anonymous users.
781 * @param string $name Name to match
784 public static function isIP( $name ) {
785 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
786 || IP
::isIPv6( $name );
790 * Is the input a valid username?
792 * Checks if the input is a valid username, we don't want an empty string,
793 * an IP address, anything that contains slashes (would mess up subpages),
794 * is longer than the maximum allowed username size or doesn't begin with
797 * @param string $name Name to match
800 public static function isValidUserName( $name ) {
801 global $wgContLang, $wgMaxNameChars;
804 || User
::isIP( $name )
805 ||
strpos( $name, '/' ) !== false
806 ||
strlen( $name ) > $wgMaxNameChars
807 ||
$name != $wgContLang->ucfirst( $name )
809 wfDebugLog( 'username', __METHOD__
.
810 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
814 // Ensure that the name can't be misresolved as a different title,
815 // such as with extra namespace keys at the start.
816 $parsed = Title
::newFromText( $name );
817 if ( is_null( $parsed )
818 ||
$parsed->getNamespace()
819 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
820 wfDebugLog( 'username', __METHOD__
.
821 ": '$name' invalid due to ambiguous prefixes" );
825 // Check an additional blacklist of troublemaker characters.
826 // Should these be merged into the title char list?
827 $unicodeBlacklist = '/[' .
828 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
829 '\x{00a0}' . # non-breaking space
830 '\x{2000}-\x{200f}' . # various whitespace
831 '\x{2028}-\x{202f}' . # breaks and control chars
832 '\x{3000}' . # ideographic space
833 '\x{e000}-\x{f8ff}' . # private use
835 if ( preg_match( $unicodeBlacklist, $name ) ) {
836 wfDebugLog( 'username', __METHOD__
.
837 ": '$name' invalid due to blacklisted characters" );
845 * Usernames which fail to pass this function will be blocked
846 * from user login and new account registrations, but may be used
847 * internally by batch processes.
849 * If an account already exists in this form, login will be blocked
850 * by a failure to pass this function.
852 * @param string $name Name to match
855 public static function isUsableName( $name ) {
856 global $wgReservedUsernames;
857 // Must be a valid username, obviously ;)
858 if ( !self
::isValidUserName( $name ) ) {
862 static $reservedUsernames = false;
863 if ( !$reservedUsernames ) {
864 $reservedUsernames = $wgReservedUsernames;
865 Hooks
::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
868 // Certain names may be reserved for batch processes.
869 foreach ( $reservedUsernames as $reserved ) {
870 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
871 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
873 if ( $reserved == $name ) {
881 * Usernames which fail to pass this function will be blocked
882 * from new account registrations, but may be used internally
883 * either by batch processes or by user accounts which have
884 * already been created.
886 * Additional blacklisting may be added here rather than in
887 * isValidUserName() to avoid disrupting existing accounts.
889 * @param string $name String to match
892 public static function isCreatableName( $name ) {
893 global $wgInvalidUsernameCharacters;
895 // Ensure that the username isn't longer than 235 bytes, so that
896 // (at least for the builtin skins) user javascript and css files
897 // will work. (bug 23080)
898 if ( strlen( $name ) > 235 ) {
899 wfDebugLog( 'username', __METHOD__
.
900 ": '$name' invalid due to length" );
904 // Preg yells if you try to give it an empty string
905 if ( $wgInvalidUsernameCharacters !== '' ) {
906 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
907 wfDebugLog( 'username', __METHOD__
.
908 ": '$name' invalid due to wgInvalidUsernameCharacters" );
913 return self
::isUsableName( $name );
917 * Is the input a valid password for this user?
919 * @param string $password Desired password
922 public function isValidPassword( $password ) {
923 // simple boolean wrapper for getPasswordValidity
924 return $this->getPasswordValidity( $password ) === true;
928 * Given unvalidated password input, return error message on failure.
930 * @param string $password Desired password
931 * @return bool|string|array True on success, string or array of error message on failure
933 public function getPasswordValidity( $password ) {
934 $result = $this->checkPasswordValidity( $password );
935 if ( $result->isGood() ) {
939 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
940 $messages[] = $error['message'];
942 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
943 $messages[] = $warning['message'];
945 if ( count( $messages ) === 1 ) {
953 * Check if this is a valid password for this user
955 * Create a Status object based on the password's validity.
956 * The Status should be set to fatal if the user should not
957 * be allowed to log in, and should have any errors that
958 * would block changing the password.
960 * If the return value of this is not OK, the password
961 * should not be checked. If the return value is not Good,
962 * the password can be checked, but the user should not be
963 * able to set their password to this.
965 * @param string $password Desired password
966 * @param string $purpose one of 'login', 'create', 'reset'
970 public function checkPasswordValidity( $password, $purpose = 'login' ) {
971 global $wgPasswordPolicy;
973 $upp = new UserPasswordPolicy(
974 $wgPasswordPolicy['policies'],
975 $wgPasswordPolicy['checks']
978 $status = Status
::newGood();
979 $result = false; // init $result to false for the internal checks
981 if ( !Hooks
::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
982 $status->error( $result );
986 if ( $result === false ) {
987 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
989 } elseif ( $result === true ) {
992 $status->error( $result );
993 return $status; // the isValidPassword hook set a string $result and returned true
998 * Given unvalidated user input, return a canonical username, or false if
999 * the username is invalid.
1000 * @param string $name User input
1001 * @param string|bool $validate Type of validation to use:
1002 * - false No validation
1003 * - 'valid' Valid for batch processes
1004 * - 'usable' Valid for batch processes and login
1005 * - 'creatable' Valid for batch processes, login and account creation
1007 * @throws InvalidArgumentException
1008 * @return bool|string
1010 public static function getCanonicalName( $name, $validate = 'valid' ) {
1011 // Force usernames to capital
1013 $name = $wgContLang->ucfirst( $name );
1015 # Reject names containing '#'; these will be cleaned up
1016 # with title normalisation, but then it's too late to
1018 if ( strpos( $name, '#' ) !== false ) {
1022 // Clean up name according to title rules,
1023 // but only when validation is requested (bug 12654)
1024 $t = ( $validate !== false ) ?
1025 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
1026 // Check for invalid titles
1027 if ( is_null( $t ) ) {
1031 // Reject various classes of invalid names
1033 $name = $wgAuth->getCanonicalName( $t->getText() );
1035 switch ( $validate ) {
1039 if ( !User
::isValidUserName( $name ) ) {
1044 if ( !User
::isUsableName( $name ) ) {
1049 if ( !User
::isCreatableName( $name ) ) {
1054 throw new InvalidArgumentException(
1055 'Invalid parameter value for $validate in ' . __METHOD__
);
1061 * Count the number of edits of a user
1063 * @param int $uid User ID to check
1064 * @return int The user's edit count
1066 * @deprecated since 1.21 in favour of User::getEditCount
1068 public static function edits( $uid ) {
1069 wfDeprecated( __METHOD__
, '1.21' );
1070 $user = self
::newFromId( $uid );
1071 return $user->getEditCount();
1075 * Return a random password.
1077 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1078 * @return string New random password
1080 public static function randomPassword() {
1081 global $wgMinimalPasswordLength;
1082 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1086 * Set cached properties to default.
1088 * @note This no longer clears uncached lazy-initialised properties;
1089 * the constructor does that instead.
1091 * @param string|bool $name
1093 public function loadDefaults( $name = false ) {
1095 $this->mName
= $name;
1096 $this->mRealName
= '';
1098 $this->mOptionOverrides
= null;
1099 $this->mOptionsLoaded
= false;
1101 $loggedOut = $this->mRequest ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1102 if ( $loggedOut !== 0 ) {
1103 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1105 $this->mTouched
= '1'; # Allow any pages to be cached
1108 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1109 $this->mEmailAuthenticated
= null;
1110 $this->mEmailToken
= '';
1111 $this->mEmailTokenExpires
= null;
1112 $this->mRegistration
= wfTimestamp( TS_MW
);
1113 $this->mGroups
= array();
1115 Hooks
::run( 'UserLoadDefaults', array( $this, $name ) );
1119 * Return whether an item has been loaded.
1121 * @param string $item Item to check. Current possibilities:
1125 * @param string $all 'all' to check if the whole object has been loaded
1126 * or any other string to check if only the item is available (e.g.
1130 public function isItemLoaded( $item, $all = 'all' ) {
1131 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1132 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1136 * Set that an item has been loaded
1138 * @param string $item
1140 protected function setItemLoaded( $item ) {
1141 if ( is_array( $this->mLoadedItems
) ) {
1142 $this->mLoadedItems
[$item] = true;
1147 * Load user data from the session.
1149 * @return bool True if the user is logged in, false otherwise.
1151 private function loadFromSession() {
1154 Hooks
::run( 'UserLoadFromSession', array( $this, &$result ), '1.27' );
1155 if ( $result !== null ) {
1159 // MediaWiki\Session\Session already did the necessary authentication of the user
1160 // returned here, so just use it if applicable.
1161 $session = $this->getRequest()->getSession();
1162 $user = $session->getUser();
1163 if ( $user->isLoggedIn() ) {
1164 $this->loadFromUserObject( $user );
1165 // Other code expects these to be set in the session, so set them.
1166 $session->set( 'wsUserID', $this->getId() );
1167 $session->set( 'wsUserName', $this->getName() );
1168 $session->set( 'wsToken', $this->getToken() );
1176 * Load user and user_group data from the database.
1177 * $this->mId must be set, this is how the user is identified.
1179 * @param integer $flags User::READ_* constant bitfield
1180 * @return bool True if the user exists, false if the user is anonymous
1182 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1184 $this->mId
= intval( $this->mId
);
1187 if ( !$this->mId
) {
1188 $this->loadDefaults();
1192 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1193 $db = wfGetDB( $index );
1195 $s = $db->selectRow(
1197 self
::selectFields(),
1198 array( 'user_id' => $this->mId
),
1203 $this->queryFlagsUsed
= $flags;
1204 Hooks
::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1206 if ( $s !== false ) {
1207 // Initialise user table data
1208 $this->loadFromRow( $s );
1209 $this->mGroups
= null; // deferred
1210 $this->getEditCount(); // revalidation for nulls
1215 $this->loadDefaults();
1221 * Initialize this object from a row from the user table.
1223 * @param stdClass $row Row from the user table to load.
1224 * @param array $data Further user data to load into the object
1226 * user_groups Array with groups out of the user_groups table
1227 * user_properties Array with properties out of the user_properties table
1229 protected function loadFromRow( $row, $data = null ) {
1232 $this->mGroups
= null; // deferred
1234 if ( isset( $row->user_name
) ) {
1235 $this->mName
= $row->user_name
;
1236 $this->mFrom
= 'name';
1237 $this->setItemLoaded( 'name' );
1242 if ( isset( $row->user_real_name
) ) {
1243 $this->mRealName
= $row->user_real_name
;
1244 $this->setItemLoaded( 'realname' );
1249 if ( isset( $row->user_id
) ) {
1250 $this->mId
= intval( $row->user_id
);
1251 $this->mFrom
= 'id';
1252 $this->setItemLoaded( 'id' );
1257 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1258 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1261 if ( isset( $row->user_editcount
) ) {
1262 $this->mEditCount
= $row->user_editcount
;
1267 if ( isset( $row->user_touched
) ) {
1268 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1273 if ( isset( $row->user_token
) ) {
1274 // The definition for the column is binary(32), so trim the NULs
1275 // that appends. The previous definition was char(32), so trim
1277 $this->mToken
= rtrim( $row->user_token
, " \0" );
1278 if ( $this->mToken
=== '' ) {
1279 $this->mToken
= null;
1285 if ( isset( $row->user_email
) ) {
1286 $this->mEmail
= $row->user_email
;
1287 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1288 $this->mEmailToken
= $row->user_email_token
;
1289 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1290 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1296 $this->mLoadedItems
= true;
1299 if ( is_array( $data ) ) {
1300 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1301 $this->mGroups
= $data['user_groups'];
1303 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1304 $this->loadOptions( $data['user_properties'] );
1310 * Load the data for this user object from another user object.
1314 protected function loadFromUserObject( $user ) {
1316 $user->loadGroups();
1317 $user->loadOptions();
1318 foreach ( self
::$mCacheVars as $var ) {
1319 $this->$var = $user->$var;
1324 * Load the groups from the database if they aren't already loaded.
1326 private function loadGroups() {
1327 if ( is_null( $this->mGroups
) ) {
1328 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1329 ?
wfGetDB( DB_MASTER
)
1330 : wfGetDB( DB_SLAVE
);
1331 $res = $db->select( 'user_groups',
1332 array( 'ug_group' ),
1333 array( 'ug_user' => $this->mId
),
1335 $this->mGroups
= array();
1336 foreach ( $res as $row ) {
1337 $this->mGroups
[] = $row->ug_group
;
1343 * Add the user to the group if he/she meets given criteria.
1345 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1346 * possible to remove manually via Special:UserRights. In such case it
1347 * will not be re-added automatically. The user will also not lose the
1348 * group if they no longer meet the criteria.
1350 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1352 * @return array Array of groups the user has been promoted to.
1354 * @see $wgAutopromoteOnce
1356 public function addAutopromoteOnceGroups( $event ) {
1357 global $wgAutopromoteOnceLogInRC, $wgAuth;
1359 if ( wfReadOnly() ||
!$this->getId() ) {
1363 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1364 if ( !count( $toPromote ) ) {
1368 if ( !$this->checkAndSetTouched() ) {
1369 return array(); // raced out (bug T48834)
1372 $oldGroups = $this->getGroups(); // previous groups
1373 foreach ( $toPromote as $group ) {
1374 $this->addGroup( $group );
1376 // update groups in external authentication database
1377 Hooks
::run( 'UserGroupsChanged', array( $this, $toPromote, array(), false ) );
1378 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1380 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1382 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1383 $logEntry->setPerformer( $this );
1384 $logEntry->setTarget( $this->getUserPage() );
1385 $logEntry->setParameters( array(
1386 '4::oldgroups' => $oldGroups,
1387 '5::newgroups' => $newGroups,
1389 $logid = $logEntry->insert();
1390 if ( $wgAutopromoteOnceLogInRC ) {
1391 $logEntry->publish( $logid );
1398 * Bump user_touched if it didn't change since this object was loaded
1400 * On success, the mTouched field is updated.
1401 * The user serialization cache is always cleared.
1403 * @return bool Whether user_touched was actually updated
1406 protected function checkAndSetTouched() {
1409 if ( !$this->mId
) {
1410 return false; // anon
1413 // Get a new user_touched that is higher than the old one
1414 $oldTouched = $this->mTouched
;
1415 $newTouched = $this->newTouchedTimestamp();
1417 $dbw = wfGetDB( DB_MASTER
);
1418 $dbw->update( 'user',
1419 array( 'user_touched' => $dbw->timestamp( $newTouched ) ),
1421 'user_id' => $this->mId
,
1422 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1426 $success = ( $dbw->affectedRows() > 0 );
1429 $this->mTouched
= $newTouched;
1430 $this->clearSharedCache();
1432 // Clears on failure too since that is desired if the cache is stale
1433 $this->clearSharedCache( 'refresh' );
1440 * Clear various cached data stored in this object. The cache of the user table
1441 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1443 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1444 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1446 public function clearInstanceCache( $reloadFrom = false ) {
1447 $this->mNewtalk
= -1;
1448 $this->mDatePreference
= null;
1449 $this->mBlockedby
= -1; # Unset
1450 $this->mHash
= false;
1451 $this->mRights
= null;
1452 $this->mEffectiveGroups
= null;
1453 $this->mImplicitGroups
= null;
1454 $this->mGroups
= null;
1455 $this->mOptions
= null;
1456 $this->mOptionsLoaded
= false;
1457 $this->mEditCount
= null;
1459 if ( $reloadFrom ) {
1460 $this->mLoadedItems
= array();
1461 $this->mFrom
= $reloadFrom;
1466 * Combine the language default options with any site-specific options
1467 * and add the default language variants.
1469 * @return array Array of String options
1471 public static function getDefaultOptions() {
1472 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1474 static $defOpt = null;
1475 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1476 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1477 // mid-request and see that change reflected in the return value of this function.
1478 // Which is insane and would never happen during normal MW operation
1482 $defOpt = $wgDefaultUserOptions;
1483 // Default language setting
1484 $defOpt['language'] = $wgContLang->getCode();
1485 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1486 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1488 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1489 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1491 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1493 Hooks
::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1499 * Get a given default option value.
1501 * @param string $opt Name of option to retrieve
1502 * @return string Default option value
1504 public static function getDefaultOption( $opt ) {
1505 $defOpts = self
::getDefaultOptions();
1506 if ( isset( $defOpts[$opt] ) ) {
1507 return $defOpts[$opt];
1514 * Get blocking information
1515 * @param bool $bFromSlave Whether to check the slave database first.
1516 * To improve performance, non-critical checks are done against slaves.
1517 * Check when actually saving should be done against master.
1519 private function getBlockedStatus( $bFromSlave = true ) {
1520 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1522 if ( -1 != $this->mBlockedby
) {
1526 wfDebug( __METHOD__
. ": checking...\n" );
1528 // Initialize data...
1529 // Otherwise something ends up stomping on $this->mBlockedby when
1530 // things get lazy-loaded later, causing false positive block hits
1531 // due to -1 !== 0. Probably session-related... Nothing should be
1532 // overwriting mBlockedby, surely?
1535 # We only need to worry about passing the IP address to the Block generator if the
1536 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1537 # know which IP address they're actually coming from
1539 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1540 // $wgUser->getName() only works after the end of Setup.php. Until
1541 // then, assume it's a logged-out user.
1542 $globalUserName = $wgUser->isSafeToLoad()
1543 ?
$wgUser->getName()
1544 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1545 if ( $this->getName() === $globalUserName ) {
1546 $ip = $this->getRequest()->getIP();
1551 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1554 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1556 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1558 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1559 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1560 $block->setTarget( $ip );
1561 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1563 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1564 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1565 $block->setTarget( $ip );
1569 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1570 if ( !$block instanceof Block
1571 && $wgApplyIpBlocksToXff
1573 && !in_array( $ip, $wgProxyWhitelist )
1575 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1576 $xff = array_map( 'trim', explode( ',', $xff ) );
1577 $xff = array_diff( $xff, array( $ip ) );
1578 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1579 $block = Block
::chooseBlock( $xffblocks, $xff );
1580 if ( $block instanceof Block
) {
1581 # Mangle the reason to alert the user that the block
1582 # originated from matching the X-Forwarded-For header.
1583 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1587 if ( $block instanceof Block
) {
1588 wfDebug( __METHOD__
. ": Found block.\n" );
1589 $this->mBlock
= $block;
1590 $this->mBlockedby
= $block->getByName();
1591 $this->mBlockreason
= $block->mReason
;
1592 $this->mHideName
= $block->mHideName
;
1593 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1595 $this->mBlockedby
= '';
1596 $this->mHideName
= 0;
1597 $this->mAllowUsertalk
= false;
1601 Hooks
::run( 'GetBlockedStatus', array( &$this ) );
1606 * Whether the given IP is in a DNS blacklist.
1608 * @param string $ip IP to check
1609 * @param bool $checkWhitelist Whether to check the whitelist first
1610 * @return bool True if blacklisted.
1612 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1613 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1615 if ( !$wgEnableDnsBlacklist ) {
1619 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1623 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1627 * Whether the given IP is in a given DNS blacklist.
1629 * @param string $ip IP to check
1630 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1631 * @return bool True if blacklisted.
1633 public function inDnsBlacklist( $ip, $bases ) {
1636 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1637 if ( IP
::isIPv4( $ip ) ) {
1638 // Reverse IP, bug 21255
1639 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1641 foreach ( (array)$bases as $base ) {
1643 // If we have an access key, use that too (ProjectHoneypot, etc.)
1645 if ( is_array( $base ) ) {
1646 if ( count( $base ) >= 2 ) {
1647 // Access key is 1, base URL is 0
1648 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1650 $host = "$ipReversed.{$base[0]}";
1652 $basename = $base[0];
1654 $host = "$ipReversed.$base";
1658 $ipList = gethostbynamel( $host );
1661 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1665 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1674 * Check if an IP address is in the local proxy list
1680 public static function isLocallyBlockedProxy( $ip ) {
1681 global $wgProxyList;
1683 if ( !$wgProxyList ) {
1687 if ( !is_array( $wgProxyList ) ) {
1688 // Load from the specified file
1689 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1692 if ( !is_array( $wgProxyList ) ) {
1694 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1696 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1697 // Old-style flipped proxy list
1706 * Is this user subject to rate limiting?
1708 * @return bool True if rate limited
1710 public function isPingLimitable() {
1711 global $wgRateLimitsExcludedIPs;
1712 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1713 // No other good way currently to disable rate limits
1714 // for specific IPs. :P
1715 // But this is a crappy hack and should die.
1718 return !$this->isAllowed( 'noratelimit' );
1722 * Primitive rate limits: enforce maximum actions per time period
1723 * to put a brake on flooding.
1725 * The method generates both a generic profiling point and a per action one
1726 * (suffix being "-$action".
1728 * @note When using a shared cache like memcached, IP-address
1729 * last-hit counters will be shared across wikis.
1731 * @param string $action Action to enforce; 'edit' if unspecified
1732 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1733 * @return bool True if a rate limiter was tripped
1735 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1736 // Call the 'PingLimiter' hook
1738 if ( !Hooks
::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1742 global $wgRateLimits;
1743 if ( !isset( $wgRateLimits[$action] ) ) {
1747 // Some groups shouldn't trigger the ping limiter, ever
1748 if ( !$this->isPingLimitable() ) {
1752 $limits = $wgRateLimits[$action];
1754 $id = $this->getId();
1757 if ( isset( $limits['anon'] ) && $id == 0 ) {
1758 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1761 if ( isset( $limits['user'] ) && $id != 0 ) {
1762 $userLimit = $limits['user'];
1764 if ( $this->isNewbie() ) {
1765 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1766 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1768 if ( isset( $limits['ip'] ) ) {
1769 $ip = $this->getRequest()->getIP();
1770 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1772 if ( isset( $limits['subnet'] ) ) {
1773 $ip = $this->getRequest()->getIP();
1776 if ( IP
::isIPv6( $ip ) ) {
1777 $parts = IP
::parseRange( "$ip/64" );
1778 $subnet = $parts[0];
1779 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1781 $subnet = $matches[1];
1783 if ( $subnet !== false ) {
1784 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1788 // Check for group-specific permissions
1789 // If more than one group applies, use the group with the highest limit
1790 foreach ( $this->getGroups() as $group ) {
1791 if ( isset( $limits[$group] ) ) {
1792 if ( $userLimit === false
1793 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1795 $userLimit = $limits[$group];
1799 // Set the user limit key
1800 if ( $userLimit !== false ) {
1801 list( $max, $period ) = $userLimit;
1802 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1803 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1806 $cache = ObjectCache
::getLocalClusterInstance();
1809 foreach ( $keys as $key => $limit ) {
1810 list( $max, $period ) = $limit;
1811 $summary = "(limit $max in {$period}s)";
1812 $count = $cache->get( $key );
1815 if ( $count >= $max ) {
1816 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1817 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1820 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1823 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1824 if ( $incrBy > 0 ) {
1825 $cache->add( $key, 0, intval( $period ) ); // first ping
1828 if ( $incrBy > 0 ) {
1829 $cache->incr( $key, $incrBy );
1837 * Check if user is blocked
1839 * @param bool $bFromSlave Whether to check the slave database instead of
1840 * the master. Hacked from false due to horrible probs on site.
1841 * @return bool True if blocked, false otherwise
1843 public function isBlocked( $bFromSlave = true ) {
1844 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1848 * Get the block affecting the user, or null if the user is not blocked
1850 * @param bool $bFromSlave Whether to check the slave database instead of the master
1851 * @return Block|null
1853 public function getBlock( $bFromSlave = true ) {
1854 $this->getBlockedStatus( $bFromSlave );
1855 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1859 * Check if user is blocked from editing a particular article
1861 * @param Title $title Title to check
1862 * @param bool $bFromSlave Whether to check the slave database instead of the master
1865 public function isBlockedFrom( $title, $bFromSlave = false ) {
1866 global $wgBlockAllowsUTEdit;
1868 $blocked = $this->isBlocked( $bFromSlave );
1869 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1870 // If a user's name is suppressed, they cannot make edits anywhere
1871 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1872 && $title->getNamespace() == NS_USER_TALK
) {
1874 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1877 Hooks
::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1883 * If user is blocked, return the name of the user who placed the block
1884 * @return string Name of blocker
1886 public function blockedBy() {
1887 $this->getBlockedStatus();
1888 return $this->mBlockedby
;
1892 * If user is blocked, return the specified reason for the block
1893 * @return string Blocking reason
1895 public function blockedFor() {
1896 $this->getBlockedStatus();
1897 return $this->mBlockreason
;
1901 * If user is blocked, return the ID for the block
1902 * @return int Block ID
1904 public function getBlockId() {
1905 $this->getBlockedStatus();
1906 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1910 * Check if user is blocked on all wikis.
1911 * Do not use for actual edit permission checks!
1912 * This is intended for quick UI checks.
1914 * @param string $ip IP address, uses current client if none given
1915 * @return bool True if blocked, false otherwise
1917 public function isBlockedGlobally( $ip = '' ) {
1918 if ( $this->mBlockedGlobally
!== null ) {
1919 return $this->mBlockedGlobally
;
1921 // User is already an IP?
1922 if ( IP
::isIPAddress( $this->getName() ) ) {
1923 $ip = $this->getName();
1925 $ip = $this->getRequest()->getIP();
1928 Hooks
::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1929 $this->mBlockedGlobally
= (bool)$blocked;
1930 return $this->mBlockedGlobally
;
1934 * Check if user account is locked
1936 * @return bool True if locked, false otherwise
1938 public function isLocked() {
1939 if ( $this->mLocked
!== null ) {
1940 return $this->mLocked
;
1943 $authUser = $wgAuth->getUserInstance( $this );
1944 $this->mLocked
= (bool)$authUser->isLocked();
1945 Hooks
::run( 'UserIsLocked', array( $this, &$this->mLocked
) );
1946 return $this->mLocked
;
1950 * Check if user account is hidden
1952 * @return bool True if hidden, false otherwise
1954 public function isHidden() {
1955 if ( $this->mHideName
!== null ) {
1956 return $this->mHideName
;
1958 $this->getBlockedStatus();
1959 if ( !$this->mHideName
) {
1961 $authUser = $wgAuth->getUserInstance( $this );
1962 $this->mHideName
= (bool)$authUser->isHidden();
1963 Hooks
::run( 'UserIsHidden', array( $this, &$this->mHideName
) );
1965 return $this->mHideName
;
1969 * Get the user's ID.
1970 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1972 public function getId() {
1973 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1974 // Special case, we know the user is anonymous
1976 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1977 // Don't load if this was initialized from an ID
1984 * Set the user and reload all fields according to a given ID
1985 * @param int $v User ID to reload
1987 public function setId( $v ) {
1989 $this->clearInstanceCache( 'id' );
1993 * Get the user name, or the IP of an anonymous user
1994 * @return string User's name or IP address
1996 public function getName() {
1997 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1998 // Special case optimisation
1999 return $this->mName
;
2002 if ( $this->mName
=== false ) {
2004 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2006 return $this->mName
;
2011 * Set the user name.
2013 * This does not reload fields from the database according to the given
2014 * name. Rather, it is used to create a temporary "nonexistent user" for
2015 * later addition to the database. It can also be used to set the IP
2016 * address for an anonymous user to something other than the current
2019 * @note User::newFromName() has roughly the same function, when the named user
2021 * @param string $str New user name to set
2023 public function setName( $str ) {
2025 $this->mName
= $str;
2029 * Get the user's name escaped by underscores.
2030 * @return string Username escaped by underscores.
2032 public function getTitleKey() {
2033 return str_replace( ' ', '_', $this->getName() );
2037 * Check if the user has new messages.
2038 * @return bool True if the user has new messages
2040 public function getNewtalk() {
2043 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2044 if ( $this->mNewtalk
=== -1 ) {
2045 $this->mNewtalk
= false; # reset talk page status
2047 // Check memcached separately for anons, who have no
2048 // entire User object stored in there.
2049 if ( !$this->mId
) {
2050 global $wgDisableAnonTalk;
2051 if ( $wgDisableAnonTalk ) {
2052 // Anon newtalk disabled by configuration.
2053 $this->mNewtalk
= false;
2055 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2058 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2062 return (bool)$this->mNewtalk
;
2066 * Return the data needed to construct links for new talk page message
2067 * alerts. If there are new messages, this will return an associative array
2068 * with the following data:
2069 * wiki: The database name of the wiki
2070 * link: Root-relative link to the user's talk page
2071 * rev: The last talk page revision that the user has seen or null. This
2072 * is useful for building diff links.
2073 * If there are no new messages, it returns an empty array.
2074 * @note This function was designed to accomodate multiple talk pages, but
2075 * currently only returns a single link and revision.
2078 public function getNewMessageLinks() {
2080 if ( !Hooks
::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2082 } elseif ( !$this->getNewtalk() ) {
2085 $utp = $this->getTalkPage();
2086 $dbr = wfGetDB( DB_SLAVE
);
2087 // Get the "last viewed rev" timestamp from the oldest message notification
2088 $timestamp = $dbr->selectField( 'user_newtalk',
2089 'MIN(user_last_timestamp)',
2090 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2092 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2093 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2097 * Get the revision ID for the last talk page revision viewed by the talk
2099 * @return int|null Revision ID or null
2101 public function getNewMessageRevisionId() {
2102 $newMessageRevisionId = null;
2103 $newMessageLinks = $this->getNewMessageLinks();
2104 if ( $newMessageLinks ) {
2105 // Note: getNewMessageLinks() never returns more than a single link
2106 // and it is always for the same wiki, but we double-check here in
2107 // case that changes some time in the future.
2108 if ( count( $newMessageLinks ) === 1
2109 && $newMessageLinks[0]['wiki'] === wfWikiID()
2110 && $newMessageLinks[0]['rev']
2112 /** @var Revision $newMessageRevision */
2113 $newMessageRevision = $newMessageLinks[0]['rev'];
2114 $newMessageRevisionId = $newMessageRevision->getId();
2117 return $newMessageRevisionId;
2121 * Internal uncached check for new messages
2124 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2125 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2126 * @return bool True if the user has new messages
2128 protected function checkNewtalk( $field, $id ) {
2129 $dbr = wfGetDB( DB_SLAVE
);
2131 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__
);
2133 return $ok !== false;
2137 * Add or update the new messages flag
2138 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2139 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2140 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2141 * @return bool True if successful, false otherwise
2143 protected function updateNewtalk( $field, $id, $curRev = null ) {
2144 // Get timestamp of the talk page revision prior to the current one
2145 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2146 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2147 // Mark the user as having new messages since this revision
2148 $dbw = wfGetDB( DB_MASTER
);
2149 $dbw->insert( 'user_newtalk',
2150 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2153 if ( $dbw->affectedRows() ) {
2154 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2157 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2163 * Clear the new messages flag for the given user
2164 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2165 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2166 * @return bool True if successful, false otherwise
2168 protected function deleteNewtalk( $field, $id ) {
2169 $dbw = wfGetDB( DB_MASTER
);
2170 $dbw->delete( 'user_newtalk',
2171 array( $field => $id ),
2173 if ( $dbw->affectedRows() ) {
2174 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2177 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2183 * Update the 'You have new messages!' status.
2184 * @param bool $val Whether the user has new messages
2185 * @param Revision $curRev New, as yet unseen revision of the user talk
2186 * page. Ignored if null or !$val.
2188 public function setNewtalk( $val, $curRev = null ) {
2189 if ( wfReadOnly() ) {
2194 $this->mNewtalk
= $val;
2196 if ( $this->isAnon() ) {
2198 $id = $this->getName();
2201 $id = $this->getId();
2205 $changed = $this->updateNewtalk( $field, $id, $curRev );
2207 $changed = $this->deleteNewtalk( $field, $id );
2211 $this->invalidateCache();
2216 * Generate a current or new-future timestamp to be stored in the
2217 * user_touched field when we update things.
2218 * @return string Timestamp in TS_MW format
2220 private function newTouchedTimestamp() {
2221 global $wgClockSkewFudge;
2223 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2224 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2225 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2232 * Clear user data from memcached
2234 * Use after applying updates to the database; caller's
2235 * responsibility to update user_touched if appropriate.
2237 * Called implicitly from invalidateCache() and saveSettings().
2239 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2241 public function clearSharedCache( $mode = 'changed' ) {
2242 if ( !$this->getId() ) {
2246 $cache = ObjectCache
::getMainWANInstance();
2247 $key = $this->getCacheKey( $cache );
2248 if ( $mode === 'refresh' ) {
2249 $cache->delete( $key, 1 );
2251 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
2252 $cache->delete( $key );
2258 * Immediately touch the user data cache for this account
2260 * Calls touch() and removes account data from memcached
2262 public function invalidateCache() {
2264 $this->clearSharedCache();
2268 * Update the "touched" timestamp for the user
2270 * This is useful on various login/logout events when making sure that
2271 * a browser or proxy that has multiple tenants does not suffer cache
2272 * pollution where the new user sees the old users content. The value
2273 * of getTouched() is checked when determining 304 vs 200 responses.
2274 * Unlike invalidateCache(), this preserves the User object cache and
2275 * avoids database writes.
2279 public function touch() {
2280 $id = $this->getId();
2282 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2283 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2284 $this->mQuickTouched
= null;
2289 * Validate the cache for this account.
2290 * @param string $timestamp A timestamp in TS_MW format
2293 public function validateCache( $timestamp ) {
2294 return ( $timestamp >= $this->getTouched() );
2298 * Get the user touched timestamp
2300 * Use this value only to validate caches via inequalities
2301 * such as in the case of HTTP If-Modified-Since response logic
2303 * @return string TS_MW Timestamp
2305 public function getTouched() {
2309 if ( $this->mQuickTouched
=== null ) {
2310 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2311 $cache = ObjectCache
::getMainWANInstance();
2313 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2316 return max( $this->mTouched
, $this->mQuickTouched
);
2319 return $this->mTouched
;
2323 * Get the user_touched timestamp field (time of last DB updates)
2324 * @return string TS_MW Timestamp
2327 public function getDBTouched() {
2330 return $this->mTouched
;
2334 * @deprecated Removed in 1.27.
2338 public function getPassword() {
2339 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2343 * @deprecated Removed in 1.27.
2347 public function getTemporaryPassword() {
2348 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2352 * Set the password and reset the random token.
2353 * Calls through to authentication plugin if necessary;
2354 * will have no effect if the auth plugin refuses to
2355 * pass the change through or if the legal password
2358 * As a special case, setting the password to null
2359 * wipes it, so the account cannot be logged in until
2360 * a new password is set, for instance via e-mail.
2362 * @deprecated since 1.27. AuthManager is coming.
2363 * @param string $str New password to set
2364 * @throws PasswordError On failure
2367 public function setPassword( $str ) {
2370 if ( $str !== null ) {
2371 if ( !$wgAuth->allowPasswordChange() ) {
2372 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2375 $status = $this->checkPasswordValidity( $str );
2376 if ( !$status->isGood() ) {
2377 throw new PasswordError( $status->getMessage()->text() );
2381 if ( !$wgAuth->setPassword( $this, $str ) ) {
2382 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2386 $this->setOption( 'watchlisttoken', false );
2387 $this->setPasswordInternal( $str );
2393 * Set the password and reset the random token unconditionally.
2395 * @deprecated since 1.27. AuthManager is coming.
2396 * @param string|null $str New password to set or null to set an invalid
2397 * password hash meaning that the user will not be able to log in
2398 * through the web interface.
2400 public function setInternalPassword( $str ) {
2403 if ( $wgAuth->allowSetLocalPassword() ) {
2405 $this->setOption( 'watchlisttoken', false );
2406 $this->setPasswordInternal( $str );
2411 * Actually set the password and such
2412 * @since 1.27 cannot set a password for a user not in the database
2413 * @param string|null $str New password to set or null to set an invalid
2414 * password hash meaning that the user will not be able to log in
2415 * through the web interface.
2417 private function setPasswordInternal( $str ) {
2418 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2420 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2423 $passwordFactory = new PasswordFactory();
2424 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2425 $dbw = wfGetDB( DB_MASTER
);
2429 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2430 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2431 'user_newpass_time' => $dbw->timestampOrNull( null ),
2439 // When the main password is changed, invalidate all bot passwords too
2440 BotPassword
::invalidateAllPasswordsForUser( $this->getName() );
2444 * Get the user's current token.
2445 * @param bool $forceCreation Force the generation of a new token if the
2446 * user doesn't have one (default=true for backwards compatibility).
2447 * @return string|null Token
2449 public function getToken( $forceCreation = true ) {
2450 global $wgAuthenticationTokenVersion;
2453 if ( !$this->mToken
&& $forceCreation ) {
2457 // If the user doesn't have a token, return null to indicate that.
2458 // Otherwise, hmac the version with the secret if we have a version.
2459 if ( !$this->mToken
) {
2461 } elseif ( $wgAuthenticationTokenVersion === null ) {
2462 return $this->mToken
;
2464 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2466 // The raw hash can be overly long. Shorten it up.
2467 $len = max( 32, self
::TOKEN_LENGTH
);
2468 if ( strlen( $ret ) < $len ) {
2469 // Should never happen, even md5 is 128 bits
2470 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2472 return substr( $ret, -$len );
2477 * Set the random token (used for persistent authentication)
2478 * Called from loadDefaults() among other places.
2480 * @param string|bool $token If specified, set the token to this value
2482 public function setToken( $token = false ) {
2485 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2487 $this->mToken
= $token;
2492 * Set the password for a password reminder or new account email
2494 * @deprecated since 1.27, AuthManager is coming
2495 * @param string $str New password to set or null to set an invalid
2496 * password hash meaning that the user will not be able to use it
2497 * @param bool $throttle If true, reset the throttle timestamp to the present
2499 public function setNewpassword( $str, $throttle = true ) {
2500 $id = $this->getId();
2502 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2505 $dbw = wfGetDB( DB_MASTER
);
2507 $passwordFactory = new PasswordFactory();
2508 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2510 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2513 if ( $str === null ) {
2514 $update['user_newpass_time'] = null;
2515 } elseif ( $throttle ) {
2516 $update['user_newpass_time'] = $dbw->timestamp();
2519 $dbw->update( 'user', $update, array( 'user_id' => $id ), __METHOD__
);
2523 * Has password reminder email been sent within the last
2524 * $wgPasswordReminderResendTime hours?
2527 public function isPasswordReminderThrottled() {
2528 global $wgPasswordReminderResendTime;
2530 if ( !$wgPasswordReminderResendTime ) {
2536 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2537 ?
wfGetDB( DB_MASTER
)
2538 : wfGetDB( DB_SLAVE
);
2539 $newpassTime = $db->selectField(
2541 'user_newpass_time',
2542 array( 'user_id' => $this->getId() ),
2546 if ( $newpassTime === null ) {
2549 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2550 return time() < $expiry;
2554 * Get the user's e-mail address
2555 * @return string User's email address
2557 public function getEmail() {
2559 Hooks
::run( 'UserGetEmail', array( $this, &$this->mEmail
) );
2560 return $this->mEmail
;
2564 * Get the timestamp of the user's e-mail authentication
2565 * @return string TS_MW timestamp
2567 public function getEmailAuthenticationTimestamp() {
2569 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2570 return $this->mEmailAuthenticated
;
2574 * Set the user's e-mail address
2575 * @param string $str New e-mail address
2577 public function setEmail( $str ) {
2579 if ( $str == $this->mEmail
) {
2582 $this->invalidateEmail();
2583 $this->mEmail
= $str;
2584 Hooks
::run( 'UserSetEmail', array( $this, &$this->mEmail
) );
2588 * Set the user's e-mail address and a confirmation mail if needed.
2591 * @param string $str New e-mail address
2594 public function setEmailWithConfirmation( $str ) {
2595 global $wgEnableEmail, $wgEmailAuthentication;
2597 if ( !$wgEnableEmail ) {
2598 return Status
::newFatal( 'emaildisabled' );
2601 $oldaddr = $this->getEmail();
2602 if ( $str === $oldaddr ) {
2603 return Status
::newGood( true );
2606 $this->setEmail( $str );
2608 if ( $str !== '' && $wgEmailAuthentication ) {
2609 // Send a confirmation request to the new address if needed
2610 $type = $oldaddr != '' ?
'changed' : 'set';
2611 $result = $this->sendConfirmationMail( $type );
2612 if ( $result->isGood() ) {
2613 // Say to the caller that a confirmation mail has been sent
2614 $result->value
= 'eauth';
2617 $result = Status
::newGood( true );
2624 * Get the user's real name
2625 * @return string User's real name
2627 public function getRealName() {
2628 if ( !$this->isItemLoaded( 'realname' ) ) {
2632 return $this->mRealName
;
2636 * Set the user's real name
2637 * @param string $str New real name
2639 public function setRealName( $str ) {
2641 $this->mRealName
= $str;
2645 * Get the user's current setting for a given option.
2647 * @param string $oname The option to check
2648 * @param string $defaultOverride A default value returned if the option does not exist
2649 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2650 * @return string User's current value for the option
2651 * @see getBoolOption()
2652 * @see getIntOption()
2654 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2655 global $wgHiddenPrefs;
2656 $this->loadOptions();
2658 # We want 'disabled' preferences to always behave as the default value for
2659 # users, even if they have set the option explicitly in their settings (ie they
2660 # set it, and then it was disabled removing their ability to change it). But
2661 # we don't want to erase the preferences in the database in case the preference
2662 # is re-enabled again. So don't touch $mOptions, just override the returned value
2663 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2664 return self
::getDefaultOption( $oname );
2667 if ( array_key_exists( $oname, $this->mOptions
) ) {
2668 return $this->mOptions
[$oname];
2670 return $defaultOverride;
2675 * Get all user's options
2677 * @param int $flags Bitwise combination of:
2678 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2679 * to the default value. (Since 1.25)
2682 public function getOptions( $flags = 0 ) {
2683 global $wgHiddenPrefs;
2684 $this->loadOptions();
2685 $options = $this->mOptions
;
2687 # We want 'disabled' preferences to always behave as the default value for
2688 # users, even if they have set the option explicitly in their settings (ie they
2689 # set it, and then it was disabled removing their ability to change it). But
2690 # we don't want to erase the preferences in the database in case the preference
2691 # is re-enabled again. So don't touch $mOptions, just override the returned value
2692 foreach ( $wgHiddenPrefs as $pref ) {
2693 $default = self
::getDefaultOption( $pref );
2694 if ( $default !== null ) {
2695 $options[$pref] = $default;
2699 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2700 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2707 * Get the user's current setting for a given option, as a boolean value.
2709 * @param string $oname The option to check
2710 * @return bool User's current value for the option
2713 public function getBoolOption( $oname ) {
2714 return (bool)$this->getOption( $oname );
2718 * Get the user's current setting for a given option, as an integer value.
2720 * @param string $oname The option to check
2721 * @param int $defaultOverride A default value returned if the option does not exist
2722 * @return int User's current value for the option
2725 public function getIntOption( $oname, $defaultOverride = 0 ) {
2726 $val = $this->getOption( $oname );
2728 $val = $defaultOverride;
2730 return intval( $val );
2734 * Set the given option for a user.
2736 * You need to call saveSettings() to actually write to the database.
2738 * @param string $oname The option to set
2739 * @param mixed $val New value to set
2741 public function setOption( $oname, $val ) {
2742 $this->loadOptions();
2744 // Explicitly NULL values should refer to defaults
2745 if ( is_null( $val ) ) {
2746 $val = self
::getDefaultOption( $oname );
2749 $this->mOptions
[$oname] = $val;
2753 * Get a token stored in the preferences (like the watchlist one),
2754 * resetting it if it's empty (and saving changes).
2756 * @param string $oname The option name to retrieve the token from
2757 * @return string|bool User's current value for the option, or false if this option is disabled.
2758 * @see resetTokenFromOption()
2760 * @deprecated 1.26 Applications should use the OAuth extension
2762 public function getTokenFromOption( $oname ) {
2763 global $wgHiddenPrefs;
2765 $id = $this->getId();
2766 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2770 $token = $this->getOption( $oname );
2772 // Default to a value based on the user token to avoid space
2773 // wasted on storing tokens for all users. When this option
2774 // is set manually by the user, only then is it stored.
2775 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2782 * Reset a token stored in the preferences (like the watchlist one).
2783 * *Does not* save user's preferences (similarly to setOption()).
2785 * @param string $oname The option name to reset the token in
2786 * @return string|bool New token value, or false if this option is disabled.
2787 * @see getTokenFromOption()
2790 public function resetTokenFromOption( $oname ) {
2791 global $wgHiddenPrefs;
2792 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2796 $token = MWCryptRand
::generateHex( 40 );
2797 $this->setOption( $oname, $token );
2802 * Return a list of the types of user options currently returned by
2803 * User::getOptionKinds().
2805 * Currently, the option kinds are:
2806 * - 'registered' - preferences which are registered in core MediaWiki or
2807 * by extensions using the UserGetDefaultOptions hook.
2808 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2809 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2810 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2811 * be used by user scripts.
2812 * - 'special' - "preferences" that are not accessible via User::getOptions
2813 * or User::setOptions.
2814 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2815 * These are usually legacy options, removed in newer versions.
2817 * The API (and possibly others) use this function to determine the possible
2818 * option types for validation purposes, so make sure to update this when a
2819 * new option kind is added.
2821 * @see User::getOptionKinds
2822 * @return array Option kinds
2824 public static function listOptionKinds() {
2827 'registered-multiselect',
2828 'registered-checkmatrix',
2836 * Return an associative array mapping preferences keys to the kind of a preference they're
2837 * used for. Different kinds are handled differently when setting or reading preferences.
2839 * See User::listOptionKinds for the list of valid option types that can be provided.
2841 * @see User::listOptionKinds
2842 * @param IContextSource $context
2843 * @param array $options Assoc. array with options keys to check as keys.
2844 * Defaults to $this->mOptions.
2845 * @return array The key => kind mapping data
2847 public function getOptionKinds( IContextSource
$context, $options = null ) {
2848 $this->loadOptions();
2849 if ( $options === null ) {
2850 $options = $this->mOptions
;
2853 $prefs = Preferences
::getPreferences( $this, $context );
2856 // Pull out the "special" options, so they don't get converted as
2857 // multiselect or checkmatrix.
2858 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2859 foreach ( $specialOptions as $name => $value ) {
2860 unset( $prefs[$name] );
2863 // Multiselect and checkmatrix options are stored in the database with
2864 // one key per option, each having a boolean value. Extract those keys.
2865 $multiselectOptions = array();
2866 foreach ( $prefs as $name => $info ) {
2867 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2868 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2869 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2870 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2872 foreach ( $opts as $value ) {
2873 $multiselectOptions["$prefix$value"] = true;
2876 unset( $prefs[$name] );
2879 $checkmatrixOptions = array();
2880 foreach ( $prefs as $name => $info ) {
2881 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2882 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2883 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2884 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2885 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2887 foreach ( $columns as $column ) {
2888 foreach ( $rows as $row ) {
2889 $checkmatrixOptions["$prefix$column-$row"] = true;
2893 unset( $prefs[$name] );
2897 // $value is ignored
2898 foreach ( $options as $key => $value ) {
2899 if ( isset( $prefs[$key] ) ) {
2900 $mapping[$key] = 'registered';
2901 } elseif ( isset( $multiselectOptions[$key] ) ) {
2902 $mapping[$key] = 'registered-multiselect';
2903 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2904 $mapping[$key] = 'registered-checkmatrix';
2905 } elseif ( isset( $specialOptions[$key] ) ) {
2906 $mapping[$key] = 'special';
2907 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2908 $mapping[$key] = 'userjs';
2910 $mapping[$key] = 'unused';
2918 * Reset certain (or all) options to the site defaults
2920 * The optional parameter determines which kinds of preferences will be reset.
2921 * Supported values are everything that can be reported by getOptionKinds()
2922 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2924 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2925 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2926 * for backwards-compatibility.
2927 * @param IContextSource|null $context Context source used when $resetKinds
2928 * does not contain 'all', passed to getOptionKinds().
2929 * Defaults to RequestContext::getMain() when null.
2931 public function resetOptions(
2932 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2933 IContextSource
$context = null
2936 $defaultOptions = self
::getDefaultOptions();
2938 if ( !is_array( $resetKinds ) ) {
2939 $resetKinds = array( $resetKinds );
2942 if ( in_array( 'all', $resetKinds ) ) {
2943 $newOptions = $defaultOptions;
2945 if ( $context === null ) {
2946 $context = RequestContext
::getMain();
2949 $optionKinds = $this->getOptionKinds( $context );
2950 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2951 $newOptions = array();
2953 // Use default values for the options that should be deleted, and
2954 // copy old values for the ones that shouldn't.
2955 foreach ( $this->mOptions
as $key => $value ) {
2956 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2957 if ( array_key_exists( $key, $defaultOptions ) ) {
2958 $newOptions[$key] = $defaultOptions[$key];
2961 $newOptions[$key] = $value;
2966 Hooks
::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2968 $this->mOptions
= $newOptions;
2969 $this->mOptionsLoaded
= true;
2973 * Get the user's preferred date format.
2974 * @return string User's preferred date format
2976 public function getDatePreference() {
2977 // Important migration for old data rows
2978 if ( is_null( $this->mDatePreference
) ) {
2980 $value = $this->getOption( 'date' );
2981 $map = $wgLang->getDatePreferenceMigrationMap();
2982 if ( isset( $map[$value] ) ) {
2983 $value = $map[$value];
2985 $this->mDatePreference
= $value;
2987 return $this->mDatePreference
;
2991 * Determine based on the wiki configuration and the user's options,
2992 * whether this user must be over HTTPS no matter what.
2996 public function requiresHTTPS() {
2997 global $wgSecureLogin;
2998 if ( !$wgSecureLogin ) {
3001 $https = $this->getBoolOption( 'prefershttps' );
3002 Hooks
::run( 'UserRequiresHTTPS', array( $this, &$https ) );
3004 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3011 * Get the user preferred stub threshold
3015 public function getStubThreshold() {
3016 global $wgMaxArticleSize; # Maximum article size, in Kb
3017 $threshold = $this->getIntOption( 'stubthreshold' );
3018 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3019 // If they have set an impossible value, disable the preference
3020 // so we can use the parser cache again.
3027 * Get the permissions this user has.
3028 * @return array Array of String permission names
3030 public function getRights() {
3031 if ( is_null( $this->mRights
) ) {
3032 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3034 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3035 if ( $allowedRights !== null ) {
3036 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3039 Hooks
::run( 'UserGetRights', array( $this, &$this->mRights
) );
3040 // Force reindexation of rights when a hook has unset one of them
3041 $this->mRights
= array_values( array_unique( $this->mRights
) );
3043 return $this->mRights
;
3047 * Get the list of explicit group memberships this user has.
3048 * The implicit * and user groups are not included.
3049 * @return array Array of String internal group names
3051 public function getGroups() {
3053 $this->loadGroups();
3054 return $this->mGroups
;
3058 * Get the list of implicit group memberships this user has.
3059 * This includes all explicit groups, plus 'user' if logged in,
3060 * '*' for all accounts, and autopromoted groups
3061 * @param bool $recache Whether to avoid the cache
3062 * @return array Array of String internal group names
3064 public function getEffectiveGroups( $recache = false ) {
3065 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3066 $this->mEffectiveGroups
= array_unique( array_merge(
3067 $this->getGroups(), // explicit groups
3068 $this->getAutomaticGroups( $recache ) // implicit groups
3070 // Hook for additional groups
3071 Hooks
::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
3072 // Force reindexation of groups when a hook has unset one of them
3073 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3075 return $this->mEffectiveGroups
;
3079 * Get the list of implicit group memberships this user has.
3080 * This includes 'user' if logged in, '*' for all accounts,
3081 * and autopromoted groups
3082 * @param bool $recache Whether to avoid the cache
3083 * @return array Array of String internal group names
3085 public function getAutomaticGroups( $recache = false ) {
3086 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3087 $this->mImplicitGroups
= array( '*' );
3088 if ( $this->getId() ) {
3089 $this->mImplicitGroups
[] = 'user';
3091 $this->mImplicitGroups
= array_unique( array_merge(
3092 $this->mImplicitGroups
,
3093 Autopromote
::getAutopromoteGroups( $this )
3097 // Assure data consistency with rights/groups,
3098 // as getEffectiveGroups() depends on this function
3099 $this->mEffectiveGroups
= null;
3102 return $this->mImplicitGroups
;
3106 * Returns the groups the user has belonged to.
3108 * The user may still belong to the returned groups. Compare with getGroups().
3110 * The function will not return groups the user had belonged to before MW 1.17
3112 * @return array Names of the groups the user has belonged to.
3114 public function getFormerGroups() {
3117 if ( is_null( $this->mFormerGroups
) ) {
3118 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3119 ?
wfGetDB( DB_MASTER
)
3120 : wfGetDB( DB_SLAVE
);
3121 $res = $db->select( 'user_former_groups',
3122 array( 'ufg_group' ),
3123 array( 'ufg_user' => $this->mId
),
3125 $this->mFormerGroups
= array();
3126 foreach ( $res as $row ) {
3127 $this->mFormerGroups
[] = $row->ufg_group
;
3131 return $this->mFormerGroups
;
3135 * Get the user's edit count.
3136 * @return int|null Null for anonymous users
3138 public function getEditCount() {
3139 if ( !$this->getId() ) {
3143 if ( $this->mEditCount
=== null ) {
3144 /* Populate the count, if it has not been populated yet */
3145 $dbr = wfGetDB( DB_SLAVE
);
3146 // check if the user_editcount field has been initialized
3147 $count = $dbr->selectField(
3148 'user', 'user_editcount',
3149 array( 'user_id' => $this->mId
),
3153 if ( $count === null ) {
3154 // it has not been initialized. do so.
3155 $count = $this->initEditCount();
3157 $this->mEditCount
= $count;
3159 return (int)$this->mEditCount
;
3163 * Add the user to the given group.
3164 * This takes immediate effect.
3165 * @param string $group Name of the group to add
3168 public function addGroup( $group ) {
3171 if ( !Hooks
::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3175 $dbw = wfGetDB( DB_MASTER
);
3176 if ( $this->getId() ) {
3177 $dbw->insert( 'user_groups',
3179 'ug_user' => $this->getID(),
3180 'ug_group' => $group,
3183 array( 'IGNORE' ) );
3186 $this->loadGroups();
3187 $this->mGroups
[] = $group;
3188 // In case loadGroups was not called before, we now have the right twice.
3189 // Get rid of the duplicate.
3190 $this->mGroups
= array_unique( $this->mGroups
);
3192 // Refresh the groups caches, and clear the rights cache so it will be
3193 // refreshed on the next call to $this->getRights().
3194 $this->getEffectiveGroups( true );
3195 $this->mRights
= null;
3197 $this->invalidateCache();
3203 * Remove the user from the given group.
3204 * This takes immediate effect.
3205 * @param string $group Name of the group to remove
3208 public function removeGroup( $group ) {
3210 if ( !Hooks
::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3214 $dbw = wfGetDB( DB_MASTER
);
3215 $dbw->delete( 'user_groups',
3217 'ug_user' => $this->getID(),
3218 'ug_group' => $group,
3221 // Remember that the user was in this group
3222 $dbw->insert( 'user_former_groups',
3224 'ufg_user' => $this->getID(),
3225 'ufg_group' => $group,
3231 $this->loadGroups();
3232 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3234 // Refresh the groups caches, and clear the rights cache so it will be
3235 // refreshed on the next call to $this->getRights().
3236 $this->getEffectiveGroups( true );
3237 $this->mRights
= null;
3239 $this->invalidateCache();
3245 * Get whether the user is logged in
3248 public function isLoggedIn() {
3249 return $this->getID() != 0;
3253 * Get whether the user is anonymous
3256 public function isAnon() {
3257 return !$this->isLoggedIn();
3261 * Check if user is allowed to access a feature / make an action
3263 * @param string ... Permissions to test
3264 * @return bool True if user is allowed to perform *any* of the given actions
3266 public function isAllowedAny() {
3267 $permissions = func_get_args();
3268 foreach ( $permissions as $permission ) {
3269 if ( $this->isAllowed( $permission ) ) {
3278 * @param string ... Permissions to test
3279 * @return bool True if the user is allowed to perform *all* of the given actions
3281 public function isAllowedAll() {
3282 $permissions = func_get_args();
3283 foreach ( $permissions as $permission ) {
3284 if ( !$this->isAllowed( $permission ) ) {
3292 * Internal mechanics of testing a permission
3293 * @param string $action
3296 public function isAllowed( $action = '' ) {
3297 if ( $action === '' ) {
3298 return true; // In the spirit of DWIM
3300 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3301 // by misconfiguration: 0 == 'foo'
3302 return in_array( $action, $this->getRights(), true );
3306 * Check whether to enable recent changes patrol features for this user
3307 * @return bool True or false
3309 public function useRCPatrol() {
3310 global $wgUseRCPatrol;
3311 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3315 * Check whether to enable new pages patrol features for this user
3316 * @return bool True or false
3318 public function useNPPatrol() {
3319 global $wgUseRCPatrol, $wgUseNPPatrol;
3321 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3322 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3327 * Check whether to enable new files patrol features for this user
3328 * @return bool True or false
3330 public function useFilePatrol() {
3331 global $wgUseRCPatrol, $wgUseFilePatrol;
3333 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3334 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3339 * Get the WebRequest object to use with this object
3341 * @return WebRequest
3343 public function getRequest() {
3344 if ( $this->mRequest
) {
3345 return $this->mRequest
;
3353 * Get a WatchedItem for this user and $title.
3355 * @since 1.22 $checkRights parameter added
3356 * @param Title $title
3357 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3358 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3359 * @return WatchedItem
3361 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3362 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3364 if ( isset( $this->mWatchedItems
[$key] ) ) {
3365 return $this->mWatchedItems
[$key];
3368 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3369 $this->mWatchedItems
= array();
3372 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3373 return $this->mWatchedItems
[$key];
3377 * Check the watched status of an article.
3378 * @since 1.22 $checkRights parameter added
3379 * @param Title $title Title of the article to look at
3380 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3381 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3384 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3385 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3390 * @since 1.22 $checkRights parameter added
3391 * @param Title $title Title of the article to look at
3392 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3393 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3395 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3396 $this->getWatchedItem( $title, $checkRights )->addWatch();
3397 $this->invalidateCache();
3401 * Stop watching an article.
3402 * @since 1.22 $checkRights parameter added
3403 * @param Title $title Title of the article to look at
3404 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3405 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3407 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3408 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3409 $this->invalidateCache();
3413 * Clear the user's notification timestamp for the given title.
3414 * If e-notif e-mails are on, they will receive notification mails on
3415 * the next change of the page if it's watched etc.
3416 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3417 * @param Title $title Title of the article to look at
3418 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3420 public function clearNotification( &$title, $oldid = 0 ) {
3421 global $wgUseEnotif, $wgShowUpdatedMarker;
3423 // Do nothing if the database is locked to writes
3424 if ( wfReadOnly() ) {
3428 // Do nothing if not allowed to edit the watchlist
3429 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3433 // If we're working on user's talk page, we should update the talk page message indicator
3434 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3435 if ( !Hooks
::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3440 // Try to update the DB post-send and only if needed...
3441 DeferredUpdates
::addCallableUpdate( function() use ( $that, $title, $oldid ) {
3442 if ( !$that->getNewtalk() ) {
3443 return; // no notifications to clear
3446 // Delete the last notifications (they stack up)
3447 $that->setNewtalk( false );
3449 // If there is a new, unseen, revision, use its timestamp
3451 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3454 $that->setNewtalk( true, Revision
::newFromId( $nextid ) );
3459 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3463 if ( $this->isAnon() ) {
3464 // Nothing else to do...
3468 // Only update the timestamp if the page is being watched.
3469 // The query to find out if it is watched is cached both in memcached and per-invocation,
3470 // and when it does have to be executed, it can be on a slave
3471 // If this is the user's newtalk page, we always update the timestamp
3473 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3477 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3483 * Resets all of the given user's page-change notification timestamps.
3484 * If e-notif e-mails are on, they will receive notification mails on
3485 * the next change of any watched page.
3486 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3488 public function clearAllNotifications() {
3489 if ( wfReadOnly() ) {
3493 // Do nothing if not allowed to edit the watchlist
3494 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3498 global $wgUseEnotif, $wgShowUpdatedMarker;
3499 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3500 $this->setNewtalk( false );
3503 $id = $this->getId();
3505 $dbw = wfGetDB( DB_MASTER
);
3506 $dbw->update( 'watchlist',
3507 array( /* SET */ 'wl_notificationtimestamp' => null ),
3508 array( /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ),
3511 // We also need to clear here the "you have new message" notification for the own user_talk page;
3512 // it's cleared one page view later in WikiPage::doViewUpdates().
3517 * Set a cookie on the user's client. Wrapper for
3518 * WebResponse::setCookie
3519 * @deprecated since 1.27
3520 * @param string $name Name of the cookie to set
3521 * @param string $value Value to set
3522 * @param int $exp Expiration time, as a UNIX time value;
3523 * if 0 or not specified, use the default $wgCookieExpiration
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
3528 * @param array $params Array of options sent passed to WebResponse::setcookie()
3529 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3532 protected function setCookie(
3533 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3535 wfDeprecated( __METHOD__
, '1.27' );
3536 if ( $request === null ) {
3537 $request = $this->getRequest();
3539 $params['secure'] = $secure;
3540 $request->response()->setCookie( $name, $value, $exp, $params );
3544 * Clear a cookie on the user's client
3545 * @deprecated since 1.27
3546 * @param string $name Name of the cookie to clear
3547 * @param bool $secure
3548 * true: Force setting the secure attribute when setting the cookie
3549 * false: Force NOT setting the secure attribute when setting the cookie
3550 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3551 * @param array $params Array of options sent passed to WebResponse::setcookie()
3553 protected function clearCookie( $name, $secure = null, $params = array() ) {
3554 wfDeprecated( __METHOD__
, '1.27' );
3555 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3559 * Set an extended login cookie on the user's client. The expiry of the cookie
3560 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3563 * @see User::setCookie
3565 * @deprecated since 1.27
3566 * @param string $name Name of the cookie to set
3567 * @param string $value Value to set
3568 * @param bool $secure
3569 * true: Force setting the secure attribute when setting the cookie
3570 * false: Force NOT setting the secure attribute when setting the cookie
3571 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3573 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3574 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3576 wfDeprecated( __METHOD__
, '1.27' );
3579 $exp +
= $wgExtendedLoginCookieExpiration !== null
3580 ?
$wgExtendedLoginCookieExpiration
3581 : $wgCookieExpiration;
3583 $this->setCookie( $name, $value, $exp, $secure );
3587 * Persist this user's session (e.g. set cookies)
3589 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3591 * @param bool $secure Whether to force secure/insecure cookies or use default
3592 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3594 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3596 if ( 0 == $this->mId
) {
3600 $session = $this->getRequest()->getSession();
3601 if ( $request && $session->getRequest() !== $request ) {
3602 $session = $session->sessionWithRequest( $request );
3604 $delay = $session->delaySave();
3606 if ( !$session->getUser()->equals( $this ) ) {
3607 if ( !$session->canSetUser() ) {
3608 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3609 ->warning( __METHOD__
.
3610 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3614 $session->setUser( $this );
3617 $session->setRememberUser( $rememberMe );
3618 if ( $secure !== null ) {
3619 $session->setForceHTTPS( $secure );
3622 $session->persist();
3624 ScopedCallback
::consume( $delay );
3628 * Log this user out.
3630 public function logout() {
3631 if ( Hooks
::run( 'UserLogout', array( &$this ) ) ) {
3637 * Clear the user's session, and reset the instance cache.
3640 public function doLogout() {
3641 $session = $this->getRequest()->getSession();
3642 if ( !$session->canSetUser() ) {
3643 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3644 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3645 } elseif ( !$session->getUser()->equals( $this ) ) {
3646 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3647 ->warning( __METHOD__
.
3648 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3650 // But we still may as well make this user object anon
3651 $this->clearInstanceCache( 'defaults' );
3653 $this->clearInstanceCache( 'defaults' );
3654 $delay = $session->delaySave();
3655 $session->setLoggedOutTimestamp( time() );
3656 $session->setUser( new User
);
3657 $session->set( 'wsUserID', 0 ); // Other code expects this
3658 ScopedCallback
::consume( $delay );
3663 * Save this user's settings into the database.
3664 * @todo Only rarely do all these fields need to be set!
3666 public function saveSettings() {
3667 if ( wfReadOnly() ) {
3668 // @TODO: caller should deal with this instead!
3669 // This should really just be an exception.
3670 MWExceptionHandler
::logException( new DBExpectedError(
3672 "Could not update user with ID '{$this->mId}'; DB is read-only."
3678 if ( 0 == $this->mId
) {
3682 // Get a new user_touched that is higher than the old one.
3683 // This will be used for a CAS check as a last-resort safety
3684 // check against race conditions and slave lag.
3685 $oldTouched = $this->mTouched
;
3686 $newTouched = $this->newTouchedTimestamp();
3688 $dbw = wfGetDB( DB_MASTER
);
3689 $dbw->update( 'user',
3691 'user_name' => $this->mName
,
3692 'user_real_name' => $this->mRealName
,
3693 'user_email' => $this->mEmail
,
3694 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3695 'user_touched' => $dbw->timestamp( $newTouched ),
3696 'user_token' => strval( $this->mToken
),
3697 'user_email_token' => $this->mEmailToken
,
3698 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3699 ), array( /* WHERE */
3700 'user_id' => $this->mId
,
3701 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3705 if ( !$dbw->affectedRows() ) {
3706 // Maybe the problem was a missed cache update; clear it to be safe
3707 $this->clearSharedCache( 'refresh' );
3708 // User was changed in the meantime or loaded with stale data
3709 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3710 throw new MWException(
3711 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3712 " the version of the user to be saved is older than the current version."
3716 $this->mTouched
= $newTouched;
3717 $this->saveOptions();
3719 Hooks
::run( 'UserSaveSettings', array( $this ) );
3720 $this->clearSharedCache();
3721 $this->getUserPage()->invalidateCache();
3725 * If only this user's username is known, and it exists, return the user ID.
3727 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3730 public function idForName( $flags = 0 ) {
3731 $s = trim( $this->getName() );
3736 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3737 ?
wfGetDB( DB_MASTER
)
3738 : wfGetDB( DB_SLAVE
);
3740 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3741 ?
array( 'LOCK IN SHARE MODE' )
3744 $id = $db->selectField( 'user',
3745 'user_id', array( 'user_name' => $s ), __METHOD__
, $options );
3751 * Add a user to the database, return the user object
3753 * @param string $name Username to add
3754 * @param array $params Array of Strings Non-default parameters to save to
3755 * the database as user_* fields:
3756 * - email: The user's email address.
3757 * - email_authenticated: The email authentication timestamp.
3758 * - real_name: The user's real name.
3759 * - options: An associative array of non-default options.
3760 * - token: Random authentication token. Do not set.
3761 * - registration: Registration timestamp. Do not set.
3763 * @return User|null User object, or null if the username already exists.
3765 public static function createNew( $name, $params = array() ) {
3766 foreach ( array( 'password', 'newpassword', 'newpass_time', 'password_expires' ) as $field ) {
3767 if ( isset( $params[$field] ) ) {
3768 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3769 unset( $params[$field] );
3775 $user->setToken(); // init token
3776 if ( isset( $params['options'] ) ) {
3777 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3778 unset( $params['options'] );
3780 $dbw = wfGetDB( DB_MASTER
);
3781 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3783 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3786 'user_id' => $seqVal,
3787 'user_name' => $name,
3788 'user_password' => $noPass,
3789 'user_newpassword' => $noPass,
3790 'user_email' => $user->mEmail
,
3791 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3792 'user_real_name' => $user->mRealName
,
3793 'user_token' => strval( $user->mToken
),
3794 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3795 'user_editcount' => 0,
3796 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3798 foreach ( $params as $name => $value ) {
3799 $fields["user_$name"] = $value;
3801 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3802 if ( $dbw->affectedRows() ) {
3803 $newUser = User
::newFromId( $dbw->insertId() );
3811 * Add this existing user object to the database. If the user already
3812 * exists, a fatal status object is returned, and the user object is
3813 * initialised with the data from the database.
3815 * Previously, this function generated a DB error due to a key conflict
3816 * if the user already existed. Many extension callers use this function
3817 * in code along the lines of:
3819 * $user = User::newFromName( $name );
3820 * if ( !$user->isLoggedIn() ) {
3821 * $user->addToDatabase();
3823 * // do something with $user...
3825 * However, this was vulnerable to a race condition (bug 16020). By
3826 * initialising the user object if the user exists, we aim to support this
3827 * calling sequence as far as possible.
3829 * Note that if the user exists, this function will acquire a write lock,
3830 * so it is still advisable to make the call conditional on isLoggedIn(),
3831 * and to commit the transaction after calling.
3833 * @throws MWException
3836 public function addToDatabase() {
3838 if ( !$this->mToken
) {
3839 $this->setToken(); // init token
3842 $this->mTouched
= $this->newTouchedTimestamp();
3844 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3846 $dbw = wfGetDB( DB_MASTER
);
3847 $inWrite = $dbw->writesOrCallbacksPending();
3848 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3849 $dbw->insert( 'user',
3851 'user_id' => $seqVal,
3852 'user_name' => $this->mName
,
3853 'user_password' => $noPass,
3854 'user_newpassword' => $noPass,
3855 'user_email' => $this->mEmail
,
3856 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3857 'user_real_name' => $this->mRealName
,
3858 'user_token' => strval( $this->mToken
),
3859 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3860 'user_editcount' => 0,
3861 'user_touched' => $dbw->timestamp( $this->mTouched
),
3865 if ( !$dbw->affectedRows() ) {
3866 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3867 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3869 // Can't commit due to pending writes that may need atomicity.
3870 // This may cause some lock contention unlike the case below.
3871 $options = array( 'LOCK IN SHARE MODE' );
3872 $flags = self
::READ_LOCKING
;
3874 // Often, this case happens early in views before any writes when
3875 // using CentralAuth. It's should be OK to commit and break the snapshot.
3876 $dbw->commit( __METHOD__
, 'flush' );
3878 $flags = self
::READ_LATEST
;
3880 $this->mId
= $dbw->selectField( 'user', 'user_id',
3881 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3884 if ( $this->loadFromDatabase( $flags ) ) {
3889 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3890 "to insert user '{$this->mName}' row, but it was not present in select!" );
3892 return Status
::newFatal( 'userexists' );
3894 $this->mId
= $dbw->insertId();
3895 self
::$idCacheByName[$this->mName
] = $this->mId
;
3897 // Clear instance cache other than user table data, which is already accurate
3898 $this->clearInstanceCache();
3900 $this->saveOptions();
3901 return Status
::newGood();
3905 * If this user is logged-in and blocked,
3906 * block any IP address they've successfully logged in from.
3907 * @return bool A block was spread
3909 public function spreadAnyEditBlock() {
3910 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3911 return $this->spreadBlock();
3917 * If this (non-anonymous) user is blocked,
3918 * block the IP address they've successfully logged in from.
3919 * @return bool A block was spread
3921 protected function spreadBlock() {
3922 wfDebug( __METHOD__
. "()\n" );
3924 if ( $this->mId
== 0 ) {
3928 $userblock = Block
::newFromTarget( $this->getName() );
3929 if ( !$userblock ) {
3933 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3937 * Get whether the user is explicitly blocked from account creation.
3938 * @return bool|Block
3940 public function isBlockedFromCreateAccount() {
3941 $this->getBlockedStatus();
3942 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3943 return $this->mBlock
;
3946 # bug 13611: if the IP address the user is trying to create an account from is
3947 # blocked with createaccount disabled, prevent new account creation there even
3948 # when the user is logged in
3949 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3950 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3952 return $this->mBlockedFromCreateAccount
instanceof Block
3953 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3954 ?
$this->mBlockedFromCreateAccount
3959 * Get whether the user is blocked from using Special:Emailuser.
3962 public function isBlockedFromEmailuser() {
3963 $this->getBlockedStatus();
3964 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3968 * Get whether the user is allowed to create an account.
3971 public function isAllowedToCreateAccount() {
3972 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3976 * Get this user's personal page title.
3978 * @return Title User's personal page title
3980 public function getUserPage() {
3981 return Title
::makeTitle( NS_USER
, $this->getName() );
3985 * Get this user's talk page title.
3987 * @return Title User's talk page title
3989 public function getTalkPage() {
3990 $title = $this->getUserPage();
3991 return $title->getTalkPage();
3995 * Determine whether the user is a newbie. Newbies are either
3996 * anonymous IPs, or the most recently created accounts.
3999 public function isNewbie() {
4000 return !$this->isAllowed( 'autoconfirmed' );
4004 * Check to see if the given clear-text password is one of the accepted passwords
4005 * @deprecated since 1.27. AuthManager is coming.
4006 * @param string $password User password
4007 * @return bool True if the given password is correct, otherwise False
4009 public function checkPassword( $password ) {
4010 global $wgAuth, $wgLegacyEncoding;
4014 // Some passwords will give a fatal Status, which means there is
4015 // some sort of technical or security reason for this password to
4016 // be completely invalid and should never be checked (e.g., T64685)
4017 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4021 // Certain authentication plugins do NOT want to save
4022 // domain passwords in a mysql database, so we should
4023 // check this (in case $wgAuth->strict() is false).
4024 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4026 } elseif ( $wgAuth->strict() ) {
4027 // Auth plugin doesn't allow local authentication
4029 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4030 // Auth plugin doesn't allow local authentication for this user name
4034 $passwordFactory = new PasswordFactory();
4035 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4036 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4037 ?
wfGetDB( DB_MASTER
)
4038 : wfGetDB( DB_SLAVE
);
4041 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4042 'user', 'user_password', array( 'user_id' => $this->getId() ), __METHOD__
4044 } catch ( PasswordError
$e ) {
4045 wfDebug( 'Invalid password hash found in database.' );
4046 $mPassword = PasswordFactory
::newInvalidPassword();
4049 if ( !$mPassword->equals( $password ) ) {
4050 if ( $wgLegacyEncoding ) {
4051 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4052 // Check for this with iconv
4053 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4054 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4062 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4063 $this->setPasswordInternal( $password );
4070 * Check if the given clear-text password matches the temporary password
4071 * sent by e-mail for password reset operations.
4073 * @deprecated since 1.27. AuthManager is coming.
4074 * @param string $plaintext
4075 * @return bool True if matches, false otherwise
4077 public function checkTemporaryPassword( $plaintext ) {
4078 global $wgNewPasswordExpiry;
4082 $passwordFactory = new PasswordFactory();
4083 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4084 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4085 ?
wfGetDB( DB_MASTER
)
4086 : wfGetDB( DB_SLAVE
);
4088 $row = $db->selectRow(
4090 array( 'user_newpassword', 'user_newpass_time' ),
4091 array( 'user_id' => $this->getId() ),
4095 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4096 } catch ( PasswordError
$e ) {
4097 wfDebug( 'Invalid password hash found in database.' );
4098 $newPassword = PasswordFactory
::newInvalidPassword();
4101 if ( $newPassword->equals( $plaintext ) ) {
4102 if ( is_null( $row->user_newpass_time
) ) {
4105 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4106 return ( time() < $expiry );
4113 * Initialize (if necessary) and return a session token value
4114 * which can be used in edit forms to show that the user's
4115 * login credentials aren't being hijacked with a foreign form
4119 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4120 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4121 * @return MediaWiki\\Session\\Token The new edit token
4123 public function getEditTokenObject( $salt = '', $request = null ) {
4124 if ( $this->isAnon() ) {
4125 return new LoggedOutEditToken();
4129 $request = $this->getRequest();
4131 return $request->getSession()->getToken( $salt );
4135 * Initialize (if necessary) and return a session token value
4136 * which can be used in edit forms to show that the user's
4137 * login credentials aren't being hijacked with a foreign form
4141 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4142 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4143 * @return string The new edit token
4145 public function getEditToken( $salt = '', $request = null ) {
4146 return $this->getEditTokenObject( $salt, $request )->toString();
4150 * Get the embedded timestamp from a token.
4151 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::getTimestamp instead.
4152 * @param string $val Input token
4155 public static function getEditTokenTimestamp( $val ) {
4156 wfDeprecated( __METHOD__
, '1.27' );
4157 return MediaWiki\Session\Token
::getTimestamp( $val );
4161 * Check given value against the token value stored in the session.
4162 * A match should confirm that the form was submitted from the
4163 * user's own login session, not a form submission from a third-party
4166 * @param string $val Input value to compare
4167 * @param string $salt Optional function-specific data for hashing
4168 * @param WebRequest|null $request Object to use or null to use $wgRequest
4169 * @param int $maxage Fail tokens older than this, in seconds
4170 * @return bool Whether the token matches
4172 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4173 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4177 * Check given value against the token value stored in the session,
4178 * ignoring the suffix.
4180 * @param string $val Input value to compare
4181 * @param string $salt Optional function-specific data for hashing
4182 * @param WebRequest|null $request Object to use or null to use $wgRequest
4183 * @param int $maxage Fail tokens older than this, in seconds
4184 * @return bool Whether the token matches
4186 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4187 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4188 return $this->matchEditToken( $val, $salt, $request, $maxage );
4192 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4193 * mail to the user's given address.
4195 * @param string $type Message to send, either "created", "changed" or "set"
4198 public function sendConfirmationMail( $type = 'created' ) {
4200 $expiration = null; // gets passed-by-ref and defined in next line.
4201 $token = $this->confirmationToken( $expiration );
4202 $url = $this->confirmationTokenUrl( $token );
4203 $invalidateURL = $this->invalidationTokenUrl( $token );
4204 $this->saveSettings();
4206 if ( $type == 'created' ||
$type === false ) {
4207 $message = 'confirmemail_body';
4208 } elseif ( $type === true ) {
4209 $message = 'confirmemail_body_changed';
4211 // Messages: confirmemail_body_changed, confirmemail_body_set
4212 $message = 'confirmemail_body_' . $type;
4215 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4216 wfMessage( $message,
4217 $this->getRequest()->getIP(),
4220 $wgLang->userTimeAndDate( $expiration, $this ),
4222 $wgLang->userDate( $expiration, $this ),
4223 $wgLang->userTime( $expiration, $this ) )->text() );
4227 * Send an e-mail to this user's account. Does not check for
4228 * confirmed status or validity.
4230 * @param string $subject Message subject
4231 * @param string $body Message body
4232 * @param User|null $from Optional sending user; if unspecified, default
4233 * $wgPasswordSender will be used.
4234 * @param string $replyto Reply-To address
4237 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4238 global $wgPasswordSender;
4240 if ( $from instanceof User
) {
4241 $sender = MailAddress
::newFromUser( $from );
4243 $sender = new MailAddress( $wgPasswordSender,
4244 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4246 $to = MailAddress
::newFromUser( $this );
4248 return UserMailer
::send( $to, $sender, $subject, $body, array(
4249 'replyTo' => $replyto,
4254 * Generate, store, and return a new e-mail confirmation code.
4255 * A hash (unsalted, since it's used as a key) is stored.
4257 * @note Call saveSettings() after calling this function to commit
4258 * this change to the database.
4260 * @param string &$expiration Accepts the expiration time
4261 * @return string New token
4263 protected function confirmationToken( &$expiration ) {
4264 global $wgUserEmailConfirmationTokenExpiry;
4266 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4267 $expiration = wfTimestamp( TS_MW
, $expires );
4269 $token = MWCryptRand
::generateHex( 32 );
4270 $hash = md5( $token );
4271 $this->mEmailToken
= $hash;
4272 $this->mEmailTokenExpires
= $expiration;
4277 * Return a URL the user can use to confirm their email address.
4278 * @param string $token Accepts the email confirmation token
4279 * @return string New token URL
4281 protected function confirmationTokenUrl( $token ) {
4282 return $this->getTokenUrl( 'ConfirmEmail', $token );
4286 * Return a URL the user can use to invalidate their email address.
4287 * @param string $token Accepts the email confirmation token
4288 * @return string New token URL
4290 protected function invalidationTokenUrl( $token ) {
4291 return $this->getTokenUrl( 'InvalidateEmail', $token );
4295 * Internal function to format the e-mail validation/invalidation URLs.
4296 * This uses a quickie hack to use the
4297 * hardcoded English names of the Special: pages, for ASCII safety.
4299 * @note Since these URLs get dropped directly into emails, using the
4300 * short English names avoids insanely long URL-encoded links, which
4301 * also sometimes can get corrupted in some browsers/mailers
4302 * (bug 6957 with Gmail and Internet Explorer).
4304 * @param string $page Special page
4305 * @param string $token Token
4306 * @return string Formatted URL
4308 protected function getTokenUrl( $page, $token ) {
4309 // Hack to bypass localization of 'Special:'
4310 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4311 return $title->getCanonicalURL();
4315 * Mark the e-mail address confirmed.
4317 * @note Call saveSettings() after calling this function to commit the change.
4321 public function confirmEmail() {
4322 // Check if it's already confirmed, so we don't touch the database
4323 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4324 if ( !$this->isEmailConfirmed() ) {
4325 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4326 Hooks
::run( 'ConfirmEmailComplete', array( $this ) );
4332 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4333 * address if it was already confirmed.
4335 * @note Call saveSettings() after calling this function to commit the change.
4336 * @return bool Returns true
4338 public function invalidateEmail() {
4340 $this->mEmailToken
= null;
4341 $this->mEmailTokenExpires
= null;
4342 $this->setEmailAuthenticationTimestamp( null );
4344 Hooks
::run( 'InvalidateEmailComplete', array( $this ) );
4349 * Set the e-mail authentication timestamp.
4350 * @param string $timestamp TS_MW timestamp
4352 public function setEmailAuthenticationTimestamp( $timestamp ) {
4354 $this->mEmailAuthenticated
= $timestamp;
4355 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4359 * Is this user allowed to send e-mails within limits of current
4360 * site configuration?
4363 public function canSendEmail() {
4364 global $wgEnableEmail, $wgEnableUserEmail;
4365 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4368 $canSend = $this->isEmailConfirmed();
4369 Hooks
::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4374 * Is this user allowed to receive e-mails within limits of current
4375 * site configuration?
4378 public function canReceiveEmail() {
4379 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4383 * Is this user's e-mail address valid-looking and confirmed within
4384 * limits of the current site configuration?
4386 * @note If $wgEmailAuthentication is on, this may require the user to have
4387 * confirmed their address by returning a code or using a password
4388 * sent to the address from the wiki.
4392 public function isEmailConfirmed() {
4393 global $wgEmailAuthentication;
4396 if ( Hooks
::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4397 if ( $this->isAnon() ) {
4400 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4403 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4413 * Check whether there is an outstanding request for e-mail confirmation.
4416 public function isEmailConfirmationPending() {
4417 global $wgEmailAuthentication;
4418 return $wgEmailAuthentication &&
4419 !$this->isEmailConfirmed() &&
4420 $this->mEmailToken
&&
4421 $this->mEmailTokenExpires
> wfTimestamp();
4425 * Get the timestamp of account creation.
4427 * @return string|bool|null Timestamp of account creation, false for
4428 * non-existent/anonymous user accounts, or null if existing account
4429 * but information is not in database.
4431 public function getRegistration() {
4432 if ( $this->isAnon() ) {
4436 return $this->mRegistration
;
4440 * Get the timestamp of the first edit
4442 * @return string|bool Timestamp of first edit, or false for
4443 * non-existent/anonymous user accounts.
4445 public function getFirstEditTimestamp() {
4446 if ( $this->getId() == 0 ) {
4447 return false; // anons
4449 $dbr = wfGetDB( DB_SLAVE
);
4450 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4451 array( 'rev_user' => $this->getId() ),
4453 array( 'ORDER BY' => 'rev_timestamp ASC' )
4456 return false; // no edits
4458 return wfTimestamp( TS_MW
, $time );
4462 * Get the permissions associated with a given list of groups
4464 * @param array $groups Array of Strings List of internal group names
4465 * @return array Array of Strings List of permission key names for given groups combined
4467 public static function getGroupPermissions( $groups ) {
4468 global $wgGroupPermissions, $wgRevokePermissions;
4470 // grant every granted permission first
4471 foreach ( $groups as $group ) {
4472 if ( isset( $wgGroupPermissions[$group] ) ) {
4473 $rights = array_merge( $rights,
4474 // array_filter removes empty items
4475 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4478 // now revoke the revoked permissions
4479 foreach ( $groups as $group ) {
4480 if ( isset( $wgRevokePermissions[$group] ) ) {
4481 $rights = array_diff( $rights,
4482 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4485 return array_unique( $rights );
4489 * Get all the groups who have a given permission
4491 * @param string $role Role to check
4492 * @return array Array of Strings List of internal group names with the given permission
4494 public static function getGroupsWithPermission( $role ) {
4495 global $wgGroupPermissions;
4496 $allowedGroups = array();
4497 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4498 if ( self
::groupHasPermission( $group, $role ) ) {
4499 $allowedGroups[] = $group;
4502 return $allowedGroups;
4506 * Check, if the given group has the given permission
4508 * If you're wanting to check whether all users have a permission, use
4509 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4513 * @param string $group Group to check
4514 * @param string $role Role to check
4517 public static function groupHasPermission( $group, $role ) {
4518 global $wgGroupPermissions, $wgRevokePermissions;
4519 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4520 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4524 * Check if all users may be assumed to have the given permission
4526 * We generally assume so if the right is granted to '*' and isn't revoked
4527 * on any group. It doesn't attempt to take grants or other extension
4528 * limitations on rights into account in the general case, though, as that
4529 * would require it to always return false and defeat the purpose.
4530 * Specifically, session-based rights restrictions (such as OAuth or bot
4531 * passwords) are applied based on the current session.
4534 * @param string $right Right to check
4537 public static function isEveryoneAllowed( $right ) {
4538 global $wgGroupPermissions, $wgRevokePermissions;
4539 static $cache = array();
4541 // Use the cached results, except in unit tests which rely on
4542 // being able change the permission mid-request
4543 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4544 return $cache[$right];
4547 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4548 $cache[$right] = false;
4552 // If it's revoked anywhere, then everyone doesn't have it
4553 foreach ( $wgRevokePermissions as $rights ) {
4554 if ( isset( $rights[$right] ) && $rights[$right] ) {
4555 $cache[$right] = false;
4560 // Remove any rights that aren't allowed to the global-session user
4561 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4562 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4563 $cache[$right] = false;
4567 // Allow extensions to say false
4568 if ( !Hooks
::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4569 $cache[$right] = false;
4573 $cache[$right] = true;
4578 * Get the localized descriptive name for a group, if it exists
4580 * @param string $group Internal group name
4581 * @return string Localized descriptive group name
4583 public static function getGroupName( $group ) {
4584 $msg = wfMessage( "group-$group" );
4585 return $msg->isBlank() ?
$group : $msg->text();
4589 * Get the localized descriptive name for a member of a group, if it exists
4591 * @param string $group Internal group name
4592 * @param string $username Username for gender (since 1.19)
4593 * @return string Localized name for group member
4595 public static function getGroupMember( $group, $username = '#' ) {
4596 $msg = wfMessage( "group-$group-member", $username );
4597 return $msg->isBlank() ?
$group : $msg->text();
4601 * Return the set of defined explicit groups.
4602 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4603 * are not included, as they are defined automatically, not in the database.
4604 * @return array Array of internal group names
4606 public static function getAllGroups() {
4607 global $wgGroupPermissions, $wgRevokePermissions;
4609 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4610 self
::getImplicitGroups()
4615 * Get a list of all available permissions.
4616 * @return string[] Array of permission names
4618 public static function getAllRights() {
4619 if ( self
::$mAllRights === false ) {
4620 global $wgAvailableRights;
4621 if ( count( $wgAvailableRights ) ) {
4622 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4624 self
::$mAllRights = self
::$mCoreRights;
4626 Hooks
::run( 'UserGetAllRights', array( &self
::$mAllRights ) );
4628 return self
::$mAllRights;
4632 * Get a list of implicit groups
4633 * @return array Array of Strings Array of internal group names
4635 public static function getImplicitGroups() {
4636 global $wgImplicitGroups;
4638 $groups = $wgImplicitGroups;
4639 # Deprecated, use $wgImplicitGroups instead
4640 Hooks
::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4646 * Get the title of a page describing a particular group
4648 * @param string $group Internal group name
4649 * @return Title|bool Title of the page if it exists, false otherwise
4651 public static function getGroupPage( $group ) {
4652 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4653 if ( $msg->exists() ) {
4654 $title = Title
::newFromText( $msg->text() );
4655 if ( is_object( $title ) ) {
4663 * Create a link to the group in HTML, if available;
4664 * else return the group name.
4666 * @param string $group Internal name of the group
4667 * @param string $text The text of the link
4668 * @return string HTML link to the group
4670 public static function makeGroupLinkHTML( $group, $text = '' ) {
4671 if ( $text == '' ) {
4672 $text = self
::getGroupName( $group );
4674 $title = self
::getGroupPage( $group );
4676 return Linker
::link( $title, htmlspecialchars( $text ) );
4678 return htmlspecialchars( $text );
4683 * Create a link to the group in Wikitext, if available;
4684 * else return the group name.
4686 * @param string $group Internal name of the group
4687 * @param string $text The text of the link
4688 * @return string Wikilink to the group
4690 public static function makeGroupLinkWiki( $group, $text = '' ) {
4691 if ( $text == '' ) {
4692 $text = self
::getGroupName( $group );
4694 $title = self
::getGroupPage( $group );
4696 $page = $title->getFullText();
4697 return "[[$page|$text]]";
4704 * Returns an array of the groups that a particular group can add/remove.
4706 * @param string $group The group to check for whether it can add/remove
4707 * @return array Array( 'add' => array( addablegroups ),
4708 * 'remove' => array( removablegroups ),
4709 * 'add-self' => array( addablegroups to self),
4710 * 'remove-self' => array( removable groups from self) )
4712 public static function changeableByGroup( $group ) {
4713 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4717 'remove' => array(),
4718 'add-self' => array(),
4719 'remove-self' => array()
4722 if ( empty( $wgAddGroups[$group] ) ) {
4723 // Don't add anything to $groups
4724 } elseif ( $wgAddGroups[$group] === true ) {
4725 // You get everything
4726 $groups['add'] = self
::getAllGroups();
4727 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4728 $groups['add'] = $wgAddGroups[$group];
4731 // Same thing for remove
4732 if ( empty( $wgRemoveGroups[$group] ) ) {
4734 } elseif ( $wgRemoveGroups[$group] === true ) {
4735 $groups['remove'] = self
::getAllGroups();
4736 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4737 $groups['remove'] = $wgRemoveGroups[$group];
4740 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4741 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4742 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4743 if ( is_int( $key ) ) {
4744 $wgGroupsAddToSelf['user'][] = $value;
4749 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4750 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4751 if ( is_int( $key ) ) {
4752 $wgGroupsRemoveFromSelf['user'][] = $value;
4757 // Now figure out what groups the user can add to him/herself
4758 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4760 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4761 // No idea WHY this would be used, but it's there
4762 $groups['add-self'] = User
::getAllGroups();
4763 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4764 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4767 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4769 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4770 $groups['remove-self'] = User
::getAllGroups();
4771 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4772 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4779 * Returns an array of groups that this user can add and remove
4780 * @return array Array( 'add' => array( addablegroups ),
4781 * 'remove' => array( removablegroups ),
4782 * 'add-self' => array( addablegroups to self),
4783 * 'remove-self' => array( removable groups from self) )
4785 public function changeableGroups() {
4786 if ( $this->isAllowed( 'userrights' ) ) {
4787 // This group gives the right to modify everything (reverse-
4788 // compatibility with old "userrights lets you change
4790 // Using array_merge to make the groups reindexed
4791 $all = array_merge( User
::getAllGroups() );
4795 'add-self' => array(),
4796 'remove-self' => array()
4800 // Okay, it's not so simple, we will have to go through the arrays
4803 'remove' => array(),
4804 'add-self' => array(),
4805 'remove-self' => array()
4807 $addergroups = $this->getEffectiveGroups();
4809 foreach ( $addergroups as $addergroup ) {
4810 $groups = array_merge_recursive(
4811 $groups, $this->changeableByGroup( $addergroup )
4813 $groups['add'] = array_unique( $groups['add'] );
4814 $groups['remove'] = array_unique( $groups['remove'] );
4815 $groups['add-self'] = array_unique( $groups['add-self'] );
4816 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4822 * Deferred version of incEditCountImmediate()
4824 public function incEditCount() {
4826 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $that ) {
4827 $that->incEditCountImmediate();
4832 * Increment the user's edit-count field.
4833 * Will have no effect for anonymous users.
4836 public function incEditCountImmediate() {
4837 if ( $this->isAnon() ) {
4841 $dbw = wfGetDB( DB_MASTER
);
4842 // No rows will be "affected" if user_editcount is NULL
4845 array( 'user_editcount=user_editcount+1' ),
4846 array( 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ),
4849 // Lazy initialization check...
4850 if ( $dbw->affectedRows() == 0 ) {
4851 // Now here's a goddamn hack...
4852 $dbr = wfGetDB( DB_SLAVE
);
4853 if ( $dbr !== $dbw ) {
4854 // If we actually have a slave server, the count is
4855 // at least one behind because the current transaction
4856 // has not been committed and replicated.
4857 $this->initEditCount( 1 );
4859 // But if DB_SLAVE is selecting the master, then the
4860 // count we just read includes the revision that was
4861 // just added in the working transaction.
4862 $this->initEditCount();
4865 // Edit count in user cache too
4866 $this->invalidateCache();
4870 * Initialize user_editcount from data out of the revision table
4872 * @param int $add Edits to add to the count from the revision table
4873 * @return int Number of edits
4875 protected function initEditCount( $add = 0 ) {
4876 // Pull from a slave to be less cruel to servers
4877 // Accuracy isn't the point anyway here
4878 $dbr = wfGetDB( DB_SLAVE
);
4879 $count = (int)$dbr->selectField(
4882 array( 'rev_user' => $this->getId() ),
4885 $count = $count +
$add;
4887 $dbw = wfGetDB( DB_MASTER
);
4890 array( 'user_editcount' => $count ),
4891 array( 'user_id' => $this->getId() ),
4899 * Get the description of a given right
4901 * @param string $right Right to query
4902 * @return string Localized description of the right
4904 public static function getRightDescription( $right ) {
4905 $key = "right-$right";
4906 $msg = wfMessage( $key );
4907 return $msg->isBlank() ?
$right : $msg->text();
4911 * Make a new-style password hash
4913 * @param string $password Plain-text password
4914 * @param bool|string $salt Optional salt, may be random or the user ID.
4915 * If unspecified or false, will generate one automatically
4916 * @return string Password hash
4917 * @deprecated since 1.24, use Password class
4919 public static function crypt( $password, $salt = false ) {
4920 wfDeprecated( __METHOD__
, '1.24' );
4921 $passwordFactory = new PasswordFactory();
4922 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4923 $hash = $passwordFactory->newFromPlaintext( $password );
4924 return $hash->toString();
4928 * Compare a password hash with a plain-text password. Requires the user
4929 * ID if there's a chance that the hash is an old-style hash.
4931 * @param string $hash Password hash
4932 * @param string $password Plain-text password to compare
4933 * @param string|bool $userId User ID for old-style password salt
4936 * @deprecated since 1.24, use Password class
4938 public static function comparePasswords( $hash, $password, $userId = false ) {
4939 wfDeprecated( __METHOD__
, '1.24' );
4941 // Check for *really* old password hashes that don't even have a type
4942 // The old hash format was just an md5 hex hash, with no type information
4943 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4944 global $wgPasswordSalt;
4945 if ( $wgPasswordSalt ) {
4946 $password = ":B:{$userId}:{$hash}";
4948 $password = ":A:{$hash}";
4952 $passwordFactory = new PasswordFactory();
4953 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4954 $hash = $passwordFactory->newFromCiphertext( $hash );
4955 return $hash->equals( $password );
4959 * Add a newuser log entry for this user.
4960 * Before 1.19 the return value was always true.
4962 * @param string|bool $action Account creation type.
4963 * - String, one of the following values:
4964 * - 'create' for an anonymous user creating an account for himself.
4965 * This will force the action's performer to be the created user itself,
4966 * no matter the value of $wgUser
4967 * - 'create2' for a logged in user creating an account for someone else
4968 * - 'byemail' when the created user will receive its password by e-mail
4969 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4970 * - Boolean means whether the account was created by e-mail (deprecated):
4971 * - true will be converted to 'byemail'
4972 * - false will be converted to 'create' if this object is the same as
4973 * $wgUser and to 'create2' otherwise
4975 * @param string $reason User supplied reason
4977 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4979 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4980 global $wgUser, $wgNewUserLog;
4981 if ( empty( $wgNewUserLog ) ) {
4982 return true; // disabled
4985 if ( $action === true ) {
4986 $action = 'byemail';
4987 } elseif ( $action === false ) {
4988 if ( $this->equals( $wgUser ) ) {
4991 $action = 'create2';
4995 if ( $action === 'create' ||
$action === 'autocreate' ) {
4998 $performer = $wgUser;
5001 $logEntry = new ManualLogEntry( 'newusers', $action );
5002 $logEntry->setPerformer( $performer );
5003 $logEntry->setTarget( $this->getUserPage() );
5004 $logEntry->setComment( $reason );
5005 $logEntry->setParameters( array(
5006 '4::userid' => $this->getId(),
5008 $logid = $logEntry->insert();
5010 if ( $action !== 'autocreate' ) {
5011 $logEntry->publish( $logid );
5018 * Add an autocreate newuser log entry for this user
5019 * Used by things like CentralAuth and perhaps other authplugins.
5020 * Consider calling addNewUserLogEntry() directly instead.
5024 public function addNewUserLogEntryAutoCreate() {
5025 $this->addNewUserLogEntry( 'autocreate' );
5031 * Load the user options either from cache, the database or an array
5033 * @param array $data Rows for the current user out of the user_properties table
5035 protected function loadOptions( $data = null ) {
5040 if ( $this->mOptionsLoaded
) {
5044 $this->mOptions
= self
::getDefaultOptions();
5046 if ( !$this->getId() ) {
5047 // For unlogged-in users, load language/variant options from request.
5048 // There's no need to do it for logged-in users: they can set preferences,
5049 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5050 // so don't override user's choice (especially when the user chooses site default).
5051 $variant = $wgContLang->getDefaultVariant();
5052 $this->mOptions
['variant'] = $variant;
5053 $this->mOptions
['language'] = $variant;
5054 $this->mOptionsLoaded
= true;
5058 // Maybe load from the object
5059 if ( !is_null( $this->mOptionOverrides
) ) {
5060 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5061 foreach ( $this->mOptionOverrides
as $key => $value ) {
5062 $this->mOptions
[$key] = $value;
5065 if ( !is_array( $data ) ) {
5066 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5067 // Load from database
5068 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5069 ?
wfGetDB( DB_MASTER
)
5070 : wfGetDB( DB_SLAVE
);
5072 $res = $dbr->select(
5074 array( 'up_property', 'up_value' ),
5075 array( 'up_user' => $this->getId() ),
5079 $this->mOptionOverrides
= array();
5081 foreach ( $res as $row ) {
5082 $data[$row->up_property
] = $row->up_value
;
5085 foreach ( $data as $property => $value ) {
5086 $this->mOptionOverrides
[$property] = $value;
5087 $this->mOptions
[$property] = $value;
5091 $this->mOptionsLoaded
= true;
5093 Hooks
::run( 'UserLoadOptions', array( $this, &$this->mOptions
) );
5097 * Saves the non-default options for this user, as previously set e.g. via
5098 * setOption(), in the database's "user_properties" (preferences) table.
5099 * Usually used via saveSettings().
5101 protected function saveOptions() {
5102 $this->loadOptions();
5104 // Not using getOptions(), to keep hidden preferences in database
5105 $saveOptions = $this->mOptions
;
5107 // Allow hooks to abort, for instance to save to a global profile.
5108 // Reset options to default state before saving.
5109 if ( !Hooks
::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5113 $userId = $this->getId();
5115 $insert_rows = array(); // all the new preference rows
5116 foreach ( $saveOptions as $key => $value ) {
5117 // Don't bother storing default values
5118 $defaultOption = self
::getDefaultOption( $key );
5119 if ( ( $defaultOption === null && $value !== false && $value !== null )
5120 ||
$value != $defaultOption
5122 $insert_rows[] = array(
5123 'up_user' => $userId,
5124 'up_property' => $key,
5125 'up_value' => $value,
5130 $dbw = wfGetDB( DB_MASTER
);
5132 $res = $dbw->select( 'user_properties',
5133 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
5135 // Find prior rows that need to be removed or updated. These rows will
5136 // all be deleted (the later so that INSERT IGNORE applies the new values).
5137 $keysDelete = array();
5138 foreach ( $res as $row ) {
5139 if ( !isset( $saveOptions[$row->up_property
] )
5140 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5142 $keysDelete[] = $row->up_property
;
5146 if ( count( $keysDelete ) ) {
5147 // Do the DELETE by PRIMARY KEY for prior rows.
5148 // In the past a very large portion of calls to this function are for setting
5149 // 'rememberpassword' for new accounts (a preference that has since been removed).
5150 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5151 // caused gap locks on [max user ID,+infinity) which caused high contention since
5152 // updates would pile up on each other as they are for higher (newer) user IDs.
5153 // It might not be necessary these days, but it shouldn't hurt either.
5154 $dbw->delete( 'user_properties',
5155 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
5157 // Insert the new preference rows
5158 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
5162 * Lazily instantiate and return a factory object for making passwords
5164 * @deprecated since 1.27, create a PasswordFactory directly instead
5165 * @return PasswordFactory
5167 public static function getPasswordFactory() {
5168 wfDeprecated( __METHOD__
, '1.27' );
5169 $ret = new PasswordFactory();
5170 $ret->init( RequestContext
::getMain()->getConfig() );
5175 * Provide an array of HTML5 attributes to put on an input element
5176 * intended for the user to enter a new password. This may include
5177 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5179 * Do *not* use this when asking the user to enter his current password!
5180 * Regardless of configuration, users may have invalid passwords for whatever
5181 * reason (e.g., they were set before requirements were tightened up).
5182 * Only use it when asking for a new password, like on account creation or
5185 * Obviously, you still need to do server-side checking.
5187 * NOTE: A combination of bugs in various browsers means that this function
5188 * actually just returns array() unconditionally at the moment. May as
5189 * well keep it around for when the browser bugs get fixed, though.
5191 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5193 * @deprecated since 1.27
5194 * @return array Array of HTML attributes suitable for feeding to
5195 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5196 * That will get confused by the boolean attribute syntax used.)
5198 public static function passwordChangeInputAttribs() {
5199 global $wgMinimalPasswordLength;
5201 if ( $wgMinimalPasswordLength == 0 ) {
5205 # Note that the pattern requirement will always be satisfied if the
5206 # input is empty, so we need required in all cases.
5208 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5209 # if e-mail confirmation is being used. Since HTML5 input validation
5210 # is b0rked anyway in some browsers, just return nothing. When it's
5211 # re-enabled, fix this code to not output required for e-mail
5213 # $ret = array( 'required' );
5216 # We can't actually do this right now, because Opera 9.6 will print out
5217 # the entered password visibly in its error message! When other
5218 # browsers add support for this attribute, or Opera fixes its support,
5219 # we can add support with a version check to avoid doing this on Opera
5220 # versions where it will be a problem. Reported to Opera as
5221 # DSK-262266, but they don't have a public bug tracker for us to follow.
5223 if ( $wgMinimalPasswordLength > 1 ) {
5224 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5225 $ret['title'] = wfMessage( 'passwordtooshort' )
5226 ->numParams( $wgMinimalPasswordLength )->text();
5234 * Return the list of user fields that should be selected to create
5235 * a new user object.
5238 public static function selectFields() {
5246 'user_email_authenticated',
5248 'user_email_token_expires',
5249 'user_registration',
5255 * Factory function for fatal permission-denied errors
5258 * @param string $permission User right required
5261 static function newFatalPermissionDeniedStatus( $permission ) {
5264 $groups = array_map(
5265 array( 'User', 'makeGroupLinkWiki' ),
5266 User
::getGroupsWithPermission( $permission )
5270 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5272 return Status
::newFatal( 'badaccess-group0' );
5277 * Get a new instance of this user that was loaded from the master via a locking read
5279 * Use this instead of the main context User when updating that user. This avoids races
5280 * where that user was loaded from a slave or even the master but without proper locks.
5282 * @return User|null Returns null if the user was not found in the DB
5285 public function getInstanceForUpdate() {
5286 if ( !$this->getId() ) {
5287 return null; // anon
5290 $user = self
::newFromId( $this->getId() );
5291 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5299 * Checks if two user objects point to the same user.
5305 public function equals( User
$user ) {
5306 return $this->getName() === $user->getName();