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
24 * String Some punctuation to prevent editing from broken text-mangling proxies.
27 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
30 * The User object encapsulates all of the user-specific settings (user_id,
31 * name, rights, email address, options, last login time). Client
32 * classes use the getXXX() functions to access these fields. These functions
33 * do all the work of determining whether the user is logged in,
34 * whether the requested option can be satisfied from cookies or
35 * whether a database query is needed. Most of the settings needed
36 * for rendering normal pages are set in the cookie to minimize use
39 class User
implements IDBAccessObject
{
41 * @const int Number of characters in user_token field.
43 const TOKEN_LENGTH
= 32;
46 * Global constant made accessible as class constants so that autoloader
49 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
52 * @const int Serialized record version.
57 * Maximum items in $mWatchedItems
59 const MAX_WATCHED_ITEMS_CACHE
= 100;
62 * Exclude user options that are set to their default value.
65 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
68 * Array of Strings List of member variables which are saved to the
69 * shared cache (memcached). Any operation which changes the
70 * corresponding database fields must call a cache-clearing function.
73 protected static $mCacheVars = array(
81 'mEmailAuthenticated',
88 // user_properties table
93 * Array of Strings Core rights.
94 * Each of these should have a corresponding message of the form
98 protected static $mCoreRights = array(
127 'editusercssjs', # deprecated
140 'move-categorypages',
141 'move-rootuserpages',
145 'override-export-depth',
168 'userrights-interwiki',
176 * String Cached results of getAllRights()
178 protected static $mAllRights = false;
180 /** Cache variables */
190 /** @var string TS_MW timestamp from the DB */
192 /** @var string TS_MW timestamp from cache */
193 protected $mQuickTouched;
197 public $mEmailAuthenticated;
199 protected $mEmailToken;
201 protected $mEmailTokenExpires;
203 protected $mRegistration;
205 protected $mEditCount;
209 protected $mOptionOverrides;
213 * Bool Whether the cache variables have been loaded.
216 public $mOptionsLoaded;
219 * Array with already loaded items or true if all items have been loaded.
221 protected $mLoadedItems = array();
225 * String Initialization data source if mLoadedItems!==true. May be one of:
226 * - 'defaults' anonymous user initialised from class defaults
227 * - 'name' initialise from mName
228 * - 'id' initialise from mId
229 * - 'session' log in from cookies or session if possible
231 * Use the User::newFrom*() family of functions to set this.
236 * Lazy-initialized variables, invalidated with clearInstanceCache
240 protected $mDatePreference;
248 protected $mBlockreason;
250 protected $mEffectiveGroups;
252 protected $mImplicitGroups;
254 protected $mFormerGroups;
256 protected $mBlockedGlobally;
273 protected $mAllowUsertalk;
276 private $mBlockedFromCreateAccount = false;
279 private $mWatchedItems = array();
281 /** @var integer User::READ_* constant bitfield used to load data */
282 protected $queryFlagsUsed = self
::READ_NORMAL
;
284 public static $idCacheByName = array();
287 * Lightweight constructor for an anonymous user.
288 * Use the User::newFrom* factory functions for other kinds of users.
292 * @see newFromConfirmationCode()
293 * @see newFromSession()
296 public function __construct() {
297 $this->clearInstanceCache( 'defaults' );
303 public function __toString() {
304 return $this->getName();
308 * Load the user table data for this object from the source given by mFrom.
310 * @param integer $flags User::READ_* constant bitfield
312 public function load( $flags = self
::READ_NORMAL
) {
313 if ( $this->mLoadedItems
=== true ) {
317 // Set it now to avoid infinite recursion in accessors
318 $this->mLoadedItems
= true;
319 $this->queryFlagsUsed
= $flags;
321 switch ( $this->mFrom
) {
323 $this->loadDefaults();
326 // Make sure this thread sees its own changes
327 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
328 $flags |
= self
::READ_LATEST
;
329 $this->queryFlagsUsed
= $flags;
332 $this->mId
= self
::idFromName( $this->mName
, $flags );
334 // Nonexistent user placeholder object
335 $this->loadDefaults( $this->mName
);
337 $this->loadFromId( $flags );
341 $this->loadFromId( $flags );
344 if ( !$this->loadFromSession() ) {
345 // Loading from session failed. Load defaults.
346 $this->loadDefaults();
348 Hooks
::run( 'UserLoadAfterLoadFromSession', array( $this ) );
351 throw new UnexpectedValueException(
352 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
357 * Load user table data, given mId has already been set.
358 * @param integer $flags User::READ_* constant bitfield
359 * @return bool False if the ID does not exist, true otherwise
361 public function loadFromId( $flags = self
::READ_NORMAL
) {
362 if ( $this->mId
== 0 ) {
363 $this->loadDefaults();
367 // Try cache (unless this needs data from the master DB).
368 // NOTE: if this thread called saveSettings(), the cache was cleared.
369 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
370 if ( $latest ||
!$this->loadFromCache() ) {
371 wfDebug( "User: cache miss for user {$this->mId}\n" );
372 // Load from DB (make sure this thread sees its own changes)
373 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
374 $flags |
= self
::READ_LATEST
;
376 if ( !$this->loadFromDatabase( $flags ) ) {
377 // Can't load from ID, user is anonymous
380 $this->saveToCache();
383 $this->mLoadedItems
= true;
384 $this->queryFlagsUsed
= $flags;
391 * @param string $wikiId
392 * @param integer $userId
394 public static function purge( $wikiId, $userId ) {
395 $cache = ObjectCache
::getMainWANInstance();
396 $cache->delete( $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId ) );
401 * @param WANObjectCache $cache
404 protected function getCacheKey( WANObjectCache
$cache ) {
405 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
409 * Load user data from shared cache, given mId has already been set.
411 * @return bool false if the ID does not exist or data is invalid, true otherwise
414 protected function loadFromCache() {
415 if ( $this->mId
== 0 ) {
416 $this->loadDefaults();
420 $cache = ObjectCache
::getMainWANInstance();
421 $data = $cache->get( $this->getCacheKey( $cache ) );
422 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
427 wfDebug( "User: got user {$this->mId} from cache\n" );
429 // Restore from cache
430 foreach ( self
::$mCacheVars as $name ) {
431 $this->$name = $data[$name];
438 * Save user data to the shared cache
440 * This method should not be called outside the User class
442 public function saveToCache() {
445 $this->loadOptions();
447 if ( $this->isAnon() ) {
448 // Anonymous users are uncached
453 foreach ( self
::$mCacheVars as $name ) {
454 $data[$name] = $this->$name;
456 $data['mVersion'] = self
::VERSION
;
457 $opts = Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
459 $cache = ObjectCache
::getMainWANInstance();
460 $key = $this->getCacheKey( $cache );
461 $cache->set( $key, $data, $cache::TTL_HOUR
, $opts );
464 /** @name newFrom*() static factory methods */
468 * Static factory method for creation from username.
470 * This is slightly less efficient than newFromId(), so use newFromId() if
471 * you have both an ID and a name handy.
473 * @param string $name Username, validated by Title::newFromText()
474 * @param string|bool $validate Validate username. Takes the same parameters as
475 * User::getCanonicalName(), except that true is accepted as an alias
476 * for 'valid', for BC.
478 * @return User|bool User object, or false if the username is invalid
479 * (e.g. if it contains illegal characters or is an IP address). If the
480 * username is not present in the database, the result will be a user object
481 * with a name, zero user ID and default settings.
483 public static function newFromName( $name, $validate = 'valid' ) {
484 if ( $validate === true ) {
487 $name = self
::getCanonicalName( $name, $validate );
488 if ( $name === false ) {
491 // Create unloaded user object
495 $u->setItemLoaded( 'name' );
501 * Static factory method for creation from a given user ID.
503 * @param int $id Valid user ID
504 * @return User The corresponding User object
506 public static function newFromId( $id ) {
510 $u->setItemLoaded( 'id' );
515 * Factory method to fetch whichever user has a given email confirmation code.
516 * This code is generated when an account is created or its e-mail address
519 * If the code is invalid or has expired, returns NULL.
521 * @param string $code Confirmation code
522 * @param int $flags User::READ_* bitfield
525 public static function newFromConfirmationCode( $code, $flags = 0 ) {
526 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
527 ?
wfGetDB( DB_MASTER
)
528 : wfGetDB( DB_SLAVE
);
530 $id = $db->selectField(
534 'user_email_token' => md5( $code ),
535 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
539 return $id ? User
::newFromId( $id ) : null;
543 * Create a new user object using data from session or cookies. If the
544 * login credentials are invalid, the result is an anonymous user.
546 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
549 public static function newFromSession( WebRequest
$request = null ) {
551 $user->mFrom
= 'session';
552 $user->mRequest
= $request;
557 * Create a new user object from a user row.
558 * The row should have the following fields from the user table in it:
559 * - either user_name or user_id to load further data if needed (or both)
561 * - all other fields (email, etc.)
562 * It is useless to provide the remaining fields if either user_id,
563 * user_name and user_real_name are not provided because the whole row
564 * will be loaded once more from the database when accessing them.
566 * @param stdClass $row A row from the user table
567 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
570 public static function newFromRow( $row, $data = null ) {
572 $user->loadFromRow( $row, $data );
577 * Static factory method for creation of a "system" user from username.
579 * A "system" user is an account that's used to attribute logged actions
580 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
581 * might include the 'Maintenance script' or 'Conversion script' accounts
582 * used by various scripts in the maintenance/ directory or accounts such
583 * as 'MediaWiki message delivery' used by the MassMessage extension.
585 * This can optionally create the user if it doesn't exist, and "steal" the
586 * account if it does exist.
588 * @param string $name Username
589 * @param array $options Options are:
590 * - validate: As for User::getCanonicalName(), default 'valid'
591 * - create: Whether to create the user if it doesn't already exist, default true
592 * - steal: Whether to reset the account's password and email if it
593 * already exists, default false
596 public static function newSystemUser( $name, $options = array() ) {
598 'validate' => 'valid',
603 $name = self
::getCanonicalName( $name, $options['validate'] );
604 if ( $name === false ) {
608 $dbw = wfGetDB( DB_MASTER
);
609 $row = $dbw->selectRow(
612 self
::selectFields(),
613 array( 'user_password', 'user_newpassword' )
615 array( 'user_name' => $name ),
619 // No user. Create it?
620 return $options['create'] ? self
::createNew( $name ) : null;
622 $user = self
::newFromRow( $row );
624 // A user is considered to exist as a non-system user if it has a
625 // password set, or a temporary password set, or an email set.
626 $passwordFactory = new PasswordFactory();
627 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
629 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
630 } catch ( PasswordError
$e ) {
631 wfDebug( 'Invalid password hash found in database.' );
632 $password = PasswordFactory
::newInvalidPassword();
635 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
636 } catch ( PasswordError
$e ) {
637 wfDebug( 'Invalid password hash found in database.' );
638 $newpassword = PasswordFactory
::newInvalidPassword();
640 if ( !$password instanceof InvalidPassword ||
!$newpassword instanceof InvalidPassword
643 // User exists. Steal it?
644 if ( !$options['steal'] ) {
648 $nopass = PasswordFactory
::newInvalidPassword()->toString();
653 'user_password' => $nopass,
654 'user_newpassword' => $nopass,
655 'user_newpass_time' => null,
657 array( 'user_id' => $user->getId() ),
660 $user->invalidateEmail();
661 $user->saveSettings();
670 * Get the username corresponding to a given user ID
671 * @param int $id User ID
672 * @return string|bool The corresponding username
674 public static function whoIs( $id ) {
675 return UserCache
::singleton()->getProp( $id, 'name' );
679 * Get the real name of a user given their user ID
681 * @param int $id User ID
682 * @return string|bool The corresponding user's real name
684 public static function whoIsReal( $id ) {
685 return UserCache
::singleton()->getProp( $id, 'real_name' );
689 * Get database id given a user name
690 * @param string $name Username
691 * @param integer $flags User::READ_* constant bitfield
692 * @return int|null The corresponding user's ID, or null if user is nonexistent
694 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
695 $nt = Title
::makeTitleSafe( NS_USER
, $name );
696 if ( is_null( $nt ) ) {
701 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
702 return self
::$idCacheByName[$name];
705 $db = ( $flags & self
::READ_LATEST
)
706 ?
wfGetDB( DB_MASTER
)
707 : wfGetDB( DB_SLAVE
);
712 array( 'user_name' => $nt->getText() ),
716 if ( $s === false ) {
719 $result = $s->user_id
;
722 self
::$idCacheByName[$name] = $result;
724 if ( count( self
::$idCacheByName ) > 1000 ) {
725 self
::$idCacheByName = array();
732 * Reset the cache used in idFromName(). For use in tests.
734 public static function resetIdByNameCache() {
735 self
::$idCacheByName = array();
739 * Does the string match an anonymous IPv4 address?
741 * This function exists for username validation, in order to reject
742 * usernames which are similar in form to IP addresses. Strings such
743 * as 300.300.300.300 will return true because it looks like an IP
744 * address, despite not being strictly valid.
746 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
747 * address because the usemod software would "cloak" anonymous IP
748 * addresses like this, if we allowed accounts like this to be created
749 * new users could get the old edits of these anonymous users.
751 * @param string $name Name to match
754 public static function isIP( $name ) {
755 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
756 || IP
::isIPv6( $name );
760 * Is the input a valid username?
762 * Checks if the input is a valid username, we don't want an empty string,
763 * an IP address, anything that contains slashes (would mess up subpages),
764 * is longer than the maximum allowed username size or doesn't begin with
767 * @param string $name Name to match
770 public static function isValidUserName( $name ) {
771 global $wgContLang, $wgMaxNameChars;
774 || User
::isIP( $name )
775 ||
strpos( $name, '/' ) !== false
776 ||
strlen( $name ) > $wgMaxNameChars
777 ||
$name != $wgContLang->ucfirst( $name )
779 wfDebugLog( 'username', __METHOD__
.
780 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
784 // Ensure that the name can't be misresolved as a different title,
785 // such as with extra namespace keys at the start.
786 $parsed = Title
::newFromText( $name );
787 if ( is_null( $parsed )
788 ||
$parsed->getNamespace()
789 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
790 wfDebugLog( 'username', __METHOD__
.
791 ": '$name' invalid due to ambiguous prefixes" );
795 // Check an additional blacklist of troublemaker characters.
796 // Should these be merged into the title char list?
797 $unicodeBlacklist = '/[' .
798 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
799 '\x{00a0}' . # non-breaking space
800 '\x{2000}-\x{200f}' . # various whitespace
801 '\x{2028}-\x{202f}' . # breaks and control chars
802 '\x{3000}' . # ideographic space
803 '\x{e000}-\x{f8ff}' . # private use
805 if ( preg_match( $unicodeBlacklist, $name ) ) {
806 wfDebugLog( 'username', __METHOD__
.
807 ": '$name' invalid due to blacklisted characters" );
815 * Usernames which fail to pass this function will be blocked
816 * from user login and new account registrations, but may be used
817 * internally by batch processes.
819 * If an account already exists in this form, login will be blocked
820 * by a failure to pass this function.
822 * @param string $name Name to match
825 public static function isUsableName( $name ) {
826 global $wgReservedUsernames;
827 // Must be a valid username, obviously ;)
828 if ( !self
::isValidUserName( $name ) ) {
832 static $reservedUsernames = false;
833 if ( !$reservedUsernames ) {
834 $reservedUsernames = $wgReservedUsernames;
835 Hooks
::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
838 // Certain names may be reserved for batch processes.
839 foreach ( $reservedUsernames as $reserved ) {
840 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
841 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
843 if ( $reserved == $name ) {
851 * Usernames which fail to pass this function will be blocked
852 * from new account registrations, but may be used internally
853 * either by batch processes or by user accounts which have
854 * already been created.
856 * Additional blacklisting may be added here rather than in
857 * isValidUserName() to avoid disrupting existing accounts.
859 * @param string $name String to match
862 public static function isCreatableName( $name ) {
863 global $wgInvalidUsernameCharacters;
865 // Ensure that the username isn't longer than 235 bytes, so that
866 // (at least for the builtin skins) user javascript and css files
867 // will work. (bug 23080)
868 if ( strlen( $name ) > 235 ) {
869 wfDebugLog( 'username', __METHOD__
.
870 ": '$name' invalid due to length" );
874 // Preg yells if you try to give it an empty string
875 if ( $wgInvalidUsernameCharacters !== '' ) {
876 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
877 wfDebugLog( 'username', __METHOD__
.
878 ": '$name' invalid due to wgInvalidUsernameCharacters" );
883 return self
::isUsableName( $name );
887 * Is the input a valid password for this user?
889 * @param string $password Desired password
892 public function isValidPassword( $password ) {
893 // simple boolean wrapper for getPasswordValidity
894 return $this->getPasswordValidity( $password ) === true;
898 * Given unvalidated password input, return error message on failure.
900 * @param string $password Desired password
901 * @return bool|string|array True on success, string or array of error message on failure
903 public function getPasswordValidity( $password ) {
904 $result = $this->checkPasswordValidity( $password );
905 if ( $result->isGood() ) {
909 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
910 $messages[] = $error['message'];
912 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
913 $messages[] = $warning['message'];
915 if ( count( $messages ) === 1 ) {
923 * Check if this is a valid password for this user
925 * Create a Status object based on the password's validity.
926 * The Status should be set to fatal if the user should not
927 * be allowed to log in, and should have any errors that
928 * would block changing the password.
930 * If the return value of this is not OK, the password
931 * should not be checked. If the return value is not Good,
932 * the password can be checked, but the user should not be
933 * able to set their password to this.
935 * @param string $password Desired password
936 * @param string $purpose one of 'login', 'create', 'reset'
940 public function checkPasswordValidity( $password, $purpose = 'login' ) {
941 global $wgPasswordPolicy;
943 $upp = new UserPasswordPolicy(
944 $wgPasswordPolicy['policies'],
945 $wgPasswordPolicy['checks']
948 $status = Status
::newGood();
949 $result = false; // init $result to false for the internal checks
951 if ( !Hooks
::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
952 $status->error( $result );
956 if ( $result === false ) {
957 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
959 } elseif ( $result === true ) {
962 $status->error( $result );
963 return $status; // the isValidPassword hook set a string $result and returned true
968 * Given unvalidated user input, return a canonical username, or false if
969 * the username is invalid.
970 * @param string $name User input
971 * @param string|bool $validate Type of validation to use:
972 * - false No validation
973 * - 'valid' Valid for batch processes
974 * - 'usable' Valid for batch processes and login
975 * - 'creatable' Valid for batch processes, login and account creation
977 * @throws InvalidArgumentException
978 * @return bool|string
980 public static function getCanonicalName( $name, $validate = 'valid' ) {
981 // Force usernames to capital
983 $name = $wgContLang->ucfirst( $name );
985 # Reject names containing '#'; these will be cleaned up
986 # with title normalisation, but then it's too late to
988 if ( strpos( $name, '#' ) !== false ) {
992 // Clean up name according to title rules,
993 // but only when validation is requested (bug 12654)
994 $t = ( $validate !== false ) ?
995 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
996 // Check for invalid titles
997 if ( is_null( $t ) ) {
1001 // Reject various classes of invalid names
1003 $name = $wgAuth->getCanonicalName( $t->getText() );
1005 switch ( $validate ) {
1009 if ( !User
::isValidUserName( $name ) ) {
1014 if ( !User
::isUsableName( $name ) ) {
1019 if ( !User
::isCreatableName( $name ) ) {
1024 throw new InvalidArgumentException(
1025 'Invalid parameter value for $validate in ' . __METHOD__
);
1031 * Count the number of edits of a user
1033 * @param int $uid User ID to check
1034 * @return int The user's edit count
1036 * @deprecated since 1.21 in favour of User::getEditCount
1038 public static function edits( $uid ) {
1039 wfDeprecated( __METHOD__
, '1.21' );
1040 $user = self
::newFromId( $uid );
1041 return $user->getEditCount();
1045 * Return a random password.
1047 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1048 * @return string New random password
1050 public static function randomPassword() {
1051 global $wgMinimalPasswordLength;
1052 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1056 * Set cached properties to default.
1058 * @note This no longer clears uncached lazy-initialised properties;
1059 * the constructor does that instead.
1061 * @param string|bool $name
1063 public function loadDefaults( $name = false ) {
1065 $this->mName
= $name;
1066 $this->mRealName
= '';
1068 $this->mOptionOverrides
= null;
1069 $this->mOptionsLoaded
= false;
1071 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1072 if ( $loggedOut !== null ) {
1073 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1075 $this->mTouched
= '1'; # Allow any pages to be cached
1078 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1079 $this->mEmailAuthenticated
= null;
1080 $this->mEmailToken
= '';
1081 $this->mEmailTokenExpires
= null;
1082 $this->mRegistration
= wfTimestamp( TS_MW
);
1083 $this->mGroups
= array();
1085 Hooks
::run( 'UserLoadDefaults', array( $this, $name ) );
1089 * Return whether an item has been loaded.
1091 * @param string $item Item to check. Current possibilities:
1095 * @param string $all 'all' to check if the whole object has been loaded
1096 * or any other string to check if only the item is available (e.g.
1100 public function isItemLoaded( $item, $all = 'all' ) {
1101 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1102 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1106 * Set that an item has been loaded
1108 * @param string $item
1110 protected function setItemLoaded( $item ) {
1111 if ( is_array( $this->mLoadedItems
) ) {
1112 $this->mLoadedItems
[$item] = true;
1117 * Load user data from the session or login cookie.
1119 * @return bool True if the user is logged in, false otherwise.
1121 private function loadFromSession() {
1123 Hooks
::run( 'UserLoadFromSession', array( $this, &$result ) );
1124 if ( $result !== null ) {
1128 $request = $this->getRequest();
1130 $cookieId = $request->getCookie( 'UserID' );
1131 $sessId = $request->getSessionData( 'wsUserID' );
1133 if ( $cookieId !== null ) {
1134 $sId = intval( $cookieId );
1135 if ( $sessId !== null && $cookieId != $sessId ) {
1136 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1137 cookie user ID ($sId) don't match!" );
1140 $request->setSessionData( 'wsUserID', $sId );
1141 } elseif ( $sessId !== null && $sessId != 0 ) {
1147 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1148 $sName = $request->getSessionData( 'wsUserName' );
1149 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1150 $sName = $request->getCookie( 'UserName' );
1151 $request->setSessionData( 'wsUserName', $sName );
1156 $proposedUser = User
::newFromId( $sId );
1157 if ( !$proposedUser->isLoggedIn() ) {
1162 global $wgBlockDisablesLogin;
1163 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1164 // User blocked and we've disabled blocked user logins
1168 if ( $request->getSessionData( 'wsToken' ) ) {
1170 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1172 } elseif ( $request->getCookie( 'Token' ) ) {
1173 # Get the token from DB/cache and clean it up to remove garbage padding.
1174 # This deals with historical problems with bugs and the default column value.
1175 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1176 // Make comparison in constant time (bug 61346)
1177 $passwordCorrect = strlen( $token )
1178 && hash_equals( $token, $request->getCookie( 'Token' ) );
1181 // No session or persistent login cookie
1185 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1186 $this->loadFromUserObject( $proposedUser );
1187 $request->setSessionData( 'wsToken', $this->getToken( false ) );
1188 wfDebug( "User: logged in from $from\n" );
1191 // Invalid credentials
1192 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1198 * Load user and user_group data from the database.
1199 * $this->mId must be set, this is how the user is identified.
1201 * @param integer $flags User::READ_* constant bitfield
1202 * @return bool True if the user exists, false if the user is anonymous
1204 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1206 $this->mId
= intval( $this->mId
);
1209 if ( !$this->mId
) {
1210 $this->loadDefaults();
1214 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1215 $db = wfGetDB( $index );
1217 $s = $db->selectRow(
1219 self
::selectFields(),
1220 array( 'user_id' => $this->mId
),
1225 $this->queryFlagsUsed
= $flags;
1226 Hooks
::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1228 if ( $s !== false ) {
1229 // Initialise user table data
1230 $this->loadFromRow( $s );
1231 $this->mGroups
= null; // deferred
1232 $this->getEditCount(); // revalidation for nulls
1237 $this->loadDefaults();
1243 * Initialize this object from a row from the user table.
1245 * @param stdClass $row Row from the user table to load.
1246 * @param array $data Further user data to load into the object
1248 * user_groups Array with groups out of the user_groups table
1249 * user_properties Array with properties out of the user_properties table
1251 protected function loadFromRow( $row, $data = null ) {
1254 $this->mGroups
= null; // deferred
1256 if ( isset( $row->user_name
) ) {
1257 $this->mName
= $row->user_name
;
1258 $this->mFrom
= 'name';
1259 $this->setItemLoaded( 'name' );
1264 if ( isset( $row->user_real_name
) ) {
1265 $this->mRealName
= $row->user_real_name
;
1266 $this->setItemLoaded( 'realname' );
1271 if ( isset( $row->user_id
) ) {
1272 $this->mId
= intval( $row->user_id
);
1273 $this->mFrom
= 'id';
1274 $this->setItemLoaded( 'id' );
1279 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1280 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1283 if ( isset( $row->user_editcount
) ) {
1284 $this->mEditCount
= $row->user_editcount
;
1289 if ( isset( $row->user_touched
) ) {
1290 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1295 if ( isset( $row->user_token
) ) {
1296 // The definition for the column is binary(32), so trim the NULs
1297 // that appends. The previous definition was char(32), so trim
1299 $this->mToken
= rtrim( $row->user_token
, " \0" );
1300 if ( $this->mToken
=== '' ) {
1301 $this->mToken
= null;
1307 if ( isset( $row->user_email
) ) {
1308 $this->mEmail
= $row->user_email
;
1309 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1310 $this->mEmailToken
= $row->user_email_token
;
1311 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1312 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1318 $this->mLoadedItems
= true;
1321 if ( is_array( $data ) ) {
1322 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1323 $this->mGroups
= $data['user_groups'];
1325 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1326 $this->loadOptions( $data['user_properties'] );
1332 * Load the data for this user object from another user object.
1336 protected function loadFromUserObject( $user ) {
1338 $user->loadGroups();
1339 $user->loadOptions();
1340 foreach ( self
::$mCacheVars as $var ) {
1341 $this->$var = $user->$var;
1346 * Load the groups from the database if they aren't already loaded.
1348 private function loadGroups() {
1349 if ( is_null( $this->mGroups
) ) {
1350 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1351 ?
wfGetDB( DB_MASTER
)
1352 : wfGetDB( DB_SLAVE
);
1353 $res = $db->select( 'user_groups',
1354 array( 'ug_group' ),
1355 array( 'ug_user' => $this->mId
),
1357 $this->mGroups
= array();
1358 foreach ( $res as $row ) {
1359 $this->mGroups
[] = $row->ug_group
;
1365 * Add the user to the group if he/she meets given criteria.
1367 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1368 * possible to remove manually via Special:UserRights. In such case it
1369 * will not be re-added automatically. The user will also not lose the
1370 * group if they no longer meet the criteria.
1372 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1374 * @return array Array of groups the user has been promoted to.
1376 * @see $wgAutopromoteOnce
1378 public function addAutopromoteOnceGroups( $event ) {
1379 global $wgAutopromoteOnceLogInRC, $wgAuth;
1381 if ( wfReadOnly() ||
!$this->getId() ) {
1385 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1386 if ( !count( $toPromote ) ) {
1390 if ( !$this->checkAndSetTouched() ) {
1391 return array(); // raced out (bug T48834)
1394 $oldGroups = $this->getGroups(); // previous groups
1395 foreach ( $toPromote as $group ) {
1396 $this->addGroup( $group );
1398 // update groups in external authentication database
1399 Hooks
::run( 'UserGroupsChanged', array( $this, $toPromote, array(), false ) );
1400 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1402 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1404 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1405 $logEntry->setPerformer( $this );
1406 $logEntry->setTarget( $this->getUserPage() );
1407 $logEntry->setParameters( array(
1408 '4::oldgroups' => $oldGroups,
1409 '5::newgroups' => $newGroups,
1411 $logid = $logEntry->insert();
1412 if ( $wgAutopromoteOnceLogInRC ) {
1413 $logEntry->publish( $logid );
1420 * Bump user_touched if it didn't change since this object was loaded
1422 * On success, the mTouched field is updated.
1423 * The user serialization cache is always cleared.
1425 * @return bool Whether user_touched was actually updated
1428 protected function checkAndSetTouched() {
1431 if ( !$this->mId
) {
1432 return false; // anon
1435 // Get a new user_touched that is higher than the old one
1436 $oldTouched = $this->mTouched
;
1437 $newTouched = $this->newTouchedTimestamp();
1439 $dbw = wfGetDB( DB_MASTER
);
1440 $dbw->update( 'user',
1441 array( 'user_touched' => $dbw->timestamp( $newTouched ) ),
1443 'user_id' => $this->mId
,
1444 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1448 $success = ( $dbw->affectedRows() > 0 );
1451 $this->mTouched
= $newTouched;
1452 $this->clearSharedCache();
1454 // Clears on failure too since that is desired if the cache is stale
1455 $this->clearSharedCache( 'refresh' );
1462 * Clear various cached data stored in this object. The cache of the user table
1463 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1465 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1466 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1468 public function clearInstanceCache( $reloadFrom = false ) {
1469 $this->mNewtalk
= -1;
1470 $this->mDatePreference
= null;
1471 $this->mBlockedby
= -1; # Unset
1472 $this->mHash
= false;
1473 $this->mRights
= null;
1474 $this->mEffectiveGroups
= null;
1475 $this->mImplicitGroups
= null;
1476 $this->mGroups
= null;
1477 $this->mOptions
= null;
1478 $this->mOptionsLoaded
= false;
1479 $this->mEditCount
= null;
1481 if ( $reloadFrom ) {
1482 $this->mLoadedItems
= array();
1483 $this->mFrom
= $reloadFrom;
1488 * Combine the language default options with any site-specific options
1489 * and add the default language variants.
1491 * @return array Array of String options
1493 public static function getDefaultOptions() {
1494 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1496 static $defOpt = null;
1497 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1498 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1499 // mid-request and see that change reflected in the return value of this function.
1500 // Which is insane and would never happen during normal MW operation
1504 $defOpt = $wgDefaultUserOptions;
1505 // Default language setting
1506 $defOpt['language'] = $wgContLang->getCode();
1507 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1508 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1510 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1511 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1513 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1515 Hooks
::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1521 * Get a given default option value.
1523 * @param string $opt Name of option to retrieve
1524 * @return string Default option value
1526 public static function getDefaultOption( $opt ) {
1527 $defOpts = self
::getDefaultOptions();
1528 if ( isset( $defOpts[$opt] ) ) {
1529 return $defOpts[$opt];
1536 * Get blocking information
1537 * @param bool $bFromSlave Whether to check the slave database first.
1538 * To improve performance, non-critical checks are done against slaves.
1539 * Check when actually saving should be done against master.
1541 private function getBlockedStatus( $bFromSlave = true ) {
1542 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1544 if ( -1 != $this->mBlockedby
) {
1548 wfDebug( __METHOD__
. ": checking...\n" );
1550 // Initialize data...
1551 // Otherwise something ends up stomping on $this->mBlockedby when
1552 // things get lazy-loaded later, causing false positive block hits
1553 // due to -1 !== 0. Probably session-related... Nothing should be
1554 // overwriting mBlockedby, surely?
1557 # We only need to worry about passing the IP address to the Block generator if the
1558 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1559 # know which IP address they're actually coming from
1560 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->equals( $wgUser ) ) {
1561 $ip = $this->getRequest()->getIP();
1567 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1570 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1572 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1574 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1575 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1576 $block->setTarget( $ip );
1577 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1579 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1580 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1581 $block->setTarget( $ip );
1585 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1586 if ( !$block instanceof Block
1587 && $wgApplyIpBlocksToXff
1589 && !in_array( $ip, $wgProxyWhitelist )
1591 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1592 $xff = array_map( 'trim', explode( ',', $xff ) );
1593 $xff = array_diff( $xff, array( $ip ) );
1594 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1595 $block = Block
::chooseBlock( $xffblocks, $xff );
1596 if ( $block instanceof Block
) {
1597 # Mangle the reason to alert the user that the block
1598 # originated from matching the X-Forwarded-For header.
1599 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1603 if ( $block instanceof Block
) {
1604 wfDebug( __METHOD__
. ": Found block.\n" );
1605 $this->mBlock
= $block;
1606 $this->mBlockedby
= $block->getByName();
1607 $this->mBlockreason
= $block->mReason
;
1608 $this->mHideName
= $block->mHideName
;
1609 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1611 $this->mBlockedby
= '';
1612 $this->mHideName
= 0;
1613 $this->mAllowUsertalk
= false;
1617 Hooks
::run( 'GetBlockedStatus', array( &$this ) );
1622 * Whether the given IP is in a DNS blacklist.
1624 * @param string $ip IP to check
1625 * @param bool $checkWhitelist Whether to check the whitelist first
1626 * @return bool True if blacklisted.
1628 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1629 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1631 if ( !$wgEnableDnsBlacklist ) {
1635 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1639 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1643 * Whether the given IP is in a given DNS blacklist.
1645 * @param string $ip IP to check
1646 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1647 * @return bool True if blacklisted.
1649 public function inDnsBlacklist( $ip, $bases ) {
1652 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1653 if ( IP
::isIPv4( $ip ) ) {
1654 // Reverse IP, bug 21255
1655 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1657 foreach ( (array)$bases as $base ) {
1659 // If we have an access key, use that too (ProjectHoneypot, etc.)
1661 if ( is_array( $base ) ) {
1662 if ( count( $base ) >= 2 ) {
1663 // Access key is 1, base URL is 0
1664 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1666 $host = "$ipReversed.{$base[0]}";
1668 $basename = $base[0];
1670 $host = "$ipReversed.$base";
1674 $ipList = gethostbynamel( $host );
1677 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1681 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1690 * Check if an IP address is in the local proxy list
1696 public static function isLocallyBlockedProxy( $ip ) {
1697 global $wgProxyList;
1699 if ( !$wgProxyList ) {
1703 if ( !is_array( $wgProxyList ) ) {
1704 // Load from the specified file
1705 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1708 if ( !is_array( $wgProxyList ) ) {
1710 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1712 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1713 // Old-style flipped proxy list
1722 * Is this user subject to rate limiting?
1724 * @return bool True if rate limited
1726 public function isPingLimitable() {
1727 global $wgRateLimitsExcludedIPs;
1728 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1729 // No other good way currently to disable rate limits
1730 // for specific IPs. :P
1731 // But this is a crappy hack and should die.
1734 return !$this->isAllowed( 'noratelimit' );
1738 * Primitive rate limits: enforce maximum actions per time period
1739 * to put a brake on flooding.
1741 * The method generates both a generic profiling point and a per action one
1742 * (suffix being "-$action".
1744 * @note When using a shared cache like memcached, IP-address
1745 * last-hit counters will be shared across wikis.
1747 * @param string $action Action to enforce; 'edit' if unspecified
1748 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1749 * @return bool True if a rate limiter was tripped
1751 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1752 // Call the 'PingLimiter' hook
1754 if ( !Hooks
::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1758 global $wgRateLimits;
1759 if ( !isset( $wgRateLimits[$action] ) ) {
1763 // Some groups shouldn't trigger the ping limiter, ever
1764 if ( !$this->isPingLimitable() ) {
1768 $limits = $wgRateLimits[$action];
1770 $id = $this->getId();
1773 if ( isset( $limits['anon'] ) && $id == 0 ) {
1774 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1777 if ( isset( $limits['user'] ) && $id != 0 ) {
1778 $userLimit = $limits['user'];
1780 if ( $this->isNewbie() ) {
1781 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1782 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1784 if ( isset( $limits['ip'] ) ) {
1785 $ip = $this->getRequest()->getIP();
1786 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1788 if ( isset( $limits['subnet'] ) ) {
1789 $ip = $this->getRequest()->getIP();
1792 if ( IP
::isIPv6( $ip ) ) {
1793 $parts = IP
::parseRange( "$ip/64" );
1794 $subnet = $parts[0];
1795 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1797 $subnet = $matches[1];
1799 if ( $subnet !== false ) {
1800 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1804 // Check for group-specific permissions
1805 // If more than one group applies, use the group with the highest limit
1806 foreach ( $this->getGroups() as $group ) {
1807 if ( isset( $limits[$group] ) ) {
1808 if ( $userLimit === false
1809 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1811 $userLimit = $limits[$group];
1815 // Set the user limit key
1816 if ( $userLimit !== false ) {
1817 list( $max, $period ) = $userLimit;
1818 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1819 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1822 $cache = ObjectCache
::getLocalClusterInstance();
1825 foreach ( $keys as $key => $limit ) {
1826 list( $max, $period ) = $limit;
1827 $summary = "(limit $max in {$period}s)";
1828 $count = $cache->get( $key );
1831 if ( $count >= $max ) {
1832 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1833 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1836 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1839 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1840 if ( $incrBy > 0 ) {
1841 $cache->add( $key, 0, intval( $period ) ); // first ping
1844 if ( $incrBy > 0 ) {
1845 $cache->incr( $key, $incrBy );
1853 * Check if user is blocked
1855 * @param bool $bFromSlave Whether to check the slave database instead of
1856 * the master. Hacked from false due to horrible probs on site.
1857 * @return bool True if blocked, false otherwise
1859 public function isBlocked( $bFromSlave = true ) {
1860 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1864 * Get the block affecting the user, or null if the user is not blocked
1866 * @param bool $bFromSlave Whether to check the slave database instead of the master
1867 * @return Block|null
1869 public function getBlock( $bFromSlave = true ) {
1870 $this->getBlockedStatus( $bFromSlave );
1871 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1875 * Check if user is blocked from editing a particular article
1877 * @param Title $title Title to check
1878 * @param bool $bFromSlave Whether to check the slave database instead of the master
1881 public function isBlockedFrom( $title, $bFromSlave = false ) {
1882 global $wgBlockAllowsUTEdit;
1884 $blocked = $this->isBlocked( $bFromSlave );
1885 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1886 // If a user's name is suppressed, they cannot make edits anywhere
1887 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1888 && $title->getNamespace() == NS_USER_TALK
) {
1890 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1893 Hooks
::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1899 * If user is blocked, return the name of the user who placed the block
1900 * @return string Name of blocker
1902 public function blockedBy() {
1903 $this->getBlockedStatus();
1904 return $this->mBlockedby
;
1908 * If user is blocked, return the specified reason for the block
1909 * @return string Blocking reason
1911 public function blockedFor() {
1912 $this->getBlockedStatus();
1913 return $this->mBlockreason
;
1917 * If user is blocked, return the ID for the block
1918 * @return int Block ID
1920 public function getBlockId() {
1921 $this->getBlockedStatus();
1922 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1926 * Check if user is blocked on all wikis.
1927 * Do not use for actual edit permission checks!
1928 * This is intended for quick UI checks.
1930 * @param string $ip IP address, uses current client if none given
1931 * @return bool True if blocked, false otherwise
1933 public function isBlockedGlobally( $ip = '' ) {
1934 if ( $this->mBlockedGlobally
!== null ) {
1935 return $this->mBlockedGlobally
;
1937 // User is already an IP?
1938 if ( IP
::isIPAddress( $this->getName() ) ) {
1939 $ip = $this->getName();
1941 $ip = $this->getRequest()->getIP();
1944 Hooks
::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1945 $this->mBlockedGlobally
= (bool)$blocked;
1946 return $this->mBlockedGlobally
;
1950 * Check if user account is locked
1952 * @return bool True if locked, false otherwise
1954 public function isLocked() {
1955 if ( $this->mLocked
!== null ) {
1956 return $this->mLocked
;
1959 $authUser = $wgAuth->getUserInstance( $this );
1960 $this->mLocked
= (bool)$authUser->isLocked();
1961 Hooks
::run( 'UserIsLocked', array( $this, &$this->mLocked
) );
1962 return $this->mLocked
;
1966 * Check if user account is hidden
1968 * @return bool True if hidden, false otherwise
1970 public function isHidden() {
1971 if ( $this->mHideName
!== null ) {
1972 return $this->mHideName
;
1974 $this->getBlockedStatus();
1975 if ( !$this->mHideName
) {
1977 $authUser = $wgAuth->getUserInstance( $this );
1978 $this->mHideName
= (bool)$authUser->isHidden();
1979 Hooks
::run( 'UserIsHidden', array( $this, &$this->mHideName
) );
1981 return $this->mHideName
;
1985 * Get the user's ID.
1986 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1988 public function getId() {
1989 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1990 // Special case, we know the user is anonymous
1992 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1993 // Don't load if this was initialized from an ID
2000 * Set the user and reload all fields according to a given ID
2001 * @param int $v User ID to reload
2003 public function setId( $v ) {
2005 $this->clearInstanceCache( 'id' );
2009 * Get the user name, or the IP of an anonymous user
2010 * @return string User's name or IP address
2012 public function getName() {
2013 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2014 // Special case optimisation
2015 return $this->mName
;
2018 if ( $this->mName
=== false ) {
2020 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2022 return $this->mName
;
2027 * Set the user name.
2029 * This does not reload fields from the database according to the given
2030 * name. Rather, it is used to create a temporary "nonexistent user" for
2031 * later addition to the database. It can also be used to set the IP
2032 * address for an anonymous user to something other than the current
2035 * @note User::newFromName() has roughly the same function, when the named user
2037 * @param string $str New user name to set
2039 public function setName( $str ) {
2041 $this->mName
= $str;
2045 * Get the user's name escaped by underscores.
2046 * @return string Username escaped by underscores.
2048 public function getTitleKey() {
2049 return str_replace( ' ', '_', $this->getName() );
2053 * Check if the user has new messages.
2054 * @return bool True if the user has new messages
2056 public function getNewtalk() {
2059 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2060 if ( $this->mNewtalk
=== -1 ) {
2061 $this->mNewtalk
= false; # reset talk page status
2063 // Check memcached separately for anons, who have no
2064 // entire User object stored in there.
2065 if ( !$this->mId
) {
2066 global $wgDisableAnonTalk;
2067 if ( $wgDisableAnonTalk ) {
2068 // Anon newtalk disabled by configuration.
2069 $this->mNewtalk
= false;
2071 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2074 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2078 return (bool)$this->mNewtalk
;
2082 * Return the data needed to construct links for new talk page message
2083 * alerts. If there are new messages, this will return an associative array
2084 * with the following data:
2085 * wiki: The database name of the wiki
2086 * link: Root-relative link to the user's talk page
2087 * rev: The last talk page revision that the user has seen or null. This
2088 * is useful for building diff links.
2089 * If there are no new messages, it returns an empty array.
2090 * @note This function was designed to accomodate multiple talk pages, but
2091 * currently only returns a single link and revision.
2094 public function getNewMessageLinks() {
2096 if ( !Hooks
::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2098 } elseif ( !$this->getNewtalk() ) {
2101 $utp = $this->getTalkPage();
2102 $dbr = wfGetDB( DB_SLAVE
);
2103 // Get the "last viewed rev" timestamp from the oldest message notification
2104 $timestamp = $dbr->selectField( 'user_newtalk',
2105 'MIN(user_last_timestamp)',
2106 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2108 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2109 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2113 * Get the revision ID for the last talk page revision viewed by the talk
2115 * @return int|null Revision ID or null
2117 public function getNewMessageRevisionId() {
2118 $newMessageRevisionId = null;
2119 $newMessageLinks = $this->getNewMessageLinks();
2120 if ( $newMessageLinks ) {
2121 // Note: getNewMessageLinks() never returns more than a single link
2122 // and it is always for the same wiki, but we double-check here in
2123 // case that changes some time in the future.
2124 if ( count( $newMessageLinks ) === 1
2125 && $newMessageLinks[0]['wiki'] === wfWikiID()
2126 && $newMessageLinks[0]['rev']
2128 /** @var Revision $newMessageRevision */
2129 $newMessageRevision = $newMessageLinks[0]['rev'];
2130 $newMessageRevisionId = $newMessageRevision->getId();
2133 return $newMessageRevisionId;
2137 * Internal uncached check for new messages
2140 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2141 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2142 * @return bool True if the user has new messages
2144 protected function checkNewtalk( $field, $id ) {
2145 $dbr = wfGetDB( DB_SLAVE
);
2147 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__
);
2149 return $ok !== false;
2153 * Add or update the new messages flag
2154 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2155 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2156 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2157 * @return bool True if successful, false otherwise
2159 protected function updateNewtalk( $field, $id, $curRev = null ) {
2160 // Get timestamp of the talk page revision prior to the current one
2161 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2162 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2163 // Mark the user as having new messages since this revision
2164 $dbw = wfGetDB( DB_MASTER
);
2165 $dbw->insert( 'user_newtalk',
2166 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2169 if ( $dbw->affectedRows() ) {
2170 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2173 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2179 * Clear the new messages flag for the given user
2180 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2181 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2182 * @return bool True if successful, false otherwise
2184 protected function deleteNewtalk( $field, $id ) {
2185 $dbw = wfGetDB( DB_MASTER
);
2186 $dbw->delete( 'user_newtalk',
2187 array( $field => $id ),
2189 if ( $dbw->affectedRows() ) {
2190 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2193 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2199 * Update the 'You have new messages!' status.
2200 * @param bool $val Whether the user has new messages
2201 * @param Revision $curRev New, as yet unseen revision of the user talk
2202 * page. Ignored if null or !$val.
2204 public function setNewtalk( $val, $curRev = null ) {
2205 if ( wfReadOnly() ) {
2210 $this->mNewtalk
= $val;
2212 if ( $this->isAnon() ) {
2214 $id = $this->getName();
2217 $id = $this->getId();
2221 $changed = $this->updateNewtalk( $field, $id, $curRev );
2223 $changed = $this->deleteNewtalk( $field, $id );
2227 $this->invalidateCache();
2232 * Generate a current or new-future timestamp to be stored in the
2233 * user_touched field when we update things.
2234 * @return string Timestamp in TS_MW format
2236 private function newTouchedTimestamp() {
2237 global $wgClockSkewFudge;
2239 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2240 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2241 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2248 * Clear user data from memcached
2250 * Use after applying updates to the database; caller's
2251 * responsibility to update user_touched if appropriate.
2253 * Called implicitly from invalidateCache() and saveSettings().
2255 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2257 public function clearSharedCache( $mode = 'changed' ) {
2258 if ( !$this->getId() ) {
2262 $cache = ObjectCache
::getMainWANInstance();
2263 $key = $this->getCacheKey( $cache );
2264 if ( $mode === 'refresh' ) {
2265 $cache->delete( $key, 1 );
2267 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
2268 $cache->delete( $key );
2274 * Immediately touch the user data cache for this account
2276 * Calls touch() and removes account data from memcached
2278 public function invalidateCache() {
2280 $this->clearSharedCache();
2284 * Update the "touched" timestamp for the user
2286 * This is useful on various login/logout events when making sure that
2287 * a browser or proxy that has multiple tenants does not suffer cache
2288 * pollution where the new user sees the old users content. The value
2289 * of getTouched() is checked when determining 304 vs 200 responses.
2290 * Unlike invalidateCache(), this preserves the User object cache and
2291 * avoids database writes.
2295 public function touch() {
2296 $id = $this->getId();
2298 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2299 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2300 $this->mQuickTouched
= null;
2305 * Validate the cache for this account.
2306 * @param string $timestamp A timestamp in TS_MW format
2309 public function validateCache( $timestamp ) {
2310 return ( $timestamp >= $this->getTouched() );
2314 * Get the user touched timestamp
2316 * Use this value only to validate caches via inequalities
2317 * such as in the case of HTTP If-Modified-Since response logic
2319 * @return string TS_MW Timestamp
2321 public function getTouched() {
2325 if ( $this->mQuickTouched
=== null ) {
2326 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2327 $cache = ObjectCache
::getMainWANInstance();
2329 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2332 return max( $this->mTouched
, $this->mQuickTouched
);
2335 return $this->mTouched
;
2339 * Get the user_touched timestamp field (time of last DB updates)
2340 * @return string TS_MW Timestamp
2343 public function getDBTouched() {
2346 return $this->mTouched
;
2350 * @deprecated Removed in 1.27.
2354 public function getPassword() {
2355 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2359 * @deprecated Removed in 1.27.
2363 public function getTemporaryPassword() {
2364 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2368 * Set the password and reset the random token.
2369 * Calls through to authentication plugin if necessary;
2370 * will have no effect if the auth plugin refuses to
2371 * pass the change through or if the legal password
2374 * As a special case, setting the password to null
2375 * wipes it, so the account cannot be logged in until
2376 * a new password is set, for instance via e-mail.
2378 * @deprecated since 1.27. AuthManager is coming.
2379 * @param string $str New password to set
2380 * @throws PasswordError On failure
2383 public function setPassword( $str ) {
2386 if ( $str !== null ) {
2387 if ( !$wgAuth->allowPasswordChange() ) {
2388 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2391 $status = $this->checkPasswordValidity( $str );
2392 if ( !$status->isGood() ) {
2393 throw new PasswordError( $status->getMessage()->text() );
2397 if ( !$wgAuth->setPassword( $this, $str ) ) {
2398 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2402 $this->setOption( 'watchlisttoken', false );
2403 $this->setPasswordInternal( $str );
2409 * Set the password and reset the random token unconditionally.
2411 * @deprecated since 1.27. AuthManager is coming.
2412 * @param string|null $str New password to set or null to set an invalid
2413 * password hash meaning that the user will not be able to log in
2414 * through the web interface.
2416 public function setInternalPassword( $str ) {
2419 if ( $wgAuth->allowSetLocalPassword() ) {
2421 $this->setOption( 'watchlisttoken', false );
2422 $this->setPasswordInternal( $str );
2427 * Actually set the password and such
2428 * @since 1.27 cannot set a password for a user not in the database
2429 * @param string|null $str New password to set or null to set an invalid
2430 * password hash meaning that the user will not be able to log in
2431 * through the web interface.
2433 private function setPasswordInternal( $str ) {
2434 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2436 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2439 $passwordFactory = new PasswordFactory();
2440 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2441 $dbw = wfGetDB( DB_MASTER
);
2445 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2446 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2447 'user_newpass_time' => $dbw->timestampOrNull( null ),
2457 * Get the user's current token.
2458 * @param bool $forceCreation Force the generation of a new token if the
2459 * user doesn't have one (default=true for backwards compatibility).
2460 * @return string|null Token
2462 public function getToken( $forceCreation = true ) {
2463 global $wgAuthenticationTokenVersion;
2466 if ( !$this->mToken
&& $forceCreation ) {
2470 // If the user doesn't have a token, return null to indicate that.
2471 // Otherwise, hmac the version with the secret if we have a version.
2472 if ( !$this->mToken
) {
2474 } elseif ( $wgAuthenticationTokenVersion === null ) {
2475 return $this->mToken
;
2477 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2479 // The raw hash can be overly long. Shorten it up.
2480 $len = max( 32, self
::TOKEN_LENGTH
);
2481 if ( strlen( $ret ) < $len ) {
2482 // Should never happen, even md5 is 128 bits
2483 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2485 return substr( $ret, -$len );
2490 * Set the random token (used for persistent authentication)
2491 * Called from loadDefaults() among other places.
2493 * @param string|bool $token If specified, set the token to this value
2495 public function setToken( $token = false ) {
2498 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2500 $this->mToken
= $token;
2505 * Set the password for a password reminder or new account email
2507 * @deprecated since 1.27, AuthManager is coming
2508 * @param string $str New password to set or null to set an invalid
2509 * password hash meaning that the user will not be able to use it
2510 * @param bool $throttle If true, reset the throttle timestamp to the present
2512 public function setNewpassword( $str, $throttle = true ) {
2513 $id = $this->getId();
2515 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2518 $dbw = wfGetDB( DB_MASTER
);
2520 $passwordFactory = new PasswordFactory();
2521 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2523 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2526 if ( $str === null ) {
2527 $update['user_newpass_time'] = null;
2528 } elseif ( $throttle ) {
2529 $update['user_newpass_time'] = $dbw->timestamp();
2532 $dbw->update( 'user', $update, array( 'user_id' => $id ), __METHOD__
);
2536 * Has password reminder email been sent within the last
2537 * $wgPasswordReminderResendTime hours?
2540 public function isPasswordReminderThrottled() {
2541 global $wgPasswordReminderResendTime;
2543 if ( !$wgPasswordReminderResendTime ) {
2549 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2550 ?
wfGetDB( DB_MASTER
)
2551 : wfGetDB( DB_SLAVE
);
2552 $newpassTime = $db->selectField(
2554 'user_newpass_time',
2555 array( 'user_id' => $this->getId() ),
2559 if ( $newpassTime === null ) {
2562 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2563 return time() < $expiry;
2567 * Get the user's e-mail address
2568 * @return string User's email address
2570 public function getEmail() {
2572 Hooks
::run( 'UserGetEmail', array( $this, &$this->mEmail
) );
2573 return $this->mEmail
;
2577 * Get the timestamp of the user's e-mail authentication
2578 * @return string TS_MW timestamp
2580 public function getEmailAuthenticationTimestamp() {
2582 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2583 return $this->mEmailAuthenticated
;
2587 * Set the user's e-mail address
2588 * @param string $str New e-mail address
2590 public function setEmail( $str ) {
2592 if ( $str == $this->mEmail
) {
2595 $this->invalidateEmail();
2596 $this->mEmail
= $str;
2597 Hooks
::run( 'UserSetEmail', array( $this, &$this->mEmail
) );
2601 * Set the user's e-mail address and a confirmation mail if needed.
2604 * @param string $str New e-mail address
2607 public function setEmailWithConfirmation( $str ) {
2608 global $wgEnableEmail, $wgEmailAuthentication;
2610 if ( !$wgEnableEmail ) {
2611 return Status
::newFatal( 'emaildisabled' );
2614 $oldaddr = $this->getEmail();
2615 if ( $str === $oldaddr ) {
2616 return Status
::newGood( true );
2619 $this->setEmail( $str );
2621 if ( $str !== '' && $wgEmailAuthentication ) {
2622 // Send a confirmation request to the new address if needed
2623 $type = $oldaddr != '' ?
'changed' : 'set';
2624 $result = $this->sendConfirmationMail( $type );
2625 if ( $result->isGood() ) {
2626 // Say to the caller that a confirmation mail has been sent
2627 $result->value
= 'eauth';
2630 $result = Status
::newGood( true );
2637 * Get the user's real name
2638 * @return string User's real name
2640 public function getRealName() {
2641 if ( !$this->isItemLoaded( 'realname' ) ) {
2645 return $this->mRealName
;
2649 * Set the user's real name
2650 * @param string $str New real name
2652 public function setRealName( $str ) {
2654 $this->mRealName
= $str;
2658 * Get the user's current setting for a given option.
2660 * @param string $oname The option to check
2661 * @param string $defaultOverride A default value returned if the option does not exist
2662 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2663 * @return string User's current value for the option
2664 * @see getBoolOption()
2665 * @see getIntOption()
2667 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2668 global $wgHiddenPrefs;
2669 $this->loadOptions();
2671 # We want 'disabled' preferences to always behave as the default value for
2672 # users, even if they have set the option explicitly in their settings (ie they
2673 # set it, and then it was disabled removing their ability to change it). But
2674 # we don't want to erase the preferences in the database in case the preference
2675 # is re-enabled again. So don't touch $mOptions, just override the returned value
2676 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2677 return self
::getDefaultOption( $oname );
2680 if ( array_key_exists( $oname, $this->mOptions
) ) {
2681 return $this->mOptions
[$oname];
2683 return $defaultOverride;
2688 * Get all user's options
2690 * @param int $flags Bitwise combination of:
2691 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2692 * to the default value. (Since 1.25)
2695 public function getOptions( $flags = 0 ) {
2696 global $wgHiddenPrefs;
2697 $this->loadOptions();
2698 $options = $this->mOptions
;
2700 # We want 'disabled' preferences to always behave as the default value for
2701 # users, even if they have set the option explicitly in their settings (ie they
2702 # set it, and then it was disabled removing their ability to change it). But
2703 # we don't want to erase the preferences in the database in case the preference
2704 # is re-enabled again. So don't touch $mOptions, just override the returned value
2705 foreach ( $wgHiddenPrefs as $pref ) {
2706 $default = self
::getDefaultOption( $pref );
2707 if ( $default !== null ) {
2708 $options[$pref] = $default;
2712 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2713 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2720 * Get the user's current setting for a given option, as a boolean value.
2722 * @param string $oname The option to check
2723 * @return bool User's current value for the option
2726 public function getBoolOption( $oname ) {
2727 return (bool)$this->getOption( $oname );
2731 * Get the user's current setting for a given option, as an integer value.
2733 * @param string $oname The option to check
2734 * @param int $defaultOverride A default value returned if the option does not exist
2735 * @return int User's current value for the option
2738 public function getIntOption( $oname, $defaultOverride = 0 ) {
2739 $val = $this->getOption( $oname );
2741 $val = $defaultOverride;
2743 return intval( $val );
2747 * Set the given option for a user.
2749 * You need to call saveSettings() to actually write to the database.
2751 * @param string $oname The option to set
2752 * @param mixed $val New value to set
2754 public function setOption( $oname, $val ) {
2755 $this->loadOptions();
2757 // Explicitly NULL values should refer to defaults
2758 if ( is_null( $val ) ) {
2759 $val = self
::getDefaultOption( $oname );
2762 $this->mOptions
[$oname] = $val;
2766 * Get a token stored in the preferences (like the watchlist one),
2767 * resetting it if it's empty (and saving changes).
2769 * @param string $oname The option name to retrieve the token from
2770 * @return string|bool User's current value for the option, or false if this option is disabled.
2771 * @see resetTokenFromOption()
2773 * @deprecated 1.26 Applications should use the OAuth extension
2775 public function getTokenFromOption( $oname ) {
2776 global $wgHiddenPrefs;
2778 $id = $this->getId();
2779 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2783 $token = $this->getOption( $oname );
2785 // Default to a value based on the user token to avoid space
2786 // wasted on storing tokens for all users. When this option
2787 // is set manually by the user, only then is it stored.
2788 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2795 * Reset a token stored in the preferences (like the watchlist one).
2796 * *Does not* save user's preferences (similarly to setOption()).
2798 * @param string $oname The option name to reset the token in
2799 * @return string|bool New token value, or false if this option is disabled.
2800 * @see getTokenFromOption()
2803 public function resetTokenFromOption( $oname ) {
2804 global $wgHiddenPrefs;
2805 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2809 $token = MWCryptRand
::generateHex( 40 );
2810 $this->setOption( $oname, $token );
2815 * Return a list of the types of user options currently returned by
2816 * User::getOptionKinds().
2818 * Currently, the option kinds are:
2819 * - 'registered' - preferences which are registered in core MediaWiki or
2820 * by extensions using the UserGetDefaultOptions hook.
2821 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2822 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2823 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2824 * be used by user scripts.
2825 * - 'special' - "preferences" that are not accessible via User::getOptions
2826 * or User::setOptions.
2827 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2828 * These are usually legacy options, removed in newer versions.
2830 * The API (and possibly others) use this function to determine the possible
2831 * option types for validation purposes, so make sure to update this when a
2832 * new option kind is added.
2834 * @see User::getOptionKinds
2835 * @return array Option kinds
2837 public static function listOptionKinds() {
2840 'registered-multiselect',
2841 'registered-checkmatrix',
2849 * Return an associative array mapping preferences keys to the kind of a preference they're
2850 * used for. Different kinds are handled differently when setting or reading preferences.
2852 * See User::listOptionKinds for the list of valid option types that can be provided.
2854 * @see User::listOptionKinds
2855 * @param IContextSource $context
2856 * @param array $options Assoc. array with options keys to check as keys.
2857 * Defaults to $this->mOptions.
2858 * @return array The key => kind mapping data
2860 public function getOptionKinds( IContextSource
$context, $options = null ) {
2861 $this->loadOptions();
2862 if ( $options === null ) {
2863 $options = $this->mOptions
;
2866 $prefs = Preferences
::getPreferences( $this, $context );
2869 // Pull out the "special" options, so they don't get converted as
2870 // multiselect or checkmatrix.
2871 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2872 foreach ( $specialOptions as $name => $value ) {
2873 unset( $prefs[$name] );
2876 // Multiselect and checkmatrix options are stored in the database with
2877 // one key per option, each having a boolean value. Extract those keys.
2878 $multiselectOptions = array();
2879 foreach ( $prefs as $name => $info ) {
2880 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2881 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2882 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2883 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2885 foreach ( $opts as $value ) {
2886 $multiselectOptions["$prefix$value"] = true;
2889 unset( $prefs[$name] );
2892 $checkmatrixOptions = array();
2893 foreach ( $prefs as $name => $info ) {
2894 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2895 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2896 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2897 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2898 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2900 foreach ( $columns as $column ) {
2901 foreach ( $rows as $row ) {
2902 $checkmatrixOptions["$prefix$column-$row"] = true;
2906 unset( $prefs[$name] );
2910 // $value is ignored
2911 foreach ( $options as $key => $value ) {
2912 if ( isset( $prefs[$key] ) ) {
2913 $mapping[$key] = 'registered';
2914 } elseif ( isset( $multiselectOptions[$key] ) ) {
2915 $mapping[$key] = 'registered-multiselect';
2916 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2917 $mapping[$key] = 'registered-checkmatrix';
2918 } elseif ( isset( $specialOptions[$key] ) ) {
2919 $mapping[$key] = 'special';
2920 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2921 $mapping[$key] = 'userjs';
2923 $mapping[$key] = 'unused';
2931 * Reset certain (or all) options to the site defaults
2933 * The optional parameter determines which kinds of preferences will be reset.
2934 * Supported values are everything that can be reported by getOptionKinds()
2935 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2937 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2938 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2939 * for backwards-compatibility.
2940 * @param IContextSource|null $context Context source used when $resetKinds
2941 * does not contain 'all', passed to getOptionKinds().
2942 * Defaults to RequestContext::getMain() when null.
2944 public function resetOptions(
2945 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2946 IContextSource
$context = null
2949 $defaultOptions = self
::getDefaultOptions();
2951 if ( !is_array( $resetKinds ) ) {
2952 $resetKinds = array( $resetKinds );
2955 if ( in_array( 'all', $resetKinds ) ) {
2956 $newOptions = $defaultOptions;
2958 if ( $context === null ) {
2959 $context = RequestContext
::getMain();
2962 $optionKinds = $this->getOptionKinds( $context );
2963 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2964 $newOptions = array();
2966 // Use default values for the options that should be deleted, and
2967 // copy old values for the ones that shouldn't.
2968 foreach ( $this->mOptions
as $key => $value ) {
2969 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2970 if ( array_key_exists( $key, $defaultOptions ) ) {
2971 $newOptions[$key] = $defaultOptions[$key];
2974 $newOptions[$key] = $value;
2979 Hooks
::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2981 $this->mOptions
= $newOptions;
2982 $this->mOptionsLoaded
= true;
2986 * Get the user's preferred date format.
2987 * @return string User's preferred date format
2989 public function getDatePreference() {
2990 // Important migration for old data rows
2991 if ( is_null( $this->mDatePreference
) ) {
2993 $value = $this->getOption( 'date' );
2994 $map = $wgLang->getDatePreferenceMigrationMap();
2995 if ( isset( $map[$value] ) ) {
2996 $value = $map[$value];
2998 $this->mDatePreference
= $value;
3000 return $this->mDatePreference
;
3004 * Determine based on the wiki configuration and the user's options,
3005 * whether this user must be over HTTPS no matter what.
3009 public function requiresHTTPS() {
3010 global $wgSecureLogin;
3011 if ( !$wgSecureLogin ) {
3014 $https = $this->getBoolOption( 'prefershttps' );
3015 Hooks
::run( 'UserRequiresHTTPS', array( $this, &$https ) );
3017 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3024 * Get the user preferred stub threshold
3028 public function getStubThreshold() {
3029 global $wgMaxArticleSize; # Maximum article size, in Kb
3030 $threshold = $this->getIntOption( 'stubthreshold' );
3031 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3032 // If they have set an impossible value, disable the preference
3033 // so we can use the parser cache again.
3040 * Get the permissions this user has.
3041 * @return array Array of String permission names
3043 public function getRights() {
3044 if ( is_null( $this->mRights
) ) {
3045 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3046 Hooks
::run( 'UserGetRights', array( $this, &$this->mRights
) );
3047 // Force reindexation of rights when a hook has unset one of them
3048 $this->mRights
= array_values( array_unique( $this->mRights
) );
3050 return $this->mRights
;
3054 * Get the list of explicit group memberships this user has.
3055 * The implicit * and user groups are not included.
3056 * @return array Array of String internal group names
3058 public function getGroups() {
3060 $this->loadGroups();
3061 return $this->mGroups
;
3065 * Get the list of implicit group memberships this user has.
3066 * This includes all explicit groups, plus 'user' if logged in,
3067 * '*' for all accounts, and autopromoted groups
3068 * @param bool $recache Whether to avoid the cache
3069 * @return array Array of String internal group names
3071 public function getEffectiveGroups( $recache = false ) {
3072 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3073 $this->mEffectiveGroups
= array_unique( array_merge(
3074 $this->getGroups(), // explicit groups
3075 $this->getAutomaticGroups( $recache ) // implicit groups
3077 // Hook for additional groups
3078 Hooks
::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
3079 // Force reindexation of groups when a hook has unset one of them
3080 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3082 return $this->mEffectiveGroups
;
3086 * Get the list of implicit group memberships this user has.
3087 * This includes 'user' if logged in, '*' for all accounts,
3088 * and autopromoted groups
3089 * @param bool $recache Whether to avoid the cache
3090 * @return array Array of String internal group names
3092 public function getAutomaticGroups( $recache = false ) {
3093 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3094 $this->mImplicitGroups
= array( '*' );
3095 if ( $this->getId() ) {
3096 $this->mImplicitGroups
[] = 'user';
3098 $this->mImplicitGroups
= array_unique( array_merge(
3099 $this->mImplicitGroups
,
3100 Autopromote
::getAutopromoteGroups( $this )
3104 // Assure data consistency with rights/groups,
3105 // as getEffectiveGroups() depends on this function
3106 $this->mEffectiveGroups
= null;
3109 return $this->mImplicitGroups
;
3113 * Returns the groups the user has belonged to.
3115 * The user may still belong to the returned groups. Compare with getGroups().
3117 * The function will not return groups the user had belonged to before MW 1.17
3119 * @return array Names of the groups the user has belonged to.
3121 public function getFormerGroups() {
3124 if ( is_null( $this->mFormerGroups
) ) {
3125 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3126 ?
wfGetDB( DB_MASTER
)
3127 : wfGetDB( DB_SLAVE
);
3128 $res = $db->select( 'user_former_groups',
3129 array( 'ufg_group' ),
3130 array( 'ufg_user' => $this->mId
),
3132 $this->mFormerGroups
= array();
3133 foreach ( $res as $row ) {
3134 $this->mFormerGroups
[] = $row->ufg_group
;
3138 return $this->mFormerGroups
;
3142 * Get the user's edit count.
3143 * @return int|null Null for anonymous users
3145 public function getEditCount() {
3146 if ( !$this->getId() ) {
3150 if ( $this->mEditCount
=== null ) {
3151 /* Populate the count, if it has not been populated yet */
3152 $dbr = wfGetDB( DB_SLAVE
);
3153 // check if the user_editcount field has been initialized
3154 $count = $dbr->selectField(
3155 'user', 'user_editcount',
3156 array( 'user_id' => $this->mId
),
3160 if ( $count === null ) {
3161 // it has not been initialized. do so.
3162 $count = $this->initEditCount();
3164 $this->mEditCount
= $count;
3166 return (int)$this->mEditCount
;
3170 * Add the user to the given group.
3171 * This takes immediate effect.
3172 * @param string $group Name of the group to add
3175 public function addGroup( $group ) {
3178 if ( !Hooks
::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3182 $dbw = wfGetDB( DB_MASTER
);
3183 if ( $this->getId() ) {
3184 $dbw->insert( 'user_groups',
3186 'ug_user' => $this->getID(),
3187 'ug_group' => $group,
3190 array( 'IGNORE' ) );
3193 $this->loadGroups();
3194 $this->mGroups
[] = $group;
3195 // In case loadGroups was not called before, we now have the right twice.
3196 // Get rid of the duplicate.
3197 $this->mGroups
= array_unique( $this->mGroups
);
3199 // Refresh the groups caches, and clear the rights cache so it will be
3200 // refreshed on the next call to $this->getRights().
3201 $this->getEffectiveGroups( true );
3202 $this->mRights
= null;
3204 $this->invalidateCache();
3210 * Remove the user from the given group.
3211 * This takes immediate effect.
3212 * @param string $group Name of the group to remove
3215 public function removeGroup( $group ) {
3217 if ( !Hooks
::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3221 $dbw = wfGetDB( DB_MASTER
);
3222 $dbw->delete( 'user_groups',
3224 'ug_user' => $this->getID(),
3225 'ug_group' => $group,
3228 // Remember that the user was in this group
3229 $dbw->insert( 'user_former_groups',
3231 'ufg_user' => $this->getID(),
3232 'ufg_group' => $group,
3238 $this->loadGroups();
3239 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3241 // Refresh the groups caches, and clear the rights cache so it will be
3242 // refreshed on the next call to $this->getRights().
3243 $this->getEffectiveGroups( true );
3244 $this->mRights
= null;
3246 $this->invalidateCache();
3252 * Get whether the user is logged in
3255 public function isLoggedIn() {
3256 return $this->getID() != 0;
3260 * Get whether the user is anonymous
3263 public function isAnon() {
3264 return !$this->isLoggedIn();
3268 * Check if user is allowed to access a feature / make an action
3270 * @param string ... Permissions to test
3271 * @return bool True if user is allowed to perform *any* of the given actions
3273 public function isAllowedAny() {
3274 $permissions = func_get_args();
3275 foreach ( $permissions as $permission ) {
3276 if ( $this->isAllowed( $permission ) ) {
3285 * @param string ... Permissions to test
3286 * @return bool True if the user is allowed to perform *all* of the given actions
3288 public function isAllowedAll() {
3289 $permissions = func_get_args();
3290 foreach ( $permissions as $permission ) {
3291 if ( !$this->isAllowed( $permission ) ) {
3299 * Internal mechanics of testing a permission
3300 * @param string $action
3303 public function isAllowed( $action = '' ) {
3304 if ( $action === '' ) {
3305 return true; // In the spirit of DWIM
3307 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3308 // by misconfiguration: 0 == 'foo'
3309 return in_array( $action, $this->getRights(), true );
3313 * Check whether to enable recent changes patrol features for this user
3314 * @return bool True or false
3316 public function useRCPatrol() {
3317 global $wgUseRCPatrol;
3318 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3322 * Check whether to enable new pages patrol features for this user
3323 * @return bool True or false
3325 public function useNPPatrol() {
3326 global $wgUseRCPatrol, $wgUseNPPatrol;
3328 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3329 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3334 * Check whether to enable new files patrol features for this user
3335 * @return bool True or false
3337 public function useFilePatrol() {
3338 global $wgUseRCPatrol, $wgUseFilePatrol;
3340 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3341 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3346 * Get the WebRequest object to use with this object
3348 * @return WebRequest
3350 public function getRequest() {
3351 if ( $this->mRequest
) {
3352 return $this->mRequest
;
3360 * Get a WatchedItem for this user and $title.
3362 * @since 1.22 $checkRights parameter added
3363 * @param Title $title
3364 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3365 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3366 * @return WatchedItem
3368 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3369 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3371 if ( isset( $this->mWatchedItems
[$key] ) ) {
3372 return $this->mWatchedItems
[$key];
3375 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3376 $this->mWatchedItems
= array();
3379 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3380 return $this->mWatchedItems
[$key];
3384 * Check the watched status of an article.
3385 * @since 1.22 $checkRights parameter added
3386 * @param Title $title Title of the article to look at
3387 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3388 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3391 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3392 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3397 * @since 1.22 $checkRights parameter added
3398 * @param Title $title Title of the article to look at
3399 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3400 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3402 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3403 $this->getWatchedItem( $title, $checkRights )->addWatch();
3404 $this->invalidateCache();
3408 * Stop watching an article.
3409 * @since 1.22 $checkRights parameter added
3410 * @param Title $title Title of the article to look at
3411 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3412 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3414 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3415 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3416 $this->invalidateCache();
3420 * Clear the user's notification timestamp for the given title.
3421 * If e-notif e-mails are on, they will receive notification mails on
3422 * the next change of the page if it's watched etc.
3423 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3424 * @param Title $title Title of the article to look at
3425 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3427 public function clearNotification( &$title, $oldid = 0 ) {
3428 global $wgUseEnotif, $wgShowUpdatedMarker;
3430 // Do nothing if the database is locked to writes
3431 if ( wfReadOnly() ) {
3435 // Do nothing if not allowed to edit the watchlist
3436 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3440 // If we're working on user's talk page, we should update the talk page message indicator
3441 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3442 if ( !Hooks
::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3447 // Try to update the DB post-send and only if needed...
3448 DeferredUpdates
::addCallableUpdate( function() use ( $that, $title, $oldid ) {
3449 if ( !$that->getNewtalk() ) {
3450 return; // no notifications to clear
3453 // Delete the last notifications (they stack up)
3454 $that->setNewtalk( false );
3456 // If there is a new, unseen, revision, use its timestamp
3458 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3461 $that->setNewtalk( true, Revision
::newFromId( $nextid ) );
3466 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3470 if ( $this->isAnon() ) {
3471 // Nothing else to do...
3475 // Only update the timestamp if the page is being watched.
3476 // The query to find out if it is watched is cached both in memcached and per-invocation,
3477 // and when it does have to be executed, it can be on a slave
3478 // If this is the user's newtalk page, we always update the timestamp
3480 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3484 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3490 * Resets all of the given user's page-change notification timestamps.
3491 * If e-notif e-mails are on, they will receive notification mails on
3492 * the next change of any watched page.
3493 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3495 public function clearAllNotifications() {
3496 if ( wfReadOnly() ) {
3500 // Do nothing if not allowed to edit the watchlist
3501 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3505 global $wgUseEnotif, $wgShowUpdatedMarker;
3506 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3507 $this->setNewtalk( false );
3510 $id = $this->getId();
3512 $dbw = wfGetDB( DB_MASTER
);
3513 $dbw->update( 'watchlist',
3514 array( /* SET */ 'wl_notificationtimestamp' => null ),
3515 array( /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ),
3518 // We also need to clear here the "you have new message" notification for the own user_talk page;
3519 // it's cleared one page view later in WikiPage::doViewUpdates().
3524 * Set a cookie on the user's client. Wrapper for
3525 * WebResponse::setCookie
3526 * @param string $name Name of the cookie to set
3527 * @param string $value Value to set
3528 * @param int $exp Expiration time, as a UNIX time value;
3529 * if 0 or not specified, use the default $wgCookieExpiration
3530 * @param bool $secure
3531 * true: Force setting the secure attribute when setting the cookie
3532 * false: Force NOT setting the secure attribute when setting the cookie
3533 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3534 * @param array $params Array of options sent passed to WebResponse::setcookie()
3535 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3538 protected function setCookie(
3539 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3541 if ( $request === null ) {
3542 $request = $this->getRequest();
3544 $params['secure'] = $secure;
3545 $request->response()->setCookie( $name, $value, $exp, $params );
3549 * Clear a cookie on the user's client
3550 * @param string $name Name of the cookie to clear
3551 * @param bool $secure
3552 * true: Force setting the secure attribute when setting the cookie
3553 * false: Force NOT setting the secure attribute when setting the cookie
3554 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3555 * @param array $params Array of options sent passed to WebResponse::setcookie()
3557 protected function clearCookie( $name, $secure = null, $params = array() ) {
3558 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3562 * Set an extended login cookie on the user's client. The expiry of the cookie
3563 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3566 * @see User::setCookie
3568 * @param string $name Name of the cookie to set
3569 * @param string $value Value to set
3570 * @param bool $secure
3571 * true: Force setting the secure attribute when setting the cookie
3572 * false: Force NOT setting the secure attribute when setting the cookie
3573 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3575 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3576 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3579 $exp +
= $wgExtendedLoginCookieExpiration !== null
3580 ?
$wgExtendedLoginCookieExpiration
3581 : $wgCookieExpiration;
3583 $this->setCookie( $name, $value, $exp, $secure );
3587 * Set the default cookies for this session on the user's client.
3589 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3591 * @param bool $secure Whether to force secure/insecure cookies or use default
3592 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3594 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3595 global $wgExtendedLoginCookies;
3597 if ( $request === null ) {
3598 $request = $this->getRequest();
3602 if ( 0 == $this->mId
) {
3605 if ( !$this->mToken
) {
3606 // When token is empty or NULL generate a new one and then save it to the database
3607 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3608 // Simply by setting every cell in the user_token column to NULL and letting them be
3609 // regenerated as users log back into the wiki.
3611 if ( !wfReadOnly() ) {
3612 $this->saveSettings();
3616 'wsUserID' => $this->mId
,
3617 'wsToken' => $this->getToken( false ),
3618 'wsUserName' => $this->getName()
3621 'UserID' => $this->mId
,
3622 'UserName' => $this->getName(),
3624 if ( $rememberMe ) {
3625 $cookies['Token'] = $this->getToken( false );
3627 $cookies['Token'] = false;
3630 Hooks
::run( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3632 foreach ( $session as $name => $value ) {
3633 $request->setSessionData( $name, $value );
3635 foreach ( $cookies as $name => $value ) {
3636 if ( $value === false ) {
3637 $this->clearCookie( $name );
3638 } elseif ( $rememberMe && in_array( $name, $wgExtendedLoginCookies ) ) {
3639 $this->setExtendedLoginCookie( $name, $value, $secure );
3641 $this->setCookie( $name, $value, 0, $secure, array(), $request );
3646 * If wpStickHTTPS was selected, also set an insecure cookie that
3647 * will cause the site to redirect the user to HTTPS, if they access
3648 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3649 * as the one set by centralauth (bug 53538). Also set it to session, or
3650 * standard time setting, based on if rememberme was set.
3652 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3656 $rememberMe ?
0 : null,
3658 array( 'prefix' => '' ) // no prefix
3664 * Log this user out.
3666 public function logout() {
3667 if ( Hooks
::run( 'UserLogout', array( &$this ) ) ) {
3673 * Clear the user's cookies and session, and reset the instance cache.
3676 public function doLogout() {
3677 $this->clearInstanceCache( 'defaults' );
3679 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3681 $this->clearCookie( 'UserID' );
3682 $this->clearCookie( 'Token' );
3683 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3685 // Remember when user logged out, to prevent seeing cached pages
3686 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3690 * Save this user's settings into the database.
3691 * @todo Only rarely do all these fields need to be set!
3693 public function saveSettings() {
3694 if ( wfReadOnly() ) {
3695 // @TODO: caller should deal with this instead!
3696 // This should really just be an exception.
3697 MWExceptionHandler
::logException( new DBExpectedError(
3699 "Could not update user with ID '{$this->mId}'; DB is read-only."
3705 if ( 0 == $this->mId
) {
3709 // Get a new user_touched that is higher than the old one.
3710 // This will be used for a CAS check as a last-resort safety
3711 // check against race conditions and slave lag.
3712 $oldTouched = $this->mTouched
;
3713 $newTouched = $this->newTouchedTimestamp();
3715 $dbw = wfGetDB( DB_MASTER
);
3716 $dbw->update( 'user',
3718 'user_name' => $this->mName
,
3719 'user_real_name' => $this->mRealName
,
3720 'user_email' => $this->mEmail
,
3721 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3722 'user_touched' => $dbw->timestamp( $newTouched ),
3723 'user_token' => strval( $this->mToken
),
3724 'user_email_token' => $this->mEmailToken
,
3725 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3726 ), array( /* WHERE */
3727 'user_id' => $this->mId
,
3728 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3732 if ( !$dbw->affectedRows() ) {
3733 // Maybe the problem was a missed cache update; clear it to be safe
3734 $this->clearSharedCache( 'refresh' );
3735 // User was changed in the meantime or loaded with stale data
3736 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3737 throw new MWException(
3738 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3739 " the version of the user to be saved is older than the current version."
3743 $this->mTouched
= $newTouched;
3744 $this->saveOptions();
3746 Hooks
::run( 'UserSaveSettings', array( $this ) );
3747 $this->clearSharedCache();
3748 $this->getUserPage()->invalidateCache();
3752 * If only this user's username is known, and it exists, return the user ID.
3754 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3757 public function idForName( $flags = 0 ) {
3758 $s = trim( $this->getName() );
3763 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3764 ?
wfGetDB( DB_MASTER
)
3765 : wfGetDB( DB_SLAVE
);
3767 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3768 ?
array( 'LOCK IN SHARE MODE' )
3771 $id = $db->selectField( 'user',
3772 'user_id', array( 'user_name' => $s ), __METHOD__
, $options );
3778 * Add a user to the database, return the user object
3780 * @param string $name Username to add
3781 * @param array $params Array of Strings Non-default parameters to save to
3782 * the database as user_* fields:
3783 * - email: The user's email address.
3784 * - email_authenticated: The email authentication timestamp.
3785 * - real_name: The user's real name.
3786 * - options: An associative array of non-default options.
3787 * - token: Random authentication token. Do not set.
3788 * - registration: Registration timestamp. Do not set.
3790 * @return User|null User object, or null if the username already exists.
3792 public static function createNew( $name, $params = array() ) {
3793 foreach ( array( 'password', 'newpassword', 'newpass_time', 'password_expires' ) as $field ) {
3794 if ( isset( $params[$field] ) ) {
3795 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3796 unset( $params[$field] );
3802 $user->setToken(); // init token
3803 if ( isset( $params['options'] ) ) {
3804 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3805 unset( $params['options'] );
3807 $dbw = wfGetDB( DB_MASTER
);
3808 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3810 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3813 'user_id' => $seqVal,
3814 'user_name' => $name,
3815 'user_password' => $noPass,
3816 'user_newpassword' => $noPass,
3817 'user_email' => $user->mEmail
,
3818 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3819 'user_real_name' => $user->mRealName
,
3820 'user_token' => strval( $user->mToken
),
3821 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3822 'user_editcount' => 0,
3823 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3825 foreach ( $params as $name => $value ) {
3826 $fields["user_$name"] = $value;
3828 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3829 if ( $dbw->affectedRows() ) {
3830 $newUser = User
::newFromId( $dbw->insertId() );
3838 * Add this existing user object to the database. If the user already
3839 * exists, a fatal status object is returned, and the user object is
3840 * initialised with the data from the database.
3842 * Previously, this function generated a DB error due to a key conflict
3843 * if the user already existed. Many extension callers use this function
3844 * in code along the lines of:
3846 * $user = User::newFromName( $name );
3847 * if ( !$user->isLoggedIn() ) {
3848 * $user->addToDatabase();
3850 * // do something with $user...
3852 * However, this was vulnerable to a race condition (bug 16020). By
3853 * initialising the user object if the user exists, we aim to support this
3854 * calling sequence as far as possible.
3856 * Note that if the user exists, this function will acquire a write lock,
3857 * so it is still advisable to make the call conditional on isLoggedIn(),
3858 * and to commit the transaction after calling.
3860 * @throws MWException
3863 public function addToDatabase() {
3865 if ( !$this->mToken
) {
3866 $this->setToken(); // init token
3869 $this->mTouched
= $this->newTouchedTimestamp();
3871 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3873 $dbw = wfGetDB( DB_MASTER
);
3874 $inWrite = $dbw->writesOrCallbacksPending();
3875 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3876 $dbw->insert( 'user',
3878 'user_id' => $seqVal,
3879 'user_name' => $this->mName
,
3880 'user_password' => $noPass,
3881 'user_newpassword' => $noPass,
3882 'user_email' => $this->mEmail
,
3883 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3884 'user_real_name' => $this->mRealName
,
3885 'user_token' => strval( $this->mToken
),
3886 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3887 'user_editcount' => 0,
3888 'user_touched' => $dbw->timestamp( $this->mTouched
),
3892 if ( !$dbw->affectedRows() ) {
3893 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3894 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3896 // Can't commit due to pending writes that may need atomicity.
3897 // This may cause some lock contention unlike the case below.
3898 $options = array( 'LOCK IN SHARE MODE' );
3899 $flags = self
::READ_LOCKING
;
3901 // Often, this case happens early in views before any writes when
3902 // using CentralAuth. It's should be OK to commit and break the snapshot.
3903 $dbw->commit( __METHOD__
, 'flush' );
3905 $flags = self
::READ_LATEST
;
3907 $this->mId
= $dbw->selectField( 'user', 'user_id',
3908 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3911 if ( $this->loadFromDatabase( $flags ) ) {
3916 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3917 "to insert user '{$this->mName}' row, but it was not present in select!" );
3919 return Status
::newFatal( 'userexists' );
3921 $this->mId
= $dbw->insertId();
3922 self
::$idCacheByName[$this->mName
] = $this->mId
;
3924 // Clear instance cache other than user table data, which is already accurate
3925 $this->clearInstanceCache();
3927 $this->saveOptions();
3928 return Status
::newGood();
3932 * If this user is logged-in and blocked,
3933 * block any IP address they've successfully logged in from.
3934 * @return bool A block was spread
3936 public function spreadAnyEditBlock() {
3937 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3938 return $this->spreadBlock();
3944 * If this (non-anonymous) user is blocked,
3945 * block the IP address they've successfully logged in from.
3946 * @return bool A block was spread
3948 protected function spreadBlock() {
3949 wfDebug( __METHOD__
. "()\n" );
3951 if ( $this->mId
== 0 ) {
3955 $userblock = Block
::newFromTarget( $this->getName() );
3956 if ( !$userblock ) {
3960 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3964 * Get whether the user is explicitly blocked from account creation.
3965 * @return bool|Block
3967 public function isBlockedFromCreateAccount() {
3968 $this->getBlockedStatus();
3969 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3970 return $this->mBlock
;
3973 # bug 13611: if the IP address the user is trying to create an account from is
3974 # blocked with createaccount disabled, prevent new account creation there even
3975 # when the user is logged in
3976 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3977 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3979 return $this->mBlockedFromCreateAccount
instanceof Block
3980 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3981 ?
$this->mBlockedFromCreateAccount
3986 * Get whether the user is blocked from using Special:Emailuser.
3989 public function isBlockedFromEmailuser() {
3990 $this->getBlockedStatus();
3991 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3995 * Get whether the user is allowed to create an account.
3998 public function isAllowedToCreateAccount() {
3999 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4003 * Get this user's personal page title.
4005 * @return Title User's personal page title
4007 public function getUserPage() {
4008 return Title
::makeTitle( NS_USER
, $this->getName() );
4012 * Get this user's talk page title.
4014 * @return Title User's talk page title
4016 public function getTalkPage() {
4017 $title = $this->getUserPage();
4018 return $title->getTalkPage();
4022 * Determine whether the user is a newbie. Newbies are either
4023 * anonymous IPs, or the most recently created accounts.
4026 public function isNewbie() {
4027 return !$this->isAllowed( 'autoconfirmed' );
4031 * Check to see if the given clear-text password is one of the accepted passwords
4032 * @deprecated since 1.27. AuthManager is coming.
4033 * @param string $password User password
4034 * @return bool True if the given password is correct, otherwise False
4036 public function checkPassword( $password ) {
4037 global $wgAuth, $wgLegacyEncoding;
4041 // Some passwords will give a fatal Status, which means there is
4042 // some sort of technical or security reason for this password to
4043 // be completely invalid and should never be checked (e.g., T64685)
4044 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4048 // Certain authentication plugins do NOT want to save
4049 // domain passwords in a mysql database, so we should
4050 // check this (in case $wgAuth->strict() is false).
4051 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4053 } elseif ( $wgAuth->strict() ) {
4054 // Auth plugin doesn't allow local authentication
4056 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4057 // Auth plugin doesn't allow local authentication for this user name
4061 $passwordFactory = new PasswordFactory();
4062 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4063 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4064 ?
wfGetDB( DB_MASTER
)
4065 : wfGetDB( DB_SLAVE
);
4068 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4069 'user', 'user_password', array( 'user_id' => $this->getId() ), __METHOD__
4071 } catch ( PasswordError
$e ) {
4072 wfDebug( 'Invalid password hash found in database.' );
4073 $mPassword = PasswordFactory
::newInvalidPassword();
4076 if ( !$mPassword->equals( $password ) ) {
4077 if ( $wgLegacyEncoding ) {
4078 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4079 // Check for this with iconv
4080 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4081 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4089 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4090 $this->setPasswordInternal( $password );
4097 * Check if the given clear-text password matches the temporary password
4098 * sent by e-mail for password reset operations.
4100 * @deprecated since 1.27. AuthManager is coming.
4101 * @param string $plaintext
4102 * @return bool True if matches, false otherwise
4104 public function checkTemporaryPassword( $plaintext ) {
4105 global $wgNewPasswordExpiry;
4109 $passwordFactory = new PasswordFactory();
4110 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4111 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4112 ?
wfGetDB( DB_MASTER
)
4113 : wfGetDB( DB_SLAVE
);
4115 $row = $db->selectRow(
4117 array( 'user_newpassword', 'user_newpass_time' ),
4118 array( 'user_id' => $this->getId() ),
4122 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4123 } catch ( PasswordError
$e ) {
4124 wfDebug( 'Invalid password hash found in database.' );
4125 $newPassword = PasswordFactory
::newInvalidPassword();
4128 if ( $newPassword->equals( $plaintext ) ) {
4129 if ( is_null( $row->user_newpass_time
) ) {
4132 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4133 return ( time() < $expiry );
4140 * Internal implementation for self::getEditToken() and
4141 * self::matchEditToken().
4143 * @param string|array $salt
4144 * @param WebRequest $request
4145 * @param string|int $timestamp
4148 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
4149 if ( $this->isAnon() ) {
4150 return self
::EDIT_TOKEN_SUFFIX
;
4152 $token = $request->getSessionData( 'wsEditToken' );
4153 if ( $token === null ) {
4154 $token = MWCryptRand
::generateHex( 32 );
4155 $request->setSessionData( 'wsEditToken', $token );
4157 if ( is_array( $salt ) ) {
4158 $salt = implode( '|', $salt );
4160 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
4161 dechex( $timestamp ) .
4162 self
::EDIT_TOKEN_SUFFIX
;
4167 * Initialize (if necessary) and return a session token value
4168 * which can be used in edit forms to show that the user's
4169 * login credentials aren't being hijacked with a foreign form
4174 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4175 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4176 * @return string The new edit token
4178 public function getEditToken( $salt = '', $request = null ) {
4179 return $this->getEditTokenAtTimestamp(
4180 $salt, $request ?
: $this->getRequest(), wfTimestamp()
4185 * Get the embedded timestamp from a token.
4186 * @param string $val Input token
4189 public static function getEditTokenTimestamp( $val ) {
4190 $suffixLen = strlen( self
::EDIT_TOKEN_SUFFIX
);
4191 if ( strlen( $val ) <= 32 +
$suffixLen ) {
4195 return hexdec( substr( $val, 32, -$suffixLen ) );
4199 * Check given value against the token value stored in the session.
4200 * A match should confirm that the form was submitted from the
4201 * user's own login session, not a form submission from a third-party
4204 * @param string $val Input value to compare
4205 * @param string $salt Optional function-specific data for hashing
4206 * @param WebRequest|null $request Object to use or null to use $wgRequest
4207 * @param int $maxage Fail tokens older than this, in seconds
4208 * @return bool Whether the token matches
4210 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4211 if ( $this->isAnon() ) {
4212 return $val === self
::EDIT_TOKEN_SUFFIX
;
4215 $timestamp = self
::getEditTokenTimestamp( $val );
4216 if ( $timestamp === null ) {
4219 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
4224 $sessionToken = $this->getEditTokenAtTimestamp(
4225 $salt, $request ?
: $this->getRequest(), $timestamp
4228 if ( !hash_equals( $sessionToken, $val ) ) {
4229 wfDebug( "User::matchEditToken: broken session data\n" );
4232 return hash_equals( $sessionToken, $val );
4236 * Check given value against the token value stored in the session,
4237 * ignoring the suffix.
4239 * @param string $val Input value to compare
4240 * @param string $salt Optional function-specific data for hashing
4241 * @param WebRequest|null $request Object to use or null to use $wgRequest
4242 * @param int $maxage Fail tokens older than this, in seconds
4243 * @return bool Whether the token matches
4245 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4246 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4247 return $this->matchEditToken( $val, $salt, $request, $maxage );
4251 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4252 * mail to the user's given address.
4254 * @param string $type Message to send, either "created", "changed" or "set"
4257 public function sendConfirmationMail( $type = 'created' ) {
4259 $expiration = null; // gets passed-by-ref and defined in next line.
4260 $token = $this->confirmationToken( $expiration );
4261 $url = $this->confirmationTokenUrl( $token );
4262 $invalidateURL = $this->invalidationTokenUrl( $token );
4263 $this->saveSettings();
4265 if ( $type == 'created' ||
$type === false ) {
4266 $message = 'confirmemail_body';
4267 } elseif ( $type === true ) {
4268 $message = 'confirmemail_body_changed';
4270 // Messages: confirmemail_body_changed, confirmemail_body_set
4271 $message = 'confirmemail_body_' . $type;
4274 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4275 wfMessage( $message,
4276 $this->getRequest()->getIP(),
4279 $wgLang->userTimeAndDate( $expiration, $this ),
4281 $wgLang->userDate( $expiration, $this ),
4282 $wgLang->userTime( $expiration, $this ) )->text() );
4286 * Send an e-mail to this user's account. Does not check for
4287 * confirmed status or validity.
4289 * @param string $subject Message subject
4290 * @param string $body Message body
4291 * @param User|null $from Optional sending user; if unspecified, default
4292 * $wgPasswordSender will be used.
4293 * @param string $replyto Reply-To address
4296 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4297 global $wgPasswordSender;
4299 if ( $from instanceof User
) {
4300 $sender = MailAddress
::newFromUser( $from );
4302 $sender = new MailAddress( $wgPasswordSender,
4303 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4305 $to = MailAddress
::newFromUser( $this );
4307 return UserMailer
::send( $to, $sender, $subject, $body, array(
4308 'replyTo' => $replyto,
4313 * Generate, store, and return a new e-mail confirmation code.
4314 * A hash (unsalted, since it's used as a key) is stored.
4316 * @note Call saveSettings() after calling this function to commit
4317 * this change to the database.
4319 * @param string &$expiration Accepts the expiration time
4320 * @return string New token
4322 protected function confirmationToken( &$expiration ) {
4323 global $wgUserEmailConfirmationTokenExpiry;
4325 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4326 $expiration = wfTimestamp( TS_MW
, $expires );
4328 $token = MWCryptRand
::generateHex( 32 );
4329 $hash = md5( $token );
4330 $this->mEmailToken
= $hash;
4331 $this->mEmailTokenExpires
= $expiration;
4336 * Return a URL the user can use to confirm their email address.
4337 * @param string $token Accepts the email confirmation token
4338 * @return string New token URL
4340 protected function confirmationTokenUrl( $token ) {
4341 return $this->getTokenUrl( 'ConfirmEmail', $token );
4345 * Return a URL the user can use to invalidate their email address.
4346 * @param string $token Accepts the email confirmation token
4347 * @return string New token URL
4349 protected function invalidationTokenUrl( $token ) {
4350 return $this->getTokenUrl( 'InvalidateEmail', $token );
4354 * Internal function to format the e-mail validation/invalidation URLs.
4355 * This uses a quickie hack to use the
4356 * hardcoded English names of the Special: pages, for ASCII safety.
4358 * @note Since these URLs get dropped directly into emails, using the
4359 * short English names avoids insanely long URL-encoded links, which
4360 * also sometimes can get corrupted in some browsers/mailers
4361 * (bug 6957 with Gmail and Internet Explorer).
4363 * @param string $page Special page
4364 * @param string $token Token
4365 * @return string Formatted URL
4367 protected function getTokenUrl( $page, $token ) {
4368 // Hack to bypass localization of 'Special:'
4369 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4370 return $title->getCanonicalURL();
4374 * Mark the e-mail address confirmed.
4376 * @note Call saveSettings() after calling this function to commit the change.
4380 public function confirmEmail() {
4381 // Check if it's already confirmed, so we don't touch the database
4382 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4383 if ( !$this->isEmailConfirmed() ) {
4384 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4385 Hooks
::run( 'ConfirmEmailComplete', array( $this ) );
4391 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4392 * address if it was already confirmed.
4394 * @note Call saveSettings() after calling this function to commit the change.
4395 * @return bool Returns true
4397 public function invalidateEmail() {
4399 $this->mEmailToken
= null;
4400 $this->mEmailTokenExpires
= null;
4401 $this->setEmailAuthenticationTimestamp( null );
4403 Hooks
::run( 'InvalidateEmailComplete', array( $this ) );
4408 * Set the e-mail authentication timestamp.
4409 * @param string $timestamp TS_MW timestamp
4411 public function setEmailAuthenticationTimestamp( $timestamp ) {
4413 $this->mEmailAuthenticated
= $timestamp;
4414 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4418 * Is this user allowed to send e-mails within limits of current
4419 * site configuration?
4422 public function canSendEmail() {
4423 global $wgEnableEmail, $wgEnableUserEmail;
4424 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4427 $canSend = $this->isEmailConfirmed();
4428 Hooks
::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4433 * Is this user allowed to receive e-mails within limits of current
4434 * site configuration?
4437 public function canReceiveEmail() {
4438 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4442 * Is this user's e-mail address valid-looking and confirmed within
4443 * limits of the current site configuration?
4445 * @note If $wgEmailAuthentication is on, this may require the user to have
4446 * confirmed their address by returning a code or using a password
4447 * sent to the address from the wiki.
4451 public function isEmailConfirmed() {
4452 global $wgEmailAuthentication;
4455 if ( Hooks
::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4456 if ( $this->isAnon() ) {
4459 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4462 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4472 * Check whether there is an outstanding request for e-mail confirmation.
4475 public function isEmailConfirmationPending() {
4476 global $wgEmailAuthentication;
4477 return $wgEmailAuthentication &&
4478 !$this->isEmailConfirmed() &&
4479 $this->mEmailToken
&&
4480 $this->mEmailTokenExpires
> wfTimestamp();
4484 * Get the timestamp of account creation.
4486 * @return string|bool|null Timestamp of account creation, false for
4487 * non-existent/anonymous user accounts, or null if existing account
4488 * but information is not in database.
4490 public function getRegistration() {
4491 if ( $this->isAnon() ) {
4495 return $this->mRegistration
;
4499 * Get the timestamp of the first edit
4501 * @return string|bool Timestamp of first edit, or false for
4502 * non-existent/anonymous user accounts.
4504 public function getFirstEditTimestamp() {
4505 if ( $this->getId() == 0 ) {
4506 return false; // anons
4508 $dbr = wfGetDB( DB_SLAVE
);
4509 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4510 array( 'rev_user' => $this->getId() ),
4512 array( 'ORDER BY' => 'rev_timestamp ASC' )
4515 return false; // no edits
4517 return wfTimestamp( TS_MW
, $time );
4521 * Get the permissions associated with a given list of groups
4523 * @param array $groups Array of Strings List of internal group names
4524 * @return array Array of Strings List of permission key names for given groups combined
4526 public static function getGroupPermissions( $groups ) {
4527 global $wgGroupPermissions, $wgRevokePermissions;
4529 // grant every granted permission first
4530 foreach ( $groups as $group ) {
4531 if ( isset( $wgGroupPermissions[$group] ) ) {
4532 $rights = array_merge( $rights,
4533 // array_filter removes empty items
4534 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4537 // now revoke the revoked permissions
4538 foreach ( $groups as $group ) {
4539 if ( isset( $wgRevokePermissions[$group] ) ) {
4540 $rights = array_diff( $rights,
4541 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4544 return array_unique( $rights );
4548 * Get all the groups who have a given permission
4550 * @param string $role Role to check
4551 * @return array Array of Strings List of internal group names with the given permission
4553 public static function getGroupsWithPermission( $role ) {
4554 global $wgGroupPermissions;
4555 $allowedGroups = array();
4556 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4557 if ( self
::groupHasPermission( $group, $role ) ) {
4558 $allowedGroups[] = $group;
4561 return $allowedGroups;
4565 * Check, if the given group has the given permission
4567 * If you're wanting to check whether all users have a permission, use
4568 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4572 * @param string $group Group to check
4573 * @param string $role Role to check
4576 public static function groupHasPermission( $group, $role ) {
4577 global $wgGroupPermissions, $wgRevokePermissions;
4578 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4579 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4583 * Check if all users may be assumed to have the given permission
4585 * We generally assume so if the right is granted to '*' and isn't revoked
4586 * on any group. It doesn't attempt to take grants or other extension
4587 * limitations on rights into account in the general case, though, as that
4588 * would require it to always return false and defeat the purpose.
4589 * Specifically, session-based rights restrictions (such as OAuth or bot
4590 * passwords) are applied based on the current session.
4593 * @param string $right Right to check
4596 public static function isEveryoneAllowed( $right ) {
4597 global $wgGroupPermissions, $wgRevokePermissions;
4598 static $cache = array();
4600 // Use the cached results, except in unit tests which rely on
4601 // being able change the permission mid-request
4602 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4603 return $cache[$right];
4606 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4607 $cache[$right] = false;
4611 // If it's revoked anywhere, then everyone doesn't have it
4612 foreach ( $wgRevokePermissions as $rights ) {
4613 if ( isset( $rights[$right] ) && $rights[$right] ) {
4614 $cache[$right] = false;
4619 // Allow extensions to say false
4620 if ( !Hooks
::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4621 $cache[$right] = false;
4625 $cache[$right] = true;
4630 * Get the localized descriptive name for a group, if it exists
4632 * @param string $group Internal group name
4633 * @return string Localized descriptive group name
4635 public static function getGroupName( $group ) {
4636 $msg = wfMessage( "group-$group" );
4637 return $msg->isBlank() ?
$group : $msg->text();
4641 * Get the localized descriptive name for a member of a group, if it exists
4643 * @param string $group Internal group name
4644 * @param string $username Username for gender (since 1.19)
4645 * @return string Localized name for group member
4647 public static function getGroupMember( $group, $username = '#' ) {
4648 $msg = wfMessage( "group-$group-member", $username );
4649 return $msg->isBlank() ?
$group : $msg->text();
4653 * Return the set of defined explicit groups.
4654 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4655 * are not included, as they are defined automatically, not in the database.
4656 * @return array Array of internal group names
4658 public static function getAllGroups() {
4659 global $wgGroupPermissions, $wgRevokePermissions;
4661 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4662 self
::getImplicitGroups()
4667 * Get a list of all available permissions.
4668 * @return string[] Array of permission names
4670 public static function getAllRights() {
4671 if ( self
::$mAllRights === false ) {
4672 global $wgAvailableRights;
4673 if ( count( $wgAvailableRights ) ) {
4674 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4676 self
::$mAllRights = self
::$mCoreRights;
4678 Hooks
::run( 'UserGetAllRights', array( &self
::$mAllRights ) );
4680 return self
::$mAllRights;
4684 * Get a list of implicit groups
4685 * @return array Array of Strings Array of internal group names
4687 public static function getImplicitGroups() {
4688 global $wgImplicitGroups;
4690 $groups = $wgImplicitGroups;
4691 # Deprecated, use $wgImplicitGroups instead
4692 Hooks
::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4698 * Get the title of a page describing a particular group
4700 * @param string $group Internal group name
4701 * @return Title|bool Title of the page if it exists, false otherwise
4703 public static function getGroupPage( $group ) {
4704 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4705 if ( $msg->exists() ) {
4706 $title = Title
::newFromText( $msg->text() );
4707 if ( is_object( $title ) ) {
4715 * Create a link to the group in HTML, if available;
4716 * else return the group name.
4718 * @param string $group Internal name of the group
4719 * @param string $text The text of the link
4720 * @return string HTML link to the group
4722 public static function makeGroupLinkHTML( $group, $text = '' ) {
4723 if ( $text == '' ) {
4724 $text = self
::getGroupName( $group );
4726 $title = self
::getGroupPage( $group );
4728 return Linker
::link( $title, htmlspecialchars( $text ) );
4730 return htmlspecialchars( $text );
4735 * Create a link to the group in Wikitext, if available;
4736 * else return the group name.
4738 * @param string $group Internal name of the group
4739 * @param string $text The text of the link
4740 * @return string Wikilink to the group
4742 public static function makeGroupLinkWiki( $group, $text = '' ) {
4743 if ( $text == '' ) {
4744 $text = self
::getGroupName( $group );
4746 $title = self
::getGroupPage( $group );
4748 $page = $title->getFullText();
4749 return "[[$page|$text]]";
4756 * Returns an array of the groups that a particular group can add/remove.
4758 * @param string $group The group to check for whether it can add/remove
4759 * @return array Array( 'add' => array( addablegroups ),
4760 * 'remove' => array( removablegroups ),
4761 * 'add-self' => array( addablegroups to self),
4762 * 'remove-self' => array( removable groups from self) )
4764 public static function changeableByGroup( $group ) {
4765 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4769 'remove' => array(),
4770 'add-self' => array(),
4771 'remove-self' => array()
4774 if ( empty( $wgAddGroups[$group] ) ) {
4775 // Don't add anything to $groups
4776 } elseif ( $wgAddGroups[$group] === true ) {
4777 // You get everything
4778 $groups['add'] = self
::getAllGroups();
4779 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4780 $groups['add'] = $wgAddGroups[$group];
4783 // Same thing for remove
4784 if ( empty( $wgRemoveGroups[$group] ) ) {
4786 } elseif ( $wgRemoveGroups[$group] === true ) {
4787 $groups['remove'] = self
::getAllGroups();
4788 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4789 $groups['remove'] = $wgRemoveGroups[$group];
4792 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4793 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4794 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4795 if ( is_int( $key ) ) {
4796 $wgGroupsAddToSelf['user'][] = $value;
4801 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4802 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4803 if ( is_int( $key ) ) {
4804 $wgGroupsRemoveFromSelf['user'][] = $value;
4809 // Now figure out what groups the user can add to him/herself
4810 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4812 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4813 // No idea WHY this would be used, but it's there
4814 $groups['add-self'] = User
::getAllGroups();
4815 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4816 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4819 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4821 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4822 $groups['remove-self'] = User
::getAllGroups();
4823 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4824 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4831 * Returns an array of groups that this user can add and remove
4832 * @return array Array( 'add' => array( addablegroups ),
4833 * 'remove' => array( removablegroups ),
4834 * 'add-self' => array( addablegroups to self),
4835 * 'remove-self' => array( removable groups from self) )
4837 public function changeableGroups() {
4838 if ( $this->isAllowed( 'userrights' ) ) {
4839 // This group gives the right to modify everything (reverse-
4840 // compatibility with old "userrights lets you change
4842 // Using array_merge to make the groups reindexed
4843 $all = array_merge( User
::getAllGroups() );
4847 'add-self' => array(),
4848 'remove-self' => array()
4852 // Okay, it's not so simple, we will have to go through the arrays
4855 'remove' => array(),
4856 'add-self' => array(),
4857 'remove-self' => array()
4859 $addergroups = $this->getEffectiveGroups();
4861 foreach ( $addergroups as $addergroup ) {
4862 $groups = array_merge_recursive(
4863 $groups, $this->changeableByGroup( $addergroup )
4865 $groups['add'] = array_unique( $groups['add'] );
4866 $groups['remove'] = array_unique( $groups['remove'] );
4867 $groups['add-self'] = array_unique( $groups['add-self'] );
4868 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4874 * Deferred version of incEditCountImmediate()
4876 public function incEditCount() {
4878 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $that ) {
4879 $that->incEditCountImmediate();
4884 * Increment the user's edit-count field.
4885 * Will have no effect for anonymous users.
4888 public function incEditCountImmediate() {
4889 if ( $this->isAnon() ) {
4893 $dbw = wfGetDB( DB_MASTER
);
4894 // No rows will be "affected" if user_editcount is NULL
4897 array( 'user_editcount=user_editcount+1' ),
4898 array( 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ),
4901 // Lazy initialization check...
4902 if ( $dbw->affectedRows() == 0 ) {
4903 // Now here's a goddamn hack...
4904 $dbr = wfGetDB( DB_SLAVE
);
4905 if ( $dbr !== $dbw ) {
4906 // If we actually have a slave server, the count is
4907 // at least one behind because the current transaction
4908 // has not been committed and replicated.
4909 $this->initEditCount( 1 );
4911 // But if DB_SLAVE is selecting the master, then the
4912 // count we just read includes the revision that was
4913 // just added in the working transaction.
4914 $this->initEditCount();
4917 // Edit count in user cache too
4918 $this->invalidateCache();
4922 * Initialize user_editcount from data out of the revision table
4924 * @param int $add Edits to add to the count from the revision table
4925 * @return int Number of edits
4927 protected function initEditCount( $add = 0 ) {
4928 // Pull from a slave to be less cruel to servers
4929 // Accuracy isn't the point anyway here
4930 $dbr = wfGetDB( DB_SLAVE
);
4931 $count = (int)$dbr->selectField(
4934 array( 'rev_user' => $this->getId() ),
4937 $count = $count +
$add;
4939 $dbw = wfGetDB( DB_MASTER
);
4942 array( 'user_editcount' => $count ),
4943 array( 'user_id' => $this->getId() ),
4951 * Get the description of a given right
4953 * @param string $right Right to query
4954 * @return string Localized description of the right
4956 public static function getRightDescription( $right ) {
4957 $key = "right-$right";
4958 $msg = wfMessage( $key );
4959 return $msg->isBlank() ?
$right : $msg->text();
4963 * Make a new-style password hash
4965 * @param string $password Plain-text password
4966 * @param bool|string $salt Optional salt, may be random or the user ID.
4967 * If unspecified or false, will generate one automatically
4968 * @return string Password hash
4969 * @deprecated since 1.24, use Password class
4971 public static function crypt( $password, $salt = false ) {
4972 wfDeprecated( __METHOD__
, '1.24' );
4973 $passwordFactory = new PasswordFactory();
4974 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4975 $hash = $passwordFactory->newFromPlaintext( $password );
4976 return $hash->toString();
4980 * Compare a password hash with a plain-text password. Requires the user
4981 * ID if there's a chance that the hash is an old-style hash.
4983 * @param string $hash Password hash
4984 * @param string $password Plain-text password to compare
4985 * @param string|bool $userId User ID for old-style password salt
4988 * @deprecated since 1.24, use Password class
4990 public static function comparePasswords( $hash, $password, $userId = false ) {
4991 wfDeprecated( __METHOD__
, '1.24' );
4993 // Check for *really* old password hashes that don't even have a type
4994 // The old hash format was just an md5 hex hash, with no type information
4995 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4996 global $wgPasswordSalt;
4997 if ( $wgPasswordSalt ) {
4998 $password = ":B:{$userId}:{$hash}";
5000 $password = ":A:{$hash}";
5004 $passwordFactory = new PasswordFactory();
5005 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5006 $hash = $passwordFactory->newFromCiphertext( $hash );
5007 return $hash->equals( $password );
5011 * Add a newuser log entry for this user.
5012 * Before 1.19 the return value was always true.
5014 * @param string|bool $action Account creation type.
5015 * - String, one of the following values:
5016 * - 'create' for an anonymous user creating an account for himself.
5017 * This will force the action's performer to be the created user itself,
5018 * no matter the value of $wgUser
5019 * - 'create2' for a logged in user creating an account for someone else
5020 * - 'byemail' when the created user will receive its password by e-mail
5021 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5022 * - Boolean means whether the account was created by e-mail (deprecated):
5023 * - true will be converted to 'byemail'
5024 * - false will be converted to 'create' if this object is the same as
5025 * $wgUser and to 'create2' otherwise
5027 * @param string $reason User supplied reason
5029 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
5031 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5032 global $wgUser, $wgNewUserLog;
5033 if ( empty( $wgNewUserLog ) ) {
5034 return true; // disabled
5037 if ( $action === true ) {
5038 $action = 'byemail';
5039 } elseif ( $action === false ) {
5040 if ( $this->equals( $wgUser ) ) {
5043 $action = 'create2';
5047 if ( $action === 'create' ||
$action === 'autocreate' ) {
5050 $performer = $wgUser;
5053 $logEntry = new ManualLogEntry( 'newusers', $action );
5054 $logEntry->setPerformer( $performer );
5055 $logEntry->setTarget( $this->getUserPage() );
5056 $logEntry->setComment( $reason );
5057 $logEntry->setParameters( array(
5058 '4::userid' => $this->getId(),
5060 $logid = $logEntry->insert();
5062 if ( $action !== 'autocreate' ) {
5063 $logEntry->publish( $logid );
5070 * Add an autocreate newuser log entry for this user
5071 * Used by things like CentralAuth and perhaps other authplugins.
5072 * Consider calling addNewUserLogEntry() directly instead.
5076 public function addNewUserLogEntryAutoCreate() {
5077 $this->addNewUserLogEntry( 'autocreate' );
5083 * Load the user options either from cache, the database or an array
5085 * @param array $data Rows for the current user out of the user_properties table
5087 protected function loadOptions( $data = null ) {
5092 if ( $this->mOptionsLoaded
) {
5096 $this->mOptions
= self
::getDefaultOptions();
5098 if ( !$this->getId() ) {
5099 // For unlogged-in users, load language/variant options from request.
5100 // There's no need to do it for logged-in users: they can set preferences,
5101 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5102 // so don't override user's choice (especially when the user chooses site default).
5103 $variant = $wgContLang->getDefaultVariant();
5104 $this->mOptions
['variant'] = $variant;
5105 $this->mOptions
['language'] = $variant;
5106 $this->mOptionsLoaded
= true;
5110 // Maybe load from the object
5111 if ( !is_null( $this->mOptionOverrides
) ) {
5112 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5113 foreach ( $this->mOptionOverrides
as $key => $value ) {
5114 $this->mOptions
[$key] = $value;
5117 if ( !is_array( $data ) ) {
5118 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5119 // Load from database
5120 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5121 ?
wfGetDB( DB_MASTER
)
5122 : wfGetDB( DB_SLAVE
);
5124 $res = $dbr->select(
5126 array( 'up_property', 'up_value' ),
5127 array( 'up_user' => $this->getId() ),
5131 $this->mOptionOverrides
= array();
5133 foreach ( $res as $row ) {
5134 $data[$row->up_property
] = $row->up_value
;
5137 foreach ( $data as $property => $value ) {
5138 $this->mOptionOverrides
[$property] = $value;
5139 $this->mOptions
[$property] = $value;
5143 $this->mOptionsLoaded
= true;
5145 Hooks
::run( 'UserLoadOptions', array( $this, &$this->mOptions
) );
5149 * Saves the non-default options for this user, as previously set e.g. via
5150 * setOption(), in the database's "user_properties" (preferences) table.
5151 * Usually used via saveSettings().
5153 protected function saveOptions() {
5154 $this->loadOptions();
5156 // Not using getOptions(), to keep hidden preferences in database
5157 $saveOptions = $this->mOptions
;
5159 // Allow hooks to abort, for instance to save to a global profile.
5160 // Reset options to default state before saving.
5161 if ( !Hooks
::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5165 $userId = $this->getId();
5167 $insert_rows = array(); // all the new preference rows
5168 foreach ( $saveOptions as $key => $value ) {
5169 // Don't bother storing default values
5170 $defaultOption = self
::getDefaultOption( $key );
5171 if ( ( $defaultOption === null && $value !== false && $value !== null )
5172 ||
$value != $defaultOption
5174 $insert_rows[] = array(
5175 'up_user' => $userId,
5176 'up_property' => $key,
5177 'up_value' => $value,
5182 $dbw = wfGetDB( DB_MASTER
);
5184 $res = $dbw->select( 'user_properties',
5185 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
5187 // Find prior rows that need to be removed or updated. These rows will
5188 // all be deleted (the later so that INSERT IGNORE applies the new values).
5189 $keysDelete = array();
5190 foreach ( $res as $row ) {
5191 if ( !isset( $saveOptions[$row->up_property
] )
5192 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5194 $keysDelete[] = $row->up_property
;
5198 if ( count( $keysDelete ) ) {
5199 // Do the DELETE by PRIMARY KEY for prior rows.
5200 // In the past a very large portion of calls to this function are for setting
5201 // 'rememberpassword' for new accounts (a preference that has since been removed).
5202 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5203 // caused gap locks on [max user ID,+infinity) which caused high contention since
5204 // updates would pile up on each other as they are for higher (newer) user IDs.
5205 // It might not be necessary these days, but it shouldn't hurt either.
5206 $dbw->delete( 'user_properties',
5207 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
5209 // Insert the new preference rows
5210 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
5214 * Lazily instantiate and return a factory object for making passwords
5216 * @deprecated since 1.27, create a PasswordFactory directly instead
5217 * @return PasswordFactory
5219 public static function getPasswordFactory() {
5220 wfDeprecated( __METHOD__
, '1.27' );
5221 $ret = new PasswordFactory();
5222 $ret->init( RequestContext
::getMain()->getConfig() );
5227 * Provide an array of HTML5 attributes to put on an input element
5228 * intended for the user to enter a new password. This may include
5229 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5231 * Do *not* use this when asking the user to enter his current password!
5232 * Regardless of configuration, users may have invalid passwords for whatever
5233 * reason (e.g., they were set before requirements were tightened up).
5234 * Only use it when asking for a new password, like on account creation or
5237 * Obviously, you still need to do server-side checking.
5239 * NOTE: A combination of bugs in various browsers means that this function
5240 * actually just returns array() unconditionally at the moment. May as
5241 * well keep it around for when the browser bugs get fixed, though.
5243 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5245 * @deprecated since 1.27
5246 * @return array Array of HTML attributes suitable for feeding to
5247 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5248 * That will get confused by the boolean attribute syntax used.)
5250 public static function passwordChangeInputAttribs() {
5251 global $wgMinimalPasswordLength;
5253 if ( $wgMinimalPasswordLength == 0 ) {
5257 # Note that the pattern requirement will always be satisfied if the
5258 # input is empty, so we need required in all cases.
5260 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5261 # if e-mail confirmation is being used. Since HTML5 input validation
5262 # is b0rked anyway in some browsers, just return nothing. When it's
5263 # re-enabled, fix this code to not output required for e-mail
5265 # $ret = array( 'required' );
5268 # We can't actually do this right now, because Opera 9.6 will print out
5269 # the entered password visibly in its error message! When other
5270 # browsers add support for this attribute, or Opera fixes its support,
5271 # we can add support with a version check to avoid doing this on Opera
5272 # versions where it will be a problem. Reported to Opera as
5273 # DSK-262266, but they don't have a public bug tracker for us to follow.
5275 if ( $wgMinimalPasswordLength > 1 ) {
5276 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5277 $ret['title'] = wfMessage( 'passwordtooshort' )
5278 ->numParams( $wgMinimalPasswordLength )->text();
5286 * Return the list of user fields that should be selected to create
5287 * a new user object.
5290 public static function selectFields() {
5298 'user_email_authenticated',
5300 'user_email_token_expires',
5301 'user_registration',
5307 * Factory function for fatal permission-denied errors
5310 * @param string $permission User right required
5313 static function newFatalPermissionDeniedStatus( $permission ) {
5316 $groups = array_map(
5317 array( 'User', 'makeGroupLinkWiki' ),
5318 User
::getGroupsWithPermission( $permission )
5322 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5324 return Status
::newFatal( 'badaccess-group0' );
5329 * Get a new instance of this user that was loaded from the master via a locking read
5331 * Use this instead of the main context User when updating that user. This avoids races
5332 * where that user was loaded from a slave or even the master but without proper locks.
5334 * @return User|null Returns null if the user was not found in the DB
5337 public function getInstanceForUpdate() {
5338 if ( !$this->getId() ) {
5339 return null; // anon
5342 $user = self
::newFromId( $this->getId() );
5343 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5351 * Checks if two user objects point to the same user.
5357 public function equals( User
$user ) {
5358 return $this->getName() === $user->getName();