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',
172 'userrights-interwiki',
180 * String Cached results of getAllRights()
182 protected static $mAllRights = false;
184 /** Cache variables */
194 /** @var string TS_MW timestamp from the DB */
196 /** @var string TS_MW timestamp from cache */
197 protected $mQuickTouched;
201 public $mEmailAuthenticated;
203 protected $mEmailToken;
205 protected $mEmailTokenExpires;
207 protected $mRegistration;
209 protected $mEditCount;
213 protected $mOptionOverrides;
217 * Bool Whether the cache variables have been loaded.
220 public $mOptionsLoaded;
223 * Array with already loaded items or true if all items have been loaded.
225 protected $mLoadedItems = array();
229 * String Initialization data source if mLoadedItems!==true. May be one of:
230 * - 'defaults' anonymous user initialised from class defaults
231 * - 'name' initialise from mName
232 * - 'id' initialise from mId
233 * - 'session' log in from session if possible
235 * Use the User::newFrom*() family of functions to set this.
240 * Lazy-initialized variables, invalidated with clearInstanceCache
244 protected $mDatePreference;
252 protected $mBlockreason;
254 protected $mEffectiveGroups;
256 protected $mImplicitGroups;
258 protected $mFormerGroups;
260 protected $mBlockedGlobally;
277 protected $mAllowUsertalk;
280 private $mBlockedFromCreateAccount = false;
283 private $mWatchedItems = array();
285 /** @var integer User::READ_* constant bitfield used to load data */
286 protected $queryFlagsUsed = self
::READ_NORMAL
;
288 public static $idCacheByName = array();
291 * Lightweight constructor for an anonymous user.
292 * Use the User::newFrom* factory functions for other kinds of users.
296 * @see newFromConfirmationCode()
297 * @see newFromSession()
300 public function __construct() {
301 $this->clearInstanceCache( 'defaults' );
307 public function __toString() {
308 return $this->getName();
312 * Load the user table data for this object from the source given by mFrom.
314 * @param integer $flags User::READ_* constant bitfield
316 public function load( $flags = self
::READ_NORMAL
) {
317 global $wgFullyInitialised;
319 if ( $this->mLoadedItems
=== true ) {
323 // Set it now to avoid infinite recursion in accessors
324 $oldLoadedItems = $this->mLoadedItems
;
325 $this->mLoadedItems
= true;
326 $this->queryFlagsUsed
= $flags;
328 // If this is called too early, things are likely to break.
329 if ( $this->mFrom
=== 'session' && empty( $wgFullyInitialised ) ) {
330 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
331 ->warning( 'User::loadFromSession called before the end of Setup.php' );
332 $this->loadDefaults();
333 $this->mLoadedItems
= $oldLoadedItems;
337 switch ( $this->mFrom
) {
339 $this->loadDefaults();
342 // Make sure this thread sees its own changes
343 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
344 $flags |
= self
::READ_LATEST
;
345 $this->queryFlagsUsed
= $flags;
348 $this->mId
= self
::idFromName( $this->mName
, $flags );
350 // Nonexistent user placeholder object
351 $this->loadDefaults( $this->mName
);
353 $this->loadFromId( $flags );
357 $this->loadFromId( $flags );
360 if ( !$this->loadFromSession() ) {
361 // Loading from session failed. Load defaults.
362 $this->loadDefaults();
364 Hooks
::run( 'UserLoadAfterLoadFromSession', array( $this ) );
367 throw new UnexpectedValueException(
368 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
373 * Load user table data, given mId has already been set.
374 * @param integer $flags User::READ_* constant bitfield
375 * @return bool False if the ID does not exist, true otherwise
377 public function loadFromId( $flags = self
::READ_NORMAL
) {
378 if ( $this->mId
== 0 ) {
379 $this->loadDefaults();
383 // Try cache (unless this needs data from the master DB).
384 // NOTE: if this thread called saveSettings(), the cache was cleared.
385 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
386 if ( $latest ||
!$this->loadFromCache() ) {
387 wfDebug( "User: cache miss for user {$this->mId}\n" );
388 // Load from DB (make sure this thread sees its own changes)
389 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
390 $flags |
= self
::READ_LATEST
;
392 if ( !$this->loadFromDatabase( $flags ) ) {
393 // Can't load from ID, user is anonymous
396 $this->saveToCache();
399 $this->mLoadedItems
= true;
400 $this->queryFlagsUsed
= $flags;
407 * @param string $wikiId
408 * @param integer $userId
410 public static function purge( $wikiId, $userId ) {
411 $cache = ObjectCache
::getMainWANInstance();
412 $cache->delete( $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId ) );
417 * @param WANObjectCache $cache
420 protected function getCacheKey( WANObjectCache
$cache ) {
421 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
425 * Load user data from shared cache, given mId has already been set.
427 * @return bool false if the ID does not exist or data is invalid, true otherwise
430 protected function loadFromCache() {
431 if ( $this->mId
== 0 ) {
432 $this->loadDefaults();
436 $cache = ObjectCache
::getMainWANInstance();
437 $data = $cache->get( $this->getCacheKey( $cache ) );
438 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
443 wfDebug( "User: got user {$this->mId} from cache\n" );
445 // Restore from cache
446 foreach ( self
::$mCacheVars as $name ) {
447 $this->$name = $data[$name];
454 * Save user data to the shared cache
456 * This method should not be called outside the User class
458 public function saveToCache() {
461 $this->loadOptions();
463 if ( $this->isAnon() ) {
464 // Anonymous users are uncached
469 foreach ( self
::$mCacheVars as $name ) {
470 $data[$name] = $this->$name;
472 $data['mVersion'] = self
::VERSION
;
473 $opts = Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
475 $cache = ObjectCache
::getMainWANInstance();
476 $key = $this->getCacheKey( $cache );
477 $cache->set( $key, $data, $cache::TTL_HOUR
, $opts );
480 /** @name newFrom*() static factory methods */
484 * Static factory method for creation from username.
486 * This is slightly less efficient than newFromId(), so use newFromId() if
487 * you have both an ID and a name handy.
489 * @param string $name Username, validated by Title::newFromText()
490 * @param string|bool $validate Validate username. Takes the same parameters as
491 * User::getCanonicalName(), except that true is accepted as an alias
492 * for 'valid', for BC.
494 * @return User|bool User object, or false if the username is invalid
495 * (e.g. if it contains illegal characters or is an IP address). If the
496 * username is not present in the database, the result will be a user object
497 * with a name, zero user ID and default settings.
499 public static function newFromName( $name, $validate = 'valid' ) {
500 if ( $validate === true ) {
503 $name = self
::getCanonicalName( $name, $validate );
504 if ( $name === false ) {
507 // Create unloaded user object
511 $u->setItemLoaded( 'name' );
517 * Static factory method for creation from a given user ID.
519 * @param int $id Valid user ID
520 * @return User The corresponding User object
522 public static function newFromId( $id ) {
526 $u->setItemLoaded( 'id' );
531 * Factory method to fetch whichever user has a given email confirmation code.
532 * This code is generated when an account is created or its e-mail address
535 * If the code is invalid or has expired, returns NULL.
537 * @param string $code Confirmation code
538 * @param int $flags User::READ_* bitfield
541 public static function newFromConfirmationCode( $code, $flags = 0 ) {
542 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
543 ?
wfGetDB( DB_MASTER
)
544 : wfGetDB( DB_SLAVE
);
546 $id = $db->selectField(
550 'user_email_token' => md5( $code ),
551 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
555 return $id ? User
::newFromId( $id ) : null;
559 * Create a new user object using data from session. If the login
560 * credentials are invalid, the result is an anonymous user.
562 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
565 public static function newFromSession( WebRequest
$request = null ) {
567 $user->mFrom
= 'session';
568 $user->mRequest
= $request;
573 * Create a new user object from a user row.
574 * The row should have the following fields from the user table in it:
575 * - either user_name or user_id to load further data if needed (or both)
577 * - all other fields (email, etc.)
578 * It is useless to provide the remaining fields if either user_id,
579 * user_name and user_real_name are not provided because the whole row
580 * will be loaded once more from the database when accessing them.
582 * @param stdClass $row A row from the user table
583 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
586 public static function newFromRow( $row, $data = null ) {
588 $user->loadFromRow( $row, $data );
593 * Static factory method for creation of a "system" user from username.
595 * A "system" user is an account that's used to attribute logged actions
596 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
597 * might include the 'Maintenance script' or 'Conversion script' accounts
598 * used by various scripts in the maintenance/ directory or accounts such
599 * as 'MediaWiki message delivery' used by the MassMessage extension.
601 * This can optionally create the user if it doesn't exist, and "steal" the
602 * account if it does exist.
604 * @param string $name Username
605 * @param array $options Options are:
606 * - validate: As for User::getCanonicalName(), default 'valid'
607 * - create: Whether to create the user if it doesn't already exist, default true
608 * - steal: Whether to reset the account's password and email if it
609 * already exists, default false
612 public static function newSystemUser( $name, $options = array() ) {
614 'validate' => 'valid',
619 $name = self
::getCanonicalName( $name, $options['validate'] );
620 if ( $name === false ) {
624 $dbw = wfGetDB( DB_MASTER
);
625 $row = $dbw->selectRow(
628 self
::selectFields(),
629 array( 'user_password', 'user_newpassword' )
631 array( 'user_name' => $name ),
635 // No user. Create it?
636 return $options['create'] ? self
::createNew( $name ) : null;
638 $user = self
::newFromRow( $row );
640 // A user is considered to exist as a non-system user if it has a
641 // password set, or a temporary password set, or an email set.
642 $passwordFactory = new PasswordFactory();
643 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
645 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
646 } catch ( PasswordError
$e ) {
647 wfDebug( 'Invalid password hash found in database.' );
648 $password = PasswordFactory
::newInvalidPassword();
651 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
652 } catch ( PasswordError
$e ) {
653 wfDebug( 'Invalid password hash found in database.' );
654 $newpassword = PasswordFactory
::newInvalidPassword();
656 if ( !$password instanceof InvalidPassword ||
!$newpassword instanceof InvalidPassword
659 // User exists. Steal it?
660 if ( !$options['steal'] ) {
664 $nopass = PasswordFactory
::newInvalidPassword()->toString();
669 'user_password' => $nopass,
670 'user_newpassword' => $nopass,
671 'user_newpass_time' => null,
673 array( 'user_id' => $user->getId() ),
676 $user->invalidateEmail();
677 $user->saveSettings();
680 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
688 * Get the username corresponding to a given user ID
689 * @param int $id User ID
690 * @return string|bool The corresponding username
692 public static function whoIs( $id ) {
693 return UserCache
::singleton()->getProp( $id, 'name' );
697 * Get the real name of a user given their user ID
699 * @param int $id User ID
700 * @return string|bool The corresponding user's real name
702 public static function whoIsReal( $id ) {
703 return UserCache
::singleton()->getProp( $id, 'real_name' );
707 * Get database id given a user name
708 * @param string $name Username
709 * @param integer $flags User::READ_* constant bitfield
710 * @return int|null The corresponding user's ID, or null if user is nonexistent
712 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
713 $nt = Title
::makeTitleSafe( NS_USER
, $name );
714 if ( is_null( $nt ) ) {
719 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
720 return self
::$idCacheByName[$name];
723 $db = ( $flags & self
::READ_LATEST
)
724 ?
wfGetDB( DB_MASTER
)
725 : wfGetDB( DB_SLAVE
);
730 array( 'user_name' => $nt->getText() ),
734 if ( $s === false ) {
737 $result = $s->user_id
;
740 self
::$idCacheByName[$name] = $result;
742 if ( count( self
::$idCacheByName ) > 1000 ) {
743 self
::$idCacheByName = array();
750 * Reset the cache used in idFromName(). For use in tests.
752 public static function resetIdByNameCache() {
753 self
::$idCacheByName = array();
757 * Does the string match an anonymous IPv4 address?
759 * This function exists for username validation, in order to reject
760 * usernames which are similar in form to IP addresses. Strings such
761 * as 300.300.300.300 will return true because it looks like an IP
762 * address, despite not being strictly valid.
764 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
765 * address because the usemod software would "cloak" anonymous IP
766 * addresses like this, if we allowed accounts like this to be created
767 * new users could get the old edits of these anonymous users.
769 * @param string $name Name to match
772 public static function isIP( $name ) {
773 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
774 || IP
::isIPv6( $name );
778 * Is the input a valid username?
780 * Checks if the input is a valid username, we don't want an empty string,
781 * an IP address, anything that contains slashes (would mess up subpages),
782 * is longer than the maximum allowed username size or doesn't begin with
785 * @param string $name Name to match
788 public static function isValidUserName( $name ) {
789 global $wgContLang, $wgMaxNameChars;
792 || User
::isIP( $name )
793 ||
strpos( $name, '/' ) !== false
794 ||
strlen( $name ) > $wgMaxNameChars
795 ||
$name != $wgContLang->ucfirst( $name )
797 wfDebugLog( 'username', __METHOD__
.
798 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
802 // Ensure that the name can't be misresolved as a different title,
803 // such as with extra namespace keys at the start.
804 $parsed = Title
::newFromText( $name );
805 if ( is_null( $parsed )
806 ||
$parsed->getNamespace()
807 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
808 wfDebugLog( 'username', __METHOD__
.
809 ": '$name' invalid due to ambiguous prefixes" );
813 // Check an additional blacklist of troublemaker characters.
814 // Should these be merged into the title char list?
815 $unicodeBlacklist = '/[' .
816 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
817 '\x{00a0}' . # non-breaking space
818 '\x{2000}-\x{200f}' . # various whitespace
819 '\x{2028}-\x{202f}' . # breaks and control chars
820 '\x{3000}' . # ideographic space
821 '\x{e000}-\x{f8ff}' . # private use
823 if ( preg_match( $unicodeBlacklist, $name ) ) {
824 wfDebugLog( 'username', __METHOD__
.
825 ": '$name' invalid due to blacklisted characters" );
833 * Usernames which fail to pass this function will be blocked
834 * from user login and new account registrations, but may be used
835 * internally by batch processes.
837 * If an account already exists in this form, login will be blocked
838 * by a failure to pass this function.
840 * @param string $name Name to match
843 public static function isUsableName( $name ) {
844 global $wgReservedUsernames;
845 // Must be a valid username, obviously ;)
846 if ( !self
::isValidUserName( $name ) ) {
850 static $reservedUsernames = false;
851 if ( !$reservedUsernames ) {
852 $reservedUsernames = $wgReservedUsernames;
853 Hooks
::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
856 // Certain names may be reserved for batch processes.
857 foreach ( $reservedUsernames as $reserved ) {
858 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
859 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
861 if ( $reserved == $name ) {
869 * Usernames which fail to pass this function will be blocked
870 * from new account registrations, but may be used internally
871 * either by batch processes or by user accounts which have
872 * already been created.
874 * Additional blacklisting may be added here rather than in
875 * isValidUserName() to avoid disrupting existing accounts.
877 * @param string $name String to match
880 public static function isCreatableName( $name ) {
881 global $wgInvalidUsernameCharacters;
883 // Ensure that the username isn't longer than 235 bytes, so that
884 // (at least for the builtin skins) user javascript and css files
885 // will work. (bug 23080)
886 if ( strlen( $name ) > 235 ) {
887 wfDebugLog( 'username', __METHOD__
.
888 ": '$name' invalid due to length" );
892 // Preg yells if you try to give it an empty string
893 if ( $wgInvalidUsernameCharacters !== '' ) {
894 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
895 wfDebugLog( 'username', __METHOD__
.
896 ": '$name' invalid due to wgInvalidUsernameCharacters" );
901 return self
::isUsableName( $name );
905 * Is the input a valid password for this user?
907 * @param string $password Desired password
910 public function isValidPassword( $password ) {
911 // simple boolean wrapper for getPasswordValidity
912 return $this->getPasswordValidity( $password ) === true;
916 * Given unvalidated password input, return error message on failure.
918 * @param string $password Desired password
919 * @return bool|string|array True on success, string or array of error message on failure
921 public function getPasswordValidity( $password ) {
922 $result = $this->checkPasswordValidity( $password );
923 if ( $result->isGood() ) {
927 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
928 $messages[] = $error['message'];
930 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
931 $messages[] = $warning['message'];
933 if ( count( $messages ) === 1 ) {
941 * Check if this is a valid password for this user
943 * Create a Status object based on the password's validity.
944 * The Status should be set to fatal if the user should not
945 * be allowed to log in, and should have any errors that
946 * would block changing the password.
948 * If the return value of this is not OK, the password
949 * should not be checked. If the return value is not Good,
950 * the password can be checked, but the user should not be
951 * able to set their password to this.
953 * @param string $password Desired password
954 * @param string $purpose one of 'login', 'create', 'reset'
958 public function checkPasswordValidity( $password, $purpose = 'login' ) {
959 global $wgPasswordPolicy;
961 $upp = new UserPasswordPolicy(
962 $wgPasswordPolicy['policies'],
963 $wgPasswordPolicy['checks']
966 $status = Status
::newGood();
967 $result = false; // init $result to false for the internal checks
969 if ( !Hooks
::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
970 $status->error( $result );
974 if ( $result === false ) {
975 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
977 } elseif ( $result === true ) {
980 $status->error( $result );
981 return $status; // the isValidPassword hook set a string $result and returned true
986 * Given unvalidated user input, return a canonical username, or false if
987 * the username is invalid.
988 * @param string $name User input
989 * @param string|bool $validate Type of validation to use:
990 * - false No validation
991 * - 'valid' Valid for batch processes
992 * - 'usable' Valid for batch processes and login
993 * - 'creatable' Valid for batch processes, login and account creation
995 * @throws InvalidArgumentException
996 * @return bool|string
998 public static function getCanonicalName( $name, $validate = 'valid' ) {
999 // Force usernames to capital
1001 $name = $wgContLang->ucfirst( $name );
1003 # Reject names containing '#'; these will be cleaned up
1004 # with title normalisation, but then it's too late to
1006 if ( strpos( $name, '#' ) !== false ) {
1010 // Clean up name according to title rules,
1011 // but only when validation is requested (bug 12654)
1012 $t = ( $validate !== false ) ?
1013 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
1014 // Check for invalid titles
1015 if ( is_null( $t ) ) {
1019 // Reject various classes of invalid names
1021 $name = $wgAuth->getCanonicalName( $t->getText() );
1023 switch ( $validate ) {
1027 if ( !User
::isValidUserName( $name ) ) {
1032 if ( !User
::isUsableName( $name ) ) {
1037 if ( !User
::isCreatableName( $name ) ) {
1042 throw new InvalidArgumentException(
1043 'Invalid parameter value for $validate in ' . __METHOD__
);
1049 * Count the number of edits of a user
1051 * @param int $uid User ID to check
1052 * @return int The user's edit count
1054 * @deprecated since 1.21 in favour of User::getEditCount
1056 public static function edits( $uid ) {
1057 wfDeprecated( __METHOD__
, '1.21' );
1058 $user = self
::newFromId( $uid );
1059 return $user->getEditCount();
1063 * Return a random password.
1065 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1066 * @return string New random password
1068 public static function randomPassword() {
1069 global $wgMinimalPasswordLength;
1070 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1074 * Set cached properties to default.
1076 * @note This no longer clears uncached lazy-initialised properties;
1077 * the constructor does that instead.
1079 * @param string|bool $name
1081 public function loadDefaults( $name = false ) {
1083 $this->mName
= $name;
1084 $this->mRealName
= '';
1086 $this->mOptionOverrides
= null;
1087 $this->mOptionsLoaded
= false;
1089 $request = $this->getRequest();
1090 $loggedOut = $request ?
$request->getSession()->getLoggedOutTimestamp() : 0;
1091 if ( $loggedOut !== 0 ) {
1092 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1094 $this->mTouched
= '1'; # Allow any pages to be cached
1097 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1098 $this->mEmailAuthenticated
= null;
1099 $this->mEmailToken
= '';
1100 $this->mEmailTokenExpires
= null;
1101 $this->mRegistration
= wfTimestamp( TS_MW
);
1102 $this->mGroups
= array();
1104 Hooks
::run( 'UserLoadDefaults', array( $this, $name ) );
1108 * Return whether an item has been loaded.
1110 * @param string $item Item to check. Current possibilities:
1114 * @param string $all 'all' to check if the whole object has been loaded
1115 * or any other string to check if only the item is available (e.g.
1119 public function isItemLoaded( $item, $all = 'all' ) {
1120 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1121 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1125 * Set that an item has been loaded
1127 * @param string $item
1129 protected function setItemLoaded( $item ) {
1130 if ( is_array( $this->mLoadedItems
) ) {
1131 $this->mLoadedItems
[$item] = true;
1136 * Load user data from the session.
1138 * @return bool True if the user is logged in, false otherwise.
1140 private function loadFromSession() {
1143 Hooks
::run( 'UserLoadFromSession', array( $this, &$result ), '1.27' );
1144 if ( $result !== null ) {
1148 // MediaWiki\Session\Session already did the necessary authentication of the user
1149 // returned here, so just use it if applicable.
1150 $session = $this->getRequest()->getSession();
1151 $user = $session->getUser();
1152 if ( $user->isLoggedIn() ) {
1153 $this->loadFromUserObject( $user );
1154 // Other code expects these to be set in the session, so set them.
1155 $session->set( 'wsUserID', $this->getId() );
1156 $session->set( 'wsUserName', $this->getName() );
1157 $session->set( 'wsToken', $this->mToken
);
1165 * Load user and user_group data from the database.
1166 * $this->mId must be set, this is how the user is identified.
1168 * @param integer $flags User::READ_* constant bitfield
1169 * @return bool True if the user exists, false if the user is anonymous
1171 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1173 $this->mId
= intval( $this->mId
);
1176 if ( !$this->mId
) {
1177 $this->loadDefaults();
1181 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1182 $db = wfGetDB( $index );
1184 $s = $db->selectRow(
1186 self
::selectFields(),
1187 array( 'user_id' => $this->mId
),
1192 $this->queryFlagsUsed
= $flags;
1193 Hooks
::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1195 if ( $s !== false ) {
1196 // Initialise user table data
1197 $this->loadFromRow( $s );
1198 $this->mGroups
= null; // deferred
1199 $this->getEditCount(); // revalidation for nulls
1204 $this->loadDefaults();
1210 * Initialize this object from a row from the user table.
1212 * @param stdClass $row Row from the user table to load.
1213 * @param array $data Further user data to load into the object
1215 * user_groups Array with groups out of the user_groups table
1216 * user_properties Array with properties out of the user_properties table
1218 protected function loadFromRow( $row, $data = null ) {
1221 $this->mGroups
= null; // deferred
1223 if ( isset( $row->user_name
) ) {
1224 $this->mName
= $row->user_name
;
1225 $this->mFrom
= 'name';
1226 $this->setItemLoaded( 'name' );
1231 if ( isset( $row->user_real_name
) ) {
1232 $this->mRealName
= $row->user_real_name
;
1233 $this->setItemLoaded( 'realname' );
1238 if ( isset( $row->user_id
) ) {
1239 $this->mId
= intval( $row->user_id
);
1240 $this->mFrom
= 'id';
1241 $this->setItemLoaded( 'id' );
1246 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1247 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1250 if ( isset( $row->user_editcount
) ) {
1251 $this->mEditCount
= $row->user_editcount
;
1256 if ( isset( $row->user_email
) ) {
1257 $this->mEmail
= $row->user_email
;
1258 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1259 $this->mToken
= $row->user_token
;
1260 if ( $this->mToken
== '' ) {
1261 $this->mToken
= null;
1263 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1264 $this->mEmailToken
= $row->user_email_token
;
1265 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1266 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1272 $this->mLoadedItems
= true;
1275 if ( is_array( $data ) ) {
1276 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1277 $this->mGroups
= $data['user_groups'];
1279 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1280 $this->loadOptions( $data['user_properties'] );
1286 * Load the data for this user object from another user object.
1290 protected function loadFromUserObject( $user ) {
1292 $user->loadGroups();
1293 $user->loadOptions();
1294 foreach ( self
::$mCacheVars as $var ) {
1295 $this->$var = $user->$var;
1300 * Load the groups from the database if they aren't already loaded.
1302 private function loadGroups() {
1303 if ( is_null( $this->mGroups
) ) {
1304 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1305 ?
wfGetDB( DB_MASTER
)
1306 : wfGetDB( DB_SLAVE
);
1307 $res = $db->select( 'user_groups',
1308 array( 'ug_group' ),
1309 array( 'ug_user' => $this->mId
),
1311 $this->mGroups
= array();
1312 foreach ( $res as $row ) {
1313 $this->mGroups
[] = $row->ug_group
;
1319 * Add the user to the group if he/she meets given criteria.
1321 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1322 * possible to remove manually via Special:UserRights. In such case it
1323 * will not be re-added automatically. The user will also not lose the
1324 * group if they no longer meet the criteria.
1326 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1328 * @return array Array of groups the user has been promoted to.
1330 * @see $wgAutopromoteOnce
1332 public function addAutopromoteOnceGroups( $event ) {
1333 global $wgAutopromoteOnceLogInRC, $wgAuth;
1335 if ( wfReadOnly() ||
!$this->getId() ) {
1339 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1340 if ( !count( $toPromote ) ) {
1344 if ( !$this->checkAndSetTouched() ) {
1345 return array(); // raced out (bug T48834)
1348 $oldGroups = $this->getGroups(); // previous groups
1349 foreach ( $toPromote as $group ) {
1350 $this->addGroup( $group );
1352 // update groups in external authentication database
1353 Hooks
::run( 'UserGroupsChanged', array( $this, $toPromote, array(), false ) );
1354 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1356 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1358 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1359 $logEntry->setPerformer( $this );
1360 $logEntry->setTarget( $this->getUserPage() );
1361 $logEntry->setParameters( array(
1362 '4::oldgroups' => $oldGroups,
1363 '5::newgroups' => $newGroups,
1365 $logid = $logEntry->insert();
1366 if ( $wgAutopromoteOnceLogInRC ) {
1367 $logEntry->publish( $logid );
1374 * Bump user_touched if it didn't change since this object was loaded
1376 * On success, the mTouched field is updated.
1377 * The user serialization cache is always cleared.
1379 * @return bool Whether user_touched was actually updated
1382 protected function checkAndSetTouched() {
1385 if ( !$this->mId
) {
1386 return false; // anon
1389 // Get a new user_touched that is higher than the old one
1390 $oldTouched = $this->mTouched
;
1391 $newTouched = $this->newTouchedTimestamp();
1393 $dbw = wfGetDB( DB_MASTER
);
1394 $dbw->update( 'user',
1395 array( 'user_touched' => $dbw->timestamp( $newTouched ) ),
1397 'user_id' => $this->mId
,
1398 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1402 $success = ( $dbw->affectedRows() > 0 );
1405 $this->mTouched
= $newTouched;
1406 $this->clearSharedCache();
1408 // Clears on failure too since that is desired if the cache is stale
1409 $this->clearSharedCache( 'refresh' );
1416 * Clear various cached data stored in this object. The cache of the user table
1417 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1419 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1420 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1422 public function clearInstanceCache( $reloadFrom = false ) {
1423 $this->mNewtalk
= -1;
1424 $this->mDatePreference
= null;
1425 $this->mBlockedby
= -1; # Unset
1426 $this->mHash
= false;
1427 $this->mRights
= null;
1428 $this->mEffectiveGroups
= null;
1429 $this->mImplicitGroups
= null;
1430 $this->mGroups
= null;
1431 $this->mOptions
= null;
1432 $this->mOptionsLoaded
= false;
1433 $this->mEditCount
= null;
1435 if ( $reloadFrom ) {
1436 $this->mLoadedItems
= array();
1437 $this->mFrom
= $reloadFrom;
1442 * Combine the language default options with any site-specific options
1443 * and add the default language variants.
1445 * @return array Array of String options
1447 public static function getDefaultOptions() {
1448 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1450 static $defOpt = null;
1451 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1452 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1453 // mid-request and see that change reflected in the return value of this function.
1454 // Which is insane and would never happen during normal MW operation
1458 $defOpt = $wgDefaultUserOptions;
1459 // Default language setting
1460 $defOpt['language'] = $wgContLang->getCode();
1461 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1462 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1464 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1465 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1467 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1469 Hooks
::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1475 * Get a given default option value.
1477 * @param string $opt Name of option to retrieve
1478 * @return string Default option value
1480 public static function getDefaultOption( $opt ) {
1481 $defOpts = self
::getDefaultOptions();
1482 if ( isset( $defOpts[$opt] ) ) {
1483 return $defOpts[$opt];
1490 * Get blocking information
1491 * @param bool $bFromSlave Whether to check the slave database first.
1492 * To improve performance, non-critical checks are done against slaves.
1493 * Check when actually saving should be done against master.
1495 private function getBlockedStatus( $bFromSlave = true ) {
1496 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1498 if ( -1 != $this->mBlockedby
) {
1502 wfDebug( __METHOD__
. ": checking...\n" );
1504 // Initialize data...
1505 // Otherwise something ends up stomping on $this->mBlockedby when
1506 // things get lazy-loaded later, causing false positive block hits
1507 // due to -1 !== 0. Probably session-related... Nothing should be
1508 // overwriting mBlockedby, surely?
1511 # We only need to worry about passing the IP address to the Block generator if the
1512 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1513 # know which IP address they're actually coming from
1514 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->equals( $wgUser ) ) {
1515 $ip = $this->getRequest()->getIP();
1521 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1524 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1525 && !in_array( $ip, $wgProxyWhitelist )
1528 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1530 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1531 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1532 $block->setTarget( $ip );
1533 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1535 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1536 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1537 $block->setTarget( $ip );
1541 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1542 if ( !$block instanceof Block
1543 && $wgApplyIpBlocksToXff
1545 && !$this->isAllowed( 'proxyunbannable' )
1546 && !in_array( $ip, $wgProxyWhitelist )
1548 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1549 $xff = array_map( 'trim', explode( ',', $xff ) );
1550 $xff = array_diff( $xff, array( $ip ) );
1551 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1552 $block = Block
::chooseBlock( $xffblocks, $xff );
1553 if ( $block instanceof Block
) {
1554 # Mangle the reason to alert the user that the block
1555 # originated from matching the X-Forwarded-For header.
1556 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1560 if ( $block instanceof Block
) {
1561 wfDebug( __METHOD__
. ": Found block.\n" );
1562 $this->mBlock
= $block;
1563 $this->mBlockedby
= $block->getByName();
1564 $this->mBlockreason
= $block->mReason
;
1565 $this->mHideName
= $block->mHideName
;
1566 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1568 $this->mBlockedby
= '';
1569 $this->mHideName
= 0;
1570 $this->mAllowUsertalk
= false;
1574 Hooks
::run( 'GetBlockedStatus', array( &$this ) );
1579 * Whether the given IP is in a DNS blacklist.
1581 * @param string $ip IP to check
1582 * @param bool $checkWhitelist Whether to check the whitelist first
1583 * @return bool True if blacklisted.
1585 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1586 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1588 if ( !$wgEnableDnsBlacklist ) {
1592 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1596 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1600 * Whether the given IP is in a given DNS blacklist.
1602 * @param string $ip IP to check
1603 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1604 * @return bool True if blacklisted.
1606 public function inDnsBlacklist( $ip, $bases ) {
1609 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1610 if ( IP
::isIPv4( $ip ) ) {
1611 // Reverse IP, bug 21255
1612 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1614 foreach ( (array)$bases as $base ) {
1616 // If we have an access key, use that too (ProjectHoneypot, etc.)
1618 if ( is_array( $base ) ) {
1619 if ( count( $base ) >= 2 ) {
1620 // Access key is 1, base URL is 0
1621 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1623 $host = "$ipReversed.{$base[0]}";
1625 $basename = $base[0];
1627 $host = "$ipReversed.$base";
1631 $ipList = gethostbynamel( $host );
1634 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1638 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1647 * Check if an IP address is in the local proxy list
1653 public static function isLocallyBlockedProxy( $ip ) {
1654 global $wgProxyList;
1656 if ( !$wgProxyList ) {
1660 if ( !is_array( $wgProxyList ) ) {
1661 // Load from the specified file
1662 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1665 if ( !is_array( $wgProxyList ) ) {
1667 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1669 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1670 // Old-style flipped proxy list
1679 * Is this user subject to rate limiting?
1681 * @return bool True if rate limited
1683 public function isPingLimitable() {
1684 global $wgRateLimitsExcludedIPs;
1685 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1686 // No other good way currently to disable rate limits
1687 // for specific IPs. :P
1688 // But this is a crappy hack and should die.
1691 return !$this->isAllowed( 'noratelimit' );
1695 * Primitive rate limits: enforce maximum actions per time period
1696 * to put a brake on flooding.
1698 * The method generates both a generic profiling point and a per action one
1699 * (suffix being "-$action".
1701 * @note When using a shared cache like memcached, IP-address
1702 * last-hit counters will be shared across wikis.
1704 * @param string $action Action to enforce; 'edit' if unspecified
1705 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1706 * @return bool True if a rate limiter was tripped
1708 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1709 // Call the 'PingLimiter' hook
1711 if ( !Hooks
::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1715 global $wgRateLimits;
1716 if ( !isset( $wgRateLimits[$action] ) ) {
1720 // Some groups shouldn't trigger the ping limiter, ever
1721 if ( !$this->isPingLimitable() ) {
1725 $limits = $wgRateLimits[$action];
1727 $id = $this->getId();
1730 if ( isset( $limits['anon'] ) && $id == 0 ) {
1731 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1734 if ( isset( $limits['user'] ) && $id != 0 ) {
1735 $userLimit = $limits['user'];
1737 if ( $this->isNewbie() ) {
1738 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1739 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1741 if ( isset( $limits['ip'] ) ) {
1742 $ip = $this->getRequest()->getIP();
1743 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1745 if ( isset( $limits['subnet'] ) ) {
1746 $ip = $this->getRequest()->getIP();
1749 if ( IP
::isIPv6( $ip ) ) {
1750 $parts = IP
::parseRange( "$ip/64" );
1751 $subnet = $parts[0];
1752 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1754 $subnet = $matches[1];
1756 if ( $subnet !== false ) {
1757 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1761 // Check for group-specific permissions
1762 // If more than one group applies, use the group with the highest limit
1763 foreach ( $this->getGroups() as $group ) {
1764 if ( isset( $limits[$group] ) ) {
1765 if ( $userLimit === false
1766 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1768 $userLimit = $limits[$group];
1772 // Set the user limit key
1773 if ( $userLimit !== false ) {
1774 list( $max, $period ) = $userLimit;
1775 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1776 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1779 $cache = ObjectCache
::getLocalClusterInstance();
1782 foreach ( $keys as $key => $limit ) {
1783 list( $max, $period ) = $limit;
1784 $summary = "(limit $max in {$period}s)";
1785 $count = $cache->get( $key );
1788 if ( $count >= $max ) {
1789 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1790 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1793 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1796 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1797 if ( $incrBy > 0 ) {
1798 $cache->add( $key, 0, intval( $period ) ); // first ping
1801 if ( $incrBy > 0 ) {
1802 $cache->incr( $key, $incrBy );
1810 * Check if user is blocked
1812 * @param bool $bFromSlave Whether to check the slave database instead of
1813 * the master. Hacked from false due to horrible probs on site.
1814 * @return bool True if blocked, false otherwise
1816 public function isBlocked( $bFromSlave = true ) {
1817 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1821 * Get the block affecting the user, or null if the user is not blocked
1823 * @param bool $bFromSlave Whether to check the slave database instead of the master
1824 * @return Block|null
1826 public function getBlock( $bFromSlave = true ) {
1827 $this->getBlockedStatus( $bFromSlave );
1828 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1832 * Check if user is blocked from editing a particular article
1834 * @param Title $title Title to check
1835 * @param bool $bFromSlave Whether to check the slave database instead of the master
1838 public function isBlockedFrom( $title, $bFromSlave = false ) {
1839 global $wgBlockAllowsUTEdit;
1841 $blocked = $this->isBlocked( $bFromSlave );
1842 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1843 // If a user's name is suppressed, they cannot make edits anywhere
1844 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1845 && $title->getNamespace() == NS_USER_TALK
) {
1847 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1850 Hooks
::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1856 * If user is blocked, return the name of the user who placed the block
1857 * @return string Name of blocker
1859 public function blockedBy() {
1860 $this->getBlockedStatus();
1861 return $this->mBlockedby
;
1865 * If user is blocked, return the specified reason for the block
1866 * @return string Blocking reason
1868 public function blockedFor() {
1869 $this->getBlockedStatus();
1870 return $this->mBlockreason
;
1874 * If user is blocked, return the ID for the block
1875 * @return int Block ID
1877 public function getBlockId() {
1878 $this->getBlockedStatus();
1879 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1883 * Check if user is blocked on all wikis.
1884 * Do not use for actual edit permission checks!
1885 * This is intended for quick UI checks.
1887 * @param string $ip IP address, uses current client if none given
1888 * @return bool True if blocked, false otherwise
1890 public function isBlockedGlobally( $ip = '' ) {
1891 if ( $this->mBlockedGlobally
!== null ) {
1892 return $this->mBlockedGlobally
;
1894 // User is already an IP?
1895 if ( IP
::isIPAddress( $this->getName() ) ) {
1896 $ip = $this->getName();
1898 $ip = $this->getRequest()->getIP();
1901 Hooks
::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1902 $this->mBlockedGlobally
= (bool)$blocked;
1903 return $this->mBlockedGlobally
;
1907 * Check if user account is locked
1909 * @return bool True if locked, false otherwise
1911 public function isLocked() {
1912 if ( $this->mLocked
!== null ) {
1913 return $this->mLocked
;
1916 $authUser = $wgAuth->getUserInstance( $this );
1917 $this->mLocked
= (bool)$authUser->isLocked();
1918 Hooks
::run( 'UserIsLocked', array( $this, &$this->mLocked
) );
1919 return $this->mLocked
;
1923 * Check if user account is hidden
1925 * @return bool True if hidden, false otherwise
1927 public function isHidden() {
1928 if ( $this->mHideName
!== null ) {
1929 return $this->mHideName
;
1931 $this->getBlockedStatus();
1932 if ( !$this->mHideName
) {
1934 $authUser = $wgAuth->getUserInstance( $this );
1935 $this->mHideName
= (bool)$authUser->isHidden();
1936 Hooks
::run( 'UserIsHidden', array( $this, &$this->mHideName
) );
1938 return $this->mHideName
;
1942 * Get the user's ID.
1943 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1945 public function getId() {
1946 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1947 // Special case, we know the user is anonymous
1949 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1950 // Don't load if this was initialized from an ID
1957 * Set the user and reload all fields according to a given ID
1958 * @param int $v User ID to reload
1960 public function setId( $v ) {
1962 $this->clearInstanceCache( 'id' );
1966 * Get the user name, or the IP of an anonymous user
1967 * @return string User's name or IP address
1969 public function getName() {
1970 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1971 // Special case optimisation
1972 return $this->mName
;
1975 if ( $this->mName
=== false ) {
1977 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1979 return $this->mName
;
1984 * Set the user name.
1986 * This does not reload fields from the database according to the given
1987 * name. Rather, it is used to create a temporary "nonexistent user" for
1988 * later addition to the database. It can also be used to set the IP
1989 * address for an anonymous user to something other than the current
1992 * @note User::newFromName() has roughly the same function, when the named user
1994 * @param string $str New user name to set
1996 public function setName( $str ) {
1998 $this->mName
= $str;
2002 * Get the user's name escaped by underscores.
2003 * @return string Username escaped by underscores.
2005 public function getTitleKey() {
2006 return str_replace( ' ', '_', $this->getName() );
2010 * Check if the user has new messages.
2011 * @return bool True if the user has new messages
2013 public function getNewtalk() {
2016 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2017 if ( $this->mNewtalk
=== -1 ) {
2018 $this->mNewtalk
= false; # reset talk page status
2020 // Check memcached separately for anons, who have no
2021 // entire User object stored in there.
2022 if ( !$this->mId
) {
2023 global $wgDisableAnonTalk;
2024 if ( $wgDisableAnonTalk ) {
2025 // Anon newtalk disabled by configuration.
2026 $this->mNewtalk
= false;
2028 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2031 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2035 return (bool)$this->mNewtalk
;
2039 * Return the data needed to construct links for new talk page message
2040 * alerts. If there are new messages, this will return an associative array
2041 * with the following data:
2042 * wiki: The database name of the wiki
2043 * link: Root-relative link to the user's talk page
2044 * rev: The last talk page revision that the user has seen or null. This
2045 * is useful for building diff links.
2046 * If there are no new messages, it returns an empty array.
2047 * @note This function was designed to accomodate multiple talk pages, but
2048 * currently only returns a single link and revision.
2051 public function getNewMessageLinks() {
2053 if ( !Hooks
::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2055 } elseif ( !$this->getNewtalk() ) {
2058 $utp = $this->getTalkPage();
2059 $dbr = wfGetDB( DB_SLAVE
);
2060 // Get the "last viewed rev" timestamp from the oldest message notification
2061 $timestamp = $dbr->selectField( 'user_newtalk',
2062 'MIN(user_last_timestamp)',
2063 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2065 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2066 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2070 * Get the revision ID for the last talk page revision viewed by the talk
2072 * @return int|null Revision ID or null
2074 public function getNewMessageRevisionId() {
2075 $newMessageRevisionId = null;
2076 $newMessageLinks = $this->getNewMessageLinks();
2077 if ( $newMessageLinks ) {
2078 // Note: getNewMessageLinks() never returns more than a single link
2079 // and it is always for the same wiki, but we double-check here in
2080 // case that changes some time in the future.
2081 if ( count( $newMessageLinks ) === 1
2082 && $newMessageLinks[0]['wiki'] === wfWikiID()
2083 && $newMessageLinks[0]['rev']
2085 /** @var Revision $newMessageRevision */
2086 $newMessageRevision = $newMessageLinks[0]['rev'];
2087 $newMessageRevisionId = $newMessageRevision->getId();
2090 return $newMessageRevisionId;
2094 * Internal uncached check for new messages
2097 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2098 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2099 * @return bool True if the user has new messages
2101 protected function checkNewtalk( $field, $id ) {
2102 $dbr = wfGetDB( DB_SLAVE
);
2104 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__
);
2106 return $ok !== false;
2110 * Add or update the new messages flag
2111 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2112 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2113 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2114 * @return bool True if successful, false otherwise
2116 protected function updateNewtalk( $field, $id, $curRev = null ) {
2117 // Get timestamp of the talk page revision prior to the current one
2118 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2119 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2120 // Mark the user as having new messages since this revision
2121 $dbw = wfGetDB( DB_MASTER
);
2122 $dbw->insert( 'user_newtalk',
2123 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2126 if ( $dbw->affectedRows() ) {
2127 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2130 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2136 * Clear the new messages flag for the given user
2137 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2138 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2139 * @return bool True if successful, false otherwise
2141 protected function deleteNewtalk( $field, $id ) {
2142 $dbw = wfGetDB( DB_MASTER
);
2143 $dbw->delete( 'user_newtalk',
2144 array( $field => $id ),
2146 if ( $dbw->affectedRows() ) {
2147 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2150 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2156 * Update the 'You have new messages!' status.
2157 * @param bool $val Whether the user has new messages
2158 * @param Revision $curRev New, as yet unseen revision of the user talk
2159 * page. Ignored if null or !$val.
2161 public function setNewtalk( $val, $curRev = null ) {
2162 if ( wfReadOnly() ) {
2167 $this->mNewtalk
= $val;
2169 if ( $this->isAnon() ) {
2171 $id = $this->getName();
2174 $id = $this->getId();
2178 $changed = $this->updateNewtalk( $field, $id, $curRev );
2180 $changed = $this->deleteNewtalk( $field, $id );
2184 $this->invalidateCache();
2189 * Generate a current or new-future timestamp to be stored in the
2190 * user_touched field when we update things.
2191 * @return string Timestamp in TS_MW format
2193 private function newTouchedTimestamp() {
2194 global $wgClockSkewFudge;
2196 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2197 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2198 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2205 * Clear user data from memcached
2207 * Use after applying updates to the database; caller's
2208 * responsibility to update user_touched if appropriate.
2210 * Called implicitly from invalidateCache() and saveSettings().
2212 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2214 public function clearSharedCache( $mode = 'changed' ) {
2215 if ( !$this->getId() ) {
2219 $cache = ObjectCache
::getMainWANInstance();
2220 $key = $this->getCacheKey( $cache );
2221 if ( $mode === 'refresh' ) {
2222 $cache->delete( $key, 1 );
2224 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
2225 $cache->delete( $key );
2231 * Immediately touch the user data cache for this account
2233 * Calls touch() and removes account data from memcached
2235 public function invalidateCache() {
2237 $this->clearSharedCache();
2241 * Update the "touched" timestamp for the user
2243 * This is useful on various login/logout events when making sure that
2244 * a browser or proxy that has multiple tenants does not suffer cache
2245 * pollution where the new user sees the old users content. The value
2246 * of getTouched() is checked when determining 304 vs 200 responses.
2247 * Unlike invalidateCache(), this preserves the User object cache and
2248 * avoids database writes.
2252 public function touch() {
2253 $id = $this->getId();
2255 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2256 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2257 $this->mQuickTouched
= null;
2262 * Validate the cache for this account.
2263 * @param string $timestamp A timestamp in TS_MW format
2266 public function validateCache( $timestamp ) {
2267 return ( $timestamp >= $this->getTouched() );
2271 * Get the user touched timestamp
2273 * Use this value only to validate caches via inequalities
2274 * such as in the case of HTTP If-Modified-Since response logic
2276 * @return string TS_MW Timestamp
2278 public function getTouched() {
2282 if ( $this->mQuickTouched
=== null ) {
2283 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2284 $cache = ObjectCache
::getMainWANInstance();
2286 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2289 return max( $this->mTouched
, $this->mQuickTouched
);
2292 return $this->mTouched
;
2296 * Get the user_touched timestamp field (time of last DB updates)
2297 * @return string TS_MW Timestamp
2300 public function getDBTouched() {
2303 return $this->mTouched
;
2307 * @deprecated Removed in 1.27.
2311 public function getPassword() {
2312 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2316 * @deprecated Removed in 1.27.
2320 public function getTemporaryPassword() {
2321 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2325 * Set the password and reset the random token.
2326 * Calls through to authentication plugin if necessary;
2327 * will have no effect if the auth plugin refuses to
2328 * pass the change through or if the legal password
2331 * As a special case, setting the password to null
2332 * wipes it, so the account cannot be logged in until
2333 * a new password is set, for instance via e-mail.
2335 * @deprecated since 1.27. AuthManager is coming.
2336 * @param string $str New password to set
2337 * @throws PasswordError On failure
2340 public function setPassword( $str ) {
2343 if ( $str !== null ) {
2344 if ( !$wgAuth->allowPasswordChange() ) {
2345 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2348 $status = $this->checkPasswordValidity( $str );
2349 if ( !$status->isGood() ) {
2350 throw new PasswordError( $status->getMessage()->text() );
2354 if ( !$wgAuth->setPassword( $this, $str ) ) {
2355 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2359 $this->setOption( 'watchlisttoken', false );
2360 $this->setPasswordInternal( $str );
2366 * Set the password and reset the random token unconditionally.
2368 * @deprecated since 1.27. AuthManager is coming.
2369 * @param string|null $str New password to set or null to set an invalid
2370 * password hash meaning that the user will not be able to log in
2371 * through the web interface.
2373 public function setInternalPassword( $str ) {
2376 if ( $wgAuth->allowSetLocalPassword() ) {
2378 $this->setOption( 'watchlisttoken', false );
2379 $this->setPasswordInternal( $str );
2384 * Actually set the password and such
2385 * @since 1.27 cannot set a password for a user not in the database
2386 * @param string|null $str New password to set or null to set an invalid
2387 * password hash meaning that the user will not be able to log in
2388 * through the web interface.
2390 private function setPasswordInternal( $str ) {
2391 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2393 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2396 $passwordFactory = new PasswordFactory();
2397 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2398 $dbw = wfGetDB( DB_MASTER
);
2402 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2403 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2404 'user_newpass_time' => $dbw->timestampOrNull( null ),
2414 * Get the user's current token.
2415 * @param bool $forceCreation Force the generation of a new token if the
2416 * user doesn't have one (default=true for backwards compatibility).
2417 * @return string Token
2419 public function getToken( $forceCreation = true ) {
2421 if ( !$this->mToken
&& $forceCreation ) {
2424 return $this->mToken
;
2428 * Set the random token (used for persistent authentication)
2429 * Called from loadDefaults() among other places.
2431 * @param string|bool $token If specified, set the token to this value
2433 public function setToken( $token = false ) {
2436 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2438 $this->mToken
= $token;
2443 * Set the password for a password reminder or new account email
2445 * @deprecated since 1.27, AuthManager is coming
2446 * @param string $str New password to set or null to set an invalid
2447 * password hash meaning that the user will not be able to use it
2448 * @param bool $throttle If true, reset the throttle timestamp to the present
2450 public function setNewpassword( $str, $throttle = true ) {
2451 $id = $this->getId();
2453 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2456 $dbw = wfGetDB( DB_MASTER
);
2458 $passwordFactory = new PasswordFactory();
2459 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2461 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2464 if ( $str === null ) {
2465 $update['user_newpass_time'] = null;
2466 } elseif ( $throttle ) {
2467 $update['user_newpass_time'] = $dbw->timestamp();
2470 $dbw->update( 'user', $update, array( 'user_id' => $id ), __METHOD__
);
2474 * Has password reminder email been sent within the last
2475 * $wgPasswordReminderResendTime hours?
2478 public function isPasswordReminderThrottled() {
2479 global $wgPasswordReminderResendTime;
2481 if ( !$wgPasswordReminderResendTime ) {
2487 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2488 ?
wfGetDB( DB_MASTER
)
2489 : wfGetDB( DB_SLAVE
);
2490 $newpassTime = $db->selectField(
2492 'user_newpass_time',
2493 array( 'user_id' => $this->getId() ),
2497 if ( $newpassTime === null ) {
2500 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2501 return time() < $expiry;
2505 * Get the user's e-mail address
2506 * @return string User's email address
2508 public function getEmail() {
2510 Hooks
::run( 'UserGetEmail', array( $this, &$this->mEmail
) );
2511 return $this->mEmail
;
2515 * Get the timestamp of the user's e-mail authentication
2516 * @return string TS_MW timestamp
2518 public function getEmailAuthenticationTimestamp() {
2520 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2521 return $this->mEmailAuthenticated
;
2525 * Set the user's e-mail address
2526 * @param string $str New e-mail address
2528 public function setEmail( $str ) {
2530 if ( $str == $this->mEmail
) {
2533 $this->invalidateEmail();
2534 $this->mEmail
= $str;
2535 Hooks
::run( 'UserSetEmail', array( $this, &$this->mEmail
) );
2539 * Set the user's e-mail address and a confirmation mail if needed.
2542 * @param string $str New e-mail address
2545 public function setEmailWithConfirmation( $str ) {
2546 global $wgEnableEmail, $wgEmailAuthentication;
2548 if ( !$wgEnableEmail ) {
2549 return Status
::newFatal( 'emaildisabled' );
2552 $oldaddr = $this->getEmail();
2553 if ( $str === $oldaddr ) {
2554 return Status
::newGood( true );
2557 $this->setEmail( $str );
2559 if ( $str !== '' && $wgEmailAuthentication ) {
2560 // Send a confirmation request to the new address if needed
2561 $type = $oldaddr != '' ?
'changed' : 'set';
2562 $result = $this->sendConfirmationMail( $type );
2563 if ( $result->isGood() ) {
2564 // Say to the caller that a confirmation mail has been sent
2565 $result->value
= 'eauth';
2568 $result = Status
::newGood( true );
2575 * Get the user's real name
2576 * @return string User's real name
2578 public function getRealName() {
2579 if ( !$this->isItemLoaded( 'realname' ) ) {
2583 return $this->mRealName
;
2587 * Set the user's real name
2588 * @param string $str New real name
2590 public function setRealName( $str ) {
2592 $this->mRealName
= $str;
2596 * Get the user's current setting for a given option.
2598 * @param string $oname The option to check
2599 * @param string $defaultOverride A default value returned if the option does not exist
2600 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2601 * @return string User's current value for the option
2602 * @see getBoolOption()
2603 * @see getIntOption()
2605 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2606 global $wgHiddenPrefs;
2607 $this->loadOptions();
2609 # We want 'disabled' preferences to always behave as the default value for
2610 # users, even if they have set the option explicitly in their settings (ie they
2611 # set it, and then it was disabled removing their ability to change it). But
2612 # we don't want to erase the preferences in the database in case the preference
2613 # is re-enabled again. So don't touch $mOptions, just override the returned value
2614 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2615 return self
::getDefaultOption( $oname );
2618 if ( array_key_exists( $oname, $this->mOptions
) ) {
2619 return $this->mOptions
[$oname];
2621 return $defaultOverride;
2626 * Get all user's options
2628 * @param int $flags Bitwise combination of:
2629 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2630 * to the default value. (Since 1.25)
2633 public function getOptions( $flags = 0 ) {
2634 global $wgHiddenPrefs;
2635 $this->loadOptions();
2636 $options = $this->mOptions
;
2638 # We want 'disabled' preferences to always behave as the default value for
2639 # users, even if they have set the option explicitly in their settings (ie they
2640 # set it, and then it was disabled removing their ability to change it). But
2641 # we don't want to erase the preferences in the database in case the preference
2642 # is re-enabled again. So don't touch $mOptions, just override the returned value
2643 foreach ( $wgHiddenPrefs as $pref ) {
2644 $default = self
::getDefaultOption( $pref );
2645 if ( $default !== null ) {
2646 $options[$pref] = $default;
2650 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2651 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2658 * Get the user's current setting for a given option, as a boolean value.
2660 * @param string $oname The option to check
2661 * @return bool User's current value for the option
2664 public function getBoolOption( $oname ) {
2665 return (bool)$this->getOption( $oname );
2669 * Get the user's current setting for a given option, as an integer value.
2671 * @param string $oname The option to check
2672 * @param int $defaultOverride A default value returned if the option does not exist
2673 * @return int User's current value for the option
2676 public function getIntOption( $oname, $defaultOverride = 0 ) {
2677 $val = $this->getOption( $oname );
2679 $val = $defaultOverride;
2681 return intval( $val );
2685 * Set the given option for a user.
2687 * You need to call saveSettings() to actually write to the database.
2689 * @param string $oname The option to set
2690 * @param mixed $val New value to set
2692 public function setOption( $oname, $val ) {
2693 $this->loadOptions();
2695 // Explicitly NULL values should refer to defaults
2696 if ( is_null( $val ) ) {
2697 $val = self
::getDefaultOption( $oname );
2700 $this->mOptions
[$oname] = $val;
2704 * Get a token stored in the preferences (like the watchlist one),
2705 * resetting it if it's empty (and saving changes).
2707 * @param string $oname The option name to retrieve the token from
2708 * @return string|bool User's current value for the option, or false if this option is disabled.
2709 * @see resetTokenFromOption()
2711 * @deprecated 1.26 Applications should use the OAuth extension
2713 public function getTokenFromOption( $oname ) {
2714 global $wgHiddenPrefs;
2716 $id = $this->getId();
2717 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2721 $token = $this->getOption( $oname );
2723 // Default to a value based on the user token to avoid space
2724 // wasted on storing tokens for all users. When this option
2725 // is set manually by the user, only then is it stored.
2726 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2733 * Reset a token stored in the preferences (like the watchlist one).
2734 * *Does not* save user's preferences (similarly to setOption()).
2736 * @param string $oname The option name to reset the token in
2737 * @return string|bool New token value, or false if this option is disabled.
2738 * @see getTokenFromOption()
2741 public function resetTokenFromOption( $oname ) {
2742 global $wgHiddenPrefs;
2743 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2747 $token = MWCryptRand
::generateHex( 40 );
2748 $this->setOption( $oname, $token );
2753 * Return a list of the types of user options currently returned by
2754 * User::getOptionKinds().
2756 * Currently, the option kinds are:
2757 * - 'registered' - preferences which are registered in core MediaWiki or
2758 * by extensions using the UserGetDefaultOptions hook.
2759 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2760 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2761 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2762 * be used by user scripts.
2763 * - 'special' - "preferences" that are not accessible via User::getOptions
2764 * or User::setOptions.
2765 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2766 * These are usually legacy options, removed in newer versions.
2768 * The API (and possibly others) use this function to determine the possible
2769 * option types for validation purposes, so make sure to update this when a
2770 * new option kind is added.
2772 * @see User::getOptionKinds
2773 * @return array Option kinds
2775 public static function listOptionKinds() {
2778 'registered-multiselect',
2779 'registered-checkmatrix',
2787 * Return an associative array mapping preferences keys to the kind of a preference they're
2788 * used for. Different kinds are handled differently when setting or reading preferences.
2790 * See User::listOptionKinds for the list of valid option types that can be provided.
2792 * @see User::listOptionKinds
2793 * @param IContextSource $context
2794 * @param array $options Assoc. array with options keys to check as keys.
2795 * Defaults to $this->mOptions.
2796 * @return array The key => kind mapping data
2798 public function getOptionKinds( IContextSource
$context, $options = null ) {
2799 $this->loadOptions();
2800 if ( $options === null ) {
2801 $options = $this->mOptions
;
2804 $prefs = Preferences
::getPreferences( $this, $context );
2807 // Pull out the "special" options, so they don't get converted as
2808 // multiselect or checkmatrix.
2809 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2810 foreach ( $specialOptions as $name => $value ) {
2811 unset( $prefs[$name] );
2814 // Multiselect and checkmatrix options are stored in the database with
2815 // one key per option, each having a boolean value. Extract those keys.
2816 $multiselectOptions = array();
2817 foreach ( $prefs as $name => $info ) {
2818 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2819 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2820 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2821 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2823 foreach ( $opts as $value ) {
2824 $multiselectOptions["$prefix$value"] = true;
2827 unset( $prefs[$name] );
2830 $checkmatrixOptions = array();
2831 foreach ( $prefs as $name => $info ) {
2832 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2833 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2834 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2835 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2836 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2838 foreach ( $columns as $column ) {
2839 foreach ( $rows as $row ) {
2840 $checkmatrixOptions["$prefix$column-$row"] = true;
2844 unset( $prefs[$name] );
2848 // $value is ignored
2849 foreach ( $options as $key => $value ) {
2850 if ( isset( $prefs[$key] ) ) {
2851 $mapping[$key] = 'registered';
2852 } elseif ( isset( $multiselectOptions[$key] ) ) {
2853 $mapping[$key] = 'registered-multiselect';
2854 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2855 $mapping[$key] = 'registered-checkmatrix';
2856 } elseif ( isset( $specialOptions[$key] ) ) {
2857 $mapping[$key] = 'special';
2858 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2859 $mapping[$key] = 'userjs';
2861 $mapping[$key] = 'unused';
2869 * Reset certain (or all) options to the site defaults
2871 * The optional parameter determines which kinds of preferences will be reset.
2872 * Supported values are everything that can be reported by getOptionKinds()
2873 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2875 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2876 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2877 * for backwards-compatibility.
2878 * @param IContextSource|null $context Context source used when $resetKinds
2879 * does not contain 'all', passed to getOptionKinds().
2880 * Defaults to RequestContext::getMain() when null.
2882 public function resetOptions(
2883 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2884 IContextSource
$context = null
2887 $defaultOptions = self
::getDefaultOptions();
2889 if ( !is_array( $resetKinds ) ) {
2890 $resetKinds = array( $resetKinds );
2893 if ( in_array( 'all', $resetKinds ) ) {
2894 $newOptions = $defaultOptions;
2896 if ( $context === null ) {
2897 $context = RequestContext
::getMain();
2900 $optionKinds = $this->getOptionKinds( $context );
2901 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2902 $newOptions = array();
2904 // Use default values for the options that should be deleted, and
2905 // copy old values for the ones that shouldn't.
2906 foreach ( $this->mOptions
as $key => $value ) {
2907 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2908 if ( array_key_exists( $key, $defaultOptions ) ) {
2909 $newOptions[$key] = $defaultOptions[$key];
2912 $newOptions[$key] = $value;
2917 Hooks
::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2919 $this->mOptions
= $newOptions;
2920 $this->mOptionsLoaded
= true;
2924 * Get the user's preferred date format.
2925 * @return string User's preferred date format
2927 public function getDatePreference() {
2928 // Important migration for old data rows
2929 if ( is_null( $this->mDatePreference
) ) {
2931 $value = $this->getOption( 'date' );
2932 $map = $wgLang->getDatePreferenceMigrationMap();
2933 if ( isset( $map[$value] ) ) {
2934 $value = $map[$value];
2936 $this->mDatePreference
= $value;
2938 return $this->mDatePreference
;
2942 * Determine based on the wiki configuration and the user's options,
2943 * whether this user must be over HTTPS no matter what.
2947 public function requiresHTTPS() {
2948 global $wgSecureLogin;
2949 if ( !$wgSecureLogin ) {
2952 $https = $this->getBoolOption( 'prefershttps' );
2953 Hooks
::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2955 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2962 * Get the user preferred stub threshold
2966 public function getStubThreshold() {
2967 global $wgMaxArticleSize; # Maximum article size, in Kb
2968 $threshold = $this->getIntOption( 'stubthreshold' );
2969 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2970 // If they have set an impossible value, disable the preference
2971 // so we can use the parser cache again.
2978 * Get the permissions this user has.
2979 * @return array Array of String permission names
2981 public function getRights() {
2982 if ( is_null( $this->mRights
) ) {
2983 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2984 Hooks
::run( 'UserGetRights', array( $this, &$this->mRights
) );
2985 // Force reindexation of rights when a hook has unset one of them
2986 $this->mRights
= array_values( array_unique( $this->mRights
) );
2988 return $this->mRights
;
2992 * Get the list of explicit group memberships this user has.
2993 * The implicit * and user groups are not included.
2994 * @return array Array of String internal group names
2996 public function getGroups() {
2998 $this->loadGroups();
2999 return $this->mGroups
;
3003 * Get the list of implicit group memberships this user has.
3004 * This includes all explicit groups, plus 'user' if logged in,
3005 * '*' for all accounts, and autopromoted groups
3006 * @param bool $recache Whether to avoid the cache
3007 * @return array Array of String internal group names
3009 public function getEffectiveGroups( $recache = false ) {
3010 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3011 $this->mEffectiveGroups
= array_unique( array_merge(
3012 $this->getGroups(), // explicit groups
3013 $this->getAutomaticGroups( $recache ) // implicit groups
3015 // Hook for additional groups
3016 Hooks
::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
3017 // Force reindexation of groups when a hook has unset one of them
3018 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3020 return $this->mEffectiveGroups
;
3024 * Get the list of implicit group memberships this user has.
3025 * This includes 'user' if logged in, '*' for all accounts,
3026 * and autopromoted groups
3027 * @param bool $recache Whether to avoid the cache
3028 * @return array Array of String internal group names
3030 public function getAutomaticGroups( $recache = false ) {
3031 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3032 $this->mImplicitGroups
= array( '*' );
3033 if ( $this->getId() ) {
3034 $this->mImplicitGroups
[] = 'user';
3036 $this->mImplicitGroups
= array_unique( array_merge(
3037 $this->mImplicitGroups
,
3038 Autopromote
::getAutopromoteGroups( $this )
3042 // Assure data consistency with rights/groups,
3043 // as getEffectiveGroups() depends on this function
3044 $this->mEffectiveGroups
= null;
3047 return $this->mImplicitGroups
;
3051 * Returns the groups the user has belonged to.
3053 * The user may still belong to the returned groups. Compare with getGroups().
3055 * The function will not return groups the user had belonged to before MW 1.17
3057 * @return array Names of the groups the user has belonged to.
3059 public function getFormerGroups() {
3062 if ( is_null( $this->mFormerGroups
) ) {
3063 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3064 ?
wfGetDB( DB_MASTER
)
3065 : wfGetDB( DB_SLAVE
);
3066 $res = $db->select( 'user_former_groups',
3067 array( 'ufg_group' ),
3068 array( 'ufg_user' => $this->mId
),
3070 $this->mFormerGroups
= array();
3071 foreach ( $res as $row ) {
3072 $this->mFormerGroups
[] = $row->ufg_group
;
3076 return $this->mFormerGroups
;
3080 * Get the user's edit count.
3081 * @return int|null Null for anonymous users
3083 public function getEditCount() {
3084 if ( !$this->getId() ) {
3088 if ( $this->mEditCount
=== null ) {
3089 /* Populate the count, if it has not been populated yet */
3090 $dbr = wfGetDB( DB_SLAVE
);
3091 // check if the user_editcount field has been initialized
3092 $count = $dbr->selectField(
3093 'user', 'user_editcount',
3094 array( 'user_id' => $this->mId
),
3098 if ( $count === null ) {
3099 // it has not been initialized. do so.
3100 $count = $this->initEditCount();
3102 $this->mEditCount
= $count;
3104 return (int)$this->mEditCount
;
3108 * Add the user to the given group.
3109 * This takes immediate effect.
3110 * @param string $group Name of the group to add
3113 public function addGroup( $group ) {
3116 if ( !Hooks
::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3120 $dbw = wfGetDB( DB_MASTER
);
3121 if ( $this->getId() ) {
3122 $dbw->insert( 'user_groups',
3124 'ug_user' => $this->getID(),
3125 'ug_group' => $group,
3128 array( 'IGNORE' ) );
3131 $this->loadGroups();
3132 $this->mGroups
[] = $group;
3133 // In case loadGroups was not called before, we now have the right twice.
3134 // Get rid of the duplicate.
3135 $this->mGroups
= array_unique( $this->mGroups
);
3137 // Refresh the groups caches, and clear the rights cache so it will be
3138 // refreshed on the next call to $this->getRights().
3139 $this->getEffectiveGroups( true );
3140 $this->mRights
= null;
3142 $this->invalidateCache();
3148 * Remove the user from the given group.
3149 * This takes immediate effect.
3150 * @param string $group Name of the group to remove
3153 public function removeGroup( $group ) {
3155 if ( !Hooks
::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3159 $dbw = wfGetDB( DB_MASTER
);
3160 $dbw->delete( 'user_groups',
3162 'ug_user' => $this->getID(),
3163 'ug_group' => $group,
3166 // Remember that the user was in this group
3167 $dbw->insert( 'user_former_groups',
3169 'ufg_user' => $this->getID(),
3170 'ufg_group' => $group,
3176 $this->loadGroups();
3177 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3179 // Refresh the groups caches, and clear the rights cache so it will be
3180 // refreshed on the next call to $this->getRights().
3181 $this->getEffectiveGroups( true );
3182 $this->mRights
= null;
3184 $this->invalidateCache();
3190 * Get whether the user is logged in
3193 public function isLoggedIn() {
3194 return $this->getID() != 0;
3198 * Get whether the user is anonymous
3201 public function isAnon() {
3202 return !$this->isLoggedIn();
3206 * Check if user is allowed to access a feature / make an action
3208 * @param string ... Permissions to test
3209 * @return bool True if user is allowed to perform *any* of the given actions
3211 public function isAllowedAny() {
3212 $permissions = func_get_args();
3213 foreach ( $permissions as $permission ) {
3214 if ( $this->isAllowed( $permission ) ) {
3223 * @param string ... Permissions to test
3224 * @return bool True if the user is allowed to perform *all* of the given actions
3226 public function isAllowedAll() {
3227 $permissions = func_get_args();
3228 foreach ( $permissions as $permission ) {
3229 if ( !$this->isAllowed( $permission ) ) {
3237 * Internal mechanics of testing a permission
3238 * @param string $action
3241 public function isAllowed( $action = '' ) {
3242 if ( $action === '' ) {
3243 return true; // In the spirit of DWIM
3245 // Patrolling may not be enabled
3246 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3247 global $wgUseRCPatrol, $wgUseNPPatrol;
3248 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3252 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3253 // by misconfiguration: 0 == 'foo'
3254 return in_array( $action, $this->getRights(), true );
3258 * Check whether to enable recent changes patrol features for this user
3259 * @return bool True or false
3261 public function useRCPatrol() {
3262 global $wgUseRCPatrol;
3263 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3267 * Check whether to enable new pages patrol features for this user
3268 * @return bool True or false
3270 public function useNPPatrol() {
3271 global $wgUseRCPatrol, $wgUseNPPatrol;
3273 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3274 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3279 * Check whether to enable new files patrol features for this user
3280 * @return bool True or false
3282 public function useFilePatrol() {
3283 global $wgUseRCPatrol, $wgUseFilePatrol;
3285 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3286 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3291 * Get the WebRequest object to use with this object
3293 * @return WebRequest
3295 public function getRequest() {
3296 if ( $this->mRequest
) {
3297 return $this->mRequest
;
3305 * Get a WatchedItem for this user and $title.
3307 * @since 1.22 $checkRights parameter added
3308 * @param Title $title
3309 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3310 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3311 * @return WatchedItem
3313 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3314 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3316 if ( isset( $this->mWatchedItems
[$key] ) ) {
3317 return $this->mWatchedItems
[$key];
3320 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3321 $this->mWatchedItems
= array();
3324 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3325 return $this->mWatchedItems
[$key];
3329 * Check the watched status of an article.
3330 * @since 1.22 $checkRights parameter added
3331 * @param Title $title Title of the article to look at
3332 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3333 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3336 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3337 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3342 * @since 1.22 $checkRights parameter added
3343 * @param Title $title Title of the article to look at
3344 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3345 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3347 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3348 $this->getWatchedItem( $title, $checkRights )->addWatch();
3349 $this->invalidateCache();
3353 * Stop watching an article.
3354 * @since 1.22 $checkRights parameter added
3355 * @param Title $title Title of the article to look at
3356 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3357 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3359 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3360 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3361 $this->invalidateCache();
3365 * Clear the user's notification timestamp for the given title.
3366 * If e-notif e-mails are on, they will receive notification mails on
3367 * the next change of the page if it's watched etc.
3368 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3369 * @param Title $title Title of the article to look at
3370 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3372 public function clearNotification( &$title, $oldid = 0 ) {
3373 global $wgUseEnotif, $wgShowUpdatedMarker;
3375 // Do nothing if the database is locked to writes
3376 if ( wfReadOnly() ) {
3380 // Do nothing if not allowed to edit the watchlist
3381 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3385 // If we're working on user's talk page, we should update the talk page message indicator
3386 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3387 if ( !Hooks
::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3392 // Try to update the DB post-send and only if needed...
3393 DeferredUpdates
::addCallableUpdate( function() use ( $that, $title, $oldid ) {
3394 if ( !$that->getNewtalk() ) {
3395 return; // no notifications to clear
3398 // Delete the last notifications (they stack up)
3399 $that->setNewtalk( false );
3401 // If there is a new, unseen, revision, use its timestamp
3403 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3406 $that->setNewtalk( true, Revision
::newFromId( $nextid ) );
3411 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3415 if ( $this->isAnon() ) {
3416 // Nothing else to do...
3420 // Only update the timestamp if the page is being watched.
3421 // The query to find out if it is watched is cached both in memcached and per-invocation,
3422 // and when it does have to be executed, it can be on a slave
3423 // If this is the user's newtalk page, we always update the timestamp
3425 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3429 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3430 $force, $oldid, WatchedItem
::DEFERRED
3435 * Resets all of the given user's page-change notification timestamps.
3436 * If e-notif e-mails are on, they will receive notification mails on
3437 * the next change of any watched page.
3438 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3440 public function clearAllNotifications() {
3441 if ( wfReadOnly() ) {
3445 // Do nothing if not allowed to edit the watchlist
3446 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3450 global $wgUseEnotif, $wgShowUpdatedMarker;
3451 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3452 $this->setNewtalk( false );
3455 $id = $this->getId();
3457 $dbw = wfGetDB( DB_MASTER
);
3458 $dbw->update( 'watchlist',
3459 array( /* SET */ 'wl_notificationtimestamp' => null ),
3460 array( /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ),
3463 // We also need to clear here the "you have new message" notification for the own user_talk page;
3464 // it's cleared one page view later in WikiPage::doViewUpdates().
3469 * Set a cookie on the user's client. Wrapper for
3470 * WebResponse::setCookie
3471 * @deprecated since 1.27
3472 * @param string $name Name of the cookie to set
3473 * @param string $value Value to set
3474 * @param int $exp Expiration time, as a UNIX time value;
3475 * if 0 or not specified, use the default $wgCookieExpiration
3476 * @param bool $secure
3477 * true: Force setting the secure attribute when setting the cookie
3478 * false: Force NOT setting the secure attribute when setting the cookie
3479 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3480 * @param array $params Array of options sent passed to WebResponse::setcookie()
3481 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3484 protected function setCookie(
3485 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3487 wfDeprecated( __METHOD__
, '1.27' );
3488 if ( $request === null ) {
3489 $request = $this->getRequest();
3491 $params['secure'] = $secure;
3492 $request->response()->setCookie( $name, $value, $exp, $params );
3496 * Clear a cookie on the user's client
3497 * @deprecated since 1.27
3498 * @param string $name Name of the cookie to clear
3499 * @param bool $secure
3500 * true: Force setting the secure attribute when setting the cookie
3501 * false: Force NOT setting the secure attribute when setting the cookie
3502 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3503 * @param array $params Array of options sent passed to WebResponse::setcookie()
3505 protected function clearCookie( $name, $secure = null, $params = array() ) {
3506 wfDeprecated( __METHOD__
, '1.27' );
3507 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3511 * Set an extended login cookie on the user's client. The expiry of the cookie
3512 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3515 * @see User::setCookie
3517 * @deprecated since 1.27
3518 * @param string $name Name of the cookie to set
3519 * @param string $value Value to set
3520 * @param bool $secure
3521 * true: Force setting the secure attribute when setting the cookie
3522 * false: Force NOT setting the secure attribute when setting the cookie
3523 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3525 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3526 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3528 wfDeprecated( __METHOD__
, '1.27' );
3531 $exp +
= $wgExtendedLoginCookieExpiration !== null
3532 ?
$wgExtendedLoginCookieExpiration
3533 : $wgCookieExpiration;
3535 $this->setCookie( $name, $value, $exp, $secure );
3539 * Persist this user's session (e.g. set cookies)
3541 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3543 * @param bool $secure Whether to force secure/insecure cookies or use default
3544 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3546 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3548 if ( 0 == $this->mId
) {
3552 $session = $this->getRequest()->getSession();
3553 if ( $request && $session->getRequest() !== $request ) {
3554 $session = $session->sessionWithRequest( $request );
3556 $delay = $session->delaySave();
3558 if ( !$session->getUser()->equals( $this ) ) {
3559 if ( !$session->canSetUser() ) {
3560 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3561 ->warning( __METHOD__
.
3562 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3566 $session->setUser( $this );
3569 $session->setRememberUser( $rememberMe );
3570 if ( $secure !== null ) {
3571 $session->setForceHTTPS( $secure );
3574 $session->persist();
3576 ScopedCallback
::consume( $delay );
3580 * Log this user out.
3582 public function logout() {
3583 if ( Hooks
::run( 'UserLogout', array( &$this ) ) ) {
3589 * Clear the user's session, and reset the instance cache.
3592 public function doLogout() {
3593 $session = $this->getRequest()->getSession();
3594 if ( !$session->canSetUser() ) {
3595 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3596 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3597 } elseif ( !$session->getUser()->equals( $this ) ) {
3598 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3599 ->warning( __METHOD__
.
3600 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3602 // But we still may as well make this user object anon
3603 $this->clearInstanceCache( 'defaults' );
3605 $this->clearInstanceCache( 'defaults' );
3606 $delay = $session->delaySave();
3607 $session->setLoggedOutTimestamp( time() );
3608 $session->setUser( new User
);
3609 $session->set( 'wsUserID', 0 ); // Other code expects this
3610 ScopedCallback
::consume( $delay );
3615 * Save this user's settings into the database.
3616 * @todo Only rarely do all these fields need to be set!
3618 public function saveSettings() {
3619 if ( wfReadOnly() ) {
3620 // @TODO: caller should deal with this instead!
3621 // This should really just be an exception.
3622 MWExceptionHandler
::logException( new DBExpectedError(
3624 "Could not update user with ID '{$this->mId}'; DB is read-only."
3630 if ( 0 == $this->mId
) {
3634 // Get a new user_touched that is higher than the old one.
3635 // This will be used for a CAS check as a last-resort safety
3636 // check against race conditions and slave lag.
3637 $oldTouched = $this->mTouched
;
3638 $newTouched = $this->newTouchedTimestamp();
3640 $dbw = wfGetDB( DB_MASTER
);
3641 $dbw->update( 'user',
3643 'user_name' => $this->mName
,
3644 'user_real_name' => $this->mRealName
,
3645 'user_email' => $this->mEmail
,
3646 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3647 'user_touched' => $dbw->timestamp( $newTouched ),
3648 'user_token' => strval( $this->mToken
),
3649 'user_email_token' => $this->mEmailToken
,
3650 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3651 ), array( /* WHERE */
3652 'user_id' => $this->mId
,
3653 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3657 if ( !$dbw->affectedRows() ) {
3658 // Maybe the problem was a missed cache update; clear it to be safe
3659 $this->clearSharedCache( 'refresh' );
3660 // User was changed in the meantime or loaded with stale data
3661 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3662 throw new MWException(
3663 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3664 " the version of the user to be saved is older than the current version."
3668 $this->mTouched
= $newTouched;
3669 $this->saveOptions();
3671 Hooks
::run( 'UserSaveSettings', array( $this ) );
3672 $this->clearSharedCache();
3673 $this->getUserPage()->invalidateCache();
3677 * If only this user's username is known, and it exists, return the user ID.
3679 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3682 public function idForName( $flags = 0 ) {
3683 $s = trim( $this->getName() );
3688 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3689 ?
wfGetDB( DB_MASTER
)
3690 : wfGetDB( DB_SLAVE
);
3692 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3693 ?
array( 'LOCK IN SHARE MODE' )
3696 $id = $db->selectField( 'user',
3697 'user_id', array( 'user_name' => $s ), __METHOD__
, $options );
3703 * Add a user to the database, return the user object
3705 * @param string $name Username to add
3706 * @param array $params Array of Strings Non-default parameters to save to
3707 * the database as user_* fields:
3708 * - email: The user's email address.
3709 * - email_authenticated: The email authentication timestamp.
3710 * - real_name: The user's real name.
3711 * - options: An associative array of non-default options.
3712 * - token: Random authentication token. Do not set.
3713 * - registration: Registration timestamp. Do not set.
3715 * @return User|null User object, or null if the username already exists.
3717 public static function createNew( $name, $params = array() ) {
3718 foreach ( array( 'password', 'newpassword', 'newpass_time', 'password_expires' ) as $field ) {
3719 if ( isset( $params[$field] ) ) {
3720 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3721 unset( $params[$field] );
3727 $user->setToken(); // init token
3728 if ( isset( $params['options'] ) ) {
3729 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3730 unset( $params['options'] );
3732 $dbw = wfGetDB( DB_MASTER
);
3733 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3735 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3738 'user_id' => $seqVal,
3739 'user_name' => $name,
3740 'user_password' => $noPass,
3741 'user_newpassword' => $noPass,
3742 'user_email' => $user->mEmail
,
3743 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3744 'user_real_name' => $user->mRealName
,
3745 'user_token' => strval( $user->mToken
),
3746 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3747 'user_editcount' => 0,
3748 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3750 foreach ( $params as $name => $value ) {
3751 $fields["user_$name"] = $value;
3753 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3754 if ( $dbw->affectedRows() ) {
3755 $newUser = User
::newFromId( $dbw->insertId() );
3763 * Add this existing user object to the database. If the user already
3764 * exists, a fatal status object is returned, and the user object is
3765 * initialised with the data from the database.
3767 * Previously, this function generated a DB error due to a key conflict
3768 * if the user already existed. Many extension callers use this function
3769 * in code along the lines of:
3771 * $user = User::newFromName( $name );
3772 * if ( !$user->isLoggedIn() ) {
3773 * $user->addToDatabase();
3775 * // do something with $user...
3777 * However, this was vulnerable to a race condition (bug 16020). By
3778 * initialising the user object if the user exists, we aim to support this
3779 * calling sequence as far as possible.
3781 * Note that if the user exists, this function will acquire a write lock,
3782 * so it is still advisable to make the call conditional on isLoggedIn(),
3783 * and to commit the transaction after calling.
3785 * @throws MWException
3788 public function addToDatabase() {
3790 if ( !$this->mToken
) {
3791 $this->setToken(); // init token
3794 $this->mTouched
= $this->newTouchedTimestamp();
3796 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3798 $dbw = wfGetDB( DB_MASTER
);
3799 $inWrite = $dbw->writesOrCallbacksPending();
3800 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3801 $dbw->insert( 'user',
3803 'user_id' => $seqVal,
3804 'user_name' => $this->mName
,
3805 'user_password' => $noPass,
3806 'user_newpassword' => $noPass,
3807 'user_email' => $this->mEmail
,
3808 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3809 'user_real_name' => $this->mRealName
,
3810 'user_token' => strval( $this->mToken
),
3811 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3812 'user_editcount' => 0,
3813 'user_touched' => $dbw->timestamp( $this->mTouched
),
3817 if ( !$dbw->affectedRows() ) {
3818 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3819 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3821 // Can't commit due to pending writes that may need atomicity.
3822 // This may cause some lock contention unlike the case below.
3823 $options = array( 'LOCK IN SHARE MODE' );
3824 $flags = self
::READ_LOCKING
;
3826 // Often, this case happens early in views before any writes when
3827 // using CentralAuth. It's should be OK to commit and break the snapshot.
3828 $dbw->commit( __METHOD__
, 'flush' );
3830 $flags = self
::READ_LATEST
;
3832 $this->mId
= $dbw->selectField( 'user', 'user_id',
3833 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3836 if ( $this->loadFromDatabase( $flags ) ) {
3841 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3842 "to insert user '{$this->mName}' row, but it was not present in select!" );
3844 return Status
::newFatal( 'userexists' );
3846 $this->mId
= $dbw->insertId();
3847 self
::$idCacheByName[$this->mName
] = $this->mId
;
3849 // Clear instance cache other than user table data, which is already accurate
3850 $this->clearInstanceCache();
3852 $this->saveOptions();
3853 return Status
::newGood();
3857 * If this user is logged-in and blocked,
3858 * block any IP address they've successfully logged in from.
3859 * @return bool A block was spread
3861 public function spreadAnyEditBlock() {
3862 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3863 return $this->spreadBlock();
3869 * If this (non-anonymous) user is blocked,
3870 * block the IP address they've successfully logged in from.
3871 * @return bool A block was spread
3873 protected function spreadBlock() {
3874 wfDebug( __METHOD__
. "()\n" );
3876 if ( $this->mId
== 0 ) {
3880 $userblock = Block
::newFromTarget( $this->getName() );
3881 if ( !$userblock ) {
3885 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3889 * Get whether the user is explicitly blocked from account creation.
3890 * @return bool|Block
3892 public function isBlockedFromCreateAccount() {
3893 $this->getBlockedStatus();
3894 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3895 return $this->mBlock
;
3898 # bug 13611: if the IP address the user is trying to create an account from is
3899 # blocked with createaccount disabled, prevent new account creation there even
3900 # when the user is logged in
3901 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3902 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3904 return $this->mBlockedFromCreateAccount
instanceof Block
3905 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3906 ?
$this->mBlockedFromCreateAccount
3911 * Get whether the user is blocked from using Special:Emailuser.
3914 public function isBlockedFromEmailuser() {
3915 $this->getBlockedStatus();
3916 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3920 * Get whether the user is allowed to create an account.
3923 public function isAllowedToCreateAccount() {
3924 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3928 * Get this user's personal page title.
3930 * @return Title User's personal page title
3932 public function getUserPage() {
3933 return Title
::makeTitle( NS_USER
, $this->getName() );
3937 * Get this user's talk page title.
3939 * @return Title User's talk page title
3941 public function getTalkPage() {
3942 $title = $this->getUserPage();
3943 return $title->getTalkPage();
3947 * Determine whether the user is a newbie. Newbies are either
3948 * anonymous IPs, or the most recently created accounts.
3951 public function isNewbie() {
3952 return !$this->isAllowed( 'autoconfirmed' );
3956 * Check to see if the given clear-text password is one of the accepted passwords
3957 * @deprecated since 1.27. AuthManager is coming.
3958 * @param string $password User password
3959 * @return bool True if the given password is correct, otherwise False
3961 public function checkPassword( $password ) {
3962 global $wgAuth, $wgLegacyEncoding;
3966 // Some passwords will give a fatal Status, which means there is
3967 // some sort of technical or security reason for this password to
3968 // be completely invalid and should never be checked (e.g., T64685)
3969 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
3973 // Certain authentication plugins do NOT want to save
3974 // domain passwords in a mysql database, so we should
3975 // check this (in case $wgAuth->strict() is false).
3976 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3978 } elseif ( $wgAuth->strict() ) {
3979 // Auth plugin doesn't allow local authentication
3981 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3982 // Auth plugin doesn't allow local authentication for this user name
3986 $passwordFactory = new PasswordFactory();
3987 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
3988 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3989 ?
wfGetDB( DB_MASTER
)
3990 : wfGetDB( DB_SLAVE
);
3993 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
3994 'user', 'user_password', array( 'user_id' => $this->getId() ), __METHOD__
3996 } catch ( PasswordError
$e ) {
3997 wfDebug( 'Invalid password hash found in database.' );
3998 $mPassword = PasswordFactory
::newInvalidPassword();
4001 if ( !$mPassword->equals( $password ) ) {
4002 if ( $wgLegacyEncoding ) {
4003 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4004 // Check for this with iconv
4005 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4006 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4014 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4015 $this->setPasswordInternal( $password );
4022 * Check if the given clear-text password matches the temporary password
4023 * sent by e-mail for password reset operations.
4025 * @deprecated since 1.27. AuthManager is coming.
4026 * @param string $plaintext
4027 * @return bool True if matches, false otherwise
4029 public function checkTemporaryPassword( $plaintext ) {
4030 global $wgNewPasswordExpiry;
4034 $passwordFactory = new PasswordFactory();
4035 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4036 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4037 ?
wfGetDB( DB_MASTER
)
4038 : wfGetDB( DB_SLAVE
);
4040 $row = $db->selectRow(
4042 array( 'user_newpassword', 'user_newpass_time' ),
4043 array( 'user_id' => $this->getId() ),
4047 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4048 } catch ( PasswordError
$e ) {
4049 wfDebug( 'Invalid password hash found in database.' );
4050 $newPassword = PasswordFactory
::newInvalidPassword();
4053 if ( $newPassword->equals( $plaintext ) ) {
4054 if ( is_null( $row->user_newpass_time
) ) {
4057 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4058 return ( time() < $expiry );
4065 * Internal implementation for self::getEditToken() and
4066 * self::matchEditToken().
4068 * @param string|array $salt
4069 * @param WebRequest $request
4070 * @param string|int $timestamp
4073 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
4074 if ( $this->isAnon() ) {
4075 return self
::EDIT_TOKEN_SUFFIX
;
4077 $token = $request->getSessionData( 'wsEditToken' );
4078 if ( $token === null ) {
4079 $token = MWCryptRand
::generateHex( 32 );
4080 $request->setSessionData( 'wsEditToken', $token );
4082 if ( is_array( $salt ) ) {
4083 $salt = implode( '|', $salt );
4085 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
4086 dechex( $timestamp ) .
4087 self
::EDIT_TOKEN_SUFFIX
;
4092 * Initialize (if necessary) and return a session token value
4093 * which can be used in edit forms to show that the user's
4094 * login credentials aren't being hijacked with a foreign form
4099 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4100 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4101 * @return string The new edit token
4103 public function getEditToken( $salt = '', $request = null ) {
4104 return $this->getEditTokenAtTimestamp(
4105 $salt, $request ?
: $this->getRequest(), wfTimestamp()
4110 * Generate a looking random token for various uses.
4112 * @return string The new random token
4113 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
4114 * wfRandomString for pseudo-randomness.
4116 public static function generateToken() {
4117 return MWCryptRand
::generateHex( 32 );
4121 * Get the embedded timestamp from a token.
4122 * @param string $val Input token
4125 public static function getEditTokenTimestamp( $val ) {
4126 $suffixLen = strlen( self
::EDIT_TOKEN_SUFFIX
);
4127 if ( strlen( $val ) <= 32 +
$suffixLen ) {
4131 return hexdec( substr( $val, 32, -$suffixLen ) );
4135 * Check given value against the token value stored in the session.
4136 * A match should confirm that the form was submitted from the
4137 * user's own login session, not a form submission from a third-party
4140 * @param string $val Input value to compare
4141 * @param string $salt Optional function-specific data for hashing
4142 * @param WebRequest|null $request Object to use or null to use $wgRequest
4143 * @param int $maxage Fail tokens older than this, in seconds
4144 * @return bool Whether the token matches
4146 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4147 if ( $this->isAnon() ) {
4148 return $val === self
::EDIT_TOKEN_SUFFIX
;
4151 $timestamp = self
::getEditTokenTimestamp( $val );
4152 if ( $timestamp === null ) {
4155 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
4160 $sessionToken = $this->getEditTokenAtTimestamp(
4161 $salt, $request ?
: $this->getRequest(), $timestamp
4164 if ( !hash_equals( $sessionToken, $val ) ) {
4165 wfDebug( "User::matchEditToken: broken session data\n" );
4168 return hash_equals( $sessionToken, $val );
4172 * Check given value against the token value stored in the session,
4173 * ignoring the suffix.
4175 * @param string $val Input value to compare
4176 * @param string $salt Optional function-specific data for hashing
4177 * @param WebRequest|null $request Object to use or null to use $wgRequest
4178 * @param int $maxage Fail tokens older than this, in seconds
4179 * @return bool Whether the token matches
4181 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4182 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4183 return $this->matchEditToken( $val, $salt, $request, $maxage );
4187 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4188 * mail to the user's given address.
4190 * @param string $type Message to send, either "created", "changed" or "set"
4193 public function sendConfirmationMail( $type = 'created' ) {
4195 $expiration = null; // gets passed-by-ref and defined in next line.
4196 $token = $this->confirmationToken( $expiration );
4197 $url = $this->confirmationTokenUrl( $token );
4198 $invalidateURL = $this->invalidationTokenUrl( $token );
4199 $this->saveSettings();
4201 if ( $type == 'created' ||
$type === false ) {
4202 $message = 'confirmemail_body';
4203 } elseif ( $type === true ) {
4204 $message = 'confirmemail_body_changed';
4206 // Messages: confirmemail_body_changed, confirmemail_body_set
4207 $message = 'confirmemail_body_' . $type;
4210 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4211 wfMessage( $message,
4212 $this->getRequest()->getIP(),
4215 $wgLang->userTimeAndDate( $expiration, $this ),
4217 $wgLang->userDate( $expiration, $this ),
4218 $wgLang->userTime( $expiration, $this ) )->text() );
4222 * Send an e-mail to this user's account. Does not check for
4223 * confirmed status or validity.
4225 * @param string $subject Message subject
4226 * @param string $body Message body
4227 * @param User|null $from Optional sending user; if unspecified, default
4228 * $wgPasswordSender will be used.
4229 * @param string $replyto Reply-To address
4232 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4233 global $wgPasswordSender;
4235 if ( $from instanceof User
) {
4236 $sender = MailAddress
::newFromUser( $from );
4238 $sender = new MailAddress( $wgPasswordSender,
4239 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4241 $to = MailAddress
::newFromUser( $this );
4243 return UserMailer
::send( $to, $sender, $subject, $body, array(
4244 'replyTo' => $replyto,
4249 * Generate, store, and return a new e-mail confirmation code.
4250 * A hash (unsalted, since it's used as a key) is stored.
4252 * @note Call saveSettings() after calling this function to commit
4253 * this change to the database.
4255 * @param string &$expiration Accepts the expiration time
4256 * @return string New token
4258 protected function confirmationToken( &$expiration ) {
4259 global $wgUserEmailConfirmationTokenExpiry;
4261 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4262 $expiration = wfTimestamp( TS_MW
, $expires );
4264 $token = MWCryptRand
::generateHex( 32 );
4265 $hash = md5( $token );
4266 $this->mEmailToken
= $hash;
4267 $this->mEmailTokenExpires
= $expiration;
4272 * Return a URL the user can use to confirm their email address.
4273 * @param string $token Accepts the email confirmation token
4274 * @return string New token URL
4276 protected function confirmationTokenUrl( $token ) {
4277 return $this->getTokenUrl( 'ConfirmEmail', $token );
4281 * Return a URL the user can use to invalidate their email address.
4282 * @param string $token Accepts the email confirmation token
4283 * @return string New token URL
4285 protected function invalidationTokenUrl( $token ) {
4286 return $this->getTokenUrl( 'InvalidateEmail', $token );
4290 * Internal function to format the e-mail validation/invalidation URLs.
4291 * This uses a quickie hack to use the
4292 * hardcoded English names of the Special: pages, for ASCII safety.
4294 * @note Since these URLs get dropped directly into emails, using the
4295 * short English names avoids insanely long URL-encoded links, which
4296 * also sometimes can get corrupted in some browsers/mailers
4297 * (bug 6957 with Gmail and Internet Explorer).
4299 * @param string $page Special page
4300 * @param string $token Token
4301 * @return string Formatted URL
4303 protected function getTokenUrl( $page, $token ) {
4304 // Hack to bypass localization of 'Special:'
4305 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4306 return $title->getCanonicalURL();
4310 * Mark the e-mail address confirmed.
4312 * @note Call saveSettings() after calling this function to commit the change.
4316 public function confirmEmail() {
4317 // Check if it's already confirmed, so we don't touch the database
4318 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4319 if ( !$this->isEmailConfirmed() ) {
4320 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4321 Hooks
::run( 'ConfirmEmailComplete', array( $this ) );
4327 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4328 * address if it was already confirmed.
4330 * @note Call saveSettings() after calling this function to commit the change.
4331 * @return bool Returns true
4333 public function invalidateEmail() {
4335 $this->mEmailToken
= null;
4336 $this->mEmailTokenExpires
= null;
4337 $this->setEmailAuthenticationTimestamp( null );
4339 Hooks
::run( 'InvalidateEmailComplete', array( $this ) );
4344 * Set the e-mail authentication timestamp.
4345 * @param string $timestamp TS_MW timestamp
4347 public function setEmailAuthenticationTimestamp( $timestamp ) {
4349 $this->mEmailAuthenticated
= $timestamp;
4350 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4354 * Is this user allowed to send e-mails within limits of current
4355 * site configuration?
4358 public function canSendEmail() {
4359 global $wgEnableEmail, $wgEnableUserEmail;
4360 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4363 $canSend = $this->isEmailConfirmed();
4364 Hooks
::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4369 * Is this user allowed to receive e-mails within limits of current
4370 * site configuration?
4373 public function canReceiveEmail() {
4374 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4378 * Is this user's e-mail address valid-looking and confirmed within
4379 * limits of the current site configuration?
4381 * @note If $wgEmailAuthentication is on, this may require the user to have
4382 * confirmed their address by returning a code or using a password
4383 * sent to the address from the wiki.
4387 public function isEmailConfirmed() {
4388 global $wgEmailAuthentication;
4391 if ( Hooks
::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4392 if ( $this->isAnon() ) {
4395 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4398 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4408 * Check whether there is an outstanding request for e-mail confirmation.
4411 public function isEmailConfirmationPending() {
4412 global $wgEmailAuthentication;
4413 return $wgEmailAuthentication &&
4414 !$this->isEmailConfirmed() &&
4415 $this->mEmailToken
&&
4416 $this->mEmailTokenExpires
> wfTimestamp();
4420 * Get the timestamp of account creation.
4422 * @return string|bool|null Timestamp of account creation, false for
4423 * non-existent/anonymous user accounts, or null if existing account
4424 * but information is not in database.
4426 public function getRegistration() {
4427 if ( $this->isAnon() ) {
4431 return $this->mRegistration
;
4435 * Get the timestamp of the first edit
4437 * @return string|bool Timestamp of first edit, or false for
4438 * non-existent/anonymous user accounts.
4440 public function getFirstEditTimestamp() {
4441 if ( $this->getId() == 0 ) {
4442 return false; // anons
4444 $dbr = wfGetDB( DB_SLAVE
);
4445 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4446 array( 'rev_user' => $this->getId() ),
4448 array( 'ORDER BY' => 'rev_timestamp ASC' )
4451 return false; // no edits
4453 return wfTimestamp( TS_MW
, $time );
4457 * Get the permissions associated with a given list of groups
4459 * @param array $groups Array of Strings List of internal group names
4460 * @return array Array of Strings List of permission key names for given groups combined
4462 public static function getGroupPermissions( $groups ) {
4463 global $wgGroupPermissions, $wgRevokePermissions;
4465 // grant every granted permission first
4466 foreach ( $groups as $group ) {
4467 if ( isset( $wgGroupPermissions[$group] ) ) {
4468 $rights = array_merge( $rights,
4469 // array_filter removes empty items
4470 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4473 // now revoke the revoked permissions
4474 foreach ( $groups as $group ) {
4475 if ( isset( $wgRevokePermissions[$group] ) ) {
4476 $rights = array_diff( $rights,
4477 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4480 return array_unique( $rights );
4484 * Get all the groups who have a given permission
4486 * @param string $role Role to check
4487 * @return array Array of Strings List of internal group names with the given permission
4489 public static function getGroupsWithPermission( $role ) {
4490 global $wgGroupPermissions;
4491 $allowedGroups = array();
4492 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4493 if ( self
::groupHasPermission( $group, $role ) ) {
4494 $allowedGroups[] = $group;
4497 return $allowedGroups;
4501 * Check, if the given group has the given permission
4503 * If you're wanting to check whether all users have a permission, use
4504 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4508 * @param string $group Group to check
4509 * @param string $role Role to check
4512 public static function groupHasPermission( $group, $role ) {
4513 global $wgGroupPermissions, $wgRevokePermissions;
4514 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4515 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4519 * Check if all users have the given permission
4522 * @param string $right Right to check
4525 public static function isEveryoneAllowed( $right ) {
4526 global $wgGroupPermissions, $wgRevokePermissions;
4527 static $cache = array();
4529 // Use the cached results, except in unit tests which rely on
4530 // being able change the permission mid-request
4531 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4532 return $cache[$right];
4535 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4536 $cache[$right] = false;
4540 // If it's revoked anywhere, then everyone doesn't have it
4541 foreach ( $wgRevokePermissions as $rights ) {
4542 if ( isset( $rights[$right] ) && $rights[$right] ) {
4543 $cache[$right] = false;
4548 // Allow extensions (e.g. OAuth) to say false
4549 if ( !Hooks
::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4550 $cache[$right] = false;
4554 $cache[$right] = true;
4559 * Get the localized descriptive name for a group, if it exists
4561 * @param string $group Internal group name
4562 * @return string Localized descriptive group name
4564 public static function getGroupName( $group ) {
4565 $msg = wfMessage( "group-$group" );
4566 return $msg->isBlank() ?
$group : $msg->text();
4570 * Get the localized descriptive name for a member of a group, if it exists
4572 * @param string $group Internal group name
4573 * @param string $username Username for gender (since 1.19)
4574 * @return string Localized name for group member
4576 public static function getGroupMember( $group, $username = '#' ) {
4577 $msg = wfMessage( "group-$group-member", $username );
4578 return $msg->isBlank() ?
$group : $msg->text();
4582 * Return the set of defined explicit groups.
4583 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4584 * are not included, as they are defined automatically, not in the database.
4585 * @return array Array of internal group names
4587 public static function getAllGroups() {
4588 global $wgGroupPermissions, $wgRevokePermissions;
4590 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4591 self
::getImplicitGroups()
4596 * Get a list of all available permissions.
4597 * @return string[] Array of permission names
4599 public static function getAllRights() {
4600 if ( self
::$mAllRights === false ) {
4601 global $wgAvailableRights;
4602 if ( count( $wgAvailableRights ) ) {
4603 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4605 self
::$mAllRights = self
::$mCoreRights;
4607 Hooks
::run( 'UserGetAllRights', array( &self
::$mAllRights ) );
4609 return self
::$mAllRights;
4613 * Get a list of implicit groups
4614 * @return array Array of Strings Array of internal group names
4616 public static function getImplicitGroups() {
4617 global $wgImplicitGroups;
4619 $groups = $wgImplicitGroups;
4620 # Deprecated, use $wgImplicitGroups instead
4621 Hooks
::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4627 * Get the title of a page describing a particular group
4629 * @param string $group Internal group name
4630 * @return Title|bool Title of the page if it exists, false otherwise
4632 public static function getGroupPage( $group ) {
4633 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4634 if ( $msg->exists() ) {
4635 $title = Title
::newFromText( $msg->text() );
4636 if ( is_object( $title ) ) {
4644 * Create a link to the group in HTML, if available;
4645 * else return the group name.
4647 * @param string $group Internal name of the group
4648 * @param string $text The text of the link
4649 * @return string HTML link to the group
4651 public static function makeGroupLinkHTML( $group, $text = '' ) {
4652 if ( $text == '' ) {
4653 $text = self
::getGroupName( $group );
4655 $title = self
::getGroupPage( $group );
4657 return Linker
::link( $title, htmlspecialchars( $text ) );
4659 return htmlspecialchars( $text );
4664 * Create a link to the group in Wikitext, if available;
4665 * else return the group name.
4667 * @param string $group Internal name of the group
4668 * @param string $text The text of the link
4669 * @return string Wikilink to the group
4671 public static function makeGroupLinkWiki( $group, $text = '' ) {
4672 if ( $text == '' ) {
4673 $text = self
::getGroupName( $group );
4675 $title = self
::getGroupPage( $group );
4677 $page = $title->getFullText();
4678 return "[[$page|$text]]";
4685 * Returns an array of the groups that a particular group can add/remove.
4687 * @param string $group The group to check for whether it can add/remove
4688 * @return array Array( 'add' => array( addablegroups ),
4689 * 'remove' => array( removablegroups ),
4690 * 'add-self' => array( addablegroups to self),
4691 * 'remove-self' => array( removable groups from self) )
4693 public static function changeableByGroup( $group ) {
4694 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4698 'remove' => array(),
4699 'add-self' => array(),
4700 'remove-self' => array()
4703 if ( empty( $wgAddGroups[$group] ) ) {
4704 // Don't add anything to $groups
4705 } elseif ( $wgAddGroups[$group] === true ) {
4706 // You get everything
4707 $groups['add'] = self
::getAllGroups();
4708 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4709 $groups['add'] = $wgAddGroups[$group];
4712 // Same thing for remove
4713 if ( empty( $wgRemoveGroups[$group] ) ) {
4715 } elseif ( $wgRemoveGroups[$group] === true ) {
4716 $groups['remove'] = self
::getAllGroups();
4717 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4718 $groups['remove'] = $wgRemoveGroups[$group];
4721 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4722 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4723 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4724 if ( is_int( $key ) ) {
4725 $wgGroupsAddToSelf['user'][] = $value;
4730 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4731 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4732 if ( is_int( $key ) ) {
4733 $wgGroupsRemoveFromSelf['user'][] = $value;
4738 // Now figure out what groups the user can add to him/herself
4739 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4741 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4742 // No idea WHY this would be used, but it's there
4743 $groups['add-self'] = User
::getAllGroups();
4744 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4745 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4748 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4750 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4751 $groups['remove-self'] = User
::getAllGroups();
4752 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4753 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4760 * Returns an array of groups that this user can add and remove
4761 * @return array Array( 'add' => array( addablegroups ),
4762 * 'remove' => array( removablegroups ),
4763 * 'add-self' => array( addablegroups to self),
4764 * 'remove-self' => array( removable groups from self) )
4766 public function changeableGroups() {
4767 if ( $this->isAllowed( 'userrights' ) ) {
4768 // This group gives the right to modify everything (reverse-
4769 // compatibility with old "userrights lets you change
4771 // Using array_merge to make the groups reindexed
4772 $all = array_merge( User
::getAllGroups() );
4776 'add-self' => array(),
4777 'remove-self' => array()
4781 // Okay, it's not so simple, we will have to go through the arrays
4784 'remove' => array(),
4785 'add-self' => array(),
4786 'remove-self' => array()
4788 $addergroups = $this->getEffectiveGroups();
4790 foreach ( $addergroups as $addergroup ) {
4791 $groups = array_merge_recursive(
4792 $groups, $this->changeableByGroup( $addergroup )
4794 $groups['add'] = array_unique( $groups['add'] );
4795 $groups['remove'] = array_unique( $groups['remove'] );
4796 $groups['add-self'] = array_unique( $groups['add-self'] );
4797 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4803 * Deferred version of incEditCountImmediate()
4805 public function incEditCount() {
4807 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $that ) {
4808 $that->incEditCountImmediate();
4813 * Increment the user's edit-count field.
4814 * Will have no effect for anonymous users.
4817 public function incEditCountImmediate() {
4818 if ( $this->isAnon() ) {
4822 $dbw = wfGetDB( DB_MASTER
);
4823 // No rows will be "affected" if user_editcount is NULL
4826 array( 'user_editcount=user_editcount+1' ),
4827 array( 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ),
4830 // Lazy initialization check...
4831 if ( $dbw->affectedRows() == 0 ) {
4832 // Now here's a goddamn hack...
4833 $dbr = wfGetDB( DB_SLAVE
);
4834 if ( $dbr !== $dbw ) {
4835 // If we actually have a slave server, the count is
4836 // at least one behind because the current transaction
4837 // has not been committed and replicated.
4838 $this->initEditCount( 1 );
4840 // But if DB_SLAVE is selecting the master, then the
4841 // count we just read includes the revision that was
4842 // just added in the working transaction.
4843 $this->initEditCount();
4846 // Edit count in user cache too
4847 $this->invalidateCache();
4851 * Initialize user_editcount from data out of the revision table
4853 * @param int $add Edits to add to the count from the revision table
4854 * @return int Number of edits
4856 protected function initEditCount( $add = 0 ) {
4857 // Pull from a slave to be less cruel to servers
4858 // Accuracy isn't the point anyway here
4859 $dbr = wfGetDB( DB_SLAVE
);
4860 $count = (int)$dbr->selectField(
4863 array( 'rev_user' => $this->getId() ),
4866 $count = $count +
$add;
4868 $dbw = wfGetDB( DB_MASTER
);
4871 array( 'user_editcount' => $count ),
4872 array( 'user_id' => $this->getId() ),
4880 * Get the description of a given right
4882 * @param string $right Right to query
4883 * @return string Localized description of the right
4885 public static function getRightDescription( $right ) {
4886 $key = "right-$right";
4887 $msg = wfMessage( $key );
4888 return $msg->isBlank() ?
$right : $msg->text();
4892 * Make a new-style password hash
4894 * @param string $password Plain-text password
4895 * @param bool|string $salt Optional salt, may be random or the user ID.
4896 * If unspecified or false, will generate one automatically
4897 * @return string Password hash
4898 * @deprecated since 1.24, use Password class
4900 public static function crypt( $password, $salt = false ) {
4901 wfDeprecated( __METHOD__
, '1.24' );
4902 $passwordFactory = new PasswordFactory();
4903 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4904 $hash = $passwordFactory->newFromPlaintext( $password );
4905 return $hash->toString();
4909 * Compare a password hash with a plain-text password. Requires the user
4910 * ID if there's a chance that the hash is an old-style hash.
4912 * @param string $hash Password hash
4913 * @param string $password Plain-text password to compare
4914 * @param string|bool $userId User ID for old-style password salt
4917 * @deprecated since 1.24, use Password class
4919 public static function comparePasswords( $hash, $password, $userId = false ) {
4920 wfDeprecated( __METHOD__
, '1.24' );
4922 // Check for *really* old password hashes that don't even have a type
4923 // The old hash format was just an md5 hex hash, with no type information
4924 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4925 global $wgPasswordSalt;
4926 if ( $wgPasswordSalt ) {
4927 $password = ":B:{$userId}:{$hash}";
4929 $password = ":A:{$hash}";
4933 $passwordFactory = new PasswordFactory();
4934 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4935 $hash = $passwordFactory->newFromCiphertext( $hash );
4936 return $hash->equals( $password );
4940 * Add a newuser log entry for this user.
4941 * Before 1.19 the return value was always true.
4943 * @param string|bool $action Account creation type.
4944 * - String, one of the following values:
4945 * - 'create' for an anonymous user creating an account for himself.
4946 * This will force the action's performer to be the created user itself,
4947 * no matter the value of $wgUser
4948 * - 'create2' for a logged in user creating an account for someone else
4949 * - 'byemail' when the created user will receive its password by e-mail
4950 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4951 * - Boolean means whether the account was created by e-mail (deprecated):
4952 * - true will be converted to 'byemail'
4953 * - false will be converted to 'create' if this object is the same as
4954 * $wgUser and to 'create2' otherwise
4956 * @param string $reason User supplied reason
4958 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4960 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4961 global $wgUser, $wgNewUserLog;
4962 if ( empty( $wgNewUserLog ) ) {
4963 return true; // disabled
4966 if ( $action === true ) {
4967 $action = 'byemail';
4968 } elseif ( $action === false ) {
4969 if ( $this->equals( $wgUser ) ) {
4972 $action = 'create2';
4976 if ( $action === 'create' ||
$action === 'autocreate' ) {
4979 $performer = $wgUser;
4982 $logEntry = new ManualLogEntry( 'newusers', $action );
4983 $logEntry->setPerformer( $performer );
4984 $logEntry->setTarget( $this->getUserPage() );
4985 $logEntry->setComment( $reason );
4986 $logEntry->setParameters( array(
4987 '4::userid' => $this->getId(),
4989 $logid = $logEntry->insert();
4991 if ( $action !== 'autocreate' ) {
4992 $logEntry->publish( $logid );
4999 * Add an autocreate newuser log entry for this user
5000 * Used by things like CentralAuth and perhaps other authplugins.
5001 * Consider calling addNewUserLogEntry() directly instead.
5005 public function addNewUserLogEntryAutoCreate() {
5006 $this->addNewUserLogEntry( 'autocreate' );
5012 * Load the user options either from cache, the database or an array
5014 * @param array $data Rows for the current user out of the user_properties table
5016 protected function loadOptions( $data = null ) {
5021 if ( $this->mOptionsLoaded
) {
5025 $this->mOptions
= self
::getDefaultOptions();
5027 if ( !$this->getId() ) {
5028 // For unlogged-in users, load language/variant options from request.
5029 // There's no need to do it for logged-in users: they can set preferences,
5030 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5031 // so don't override user's choice (especially when the user chooses site default).
5032 $variant = $wgContLang->getDefaultVariant();
5033 $this->mOptions
['variant'] = $variant;
5034 $this->mOptions
['language'] = $variant;
5035 $this->mOptionsLoaded
= true;
5039 // Maybe load from the object
5040 if ( !is_null( $this->mOptionOverrides
) ) {
5041 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5042 foreach ( $this->mOptionOverrides
as $key => $value ) {
5043 $this->mOptions
[$key] = $value;
5046 if ( !is_array( $data ) ) {
5047 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5048 // Load from database
5049 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5050 ?
wfGetDB( DB_MASTER
)
5051 : wfGetDB( DB_SLAVE
);
5053 $res = $dbr->select(
5055 array( 'up_property', 'up_value' ),
5056 array( 'up_user' => $this->getId() ),
5060 $this->mOptionOverrides
= array();
5062 foreach ( $res as $row ) {
5063 $data[$row->up_property
] = $row->up_value
;
5066 foreach ( $data as $property => $value ) {
5067 $this->mOptionOverrides
[$property] = $value;
5068 $this->mOptions
[$property] = $value;
5072 $this->mOptionsLoaded
= true;
5074 Hooks
::run( 'UserLoadOptions', array( $this, &$this->mOptions
) );
5078 * Saves the non-default options for this user, as previously set e.g. via
5079 * setOption(), in the database's "user_properties" (preferences) table.
5080 * Usually used via saveSettings().
5082 protected function saveOptions() {
5083 $this->loadOptions();
5085 // Not using getOptions(), to keep hidden preferences in database
5086 $saveOptions = $this->mOptions
;
5088 // Allow hooks to abort, for instance to save to a global profile.
5089 // Reset options to default state before saving.
5090 if ( !Hooks
::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5094 $userId = $this->getId();
5096 $insert_rows = array(); // all the new preference rows
5097 foreach ( $saveOptions as $key => $value ) {
5098 // Don't bother storing default values
5099 $defaultOption = self
::getDefaultOption( $key );
5100 if ( ( $defaultOption === null && $value !== false && $value !== null )
5101 ||
$value != $defaultOption
5103 $insert_rows[] = array(
5104 'up_user' => $userId,
5105 'up_property' => $key,
5106 'up_value' => $value,
5111 $dbw = wfGetDB( DB_MASTER
);
5113 $res = $dbw->select( 'user_properties',
5114 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
5116 // Find prior rows that need to be removed or updated. These rows will
5117 // all be deleted (the later so that INSERT IGNORE applies the new values).
5118 $keysDelete = array();
5119 foreach ( $res as $row ) {
5120 if ( !isset( $saveOptions[$row->up_property
] )
5121 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5123 $keysDelete[] = $row->up_property
;
5127 if ( count( $keysDelete ) ) {
5128 // Do the DELETE by PRIMARY KEY for prior rows.
5129 // In the past a very large portion of calls to this function are for setting
5130 // 'rememberpassword' for new accounts (a preference that has since been removed).
5131 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5132 // caused gap locks on [max user ID,+infinity) which caused high contention since
5133 // updates would pile up on each other as they are for higher (newer) user IDs.
5134 // It might not be necessary these days, but it shouldn't hurt either.
5135 $dbw->delete( 'user_properties',
5136 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
5138 // Insert the new preference rows
5139 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
5143 * Lazily instantiate and return a factory object for making passwords
5145 * @deprecated since 1.27, create a PasswordFactory directly instead
5146 * @return PasswordFactory
5148 public static function getPasswordFactory() {
5149 wfDeprecated( __METHOD__
, '1.27' );
5150 $ret = new PasswordFactory();
5151 $ret->init( RequestContext
::getMain()->getConfig() );
5156 * Provide an array of HTML5 attributes to put on an input element
5157 * intended for the user to enter a new password. This may include
5158 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5160 * Do *not* use this when asking the user to enter his current password!
5161 * Regardless of configuration, users may have invalid passwords for whatever
5162 * reason (e.g., they were set before requirements were tightened up).
5163 * Only use it when asking for a new password, like on account creation or
5166 * Obviously, you still need to do server-side checking.
5168 * NOTE: A combination of bugs in various browsers means that this function
5169 * actually just returns array() unconditionally at the moment. May as
5170 * well keep it around for when the browser bugs get fixed, though.
5172 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5174 * @deprecated since 1.27
5175 * @return array Array of HTML attributes suitable for feeding to
5176 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5177 * That will get confused by the boolean attribute syntax used.)
5179 public static function passwordChangeInputAttribs() {
5180 global $wgMinimalPasswordLength;
5182 if ( $wgMinimalPasswordLength == 0 ) {
5186 # Note that the pattern requirement will always be satisfied if the
5187 # input is empty, so we need required in all cases.
5189 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5190 # if e-mail confirmation is being used. Since HTML5 input validation
5191 # is b0rked anyway in some browsers, just return nothing. When it's
5192 # re-enabled, fix this code to not output required for e-mail
5194 # $ret = array( 'required' );
5197 # We can't actually do this right now, because Opera 9.6 will print out
5198 # the entered password visibly in its error message! When other
5199 # browsers add support for this attribute, or Opera fixes its support,
5200 # we can add support with a version check to avoid doing this on Opera
5201 # versions where it will be a problem. Reported to Opera as
5202 # DSK-262266, but they don't have a public bug tracker for us to follow.
5204 if ( $wgMinimalPasswordLength > 1 ) {
5205 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5206 $ret['title'] = wfMessage( 'passwordtooshort' )
5207 ->numParams( $wgMinimalPasswordLength )->text();
5215 * Return the list of user fields that should be selected to create
5216 * a new user object.
5219 public static function selectFields() {
5227 'user_email_authenticated',
5229 'user_email_token_expires',
5230 'user_registration',
5236 * Factory function for fatal permission-denied errors
5239 * @param string $permission User right required
5242 static function newFatalPermissionDeniedStatus( $permission ) {
5245 $groups = array_map(
5246 array( 'User', 'makeGroupLinkWiki' ),
5247 User
::getGroupsWithPermission( $permission )
5251 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5253 return Status
::newFatal( 'badaccess-group0' );
5258 * Get a new instance of this user that was loaded from the master via a locking read
5260 * Use this instead of the main context User when updating that user. This avoids races
5261 * where that user was loaded from a slave or even the master but without proper locks.
5263 * @return User|null Returns null if the user was not found in the DB
5266 public function getInstanceForUpdate() {
5267 if ( !$this->getId() ) {
5268 return null; // anon
5271 $user = self
::newFromId( $this->getId() );
5272 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5280 * Checks if two user objects point to the same user.
5286 public function equals( User
$user ) {
5287 return $this->getName() === $user->getName();