3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Session\SessionManager
;
26 * String Some punctuation to prevent editing from broken text-mangling proxies.
29 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
32 * The User object encapsulates all of the user-specific settings (user_id,
33 * name, rights, email address, options, last login time). Client
34 * classes use the getXXX() functions to access these fields. These functions
35 * do all the work of determining whether the user is logged in,
36 * whether the requested option can be satisfied from cookies or
37 * whether a database query is needed. Most of the settings needed
38 * for rendering normal pages are set in the cookie to minimize use
41 class User
implements IDBAccessObject
{
43 * @const int Number of characters in user_token field.
45 const TOKEN_LENGTH
= 32;
48 * Global constant made accessible as class constants so that autoloader
51 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
54 * @const int Serialized record version.
59 * Maximum items in $mWatchedItems
61 const MAX_WATCHED_ITEMS_CACHE
= 100;
64 * Exclude user options that are set to their default value.
67 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
70 * Array of Strings List of member variables which are saved to the
71 * shared cache (memcached). Any operation which changes the
72 * corresponding database fields must call a cache-clearing function.
75 protected static $mCacheVars = array(
83 'mEmailAuthenticated',
90 // user_properties table
95 * Array of Strings Core rights.
96 * Each of these should have a corresponding message of the form
100 protected static $mCoreRights = array(
130 'editusercssjs', # deprecated
143 'move-categorypages',
144 'move-rootuserpages',
148 'override-export-depth',
171 'userrights-interwiki',
179 * String Cached results of getAllRights()
181 protected static $mAllRights = false;
183 /** Cache variables */
193 /** @var string TS_MW timestamp from the DB */
195 /** @var string TS_MW timestamp from cache */
196 protected $mQuickTouched;
200 public $mEmailAuthenticated;
202 protected $mEmailToken;
204 protected $mEmailTokenExpires;
206 protected $mRegistration;
208 protected $mEditCount;
212 protected $mOptionOverrides;
216 * Bool Whether the cache variables have been loaded.
219 public $mOptionsLoaded;
222 * Array with already loaded items or true if all items have been loaded.
224 protected $mLoadedItems = array();
228 * String Initialization data source if mLoadedItems!==true. May be one of:
229 * - 'defaults' anonymous user initialised from class defaults
230 * - 'name' initialise from mName
231 * - 'id' initialise from mId
232 * - 'session' log in from session if possible
234 * Use the User::newFrom*() family of functions to set this.
239 * Lazy-initialized variables, invalidated with clearInstanceCache
243 protected $mDatePreference;
251 protected $mBlockreason;
253 protected $mEffectiveGroups;
255 protected $mImplicitGroups;
257 protected $mFormerGroups;
259 protected $mBlockedGlobally;
276 protected $mAllowUsertalk;
279 private $mBlockedFromCreateAccount = false;
282 private $mWatchedItems = array();
284 /** @var integer User::READ_* constant bitfield used to load data */
285 protected $queryFlagsUsed = self
::READ_NORMAL
;
287 public static $idCacheByName = array();
290 * Lightweight constructor for an anonymous user.
291 * Use the User::newFrom* factory functions for other kinds of users.
295 * @see newFromConfirmationCode()
296 * @see newFromSession()
299 public function __construct() {
300 $this->clearInstanceCache( 'defaults' );
306 public function __toString() {
307 return $this->getName();
311 * Load the user table data for this object from the source given by mFrom.
313 * @param integer $flags User::READ_* constant bitfield
315 public function load( $flags = self
::READ_NORMAL
) {
316 global $wgFullyInitialised;
318 if ( $this->mLoadedItems
=== true ) {
322 // Set it now to avoid infinite recursion in accessors
323 $oldLoadedItems = $this->mLoadedItems
;
324 $this->mLoadedItems
= true;
325 $this->queryFlagsUsed
= $flags;
327 // If this is called too early, things are likely to break.
328 if ( $this->mFrom
=== 'session' && empty( $wgFullyInitialised ) ) {
329 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
330 ->warning( 'User::loadFromSession called before the end of Setup.php' );
331 $this->loadDefaults();
332 $this->mLoadedItems
= $oldLoadedItems;
336 switch ( $this->mFrom
) {
338 $this->loadDefaults();
341 // Make sure this thread sees its own changes
342 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
343 $flags |
= self
::READ_LATEST
;
344 $this->queryFlagsUsed
= $flags;
347 $this->mId
= self
::idFromName( $this->mName
, $flags );
349 // Nonexistent user placeholder object
350 $this->loadDefaults( $this->mName
);
352 $this->loadFromId( $flags );
356 $this->loadFromId( $flags );
359 if ( !$this->loadFromSession() ) {
360 // Loading from session failed. Load defaults.
361 $this->loadDefaults();
363 Hooks
::run( 'UserLoadAfterLoadFromSession', array( $this ) );
366 throw new UnexpectedValueException(
367 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
372 * Load user table data, given mId has already been set.
373 * @param integer $flags User::READ_* constant bitfield
374 * @return bool False if the ID does not exist, true otherwise
376 public function loadFromId( $flags = self
::READ_NORMAL
) {
377 if ( $this->mId
== 0 ) {
378 $this->loadDefaults();
382 // Try cache (unless this needs data from the master DB).
383 // NOTE: if this thread called saveSettings(), the cache was cleared.
384 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
385 if ( $latest ||
!$this->loadFromCache() ) {
386 wfDebug( "User: cache miss for user {$this->mId}\n" );
387 // Load from DB (make sure this thread sees its own changes)
388 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
389 $flags |
= self
::READ_LATEST
;
391 if ( !$this->loadFromDatabase( $flags ) ) {
392 // Can't load from ID, user is anonymous
395 $this->saveToCache();
398 $this->mLoadedItems
= true;
399 $this->queryFlagsUsed
= $flags;
406 * @param string $wikiId
407 * @param integer $userId
409 public static function purge( $wikiId, $userId ) {
410 $cache = ObjectCache
::getMainWANInstance();
411 $cache->delete( $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId ) );
416 * @param WANObjectCache $cache
419 protected function getCacheKey( WANObjectCache
$cache ) {
420 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
424 * Load user data from shared cache, given mId has already been set.
426 * @return bool false if the ID does not exist or data is invalid, true otherwise
429 protected function loadFromCache() {
430 if ( $this->mId
== 0 ) {
431 $this->loadDefaults();
435 $cache = ObjectCache
::getMainWANInstance();
436 $data = $cache->get( $this->getCacheKey( $cache ) );
437 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
442 wfDebug( "User: got user {$this->mId} from cache\n" );
444 // Restore from cache
445 foreach ( self
::$mCacheVars as $name ) {
446 $this->$name = $data[$name];
453 * Save user data to the shared cache
455 * This method should not be called outside the User class
457 public function saveToCache() {
460 $this->loadOptions();
462 if ( $this->isAnon() ) {
463 // Anonymous users are uncached
468 foreach ( self
::$mCacheVars as $name ) {
469 $data[$name] = $this->$name;
471 $data['mVersion'] = self
::VERSION
;
472 $opts = Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
474 $cache = ObjectCache
::getMainWANInstance();
475 $key = $this->getCacheKey( $cache );
476 $cache->set( $key, $data, $cache::TTL_HOUR
, $opts );
479 /** @name newFrom*() static factory methods */
483 * Static factory method for creation from username.
485 * This is slightly less efficient than newFromId(), so use newFromId() if
486 * you have both an ID and a name handy.
488 * @param string $name Username, validated by Title::newFromText()
489 * @param string|bool $validate Validate username. Takes the same parameters as
490 * User::getCanonicalName(), except that true is accepted as an alias
491 * for 'valid', for BC.
493 * @return User|bool User object, or false if the username is invalid
494 * (e.g. if it contains illegal characters or is an IP address). If the
495 * username is not present in the database, the result will be a user object
496 * with a name, zero user ID and default settings.
498 public static function newFromName( $name, $validate = 'valid' ) {
499 if ( $validate === true ) {
502 $name = self
::getCanonicalName( $name, $validate );
503 if ( $name === false ) {
506 // Create unloaded user object
510 $u->setItemLoaded( 'name' );
516 * Static factory method for creation from a given user ID.
518 * @param int $id Valid user ID
519 * @return User The corresponding User object
521 public static function newFromId( $id ) {
525 $u->setItemLoaded( 'id' );
530 * Factory method to fetch whichever user has a given email confirmation code.
531 * This code is generated when an account is created or its e-mail address
534 * If the code is invalid or has expired, returns NULL.
536 * @param string $code Confirmation code
537 * @param int $flags User::READ_* bitfield
540 public static function newFromConfirmationCode( $code, $flags = 0 ) {
541 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
542 ?
wfGetDB( DB_MASTER
)
543 : wfGetDB( DB_SLAVE
);
545 $id = $db->selectField(
549 'user_email_token' => md5( $code ),
550 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
554 return $id ? User
::newFromId( $id ) : null;
558 * Create a new user object using data from session. If the login
559 * credentials are invalid, the result is an anonymous user.
561 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
564 public static function newFromSession( WebRequest
$request = null ) {
566 $user->mFrom
= 'session';
567 $user->mRequest
= $request;
572 * Create a new user object from a user row.
573 * The row should have the following fields from the user table in it:
574 * - either user_name or user_id to load further data if needed (or both)
576 * - all other fields (email, etc.)
577 * It is useless to provide the remaining fields if either user_id,
578 * user_name and user_real_name are not provided because the whole row
579 * will be loaded once more from the database when accessing them.
581 * @param stdClass $row A row from the user table
582 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
585 public static function newFromRow( $row, $data = null ) {
587 $user->loadFromRow( $row, $data );
592 * Static factory method for creation of a "system" user from username.
594 * A "system" user is an account that's used to attribute logged actions
595 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
596 * might include the 'Maintenance script' or 'Conversion script' accounts
597 * used by various scripts in the maintenance/ directory or accounts such
598 * as 'MediaWiki message delivery' used by the MassMessage extension.
600 * This can optionally create the user if it doesn't exist, and "steal" the
601 * account if it does exist.
603 * @param string $name Username
604 * @param array $options Options are:
605 * - validate: As for User::getCanonicalName(), default 'valid'
606 * - create: Whether to create the user if it doesn't already exist, default true
607 * - steal: Whether to reset the account's password and email if it
608 * already exists, default false
611 public static function newSystemUser( $name, $options = array() ) {
613 'validate' => 'valid',
618 $name = self
::getCanonicalName( $name, $options['validate'] );
619 if ( $name === false ) {
623 $dbw = wfGetDB( DB_MASTER
);
624 $row = $dbw->selectRow(
627 self
::selectFields(),
628 array( 'user_password', 'user_newpassword' )
630 array( 'user_name' => $name ),
634 // No user. Create it?
635 return $options['create'] ? self
::createNew( $name ) : null;
637 $user = self
::newFromRow( $row );
639 // A user is considered to exist as a non-system user if it has a
640 // password set, or a temporary password set, or an email set.
641 $passwordFactory = new PasswordFactory();
642 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
644 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
645 } catch ( PasswordError
$e ) {
646 wfDebug( 'Invalid password hash found in database.' );
647 $password = PasswordFactory
::newInvalidPassword();
650 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
651 } catch ( PasswordError
$e ) {
652 wfDebug( 'Invalid password hash found in database.' );
653 $newpassword = PasswordFactory
::newInvalidPassword();
655 if ( !$password instanceof InvalidPassword ||
!$newpassword instanceof InvalidPassword
658 // User exists. Steal it?
659 if ( !$options['steal'] ) {
663 $nopass = PasswordFactory
::newInvalidPassword()->toString();
668 'user_password' => $nopass,
669 'user_newpassword' => $nopass,
670 'user_newpass_time' => null,
672 array( 'user_id' => $user->getId() ),
675 $user->invalidateEmail();
676 $user->saveSettings();
679 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
687 * Get the username corresponding to a given user ID
688 * @param int $id User ID
689 * @return string|bool The corresponding username
691 public static function whoIs( $id ) {
692 return UserCache
::singleton()->getProp( $id, 'name' );
696 * Get the real name of a user given their user ID
698 * @param int $id User ID
699 * @return string|bool The corresponding user's real name
701 public static function whoIsReal( $id ) {
702 return UserCache
::singleton()->getProp( $id, 'real_name' );
706 * Get database id given a user name
707 * @param string $name Username
708 * @param integer $flags User::READ_* constant bitfield
709 * @return int|null The corresponding user's ID, or null if user is nonexistent
711 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
712 $nt = Title
::makeTitleSafe( NS_USER
, $name );
713 if ( is_null( $nt ) ) {
718 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
719 return self
::$idCacheByName[$name];
722 $db = ( $flags & self
::READ_LATEST
)
723 ?
wfGetDB( DB_MASTER
)
724 : wfGetDB( DB_SLAVE
);
729 array( 'user_name' => $nt->getText() ),
733 if ( $s === false ) {
736 $result = $s->user_id
;
739 self
::$idCacheByName[$name] = $result;
741 if ( count( self
::$idCacheByName ) > 1000 ) {
742 self
::$idCacheByName = array();
749 * Reset the cache used in idFromName(). For use in tests.
751 public static function resetIdByNameCache() {
752 self
::$idCacheByName = array();
756 * Does the string match an anonymous IPv4 address?
758 * This function exists for username validation, in order to reject
759 * usernames which are similar in form to IP addresses. Strings such
760 * as 300.300.300.300 will return true because it looks like an IP
761 * address, despite not being strictly valid.
763 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
764 * address because the usemod software would "cloak" anonymous IP
765 * addresses like this, if we allowed accounts like this to be created
766 * new users could get the old edits of these anonymous users.
768 * @param string $name Name to match
771 public static function isIP( $name ) {
772 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
773 || IP
::isIPv6( $name );
777 * Is the input a valid username?
779 * Checks if the input is a valid username, we don't want an empty string,
780 * an IP address, anything that contains slashes (would mess up subpages),
781 * is longer than the maximum allowed username size or doesn't begin with
784 * @param string $name Name to match
787 public static function isValidUserName( $name ) {
788 global $wgContLang, $wgMaxNameChars;
791 || User
::isIP( $name )
792 ||
strpos( $name, '/' ) !== false
793 ||
strlen( $name ) > $wgMaxNameChars
794 ||
$name != $wgContLang->ucfirst( $name )
796 wfDebugLog( 'username', __METHOD__
.
797 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
801 // Ensure that the name can't be misresolved as a different title,
802 // such as with extra namespace keys at the start.
803 $parsed = Title
::newFromText( $name );
804 if ( is_null( $parsed )
805 ||
$parsed->getNamespace()
806 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
807 wfDebugLog( 'username', __METHOD__
.
808 ": '$name' invalid due to ambiguous prefixes" );
812 // Check an additional blacklist of troublemaker characters.
813 // Should these be merged into the title char list?
814 $unicodeBlacklist = '/[' .
815 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
816 '\x{00a0}' . # non-breaking space
817 '\x{2000}-\x{200f}' . # various whitespace
818 '\x{2028}-\x{202f}' . # breaks and control chars
819 '\x{3000}' . # ideographic space
820 '\x{e000}-\x{f8ff}' . # private use
822 if ( preg_match( $unicodeBlacklist, $name ) ) {
823 wfDebugLog( 'username', __METHOD__
.
824 ": '$name' invalid due to blacklisted characters" );
832 * Usernames which fail to pass this function will be blocked
833 * from user login and new account registrations, but may be used
834 * internally by batch processes.
836 * If an account already exists in this form, login will be blocked
837 * by a failure to pass this function.
839 * @param string $name Name to match
842 public static function isUsableName( $name ) {
843 global $wgReservedUsernames;
844 // Must be a valid username, obviously ;)
845 if ( !self
::isValidUserName( $name ) ) {
849 static $reservedUsernames = false;
850 if ( !$reservedUsernames ) {
851 $reservedUsernames = $wgReservedUsernames;
852 Hooks
::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
855 // Certain names may be reserved for batch processes.
856 foreach ( $reservedUsernames as $reserved ) {
857 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
858 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
860 if ( $reserved == $name ) {
868 * Usernames which fail to pass this function will be blocked
869 * from new account registrations, but may be used internally
870 * either by batch processes or by user accounts which have
871 * already been created.
873 * Additional blacklisting may be added here rather than in
874 * isValidUserName() to avoid disrupting existing accounts.
876 * @param string $name String to match
879 public static function isCreatableName( $name ) {
880 global $wgInvalidUsernameCharacters;
882 // Ensure that the username isn't longer than 235 bytes, so that
883 // (at least for the builtin skins) user javascript and css files
884 // will work. (bug 23080)
885 if ( strlen( $name ) > 235 ) {
886 wfDebugLog( 'username', __METHOD__
.
887 ": '$name' invalid due to length" );
891 // Preg yells if you try to give it an empty string
892 if ( $wgInvalidUsernameCharacters !== '' ) {
893 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
894 wfDebugLog( 'username', __METHOD__
.
895 ": '$name' invalid due to wgInvalidUsernameCharacters" );
900 return self
::isUsableName( $name );
904 * Is the input a valid password for this user?
906 * @param string $password Desired password
909 public function isValidPassword( $password ) {
910 // simple boolean wrapper for getPasswordValidity
911 return $this->getPasswordValidity( $password ) === true;
915 * Given unvalidated password input, return error message on failure.
917 * @param string $password Desired password
918 * @return bool|string|array True on success, string or array of error message on failure
920 public function getPasswordValidity( $password ) {
921 $result = $this->checkPasswordValidity( $password );
922 if ( $result->isGood() ) {
926 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
927 $messages[] = $error['message'];
929 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
930 $messages[] = $warning['message'];
932 if ( count( $messages ) === 1 ) {
940 * Check if this is a valid password for this user
942 * Create a Status object based on the password's validity.
943 * The Status should be set to fatal if the user should not
944 * be allowed to log in, and should have any errors that
945 * would block changing the password.
947 * If the return value of this is not OK, the password
948 * should not be checked. If the return value is not Good,
949 * the password can be checked, but the user should not be
950 * able to set their password to this.
952 * @param string $password Desired password
953 * @param string $purpose one of 'login', 'create', 'reset'
957 public function checkPasswordValidity( $password, $purpose = 'login' ) {
958 global $wgPasswordPolicy;
960 $upp = new UserPasswordPolicy(
961 $wgPasswordPolicy['policies'],
962 $wgPasswordPolicy['checks']
965 $status = Status
::newGood();
966 $result = false; // init $result to false for the internal checks
968 if ( !Hooks
::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
969 $status->error( $result );
973 if ( $result === false ) {
974 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
976 } elseif ( $result === true ) {
979 $status->error( $result );
980 return $status; // the isValidPassword hook set a string $result and returned true
985 * Given unvalidated user input, return a canonical username, or false if
986 * the username is invalid.
987 * @param string $name User input
988 * @param string|bool $validate Type of validation to use:
989 * - false No validation
990 * - 'valid' Valid for batch processes
991 * - 'usable' Valid for batch processes and login
992 * - 'creatable' Valid for batch processes, login and account creation
994 * @throws InvalidArgumentException
995 * @return bool|string
997 public static function getCanonicalName( $name, $validate = 'valid' ) {
998 // Force usernames to capital
1000 $name = $wgContLang->ucfirst( $name );
1002 # Reject names containing '#'; these will be cleaned up
1003 # with title normalisation, but then it's too late to
1005 if ( strpos( $name, '#' ) !== false ) {
1009 // Clean up name according to title rules,
1010 // but only when validation is requested (bug 12654)
1011 $t = ( $validate !== false ) ?
1012 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
1013 // Check for invalid titles
1014 if ( is_null( $t ) ) {
1018 // Reject various classes of invalid names
1020 $name = $wgAuth->getCanonicalName( $t->getText() );
1022 switch ( $validate ) {
1026 if ( !User
::isValidUserName( $name ) ) {
1031 if ( !User
::isUsableName( $name ) ) {
1036 if ( !User
::isCreatableName( $name ) ) {
1041 throw new InvalidArgumentException(
1042 'Invalid parameter value for $validate in ' . __METHOD__
);
1048 * Count the number of edits of a user
1050 * @param int $uid User ID to check
1051 * @return int The user's edit count
1053 * @deprecated since 1.21 in favour of User::getEditCount
1055 public static function edits( $uid ) {
1056 wfDeprecated( __METHOD__
, '1.21' );
1057 $user = self
::newFromId( $uid );
1058 return $user->getEditCount();
1062 * Return a random password.
1064 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1065 * @return string New random password
1067 public static function randomPassword() {
1068 global $wgMinimalPasswordLength;
1069 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1073 * Set cached properties to default.
1075 * @note This no longer clears uncached lazy-initialised properties;
1076 * the constructor does that instead.
1078 * @param string|bool $name
1080 public function loadDefaults( $name = false ) {
1082 $this->mName
= $name;
1083 $this->mRealName
= '';
1085 $this->mOptionOverrides
= null;
1086 $this->mOptionsLoaded
= false;
1088 $loggedOut = $this->mRequest ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1089 if ( $loggedOut !== 0 ) {
1090 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1092 $this->mTouched
= '1'; # Allow any pages to be cached
1095 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1096 $this->mEmailAuthenticated
= null;
1097 $this->mEmailToken
= '';
1098 $this->mEmailTokenExpires
= null;
1099 $this->mRegistration
= wfTimestamp( TS_MW
);
1100 $this->mGroups
= array();
1102 Hooks
::run( 'UserLoadDefaults', array( $this, $name ) );
1106 * Return whether an item has been loaded.
1108 * @param string $item Item to check. Current possibilities:
1112 * @param string $all 'all' to check if the whole object has been loaded
1113 * or any other string to check if only the item is available (e.g.
1117 public function isItemLoaded( $item, $all = 'all' ) {
1118 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1119 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1123 * Set that an item has been loaded
1125 * @param string $item
1127 protected function setItemLoaded( $item ) {
1128 if ( is_array( $this->mLoadedItems
) ) {
1129 $this->mLoadedItems
[$item] = true;
1134 * Load user data from the session.
1136 * @return bool True if the user is logged in, false otherwise.
1138 private function loadFromSession() {
1141 Hooks
::run( 'UserLoadFromSession', array( $this, &$result ), '1.27' );
1142 if ( $result !== null ) {
1146 // MediaWiki\Session\Session already did the necessary authentication of the user
1147 // returned here, so just use it if applicable.
1148 $session = $this->getRequest()->getSession();
1149 $user = $session->getUser();
1150 if ( $user->isLoggedIn() ) {
1151 $this->loadFromUserObject( $user );
1152 // Other code expects these to be set in the session, so set them.
1153 $session->set( 'wsUserID', $this->getId() );
1154 $session->set( 'wsUserName', $this->getName() );
1155 $session->set( 'wsToken', $this->mToken
);
1163 * Load user and user_group data from the database.
1164 * $this->mId must be set, this is how the user is identified.
1166 * @param integer $flags User::READ_* constant bitfield
1167 * @return bool True if the user exists, false if the user is anonymous
1169 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1171 $this->mId
= intval( $this->mId
);
1174 if ( !$this->mId
) {
1175 $this->loadDefaults();
1179 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1180 $db = wfGetDB( $index );
1182 $s = $db->selectRow(
1184 self
::selectFields(),
1185 array( 'user_id' => $this->mId
),
1190 $this->queryFlagsUsed
= $flags;
1191 Hooks
::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1193 if ( $s !== false ) {
1194 // Initialise user table data
1195 $this->loadFromRow( $s );
1196 $this->mGroups
= null; // deferred
1197 $this->getEditCount(); // revalidation for nulls
1202 $this->loadDefaults();
1208 * Initialize this object from a row from the user table.
1210 * @param stdClass $row Row from the user table to load.
1211 * @param array $data Further user data to load into the object
1213 * user_groups Array with groups out of the user_groups table
1214 * user_properties Array with properties out of the user_properties table
1216 protected function loadFromRow( $row, $data = null ) {
1219 $this->mGroups
= null; // deferred
1221 if ( isset( $row->user_name
) ) {
1222 $this->mName
= $row->user_name
;
1223 $this->mFrom
= 'name';
1224 $this->setItemLoaded( 'name' );
1229 if ( isset( $row->user_real_name
) ) {
1230 $this->mRealName
= $row->user_real_name
;
1231 $this->setItemLoaded( 'realname' );
1236 if ( isset( $row->user_id
) ) {
1237 $this->mId
= intval( $row->user_id
);
1238 $this->mFrom
= 'id';
1239 $this->setItemLoaded( 'id' );
1244 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1245 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1248 if ( isset( $row->user_editcount
) ) {
1249 $this->mEditCount
= $row->user_editcount
;
1254 if ( isset( $row->user_touched
) ) {
1255 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1260 if ( isset( $row->user_email
) ) {
1261 $this->mEmail
= $row->user_email
;
1262 $this->mToken
= $row->user_token
;
1263 if ( $this->mToken
== '' ) {
1264 $this->mToken
= null;
1266 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1267 $this->mEmailToken
= $row->user_email_token
;
1268 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1269 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1275 $this->mLoadedItems
= true;
1278 if ( is_array( $data ) ) {
1279 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1280 $this->mGroups
= $data['user_groups'];
1282 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1283 $this->loadOptions( $data['user_properties'] );
1289 * Load the data for this user object from another user object.
1293 protected function loadFromUserObject( $user ) {
1295 $user->loadGroups();
1296 $user->loadOptions();
1297 foreach ( self
::$mCacheVars as $var ) {
1298 $this->$var = $user->$var;
1303 * Load the groups from the database if they aren't already loaded.
1305 private function loadGroups() {
1306 if ( is_null( $this->mGroups
) ) {
1307 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1308 ?
wfGetDB( DB_MASTER
)
1309 : wfGetDB( DB_SLAVE
);
1310 $res = $db->select( 'user_groups',
1311 array( 'ug_group' ),
1312 array( 'ug_user' => $this->mId
),
1314 $this->mGroups
= array();
1315 foreach ( $res as $row ) {
1316 $this->mGroups
[] = $row->ug_group
;
1322 * Add the user to the group if he/she meets given criteria.
1324 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1325 * possible to remove manually via Special:UserRights. In such case it
1326 * will not be re-added automatically. The user will also not lose the
1327 * group if they no longer meet the criteria.
1329 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1331 * @return array Array of groups the user has been promoted to.
1333 * @see $wgAutopromoteOnce
1335 public function addAutopromoteOnceGroups( $event ) {
1336 global $wgAutopromoteOnceLogInRC, $wgAuth;
1338 if ( wfReadOnly() ||
!$this->getId() ) {
1342 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1343 if ( !count( $toPromote ) ) {
1347 if ( !$this->checkAndSetTouched() ) {
1348 return array(); // raced out (bug T48834)
1351 $oldGroups = $this->getGroups(); // previous groups
1352 foreach ( $toPromote as $group ) {
1353 $this->addGroup( $group );
1355 // update groups in external authentication database
1356 Hooks
::run( 'UserGroupsChanged', array( $this, $toPromote, array(), false ) );
1357 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1359 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1361 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1362 $logEntry->setPerformer( $this );
1363 $logEntry->setTarget( $this->getUserPage() );
1364 $logEntry->setParameters( array(
1365 '4::oldgroups' => $oldGroups,
1366 '5::newgroups' => $newGroups,
1368 $logid = $logEntry->insert();
1369 if ( $wgAutopromoteOnceLogInRC ) {
1370 $logEntry->publish( $logid );
1377 * Bump user_touched if it didn't change since this object was loaded
1379 * On success, the mTouched field is updated.
1380 * The user serialization cache is always cleared.
1382 * @return bool Whether user_touched was actually updated
1385 protected function checkAndSetTouched() {
1388 if ( !$this->mId
) {
1389 return false; // anon
1392 // Get a new user_touched that is higher than the old one
1393 $oldTouched = $this->mTouched
;
1394 $newTouched = $this->newTouchedTimestamp();
1396 $dbw = wfGetDB( DB_MASTER
);
1397 $dbw->update( 'user',
1398 array( 'user_touched' => $dbw->timestamp( $newTouched ) ),
1400 'user_id' => $this->mId
,
1401 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1405 $success = ( $dbw->affectedRows() > 0 );
1408 $this->mTouched
= $newTouched;
1409 $this->clearSharedCache();
1411 // Clears on failure too since that is desired if the cache is stale
1412 $this->clearSharedCache( 'refresh' );
1419 * Clear various cached data stored in this object. The cache of the user table
1420 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1422 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1423 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1425 public function clearInstanceCache( $reloadFrom = false ) {
1426 $this->mNewtalk
= -1;
1427 $this->mDatePreference
= null;
1428 $this->mBlockedby
= -1; # Unset
1429 $this->mHash
= false;
1430 $this->mRights
= null;
1431 $this->mEffectiveGroups
= null;
1432 $this->mImplicitGroups
= null;
1433 $this->mGroups
= null;
1434 $this->mOptions
= null;
1435 $this->mOptionsLoaded
= false;
1436 $this->mEditCount
= null;
1438 if ( $reloadFrom ) {
1439 $this->mLoadedItems
= array();
1440 $this->mFrom
= $reloadFrom;
1445 * Combine the language default options with any site-specific options
1446 * and add the default language variants.
1448 * @return array Array of String options
1450 public static function getDefaultOptions() {
1451 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1453 static $defOpt = null;
1454 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1455 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1456 // mid-request and see that change reflected in the return value of this function.
1457 // Which is insane and would never happen during normal MW operation
1461 $defOpt = $wgDefaultUserOptions;
1462 // Default language setting
1463 $defOpt['language'] = $wgContLang->getCode();
1464 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1465 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1467 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1468 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1470 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1472 Hooks
::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1478 * Get a given default option value.
1480 * @param string $opt Name of option to retrieve
1481 * @return string Default option value
1483 public static function getDefaultOption( $opt ) {
1484 $defOpts = self
::getDefaultOptions();
1485 if ( isset( $defOpts[$opt] ) ) {
1486 return $defOpts[$opt];
1493 * Get blocking information
1494 * @param bool $bFromSlave Whether to check the slave database first.
1495 * To improve performance, non-critical checks are done against slaves.
1496 * Check when actually saving should be done against master.
1498 private function getBlockedStatus( $bFromSlave = true ) {
1499 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1501 if ( -1 != $this->mBlockedby
) {
1505 wfDebug( __METHOD__
. ": checking...\n" );
1507 // Initialize data...
1508 // Otherwise something ends up stomping on $this->mBlockedby when
1509 // things get lazy-loaded later, causing false positive block hits
1510 // due to -1 !== 0. Probably session-related... Nothing should be
1511 // overwriting mBlockedby, surely?
1514 # We only need to worry about passing the IP address to the Block generator if the
1515 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1516 # know which IP address they're actually coming from
1517 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->equals( $wgUser ) ) {
1518 $ip = $this->getRequest()->getIP();
1524 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1527 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1529 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1531 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1532 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1533 $block->setTarget( $ip );
1534 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1536 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1537 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1538 $block->setTarget( $ip );
1542 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1543 if ( !$block instanceof Block
1544 && $wgApplyIpBlocksToXff
1546 && !in_array( $ip, $wgProxyWhitelist )
1548 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1549 $xff = array_map( 'trim', explode( ',', $xff ) );
1550 $xff = array_diff( $xff, array( $ip ) );
1551 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1552 $block = Block
::chooseBlock( $xffblocks, $xff );
1553 if ( $block instanceof Block
) {
1554 # Mangle the reason to alert the user that the block
1555 # originated from matching the X-Forwarded-For header.
1556 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1560 if ( $block instanceof Block
) {
1561 wfDebug( __METHOD__
. ": Found block.\n" );
1562 $this->mBlock
= $block;
1563 $this->mBlockedby
= $block->getByName();
1564 $this->mBlockreason
= $block->mReason
;
1565 $this->mHideName
= $block->mHideName
;
1566 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1568 $this->mBlockedby
= '';
1569 $this->mHideName
= 0;
1570 $this->mAllowUsertalk
= false;
1574 Hooks
::run( 'GetBlockedStatus', array( &$this ) );
1579 * Whether the given IP is in a DNS blacklist.
1581 * @param string $ip IP to check
1582 * @param bool $checkWhitelist Whether to check the whitelist first
1583 * @return bool True if blacklisted.
1585 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1586 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1588 if ( !$wgEnableDnsBlacklist ) {
1592 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1596 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1600 * Whether the given IP is in a given DNS blacklist.
1602 * @param string $ip IP to check
1603 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1604 * @return bool True if blacklisted.
1606 public function inDnsBlacklist( $ip, $bases ) {
1609 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1610 if ( IP
::isIPv4( $ip ) ) {
1611 // Reverse IP, bug 21255
1612 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1614 foreach ( (array)$bases as $base ) {
1616 // If we have an access key, use that too (ProjectHoneypot, etc.)
1618 if ( is_array( $base ) ) {
1619 if ( count( $base ) >= 2 ) {
1620 // Access key is 1, base URL is 0
1621 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1623 $host = "$ipReversed.{$base[0]}";
1625 $basename = $base[0];
1627 $host = "$ipReversed.$base";
1631 $ipList = gethostbynamel( $host );
1634 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1638 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1647 * Check if an IP address is in the local proxy list
1653 public static function isLocallyBlockedProxy( $ip ) {
1654 global $wgProxyList;
1656 if ( !$wgProxyList ) {
1660 if ( !is_array( $wgProxyList ) ) {
1661 // Load from the specified file
1662 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1665 if ( !is_array( $wgProxyList ) ) {
1667 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1669 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1670 // Old-style flipped proxy list
1679 * Is this user subject to rate limiting?
1681 * @return bool True if rate limited
1683 public function isPingLimitable() {
1684 global $wgRateLimitsExcludedIPs;
1685 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1686 // No other good way currently to disable rate limits
1687 // for specific IPs. :P
1688 // But this is a crappy hack and should die.
1691 return !$this->isAllowed( 'noratelimit' );
1695 * Primitive rate limits: enforce maximum actions per time period
1696 * to put a brake on flooding.
1698 * The method generates both a generic profiling point and a per action one
1699 * (suffix being "-$action".
1701 * @note When using a shared cache like memcached, IP-address
1702 * last-hit counters will be shared across wikis.
1704 * @param string $action Action to enforce; 'edit' if unspecified
1705 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1706 * @return bool True if a rate limiter was tripped
1708 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1709 // Call the 'PingLimiter' hook
1711 if ( !Hooks
::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1715 global $wgRateLimits;
1716 if ( !isset( $wgRateLimits[$action] ) ) {
1720 // Some groups shouldn't trigger the ping limiter, ever
1721 if ( !$this->isPingLimitable() ) {
1725 $limits = $wgRateLimits[$action];
1727 $id = $this->getId();
1730 if ( isset( $limits['anon'] ) && $id == 0 ) {
1731 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1734 if ( isset( $limits['user'] ) && $id != 0 ) {
1735 $userLimit = $limits['user'];
1737 if ( $this->isNewbie() ) {
1738 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1739 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1741 if ( isset( $limits['ip'] ) ) {
1742 $ip = $this->getRequest()->getIP();
1743 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1745 if ( isset( $limits['subnet'] ) ) {
1746 $ip = $this->getRequest()->getIP();
1749 if ( IP
::isIPv6( $ip ) ) {
1750 $parts = IP
::parseRange( "$ip/64" );
1751 $subnet = $parts[0];
1752 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1754 $subnet = $matches[1];
1756 if ( $subnet !== false ) {
1757 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1761 // Check for group-specific permissions
1762 // If more than one group applies, use the group with the highest limit
1763 foreach ( $this->getGroups() as $group ) {
1764 if ( isset( $limits[$group] ) ) {
1765 if ( $userLimit === false
1766 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1768 $userLimit = $limits[$group];
1772 // Set the user limit key
1773 if ( $userLimit !== false ) {
1774 list( $max, $period ) = $userLimit;
1775 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1776 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1779 $cache = ObjectCache
::getLocalClusterInstance();
1782 foreach ( $keys as $key => $limit ) {
1783 list( $max, $period ) = $limit;
1784 $summary = "(limit $max in {$period}s)";
1785 $count = $cache->get( $key );
1788 if ( $count >= $max ) {
1789 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1790 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1793 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1796 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1797 if ( $incrBy > 0 ) {
1798 $cache->add( $key, 0, intval( $period ) ); // first ping
1801 if ( $incrBy > 0 ) {
1802 $cache->incr( $key, $incrBy );
1810 * Check if user is blocked
1812 * @param bool $bFromSlave Whether to check the slave database instead of
1813 * the master. Hacked from false due to horrible probs on site.
1814 * @return bool True if blocked, false otherwise
1816 public function isBlocked( $bFromSlave = true ) {
1817 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1821 * Get the block affecting the user, or null if the user is not blocked
1823 * @param bool $bFromSlave Whether to check the slave database instead of the master
1824 * @return Block|null
1826 public function getBlock( $bFromSlave = true ) {
1827 $this->getBlockedStatus( $bFromSlave );
1828 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1832 * Check if user is blocked from editing a particular article
1834 * @param Title $title Title to check
1835 * @param bool $bFromSlave Whether to check the slave database instead of the master
1838 public function isBlockedFrom( $title, $bFromSlave = false ) {
1839 global $wgBlockAllowsUTEdit;
1841 $blocked = $this->isBlocked( $bFromSlave );
1842 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1843 // If a user's name is suppressed, they cannot make edits anywhere
1844 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1845 && $title->getNamespace() == NS_USER_TALK
) {
1847 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1850 Hooks
::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1856 * If user is blocked, return the name of the user who placed the block
1857 * @return string Name of blocker
1859 public function blockedBy() {
1860 $this->getBlockedStatus();
1861 return $this->mBlockedby
;
1865 * If user is blocked, return the specified reason for the block
1866 * @return string Blocking reason
1868 public function blockedFor() {
1869 $this->getBlockedStatus();
1870 return $this->mBlockreason
;
1874 * If user is blocked, return the ID for the block
1875 * @return int Block ID
1877 public function getBlockId() {
1878 $this->getBlockedStatus();
1879 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1883 * Check if user is blocked on all wikis.
1884 * Do not use for actual edit permission checks!
1885 * This is intended for quick UI checks.
1887 * @param string $ip IP address, uses current client if none given
1888 * @return bool True if blocked, false otherwise
1890 public function isBlockedGlobally( $ip = '' ) {
1891 if ( $this->mBlockedGlobally
!== null ) {
1892 return $this->mBlockedGlobally
;
1894 // User is already an IP?
1895 if ( IP
::isIPAddress( $this->getName() ) ) {
1896 $ip = $this->getName();
1898 $ip = $this->getRequest()->getIP();
1901 Hooks
::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1902 $this->mBlockedGlobally
= (bool)$blocked;
1903 return $this->mBlockedGlobally
;
1907 * Check if user account is locked
1909 * @return bool True if locked, false otherwise
1911 public function isLocked() {
1912 if ( $this->mLocked
!== null ) {
1913 return $this->mLocked
;
1916 $authUser = $wgAuth->getUserInstance( $this );
1917 $this->mLocked
= (bool)$authUser->isLocked();
1918 Hooks
::run( 'UserIsLocked', array( $this, &$this->mLocked
) );
1919 return $this->mLocked
;
1923 * Check if user account is hidden
1925 * @return bool True if hidden, false otherwise
1927 public function isHidden() {
1928 if ( $this->mHideName
!== null ) {
1929 return $this->mHideName
;
1931 $this->getBlockedStatus();
1932 if ( !$this->mHideName
) {
1934 $authUser = $wgAuth->getUserInstance( $this );
1935 $this->mHideName
= (bool)$authUser->isHidden();
1936 Hooks
::run( 'UserIsHidden', array( $this, &$this->mHideName
) );
1938 return $this->mHideName
;
1942 * Get the user's ID.
1943 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1945 public function getId() {
1946 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1947 // Special case, we know the user is anonymous
1949 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1950 // Don't load if this was initialized from an ID
1957 * Set the user and reload all fields according to a given ID
1958 * @param int $v User ID to reload
1960 public function setId( $v ) {
1962 $this->clearInstanceCache( 'id' );
1966 * Get the user name, or the IP of an anonymous user
1967 * @return string User's name or IP address
1969 public function getName() {
1970 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1971 // Special case optimisation
1972 return $this->mName
;
1975 if ( $this->mName
=== false ) {
1977 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1979 return $this->mName
;
1984 * Set the user name.
1986 * This does not reload fields from the database according to the given
1987 * name. Rather, it is used to create a temporary "nonexistent user" for
1988 * later addition to the database. It can also be used to set the IP
1989 * address for an anonymous user to something other than the current
1992 * @note User::newFromName() has roughly the same function, when the named user
1994 * @param string $str New user name to set
1996 public function setName( $str ) {
1998 $this->mName
= $str;
2002 * Get the user's name escaped by underscores.
2003 * @return string Username escaped by underscores.
2005 public function getTitleKey() {
2006 return str_replace( ' ', '_', $this->getName() );
2010 * Check if the user has new messages.
2011 * @return bool True if the user has new messages
2013 public function getNewtalk() {
2016 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2017 if ( $this->mNewtalk
=== -1 ) {
2018 $this->mNewtalk
= false; # reset talk page status
2020 // Check memcached separately for anons, who have no
2021 // entire User object stored in there.
2022 if ( !$this->mId
) {
2023 global $wgDisableAnonTalk;
2024 if ( $wgDisableAnonTalk ) {
2025 // Anon newtalk disabled by configuration.
2026 $this->mNewtalk
= false;
2028 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2031 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2035 return (bool)$this->mNewtalk
;
2039 * Return the data needed to construct links for new talk page message
2040 * alerts. If there are new messages, this will return an associative array
2041 * with the following data:
2042 * wiki: The database name of the wiki
2043 * link: Root-relative link to the user's talk page
2044 * rev: The last talk page revision that the user has seen or null. This
2045 * is useful for building diff links.
2046 * If there are no new messages, it returns an empty array.
2047 * @note This function was designed to accomodate multiple talk pages, but
2048 * currently only returns a single link and revision.
2051 public function getNewMessageLinks() {
2053 if ( !Hooks
::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2055 } elseif ( !$this->getNewtalk() ) {
2058 $utp = $this->getTalkPage();
2059 $dbr = wfGetDB( DB_SLAVE
);
2060 // Get the "last viewed rev" timestamp from the oldest message notification
2061 $timestamp = $dbr->selectField( 'user_newtalk',
2062 'MIN(user_last_timestamp)',
2063 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2065 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2066 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2070 * Get the revision ID for the last talk page revision viewed by the talk
2072 * @return int|null Revision ID or null
2074 public function getNewMessageRevisionId() {
2075 $newMessageRevisionId = null;
2076 $newMessageLinks = $this->getNewMessageLinks();
2077 if ( $newMessageLinks ) {
2078 // Note: getNewMessageLinks() never returns more than a single link
2079 // and it is always for the same wiki, but we double-check here in
2080 // case that changes some time in the future.
2081 if ( count( $newMessageLinks ) === 1
2082 && $newMessageLinks[0]['wiki'] === wfWikiID()
2083 && $newMessageLinks[0]['rev']
2085 /** @var Revision $newMessageRevision */
2086 $newMessageRevision = $newMessageLinks[0]['rev'];
2087 $newMessageRevisionId = $newMessageRevision->getId();
2090 return $newMessageRevisionId;
2094 * Internal uncached check for new messages
2097 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2098 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2099 * @return bool True if the user has new messages
2101 protected function checkNewtalk( $field, $id ) {
2102 $dbr = wfGetDB( DB_SLAVE
);
2104 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__
);
2106 return $ok !== false;
2110 * Add or update the new messages flag
2111 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2112 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2113 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2114 * @return bool True if successful, false otherwise
2116 protected function updateNewtalk( $field, $id, $curRev = null ) {
2117 // Get timestamp of the talk page revision prior to the current one
2118 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2119 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2120 // Mark the user as having new messages since this revision
2121 $dbw = wfGetDB( DB_MASTER
);
2122 $dbw->insert( 'user_newtalk',
2123 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2126 if ( $dbw->affectedRows() ) {
2127 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2130 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2136 * Clear the new messages flag for the given user
2137 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2138 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2139 * @return bool True if successful, false otherwise
2141 protected function deleteNewtalk( $field, $id ) {
2142 $dbw = wfGetDB( DB_MASTER
);
2143 $dbw->delete( 'user_newtalk',
2144 array( $field => $id ),
2146 if ( $dbw->affectedRows() ) {
2147 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2150 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2156 * Update the 'You have new messages!' status.
2157 * @param bool $val Whether the user has new messages
2158 * @param Revision $curRev New, as yet unseen revision of the user talk
2159 * page. Ignored if null or !$val.
2161 public function setNewtalk( $val, $curRev = null ) {
2162 if ( wfReadOnly() ) {
2167 $this->mNewtalk
= $val;
2169 if ( $this->isAnon() ) {
2171 $id = $this->getName();
2174 $id = $this->getId();
2178 $changed = $this->updateNewtalk( $field, $id, $curRev );
2180 $changed = $this->deleteNewtalk( $field, $id );
2184 $this->invalidateCache();
2189 * Generate a current or new-future timestamp to be stored in the
2190 * user_touched field when we update things.
2191 * @return string Timestamp in TS_MW format
2193 private function newTouchedTimestamp() {
2194 global $wgClockSkewFudge;
2196 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2197 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2198 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2205 * Clear user data from memcached
2207 * Use after applying updates to the database; caller's
2208 * responsibility to update user_touched if appropriate.
2210 * Called implicitly from invalidateCache() and saveSettings().
2212 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2214 public function clearSharedCache( $mode = 'changed' ) {
2215 if ( !$this->getId() ) {
2219 $cache = ObjectCache
::getMainWANInstance();
2220 $key = $this->getCacheKey( $cache );
2221 if ( $mode === 'refresh' ) {
2222 $cache->delete( $key, 1 );
2224 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
2225 $cache->delete( $key );
2231 * Immediately touch the user data cache for this account
2233 * Calls touch() and removes account data from memcached
2235 public function invalidateCache() {
2237 $this->clearSharedCache();
2241 * Update the "touched" timestamp for the user
2243 * This is useful on various login/logout events when making sure that
2244 * a browser or proxy that has multiple tenants does not suffer cache
2245 * pollution where the new user sees the old users content. The value
2246 * of getTouched() is checked when determining 304 vs 200 responses.
2247 * Unlike invalidateCache(), this preserves the User object cache and
2248 * avoids database writes.
2252 public function touch() {
2253 $id = $this->getId();
2255 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2256 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2257 $this->mQuickTouched
= null;
2262 * Validate the cache for this account.
2263 * @param string $timestamp A timestamp in TS_MW format
2266 public function validateCache( $timestamp ) {
2267 return ( $timestamp >= $this->getTouched() );
2271 * Get the user touched timestamp
2273 * Use this value only to validate caches via inequalities
2274 * such as in the case of HTTP If-Modified-Since response logic
2276 * @return string TS_MW Timestamp
2278 public function getTouched() {
2282 if ( $this->mQuickTouched
=== null ) {
2283 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2284 $cache = ObjectCache
::getMainWANInstance();
2286 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2289 return max( $this->mTouched
, $this->mQuickTouched
);
2292 return $this->mTouched
;
2296 * Get the user_touched timestamp field (time of last DB updates)
2297 * @return string TS_MW Timestamp
2300 public function getDBTouched() {
2303 return $this->mTouched
;
2307 * @deprecated Removed in 1.27.
2311 public function getPassword() {
2312 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2316 * @deprecated Removed in 1.27.
2320 public function getTemporaryPassword() {
2321 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2325 * Set the password and reset the random token.
2326 * Calls through to authentication plugin if necessary;
2327 * will have no effect if the auth plugin refuses to
2328 * pass the change through or if the legal password
2331 * As a special case, setting the password to null
2332 * wipes it, so the account cannot be logged in until
2333 * a new password is set, for instance via e-mail.
2335 * @deprecated since 1.27. AuthManager is coming.
2336 * @param string $str New password to set
2337 * @throws PasswordError On failure
2340 public function setPassword( $str ) {
2343 if ( $str !== null ) {
2344 if ( !$wgAuth->allowPasswordChange() ) {
2345 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2348 $status = $this->checkPasswordValidity( $str );
2349 if ( !$status->isGood() ) {
2350 throw new PasswordError( $status->getMessage()->text() );
2354 if ( !$wgAuth->setPassword( $this, $str ) ) {
2355 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2359 $this->setOption( 'watchlisttoken', false );
2360 $this->setPasswordInternal( $str );
2366 * Set the password and reset the random token unconditionally.
2368 * @deprecated since 1.27. AuthManager is coming.
2369 * @param string|null $str New password to set or null to set an invalid
2370 * password hash meaning that the user will not be able to log in
2371 * through the web interface.
2373 public function setInternalPassword( $str ) {
2376 if ( $wgAuth->allowSetLocalPassword() ) {
2378 $this->setOption( 'watchlisttoken', false );
2379 $this->setPasswordInternal( $str );
2384 * Actually set the password and such
2385 * @since 1.27 cannot set a password for a user not in the database
2386 * @param string|null $str New password to set or null to set an invalid
2387 * password hash meaning that the user will not be able to log in
2388 * through the web interface.
2390 private function setPasswordInternal( $str ) {
2391 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2393 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2396 $passwordFactory = new PasswordFactory();
2397 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2398 $dbw = wfGetDB( DB_MASTER
);
2402 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2403 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2404 'user_newpass_time' => $dbw->timestampOrNull( null ),
2412 // When the main password is changed, invalidate all bot passwords too
2413 BotPassword
::invalidateAllPasswordsForUser( $this->getName() );
2417 * Get the user's current token.
2418 * @param bool $forceCreation Force the generation of a new token if the
2419 * user doesn't have one (default=true for backwards compatibility).
2420 * @return string Token
2422 public function getToken( $forceCreation = true ) {
2424 if ( !$this->mToken
&& $forceCreation ) {
2427 return $this->mToken
;
2431 * Set the random token (used for persistent authentication)
2432 * Called from loadDefaults() among other places.
2434 * @param string|bool $token If specified, set the token to this value
2436 public function setToken( $token = false ) {
2439 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2441 $this->mToken
= $token;
2446 * Set the password for a password reminder or new account email
2448 * @deprecated since 1.27, AuthManager is coming
2449 * @param string $str New password to set or null to set an invalid
2450 * password hash meaning that the user will not be able to use it
2451 * @param bool $throttle If true, reset the throttle timestamp to the present
2453 public function setNewpassword( $str, $throttle = true ) {
2454 $id = $this->getId();
2456 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2459 $dbw = wfGetDB( DB_MASTER
);
2461 $passwordFactory = new PasswordFactory();
2462 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2464 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2467 if ( $str === null ) {
2468 $update['user_newpass_time'] = null;
2469 } elseif ( $throttle ) {
2470 $update['user_newpass_time'] = $dbw->timestamp();
2473 $dbw->update( 'user', $update, array( 'user_id' => $id ), __METHOD__
);
2477 * Has password reminder email been sent within the last
2478 * $wgPasswordReminderResendTime hours?
2481 public function isPasswordReminderThrottled() {
2482 global $wgPasswordReminderResendTime;
2484 if ( !$wgPasswordReminderResendTime ) {
2490 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2491 ?
wfGetDB( DB_MASTER
)
2492 : wfGetDB( DB_SLAVE
);
2493 $newpassTime = $db->selectField(
2495 'user_newpass_time',
2496 array( 'user_id' => $this->getId() ),
2500 if ( $newpassTime === null ) {
2503 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2504 return time() < $expiry;
2508 * Get the user's e-mail address
2509 * @return string User's email address
2511 public function getEmail() {
2513 Hooks
::run( 'UserGetEmail', array( $this, &$this->mEmail
) );
2514 return $this->mEmail
;
2518 * Get the timestamp of the user's e-mail authentication
2519 * @return string TS_MW timestamp
2521 public function getEmailAuthenticationTimestamp() {
2523 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2524 return $this->mEmailAuthenticated
;
2528 * Set the user's e-mail address
2529 * @param string $str New e-mail address
2531 public function setEmail( $str ) {
2533 if ( $str == $this->mEmail
) {
2536 $this->invalidateEmail();
2537 $this->mEmail
= $str;
2538 Hooks
::run( 'UserSetEmail', array( $this, &$this->mEmail
) );
2542 * Set the user's e-mail address and a confirmation mail if needed.
2545 * @param string $str New e-mail address
2548 public function setEmailWithConfirmation( $str ) {
2549 global $wgEnableEmail, $wgEmailAuthentication;
2551 if ( !$wgEnableEmail ) {
2552 return Status
::newFatal( 'emaildisabled' );
2555 $oldaddr = $this->getEmail();
2556 if ( $str === $oldaddr ) {
2557 return Status
::newGood( true );
2560 $this->setEmail( $str );
2562 if ( $str !== '' && $wgEmailAuthentication ) {
2563 // Send a confirmation request to the new address if needed
2564 $type = $oldaddr != '' ?
'changed' : 'set';
2565 $result = $this->sendConfirmationMail( $type );
2566 if ( $result->isGood() ) {
2567 // Say to the caller that a confirmation mail has been sent
2568 $result->value
= 'eauth';
2571 $result = Status
::newGood( true );
2578 * Get the user's real name
2579 * @return string User's real name
2581 public function getRealName() {
2582 if ( !$this->isItemLoaded( 'realname' ) ) {
2586 return $this->mRealName
;
2590 * Set the user's real name
2591 * @param string $str New real name
2593 public function setRealName( $str ) {
2595 $this->mRealName
= $str;
2599 * Get the user's current setting for a given option.
2601 * @param string $oname The option to check
2602 * @param string $defaultOverride A default value returned if the option does not exist
2603 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2604 * @return string User's current value for the option
2605 * @see getBoolOption()
2606 * @see getIntOption()
2608 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2609 global $wgHiddenPrefs;
2610 $this->loadOptions();
2612 # We want 'disabled' preferences to always behave as the default value for
2613 # users, even if they have set the option explicitly in their settings (ie they
2614 # set it, and then it was disabled removing their ability to change it). But
2615 # we don't want to erase the preferences in the database in case the preference
2616 # is re-enabled again. So don't touch $mOptions, just override the returned value
2617 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2618 return self
::getDefaultOption( $oname );
2621 if ( array_key_exists( $oname, $this->mOptions
) ) {
2622 return $this->mOptions
[$oname];
2624 return $defaultOverride;
2629 * Get all user's options
2631 * @param int $flags Bitwise combination of:
2632 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2633 * to the default value. (Since 1.25)
2636 public function getOptions( $flags = 0 ) {
2637 global $wgHiddenPrefs;
2638 $this->loadOptions();
2639 $options = $this->mOptions
;
2641 # We want 'disabled' preferences to always behave as the default value for
2642 # users, even if they have set the option explicitly in their settings (ie they
2643 # set it, and then it was disabled removing their ability to change it). But
2644 # we don't want to erase the preferences in the database in case the preference
2645 # is re-enabled again. So don't touch $mOptions, just override the returned value
2646 foreach ( $wgHiddenPrefs as $pref ) {
2647 $default = self
::getDefaultOption( $pref );
2648 if ( $default !== null ) {
2649 $options[$pref] = $default;
2653 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2654 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2661 * Get the user's current setting for a given option, as a boolean value.
2663 * @param string $oname The option to check
2664 * @return bool User's current value for the option
2667 public function getBoolOption( $oname ) {
2668 return (bool)$this->getOption( $oname );
2672 * Get the user's current setting for a given option, as an integer value.
2674 * @param string $oname The option to check
2675 * @param int $defaultOverride A default value returned if the option does not exist
2676 * @return int User's current value for the option
2679 public function getIntOption( $oname, $defaultOverride = 0 ) {
2680 $val = $this->getOption( $oname );
2682 $val = $defaultOverride;
2684 return intval( $val );
2688 * Set the given option for a user.
2690 * You need to call saveSettings() to actually write to the database.
2692 * @param string $oname The option to set
2693 * @param mixed $val New value to set
2695 public function setOption( $oname, $val ) {
2696 $this->loadOptions();
2698 // Explicitly NULL values should refer to defaults
2699 if ( is_null( $val ) ) {
2700 $val = self
::getDefaultOption( $oname );
2703 $this->mOptions
[$oname] = $val;
2707 * Get a token stored in the preferences (like the watchlist one),
2708 * resetting it if it's empty (and saving changes).
2710 * @param string $oname The option name to retrieve the token from
2711 * @return string|bool User's current value for the option, or false if this option is disabled.
2712 * @see resetTokenFromOption()
2714 * @deprecated 1.26 Applications should use the OAuth extension
2716 public function getTokenFromOption( $oname ) {
2717 global $wgHiddenPrefs;
2719 $id = $this->getId();
2720 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2724 $token = $this->getOption( $oname );
2726 // Default to a value based on the user token to avoid space
2727 // wasted on storing tokens for all users. When this option
2728 // is set manually by the user, only then is it stored.
2729 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2736 * Reset a token stored in the preferences (like the watchlist one).
2737 * *Does not* save user's preferences (similarly to setOption()).
2739 * @param string $oname The option name to reset the token in
2740 * @return string|bool New token value, or false if this option is disabled.
2741 * @see getTokenFromOption()
2744 public function resetTokenFromOption( $oname ) {
2745 global $wgHiddenPrefs;
2746 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2750 $token = MWCryptRand
::generateHex( 40 );
2751 $this->setOption( $oname, $token );
2756 * Return a list of the types of user options currently returned by
2757 * User::getOptionKinds().
2759 * Currently, the option kinds are:
2760 * - 'registered' - preferences which are registered in core MediaWiki or
2761 * by extensions using the UserGetDefaultOptions hook.
2762 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2763 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2764 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2765 * be used by user scripts.
2766 * - 'special' - "preferences" that are not accessible via User::getOptions
2767 * or User::setOptions.
2768 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2769 * These are usually legacy options, removed in newer versions.
2771 * The API (and possibly others) use this function to determine the possible
2772 * option types for validation purposes, so make sure to update this when a
2773 * new option kind is added.
2775 * @see User::getOptionKinds
2776 * @return array Option kinds
2778 public static function listOptionKinds() {
2781 'registered-multiselect',
2782 'registered-checkmatrix',
2790 * Return an associative array mapping preferences keys to the kind of a preference they're
2791 * used for. Different kinds are handled differently when setting or reading preferences.
2793 * See User::listOptionKinds for the list of valid option types that can be provided.
2795 * @see User::listOptionKinds
2796 * @param IContextSource $context
2797 * @param array $options Assoc. array with options keys to check as keys.
2798 * Defaults to $this->mOptions.
2799 * @return array The key => kind mapping data
2801 public function getOptionKinds( IContextSource
$context, $options = null ) {
2802 $this->loadOptions();
2803 if ( $options === null ) {
2804 $options = $this->mOptions
;
2807 $prefs = Preferences
::getPreferences( $this, $context );
2810 // Pull out the "special" options, so they don't get converted as
2811 // multiselect or checkmatrix.
2812 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2813 foreach ( $specialOptions as $name => $value ) {
2814 unset( $prefs[$name] );
2817 // Multiselect and checkmatrix options are stored in the database with
2818 // one key per option, each having a boolean value. Extract those keys.
2819 $multiselectOptions = array();
2820 foreach ( $prefs as $name => $info ) {
2821 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2822 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2823 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2824 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2826 foreach ( $opts as $value ) {
2827 $multiselectOptions["$prefix$value"] = true;
2830 unset( $prefs[$name] );
2833 $checkmatrixOptions = array();
2834 foreach ( $prefs as $name => $info ) {
2835 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2836 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2837 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2838 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2839 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2841 foreach ( $columns as $column ) {
2842 foreach ( $rows as $row ) {
2843 $checkmatrixOptions["$prefix$column-$row"] = true;
2847 unset( $prefs[$name] );
2851 // $value is ignored
2852 foreach ( $options as $key => $value ) {
2853 if ( isset( $prefs[$key] ) ) {
2854 $mapping[$key] = 'registered';
2855 } elseif ( isset( $multiselectOptions[$key] ) ) {
2856 $mapping[$key] = 'registered-multiselect';
2857 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2858 $mapping[$key] = 'registered-checkmatrix';
2859 } elseif ( isset( $specialOptions[$key] ) ) {
2860 $mapping[$key] = 'special';
2861 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2862 $mapping[$key] = 'userjs';
2864 $mapping[$key] = 'unused';
2872 * Reset certain (or all) options to the site defaults
2874 * The optional parameter determines which kinds of preferences will be reset.
2875 * Supported values are everything that can be reported by getOptionKinds()
2876 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2878 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2879 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2880 * for backwards-compatibility.
2881 * @param IContextSource|null $context Context source used when $resetKinds
2882 * does not contain 'all', passed to getOptionKinds().
2883 * Defaults to RequestContext::getMain() when null.
2885 public function resetOptions(
2886 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2887 IContextSource
$context = null
2890 $defaultOptions = self
::getDefaultOptions();
2892 if ( !is_array( $resetKinds ) ) {
2893 $resetKinds = array( $resetKinds );
2896 if ( in_array( 'all', $resetKinds ) ) {
2897 $newOptions = $defaultOptions;
2899 if ( $context === null ) {
2900 $context = RequestContext
::getMain();
2903 $optionKinds = $this->getOptionKinds( $context );
2904 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2905 $newOptions = array();
2907 // Use default values for the options that should be deleted, and
2908 // copy old values for the ones that shouldn't.
2909 foreach ( $this->mOptions
as $key => $value ) {
2910 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2911 if ( array_key_exists( $key, $defaultOptions ) ) {
2912 $newOptions[$key] = $defaultOptions[$key];
2915 $newOptions[$key] = $value;
2920 Hooks
::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2922 $this->mOptions
= $newOptions;
2923 $this->mOptionsLoaded
= true;
2927 * Get the user's preferred date format.
2928 * @return string User's preferred date format
2930 public function getDatePreference() {
2931 // Important migration for old data rows
2932 if ( is_null( $this->mDatePreference
) ) {
2934 $value = $this->getOption( 'date' );
2935 $map = $wgLang->getDatePreferenceMigrationMap();
2936 if ( isset( $map[$value] ) ) {
2937 $value = $map[$value];
2939 $this->mDatePreference
= $value;
2941 return $this->mDatePreference
;
2945 * Determine based on the wiki configuration and the user's options,
2946 * whether this user must be over HTTPS no matter what.
2950 public function requiresHTTPS() {
2951 global $wgSecureLogin;
2952 if ( !$wgSecureLogin ) {
2955 $https = $this->getBoolOption( 'prefershttps' );
2956 Hooks
::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2958 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2965 * Get the user preferred stub threshold
2969 public function getStubThreshold() {
2970 global $wgMaxArticleSize; # Maximum article size, in Kb
2971 $threshold = $this->getIntOption( 'stubthreshold' );
2972 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2973 // If they have set an impossible value, disable the preference
2974 // so we can use the parser cache again.
2981 * Get the permissions this user has.
2982 * @return array Array of String permission names
2984 public function getRights() {
2985 if ( is_null( $this->mRights
) ) {
2986 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2988 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
2989 if ( $allowedRights !== null ) {
2990 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
2993 Hooks
::run( 'UserGetRights', array( $this, &$this->mRights
) );
2994 // Force reindexation of rights when a hook has unset one of them
2995 $this->mRights
= array_values( array_unique( $this->mRights
) );
2997 return $this->mRights
;
3001 * Get the list of explicit group memberships this user has.
3002 * The implicit * and user groups are not included.
3003 * @return array Array of String internal group names
3005 public function getGroups() {
3007 $this->loadGroups();
3008 return $this->mGroups
;
3012 * Get the list of implicit group memberships this user has.
3013 * This includes all explicit groups, plus 'user' if logged in,
3014 * '*' for all accounts, and autopromoted groups
3015 * @param bool $recache Whether to avoid the cache
3016 * @return array Array of String internal group names
3018 public function getEffectiveGroups( $recache = false ) {
3019 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3020 $this->mEffectiveGroups
= array_unique( array_merge(
3021 $this->getGroups(), // explicit groups
3022 $this->getAutomaticGroups( $recache ) // implicit groups
3024 // Hook for additional groups
3025 Hooks
::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
3026 // Force reindexation of groups when a hook has unset one of them
3027 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3029 return $this->mEffectiveGroups
;
3033 * Get the list of implicit group memberships this user has.
3034 * This includes 'user' if logged in, '*' for all accounts,
3035 * and autopromoted groups
3036 * @param bool $recache Whether to avoid the cache
3037 * @return array Array of String internal group names
3039 public function getAutomaticGroups( $recache = false ) {
3040 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3041 $this->mImplicitGroups
= array( '*' );
3042 if ( $this->getId() ) {
3043 $this->mImplicitGroups
[] = 'user';
3045 $this->mImplicitGroups
= array_unique( array_merge(
3046 $this->mImplicitGroups
,
3047 Autopromote
::getAutopromoteGroups( $this )
3051 // Assure data consistency with rights/groups,
3052 // as getEffectiveGroups() depends on this function
3053 $this->mEffectiveGroups
= null;
3056 return $this->mImplicitGroups
;
3060 * Returns the groups the user has belonged to.
3062 * The user may still belong to the returned groups. Compare with getGroups().
3064 * The function will not return groups the user had belonged to before MW 1.17
3066 * @return array Names of the groups the user has belonged to.
3068 public function getFormerGroups() {
3071 if ( is_null( $this->mFormerGroups
) ) {
3072 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3073 ?
wfGetDB( DB_MASTER
)
3074 : wfGetDB( DB_SLAVE
);
3075 $res = $db->select( 'user_former_groups',
3076 array( 'ufg_group' ),
3077 array( 'ufg_user' => $this->mId
),
3079 $this->mFormerGroups
= array();
3080 foreach ( $res as $row ) {
3081 $this->mFormerGroups
[] = $row->ufg_group
;
3085 return $this->mFormerGroups
;
3089 * Get the user's edit count.
3090 * @return int|null Null for anonymous users
3092 public function getEditCount() {
3093 if ( !$this->getId() ) {
3097 if ( $this->mEditCount
=== null ) {
3098 /* Populate the count, if it has not been populated yet */
3099 $dbr = wfGetDB( DB_SLAVE
);
3100 // check if the user_editcount field has been initialized
3101 $count = $dbr->selectField(
3102 'user', 'user_editcount',
3103 array( 'user_id' => $this->mId
),
3107 if ( $count === null ) {
3108 // it has not been initialized. do so.
3109 $count = $this->initEditCount();
3111 $this->mEditCount
= $count;
3113 return (int)$this->mEditCount
;
3117 * Add the user to the given group.
3118 * This takes immediate effect.
3119 * @param string $group Name of the group to add
3122 public function addGroup( $group ) {
3125 if ( !Hooks
::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3129 $dbw = wfGetDB( DB_MASTER
);
3130 if ( $this->getId() ) {
3131 $dbw->insert( 'user_groups',
3133 'ug_user' => $this->getID(),
3134 'ug_group' => $group,
3137 array( 'IGNORE' ) );
3140 $this->loadGroups();
3141 $this->mGroups
[] = $group;
3142 // In case loadGroups was not called before, we now have the right twice.
3143 // Get rid of the duplicate.
3144 $this->mGroups
= array_unique( $this->mGroups
);
3146 // Refresh the groups caches, and clear the rights cache so it will be
3147 // refreshed on the next call to $this->getRights().
3148 $this->getEffectiveGroups( true );
3149 $this->mRights
= null;
3151 $this->invalidateCache();
3157 * Remove the user from the given group.
3158 * This takes immediate effect.
3159 * @param string $group Name of the group to remove
3162 public function removeGroup( $group ) {
3164 if ( !Hooks
::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3168 $dbw = wfGetDB( DB_MASTER
);
3169 $dbw->delete( 'user_groups',
3171 'ug_user' => $this->getID(),
3172 'ug_group' => $group,
3175 // Remember that the user was in this group
3176 $dbw->insert( 'user_former_groups',
3178 'ufg_user' => $this->getID(),
3179 'ufg_group' => $group,
3185 $this->loadGroups();
3186 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3188 // Refresh the groups caches, and clear the rights cache so it will be
3189 // refreshed on the next call to $this->getRights().
3190 $this->getEffectiveGroups( true );
3191 $this->mRights
= null;
3193 $this->invalidateCache();
3199 * Get whether the user is logged in
3202 public function isLoggedIn() {
3203 return $this->getID() != 0;
3207 * Get whether the user is anonymous
3210 public function isAnon() {
3211 return !$this->isLoggedIn();
3215 * Check if user is allowed to access a feature / make an action
3217 * @param string ... Permissions to test
3218 * @return bool True if user is allowed to perform *any* of the given actions
3220 public function isAllowedAny() {
3221 $permissions = func_get_args();
3222 foreach ( $permissions as $permission ) {
3223 if ( $this->isAllowed( $permission ) ) {
3232 * @param string ... Permissions to test
3233 * @return bool True if the user is allowed to perform *all* of the given actions
3235 public function isAllowedAll() {
3236 $permissions = func_get_args();
3237 foreach ( $permissions as $permission ) {
3238 if ( !$this->isAllowed( $permission ) ) {
3246 * Internal mechanics of testing a permission
3247 * @param string $action
3250 public function isAllowed( $action = '' ) {
3251 if ( $action === '' ) {
3252 return true; // In the spirit of DWIM
3254 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3255 // by misconfiguration: 0 == 'foo'
3256 return in_array( $action, $this->getRights(), true );
3260 * Check whether to enable recent changes patrol features for this user
3261 * @return bool True or false
3263 public function useRCPatrol() {
3264 global $wgUseRCPatrol;
3265 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3269 * Check whether to enable new pages patrol features for this user
3270 * @return bool True or false
3272 public function useNPPatrol() {
3273 global $wgUseRCPatrol, $wgUseNPPatrol;
3275 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3276 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3281 * Check whether to enable new files patrol features for this user
3282 * @return bool True or false
3284 public function useFilePatrol() {
3285 global $wgUseRCPatrol, $wgUseFilePatrol;
3287 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3288 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3293 * Get the WebRequest object to use with this object
3295 * @return WebRequest
3297 public function getRequest() {
3298 if ( $this->mRequest
) {
3299 return $this->mRequest
;
3307 * Get a WatchedItem for this user and $title.
3309 * @since 1.22 $checkRights parameter added
3310 * @param Title $title
3311 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3312 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3313 * @return WatchedItem
3315 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3316 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3318 if ( isset( $this->mWatchedItems
[$key] ) ) {
3319 return $this->mWatchedItems
[$key];
3322 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3323 $this->mWatchedItems
= array();
3326 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3327 return $this->mWatchedItems
[$key];
3331 * Check the watched status of an article.
3332 * @since 1.22 $checkRights parameter added
3333 * @param Title $title Title of the article to look at
3334 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3335 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3338 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3339 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3344 * @since 1.22 $checkRights parameter added
3345 * @param Title $title Title of the article to look at
3346 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3347 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3349 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3350 $this->getWatchedItem( $title, $checkRights )->addWatch();
3351 $this->invalidateCache();
3355 * Stop watching an article.
3356 * @since 1.22 $checkRights parameter added
3357 * @param Title $title Title of the article to look at
3358 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3359 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3361 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3362 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3363 $this->invalidateCache();
3367 * Clear the user's notification timestamp for the given title.
3368 * If e-notif e-mails are on, they will receive notification mails on
3369 * the next change of the page if it's watched etc.
3370 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3371 * @param Title $title Title of the article to look at
3372 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3374 public function clearNotification( &$title, $oldid = 0 ) {
3375 global $wgUseEnotif, $wgShowUpdatedMarker;
3377 // Do nothing if the database is locked to writes
3378 if ( wfReadOnly() ) {
3382 // Do nothing if not allowed to edit the watchlist
3383 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3387 // If we're working on user's talk page, we should update the talk page message indicator
3388 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3389 if ( !Hooks
::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3394 // Try to update the DB post-send and only if needed...
3395 DeferredUpdates
::addCallableUpdate( function() use ( $that, $title, $oldid ) {
3396 if ( !$that->getNewtalk() ) {
3397 return; // no notifications to clear
3400 // Delete the last notifications (they stack up)
3401 $that->setNewtalk( false );
3403 // If there is a new, unseen, revision, use its timestamp
3405 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3408 $that->setNewtalk( true, Revision
::newFromId( $nextid ) );
3413 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3417 if ( $this->isAnon() ) {
3418 // Nothing else to do...
3422 // Only update the timestamp if the page is being watched.
3423 // The query to find out if it is watched is cached both in memcached and per-invocation,
3424 // and when it does have to be executed, it can be on a slave
3425 // If this is the user's newtalk page, we always update the timestamp
3427 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3431 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3432 $force, $oldid, WatchedItem
::DEFERRED
3437 * Resets all of the given user's page-change notification timestamps.
3438 * If e-notif e-mails are on, they will receive notification mails on
3439 * the next change of any watched page.
3440 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3442 public function clearAllNotifications() {
3443 if ( wfReadOnly() ) {
3447 // Do nothing if not allowed to edit the watchlist
3448 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3452 global $wgUseEnotif, $wgShowUpdatedMarker;
3453 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3454 $this->setNewtalk( false );
3457 $id = $this->getId();
3459 $dbw = wfGetDB( DB_MASTER
);
3460 $dbw->update( 'watchlist',
3461 array( /* SET */ 'wl_notificationtimestamp' => null ),
3462 array( /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ),
3465 // We also need to clear here the "you have new message" notification for the own user_talk page;
3466 // it's cleared one page view later in WikiPage::doViewUpdates().
3471 * Set a cookie on the user's client. Wrapper for
3472 * WebResponse::setCookie
3473 * @deprecated since 1.27
3474 * @param string $name Name of the cookie to set
3475 * @param string $value Value to set
3476 * @param int $exp Expiration time, as a UNIX time value;
3477 * if 0 or not specified, use the default $wgCookieExpiration
3478 * @param bool $secure
3479 * true: Force setting the secure attribute when setting the cookie
3480 * false: Force NOT setting the secure attribute when setting the cookie
3481 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3482 * @param array $params Array of options sent passed to WebResponse::setcookie()
3483 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3486 protected function setCookie(
3487 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3489 wfDeprecated( __METHOD__
, '1.27' );
3490 if ( $request === null ) {
3491 $request = $this->getRequest();
3493 $params['secure'] = $secure;
3494 $request->response()->setCookie( $name, $value, $exp, $params );
3498 * Clear a cookie on the user's client
3499 * @deprecated since 1.27
3500 * @param string $name Name of the cookie to clear
3501 * @param bool $secure
3502 * true: Force setting the secure attribute when setting the cookie
3503 * false: Force NOT setting the secure attribute when setting the cookie
3504 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3505 * @param array $params Array of options sent passed to WebResponse::setcookie()
3507 protected function clearCookie( $name, $secure = null, $params = array() ) {
3508 wfDeprecated( __METHOD__
, '1.27' );
3509 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3513 * Set an extended login cookie on the user's client. The expiry of the cookie
3514 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3517 * @see User::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 bool $secure
3523 * true: Force setting the secure attribute when setting the cookie
3524 * false: Force NOT setting the secure attribute when setting the cookie
3525 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3527 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3528 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3530 wfDeprecated( __METHOD__
, '1.27' );
3533 $exp +
= $wgExtendedLoginCookieExpiration !== null
3534 ?
$wgExtendedLoginCookieExpiration
3535 : $wgCookieExpiration;
3537 $this->setCookie( $name, $value, $exp, $secure );
3541 * Persist this user's session (e.g. set cookies)
3543 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3545 * @param bool $secure Whether to force secure/insecure cookies or use default
3546 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3548 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3550 if ( 0 == $this->mId
) {
3554 $session = $this->getRequest()->getSession();
3555 if ( $request && $session->getRequest() !== $request ) {
3556 $session = $session->sessionWithRequest( $request );
3558 $delay = $session->delaySave();
3560 if ( !$session->getUser()->equals( $this ) ) {
3561 if ( !$session->canSetUser() ) {
3562 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3563 ->warning( __METHOD__
.
3564 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3568 $session->setUser( $this );
3571 $session->setRememberUser( $rememberMe );
3572 if ( $secure !== null ) {
3573 $session->setForceHTTPS( $secure );
3576 $session->persist();
3578 ScopedCallback
::consume( $delay );
3582 * Log this user out.
3584 public function logout() {
3585 if ( Hooks
::run( 'UserLogout', array( &$this ) ) ) {
3591 * Clear the user's session, and reset the instance cache.
3594 public function doLogout() {
3595 $session = $this->getRequest()->getSession();
3596 if ( !$session->canSetUser() ) {
3597 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3598 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3599 } elseif ( !$session->getUser()->equals( $this ) ) {
3600 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3601 ->warning( __METHOD__
.
3602 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3604 // But we still may as well make this user object anon
3605 $this->clearInstanceCache( 'defaults' );
3607 $this->clearInstanceCache( 'defaults' );
3608 $delay = $session->delaySave();
3609 $session->setLoggedOutTimestamp( time() );
3610 $session->setUser( new User
);
3611 $session->set( 'wsUserID', 0 ); // Other code expects this
3612 ScopedCallback
::consume( $delay );
3617 * Save this user's settings into the database.
3618 * @todo Only rarely do all these fields need to be set!
3620 public function saveSettings() {
3621 if ( wfReadOnly() ) {
3622 // @TODO: caller should deal with this instead!
3623 // This should really just be an exception.
3624 MWExceptionHandler
::logException( new DBExpectedError(
3626 "Could not update user with ID '{$this->mId}'; DB is read-only."
3632 if ( 0 == $this->mId
) {
3636 // Get a new user_touched that is higher than the old one.
3637 // This will be used for a CAS check as a last-resort safety
3638 // check against race conditions and slave lag.
3639 $oldTouched = $this->mTouched
;
3640 $newTouched = $this->newTouchedTimestamp();
3642 $dbw = wfGetDB( DB_MASTER
);
3643 $dbw->update( 'user',
3645 'user_name' => $this->mName
,
3646 'user_real_name' => $this->mRealName
,
3647 'user_email' => $this->mEmail
,
3648 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3649 'user_touched' => $dbw->timestamp( $newTouched ),
3650 'user_token' => strval( $this->mToken
),
3651 'user_email_token' => $this->mEmailToken
,
3652 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3653 ), array( /* WHERE */
3654 'user_id' => $this->mId
,
3655 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3659 if ( !$dbw->affectedRows() ) {
3660 // Maybe the problem was a missed cache update; clear it to be safe
3661 $this->clearSharedCache( 'refresh' );
3662 // User was changed in the meantime or loaded with stale data
3663 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3664 throw new MWException(
3665 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3666 " the version of the user to be saved is older than the current version."
3670 $this->mTouched
= $newTouched;
3671 $this->saveOptions();
3673 Hooks
::run( 'UserSaveSettings', array( $this ) );
3674 $this->clearSharedCache();
3675 $this->getUserPage()->invalidateCache();
3679 * If only this user's username is known, and it exists, return the user ID.
3681 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3684 public function idForName( $flags = 0 ) {
3685 $s = trim( $this->getName() );
3690 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3691 ?
wfGetDB( DB_MASTER
)
3692 : wfGetDB( DB_SLAVE
);
3694 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3695 ?
array( 'LOCK IN SHARE MODE' )
3698 $id = $db->selectField( 'user',
3699 'user_id', array( 'user_name' => $s ), __METHOD__
, $options );
3705 * Add a user to the database, return the user object
3707 * @param string $name Username to add
3708 * @param array $params Array of Strings Non-default parameters to save to
3709 * the database as user_* fields:
3710 * - email: The user's email address.
3711 * - email_authenticated: The email authentication timestamp.
3712 * - real_name: The user's real name.
3713 * - options: An associative array of non-default options.
3714 * - token: Random authentication token. Do not set.
3715 * - registration: Registration timestamp. Do not set.
3717 * @return User|null User object, or null if the username already exists.
3719 public static function createNew( $name, $params = array() ) {
3720 foreach ( array( 'password', 'newpassword', 'newpass_time', 'password_expires' ) as $field ) {
3721 if ( isset( $params[$field] ) ) {
3722 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3723 unset( $params[$field] );
3729 $user->setToken(); // init token
3730 if ( isset( $params['options'] ) ) {
3731 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3732 unset( $params['options'] );
3734 $dbw = wfGetDB( DB_MASTER
);
3735 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3737 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3740 'user_id' => $seqVal,
3741 'user_name' => $name,
3742 'user_password' => $noPass,
3743 'user_newpassword' => $noPass,
3744 'user_email' => $user->mEmail
,
3745 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3746 'user_real_name' => $user->mRealName
,
3747 'user_token' => strval( $user->mToken
),
3748 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3749 'user_editcount' => 0,
3750 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3752 foreach ( $params as $name => $value ) {
3753 $fields["user_$name"] = $value;
3755 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3756 if ( $dbw->affectedRows() ) {
3757 $newUser = User
::newFromId( $dbw->insertId() );
3765 * Add this existing user object to the database. If the user already
3766 * exists, a fatal status object is returned, and the user object is
3767 * initialised with the data from the database.
3769 * Previously, this function generated a DB error due to a key conflict
3770 * if the user already existed. Many extension callers use this function
3771 * in code along the lines of:
3773 * $user = User::newFromName( $name );
3774 * if ( !$user->isLoggedIn() ) {
3775 * $user->addToDatabase();
3777 * // do something with $user...
3779 * However, this was vulnerable to a race condition (bug 16020). By
3780 * initialising the user object if the user exists, we aim to support this
3781 * calling sequence as far as possible.
3783 * Note that if the user exists, this function will acquire a write lock,
3784 * so it is still advisable to make the call conditional on isLoggedIn(),
3785 * and to commit the transaction after calling.
3787 * @throws MWException
3790 public function addToDatabase() {
3792 if ( !$this->mToken
) {
3793 $this->setToken(); // init token
3796 $this->mTouched
= $this->newTouchedTimestamp();
3798 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3800 $dbw = wfGetDB( DB_MASTER
);
3801 $inWrite = $dbw->writesOrCallbacksPending();
3802 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3803 $dbw->insert( 'user',
3805 'user_id' => $seqVal,
3806 'user_name' => $this->mName
,
3807 'user_password' => $noPass,
3808 'user_newpassword' => $noPass,
3809 'user_email' => $this->mEmail
,
3810 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3811 'user_real_name' => $this->mRealName
,
3812 'user_token' => strval( $this->mToken
),
3813 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3814 'user_editcount' => 0,
3815 'user_touched' => $dbw->timestamp( $this->mTouched
),
3819 if ( !$dbw->affectedRows() ) {
3820 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3821 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3823 // Can't commit due to pending writes that may need atomicity.
3824 // This may cause some lock contention unlike the case below.
3825 $options = array( 'LOCK IN SHARE MODE' );
3826 $flags = self
::READ_LOCKING
;
3828 // Often, this case happens early in views before any writes when
3829 // using CentralAuth. It's should be OK to commit and break the snapshot.
3830 $dbw->commit( __METHOD__
, 'flush' );
3832 $flags = self
::READ_LATEST
;
3834 $this->mId
= $dbw->selectField( 'user', 'user_id',
3835 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3838 if ( $this->loadFromDatabase( $flags ) ) {
3843 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3844 "to insert user '{$this->mName}' row, but it was not present in select!" );
3846 return Status
::newFatal( 'userexists' );
3848 $this->mId
= $dbw->insertId();
3849 self
::$idCacheByName[$this->mName
] = $this->mId
;
3851 // Clear instance cache other than user table data, which is already accurate
3852 $this->clearInstanceCache();
3854 $this->saveOptions();
3855 return Status
::newGood();
3859 * If this user is logged-in and blocked,
3860 * block any IP address they've successfully logged in from.
3861 * @return bool A block was spread
3863 public function spreadAnyEditBlock() {
3864 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3865 return $this->spreadBlock();
3871 * If this (non-anonymous) user is blocked,
3872 * block the IP address they've successfully logged in from.
3873 * @return bool A block was spread
3875 protected function spreadBlock() {
3876 wfDebug( __METHOD__
. "()\n" );
3878 if ( $this->mId
== 0 ) {
3882 $userblock = Block
::newFromTarget( $this->getName() );
3883 if ( !$userblock ) {
3887 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3891 * Get whether the user is explicitly blocked from account creation.
3892 * @return bool|Block
3894 public function isBlockedFromCreateAccount() {
3895 $this->getBlockedStatus();
3896 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3897 return $this->mBlock
;
3900 # bug 13611: if the IP address the user is trying to create an account from is
3901 # blocked with createaccount disabled, prevent new account creation there even
3902 # when the user is logged in
3903 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3904 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3906 return $this->mBlockedFromCreateAccount
instanceof Block
3907 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3908 ?
$this->mBlockedFromCreateAccount
3913 * Get whether the user is blocked from using Special:Emailuser.
3916 public function isBlockedFromEmailuser() {
3917 $this->getBlockedStatus();
3918 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3922 * Get whether the user is allowed to create an account.
3925 public function isAllowedToCreateAccount() {
3926 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3930 * Get this user's personal page title.
3932 * @return Title User's personal page title
3934 public function getUserPage() {
3935 return Title
::makeTitle( NS_USER
, $this->getName() );
3939 * Get this user's talk page title.
3941 * @return Title User's talk page title
3943 public function getTalkPage() {
3944 $title = $this->getUserPage();
3945 return $title->getTalkPage();
3949 * Determine whether the user is a newbie. Newbies are either
3950 * anonymous IPs, or the most recently created accounts.
3953 public function isNewbie() {
3954 return !$this->isAllowed( 'autoconfirmed' );
3958 * Check to see if the given clear-text password is one of the accepted passwords
3959 * @deprecated since 1.27. AuthManager is coming.
3960 * @param string $password User password
3961 * @return bool True if the given password is correct, otherwise False
3963 public function checkPassword( $password ) {
3964 global $wgAuth, $wgLegacyEncoding;
3968 // Some passwords will give a fatal Status, which means there is
3969 // some sort of technical or security reason for this password to
3970 // be completely invalid and should never be checked (e.g., T64685)
3971 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
3975 // Certain authentication plugins do NOT want to save
3976 // domain passwords in a mysql database, so we should
3977 // check this (in case $wgAuth->strict() is false).
3978 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3980 } elseif ( $wgAuth->strict() ) {
3981 // Auth plugin doesn't allow local authentication
3983 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3984 // Auth plugin doesn't allow local authentication for this user name
3988 $passwordFactory = new PasswordFactory();
3989 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
3990 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3991 ?
wfGetDB( DB_MASTER
)
3992 : wfGetDB( DB_SLAVE
);
3995 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
3996 'user', 'user_password', array( 'user_id' => $this->getId() ), __METHOD__
3998 } catch ( PasswordError
$e ) {
3999 wfDebug( 'Invalid password hash found in database.' );
4000 $mPassword = PasswordFactory
::newInvalidPassword();
4003 if ( !$mPassword->equals( $password ) ) {
4004 if ( $wgLegacyEncoding ) {
4005 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4006 // Check for this with iconv
4007 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4008 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4016 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4017 $this->setPasswordInternal( $password );
4024 * Check if the given clear-text password matches the temporary password
4025 * sent by e-mail for password reset operations.
4027 * @deprecated since 1.27. AuthManager is coming.
4028 * @param string $plaintext
4029 * @return bool True if matches, false otherwise
4031 public function checkTemporaryPassword( $plaintext ) {
4032 global $wgNewPasswordExpiry;
4036 $passwordFactory = new PasswordFactory();
4037 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4038 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4039 ?
wfGetDB( DB_MASTER
)
4040 : wfGetDB( DB_SLAVE
);
4042 $row = $db->selectRow(
4044 array( 'user_newpassword', 'user_newpass_time' ),
4045 array( 'user_id' => $this->getId() ),
4049 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4050 } catch ( PasswordError
$e ) {
4051 wfDebug( 'Invalid password hash found in database.' );
4052 $newPassword = PasswordFactory
::newInvalidPassword();
4055 if ( $newPassword->equals( $plaintext ) ) {
4056 if ( is_null( $row->user_newpass_time
) ) {
4059 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4060 return ( time() < $expiry );
4067 * Internal implementation for self::getEditToken() and
4068 * self::matchEditToken().
4070 * @param string|array $salt
4071 * @param WebRequest $request
4072 * @param string|int $timestamp
4075 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
4076 if ( $this->isAnon() ) {
4077 return self
::EDIT_TOKEN_SUFFIX
;
4079 $token = $request->getSessionData( 'wsEditToken' );
4080 if ( $token === null ) {
4081 $token = MWCryptRand
::generateHex( 32 );
4082 $request->setSessionData( 'wsEditToken', $token );
4084 if ( is_array( $salt ) ) {
4085 $salt = implode( '|', $salt );
4087 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
4088 dechex( $timestamp ) .
4089 self
::EDIT_TOKEN_SUFFIX
;
4094 * Initialize (if necessary) and return a session token value
4095 * which can be used in edit forms to show that the user's
4096 * login credentials aren't being hijacked with a foreign form
4101 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4102 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4103 * @return string The new edit token
4105 public function getEditToken( $salt = '', $request = null ) {
4106 return $this->getEditTokenAtTimestamp(
4107 $salt, $request ?
: $this->getRequest(), wfTimestamp()
4112 * Get the embedded timestamp from a token.
4113 * @param string $val Input token
4116 public static function getEditTokenTimestamp( $val ) {
4117 $suffixLen = strlen( self
::EDIT_TOKEN_SUFFIX
);
4118 if ( strlen( $val ) <= 32 +
$suffixLen ) {
4122 return hexdec( substr( $val, 32, -$suffixLen ) );
4126 * Check given value against the token value stored in the session.
4127 * A match should confirm that the form was submitted from the
4128 * user's own login session, not a form submission from a third-party
4131 * @param string $val Input value to compare
4132 * @param string $salt Optional function-specific data for hashing
4133 * @param WebRequest|null $request Object to use or null to use $wgRequest
4134 * @param int $maxage Fail tokens older than this, in seconds
4135 * @return bool Whether the token matches
4137 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4138 if ( $this->isAnon() ) {
4139 return $val === self
::EDIT_TOKEN_SUFFIX
;
4142 $timestamp = self
::getEditTokenTimestamp( $val );
4143 if ( $timestamp === null ) {
4146 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
4151 $sessionToken = $this->getEditTokenAtTimestamp(
4152 $salt, $request ?
: $this->getRequest(), $timestamp
4155 if ( !hash_equals( $sessionToken, $val ) ) {
4156 wfDebug( "User::matchEditToken: broken session data\n" );
4159 return hash_equals( $sessionToken, $val );
4163 * Check given value against the token value stored in the session,
4164 * ignoring the suffix.
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 matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4173 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4174 return $this->matchEditToken( $val, $salt, $request, $maxage );
4178 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4179 * mail to the user's given address.
4181 * @param string $type Message to send, either "created", "changed" or "set"
4184 public function sendConfirmationMail( $type = 'created' ) {
4186 $expiration = null; // gets passed-by-ref and defined in next line.
4187 $token = $this->confirmationToken( $expiration );
4188 $url = $this->confirmationTokenUrl( $token );
4189 $invalidateURL = $this->invalidationTokenUrl( $token );
4190 $this->saveSettings();
4192 if ( $type == 'created' ||
$type === false ) {
4193 $message = 'confirmemail_body';
4194 } elseif ( $type === true ) {
4195 $message = 'confirmemail_body_changed';
4197 // Messages: confirmemail_body_changed, confirmemail_body_set
4198 $message = 'confirmemail_body_' . $type;
4201 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4202 wfMessage( $message,
4203 $this->getRequest()->getIP(),
4206 $wgLang->userTimeAndDate( $expiration, $this ),
4208 $wgLang->userDate( $expiration, $this ),
4209 $wgLang->userTime( $expiration, $this ) )->text() );
4213 * Send an e-mail to this user's account. Does not check for
4214 * confirmed status or validity.
4216 * @param string $subject Message subject
4217 * @param string $body Message body
4218 * @param User|null $from Optional sending user; if unspecified, default
4219 * $wgPasswordSender will be used.
4220 * @param string $replyto Reply-To address
4223 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4224 global $wgPasswordSender;
4226 if ( $from instanceof User
) {
4227 $sender = MailAddress
::newFromUser( $from );
4229 $sender = new MailAddress( $wgPasswordSender,
4230 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4232 $to = MailAddress
::newFromUser( $this );
4234 return UserMailer
::send( $to, $sender, $subject, $body, array(
4235 'replyTo' => $replyto,
4240 * Generate, store, and return a new e-mail confirmation code.
4241 * A hash (unsalted, since it's used as a key) is stored.
4243 * @note Call saveSettings() after calling this function to commit
4244 * this change to the database.
4246 * @param string &$expiration Accepts the expiration time
4247 * @return string New token
4249 protected function confirmationToken( &$expiration ) {
4250 global $wgUserEmailConfirmationTokenExpiry;
4252 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4253 $expiration = wfTimestamp( TS_MW
, $expires );
4255 $token = MWCryptRand
::generateHex( 32 );
4256 $hash = md5( $token );
4257 $this->mEmailToken
= $hash;
4258 $this->mEmailTokenExpires
= $expiration;
4263 * Return a URL the user can use to confirm their email address.
4264 * @param string $token Accepts the email confirmation token
4265 * @return string New token URL
4267 protected function confirmationTokenUrl( $token ) {
4268 return $this->getTokenUrl( 'ConfirmEmail', $token );
4272 * Return a URL the user can use to invalidate their email address.
4273 * @param string $token Accepts the email confirmation token
4274 * @return string New token URL
4276 protected function invalidationTokenUrl( $token ) {
4277 return $this->getTokenUrl( 'InvalidateEmail', $token );
4281 * Internal function to format the e-mail validation/invalidation URLs.
4282 * This uses a quickie hack to use the
4283 * hardcoded English names of the Special: pages, for ASCII safety.
4285 * @note Since these URLs get dropped directly into emails, using the
4286 * short English names avoids insanely long URL-encoded links, which
4287 * also sometimes can get corrupted in some browsers/mailers
4288 * (bug 6957 with Gmail and Internet Explorer).
4290 * @param string $page Special page
4291 * @param string $token Token
4292 * @return string Formatted URL
4294 protected function getTokenUrl( $page, $token ) {
4295 // Hack to bypass localization of 'Special:'
4296 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4297 return $title->getCanonicalURL();
4301 * Mark the e-mail address confirmed.
4303 * @note Call saveSettings() after calling this function to commit the change.
4307 public function confirmEmail() {
4308 // Check if it's already confirmed, so we don't touch the database
4309 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4310 if ( !$this->isEmailConfirmed() ) {
4311 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4312 Hooks
::run( 'ConfirmEmailComplete', array( $this ) );
4318 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4319 * address if it was already confirmed.
4321 * @note Call saveSettings() after calling this function to commit the change.
4322 * @return bool Returns true
4324 public function invalidateEmail() {
4326 $this->mEmailToken
= null;
4327 $this->mEmailTokenExpires
= null;
4328 $this->setEmailAuthenticationTimestamp( null );
4330 Hooks
::run( 'InvalidateEmailComplete', array( $this ) );
4335 * Set the e-mail authentication timestamp.
4336 * @param string $timestamp TS_MW timestamp
4338 public function setEmailAuthenticationTimestamp( $timestamp ) {
4340 $this->mEmailAuthenticated
= $timestamp;
4341 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4345 * Is this user allowed to send e-mails within limits of current
4346 * site configuration?
4349 public function canSendEmail() {
4350 global $wgEnableEmail, $wgEnableUserEmail;
4351 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4354 $canSend = $this->isEmailConfirmed();
4355 Hooks
::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4360 * Is this user allowed to receive e-mails within limits of current
4361 * site configuration?
4364 public function canReceiveEmail() {
4365 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4369 * Is this user's e-mail address valid-looking and confirmed within
4370 * limits of the current site configuration?
4372 * @note If $wgEmailAuthentication is on, this may require the user to have
4373 * confirmed their address by returning a code or using a password
4374 * sent to the address from the wiki.
4378 public function isEmailConfirmed() {
4379 global $wgEmailAuthentication;
4382 if ( Hooks
::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4383 if ( $this->isAnon() ) {
4386 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4389 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4399 * Check whether there is an outstanding request for e-mail confirmation.
4402 public function isEmailConfirmationPending() {
4403 global $wgEmailAuthentication;
4404 return $wgEmailAuthentication &&
4405 !$this->isEmailConfirmed() &&
4406 $this->mEmailToken
&&
4407 $this->mEmailTokenExpires
> wfTimestamp();
4411 * Get the timestamp of account creation.
4413 * @return string|bool|null Timestamp of account creation, false for
4414 * non-existent/anonymous user accounts, or null if existing account
4415 * but information is not in database.
4417 public function getRegistration() {
4418 if ( $this->isAnon() ) {
4422 return $this->mRegistration
;
4426 * Get the timestamp of the first edit
4428 * @return string|bool Timestamp of first edit, or false for
4429 * non-existent/anonymous user accounts.
4431 public function getFirstEditTimestamp() {
4432 if ( $this->getId() == 0 ) {
4433 return false; // anons
4435 $dbr = wfGetDB( DB_SLAVE
);
4436 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4437 array( 'rev_user' => $this->getId() ),
4439 array( 'ORDER BY' => 'rev_timestamp ASC' )
4442 return false; // no edits
4444 return wfTimestamp( TS_MW
, $time );
4448 * Get the permissions associated with a given list of groups
4450 * @param array $groups Array of Strings List of internal group names
4451 * @return array Array of Strings List of permission key names for given groups combined
4453 public static function getGroupPermissions( $groups ) {
4454 global $wgGroupPermissions, $wgRevokePermissions;
4456 // grant every granted permission first
4457 foreach ( $groups as $group ) {
4458 if ( isset( $wgGroupPermissions[$group] ) ) {
4459 $rights = array_merge( $rights,
4460 // array_filter removes empty items
4461 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4464 // now revoke the revoked permissions
4465 foreach ( $groups as $group ) {
4466 if ( isset( $wgRevokePermissions[$group] ) ) {
4467 $rights = array_diff( $rights,
4468 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4471 return array_unique( $rights );
4475 * Get all the groups who have a given permission
4477 * @param string $role Role to check
4478 * @return array Array of Strings List of internal group names with the given permission
4480 public static function getGroupsWithPermission( $role ) {
4481 global $wgGroupPermissions;
4482 $allowedGroups = array();
4483 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4484 if ( self
::groupHasPermission( $group, $role ) ) {
4485 $allowedGroups[] = $group;
4488 return $allowedGroups;
4492 * Check, if the given group has the given permission
4494 * If you're wanting to check whether all users have a permission, use
4495 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4499 * @param string $group Group to check
4500 * @param string $role Role to check
4503 public static function groupHasPermission( $group, $role ) {
4504 global $wgGroupPermissions, $wgRevokePermissions;
4505 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4506 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4510 * Check if all users may be assumed to have the given permission
4512 * We generally assume so if the right is granted to '*' and isn't revoked
4513 * on any group. It doesn't attempt to take grants or other extension
4514 * limitations on rights into account in the general case, though, as that
4515 * would require it to always return false and defeat the purpose.
4516 * Specifically, session-based rights restrictions (such as OAuth or bot
4517 * passwords) are applied based on the current session.
4520 * @param string $right Right to check
4523 public static function isEveryoneAllowed( $right ) {
4524 global $wgGroupPermissions, $wgRevokePermissions;
4525 static $cache = array();
4527 // Use the cached results, except in unit tests which rely on
4528 // being able change the permission mid-request
4529 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4530 return $cache[$right];
4533 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4534 $cache[$right] = false;
4538 // If it's revoked anywhere, then everyone doesn't have it
4539 foreach ( $wgRevokePermissions as $rights ) {
4540 if ( isset( $rights[$right] ) && $rights[$right] ) {
4541 $cache[$right] = false;
4546 // Remove any rights that aren't allowed to the global-session user
4547 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4548 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4549 $cache[$right] = false;
4553 // Allow extensions to say false
4554 if ( !Hooks
::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4555 $cache[$right] = false;
4559 $cache[$right] = true;
4564 * Get the localized descriptive name for a group, if it exists
4566 * @param string $group Internal group name
4567 * @return string Localized descriptive group name
4569 public static function getGroupName( $group ) {
4570 $msg = wfMessage( "group-$group" );
4571 return $msg->isBlank() ?
$group : $msg->text();
4575 * Get the localized descriptive name for a member of a group, if it exists
4577 * @param string $group Internal group name
4578 * @param string $username Username for gender (since 1.19)
4579 * @return string Localized name for group member
4581 public static function getGroupMember( $group, $username = '#' ) {
4582 $msg = wfMessage( "group-$group-member", $username );
4583 return $msg->isBlank() ?
$group : $msg->text();
4587 * Return the set of defined explicit groups.
4588 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4589 * are not included, as they are defined automatically, not in the database.
4590 * @return array Array of internal group names
4592 public static function getAllGroups() {
4593 global $wgGroupPermissions, $wgRevokePermissions;
4595 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4596 self
::getImplicitGroups()
4601 * Get a list of all available permissions.
4602 * @return string[] Array of permission names
4604 public static function getAllRights() {
4605 if ( self
::$mAllRights === false ) {
4606 global $wgAvailableRights;
4607 if ( count( $wgAvailableRights ) ) {
4608 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4610 self
::$mAllRights = self
::$mCoreRights;
4612 Hooks
::run( 'UserGetAllRights', array( &self
::$mAllRights ) );
4614 return self
::$mAllRights;
4618 * Get a list of implicit groups
4619 * @return array Array of Strings Array of internal group names
4621 public static function getImplicitGroups() {
4622 global $wgImplicitGroups;
4624 $groups = $wgImplicitGroups;
4625 # Deprecated, use $wgImplicitGroups instead
4626 Hooks
::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4632 * Get the title of a page describing a particular group
4634 * @param string $group Internal group name
4635 * @return Title|bool Title of the page if it exists, false otherwise
4637 public static function getGroupPage( $group ) {
4638 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4639 if ( $msg->exists() ) {
4640 $title = Title
::newFromText( $msg->text() );
4641 if ( is_object( $title ) ) {
4649 * Create a link to the group in HTML, if available;
4650 * else return the group name.
4652 * @param string $group Internal name of the group
4653 * @param string $text The text of the link
4654 * @return string HTML link to the group
4656 public static function makeGroupLinkHTML( $group, $text = '' ) {
4657 if ( $text == '' ) {
4658 $text = self
::getGroupName( $group );
4660 $title = self
::getGroupPage( $group );
4662 return Linker
::link( $title, htmlspecialchars( $text ) );
4664 return htmlspecialchars( $text );
4669 * Create a link to the group in Wikitext, if available;
4670 * else return the group name.
4672 * @param string $group Internal name of the group
4673 * @param string $text The text of the link
4674 * @return string Wikilink to the group
4676 public static function makeGroupLinkWiki( $group, $text = '' ) {
4677 if ( $text == '' ) {
4678 $text = self
::getGroupName( $group );
4680 $title = self
::getGroupPage( $group );
4682 $page = $title->getFullText();
4683 return "[[$page|$text]]";
4690 * Returns an array of the groups that a particular group can add/remove.
4692 * @param string $group The group to check for whether it can add/remove
4693 * @return array Array( 'add' => array( addablegroups ),
4694 * 'remove' => array( removablegroups ),
4695 * 'add-self' => array( addablegroups to self),
4696 * 'remove-self' => array( removable groups from self) )
4698 public static function changeableByGroup( $group ) {
4699 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4703 'remove' => array(),
4704 'add-self' => array(),
4705 'remove-self' => array()
4708 if ( empty( $wgAddGroups[$group] ) ) {
4709 // Don't add anything to $groups
4710 } elseif ( $wgAddGroups[$group] === true ) {
4711 // You get everything
4712 $groups['add'] = self
::getAllGroups();
4713 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4714 $groups['add'] = $wgAddGroups[$group];
4717 // Same thing for remove
4718 if ( empty( $wgRemoveGroups[$group] ) ) {
4720 } elseif ( $wgRemoveGroups[$group] === true ) {
4721 $groups['remove'] = self
::getAllGroups();
4722 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4723 $groups['remove'] = $wgRemoveGroups[$group];
4726 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4727 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4728 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4729 if ( is_int( $key ) ) {
4730 $wgGroupsAddToSelf['user'][] = $value;
4735 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4736 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4737 if ( is_int( $key ) ) {
4738 $wgGroupsRemoveFromSelf['user'][] = $value;
4743 // Now figure out what groups the user can add to him/herself
4744 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4746 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4747 // No idea WHY this would be used, but it's there
4748 $groups['add-self'] = User
::getAllGroups();
4749 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4750 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4753 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4755 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4756 $groups['remove-self'] = User
::getAllGroups();
4757 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4758 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4765 * Returns an array of groups that this user can add and remove
4766 * @return array Array( 'add' => array( addablegroups ),
4767 * 'remove' => array( removablegroups ),
4768 * 'add-self' => array( addablegroups to self),
4769 * 'remove-self' => array( removable groups from self) )
4771 public function changeableGroups() {
4772 if ( $this->isAllowed( 'userrights' ) ) {
4773 // This group gives the right to modify everything (reverse-
4774 // compatibility with old "userrights lets you change
4776 // Using array_merge to make the groups reindexed
4777 $all = array_merge( User
::getAllGroups() );
4781 'add-self' => array(),
4782 'remove-self' => array()
4786 // Okay, it's not so simple, we will have to go through the arrays
4789 'remove' => array(),
4790 'add-self' => array(),
4791 'remove-self' => array()
4793 $addergroups = $this->getEffectiveGroups();
4795 foreach ( $addergroups as $addergroup ) {
4796 $groups = array_merge_recursive(
4797 $groups, $this->changeableByGroup( $addergroup )
4799 $groups['add'] = array_unique( $groups['add'] );
4800 $groups['remove'] = array_unique( $groups['remove'] );
4801 $groups['add-self'] = array_unique( $groups['add-self'] );
4802 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4808 * Deferred version of incEditCountImmediate()
4810 public function incEditCount() {
4812 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $that ) {
4813 $that->incEditCountImmediate();
4818 * Increment the user's edit-count field.
4819 * Will have no effect for anonymous users.
4822 public function incEditCountImmediate() {
4823 if ( $this->isAnon() ) {
4827 $dbw = wfGetDB( DB_MASTER
);
4828 // No rows will be "affected" if user_editcount is NULL
4831 array( 'user_editcount=user_editcount+1' ),
4832 array( 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ),
4835 // Lazy initialization check...
4836 if ( $dbw->affectedRows() == 0 ) {
4837 // Now here's a goddamn hack...
4838 $dbr = wfGetDB( DB_SLAVE
);
4839 if ( $dbr !== $dbw ) {
4840 // If we actually have a slave server, the count is
4841 // at least one behind because the current transaction
4842 // has not been committed and replicated.
4843 $this->initEditCount( 1 );
4845 // But if DB_SLAVE is selecting the master, then the
4846 // count we just read includes the revision that was
4847 // just added in the working transaction.
4848 $this->initEditCount();
4851 // Edit count in user cache too
4852 $this->invalidateCache();
4856 * Initialize user_editcount from data out of the revision table
4858 * @param int $add Edits to add to the count from the revision table
4859 * @return int Number of edits
4861 protected function initEditCount( $add = 0 ) {
4862 // Pull from a slave to be less cruel to servers
4863 // Accuracy isn't the point anyway here
4864 $dbr = wfGetDB( DB_SLAVE
);
4865 $count = (int)$dbr->selectField(
4868 array( 'rev_user' => $this->getId() ),
4871 $count = $count +
$add;
4873 $dbw = wfGetDB( DB_MASTER
);
4876 array( 'user_editcount' => $count ),
4877 array( 'user_id' => $this->getId() ),
4885 * Get the description of a given right
4887 * @param string $right Right to query
4888 * @return string Localized description of the right
4890 public static function getRightDescription( $right ) {
4891 $key = "right-$right";
4892 $msg = wfMessage( $key );
4893 return $msg->isBlank() ?
$right : $msg->text();
4897 * Make a new-style password hash
4899 * @param string $password Plain-text password
4900 * @param bool|string $salt Optional salt, may be random or the user ID.
4901 * If unspecified or false, will generate one automatically
4902 * @return string Password hash
4903 * @deprecated since 1.24, use Password class
4905 public static function crypt( $password, $salt = false ) {
4906 wfDeprecated( __METHOD__
, '1.24' );
4907 $passwordFactory = new PasswordFactory();
4908 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4909 $hash = $passwordFactory->newFromPlaintext( $password );
4910 return $hash->toString();
4914 * Compare a password hash with a plain-text password. Requires the user
4915 * ID if there's a chance that the hash is an old-style hash.
4917 * @param string $hash Password hash
4918 * @param string $password Plain-text password to compare
4919 * @param string|bool $userId User ID for old-style password salt
4922 * @deprecated since 1.24, use Password class
4924 public static function comparePasswords( $hash, $password, $userId = false ) {
4925 wfDeprecated( __METHOD__
, '1.24' );
4927 // Check for *really* old password hashes that don't even have a type
4928 // The old hash format was just an md5 hex hash, with no type information
4929 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4930 global $wgPasswordSalt;
4931 if ( $wgPasswordSalt ) {
4932 $password = ":B:{$userId}:{$hash}";
4934 $password = ":A:{$hash}";
4938 $passwordFactory = new PasswordFactory();
4939 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4940 $hash = $passwordFactory->newFromCiphertext( $hash );
4941 return $hash->equals( $password );
4945 * Add a newuser log entry for this user.
4946 * Before 1.19 the return value was always true.
4948 * @param string|bool $action Account creation type.
4949 * - String, one of the following values:
4950 * - 'create' for an anonymous user creating an account for himself.
4951 * This will force the action's performer to be the created user itself,
4952 * no matter the value of $wgUser
4953 * - 'create2' for a logged in user creating an account for someone else
4954 * - 'byemail' when the created user will receive its password by e-mail
4955 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4956 * - Boolean means whether the account was created by e-mail (deprecated):
4957 * - true will be converted to 'byemail'
4958 * - false will be converted to 'create' if this object is the same as
4959 * $wgUser and to 'create2' otherwise
4961 * @param string $reason User supplied reason
4963 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4965 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4966 global $wgUser, $wgNewUserLog;
4967 if ( empty( $wgNewUserLog ) ) {
4968 return true; // disabled
4971 if ( $action === true ) {
4972 $action = 'byemail';
4973 } elseif ( $action === false ) {
4974 if ( $this->equals( $wgUser ) ) {
4977 $action = 'create2';
4981 if ( $action === 'create' ||
$action === 'autocreate' ) {
4984 $performer = $wgUser;
4987 $logEntry = new ManualLogEntry( 'newusers', $action );
4988 $logEntry->setPerformer( $performer );
4989 $logEntry->setTarget( $this->getUserPage() );
4990 $logEntry->setComment( $reason );
4991 $logEntry->setParameters( array(
4992 '4::userid' => $this->getId(),
4994 $logid = $logEntry->insert();
4996 if ( $action !== 'autocreate' ) {
4997 $logEntry->publish( $logid );
5004 * Add an autocreate newuser log entry for this user
5005 * Used by things like CentralAuth and perhaps other authplugins.
5006 * Consider calling addNewUserLogEntry() directly instead.
5010 public function addNewUserLogEntryAutoCreate() {
5011 $this->addNewUserLogEntry( 'autocreate' );
5017 * Load the user options either from cache, the database or an array
5019 * @param array $data Rows for the current user out of the user_properties table
5021 protected function loadOptions( $data = null ) {
5026 if ( $this->mOptionsLoaded
) {
5030 $this->mOptions
= self
::getDefaultOptions();
5032 if ( !$this->getId() ) {
5033 // For unlogged-in users, load language/variant options from request.
5034 // There's no need to do it for logged-in users: they can set preferences,
5035 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5036 // so don't override user's choice (especially when the user chooses site default).
5037 $variant = $wgContLang->getDefaultVariant();
5038 $this->mOptions
['variant'] = $variant;
5039 $this->mOptions
['language'] = $variant;
5040 $this->mOptionsLoaded
= true;
5044 // Maybe load from the object
5045 if ( !is_null( $this->mOptionOverrides
) ) {
5046 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5047 foreach ( $this->mOptionOverrides
as $key => $value ) {
5048 $this->mOptions
[$key] = $value;
5051 if ( !is_array( $data ) ) {
5052 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5053 // Load from database
5054 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5055 ?
wfGetDB( DB_MASTER
)
5056 : wfGetDB( DB_SLAVE
);
5058 $res = $dbr->select(
5060 array( 'up_property', 'up_value' ),
5061 array( 'up_user' => $this->getId() ),
5065 $this->mOptionOverrides
= array();
5067 foreach ( $res as $row ) {
5068 $data[$row->up_property
] = $row->up_value
;
5071 foreach ( $data as $property => $value ) {
5072 $this->mOptionOverrides
[$property] = $value;
5073 $this->mOptions
[$property] = $value;
5077 $this->mOptionsLoaded
= true;
5079 Hooks
::run( 'UserLoadOptions', array( $this, &$this->mOptions
) );
5083 * Saves the non-default options for this user, as previously set e.g. via
5084 * setOption(), in the database's "user_properties" (preferences) table.
5085 * Usually used via saveSettings().
5087 protected function saveOptions() {
5088 $this->loadOptions();
5090 // Not using getOptions(), to keep hidden preferences in database
5091 $saveOptions = $this->mOptions
;
5093 // Allow hooks to abort, for instance to save to a global profile.
5094 // Reset options to default state before saving.
5095 if ( !Hooks
::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5099 $userId = $this->getId();
5101 $insert_rows = array(); // all the new preference rows
5102 foreach ( $saveOptions as $key => $value ) {
5103 // Don't bother storing default values
5104 $defaultOption = self
::getDefaultOption( $key );
5105 if ( ( $defaultOption === null && $value !== false && $value !== null )
5106 ||
$value != $defaultOption
5108 $insert_rows[] = array(
5109 'up_user' => $userId,
5110 'up_property' => $key,
5111 'up_value' => $value,
5116 $dbw = wfGetDB( DB_MASTER
);
5118 $res = $dbw->select( 'user_properties',
5119 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
5121 // Find prior rows that need to be removed or updated. These rows will
5122 // all be deleted (the later so that INSERT IGNORE applies the new values).
5123 $keysDelete = array();
5124 foreach ( $res as $row ) {
5125 if ( !isset( $saveOptions[$row->up_property
] )
5126 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5128 $keysDelete[] = $row->up_property
;
5132 if ( count( $keysDelete ) ) {
5133 // Do the DELETE by PRIMARY KEY for prior rows.
5134 // In the past a very large portion of calls to this function are for setting
5135 // 'rememberpassword' for new accounts (a preference that has since been removed).
5136 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5137 // caused gap locks on [max user ID,+infinity) which caused high contention since
5138 // updates would pile up on each other as they are for higher (newer) user IDs.
5139 // It might not be necessary these days, but it shouldn't hurt either.
5140 $dbw->delete( 'user_properties',
5141 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
5143 // Insert the new preference rows
5144 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
5148 * Lazily instantiate and return a factory object for making passwords
5150 * @deprecated since 1.27, create a PasswordFactory directly instead
5151 * @return PasswordFactory
5153 public static function getPasswordFactory() {
5154 wfDeprecated( __METHOD__
, '1.27' );
5155 $ret = new PasswordFactory();
5156 $ret->init( RequestContext
::getMain()->getConfig() );
5161 * Provide an array of HTML5 attributes to put on an input element
5162 * intended for the user to enter a new password. This may include
5163 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5165 * Do *not* use this when asking the user to enter his current password!
5166 * Regardless of configuration, users may have invalid passwords for whatever
5167 * reason (e.g., they were set before requirements were tightened up).
5168 * Only use it when asking for a new password, like on account creation or
5171 * Obviously, you still need to do server-side checking.
5173 * NOTE: A combination of bugs in various browsers means that this function
5174 * actually just returns array() unconditionally at the moment. May as
5175 * well keep it around for when the browser bugs get fixed, though.
5177 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5179 * @deprecated since 1.27
5180 * @return array Array of HTML attributes suitable for feeding to
5181 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5182 * That will get confused by the boolean attribute syntax used.)
5184 public static function passwordChangeInputAttribs() {
5185 global $wgMinimalPasswordLength;
5187 if ( $wgMinimalPasswordLength == 0 ) {
5191 # Note that the pattern requirement will always be satisfied if the
5192 # input is empty, so we need required in all cases.
5194 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5195 # if e-mail confirmation is being used. Since HTML5 input validation
5196 # is b0rked anyway in some browsers, just return nothing. When it's
5197 # re-enabled, fix this code to not output required for e-mail
5199 # $ret = array( 'required' );
5202 # We can't actually do this right now, because Opera 9.6 will print out
5203 # the entered password visibly in its error message! When other
5204 # browsers add support for this attribute, or Opera fixes its support,
5205 # we can add support with a version check to avoid doing this on Opera
5206 # versions where it will be a problem. Reported to Opera as
5207 # DSK-262266, but they don't have a public bug tracker for us to follow.
5209 if ( $wgMinimalPasswordLength > 1 ) {
5210 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5211 $ret['title'] = wfMessage( 'passwordtooshort' )
5212 ->numParams( $wgMinimalPasswordLength )->text();
5220 * Return the list of user fields that should be selected to create
5221 * a new user object.
5224 public static function selectFields() {
5232 'user_email_authenticated',
5234 'user_email_token_expires',
5235 'user_registration',
5241 * Factory function for fatal permission-denied errors
5244 * @param string $permission User right required
5247 static function newFatalPermissionDeniedStatus( $permission ) {
5250 $groups = array_map(
5251 array( 'User', 'makeGroupLinkWiki' ),
5252 User
::getGroupsWithPermission( $permission )
5256 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5258 return Status
::newFatal( 'badaccess-group0' );
5263 * Get a new instance of this user that was loaded from the master via a locking read
5265 * Use this instead of the main context User when updating that user. This avoids races
5266 * where that user was loaded from a slave or even the master but without proper locks.
5268 * @return User|null Returns null if the user was not found in the DB
5271 public function getInstanceForUpdate() {
5272 if ( !$this->getId() ) {
5273 return null; // anon
5276 $user = self
::newFromId( $this->getId() );
5277 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5285 * Checks if two user objects point to the same user.
5291 public function equals( User
$user ) {
5292 return $this->getName() === $user->getName();