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 $request = $this->getRequest();
1089 $loggedOut = $request ?
$request->getSession()->getLoggedOutTimestamp() : 0;
1090 if ( $loggedOut !== 0 ) {
1091 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1093 $this->mTouched
= '1'; # Allow any pages to be cached
1096 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1097 $this->mEmailAuthenticated
= null;
1098 $this->mEmailToken
= '';
1099 $this->mEmailTokenExpires
= null;
1100 $this->mRegistration
= wfTimestamp( TS_MW
);
1101 $this->mGroups
= array();
1103 Hooks
::run( 'UserLoadDefaults', array( $this, $name ) );
1107 * Return whether an item has been loaded.
1109 * @param string $item Item to check. Current possibilities:
1113 * @param string $all 'all' to check if the whole object has been loaded
1114 * or any other string to check if only the item is available (e.g.
1118 public function isItemLoaded( $item, $all = 'all' ) {
1119 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1120 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1124 * Set that an item has been loaded
1126 * @param string $item
1128 protected function setItemLoaded( $item ) {
1129 if ( is_array( $this->mLoadedItems
) ) {
1130 $this->mLoadedItems
[$item] = true;
1135 * Load user data from the session.
1137 * @return bool True if the user is logged in, false otherwise.
1139 private function loadFromSession() {
1142 Hooks
::run( 'UserLoadFromSession', array( $this, &$result ), '1.27' );
1143 if ( $result !== null ) {
1147 // MediaWiki\Session\Session already did the necessary authentication of the user
1148 // returned here, so just use it if applicable.
1149 $session = $this->getRequest()->getSession();
1150 $user = $session->getUser();
1151 if ( $user->isLoggedIn() ) {
1152 $this->loadFromUserObject( $user );
1153 // Other code expects these to be set in the session, so set them.
1154 $session->set( 'wsUserID', $this->getId() );
1155 $session->set( 'wsUserName', $this->getName() );
1156 $session->set( 'wsToken', $this->mToken
);
1164 * Load user and user_group data from the database.
1165 * $this->mId must be set, this is how the user is identified.
1167 * @param integer $flags User::READ_* constant bitfield
1168 * @return bool True if the user exists, false if the user is anonymous
1170 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1172 $this->mId
= intval( $this->mId
);
1175 if ( !$this->mId
) {
1176 $this->loadDefaults();
1180 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1181 $db = wfGetDB( $index );
1183 $s = $db->selectRow(
1185 self
::selectFields(),
1186 array( 'user_id' => $this->mId
),
1191 $this->queryFlagsUsed
= $flags;
1192 Hooks
::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1194 if ( $s !== false ) {
1195 // Initialise user table data
1196 $this->loadFromRow( $s );
1197 $this->mGroups
= null; // deferred
1198 $this->getEditCount(); // revalidation for nulls
1203 $this->loadDefaults();
1209 * Initialize this object from a row from the user table.
1211 * @param stdClass $row Row from the user table to load.
1212 * @param array $data Further user data to load into the object
1214 * user_groups Array with groups out of the user_groups table
1215 * user_properties Array with properties out of the user_properties table
1217 protected function loadFromRow( $row, $data = null ) {
1220 $this->mGroups
= null; // deferred
1222 if ( isset( $row->user_name
) ) {
1223 $this->mName
= $row->user_name
;
1224 $this->mFrom
= 'name';
1225 $this->setItemLoaded( 'name' );
1230 if ( isset( $row->user_real_name
) ) {
1231 $this->mRealName
= $row->user_real_name
;
1232 $this->setItemLoaded( 'realname' );
1237 if ( isset( $row->user_id
) ) {
1238 $this->mId
= intval( $row->user_id
);
1239 $this->mFrom
= 'id';
1240 $this->setItemLoaded( 'id' );
1245 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1246 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1249 if ( isset( $row->user_editcount
) ) {
1250 $this->mEditCount
= $row->user_editcount
;
1255 if ( isset( $row->user_email
) ) {
1256 $this->mEmail
= $row->user_email
;
1257 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1258 $this->mToken
= $row->user_token
;
1259 if ( $this->mToken
== '' ) {
1260 $this->mToken
= null;
1262 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1263 $this->mEmailToken
= $row->user_email_token
;
1264 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1265 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1271 $this->mLoadedItems
= true;
1274 if ( is_array( $data ) ) {
1275 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1276 $this->mGroups
= $data['user_groups'];
1278 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1279 $this->loadOptions( $data['user_properties'] );
1285 * Load the data for this user object from another user object.
1289 protected function loadFromUserObject( $user ) {
1291 $user->loadGroups();
1292 $user->loadOptions();
1293 foreach ( self
::$mCacheVars as $var ) {
1294 $this->$var = $user->$var;
1299 * Load the groups from the database if they aren't already loaded.
1301 private function loadGroups() {
1302 if ( is_null( $this->mGroups
) ) {
1303 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1304 ?
wfGetDB( DB_MASTER
)
1305 : wfGetDB( DB_SLAVE
);
1306 $res = $db->select( 'user_groups',
1307 array( 'ug_group' ),
1308 array( 'ug_user' => $this->mId
),
1310 $this->mGroups
= array();
1311 foreach ( $res as $row ) {
1312 $this->mGroups
[] = $row->ug_group
;
1318 * Add the user to the group if he/she meets given criteria.
1320 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1321 * possible to remove manually via Special:UserRights. In such case it
1322 * will not be re-added automatically. The user will also not lose the
1323 * group if they no longer meet the criteria.
1325 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1327 * @return array Array of groups the user has been promoted to.
1329 * @see $wgAutopromoteOnce
1331 public function addAutopromoteOnceGroups( $event ) {
1332 global $wgAutopromoteOnceLogInRC, $wgAuth;
1334 if ( wfReadOnly() ||
!$this->getId() ) {
1338 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1339 if ( !count( $toPromote ) ) {
1343 if ( !$this->checkAndSetTouched() ) {
1344 return array(); // raced out (bug T48834)
1347 $oldGroups = $this->getGroups(); // previous groups
1348 foreach ( $toPromote as $group ) {
1349 $this->addGroup( $group );
1351 // update groups in external authentication database
1352 Hooks
::run( 'UserGroupsChanged', array( $this, $toPromote, array(), false ) );
1353 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1355 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1357 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1358 $logEntry->setPerformer( $this );
1359 $logEntry->setTarget( $this->getUserPage() );
1360 $logEntry->setParameters( array(
1361 '4::oldgroups' => $oldGroups,
1362 '5::newgroups' => $newGroups,
1364 $logid = $logEntry->insert();
1365 if ( $wgAutopromoteOnceLogInRC ) {
1366 $logEntry->publish( $logid );
1373 * Bump user_touched if it didn't change since this object was loaded
1375 * On success, the mTouched field is updated.
1376 * The user serialization cache is always cleared.
1378 * @return bool Whether user_touched was actually updated
1381 protected function checkAndSetTouched() {
1384 if ( !$this->mId
) {
1385 return false; // anon
1388 // Get a new user_touched that is higher than the old one
1389 $oldTouched = $this->mTouched
;
1390 $newTouched = $this->newTouchedTimestamp();
1392 $dbw = wfGetDB( DB_MASTER
);
1393 $dbw->update( 'user',
1394 array( 'user_touched' => $dbw->timestamp( $newTouched ) ),
1396 'user_id' => $this->mId
,
1397 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1401 $success = ( $dbw->affectedRows() > 0 );
1404 $this->mTouched
= $newTouched;
1405 $this->clearSharedCache();
1407 // Clears on failure too since that is desired if the cache is stale
1408 $this->clearSharedCache( 'refresh' );
1415 * Clear various cached data stored in this object. The cache of the user table
1416 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1418 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1419 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1421 public function clearInstanceCache( $reloadFrom = false ) {
1422 $this->mNewtalk
= -1;
1423 $this->mDatePreference
= null;
1424 $this->mBlockedby
= -1; # Unset
1425 $this->mHash
= false;
1426 $this->mRights
= null;
1427 $this->mEffectiveGroups
= null;
1428 $this->mImplicitGroups
= null;
1429 $this->mGroups
= null;
1430 $this->mOptions
= null;
1431 $this->mOptionsLoaded
= false;
1432 $this->mEditCount
= null;
1434 if ( $reloadFrom ) {
1435 $this->mLoadedItems
= array();
1436 $this->mFrom
= $reloadFrom;
1441 * Combine the language default options with any site-specific options
1442 * and add the default language variants.
1444 * @return array Array of String options
1446 public static function getDefaultOptions() {
1447 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1449 static $defOpt = null;
1450 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1451 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1452 // mid-request and see that change reflected in the return value of this function.
1453 // Which is insane and would never happen during normal MW operation
1457 $defOpt = $wgDefaultUserOptions;
1458 // Default language setting
1459 $defOpt['language'] = $wgContLang->getCode();
1460 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1461 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1463 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1464 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1466 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1468 Hooks
::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1474 * Get a given default option value.
1476 * @param string $opt Name of option to retrieve
1477 * @return string Default option value
1479 public static function getDefaultOption( $opt ) {
1480 $defOpts = self
::getDefaultOptions();
1481 if ( isset( $defOpts[$opt] ) ) {
1482 return $defOpts[$opt];
1489 * Get blocking information
1490 * @param bool $bFromSlave Whether to check the slave database first.
1491 * To improve performance, non-critical checks are done against slaves.
1492 * Check when actually saving should be done against master.
1494 private function getBlockedStatus( $bFromSlave = true ) {
1495 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1497 if ( -1 != $this->mBlockedby
) {
1501 wfDebug( __METHOD__
. ": checking...\n" );
1503 // Initialize data...
1504 // Otherwise something ends up stomping on $this->mBlockedby when
1505 // things get lazy-loaded later, causing false positive block hits
1506 // due to -1 !== 0. Probably session-related... Nothing should be
1507 // overwriting mBlockedby, surely?
1510 # We only need to worry about passing the IP address to the Block generator if the
1511 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1512 # know which IP address they're actually coming from
1513 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->equals( $wgUser ) ) {
1514 $ip = $this->getRequest()->getIP();
1520 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1523 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1525 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1527 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1528 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1529 $block->setTarget( $ip );
1530 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1532 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1533 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1534 $block->setTarget( $ip );
1538 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1539 if ( !$block instanceof Block
1540 && $wgApplyIpBlocksToXff
1542 && !in_array( $ip, $wgProxyWhitelist )
1544 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1545 $xff = array_map( 'trim', explode( ',', $xff ) );
1546 $xff = array_diff( $xff, array( $ip ) );
1547 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1548 $block = Block
::chooseBlock( $xffblocks, $xff );
1549 if ( $block instanceof Block
) {
1550 # Mangle the reason to alert the user that the block
1551 # originated from matching the X-Forwarded-For header.
1552 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1556 if ( $block instanceof Block
) {
1557 wfDebug( __METHOD__
. ": Found block.\n" );
1558 $this->mBlock
= $block;
1559 $this->mBlockedby
= $block->getByName();
1560 $this->mBlockreason
= $block->mReason
;
1561 $this->mHideName
= $block->mHideName
;
1562 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1564 $this->mBlockedby
= '';
1565 $this->mHideName
= 0;
1566 $this->mAllowUsertalk
= false;
1570 Hooks
::run( 'GetBlockedStatus', array( &$this ) );
1575 * Whether the given IP is in a DNS blacklist.
1577 * @param string $ip IP to check
1578 * @param bool $checkWhitelist Whether to check the whitelist first
1579 * @return bool True if blacklisted.
1581 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1582 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1584 if ( !$wgEnableDnsBlacklist ) {
1588 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1592 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1596 * Whether the given IP is in a given DNS blacklist.
1598 * @param string $ip IP to check
1599 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1600 * @return bool True if blacklisted.
1602 public function inDnsBlacklist( $ip, $bases ) {
1605 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1606 if ( IP
::isIPv4( $ip ) ) {
1607 // Reverse IP, bug 21255
1608 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1610 foreach ( (array)$bases as $base ) {
1612 // If we have an access key, use that too (ProjectHoneypot, etc.)
1614 if ( is_array( $base ) ) {
1615 if ( count( $base ) >= 2 ) {
1616 // Access key is 1, base URL is 0
1617 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1619 $host = "$ipReversed.{$base[0]}";
1621 $basename = $base[0];
1623 $host = "$ipReversed.$base";
1627 $ipList = gethostbynamel( $host );
1630 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1634 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1643 * Check if an IP address is in the local proxy list
1649 public static function isLocallyBlockedProxy( $ip ) {
1650 global $wgProxyList;
1652 if ( !$wgProxyList ) {
1656 if ( !is_array( $wgProxyList ) ) {
1657 // Load from the specified file
1658 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1661 if ( !is_array( $wgProxyList ) ) {
1663 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1665 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1666 // Old-style flipped proxy list
1675 * Is this user subject to rate limiting?
1677 * @return bool True if rate limited
1679 public function isPingLimitable() {
1680 global $wgRateLimitsExcludedIPs;
1681 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1682 // No other good way currently to disable rate limits
1683 // for specific IPs. :P
1684 // But this is a crappy hack and should die.
1687 return !$this->isAllowed( 'noratelimit' );
1691 * Primitive rate limits: enforce maximum actions per time period
1692 * to put a brake on flooding.
1694 * The method generates both a generic profiling point and a per action one
1695 * (suffix being "-$action".
1697 * @note When using a shared cache like memcached, IP-address
1698 * last-hit counters will be shared across wikis.
1700 * @param string $action Action to enforce; 'edit' if unspecified
1701 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1702 * @return bool True if a rate limiter was tripped
1704 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1705 // Call the 'PingLimiter' hook
1707 if ( !Hooks
::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1711 global $wgRateLimits;
1712 if ( !isset( $wgRateLimits[$action] ) ) {
1716 // Some groups shouldn't trigger the ping limiter, ever
1717 if ( !$this->isPingLimitable() ) {
1721 $limits = $wgRateLimits[$action];
1723 $id = $this->getId();
1726 if ( isset( $limits['anon'] ) && $id == 0 ) {
1727 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1730 if ( isset( $limits['user'] ) && $id != 0 ) {
1731 $userLimit = $limits['user'];
1733 if ( $this->isNewbie() ) {
1734 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1735 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1737 if ( isset( $limits['ip'] ) ) {
1738 $ip = $this->getRequest()->getIP();
1739 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1741 if ( isset( $limits['subnet'] ) ) {
1742 $ip = $this->getRequest()->getIP();
1745 if ( IP
::isIPv6( $ip ) ) {
1746 $parts = IP
::parseRange( "$ip/64" );
1747 $subnet = $parts[0];
1748 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1750 $subnet = $matches[1];
1752 if ( $subnet !== false ) {
1753 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1757 // Check for group-specific permissions
1758 // If more than one group applies, use the group with the highest limit
1759 foreach ( $this->getGroups() as $group ) {
1760 if ( isset( $limits[$group] ) ) {
1761 if ( $userLimit === false
1762 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1764 $userLimit = $limits[$group];
1768 // Set the user limit key
1769 if ( $userLimit !== false ) {
1770 list( $max, $period ) = $userLimit;
1771 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1772 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1775 $cache = ObjectCache
::getLocalClusterInstance();
1778 foreach ( $keys as $key => $limit ) {
1779 list( $max, $period ) = $limit;
1780 $summary = "(limit $max in {$period}s)";
1781 $count = $cache->get( $key );
1784 if ( $count >= $max ) {
1785 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1786 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1789 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1792 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1793 if ( $incrBy > 0 ) {
1794 $cache->add( $key, 0, intval( $period ) ); // first ping
1797 if ( $incrBy > 0 ) {
1798 $cache->incr( $key, $incrBy );
1806 * Check if user is blocked
1808 * @param bool $bFromSlave Whether to check the slave database instead of
1809 * the master. Hacked from false due to horrible probs on site.
1810 * @return bool True if blocked, false otherwise
1812 public function isBlocked( $bFromSlave = true ) {
1813 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1817 * Get the block affecting the user, or null if the user is not blocked
1819 * @param bool $bFromSlave Whether to check the slave database instead of the master
1820 * @return Block|null
1822 public function getBlock( $bFromSlave = true ) {
1823 $this->getBlockedStatus( $bFromSlave );
1824 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1828 * Check if user is blocked from editing a particular article
1830 * @param Title $title Title to check
1831 * @param bool $bFromSlave Whether to check the slave database instead of the master
1834 public function isBlockedFrom( $title, $bFromSlave = false ) {
1835 global $wgBlockAllowsUTEdit;
1837 $blocked = $this->isBlocked( $bFromSlave );
1838 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1839 // If a user's name is suppressed, they cannot make edits anywhere
1840 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1841 && $title->getNamespace() == NS_USER_TALK
) {
1843 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1846 Hooks
::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1852 * If user is blocked, return the name of the user who placed the block
1853 * @return string Name of blocker
1855 public function blockedBy() {
1856 $this->getBlockedStatus();
1857 return $this->mBlockedby
;
1861 * If user is blocked, return the specified reason for the block
1862 * @return string Blocking reason
1864 public function blockedFor() {
1865 $this->getBlockedStatus();
1866 return $this->mBlockreason
;
1870 * If user is blocked, return the ID for the block
1871 * @return int Block ID
1873 public function getBlockId() {
1874 $this->getBlockedStatus();
1875 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1879 * Check if user is blocked on all wikis.
1880 * Do not use for actual edit permission checks!
1881 * This is intended for quick UI checks.
1883 * @param string $ip IP address, uses current client if none given
1884 * @return bool True if blocked, false otherwise
1886 public function isBlockedGlobally( $ip = '' ) {
1887 if ( $this->mBlockedGlobally
!== null ) {
1888 return $this->mBlockedGlobally
;
1890 // User is already an IP?
1891 if ( IP
::isIPAddress( $this->getName() ) ) {
1892 $ip = $this->getName();
1894 $ip = $this->getRequest()->getIP();
1897 Hooks
::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1898 $this->mBlockedGlobally
= (bool)$blocked;
1899 return $this->mBlockedGlobally
;
1903 * Check if user account is locked
1905 * @return bool True if locked, false otherwise
1907 public function isLocked() {
1908 if ( $this->mLocked
!== null ) {
1909 return $this->mLocked
;
1912 $authUser = $wgAuth->getUserInstance( $this );
1913 $this->mLocked
= (bool)$authUser->isLocked();
1914 Hooks
::run( 'UserIsLocked', array( $this, &$this->mLocked
) );
1915 return $this->mLocked
;
1919 * Check if user account is hidden
1921 * @return bool True if hidden, false otherwise
1923 public function isHidden() {
1924 if ( $this->mHideName
!== null ) {
1925 return $this->mHideName
;
1927 $this->getBlockedStatus();
1928 if ( !$this->mHideName
) {
1930 $authUser = $wgAuth->getUserInstance( $this );
1931 $this->mHideName
= (bool)$authUser->isHidden();
1932 Hooks
::run( 'UserIsHidden', array( $this, &$this->mHideName
) );
1934 return $this->mHideName
;
1938 * Get the user's ID.
1939 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1941 public function getId() {
1942 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1943 // Special case, we know the user is anonymous
1945 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1946 // Don't load if this was initialized from an ID
1953 * Set the user and reload all fields according to a given ID
1954 * @param int $v User ID to reload
1956 public function setId( $v ) {
1958 $this->clearInstanceCache( 'id' );
1962 * Get the user name, or the IP of an anonymous user
1963 * @return string User's name or IP address
1965 public function getName() {
1966 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1967 // Special case optimisation
1968 return $this->mName
;
1971 if ( $this->mName
=== false ) {
1973 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1975 return $this->mName
;
1980 * Set the user name.
1982 * This does not reload fields from the database according to the given
1983 * name. Rather, it is used to create a temporary "nonexistent user" for
1984 * later addition to the database. It can also be used to set the IP
1985 * address for an anonymous user to something other than the current
1988 * @note User::newFromName() has roughly the same function, when the named user
1990 * @param string $str New user name to set
1992 public function setName( $str ) {
1994 $this->mName
= $str;
1998 * Get the user's name escaped by underscores.
1999 * @return string Username escaped by underscores.
2001 public function getTitleKey() {
2002 return str_replace( ' ', '_', $this->getName() );
2006 * Check if the user has new messages.
2007 * @return bool True if the user has new messages
2009 public function getNewtalk() {
2012 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2013 if ( $this->mNewtalk
=== -1 ) {
2014 $this->mNewtalk
= false; # reset talk page status
2016 // Check memcached separately for anons, who have no
2017 // entire User object stored in there.
2018 if ( !$this->mId
) {
2019 global $wgDisableAnonTalk;
2020 if ( $wgDisableAnonTalk ) {
2021 // Anon newtalk disabled by configuration.
2022 $this->mNewtalk
= false;
2024 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2027 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2031 return (bool)$this->mNewtalk
;
2035 * Return the data needed to construct links for new talk page message
2036 * alerts. If there are new messages, this will return an associative array
2037 * with the following data:
2038 * wiki: The database name of the wiki
2039 * link: Root-relative link to the user's talk page
2040 * rev: The last talk page revision that the user has seen or null. This
2041 * is useful for building diff links.
2042 * If there are no new messages, it returns an empty array.
2043 * @note This function was designed to accomodate multiple talk pages, but
2044 * currently only returns a single link and revision.
2047 public function getNewMessageLinks() {
2049 if ( !Hooks
::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2051 } elseif ( !$this->getNewtalk() ) {
2054 $utp = $this->getTalkPage();
2055 $dbr = wfGetDB( DB_SLAVE
);
2056 // Get the "last viewed rev" timestamp from the oldest message notification
2057 $timestamp = $dbr->selectField( 'user_newtalk',
2058 'MIN(user_last_timestamp)',
2059 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2061 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2062 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2066 * Get the revision ID for the last talk page revision viewed by the talk
2068 * @return int|null Revision ID or null
2070 public function getNewMessageRevisionId() {
2071 $newMessageRevisionId = null;
2072 $newMessageLinks = $this->getNewMessageLinks();
2073 if ( $newMessageLinks ) {
2074 // Note: getNewMessageLinks() never returns more than a single link
2075 // and it is always for the same wiki, but we double-check here in
2076 // case that changes some time in the future.
2077 if ( count( $newMessageLinks ) === 1
2078 && $newMessageLinks[0]['wiki'] === wfWikiID()
2079 && $newMessageLinks[0]['rev']
2081 /** @var Revision $newMessageRevision */
2082 $newMessageRevision = $newMessageLinks[0]['rev'];
2083 $newMessageRevisionId = $newMessageRevision->getId();
2086 return $newMessageRevisionId;
2090 * Internal uncached check for new messages
2093 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2094 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2095 * @return bool True if the user has new messages
2097 protected function checkNewtalk( $field, $id ) {
2098 $dbr = wfGetDB( DB_SLAVE
);
2100 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__
);
2102 return $ok !== false;
2106 * Add or update the new messages flag
2107 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2108 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2109 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2110 * @return bool True if successful, false otherwise
2112 protected function updateNewtalk( $field, $id, $curRev = null ) {
2113 // Get timestamp of the talk page revision prior to the current one
2114 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2115 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2116 // Mark the user as having new messages since this revision
2117 $dbw = wfGetDB( DB_MASTER
);
2118 $dbw->insert( 'user_newtalk',
2119 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2122 if ( $dbw->affectedRows() ) {
2123 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2126 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2132 * Clear the new messages flag for the given user
2133 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2134 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2135 * @return bool True if successful, false otherwise
2137 protected function deleteNewtalk( $field, $id ) {
2138 $dbw = wfGetDB( DB_MASTER
);
2139 $dbw->delete( 'user_newtalk',
2140 array( $field => $id ),
2142 if ( $dbw->affectedRows() ) {
2143 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2146 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2152 * Update the 'You have new messages!' status.
2153 * @param bool $val Whether the user has new messages
2154 * @param Revision $curRev New, as yet unseen revision of the user talk
2155 * page. Ignored if null or !$val.
2157 public function setNewtalk( $val, $curRev = null ) {
2158 if ( wfReadOnly() ) {
2163 $this->mNewtalk
= $val;
2165 if ( $this->isAnon() ) {
2167 $id = $this->getName();
2170 $id = $this->getId();
2174 $changed = $this->updateNewtalk( $field, $id, $curRev );
2176 $changed = $this->deleteNewtalk( $field, $id );
2180 $this->invalidateCache();
2185 * Generate a current or new-future timestamp to be stored in the
2186 * user_touched field when we update things.
2187 * @return string Timestamp in TS_MW format
2189 private function newTouchedTimestamp() {
2190 global $wgClockSkewFudge;
2192 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2193 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2194 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2201 * Clear user data from memcached
2203 * Use after applying updates to the database; caller's
2204 * responsibility to update user_touched if appropriate.
2206 * Called implicitly from invalidateCache() and saveSettings().
2208 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2210 public function clearSharedCache( $mode = 'changed' ) {
2211 if ( !$this->getId() ) {
2215 $cache = ObjectCache
::getMainWANInstance();
2216 $key = $this->getCacheKey( $cache );
2217 if ( $mode === 'refresh' ) {
2218 $cache->delete( $key, 1 );
2220 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
2221 $cache->delete( $key );
2227 * Immediately touch the user data cache for this account
2229 * Calls touch() and removes account data from memcached
2231 public function invalidateCache() {
2233 $this->clearSharedCache();
2237 * Update the "touched" timestamp for the user
2239 * This is useful on various login/logout events when making sure that
2240 * a browser or proxy that has multiple tenants does not suffer cache
2241 * pollution where the new user sees the old users content. The value
2242 * of getTouched() is checked when determining 304 vs 200 responses.
2243 * Unlike invalidateCache(), this preserves the User object cache and
2244 * avoids database writes.
2248 public function touch() {
2249 $id = $this->getId();
2251 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2252 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2253 $this->mQuickTouched
= null;
2258 * Validate the cache for this account.
2259 * @param string $timestamp A timestamp in TS_MW format
2262 public function validateCache( $timestamp ) {
2263 return ( $timestamp >= $this->getTouched() );
2267 * Get the user touched timestamp
2269 * Use this value only to validate caches via inequalities
2270 * such as in the case of HTTP If-Modified-Since response logic
2272 * @return string TS_MW Timestamp
2274 public function getTouched() {
2278 if ( $this->mQuickTouched
=== null ) {
2279 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2280 $cache = ObjectCache
::getMainWANInstance();
2282 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2285 return max( $this->mTouched
, $this->mQuickTouched
);
2288 return $this->mTouched
;
2292 * Get the user_touched timestamp field (time of last DB updates)
2293 * @return string TS_MW Timestamp
2296 public function getDBTouched() {
2299 return $this->mTouched
;
2303 * @deprecated Removed in 1.27.
2307 public function getPassword() {
2308 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2312 * @deprecated Removed in 1.27.
2316 public function getTemporaryPassword() {
2317 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2321 * Set the password and reset the random token.
2322 * Calls through to authentication plugin if necessary;
2323 * will have no effect if the auth plugin refuses to
2324 * pass the change through or if the legal password
2327 * As a special case, setting the password to null
2328 * wipes it, so the account cannot be logged in until
2329 * a new password is set, for instance via e-mail.
2331 * @deprecated since 1.27. AuthManager is coming.
2332 * @param string $str New password to set
2333 * @throws PasswordError On failure
2336 public function setPassword( $str ) {
2339 if ( $str !== null ) {
2340 if ( !$wgAuth->allowPasswordChange() ) {
2341 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2344 $status = $this->checkPasswordValidity( $str );
2345 if ( !$status->isGood() ) {
2346 throw new PasswordError( $status->getMessage()->text() );
2350 if ( !$wgAuth->setPassword( $this, $str ) ) {
2351 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2355 $this->setOption( 'watchlisttoken', false );
2356 $this->setPasswordInternal( $str );
2362 * Set the password and reset the random token unconditionally.
2364 * @deprecated since 1.27. AuthManager is coming.
2365 * @param string|null $str New password to set or null to set an invalid
2366 * password hash meaning that the user will not be able to log in
2367 * through the web interface.
2369 public function setInternalPassword( $str ) {
2372 if ( $wgAuth->allowSetLocalPassword() ) {
2374 $this->setOption( 'watchlisttoken', false );
2375 $this->setPasswordInternal( $str );
2380 * Actually set the password and such
2381 * @since 1.27 cannot set a password for a user not in the database
2382 * @param string|null $str New password to set or null to set an invalid
2383 * password hash meaning that the user will not be able to log in
2384 * through the web interface.
2386 private function setPasswordInternal( $str ) {
2387 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2389 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2392 $passwordFactory = new PasswordFactory();
2393 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2394 $dbw = wfGetDB( DB_MASTER
);
2398 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2399 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2400 'user_newpass_time' => $dbw->timestampOrNull( null ),
2408 // When the main password is changed, invalidate all bot passwords too
2409 BotPassword
::invalidateAllPasswordsForUser( $this->getName() );
2413 * Get the user's current token.
2414 * @param bool $forceCreation Force the generation of a new token if the
2415 * user doesn't have one (default=true for backwards compatibility).
2416 * @return string Token
2418 public function getToken( $forceCreation = true ) {
2420 if ( !$this->mToken
&& $forceCreation ) {
2423 return $this->mToken
;
2427 * Set the random token (used for persistent authentication)
2428 * Called from loadDefaults() among other places.
2430 * @param string|bool $token If specified, set the token to this value
2432 public function setToken( $token = false ) {
2435 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2437 $this->mToken
= $token;
2442 * Set the password for a password reminder or new account email
2444 * @deprecated since 1.27, AuthManager is coming
2445 * @param string $str New password to set or null to set an invalid
2446 * password hash meaning that the user will not be able to use it
2447 * @param bool $throttle If true, reset the throttle timestamp to the present
2449 public function setNewpassword( $str, $throttle = true ) {
2450 $id = $this->getId();
2452 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2455 $dbw = wfGetDB( DB_MASTER
);
2457 $passwordFactory = new PasswordFactory();
2458 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2460 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2463 if ( $str === null ) {
2464 $update['user_newpass_time'] = null;
2465 } elseif ( $throttle ) {
2466 $update['user_newpass_time'] = $dbw->timestamp();
2469 $dbw->update( 'user', $update, array( 'user_id' => $id ), __METHOD__
);
2473 * Has password reminder email been sent within the last
2474 * $wgPasswordReminderResendTime hours?
2477 public function isPasswordReminderThrottled() {
2478 global $wgPasswordReminderResendTime;
2480 if ( !$wgPasswordReminderResendTime ) {
2486 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2487 ?
wfGetDB( DB_MASTER
)
2488 : wfGetDB( DB_SLAVE
);
2489 $newpassTime = $db->selectField(
2491 'user_newpass_time',
2492 array( 'user_id' => $this->getId() ),
2496 if ( $newpassTime === null ) {
2499 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2500 return time() < $expiry;
2504 * Get the user's e-mail address
2505 * @return string User's email address
2507 public function getEmail() {
2509 Hooks
::run( 'UserGetEmail', array( $this, &$this->mEmail
) );
2510 return $this->mEmail
;
2514 * Get the timestamp of the user's e-mail authentication
2515 * @return string TS_MW timestamp
2517 public function getEmailAuthenticationTimestamp() {
2519 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2520 return $this->mEmailAuthenticated
;
2524 * Set the user's e-mail address
2525 * @param string $str New e-mail address
2527 public function setEmail( $str ) {
2529 if ( $str == $this->mEmail
) {
2532 $this->invalidateEmail();
2533 $this->mEmail
= $str;
2534 Hooks
::run( 'UserSetEmail', array( $this, &$this->mEmail
) );
2538 * Set the user's e-mail address and a confirmation mail if needed.
2541 * @param string $str New e-mail address
2544 public function setEmailWithConfirmation( $str ) {
2545 global $wgEnableEmail, $wgEmailAuthentication;
2547 if ( !$wgEnableEmail ) {
2548 return Status
::newFatal( 'emaildisabled' );
2551 $oldaddr = $this->getEmail();
2552 if ( $str === $oldaddr ) {
2553 return Status
::newGood( true );
2556 $this->setEmail( $str );
2558 if ( $str !== '' && $wgEmailAuthentication ) {
2559 // Send a confirmation request to the new address if needed
2560 $type = $oldaddr != '' ?
'changed' : 'set';
2561 $result = $this->sendConfirmationMail( $type );
2562 if ( $result->isGood() ) {
2563 // Say to the caller that a confirmation mail has been sent
2564 $result->value
= 'eauth';
2567 $result = Status
::newGood( true );
2574 * Get the user's real name
2575 * @return string User's real name
2577 public function getRealName() {
2578 if ( !$this->isItemLoaded( 'realname' ) ) {
2582 return $this->mRealName
;
2586 * Set the user's real name
2587 * @param string $str New real name
2589 public function setRealName( $str ) {
2591 $this->mRealName
= $str;
2595 * Get the user's current setting for a given option.
2597 * @param string $oname The option to check
2598 * @param string $defaultOverride A default value returned if the option does not exist
2599 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2600 * @return string User's current value for the option
2601 * @see getBoolOption()
2602 * @see getIntOption()
2604 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2605 global $wgHiddenPrefs;
2606 $this->loadOptions();
2608 # We want 'disabled' preferences to always behave as the default value for
2609 # users, even if they have set the option explicitly in their settings (ie they
2610 # set it, and then it was disabled removing their ability to change it). But
2611 # we don't want to erase the preferences in the database in case the preference
2612 # is re-enabled again. So don't touch $mOptions, just override the returned value
2613 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2614 return self
::getDefaultOption( $oname );
2617 if ( array_key_exists( $oname, $this->mOptions
) ) {
2618 return $this->mOptions
[$oname];
2620 return $defaultOverride;
2625 * Get all user's options
2627 * @param int $flags Bitwise combination of:
2628 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2629 * to the default value. (Since 1.25)
2632 public function getOptions( $flags = 0 ) {
2633 global $wgHiddenPrefs;
2634 $this->loadOptions();
2635 $options = $this->mOptions
;
2637 # We want 'disabled' preferences to always behave as the default value for
2638 # users, even if they have set the option explicitly in their settings (ie they
2639 # set it, and then it was disabled removing their ability to change it). But
2640 # we don't want to erase the preferences in the database in case the preference
2641 # is re-enabled again. So don't touch $mOptions, just override the returned value
2642 foreach ( $wgHiddenPrefs as $pref ) {
2643 $default = self
::getDefaultOption( $pref );
2644 if ( $default !== null ) {
2645 $options[$pref] = $default;
2649 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2650 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2657 * Get the user's current setting for a given option, as a boolean value.
2659 * @param string $oname The option to check
2660 * @return bool User's current value for the option
2663 public function getBoolOption( $oname ) {
2664 return (bool)$this->getOption( $oname );
2668 * Get the user's current setting for a given option, as an integer value.
2670 * @param string $oname The option to check
2671 * @param int $defaultOverride A default value returned if the option does not exist
2672 * @return int User's current value for the option
2675 public function getIntOption( $oname, $defaultOverride = 0 ) {
2676 $val = $this->getOption( $oname );
2678 $val = $defaultOverride;
2680 return intval( $val );
2684 * Set the given option for a user.
2686 * You need to call saveSettings() to actually write to the database.
2688 * @param string $oname The option to set
2689 * @param mixed $val New value to set
2691 public function setOption( $oname, $val ) {
2692 $this->loadOptions();
2694 // Explicitly NULL values should refer to defaults
2695 if ( is_null( $val ) ) {
2696 $val = self
::getDefaultOption( $oname );
2699 $this->mOptions
[$oname] = $val;
2703 * Get a token stored in the preferences (like the watchlist one),
2704 * resetting it if it's empty (and saving changes).
2706 * @param string $oname The option name to retrieve the token from
2707 * @return string|bool User's current value for the option, or false if this option is disabled.
2708 * @see resetTokenFromOption()
2710 * @deprecated 1.26 Applications should use the OAuth extension
2712 public function getTokenFromOption( $oname ) {
2713 global $wgHiddenPrefs;
2715 $id = $this->getId();
2716 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2720 $token = $this->getOption( $oname );
2722 // Default to a value based on the user token to avoid space
2723 // wasted on storing tokens for all users. When this option
2724 // is set manually by the user, only then is it stored.
2725 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2732 * Reset a token stored in the preferences (like the watchlist one).
2733 * *Does not* save user's preferences (similarly to setOption()).
2735 * @param string $oname The option name to reset the token in
2736 * @return string|bool New token value, or false if this option is disabled.
2737 * @see getTokenFromOption()
2740 public function resetTokenFromOption( $oname ) {
2741 global $wgHiddenPrefs;
2742 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2746 $token = MWCryptRand
::generateHex( 40 );
2747 $this->setOption( $oname, $token );
2752 * Return a list of the types of user options currently returned by
2753 * User::getOptionKinds().
2755 * Currently, the option kinds are:
2756 * - 'registered' - preferences which are registered in core MediaWiki or
2757 * by extensions using the UserGetDefaultOptions hook.
2758 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2759 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2760 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2761 * be used by user scripts.
2762 * - 'special' - "preferences" that are not accessible via User::getOptions
2763 * or User::setOptions.
2764 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2765 * These are usually legacy options, removed in newer versions.
2767 * The API (and possibly others) use this function to determine the possible
2768 * option types for validation purposes, so make sure to update this when a
2769 * new option kind is added.
2771 * @see User::getOptionKinds
2772 * @return array Option kinds
2774 public static function listOptionKinds() {
2777 'registered-multiselect',
2778 'registered-checkmatrix',
2786 * Return an associative array mapping preferences keys to the kind of a preference they're
2787 * used for. Different kinds are handled differently when setting or reading preferences.
2789 * See User::listOptionKinds for the list of valid option types that can be provided.
2791 * @see User::listOptionKinds
2792 * @param IContextSource $context
2793 * @param array $options Assoc. array with options keys to check as keys.
2794 * Defaults to $this->mOptions.
2795 * @return array The key => kind mapping data
2797 public function getOptionKinds( IContextSource
$context, $options = null ) {
2798 $this->loadOptions();
2799 if ( $options === null ) {
2800 $options = $this->mOptions
;
2803 $prefs = Preferences
::getPreferences( $this, $context );
2806 // Pull out the "special" options, so they don't get converted as
2807 // multiselect or checkmatrix.
2808 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2809 foreach ( $specialOptions as $name => $value ) {
2810 unset( $prefs[$name] );
2813 // Multiselect and checkmatrix options are stored in the database with
2814 // one key per option, each having a boolean value. Extract those keys.
2815 $multiselectOptions = array();
2816 foreach ( $prefs as $name => $info ) {
2817 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2818 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2819 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2820 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2822 foreach ( $opts as $value ) {
2823 $multiselectOptions["$prefix$value"] = true;
2826 unset( $prefs[$name] );
2829 $checkmatrixOptions = array();
2830 foreach ( $prefs as $name => $info ) {
2831 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2832 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2833 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2834 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2835 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2837 foreach ( $columns as $column ) {
2838 foreach ( $rows as $row ) {
2839 $checkmatrixOptions["$prefix$column-$row"] = true;
2843 unset( $prefs[$name] );
2847 // $value is ignored
2848 foreach ( $options as $key => $value ) {
2849 if ( isset( $prefs[$key] ) ) {
2850 $mapping[$key] = 'registered';
2851 } elseif ( isset( $multiselectOptions[$key] ) ) {
2852 $mapping[$key] = 'registered-multiselect';
2853 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2854 $mapping[$key] = 'registered-checkmatrix';
2855 } elseif ( isset( $specialOptions[$key] ) ) {
2856 $mapping[$key] = 'special';
2857 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2858 $mapping[$key] = 'userjs';
2860 $mapping[$key] = 'unused';
2868 * Reset certain (or all) options to the site defaults
2870 * The optional parameter determines which kinds of preferences will be reset.
2871 * Supported values are everything that can be reported by getOptionKinds()
2872 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2874 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2875 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2876 * for backwards-compatibility.
2877 * @param IContextSource|null $context Context source used when $resetKinds
2878 * does not contain 'all', passed to getOptionKinds().
2879 * Defaults to RequestContext::getMain() when null.
2881 public function resetOptions(
2882 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2883 IContextSource
$context = null
2886 $defaultOptions = self
::getDefaultOptions();
2888 if ( !is_array( $resetKinds ) ) {
2889 $resetKinds = array( $resetKinds );
2892 if ( in_array( 'all', $resetKinds ) ) {
2893 $newOptions = $defaultOptions;
2895 if ( $context === null ) {
2896 $context = RequestContext
::getMain();
2899 $optionKinds = $this->getOptionKinds( $context );
2900 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2901 $newOptions = array();
2903 // Use default values for the options that should be deleted, and
2904 // copy old values for the ones that shouldn't.
2905 foreach ( $this->mOptions
as $key => $value ) {
2906 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2907 if ( array_key_exists( $key, $defaultOptions ) ) {
2908 $newOptions[$key] = $defaultOptions[$key];
2911 $newOptions[$key] = $value;
2916 Hooks
::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2918 $this->mOptions
= $newOptions;
2919 $this->mOptionsLoaded
= true;
2923 * Get the user's preferred date format.
2924 * @return string User's preferred date format
2926 public function getDatePreference() {
2927 // Important migration for old data rows
2928 if ( is_null( $this->mDatePreference
) ) {
2930 $value = $this->getOption( 'date' );
2931 $map = $wgLang->getDatePreferenceMigrationMap();
2932 if ( isset( $map[$value] ) ) {
2933 $value = $map[$value];
2935 $this->mDatePreference
= $value;
2937 return $this->mDatePreference
;
2941 * Determine based on the wiki configuration and the user's options,
2942 * whether this user must be over HTTPS no matter what.
2946 public function requiresHTTPS() {
2947 global $wgSecureLogin;
2948 if ( !$wgSecureLogin ) {
2951 $https = $this->getBoolOption( 'prefershttps' );
2952 Hooks
::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2954 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2961 * Get the user preferred stub threshold
2965 public function getStubThreshold() {
2966 global $wgMaxArticleSize; # Maximum article size, in Kb
2967 $threshold = $this->getIntOption( 'stubthreshold' );
2968 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2969 // If they have set an impossible value, disable the preference
2970 // so we can use the parser cache again.
2977 * Get the permissions this user has.
2978 * @return array Array of String permission names
2980 public function getRights() {
2981 if ( is_null( $this->mRights
) ) {
2982 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2984 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
2985 if ( $allowedRights !== null ) {
2986 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
2989 Hooks
::run( 'UserGetRights', array( $this, &$this->mRights
) );
2990 // Force reindexation of rights when a hook has unset one of them
2991 $this->mRights
= array_values( array_unique( $this->mRights
) );
2993 return $this->mRights
;
2997 * Get the list of explicit group memberships this user has.
2998 * The implicit * and user groups are not included.
2999 * @return array Array of String internal group names
3001 public function getGroups() {
3003 $this->loadGroups();
3004 return $this->mGroups
;
3008 * Get the list of implicit group memberships this user has.
3009 * This includes all explicit groups, plus 'user' if logged in,
3010 * '*' for all accounts, and autopromoted groups
3011 * @param bool $recache Whether to avoid the cache
3012 * @return array Array of String internal group names
3014 public function getEffectiveGroups( $recache = false ) {
3015 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3016 $this->mEffectiveGroups
= array_unique( array_merge(
3017 $this->getGroups(), // explicit groups
3018 $this->getAutomaticGroups( $recache ) // implicit groups
3020 // Hook for additional groups
3021 Hooks
::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
3022 // Force reindexation of groups when a hook has unset one of them
3023 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3025 return $this->mEffectiveGroups
;
3029 * Get the list of implicit group memberships this user has.
3030 * This includes 'user' if logged in, '*' for all accounts,
3031 * and autopromoted groups
3032 * @param bool $recache Whether to avoid the cache
3033 * @return array Array of String internal group names
3035 public function getAutomaticGroups( $recache = false ) {
3036 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3037 $this->mImplicitGroups
= array( '*' );
3038 if ( $this->getId() ) {
3039 $this->mImplicitGroups
[] = 'user';
3041 $this->mImplicitGroups
= array_unique( array_merge(
3042 $this->mImplicitGroups
,
3043 Autopromote
::getAutopromoteGroups( $this )
3047 // Assure data consistency with rights/groups,
3048 // as getEffectiveGroups() depends on this function
3049 $this->mEffectiveGroups
= null;
3052 return $this->mImplicitGroups
;
3056 * Returns the groups the user has belonged to.
3058 * The user may still belong to the returned groups. Compare with getGroups().
3060 * The function will not return groups the user had belonged to before MW 1.17
3062 * @return array Names of the groups the user has belonged to.
3064 public function getFormerGroups() {
3067 if ( is_null( $this->mFormerGroups
) ) {
3068 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3069 ?
wfGetDB( DB_MASTER
)
3070 : wfGetDB( DB_SLAVE
);
3071 $res = $db->select( 'user_former_groups',
3072 array( 'ufg_group' ),
3073 array( 'ufg_user' => $this->mId
),
3075 $this->mFormerGroups
= array();
3076 foreach ( $res as $row ) {
3077 $this->mFormerGroups
[] = $row->ufg_group
;
3081 return $this->mFormerGroups
;
3085 * Get the user's edit count.
3086 * @return int|null Null for anonymous users
3088 public function getEditCount() {
3089 if ( !$this->getId() ) {
3093 if ( $this->mEditCount
=== null ) {
3094 /* Populate the count, if it has not been populated yet */
3095 $dbr = wfGetDB( DB_SLAVE
);
3096 // check if the user_editcount field has been initialized
3097 $count = $dbr->selectField(
3098 'user', 'user_editcount',
3099 array( 'user_id' => $this->mId
),
3103 if ( $count === null ) {
3104 // it has not been initialized. do so.
3105 $count = $this->initEditCount();
3107 $this->mEditCount
= $count;
3109 return (int)$this->mEditCount
;
3113 * Add the user to the given group.
3114 * This takes immediate effect.
3115 * @param string $group Name of the group to add
3118 public function addGroup( $group ) {
3121 if ( !Hooks
::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3125 $dbw = wfGetDB( DB_MASTER
);
3126 if ( $this->getId() ) {
3127 $dbw->insert( 'user_groups',
3129 'ug_user' => $this->getID(),
3130 'ug_group' => $group,
3133 array( 'IGNORE' ) );
3136 $this->loadGroups();
3137 $this->mGroups
[] = $group;
3138 // In case loadGroups was not called before, we now have the right twice.
3139 // Get rid of the duplicate.
3140 $this->mGroups
= array_unique( $this->mGroups
);
3142 // Refresh the groups caches, and clear the rights cache so it will be
3143 // refreshed on the next call to $this->getRights().
3144 $this->getEffectiveGroups( true );
3145 $this->mRights
= null;
3147 $this->invalidateCache();
3153 * Remove the user from the given group.
3154 * This takes immediate effect.
3155 * @param string $group Name of the group to remove
3158 public function removeGroup( $group ) {
3160 if ( !Hooks
::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3164 $dbw = wfGetDB( DB_MASTER
);
3165 $dbw->delete( 'user_groups',
3167 'ug_user' => $this->getID(),
3168 'ug_group' => $group,
3171 // Remember that the user was in this group
3172 $dbw->insert( 'user_former_groups',
3174 'ufg_user' => $this->getID(),
3175 'ufg_group' => $group,
3181 $this->loadGroups();
3182 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3184 // Refresh the groups caches, and clear the rights cache so it will be
3185 // refreshed on the next call to $this->getRights().
3186 $this->getEffectiveGroups( true );
3187 $this->mRights
= null;
3189 $this->invalidateCache();
3195 * Get whether the user is logged in
3198 public function isLoggedIn() {
3199 return $this->getID() != 0;
3203 * Get whether the user is anonymous
3206 public function isAnon() {
3207 return !$this->isLoggedIn();
3211 * Check if user is allowed to access a feature / make an action
3213 * @param string ... Permissions to test
3214 * @return bool True if user is allowed to perform *any* of the given actions
3216 public function isAllowedAny() {
3217 $permissions = func_get_args();
3218 foreach ( $permissions as $permission ) {
3219 if ( $this->isAllowed( $permission ) ) {
3228 * @param string ... Permissions to test
3229 * @return bool True if the user is allowed to perform *all* of the given actions
3231 public function isAllowedAll() {
3232 $permissions = func_get_args();
3233 foreach ( $permissions as $permission ) {
3234 if ( !$this->isAllowed( $permission ) ) {
3242 * Internal mechanics of testing a permission
3243 * @param string $action
3246 public function isAllowed( $action = '' ) {
3247 if ( $action === '' ) {
3248 return true; // In the spirit of DWIM
3250 // Patrolling may not be enabled
3251 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3252 global $wgUseRCPatrol, $wgUseNPPatrol;
3253 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3257 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3258 // by misconfiguration: 0 == 'foo'
3259 return in_array( $action, $this->getRights(), true );
3263 * Check whether to enable recent changes patrol features for this user
3264 * @return bool True or false
3266 public function useRCPatrol() {
3267 global $wgUseRCPatrol;
3268 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3272 * Check whether to enable new pages patrol features for this user
3273 * @return bool True or false
3275 public function useNPPatrol() {
3276 global $wgUseRCPatrol, $wgUseNPPatrol;
3278 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3279 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3284 * Check whether to enable new files patrol features for this user
3285 * @return bool True or false
3287 public function useFilePatrol() {
3288 global $wgUseRCPatrol, $wgUseFilePatrol;
3290 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3291 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3296 * Get the WebRequest object to use with this object
3298 * @return WebRequest
3300 public function getRequest() {
3301 if ( $this->mRequest
) {
3302 return $this->mRequest
;
3310 * Get a WatchedItem for this user and $title.
3312 * @since 1.22 $checkRights parameter added
3313 * @param Title $title
3314 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3315 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3316 * @return WatchedItem
3318 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3319 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3321 if ( isset( $this->mWatchedItems
[$key] ) ) {
3322 return $this->mWatchedItems
[$key];
3325 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3326 $this->mWatchedItems
= array();
3329 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3330 return $this->mWatchedItems
[$key];
3334 * Check the watched status of an article.
3335 * @since 1.22 $checkRights parameter added
3336 * @param Title $title Title of the article to look at
3337 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3338 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3341 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3342 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3347 * @since 1.22 $checkRights parameter added
3348 * @param Title $title Title of the article to look at
3349 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3350 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3352 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3353 $this->getWatchedItem( $title, $checkRights )->addWatch();
3354 $this->invalidateCache();
3358 * Stop watching an article.
3359 * @since 1.22 $checkRights parameter added
3360 * @param Title $title Title of the article to look at
3361 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3362 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3364 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3365 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3366 $this->invalidateCache();
3370 * Clear the user's notification timestamp for the given title.
3371 * If e-notif e-mails are on, they will receive notification mails on
3372 * the next change of the page if it's watched etc.
3373 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3374 * @param Title $title Title of the article to look at
3375 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3377 public function clearNotification( &$title, $oldid = 0 ) {
3378 global $wgUseEnotif, $wgShowUpdatedMarker;
3380 // Do nothing if the database is locked to writes
3381 if ( wfReadOnly() ) {
3385 // Do nothing if not allowed to edit the watchlist
3386 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3390 // If we're working on user's talk page, we should update the talk page message indicator
3391 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3392 if ( !Hooks
::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3397 // Try to update the DB post-send and only if needed...
3398 DeferredUpdates
::addCallableUpdate( function() use ( $that, $title, $oldid ) {
3399 if ( !$that->getNewtalk() ) {
3400 return; // no notifications to clear
3403 // Delete the last notifications (they stack up)
3404 $that->setNewtalk( false );
3406 // If there is a new, unseen, revision, use its timestamp
3408 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3411 $that->setNewtalk( true, Revision
::newFromId( $nextid ) );
3416 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3420 if ( $this->isAnon() ) {
3421 // Nothing else to do...
3425 // Only update the timestamp if the page is being watched.
3426 // The query to find out if it is watched is cached both in memcached and per-invocation,
3427 // and when it does have to be executed, it can be on a slave
3428 // If this is the user's newtalk page, we always update the timestamp
3430 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3434 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3435 $force, $oldid, WatchedItem
::DEFERRED
3440 * Resets all of the given user's page-change notification timestamps.
3441 * If e-notif e-mails are on, they will receive notification mails on
3442 * the next change of any watched page.
3443 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3445 public function clearAllNotifications() {
3446 if ( wfReadOnly() ) {
3450 // Do nothing if not allowed to edit the watchlist
3451 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3455 global $wgUseEnotif, $wgShowUpdatedMarker;
3456 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3457 $this->setNewtalk( false );
3460 $id = $this->getId();
3462 $dbw = wfGetDB( DB_MASTER
);
3463 $dbw->update( 'watchlist',
3464 array( /* SET */ 'wl_notificationtimestamp' => null ),
3465 array( /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ),
3468 // We also need to clear here the "you have new message" notification for the own user_talk page;
3469 // it's cleared one page view later in WikiPage::doViewUpdates().
3474 * Set a cookie on the user's client. Wrapper for
3475 * WebResponse::setCookie
3476 * @deprecated since 1.27
3477 * @param string $name Name of the cookie to set
3478 * @param string $value Value to set
3479 * @param int $exp Expiration time, as a UNIX time value;
3480 * if 0 or not specified, use the default $wgCookieExpiration
3481 * @param bool $secure
3482 * true: Force setting the secure attribute when setting the cookie
3483 * false: Force NOT setting the secure attribute when setting the cookie
3484 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3485 * @param array $params Array of options sent passed to WebResponse::setcookie()
3486 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3489 protected function setCookie(
3490 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3492 wfDeprecated( __METHOD__
, '1.27' );
3493 if ( $request === null ) {
3494 $request = $this->getRequest();
3496 $params['secure'] = $secure;
3497 $request->response()->setCookie( $name, $value, $exp, $params );
3501 * Clear a cookie on the user's client
3502 * @deprecated since 1.27
3503 * @param string $name Name of the cookie to clear
3504 * @param bool $secure
3505 * true: Force setting the secure attribute when setting the cookie
3506 * false: Force NOT setting the secure attribute when setting the cookie
3507 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3508 * @param array $params Array of options sent passed to WebResponse::setcookie()
3510 protected function clearCookie( $name, $secure = null, $params = array() ) {
3511 wfDeprecated( __METHOD__
, '1.27' );
3512 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3516 * Set an extended login cookie on the user's client. The expiry of the cookie
3517 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3520 * @see User::setCookie
3522 * @deprecated since 1.27
3523 * @param string $name Name of the cookie to set
3524 * @param string $value Value to set
3525 * @param bool $secure
3526 * true: Force setting the secure attribute when setting the cookie
3527 * false: Force NOT setting the secure attribute when setting the cookie
3528 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3530 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3531 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3533 wfDeprecated( __METHOD__
, '1.27' );
3536 $exp +
= $wgExtendedLoginCookieExpiration !== null
3537 ?
$wgExtendedLoginCookieExpiration
3538 : $wgCookieExpiration;
3540 $this->setCookie( $name, $value, $exp, $secure );
3544 * Persist this user's session (e.g. set cookies)
3546 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3548 * @param bool $secure Whether to force secure/insecure cookies or use default
3549 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3551 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3553 if ( 0 == $this->mId
) {
3557 $session = $this->getRequest()->getSession();
3558 if ( $request && $session->getRequest() !== $request ) {
3559 $session = $session->sessionWithRequest( $request );
3561 $delay = $session->delaySave();
3563 if ( !$session->getUser()->equals( $this ) ) {
3564 if ( !$session->canSetUser() ) {
3565 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3566 ->warning( __METHOD__
.
3567 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3571 $session->setUser( $this );
3574 $session->setRememberUser( $rememberMe );
3575 if ( $secure !== null ) {
3576 $session->setForceHTTPS( $secure );
3579 $session->persist();
3581 ScopedCallback
::consume( $delay );
3585 * Log this user out.
3587 public function logout() {
3588 if ( Hooks
::run( 'UserLogout', array( &$this ) ) ) {
3594 * Clear the user's session, and reset the instance cache.
3597 public function doLogout() {
3598 $session = $this->getRequest()->getSession();
3599 if ( !$session->canSetUser() ) {
3600 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3601 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3602 } elseif ( !$session->getUser()->equals( $this ) ) {
3603 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3604 ->warning( __METHOD__
.
3605 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3607 // But we still may as well make this user object anon
3608 $this->clearInstanceCache( 'defaults' );
3610 $this->clearInstanceCache( 'defaults' );
3611 $delay = $session->delaySave();
3612 $session->setLoggedOutTimestamp( time() );
3613 $session->setUser( new User
);
3614 $session->set( 'wsUserID', 0 ); // Other code expects this
3615 ScopedCallback
::consume( $delay );
3620 * Save this user's settings into the database.
3621 * @todo Only rarely do all these fields need to be set!
3623 public function saveSettings() {
3624 if ( wfReadOnly() ) {
3625 // @TODO: caller should deal with this instead!
3626 // This should really just be an exception.
3627 MWExceptionHandler
::logException( new DBExpectedError(
3629 "Could not update user with ID '{$this->mId}'; DB is read-only."
3635 if ( 0 == $this->mId
) {
3639 // Get a new user_touched that is higher than the old one.
3640 // This will be used for a CAS check as a last-resort safety
3641 // check against race conditions and slave lag.
3642 $oldTouched = $this->mTouched
;
3643 $newTouched = $this->newTouchedTimestamp();
3645 $dbw = wfGetDB( DB_MASTER
);
3646 $dbw->update( 'user',
3648 'user_name' => $this->mName
,
3649 'user_real_name' => $this->mRealName
,
3650 'user_email' => $this->mEmail
,
3651 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3652 'user_touched' => $dbw->timestamp( $newTouched ),
3653 'user_token' => strval( $this->mToken
),
3654 'user_email_token' => $this->mEmailToken
,
3655 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3656 ), array( /* WHERE */
3657 'user_id' => $this->mId
,
3658 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3662 if ( !$dbw->affectedRows() ) {
3663 // Maybe the problem was a missed cache update; clear it to be safe
3664 $this->clearSharedCache( 'refresh' );
3665 // User was changed in the meantime or loaded with stale data
3666 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3667 throw new MWException(
3668 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3669 " the version of the user to be saved is older than the current version."
3673 $this->mTouched
= $newTouched;
3674 $this->saveOptions();
3676 Hooks
::run( 'UserSaveSettings', array( $this ) );
3677 $this->clearSharedCache();
3678 $this->getUserPage()->invalidateCache();
3682 * If only this user's username is known, and it exists, return the user ID.
3684 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3687 public function idForName( $flags = 0 ) {
3688 $s = trim( $this->getName() );
3693 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3694 ?
wfGetDB( DB_MASTER
)
3695 : wfGetDB( DB_SLAVE
);
3697 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3698 ?
array( 'LOCK IN SHARE MODE' )
3701 $id = $db->selectField( 'user',
3702 'user_id', array( 'user_name' => $s ), __METHOD__
, $options );
3708 * Add a user to the database, return the user object
3710 * @param string $name Username to add
3711 * @param array $params Array of Strings Non-default parameters to save to
3712 * the database as user_* fields:
3713 * - email: The user's email address.
3714 * - email_authenticated: The email authentication timestamp.
3715 * - real_name: The user's real name.
3716 * - options: An associative array of non-default options.
3717 * - token: Random authentication token. Do not set.
3718 * - registration: Registration timestamp. Do not set.
3720 * @return User|null User object, or null if the username already exists.
3722 public static function createNew( $name, $params = array() ) {
3723 foreach ( array( 'password', 'newpassword', 'newpass_time', 'password_expires' ) as $field ) {
3724 if ( isset( $params[$field] ) ) {
3725 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3726 unset( $params[$field] );
3732 $user->setToken(); // init token
3733 if ( isset( $params['options'] ) ) {
3734 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3735 unset( $params['options'] );
3737 $dbw = wfGetDB( DB_MASTER
);
3738 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3740 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3743 'user_id' => $seqVal,
3744 'user_name' => $name,
3745 'user_password' => $noPass,
3746 'user_newpassword' => $noPass,
3747 'user_email' => $user->mEmail
,
3748 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3749 'user_real_name' => $user->mRealName
,
3750 'user_token' => strval( $user->mToken
),
3751 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3752 'user_editcount' => 0,
3753 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3755 foreach ( $params as $name => $value ) {
3756 $fields["user_$name"] = $value;
3758 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3759 if ( $dbw->affectedRows() ) {
3760 $newUser = User
::newFromId( $dbw->insertId() );
3768 * Add this existing user object to the database. If the user already
3769 * exists, a fatal status object is returned, and the user object is
3770 * initialised with the data from the database.
3772 * Previously, this function generated a DB error due to a key conflict
3773 * if the user already existed. Many extension callers use this function
3774 * in code along the lines of:
3776 * $user = User::newFromName( $name );
3777 * if ( !$user->isLoggedIn() ) {
3778 * $user->addToDatabase();
3780 * // do something with $user...
3782 * However, this was vulnerable to a race condition (bug 16020). By
3783 * initialising the user object if the user exists, we aim to support this
3784 * calling sequence as far as possible.
3786 * Note that if the user exists, this function will acquire a write lock,
3787 * so it is still advisable to make the call conditional on isLoggedIn(),
3788 * and to commit the transaction after calling.
3790 * @throws MWException
3793 public function addToDatabase() {
3795 if ( !$this->mToken
) {
3796 $this->setToken(); // init token
3799 $this->mTouched
= $this->newTouchedTimestamp();
3801 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3803 $dbw = wfGetDB( DB_MASTER
);
3804 $inWrite = $dbw->writesOrCallbacksPending();
3805 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3806 $dbw->insert( 'user',
3808 'user_id' => $seqVal,
3809 'user_name' => $this->mName
,
3810 'user_password' => $noPass,
3811 'user_newpassword' => $noPass,
3812 'user_email' => $this->mEmail
,
3813 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3814 'user_real_name' => $this->mRealName
,
3815 'user_token' => strval( $this->mToken
),
3816 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3817 'user_editcount' => 0,
3818 'user_touched' => $dbw->timestamp( $this->mTouched
),
3822 if ( !$dbw->affectedRows() ) {
3823 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3824 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3826 // Can't commit due to pending writes that may need atomicity.
3827 // This may cause some lock contention unlike the case below.
3828 $options = array( 'LOCK IN SHARE MODE' );
3829 $flags = self
::READ_LOCKING
;
3831 // Often, this case happens early in views before any writes when
3832 // using CentralAuth. It's should be OK to commit and break the snapshot.
3833 $dbw->commit( __METHOD__
, 'flush' );
3835 $flags = self
::READ_LATEST
;
3837 $this->mId
= $dbw->selectField( 'user', 'user_id',
3838 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3841 if ( $this->loadFromDatabase( $flags ) ) {
3846 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3847 "to insert user '{$this->mName}' row, but it was not present in select!" );
3849 return Status
::newFatal( 'userexists' );
3851 $this->mId
= $dbw->insertId();
3852 self
::$idCacheByName[$this->mName
] = $this->mId
;
3854 // Clear instance cache other than user table data, which is already accurate
3855 $this->clearInstanceCache();
3857 $this->saveOptions();
3858 return Status
::newGood();
3862 * If this user is logged-in and blocked,
3863 * block any IP address they've successfully logged in from.
3864 * @return bool A block was spread
3866 public function spreadAnyEditBlock() {
3867 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3868 return $this->spreadBlock();
3874 * If this (non-anonymous) user is blocked,
3875 * block the IP address they've successfully logged in from.
3876 * @return bool A block was spread
3878 protected function spreadBlock() {
3879 wfDebug( __METHOD__
. "()\n" );
3881 if ( $this->mId
== 0 ) {
3885 $userblock = Block
::newFromTarget( $this->getName() );
3886 if ( !$userblock ) {
3890 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3894 * Get whether the user is explicitly blocked from account creation.
3895 * @return bool|Block
3897 public function isBlockedFromCreateAccount() {
3898 $this->getBlockedStatus();
3899 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3900 return $this->mBlock
;
3903 # bug 13611: if the IP address the user is trying to create an account from is
3904 # blocked with createaccount disabled, prevent new account creation there even
3905 # when the user is logged in
3906 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3907 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3909 return $this->mBlockedFromCreateAccount
instanceof Block
3910 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3911 ?
$this->mBlockedFromCreateAccount
3916 * Get whether the user is blocked from using Special:Emailuser.
3919 public function isBlockedFromEmailuser() {
3920 $this->getBlockedStatus();
3921 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3925 * Get whether the user is allowed to create an account.
3928 public function isAllowedToCreateAccount() {
3929 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3933 * Get this user's personal page title.
3935 * @return Title User's personal page title
3937 public function getUserPage() {
3938 return Title
::makeTitle( NS_USER
, $this->getName() );
3942 * Get this user's talk page title.
3944 * @return Title User's talk page title
3946 public function getTalkPage() {
3947 $title = $this->getUserPage();
3948 return $title->getTalkPage();
3952 * Determine whether the user is a newbie. Newbies are either
3953 * anonymous IPs, or the most recently created accounts.
3956 public function isNewbie() {
3957 return !$this->isAllowed( 'autoconfirmed' );
3961 * Check to see if the given clear-text password is one of the accepted passwords
3962 * @deprecated since 1.27. AuthManager is coming.
3963 * @param string $password User password
3964 * @return bool True if the given password is correct, otherwise False
3966 public function checkPassword( $password ) {
3967 global $wgAuth, $wgLegacyEncoding;
3971 // Some passwords will give a fatal Status, which means there is
3972 // some sort of technical or security reason for this password to
3973 // be completely invalid and should never be checked (e.g., T64685)
3974 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
3978 // Certain authentication plugins do NOT want to save
3979 // domain passwords in a mysql database, so we should
3980 // check this (in case $wgAuth->strict() is false).
3981 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3983 } elseif ( $wgAuth->strict() ) {
3984 // Auth plugin doesn't allow local authentication
3986 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3987 // Auth plugin doesn't allow local authentication for this user name
3991 $passwordFactory = new PasswordFactory();
3992 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
3993 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3994 ?
wfGetDB( DB_MASTER
)
3995 : wfGetDB( DB_SLAVE
);
3998 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
3999 'user', 'user_password', array( 'user_id' => $this->getId() ), __METHOD__
4001 } catch ( PasswordError
$e ) {
4002 wfDebug( 'Invalid password hash found in database.' );
4003 $mPassword = PasswordFactory
::newInvalidPassword();
4006 if ( !$mPassword->equals( $password ) ) {
4007 if ( $wgLegacyEncoding ) {
4008 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4009 // Check for this with iconv
4010 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4011 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4019 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4020 $this->setPasswordInternal( $password );
4027 * Check if the given clear-text password matches the temporary password
4028 * sent by e-mail for password reset operations.
4030 * @deprecated since 1.27. AuthManager is coming.
4031 * @param string $plaintext
4032 * @return bool True if matches, false otherwise
4034 public function checkTemporaryPassword( $plaintext ) {
4035 global $wgNewPasswordExpiry;
4039 $passwordFactory = new PasswordFactory();
4040 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4041 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4042 ?
wfGetDB( DB_MASTER
)
4043 : wfGetDB( DB_SLAVE
);
4045 $row = $db->selectRow(
4047 array( 'user_newpassword', 'user_newpass_time' ),
4048 array( 'user_id' => $this->getId() ),
4052 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4053 } catch ( PasswordError
$e ) {
4054 wfDebug( 'Invalid password hash found in database.' );
4055 $newPassword = PasswordFactory
::newInvalidPassword();
4058 if ( $newPassword->equals( $plaintext ) ) {
4059 if ( is_null( $row->user_newpass_time
) ) {
4062 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4063 return ( time() < $expiry );
4070 * Internal implementation for self::getEditToken() and
4071 * self::matchEditToken().
4073 * @param string|array $salt
4074 * @param WebRequest $request
4075 * @param string|int $timestamp
4078 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
4079 if ( $this->isAnon() ) {
4080 return self
::EDIT_TOKEN_SUFFIX
;
4082 $token = $request->getSessionData( 'wsEditToken' );
4083 if ( $token === null ) {
4084 $token = MWCryptRand
::generateHex( 32 );
4085 $request->setSessionData( 'wsEditToken', $token );
4087 if ( is_array( $salt ) ) {
4088 $salt = implode( '|', $salt );
4090 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
4091 dechex( $timestamp ) .
4092 self
::EDIT_TOKEN_SUFFIX
;
4097 * Initialize (if necessary) and return a session token value
4098 * which can be used in edit forms to show that the user's
4099 * login credentials aren't being hijacked with a foreign form
4104 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4105 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4106 * @return string The new edit token
4108 public function getEditToken( $salt = '', $request = null ) {
4109 return $this->getEditTokenAtTimestamp(
4110 $salt, $request ?
: $this->getRequest(), wfTimestamp()
4115 * Generate a looking random token for various uses.
4117 * @return string The new random token
4118 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
4119 * wfRandomString for pseudo-randomness.
4121 public static function generateToken() {
4122 return MWCryptRand
::generateHex( 32 );
4126 * Get the embedded timestamp from a token.
4127 * @param string $val Input token
4130 public static function getEditTokenTimestamp( $val ) {
4131 $suffixLen = strlen( self
::EDIT_TOKEN_SUFFIX
);
4132 if ( strlen( $val ) <= 32 +
$suffixLen ) {
4136 return hexdec( substr( $val, 32, -$suffixLen ) );
4140 * Check given value against the token value stored in the session.
4141 * A match should confirm that the form was submitted from the
4142 * user's own login session, not a form submission from a third-party
4145 * @param string $val Input value to compare
4146 * @param string $salt Optional function-specific data for hashing
4147 * @param WebRequest|null $request Object to use or null to use $wgRequest
4148 * @param int $maxage Fail tokens older than this, in seconds
4149 * @return bool Whether the token matches
4151 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4152 if ( $this->isAnon() ) {
4153 return $val === self
::EDIT_TOKEN_SUFFIX
;
4156 $timestamp = self
::getEditTokenTimestamp( $val );
4157 if ( $timestamp === null ) {
4160 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
4165 $sessionToken = $this->getEditTokenAtTimestamp(
4166 $salt, $request ?
: $this->getRequest(), $timestamp
4169 if ( !hash_equals( $sessionToken, $val ) ) {
4170 wfDebug( "User::matchEditToken: broken session data\n" );
4173 return hash_equals( $sessionToken, $val );
4177 * Check given value against the token value stored in the session,
4178 * ignoring the suffix.
4180 * @param string $val Input value to compare
4181 * @param string $salt Optional function-specific data for hashing
4182 * @param WebRequest|null $request Object to use or null to use $wgRequest
4183 * @param int $maxage Fail tokens older than this, in seconds
4184 * @return bool Whether the token matches
4186 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4187 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4188 return $this->matchEditToken( $val, $salt, $request, $maxage );
4192 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4193 * mail to the user's given address.
4195 * @param string $type Message to send, either "created", "changed" or "set"
4198 public function sendConfirmationMail( $type = 'created' ) {
4200 $expiration = null; // gets passed-by-ref and defined in next line.
4201 $token = $this->confirmationToken( $expiration );
4202 $url = $this->confirmationTokenUrl( $token );
4203 $invalidateURL = $this->invalidationTokenUrl( $token );
4204 $this->saveSettings();
4206 if ( $type == 'created' ||
$type === false ) {
4207 $message = 'confirmemail_body';
4208 } elseif ( $type === true ) {
4209 $message = 'confirmemail_body_changed';
4211 // Messages: confirmemail_body_changed, confirmemail_body_set
4212 $message = 'confirmemail_body_' . $type;
4215 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4216 wfMessage( $message,
4217 $this->getRequest()->getIP(),
4220 $wgLang->userTimeAndDate( $expiration, $this ),
4222 $wgLang->userDate( $expiration, $this ),
4223 $wgLang->userTime( $expiration, $this ) )->text() );
4227 * Send an e-mail to this user's account. Does not check for
4228 * confirmed status or validity.
4230 * @param string $subject Message subject
4231 * @param string $body Message body
4232 * @param User|null $from Optional sending user; if unspecified, default
4233 * $wgPasswordSender will be used.
4234 * @param string $replyto Reply-To address
4237 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4238 global $wgPasswordSender;
4240 if ( $from instanceof User
) {
4241 $sender = MailAddress
::newFromUser( $from );
4243 $sender = new MailAddress( $wgPasswordSender,
4244 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4246 $to = MailAddress
::newFromUser( $this );
4248 return UserMailer
::send( $to, $sender, $subject, $body, array(
4249 'replyTo' => $replyto,
4254 * Generate, store, and return a new e-mail confirmation code.
4255 * A hash (unsalted, since it's used as a key) is stored.
4257 * @note Call saveSettings() after calling this function to commit
4258 * this change to the database.
4260 * @param string &$expiration Accepts the expiration time
4261 * @return string New token
4263 protected function confirmationToken( &$expiration ) {
4264 global $wgUserEmailConfirmationTokenExpiry;
4266 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4267 $expiration = wfTimestamp( TS_MW
, $expires );
4269 $token = MWCryptRand
::generateHex( 32 );
4270 $hash = md5( $token );
4271 $this->mEmailToken
= $hash;
4272 $this->mEmailTokenExpires
= $expiration;
4277 * Return a URL the user can use to confirm their email address.
4278 * @param string $token Accepts the email confirmation token
4279 * @return string New token URL
4281 protected function confirmationTokenUrl( $token ) {
4282 return $this->getTokenUrl( 'ConfirmEmail', $token );
4286 * Return a URL the user can use to invalidate their email address.
4287 * @param string $token Accepts the email confirmation token
4288 * @return string New token URL
4290 protected function invalidationTokenUrl( $token ) {
4291 return $this->getTokenUrl( 'InvalidateEmail', $token );
4295 * Internal function to format the e-mail validation/invalidation URLs.
4296 * This uses a quickie hack to use the
4297 * hardcoded English names of the Special: pages, for ASCII safety.
4299 * @note Since these URLs get dropped directly into emails, using the
4300 * short English names avoids insanely long URL-encoded links, which
4301 * also sometimes can get corrupted in some browsers/mailers
4302 * (bug 6957 with Gmail and Internet Explorer).
4304 * @param string $page Special page
4305 * @param string $token Token
4306 * @return string Formatted URL
4308 protected function getTokenUrl( $page, $token ) {
4309 // Hack to bypass localization of 'Special:'
4310 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4311 return $title->getCanonicalURL();
4315 * Mark the e-mail address confirmed.
4317 * @note Call saveSettings() after calling this function to commit the change.
4321 public function confirmEmail() {
4322 // Check if it's already confirmed, so we don't touch the database
4323 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4324 if ( !$this->isEmailConfirmed() ) {
4325 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4326 Hooks
::run( 'ConfirmEmailComplete', array( $this ) );
4332 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4333 * address if it was already confirmed.
4335 * @note Call saveSettings() after calling this function to commit the change.
4336 * @return bool Returns true
4338 public function invalidateEmail() {
4340 $this->mEmailToken
= null;
4341 $this->mEmailTokenExpires
= null;
4342 $this->setEmailAuthenticationTimestamp( null );
4344 Hooks
::run( 'InvalidateEmailComplete', array( $this ) );
4349 * Set the e-mail authentication timestamp.
4350 * @param string $timestamp TS_MW timestamp
4352 public function setEmailAuthenticationTimestamp( $timestamp ) {
4354 $this->mEmailAuthenticated
= $timestamp;
4355 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4359 * Is this user allowed to send e-mails within limits of current
4360 * site configuration?
4363 public function canSendEmail() {
4364 global $wgEnableEmail, $wgEnableUserEmail;
4365 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4368 $canSend = $this->isEmailConfirmed();
4369 Hooks
::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4374 * Is this user allowed to receive e-mails within limits of current
4375 * site configuration?
4378 public function canReceiveEmail() {
4379 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4383 * Is this user's e-mail address valid-looking and confirmed within
4384 * limits of the current site configuration?
4386 * @note If $wgEmailAuthentication is on, this may require the user to have
4387 * confirmed their address by returning a code or using a password
4388 * sent to the address from the wiki.
4392 public function isEmailConfirmed() {
4393 global $wgEmailAuthentication;
4396 if ( Hooks
::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4397 if ( $this->isAnon() ) {
4400 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4403 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4413 * Check whether there is an outstanding request for e-mail confirmation.
4416 public function isEmailConfirmationPending() {
4417 global $wgEmailAuthentication;
4418 return $wgEmailAuthentication &&
4419 !$this->isEmailConfirmed() &&
4420 $this->mEmailToken
&&
4421 $this->mEmailTokenExpires
> wfTimestamp();
4425 * Get the timestamp of account creation.
4427 * @return string|bool|null Timestamp of account creation, false for
4428 * non-existent/anonymous user accounts, or null if existing account
4429 * but information is not in database.
4431 public function getRegistration() {
4432 if ( $this->isAnon() ) {
4436 return $this->mRegistration
;
4440 * Get the timestamp of the first edit
4442 * @return string|bool Timestamp of first edit, or false for
4443 * non-existent/anonymous user accounts.
4445 public function getFirstEditTimestamp() {
4446 if ( $this->getId() == 0 ) {
4447 return false; // anons
4449 $dbr = wfGetDB( DB_SLAVE
);
4450 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4451 array( 'rev_user' => $this->getId() ),
4453 array( 'ORDER BY' => 'rev_timestamp ASC' )
4456 return false; // no edits
4458 return wfTimestamp( TS_MW
, $time );
4462 * Get the permissions associated with a given list of groups
4464 * @param array $groups Array of Strings List of internal group names
4465 * @return array Array of Strings List of permission key names for given groups combined
4467 public static function getGroupPermissions( $groups ) {
4468 global $wgGroupPermissions, $wgRevokePermissions;
4470 // grant every granted permission first
4471 foreach ( $groups as $group ) {
4472 if ( isset( $wgGroupPermissions[$group] ) ) {
4473 $rights = array_merge( $rights,
4474 // array_filter removes empty items
4475 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4478 // now revoke the revoked permissions
4479 foreach ( $groups as $group ) {
4480 if ( isset( $wgRevokePermissions[$group] ) ) {
4481 $rights = array_diff( $rights,
4482 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4485 return array_unique( $rights );
4489 * Get all the groups who have a given permission
4491 * @param string $role Role to check
4492 * @return array Array of Strings List of internal group names with the given permission
4494 public static function getGroupsWithPermission( $role ) {
4495 global $wgGroupPermissions;
4496 $allowedGroups = array();
4497 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4498 if ( self
::groupHasPermission( $group, $role ) ) {
4499 $allowedGroups[] = $group;
4502 return $allowedGroups;
4506 * Check, if the given group has the given permission
4508 * If you're wanting to check whether all users have a permission, use
4509 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4513 * @param string $group Group to check
4514 * @param string $role Role to check
4517 public static function groupHasPermission( $group, $role ) {
4518 global $wgGroupPermissions, $wgRevokePermissions;
4519 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4520 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4524 * Check if all users may be assumed to have the given permission
4526 * We generally assume so if the right is granted to '*' and isn't revoked
4527 * on any group. It doesn't attempt to take grants or other extension
4528 * limitations on rights into account in the general case, though, as that
4529 * would require it to always return false and defeat the purpose.
4530 * Specifically, session-based rights restrictions (such as OAuth or bot
4531 * passwords) are applied based on the current session.
4534 * @param string $right Right to check
4537 public static function isEveryoneAllowed( $right ) {
4538 global $wgGroupPermissions, $wgRevokePermissions;
4539 static $cache = array();
4541 // Use the cached results, except in unit tests which rely on
4542 // being able change the permission mid-request
4543 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4544 return $cache[$right];
4547 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4548 $cache[$right] = false;
4552 // If it's revoked anywhere, then everyone doesn't have it
4553 foreach ( $wgRevokePermissions as $rights ) {
4554 if ( isset( $rights[$right] ) && $rights[$right] ) {
4555 $cache[$right] = false;
4560 // Remove any rights that aren't allowed to the global-session user
4561 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4562 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4563 $cache[$right] = false;
4567 // Allow extensions to say false
4568 if ( !Hooks
::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4569 $cache[$right] = false;
4573 $cache[$right] = true;
4578 * Get the localized descriptive name for a group, if it exists
4580 * @param string $group Internal group name
4581 * @return string Localized descriptive group name
4583 public static function getGroupName( $group ) {
4584 $msg = wfMessage( "group-$group" );
4585 return $msg->isBlank() ?
$group : $msg->text();
4589 * Get the localized descriptive name for a member of a group, if it exists
4591 * @param string $group Internal group name
4592 * @param string $username Username for gender (since 1.19)
4593 * @return string Localized name for group member
4595 public static function getGroupMember( $group, $username = '#' ) {
4596 $msg = wfMessage( "group-$group-member", $username );
4597 return $msg->isBlank() ?
$group : $msg->text();
4601 * Return the set of defined explicit groups.
4602 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4603 * are not included, as they are defined automatically, not in the database.
4604 * @return array Array of internal group names
4606 public static function getAllGroups() {
4607 global $wgGroupPermissions, $wgRevokePermissions;
4609 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4610 self
::getImplicitGroups()
4615 * Get a list of all available permissions.
4616 * @return string[] Array of permission names
4618 public static function getAllRights() {
4619 if ( self
::$mAllRights === false ) {
4620 global $wgAvailableRights;
4621 if ( count( $wgAvailableRights ) ) {
4622 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4624 self
::$mAllRights = self
::$mCoreRights;
4626 Hooks
::run( 'UserGetAllRights', array( &self
::$mAllRights ) );
4628 return self
::$mAllRights;
4632 * Get a list of implicit groups
4633 * @return array Array of Strings Array of internal group names
4635 public static function getImplicitGroups() {
4636 global $wgImplicitGroups;
4638 $groups = $wgImplicitGroups;
4639 # Deprecated, use $wgImplicitGroups instead
4640 Hooks
::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4646 * Get the title of a page describing a particular group
4648 * @param string $group Internal group name
4649 * @return Title|bool Title of the page if it exists, false otherwise
4651 public static function getGroupPage( $group ) {
4652 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4653 if ( $msg->exists() ) {
4654 $title = Title
::newFromText( $msg->text() );
4655 if ( is_object( $title ) ) {
4663 * Create a link to the group in HTML, if available;
4664 * else return the group name.
4666 * @param string $group Internal name of the group
4667 * @param string $text The text of the link
4668 * @return string HTML link to the group
4670 public static function makeGroupLinkHTML( $group, $text = '' ) {
4671 if ( $text == '' ) {
4672 $text = self
::getGroupName( $group );
4674 $title = self
::getGroupPage( $group );
4676 return Linker
::link( $title, htmlspecialchars( $text ) );
4678 return htmlspecialchars( $text );
4683 * Create a link to the group in Wikitext, if available;
4684 * else return the group name.
4686 * @param string $group Internal name of the group
4687 * @param string $text The text of the link
4688 * @return string Wikilink to the group
4690 public static function makeGroupLinkWiki( $group, $text = '' ) {
4691 if ( $text == '' ) {
4692 $text = self
::getGroupName( $group );
4694 $title = self
::getGroupPage( $group );
4696 $page = $title->getFullText();
4697 return "[[$page|$text]]";
4704 * Returns an array of the groups that a particular group can add/remove.
4706 * @param string $group The group to check for whether it can add/remove
4707 * @return array Array( 'add' => array( addablegroups ),
4708 * 'remove' => array( removablegroups ),
4709 * 'add-self' => array( addablegroups to self),
4710 * 'remove-self' => array( removable groups from self) )
4712 public static function changeableByGroup( $group ) {
4713 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4717 'remove' => array(),
4718 'add-self' => array(),
4719 'remove-self' => array()
4722 if ( empty( $wgAddGroups[$group] ) ) {
4723 // Don't add anything to $groups
4724 } elseif ( $wgAddGroups[$group] === true ) {
4725 // You get everything
4726 $groups['add'] = self
::getAllGroups();
4727 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4728 $groups['add'] = $wgAddGroups[$group];
4731 // Same thing for remove
4732 if ( empty( $wgRemoveGroups[$group] ) ) {
4734 } elseif ( $wgRemoveGroups[$group] === true ) {
4735 $groups['remove'] = self
::getAllGroups();
4736 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4737 $groups['remove'] = $wgRemoveGroups[$group];
4740 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4741 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4742 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4743 if ( is_int( $key ) ) {
4744 $wgGroupsAddToSelf['user'][] = $value;
4749 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4750 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4751 if ( is_int( $key ) ) {
4752 $wgGroupsRemoveFromSelf['user'][] = $value;
4757 // Now figure out what groups the user can add to him/herself
4758 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4760 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4761 // No idea WHY this would be used, but it's there
4762 $groups['add-self'] = User
::getAllGroups();
4763 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4764 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4767 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4769 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4770 $groups['remove-self'] = User
::getAllGroups();
4771 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4772 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4779 * Returns an array of groups that this user can add and remove
4780 * @return array Array( 'add' => array( addablegroups ),
4781 * 'remove' => array( removablegroups ),
4782 * 'add-self' => array( addablegroups to self),
4783 * 'remove-self' => array( removable groups from self) )
4785 public function changeableGroups() {
4786 if ( $this->isAllowed( 'userrights' ) ) {
4787 // This group gives the right to modify everything (reverse-
4788 // compatibility with old "userrights lets you change
4790 // Using array_merge to make the groups reindexed
4791 $all = array_merge( User
::getAllGroups() );
4795 'add-self' => array(),
4796 'remove-self' => array()
4800 // Okay, it's not so simple, we will have to go through the arrays
4803 'remove' => array(),
4804 'add-self' => array(),
4805 'remove-self' => array()
4807 $addergroups = $this->getEffectiveGroups();
4809 foreach ( $addergroups as $addergroup ) {
4810 $groups = array_merge_recursive(
4811 $groups, $this->changeableByGroup( $addergroup )
4813 $groups['add'] = array_unique( $groups['add'] );
4814 $groups['remove'] = array_unique( $groups['remove'] );
4815 $groups['add-self'] = array_unique( $groups['add-self'] );
4816 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4822 * Deferred version of incEditCountImmediate()
4824 public function incEditCount() {
4826 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $that ) {
4827 $that->incEditCountImmediate();
4832 * Increment the user's edit-count field.
4833 * Will have no effect for anonymous users.
4836 public function incEditCountImmediate() {
4837 if ( $this->isAnon() ) {
4841 $dbw = wfGetDB( DB_MASTER
);
4842 // No rows will be "affected" if user_editcount is NULL
4845 array( 'user_editcount=user_editcount+1' ),
4846 array( 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ),
4849 // Lazy initialization check...
4850 if ( $dbw->affectedRows() == 0 ) {
4851 // Now here's a goddamn hack...
4852 $dbr = wfGetDB( DB_SLAVE
);
4853 if ( $dbr !== $dbw ) {
4854 // If we actually have a slave server, the count is
4855 // at least one behind because the current transaction
4856 // has not been committed and replicated.
4857 $this->initEditCount( 1 );
4859 // But if DB_SLAVE is selecting the master, then the
4860 // count we just read includes the revision that was
4861 // just added in the working transaction.
4862 $this->initEditCount();
4865 // Edit count in user cache too
4866 $this->invalidateCache();
4870 * Initialize user_editcount from data out of the revision table
4872 * @param int $add Edits to add to the count from the revision table
4873 * @return int Number of edits
4875 protected function initEditCount( $add = 0 ) {
4876 // Pull from a slave to be less cruel to servers
4877 // Accuracy isn't the point anyway here
4878 $dbr = wfGetDB( DB_SLAVE
);
4879 $count = (int)$dbr->selectField(
4882 array( 'rev_user' => $this->getId() ),
4885 $count = $count +
$add;
4887 $dbw = wfGetDB( DB_MASTER
);
4890 array( 'user_editcount' => $count ),
4891 array( 'user_id' => $this->getId() ),
4899 * Get the description of a given right
4901 * @param string $right Right to query
4902 * @return string Localized description of the right
4904 public static function getRightDescription( $right ) {
4905 $key = "right-$right";
4906 $msg = wfMessage( $key );
4907 return $msg->isBlank() ?
$right : $msg->text();
4911 * Make a new-style password hash
4913 * @param string $password Plain-text password
4914 * @param bool|string $salt Optional salt, may be random or the user ID.
4915 * If unspecified or false, will generate one automatically
4916 * @return string Password hash
4917 * @deprecated since 1.24, use Password class
4919 public static function crypt( $password, $salt = false ) {
4920 wfDeprecated( __METHOD__
, '1.24' );
4921 $passwordFactory = new PasswordFactory();
4922 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4923 $hash = $passwordFactory->newFromPlaintext( $password );
4924 return $hash->toString();
4928 * Compare a password hash with a plain-text password. Requires the user
4929 * ID if there's a chance that the hash is an old-style hash.
4931 * @param string $hash Password hash
4932 * @param string $password Plain-text password to compare
4933 * @param string|bool $userId User ID for old-style password salt
4936 * @deprecated since 1.24, use Password class
4938 public static function comparePasswords( $hash, $password, $userId = false ) {
4939 wfDeprecated( __METHOD__
, '1.24' );
4941 // Check for *really* old password hashes that don't even have a type
4942 // The old hash format was just an md5 hex hash, with no type information
4943 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4944 global $wgPasswordSalt;
4945 if ( $wgPasswordSalt ) {
4946 $password = ":B:{$userId}:{$hash}";
4948 $password = ":A:{$hash}";
4952 $passwordFactory = new PasswordFactory();
4953 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4954 $hash = $passwordFactory->newFromCiphertext( $hash );
4955 return $hash->equals( $password );
4959 * Add a newuser log entry for this user.
4960 * Before 1.19 the return value was always true.
4962 * @param string|bool $action Account creation type.
4963 * - String, one of the following values:
4964 * - 'create' for an anonymous user creating an account for himself.
4965 * This will force the action's performer to be the created user itself,
4966 * no matter the value of $wgUser
4967 * - 'create2' for a logged in user creating an account for someone else
4968 * - 'byemail' when the created user will receive its password by e-mail
4969 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4970 * - Boolean means whether the account was created by e-mail (deprecated):
4971 * - true will be converted to 'byemail'
4972 * - false will be converted to 'create' if this object is the same as
4973 * $wgUser and to 'create2' otherwise
4975 * @param string $reason User supplied reason
4977 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4979 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4980 global $wgUser, $wgNewUserLog;
4981 if ( empty( $wgNewUserLog ) ) {
4982 return true; // disabled
4985 if ( $action === true ) {
4986 $action = 'byemail';
4987 } elseif ( $action === false ) {
4988 if ( $this->equals( $wgUser ) ) {
4991 $action = 'create2';
4995 if ( $action === 'create' ||
$action === 'autocreate' ) {
4998 $performer = $wgUser;
5001 $logEntry = new ManualLogEntry( 'newusers', $action );
5002 $logEntry->setPerformer( $performer );
5003 $logEntry->setTarget( $this->getUserPage() );
5004 $logEntry->setComment( $reason );
5005 $logEntry->setParameters( array(
5006 '4::userid' => $this->getId(),
5008 $logid = $logEntry->insert();
5010 if ( $action !== 'autocreate' ) {
5011 $logEntry->publish( $logid );
5018 * Add an autocreate newuser log entry for this user
5019 * Used by things like CentralAuth and perhaps other authplugins.
5020 * Consider calling addNewUserLogEntry() directly instead.
5024 public function addNewUserLogEntryAutoCreate() {
5025 $this->addNewUserLogEntry( 'autocreate' );
5031 * Load the user options either from cache, the database or an array
5033 * @param array $data Rows for the current user out of the user_properties table
5035 protected function loadOptions( $data = null ) {
5040 if ( $this->mOptionsLoaded
) {
5044 $this->mOptions
= self
::getDefaultOptions();
5046 if ( !$this->getId() ) {
5047 // For unlogged-in users, load language/variant options from request.
5048 // There's no need to do it for logged-in users: they can set preferences,
5049 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5050 // so don't override user's choice (especially when the user chooses site default).
5051 $variant = $wgContLang->getDefaultVariant();
5052 $this->mOptions
['variant'] = $variant;
5053 $this->mOptions
['language'] = $variant;
5054 $this->mOptionsLoaded
= true;
5058 // Maybe load from the object
5059 if ( !is_null( $this->mOptionOverrides
) ) {
5060 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5061 foreach ( $this->mOptionOverrides
as $key => $value ) {
5062 $this->mOptions
[$key] = $value;
5065 if ( !is_array( $data ) ) {
5066 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5067 // Load from database
5068 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5069 ?
wfGetDB( DB_MASTER
)
5070 : wfGetDB( DB_SLAVE
);
5072 $res = $dbr->select(
5074 array( 'up_property', 'up_value' ),
5075 array( 'up_user' => $this->getId() ),
5079 $this->mOptionOverrides
= array();
5081 foreach ( $res as $row ) {
5082 $data[$row->up_property
] = $row->up_value
;
5085 foreach ( $data as $property => $value ) {
5086 $this->mOptionOverrides
[$property] = $value;
5087 $this->mOptions
[$property] = $value;
5091 $this->mOptionsLoaded
= true;
5093 Hooks
::run( 'UserLoadOptions', array( $this, &$this->mOptions
) );
5097 * Saves the non-default options for this user, as previously set e.g. via
5098 * setOption(), in the database's "user_properties" (preferences) table.
5099 * Usually used via saveSettings().
5101 protected function saveOptions() {
5102 $this->loadOptions();
5104 // Not using getOptions(), to keep hidden preferences in database
5105 $saveOptions = $this->mOptions
;
5107 // Allow hooks to abort, for instance to save to a global profile.
5108 // Reset options to default state before saving.
5109 if ( !Hooks
::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5113 $userId = $this->getId();
5115 $insert_rows = array(); // all the new preference rows
5116 foreach ( $saveOptions as $key => $value ) {
5117 // Don't bother storing default values
5118 $defaultOption = self
::getDefaultOption( $key );
5119 if ( ( $defaultOption === null && $value !== false && $value !== null )
5120 ||
$value != $defaultOption
5122 $insert_rows[] = array(
5123 'up_user' => $userId,
5124 'up_property' => $key,
5125 'up_value' => $value,
5130 $dbw = wfGetDB( DB_MASTER
);
5132 $res = $dbw->select( 'user_properties',
5133 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
5135 // Find prior rows that need to be removed or updated. These rows will
5136 // all be deleted (the later so that INSERT IGNORE applies the new values).
5137 $keysDelete = array();
5138 foreach ( $res as $row ) {
5139 if ( !isset( $saveOptions[$row->up_property
] )
5140 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5142 $keysDelete[] = $row->up_property
;
5146 if ( count( $keysDelete ) ) {
5147 // Do the DELETE by PRIMARY KEY for prior rows.
5148 // In the past a very large portion of calls to this function are for setting
5149 // 'rememberpassword' for new accounts (a preference that has since been removed).
5150 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5151 // caused gap locks on [max user ID,+infinity) which caused high contention since
5152 // updates would pile up on each other as they are for higher (newer) user IDs.
5153 // It might not be necessary these days, but it shouldn't hurt either.
5154 $dbw->delete( 'user_properties',
5155 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
5157 // Insert the new preference rows
5158 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
5162 * Lazily instantiate and return a factory object for making passwords
5164 * @deprecated since 1.27, create a PasswordFactory directly instead
5165 * @return PasswordFactory
5167 public static function getPasswordFactory() {
5168 wfDeprecated( __METHOD__
, '1.27' );
5169 $ret = new PasswordFactory();
5170 $ret->init( RequestContext
::getMain()->getConfig() );
5175 * Provide an array of HTML5 attributes to put on an input element
5176 * intended for the user to enter a new password. This may include
5177 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5179 * Do *not* use this when asking the user to enter his current password!
5180 * Regardless of configuration, users may have invalid passwords for whatever
5181 * reason (e.g., they were set before requirements were tightened up).
5182 * Only use it when asking for a new password, like on account creation or
5185 * Obviously, you still need to do server-side checking.
5187 * NOTE: A combination of bugs in various browsers means that this function
5188 * actually just returns array() unconditionally at the moment. May as
5189 * well keep it around for when the browser bugs get fixed, though.
5191 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5193 * @deprecated since 1.27
5194 * @return array Array of HTML attributes suitable for feeding to
5195 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5196 * That will get confused by the boolean attribute syntax used.)
5198 public static function passwordChangeInputAttribs() {
5199 global $wgMinimalPasswordLength;
5201 if ( $wgMinimalPasswordLength == 0 ) {
5205 # Note that the pattern requirement will always be satisfied if the
5206 # input is empty, so we need required in all cases.
5208 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5209 # if e-mail confirmation is being used. Since HTML5 input validation
5210 # is b0rked anyway in some browsers, just return nothing. When it's
5211 # re-enabled, fix this code to not output required for e-mail
5213 # $ret = array( 'required' );
5216 # We can't actually do this right now, because Opera 9.6 will print out
5217 # the entered password visibly in its error message! When other
5218 # browsers add support for this attribute, or Opera fixes its support,
5219 # we can add support with a version check to avoid doing this on Opera
5220 # versions where it will be a problem. Reported to Opera as
5221 # DSK-262266, but they don't have a public bug tracker for us to follow.
5223 if ( $wgMinimalPasswordLength > 1 ) {
5224 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5225 $ret['title'] = wfMessage( 'passwordtooshort' )
5226 ->numParams( $wgMinimalPasswordLength )->text();
5234 * Return the list of user fields that should be selected to create
5235 * a new user object.
5238 public static function selectFields() {
5246 'user_email_authenticated',
5248 'user_email_token_expires',
5249 'user_registration',
5255 * Factory function for fatal permission-denied errors
5258 * @param string $permission User right required
5261 static function newFatalPermissionDeniedStatus( $permission ) {
5264 $groups = array_map(
5265 array( 'User', 'makeGroupLinkWiki' ),
5266 User
::getGroupsWithPermission( $permission )
5270 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5272 return Status
::newFatal( 'badaccess-group0' );
5277 * Get a new instance of this user that was loaded from the master via a locking read
5279 * Use this instead of the main context User when updating that user. This avoids races
5280 * where that user was loaded from a slave or even the master but without proper locks.
5282 * @return User|null Returns null if the user was not found in the DB
5285 public function getInstanceForUpdate() {
5286 if ( !$this->getId() ) {
5287 return null; // anon
5290 $user = self
::newFromId( $this->getId() );
5291 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5299 * Checks if two user objects point to the same user.
5305 public function equals( User
$user ) {
5306 return $this->getName() === $user->getName();