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',
169 'userrights-interwiki',
177 * String Cached results of getAllRights()
179 protected static $mAllRights = false;
181 /** Cache variables */
188 /** @var Password|null */
189 private $mPassword = null;
193 /** @var string TS_MW timestamp from the DB */
195 /** @var string TS_MW timestamp from cache */
196 protected $mQuickTouched;
200 public $mEmailAuthenticated;
202 protected $mEmailToken;
204 protected $mEmailTokenExpires;
206 protected $mRegistration;
208 protected $mEditCount;
212 protected $mOptionOverrides;
216 * Bool Whether the cache variables have been loaded.
219 public $mOptionsLoaded;
222 * Array with already loaded items or true if all items have been loaded.
224 protected $mLoadedItems = array();
228 * String Initialization data source if mLoadedItems!==true. May be one of:
229 * - 'defaults' anonymous user initialised from class defaults
230 * - 'name' initialise from mName
231 * - 'id' initialise from mId
232 * - 'session' log in from cookies or session if possible
234 * Use the User::newFrom*() family of functions to set this.
239 * Lazy-initialized variables, invalidated with clearInstanceCache
243 protected $mDatePreference;
251 protected $mBlockreason;
253 protected $mEffectiveGroups;
255 protected $mImplicitGroups;
257 protected $mFormerGroups;
259 protected $mBlockedGlobally;
276 protected $mAllowUsertalk;
279 private $mBlockedFromCreateAccount = false;
282 private $mWatchedItems = array();
284 /** @var integer User::READ_* constant bitfield used to load data */
285 protected $queryFlagsUsed = self
::READ_NORMAL
;
287 public static $idCacheByName = array();
290 * Lightweight constructor for an anonymous user.
291 * Use the User::newFrom* factory functions for other kinds of users.
295 * @see newFromConfirmationCode()
296 * @see newFromSession()
299 public function __construct() {
300 $this->clearInstanceCache( 'defaults' );
306 public function __toString() {
307 return $this->getName();
311 * Load the user table data for this object from the source given by mFrom.
313 * @param integer $flags User::READ_* constant bitfield
315 public function load( $flags = self
::READ_NORMAL
) {
316 if ( $this->mLoadedItems
=== true ) {
320 // Set it now to avoid infinite recursion in accessors
321 $this->mLoadedItems
= true;
322 $this->queryFlagsUsed
= $flags;
324 switch ( $this->mFrom
) {
326 $this->loadDefaults();
329 // Make sure this thread sees its own changes
330 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
331 $flags |
= self
::READ_LATEST
;
332 $this->queryFlagsUsed
= $flags;
335 $this->mId
= self
::idFromName( $this->mName
, $flags );
337 // Nonexistent user placeholder object
338 $this->loadDefaults( $this->mName
);
340 $this->loadFromId( $flags );
344 $this->loadFromId( $flags );
347 if ( !$this->loadFromSession() ) {
348 // Loading from session failed. Load defaults.
349 $this->loadDefaults();
351 Hooks
::run( 'UserLoadAfterLoadFromSession', array( $this ) );
354 throw new UnexpectedValueException(
355 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
360 * Load user table data, given mId has already been set.
361 * @param integer $flags User::READ_* constant bitfield
362 * @return bool False if the ID does not exist, true otherwise
364 public function loadFromId( $flags = self
::READ_NORMAL
) {
365 if ( $this->mId
== 0 ) {
366 $this->loadDefaults();
370 // Try cache (unless this needs data from the master DB).
371 // NOTE: if this thread called saveSettings(), the cache was cleared.
372 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
373 if ( $latest ||
!$this->loadFromCache() ) {
374 wfDebug( "User: cache miss for user {$this->mId}\n" );
375 // Load from DB (make sure this thread sees its own changes)
376 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
377 $flags |
= self
::READ_LATEST
;
379 if ( !$this->loadFromDatabase( $flags ) ) {
380 // Can't load from ID, user is anonymous
383 $this->saveToCache();
386 $this->mLoadedItems
= true;
387 $this->queryFlagsUsed
= $flags;
393 * Load user data from shared cache, given mId has already been set.
395 * @return bool false if the ID does not exist or data is invalid, true otherwise
398 protected function loadFromCache() {
399 if ( $this->mId
== 0 ) {
400 $this->loadDefaults();
404 $key = wfMemcKey( 'user', 'id', $this->mId
);
405 $data = ObjectCache
::getMainWANInstance()->get( $key );
406 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
411 wfDebug( "User: got user {$this->mId} from cache\n" );
413 // Restore from cache
414 foreach ( self
::$mCacheVars as $name ) {
415 $this->$name = $data[$name];
422 * Save user data to the shared cache
424 * This method should not be called outside the User class
426 public function saveToCache() {
429 $this->loadOptions();
431 if ( $this->isAnon() ) {
432 // Anonymous users are uncached
437 foreach ( self
::$mCacheVars as $name ) {
438 $data[$name] = $this->$name;
440 $data['mVersion'] = self
::VERSION
;
441 $key = wfMemcKey( 'user', 'id', $this->mId
);
443 $opts = Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
444 ObjectCache
::getMainWANInstance()->set( $key, $data, 3600, $opts );
447 /** @name newFrom*() static factory methods */
451 * Static factory method for creation from username.
453 * This is slightly less efficient than newFromId(), so use newFromId() if
454 * you have both an ID and a name handy.
456 * @param string $name Username, validated by Title::newFromText()
457 * @param string|bool $validate Validate username. Takes the same parameters as
458 * User::getCanonicalName(), except that true is accepted as an alias
459 * for 'valid', for BC.
461 * @return User|bool User object, or false if the username is invalid
462 * (e.g. if it contains illegal characters or is an IP address). If the
463 * username is not present in the database, the result will be a user object
464 * with a name, zero user ID and default settings.
466 public static function newFromName( $name, $validate = 'valid' ) {
467 if ( $validate === true ) {
470 $name = self
::getCanonicalName( $name, $validate );
471 if ( $name === false ) {
474 // Create unloaded user object
478 $u->setItemLoaded( 'name' );
484 * Static factory method for creation from a given user ID.
486 * @param int $id Valid user ID
487 * @return User The corresponding User object
489 public static function newFromId( $id ) {
493 $u->setItemLoaded( 'id' );
498 * Factory method to fetch whichever user has a given email confirmation code.
499 * This code is generated when an account is created or its e-mail address
502 * If the code is invalid or has expired, returns NULL.
504 * @param string $code Confirmation code
505 * @param int $flags User::READ_* bitfield
508 public static function newFromConfirmationCode( $code, $flags = 0 ) {
509 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
510 ?
wfGetDB( DB_MASTER
)
511 : wfGetDB( DB_SLAVE
);
513 $id = $db->selectField(
517 'user_email_token' => md5( $code ),
518 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
522 return $id ? User
::newFromId( $id ) : null;
526 * Create a new user object using data from session or cookies. If the
527 * login credentials are invalid, the result is an anonymous user.
529 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
532 public static function newFromSession( WebRequest
$request = null ) {
534 $user->mFrom
= 'session';
535 $user->mRequest
= $request;
540 * Create a new user object from a user row.
541 * The row should have the following fields from the user table in it:
542 * - either user_name or user_id to load further data if needed (or both)
544 * - all other fields (email, etc.)
545 * It is useless to provide the remaining fields if either user_id,
546 * user_name and user_real_name are not provided because the whole row
547 * will be loaded once more from the database when accessing them.
549 * @param stdClass $row A row from the user table
550 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
553 public static function newFromRow( $row, $data = null ) {
555 $user->loadFromRow( $row, $data );
560 * Static factory method for creation of a "system" user from username.
562 * A "system" user is an account that's used to attribute logged actions
563 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
564 * might include the 'Maintenance script' or 'Conversion script' accounts
565 * used by various scripts in the maintenance/ directory or accounts such
566 * as 'MediaWiki message delivery' used by the MassMessage extension.
568 * This can optionally create the user if it doesn't exist, and "steal" the
569 * account if it does exist.
571 * @param string $name Username
572 * @param array $options Options are:
573 * - validate: As for User::getCanonicalName(), default 'valid'
574 * - create: Whether to create the user if it doesn't already exist, default true
575 * - steal: Whether to reset the account's password and email if it
576 * already exists, default false
579 public static function newSystemUser( $name, $options = array() ) {
581 'validate' => 'valid',
586 $name = self
::getCanonicalName( $name, $options['validate'] );
587 if ( $name === false ) {
591 $dbw = wfGetDB( DB_MASTER
);
592 $row = $dbw->selectRow(
595 self
::selectFields(),
596 array( 'user_password', 'user_newpassword' )
598 array( 'user_name' => $name ),
602 // No user. Create it?
603 return $options['create'] ? self
::createNew( $name ) : null;
605 $user = self
::newFromRow( $row );
607 // A user is considered to exist as a non-system user if it has a
608 // password set, or a temporary password set, or an email set.
609 $passwordFactory = new PasswordFactory();
610 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
612 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
613 } catch ( PasswordError
$e ) {
614 wfDebug( 'Invalid password hash found in database.' );
615 $password = PasswordFactory
::newInvalidPassword();
618 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
619 } catch ( PasswordError
$e ) {
620 wfDebug( 'Invalid password hash found in database.' );
621 $newpassword = PasswordFactory
::newInvalidPassword();
623 if ( !$password instanceof InvalidPassword ||
!$newpassword instanceof InvalidPassword
626 // User exists. Steal it?
627 if ( !$options['steal'] ) {
631 $nopass = PasswordFactory
::newInvalidPassword()->toString();
636 'user_password' => $nopass,
637 'user_newpassword' => $nopass,
638 'user_newpass_time' => null,
640 array( 'user_id' => $user->getId() ),
643 $user->invalidateEmail();
644 $user->saveSettings();
653 * Get the username corresponding to a given user ID
654 * @param int $id User ID
655 * @return string|bool The corresponding username
657 public static function whoIs( $id ) {
658 return UserCache
::singleton()->getProp( $id, 'name' );
662 * Get the real name of a user given their user ID
664 * @param int $id User ID
665 * @return string|bool The corresponding user's real name
667 public static function whoIsReal( $id ) {
668 return UserCache
::singleton()->getProp( $id, 'real_name' );
672 * Get database id given a user name
673 * @param string $name Username
674 * @param integer $flags User::READ_* constant bitfield
675 * @return int|null The corresponding user's ID, or null if user is nonexistent
677 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
678 $nt = Title
::makeTitleSafe( NS_USER
, $name );
679 if ( is_null( $nt ) ) {
684 if ( isset( self
::$idCacheByName[$name] ) ) {
685 return self
::$idCacheByName[$name];
688 $db = ( $flags & self
::READ_LATEST
)
689 ?
wfGetDB( DB_MASTER
)
690 : wfGetDB( DB_SLAVE
);
695 array( 'user_name' => $nt->getText() ),
699 if ( $s === false ) {
702 $result = $s->user_id
;
705 self
::$idCacheByName[$name] = $result;
707 if ( count( self
::$idCacheByName ) > 1000 ) {
708 self
::$idCacheByName = array();
715 * Reset the cache used in idFromName(). For use in tests.
717 public static function resetIdByNameCache() {
718 self
::$idCacheByName = array();
722 * Does the string match an anonymous IPv4 address?
724 * This function exists for username validation, in order to reject
725 * usernames which are similar in form to IP addresses. Strings such
726 * as 300.300.300.300 will return true because it looks like an IP
727 * address, despite not being strictly valid.
729 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
730 * address because the usemod software would "cloak" anonymous IP
731 * addresses like this, if we allowed accounts like this to be created
732 * new users could get the old edits of these anonymous users.
734 * @param string $name Name to match
737 public static function isIP( $name ) {
738 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
739 || IP
::isIPv6( $name );
743 * Is the input a valid username?
745 * Checks if the input is a valid username, we don't want an empty string,
746 * an IP address, anything that contains slashes (would mess up subpages),
747 * is longer than the maximum allowed username size or doesn't begin with
750 * @param string $name Name to match
753 public static function isValidUserName( $name ) {
754 global $wgContLang, $wgMaxNameChars;
757 || User
::isIP( $name )
758 ||
strpos( $name, '/' ) !== false
759 ||
strlen( $name ) > $wgMaxNameChars
760 ||
$name != $wgContLang->ucfirst( $name )
762 wfDebugLog( 'username', __METHOD__
.
763 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
767 // Ensure that the name can't be misresolved as a different title,
768 // such as with extra namespace keys at the start.
769 $parsed = Title
::newFromText( $name );
770 if ( is_null( $parsed )
771 ||
$parsed->getNamespace()
772 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
773 wfDebugLog( 'username', __METHOD__
.
774 ": '$name' invalid due to ambiguous prefixes" );
778 // Check an additional blacklist of troublemaker characters.
779 // Should these be merged into the title char list?
780 $unicodeBlacklist = '/[' .
781 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
782 '\x{00a0}' . # non-breaking space
783 '\x{2000}-\x{200f}' . # various whitespace
784 '\x{2028}-\x{202f}' . # breaks and control chars
785 '\x{3000}' . # ideographic space
786 '\x{e000}-\x{f8ff}' . # private use
788 if ( preg_match( $unicodeBlacklist, $name ) ) {
789 wfDebugLog( 'username', __METHOD__
.
790 ": '$name' invalid due to blacklisted characters" );
798 * Usernames which fail to pass this function will be blocked
799 * from user login and new account registrations, but may be used
800 * internally by batch processes.
802 * If an account already exists in this form, login will be blocked
803 * by a failure to pass this function.
805 * @param string $name Name to match
808 public static function isUsableName( $name ) {
809 global $wgReservedUsernames;
810 // Must be a valid username, obviously ;)
811 if ( !self
::isValidUserName( $name ) ) {
815 static $reservedUsernames = false;
816 if ( !$reservedUsernames ) {
817 $reservedUsernames = $wgReservedUsernames;
818 Hooks
::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
821 // Certain names may be reserved for batch processes.
822 foreach ( $reservedUsernames as $reserved ) {
823 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
824 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
826 if ( $reserved == $name ) {
834 * Usernames which fail to pass this function will be blocked
835 * from new account registrations, but may be used internally
836 * either by batch processes or by user accounts which have
837 * already been created.
839 * Additional blacklisting may be added here rather than in
840 * isValidUserName() to avoid disrupting existing accounts.
842 * @param string $name String to match
845 public static function isCreatableName( $name ) {
846 global $wgInvalidUsernameCharacters;
848 // Ensure that the username isn't longer than 235 bytes, so that
849 // (at least for the builtin skins) user javascript and css files
850 // will work. (bug 23080)
851 if ( strlen( $name ) > 235 ) {
852 wfDebugLog( 'username', __METHOD__
.
853 ": '$name' invalid due to length" );
857 // Preg yells if you try to give it an empty string
858 if ( $wgInvalidUsernameCharacters !== '' ) {
859 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
860 wfDebugLog( 'username', __METHOD__
.
861 ": '$name' invalid due to wgInvalidUsernameCharacters" );
866 return self
::isUsableName( $name );
870 * Is the input a valid password for this user?
872 * @param string $password Desired password
875 public function isValidPassword( $password ) {
876 // simple boolean wrapper for getPasswordValidity
877 return $this->getPasswordValidity( $password ) === true;
882 * Given unvalidated password input, return error message on failure.
884 * @param string $password Desired password
885 * @return bool|string|array True on success, string or array of error message on failure
887 public function getPasswordValidity( $password ) {
888 $result = $this->checkPasswordValidity( $password );
889 if ( $result->isGood() ) {
893 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
894 $messages[] = $error['message'];
896 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
897 $messages[] = $warning['message'];
899 if ( count( $messages ) === 1 ) {
907 * Check if this is a valid password for this user
909 * Create a Status object based on the password's validity.
910 * The Status should be set to fatal if the user should not
911 * be allowed to log in, and should have any errors that
912 * would block changing the password.
914 * If the return value of this is not OK, the password
915 * should not be checked. If the return value is not Good,
916 * the password can be checked, but the user should not be
917 * able to set their password to this.
919 * @param string $password Desired password
920 * @param string $purpose one of 'login', 'create', 'reset'
924 public function checkPasswordValidity( $password, $purpose = 'login' ) {
925 global $wgPasswordPolicy;
927 $upp = new UserPasswordPolicy(
928 $wgPasswordPolicy['policies'],
929 $wgPasswordPolicy['checks']
932 $status = Status
::newGood();
933 $result = false; // init $result to false for the internal checks
935 if ( !Hooks
::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
936 $status->error( $result );
940 if ( $result === false ) {
941 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
943 } elseif ( $result === true ) {
946 $status->error( $result );
947 return $status; // the isValidPassword hook set a string $result and returned true
952 * Given unvalidated user input, return a canonical username, or false if
953 * the username is invalid.
954 * @param string $name User input
955 * @param string|bool $validate Type of validation to use:
956 * - false No validation
957 * - 'valid' Valid for batch processes
958 * - 'usable' Valid for batch processes and login
959 * - 'creatable' Valid for batch processes, login and account creation
961 * @throws InvalidArgumentException
962 * @return bool|string
964 public static function getCanonicalName( $name, $validate = 'valid' ) {
965 // Force usernames to capital
967 $name = $wgContLang->ucfirst( $name );
969 # Reject names containing '#'; these will be cleaned up
970 # with title normalisation, but then it's too late to
972 if ( strpos( $name, '#' ) !== false ) {
976 // Clean up name according to title rules,
977 // but only when validation is requested (bug 12654)
978 $t = ( $validate !== false ) ?
979 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
980 // Check for invalid titles
981 if ( is_null( $t ) ) {
985 // Reject various classes of invalid names
987 $name = $wgAuth->getCanonicalName( $t->getText() );
989 switch ( $validate ) {
993 if ( !User
::isValidUserName( $name ) ) {
998 if ( !User
::isUsableName( $name ) ) {
1003 if ( !User
::isCreatableName( $name ) ) {
1008 throw new InvalidArgumentException(
1009 'Invalid parameter value for $validate in ' . __METHOD__
);
1015 * Count the number of edits of a user
1017 * @param int $uid User ID to check
1018 * @return int The user's edit count
1020 * @deprecated since 1.21 in favour of User::getEditCount
1022 public static function edits( $uid ) {
1023 wfDeprecated( __METHOD__
, '1.21' );
1024 $user = self
::newFromId( $uid );
1025 return $user->getEditCount();
1029 * Return a random password.
1031 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1032 * @return string New random password
1034 public static function randomPassword() {
1035 global $wgMinimalPasswordLength;
1036 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1040 * Set cached properties to default.
1042 * @note This no longer clears uncached lazy-initialised properties;
1043 * the constructor does that instead.
1045 * @param string|bool $name
1047 public function loadDefaults( $name = false ) {
1049 $this->mName
= $name;
1050 $this->mRealName
= '';
1052 $this->mOptionOverrides
= null;
1053 $this->mOptionsLoaded
= false;
1055 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1056 if ( $loggedOut !== null ) {
1057 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1059 $this->mTouched
= '1'; # Allow any pages to be cached
1062 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1063 $this->mEmailAuthenticated
= null;
1064 $this->mEmailToken
= '';
1065 $this->mEmailTokenExpires
= null;
1066 $this->mRegistration
= wfTimestamp( TS_MW
);
1067 $this->mGroups
= array();
1069 Hooks
::run( 'UserLoadDefaults', array( $this, $name ) );
1073 * Return whether an item has been loaded.
1075 * @param string $item Item to check. Current possibilities:
1079 * @param string $all 'all' to check if the whole object has been loaded
1080 * or any other string to check if only the item is available (e.g.
1084 public function isItemLoaded( $item, $all = 'all' ) {
1085 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1086 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1090 * Set that an item has been loaded
1092 * @param string $item
1094 protected function setItemLoaded( $item ) {
1095 if ( is_array( $this->mLoadedItems
) ) {
1096 $this->mLoadedItems
[$item] = true;
1101 * Load user data from the session or login cookie.
1103 * @return bool True if the user is logged in, false otherwise.
1105 private function loadFromSession() {
1107 Hooks
::run( 'UserLoadFromSession', array( $this, &$result ) );
1108 if ( $result !== null ) {
1112 $request = $this->getRequest();
1114 $cookieId = $request->getCookie( 'UserID' );
1115 $sessId = $request->getSessionData( 'wsUserID' );
1117 if ( $cookieId !== null ) {
1118 $sId = intval( $cookieId );
1119 if ( $sessId !== null && $cookieId != $sessId ) {
1120 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1121 cookie user ID ($sId) don't match!" );
1124 $request->setSessionData( 'wsUserID', $sId );
1125 } elseif ( $sessId !== null && $sessId != 0 ) {
1131 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1132 $sName = $request->getSessionData( 'wsUserName' );
1133 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1134 $sName = $request->getCookie( 'UserName' );
1135 $request->setSessionData( 'wsUserName', $sName );
1140 $proposedUser = User
::newFromId( $sId );
1141 if ( !$proposedUser->isLoggedIn() ) {
1146 global $wgBlockDisablesLogin;
1147 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1148 // User blocked and we've disabled blocked user logins
1152 if ( $request->getSessionData( 'wsToken' ) ) {
1154 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1156 } elseif ( $request->getCookie( 'Token' ) ) {
1157 # Get the token from DB/cache and clean it up to remove garbage padding.
1158 # This deals with historical problems with bugs and the default column value.
1159 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1160 // Make comparison in constant time (bug 61346)
1161 $passwordCorrect = strlen( $token )
1162 && hash_equals( $token, $request->getCookie( 'Token' ) );
1165 // No session or persistent login cookie
1169 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1170 $this->loadFromUserObject( $proposedUser );
1171 $request->setSessionData( 'wsToken', $this->mToken
);
1172 wfDebug( "User: logged in from $from\n" );
1175 // Invalid credentials
1176 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1182 * Load user and user_group data from the database.
1183 * $this->mId must be set, this is how the user is identified.
1185 * @param integer $flags User::READ_* constant bitfield
1186 * @return bool True if the user exists, false if the user is anonymous
1188 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1190 $this->mId
= intval( $this->mId
);
1193 if ( !$this->mId
) {
1194 $this->loadDefaults();
1198 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1199 $db = wfGetDB( $index );
1201 $s = $db->selectRow(
1203 self
::selectFields(),
1204 array( 'user_id' => $this->mId
),
1209 $this->queryFlagsUsed
= $flags;
1210 Hooks
::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1212 if ( $s !== false ) {
1213 // Initialise user table data
1214 $this->loadFromRow( $s );
1215 $this->mGroups
= null; // deferred
1216 $this->getEditCount(); // revalidation for nulls
1221 $this->loadDefaults();
1227 * Initialize this object from a row from the user table.
1229 * @param stdClass $row Row from the user table to load.
1230 * @param array $data Further user data to load into the object
1232 * user_groups Array with groups out of the user_groups table
1233 * user_properties Array with properties out of the user_properties table
1235 protected function loadFromRow( $row, $data = null ) {
1238 $this->mGroups
= null; // deferred
1240 if ( isset( $row->user_name
) ) {
1241 $this->mName
= $row->user_name
;
1242 $this->mFrom
= 'name';
1243 $this->setItemLoaded( 'name' );
1248 if ( isset( $row->user_real_name
) ) {
1249 $this->mRealName
= $row->user_real_name
;
1250 $this->setItemLoaded( 'realname' );
1255 if ( isset( $row->user_id
) ) {
1256 $this->mId
= intval( $row->user_id
);
1257 $this->mFrom
= 'id';
1258 $this->setItemLoaded( 'id' );
1263 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1264 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1267 if ( isset( $row->user_editcount
) ) {
1268 $this->mEditCount
= $row->user_editcount
;
1273 if ( isset( $row->user_email
) ) {
1274 $this->mEmail
= $row->user_email
;
1275 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1276 $this->mToken
= $row->user_token
;
1277 if ( $this->mToken
== '' ) {
1278 $this->mToken
= null;
1280 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1281 $this->mEmailToken
= $row->user_email_token
;
1282 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1283 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1289 $this->mLoadedItems
= true;
1292 if ( is_array( $data ) ) {
1293 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1294 $this->mGroups
= $data['user_groups'];
1296 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1297 $this->loadOptions( $data['user_properties'] );
1303 * Load the data for this user object from another user object.
1307 protected function loadFromUserObject( $user ) {
1309 $user->loadGroups();
1310 $user->loadOptions();
1311 foreach ( self
::$mCacheVars as $var ) {
1312 $this->$var = $user->$var;
1317 * Load the groups from the database if they aren't already loaded.
1319 private function loadGroups() {
1320 if ( is_null( $this->mGroups
) ) {
1321 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1322 ?
wfGetDB( DB_MASTER
)
1323 : wfGetDB( DB_SLAVE
);
1324 $res = $db->select( 'user_groups',
1325 array( 'ug_group' ),
1326 array( 'ug_user' => $this->mId
),
1328 $this->mGroups
= array();
1329 foreach ( $res as $row ) {
1330 $this->mGroups
[] = $row->ug_group
;
1336 * Add the user to the group if he/she meets given criteria.
1338 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1339 * possible to remove manually via Special:UserRights. In such case it
1340 * will not be re-added automatically. The user will also not lose the
1341 * group if they no longer meet the criteria.
1343 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1345 * @return array Array of groups the user has been promoted to.
1347 * @see $wgAutopromoteOnce
1349 public function addAutopromoteOnceGroups( $event ) {
1350 global $wgAutopromoteOnceLogInRC, $wgAuth;
1352 if ( wfReadOnly() ||
!$this->getId() ) {
1356 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1357 if ( !count( $toPromote ) ) {
1361 if ( !$this->checkAndSetTouched() ) {
1362 return array(); // raced out (bug T48834)
1365 $oldGroups = $this->getGroups(); // previous groups
1366 foreach ( $toPromote as $group ) {
1367 $this->addGroup( $group );
1369 // update groups in external authentication database
1370 Hooks
::run( 'UserGroupsChanged', array( $this, $toPromote, array(), false ) );
1371 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1373 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1375 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1376 $logEntry->setPerformer( $this );
1377 $logEntry->setTarget( $this->getUserPage() );
1378 $logEntry->setParameters( array(
1379 '4::oldgroups' => $oldGroups,
1380 '5::newgroups' => $newGroups,
1382 $logid = $logEntry->insert();
1383 if ( $wgAutopromoteOnceLogInRC ) {
1384 $logEntry->publish( $logid );
1391 * Bump user_touched if it didn't change since this object was loaded
1393 * On success, the mTouched field is updated.
1394 * The user serialization cache is always cleared.
1396 * @return bool Whether user_touched was actually updated
1399 protected function checkAndSetTouched() {
1402 if ( !$this->mId
) {
1403 return false; // anon
1406 // Get a new user_touched that is higher than the old one
1407 $oldTouched = $this->mTouched
;
1408 $newTouched = $this->newTouchedTimestamp();
1410 $dbw = wfGetDB( DB_MASTER
);
1411 $dbw->update( 'user',
1412 array( 'user_touched' => $dbw->timestamp( $newTouched ) ),
1414 'user_id' => $this->mId
,
1415 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1419 $success = ( $dbw->affectedRows() > 0 );
1422 $this->mTouched
= $newTouched;
1423 $this->clearSharedCache();
1425 // Clears on failure too since that is desired if the cache is stale
1426 $this->clearSharedCache( 'refresh' );
1433 * Clear various cached data stored in this object. The cache of the user table
1434 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1436 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1437 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1439 public function clearInstanceCache( $reloadFrom = false ) {
1440 $this->mNewtalk
= -1;
1441 $this->mDatePreference
= null;
1442 $this->mBlockedby
= -1; # Unset
1443 $this->mHash
= false;
1444 $this->mRights
= null;
1445 $this->mEffectiveGroups
= null;
1446 $this->mImplicitGroups
= null;
1447 $this->mGroups
= null;
1448 $this->mOptions
= null;
1449 $this->mOptionsLoaded
= false;
1450 $this->mEditCount
= null;
1452 if ( $reloadFrom ) {
1453 $this->mLoadedItems
= array();
1454 $this->mFrom
= $reloadFrom;
1459 * Combine the language default options with any site-specific options
1460 * and add the default language variants.
1462 * @return array Array of String options
1464 public static function getDefaultOptions() {
1465 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1467 static $defOpt = null;
1468 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1469 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1470 // mid-request and see that change reflected in the return value of this function.
1471 // Which is insane and would never happen during normal MW operation
1475 $defOpt = $wgDefaultUserOptions;
1476 // Default language setting
1477 $defOpt['language'] = $wgContLang->getCode();
1478 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1479 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1481 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1482 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1484 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1486 Hooks
::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1492 * Get a given default option value.
1494 * @param string $opt Name of option to retrieve
1495 * @return string Default option value
1497 public static function getDefaultOption( $opt ) {
1498 $defOpts = self
::getDefaultOptions();
1499 if ( isset( $defOpts[$opt] ) ) {
1500 return $defOpts[$opt];
1507 * Get blocking information
1508 * @param bool $bFromSlave Whether to check the slave database first.
1509 * To improve performance, non-critical checks are done against slaves.
1510 * Check when actually saving should be done against master.
1512 private function getBlockedStatus( $bFromSlave = true ) {
1513 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1515 if ( -1 != $this->mBlockedby
) {
1519 wfDebug( __METHOD__
. ": checking...\n" );
1521 // Initialize data...
1522 // Otherwise something ends up stomping on $this->mBlockedby when
1523 // things get lazy-loaded later, causing false positive block hits
1524 // due to -1 !== 0. Probably session-related... Nothing should be
1525 // overwriting mBlockedby, surely?
1528 # We only need to worry about passing the IP address to the Block generator if the
1529 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1530 # know which IP address they're actually coming from
1531 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->equals( $wgUser ) ) {
1532 $ip = $this->getRequest()->getIP();
1538 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1541 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1542 && !in_array( $ip, $wgProxyWhitelist )
1545 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1547 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1548 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1549 $block->setTarget( $ip );
1550 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1552 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1553 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1554 $block->setTarget( $ip );
1558 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1559 if ( !$block instanceof Block
1560 && $wgApplyIpBlocksToXff
1562 && !$this->isAllowed( 'proxyunbannable' )
1563 && !in_array( $ip, $wgProxyWhitelist )
1565 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1566 $xff = array_map( 'trim', explode( ',', $xff ) );
1567 $xff = array_diff( $xff, array( $ip ) );
1568 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1569 $block = Block
::chooseBlock( $xffblocks, $xff );
1570 if ( $block instanceof Block
) {
1571 # Mangle the reason to alert the user that the block
1572 # originated from matching the X-Forwarded-For header.
1573 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1577 if ( $block instanceof Block
) {
1578 wfDebug( __METHOD__
. ": Found block.\n" );
1579 $this->mBlock
= $block;
1580 $this->mBlockedby
= $block->getByName();
1581 $this->mBlockreason
= $block->mReason
;
1582 $this->mHideName
= $block->mHideName
;
1583 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1585 $this->mBlockedby
= '';
1586 $this->mHideName
= 0;
1587 $this->mAllowUsertalk
= false;
1591 Hooks
::run( 'GetBlockedStatus', array( &$this ) );
1596 * Whether the given IP is in a DNS blacklist.
1598 * @param string $ip IP to check
1599 * @param bool $checkWhitelist Whether to check the whitelist first
1600 * @return bool True if blacklisted.
1602 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1603 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1605 if ( !$wgEnableDnsBlacklist ) {
1609 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1613 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1617 * Whether the given IP is in a given DNS blacklist.
1619 * @param string $ip IP to check
1620 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1621 * @return bool True if blacklisted.
1623 public function inDnsBlacklist( $ip, $bases ) {
1626 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1627 if ( IP
::isIPv4( $ip ) ) {
1628 // Reverse IP, bug 21255
1629 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1631 foreach ( (array)$bases as $base ) {
1633 // If we have an access key, use that too (ProjectHoneypot, etc.)
1635 if ( is_array( $base ) ) {
1636 if ( count( $base ) >= 2 ) {
1637 // Access key is 1, base URL is 0
1638 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1640 $host = "$ipReversed.{$base[0]}";
1642 $basename = $base[0];
1644 $host = "$ipReversed.$base";
1648 $ipList = gethostbynamel( $host );
1651 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1655 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1664 * Check if an IP address is in the local proxy list
1670 public static function isLocallyBlockedProxy( $ip ) {
1671 global $wgProxyList;
1673 if ( !$wgProxyList ) {
1677 if ( !is_array( $wgProxyList ) ) {
1678 // Load from the specified file
1679 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1682 if ( !is_array( $wgProxyList ) ) {
1684 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1686 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1687 // Old-style flipped proxy list
1696 * Is this user subject to rate limiting?
1698 * @return bool True if rate limited
1700 public function isPingLimitable() {
1701 global $wgRateLimitsExcludedIPs;
1702 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1703 // No other good way currently to disable rate limits
1704 // for specific IPs. :P
1705 // But this is a crappy hack and should die.
1708 return !$this->isAllowed( 'noratelimit' );
1712 * Primitive rate limits: enforce maximum actions per time period
1713 * to put a brake on flooding.
1715 * The method generates both a generic profiling point and a per action one
1716 * (suffix being "-$action".
1718 * @note When using a shared cache like memcached, IP-address
1719 * last-hit counters will be shared across wikis.
1721 * @param string $action Action to enforce; 'edit' if unspecified
1722 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1723 * @return bool True if a rate limiter was tripped
1725 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1726 // Call the 'PingLimiter' hook
1728 if ( !Hooks
::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1732 global $wgRateLimits;
1733 if ( !isset( $wgRateLimits[$action] ) ) {
1737 // Some groups shouldn't trigger the ping limiter, ever
1738 if ( !$this->isPingLimitable() ) {
1742 $limits = $wgRateLimits[$action];
1744 $id = $this->getId();
1747 if ( isset( $limits['anon'] ) && $id == 0 ) {
1748 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1751 if ( isset( $limits['user'] ) && $id != 0 ) {
1752 $userLimit = $limits['user'];
1754 if ( $this->isNewbie() ) {
1755 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1756 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1758 if ( isset( $limits['ip'] ) ) {
1759 $ip = $this->getRequest()->getIP();
1760 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1762 if ( isset( $limits['subnet'] ) ) {
1763 $ip = $this->getRequest()->getIP();
1766 if ( IP
::isIPv6( $ip ) ) {
1767 $parts = IP
::parseRange( "$ip/64" );
1768 $subnet = $parts[0];
1769 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1771 $subnet = $matches[1];
1773 if ( $subnet !== false ) {
1774 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1778 // Check for group-specific permissions
1779 // If more than one group applies, use the group with the highest limit
1780 foreach ( $this->getGroups() as $group ) {
1781 if ( isset( $limits[$group] ) ) {
1782 if ( $userLimit === false
1783 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1785 $userLimit = $limits[$group];
1789 // Set the user limit key
1790 if ( $userLimit !== false ) {
1791 list( $max, $period ) = $userLimit;
1792 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1793 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1796 $cache = ObjectCache
::getLocalClusterInstance();
1799 foreach ( $keys as $key => $limit ) {
1800 list( $max, $period ) = $limit;
1801 $summary = "(limit $max in {$period}s)";
1802 $count = $cache->get( $key );
1805 if ( $count >= $max ) {
1806 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1807 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1810 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1813 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1814 if ( $incrBy > 0 ) {
1815 $cache->add( $key, 0, intval( $period ) ); // first ping
1818 if ( $incrBy > 0 ) {
1819 $cache->incr( $key, $incrBy );
1827 * Check if user is blocked
1829 * @param bool $bFromSlave Whether to check the slave database instead of
1830 * the master. Hacked from false due to horrible probs on site.
1831 * @return bool True if blocked, false otherwise
1833 public function isBlocked( $bFromSlave = true ) {
1834 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1838 * Get the block affecting the user, or null if the user is not blocked
1840 * @param bool $bFromSlave Whether to check the slave database instead of the master
1841 * @return Block|null
1843 public function getBlock( $bFromSlave = true ) {
1844 $this->getBlockedStatus( $bFromSlave );
1845 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1849 * Check if user is blocked from editing a particular article
1851 * @param Title $title Title to check
1852 * @param bool $bFromSlave Whether to check the slave database instead of the master
1855 public function isBlockedFrom( $title, $bFromSlave = false ) {
1856 global $wgBlockAllowsUTEdit;
1858 $blocked = $this->isBlocked( $bFromSlave );
1859 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1860 // If a user's name is suppressed, they cannot make edits anywhere
1861 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1862 && $title->getNamespace() == NS_USER_TALK
) {
1864 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1867 Hooks
::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1873 * If user is blocked, return the name of the user who placed the block
1874 * @return string Name of blocker
1876 public function blockedBy() {
1877 $this->getBlockedStatus();
1878 return $this->mBlockedby
;
1882 * If user is blocked, return the specified reason for the block
1883 * @return string Blocking reason
1885 public function blockedFor() {
1886 $this->getBlockedStatus();
1887 return $this->mBlockreason
;
1891 * If user is blocked, return the ID for the block
1892 * @return int Block ID
1894 public function getBlockId() {
1895 $this->getBlockedStatus();
1896 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1900 * Check if user is blocked on all wikis.
1901 * Do not use for actual edit permission checks!
1902 * This is intended for quick UI checks.
1904 * @param string $ip IP address, uses current client if none given
1905 * @return bool True if blocked, false otherwise
1907 public function isBlockedGlobally( $ip = '' ) {
1908 if ( $this->mBlockedGlobally
!== null ) {
1909 return $this->mBlockedGlobally
;
1911 // User is already an IP?
1912 if ( IP
::isIPAddress( $this->getName() ) ) {
1913 $ip = $this->getName();
1915 $ip = $this->getRequest()->getIP();
1918 Hooks
::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1919 $this->mBlockedGlobally
= (bool)$blocked;
1920 return $this->mBlockedGlobally
;
1924 * Check if user account is locked
1926 * @return bool True if locked, false otherwise
1928 public function isLocked() {
1929 if ( $this->mLocked
!== null ) {
1930 return $this->mLocked
;
1933 $authUser = $wgAuth->getUserInstance( $this );
1934 $this->mLocked
= (bool)$authUser->isLocked();
1935 Hooks
::run( 'UserIsLocked', array( $this, &$this->mLocked
) );
1936 return $this->mLocked
;
1940 * Check if user account is hidden
1942 * @return bool True if hidden, false otherwise
1944 public function isHidden() {
1945 if ( $this->mHideName
!== null ) {
1946 return $this->mHideName
;
1948 $this->getBlockedStatus();
1949 if ( !$this->mHideName
) {
1951 $authUser = $wgAuth->getUserInstance( $this );
1952 $this->mHideName
= (bool)$authUser->isHidden();
1953 Hooks
::run( 'UserIsHidden', array( $this, &$this->mHideName
) );
1955 return $this->mHideName
;
1959 * Get the user's ID.
1960 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1962 public function getId() {
1963 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1964 // Special case, we know the user is anonymous
1966 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1967 // Don't load if this was initialized from an ID
1974 * Set the user and reload all fields according to a given ID
1975 * @param int $v User ID to reload
1977 public function setId( $v ) {
1979 $this->clearInstanceCache( 'id' );
1983 * Get the user name, or the IP of an anonymous user
1984 * @return string User's name or IP address
1986 public function getName() {
1987 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1988 // Special case optimisation
1989 return $this->mName
;
1992 if ( $this->mName
=== false ) {
1994 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1996 return $this->mName
;
2001 * Set the user name.
2003 * This does not reload fields from the database according to the given
2004 * name. Rather, it is used to create a temporary "nonexistent user" for
2005 * later addition to the database. It can also be used to set the IP
2006 * address for an anonymous user to something other than the current
2009 * @note User::newFromName() has roughly the same function, when the named user
2011 * @param string $str New user name to set
2013 public function setName( $str ) {
2015 $this->mName
= $str;
2019 * Get the user's name escaped by underscores.
2020 * @return string Username escaped by underscores.
2022 public function getTitleKey() {
2023 return str_replace( ' ', '_', $this->getName() );
2027 * Check if the user has new messages.
2028 * @return bool True if the user has new messages
2030 public function getNewtalk() {
2033 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2034 if ( $this->mNewtalk
=== -1 ) {
2035 $this->mNewtalk
= false; # reset talk page status
2037 // Check memcached separately for anons, who have no
2038 // entire User object stored in there.
2039 if ( !$this->mId
) {
2040 global $wgDisableAnonTalk;
2041 if ( $wgDisableAnonTalk ) {
2042 // Anon newtalk disabled by configuration.
2043 $this->mNewtalk
= false;
2045 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2048 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2052 return (bool)$this->mNewtalk
;
2056 * Return the data needed to construct links for new talk page message
2057 * alerts. If there are new messages, this will return an associative array
2058 * with the following data:
2059 * wiki: The database name of the wiki
2060 * link: Root-relative link to the user's talk page
2061 * rev: The last talk page revision that the user has seen or null. This
2062 * is useful for building diff links.
2063 * If there are no new messages, it returns an empty array.
2064 * @note This function was designed to accomodate multiple talk pages, but
2065 * currently only returns a single link and revision.
2068 public function getNewMessageLinks() {
2070 if ( !Hooks
::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2072 } elseif ( !$this->getNewtalk() ) {
2075 $utp = $this->getTalkPage();
2076 $dbr = wfGetDB( DB_SLAVE
);
2077 // Get the "last viewed rev" timestamp from the oldest message notification
2078 $timestamp = $dbr->selectField( 'user_newtalk',
2079 'MIN(user_last_timestamp)',
2080 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2082 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2083 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2087 * Get the revision ID for the last talk page revision viewed by the talk
2089 * @return int|null Revision ID or null
2091 public function getNewMessageRevisionId() {
2092 $newMessageRevisionId = null;
2093 $newMessageLinks = $this->getNewMessageLinks();
2094 if ( $newMessageLinks ) {
2095 // Note: getNewMessageLinks() never returns more than a single link
2096 // and it is always for the same wiki, but we double-check here in
2097 // case that changes some time in the future.
2098 if ( count( $newMessageLinks ) === 1
2099 && $newMessageLinks[0]['wiki'] === wfWikiID()
2100 && $newMessageLinks[0]['rev']
2102 /** @var Revision $newMessageRevision */
2103 $newMessageRevision = $newMessageLinks[0]['rev'];
2104 $newMessageRevisionId = $newMessageRevision->getId();
2107 return $newMessageRevisionId;
2111 * Internal uncached check for new messages
2114 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2115 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2116 * @return bool True if the user has new messages
2118 protected function checkNewtalk( $field, $id ) {
2119 $dbr = wfGetDB( DB_SLAVE
);
2121 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__
);
2123 return $ok !== false;
2127 * Add or update the new messages flag
2128 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2129 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2130 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2131 * @return bool True if successful, false otherwise
2133 protected function updateNewtalk( $field, $id, $curRev = null ) {
2134 // Get timestamp of the talk page revision prior to the current one
2135 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2136 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2137 // Mark the user as having new messages since this revision
2138 $dbw = wfGetDB( DB_MASTER
);
2139 $dbw->insert( 'user_newtalk',
2140 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2143 if ( $dbw->affectedRows() ) {
2144 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2147 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2153 * Clear the new messages flag for the given user
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 * @return bool True if successful, false otherwise
2158 protected function deleteNewtalk( $field, $id ) {
2159 $dbw = wfGetDB( DB_MASTER
);
2160 $dbw->delete( 'user_newtalk',
2161 array( $field => $id ),
2163 if ( $dbw->affectedRows() ) {
2164 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2167 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2173 * Update the 'You have new messages!' status.
2174 * @param bool $val Whether the user has new messages
2175 * @param Revision $curRev New, as yet unseen revision of the user talk
2176 * page. Ignored if null or !$val.
2178 public function setNewtalk( $val, $curRev = null ) {
2179 if ( wfReadOnly() ) {
2184 $this->mNewtalk
= $val;
2186 if ( $this->isAnon() ) {
2188 $id = $this->getName();
2191 $id = $this->getId();
2195 $changed = $this->updateNewtalk( $field, $id, $curRev );
2197 $changed = $this->deleteNewtalk( $field, $id );
2201 $this->invalidateCache();
2206 * Generate a current or new-future timestamp to be stored in the
2207 * user_touched field when we update things.
2208 * @return string Timestamp in TS_MW format
2210 private function newTouchedTimestamp() {
2211 global $wgClockSkewFudge;
2213 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2214 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2215 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2222 * Clear user data from memcached
2224 * Use after applying updates to the database; caller's
2225 * responsibility to update user_touched if appropriate.
2227 * Called implicitly from invalidateCache() and saveSettings().
2229 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2231 public function clearSharedCache( $mode = 'changed' ) {
2232 $id = $this->getId();
2237 $key = wfMemcKey( 'user', 'id', $id );
2238 if ( $mode === 'refresh' ) {
2239 ObjectCache
::getMainWANInstance()->delete( $key, 1 );
2241 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $key ) {
2242 ObjectCache
::getMainWANInstance()->delete( $key );
2248 * Immediately touch the user data cache for this account
2250 * Calls touch() and removes account data from memcached
2252 public function invalidateCache() {
2254 $this->clearSharedCache();
2258 * Update the "touched" timestamp for the user
2260 * This is useful on various login/logout events when making sure that
2261 * a browser or proxy that has multiple tenants does not suffer cache
2262 * pollution where the new user sees the old users content. The value
2263 * of getTouched() is checked when determining 304 vs 200 responses.
2264 * Unlike invalidateCache(), this preserves the User object cache and
2265 * avoids database writes.
2269 public function touch() {
2270 $id = $this->getId();
2272 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2273 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2274 $this->mQuickTouched
= null;
2279 * Validate the cache for this account.
2280 * @param string $timestamp A timestamp in TS_MW format
2283 public function validateCache( $timestamp ) {
2284 return ( $timestamp >= $this->getTouched() );
2288 * Get the user touched timestamp
2290 * Use this value only to validate caches via inequalities
2291 * such as in the case of HTTP If-Modified-Since response logic
2293 * @return string TS_MW Timestamp
2295 public function getTouched() {
2299 if ( $this->mQuickTouched
=== null ) {
2300 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2301 $cache = ObjectCache
::getMainWANInstance();
2303 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2306 return max( $this->mTouched
, $this->mQuickTouched
);
2309 return $this->mTouched
;
2313 * Get the user_touched timestamp field (time of last DB updates)
2314 * @return string TS_MW Timestamp
2317 public function getDBTouched() {
2320 return $this->mTouched
;
2324 * @deprecated Removed in 1.27.
2328 public function getPassword() {
2329 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2333 * @deprecated Removed in 1.27.
2337 public function getTemporaryPassword() {
2338 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2342 * Set the password and reset the random token.
2343 * Calls through to authentication plugin if necessary;
2344 * will have no effect if the auth plugin refuses to
2345 * pass the change through or if the legal password
2348 * As a special case, setting the password to null
2349 * wipes it, so the account cannot be logged in until
2350 * a new password is set, for instance via e-mail.
2352 * @deprecated since 1.27. AuthManager is coming.
2353 * @param string $str New password to set
2354 * @throws PasswordError On failure
2357 public function setPassword( $str ) {
2360 if ( $str !== null ) {
2361 if ( !$wgAuth->allowPasswordChange() ) {
2362 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2365 $status = $this->checkPasswordValidity( $str );
2366 if ( !$status->isGood() ) {
2367 throw new PasswordError( $status->getMessage()->text() );
2371 if ( !$wgAuth->setPassword( $this, $str ) ) {
2372 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2376 $this->setOption( 'watchlisttoken', false );
2377 $this->setPasswordInternal( $str );
2383 * Set the password and reset the random token unconditionally.
2385 * @deprecated since 1.27. AuthManager is coming.
2386 * @param string|null $str New password to set or null to set an invalid
2387 * password hash meaning that the user will not be able to log in
2388 * through the web interface.
2390 public function setInternalPassword( $str ) {
2393 if ( $wgAuth->allowSetLocalPassword() ) {
2395 $this->setOption( 'watchlisttoken', false );
2396 $this->setPasswordInternal( $str );
2401 * Actually set the password and such
2402 * @param string|null $str New password to set or null to set an invalid
2403 * password hash meaning that the user will not be able to log in
2404 * through the web interface.
2406 private function setPasswordInternal( $str ) {
2407 $id = self
::idFromName( $this->getName() );
2409 $passwordFactory = new PasswordFactory();
2410 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2411 $dbw = wfGetDB( DB_MASTER
);
2415 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2416 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2417 'user_newpass_time' => $dbw->timestampOrNull( null ),
2424 $this->mPassword
= null;
2426 $this->mPassword
= $str;
2431 * Get the user's current token.
2432 * @param bool $forceCreation Force the generation of a new token if the
2433 * user doesn't have one (default=true for backwards compatibility).
2434 * @return string Token
2436 public function getToken( $forceCreation = true ) {
2438 if ( !$this->mToken
&& $forceCreation ) {
2441 return $this->mToken
;
2445 * Set the random token (used for persistent authentication)
2446 * Called from loadDefaults() among other places.
2448 * @param string|bool $token If specified, set the token to this value
2450 public function setToken( $token = false ) {
2453 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2455 $this->mToken
= $token;
2460 * Set the password for a password reminder or new account email
2462 * @deprecated since 1.27, AuthManager is coming
2463 * @param string $str New password to set or null to set an invalid
2464 * password hash meaning that the user will not be able to use it
2465 * @param bool $throttle If true, reset the throttle timestamp to the present
2467 public function setNewpassword( $str, $throttle = true ) {
2468 $id = $this->getId();
2470 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2473 $dbw = wfGetDB( DB_MASTER
);
2475 $passwordFactory = new PasswordFactory();
2476 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2478 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2481 if ( $str === null ) {
2482 $update['user_newpass_time'] = null;
2483 } elseif ( $throttle ) {
2484 $update['user_newpass_time'] = $dbw->timestamp();
2487 $dbw->update( 'user', $update, array( 'user_id' => $id ), __METHOD__
);
2491 * Has password reminder email been sent within the last
2492 * $wgPasswordReminderResendTime hours?
2495 public function isPasswordReminderThrottled() {
2496 global $wgPasswordReminderResendTime;
2498 if ( !$wgPasswordReminderResendTime ) {
2504 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2505 ?
wfGetDB( DB_MASTER
)
2506 : wfGetDB( DB_SLAVE
);
2507 $newpassTime = $db->selectField(
2509 'user_newpass_time',
2510 array( 'user_id' => $this->getId() ),
2514 if ( $newpassTime === null ) {
2517 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2518 return time() < $expiry;
2522 * Get the user's e-mail address
2523 * @return string User's email address
2525 public function getEmail() {
2527 Hooks
::run( 'UserGetEmail', array( $this, &$this->mEmail
) );
2528 return $this->mEmail
;
2532 * Get the timestamp of the user's e-mail authentication
2533 * @return string TS_MW timestamp
2535 public function getEmailAuthenticationTimestamp() {
2537 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2538 return $this->mEmailAuthenticated
;
2542 * Set the user's e-mail address
2543 * @param string $str New e-mail address
2545 public function setEmail( $str ) {
2547 if ( $str == $this->mEmail
) {
2550 $this->invalidateEmail();
2551 $this->mEmail
= $str;
2552 Hooks
::run( 'UserSetEmail', array( $this, &$this->mEmail
) );
2556 * Set the user's e-mail address and a confirmation mail if needed.
2559 * @param string $str New e-mail address
2562 public function setEmailWithConfirmation( $str ) {
2563 global $wgEnableEmail, $wgEmailAuthentication;
2565 if ( !$wgEnableEmail ) {
2566 return Status
::newFatal( 'emaildisabled' );
2569 $oldaddr = $this->getEmail();
2570 if ( $str === $oldaddr ) {
2571 return Status
::newGood( true );
2574 $this->setEmail( $str );
2576 if ( $str !== '' && $wgEmailAuthentication ) {
2577 // Send a confirmation request to the new address if needed
2578 $type = $oldaddr != '' ?
'changed' : 'set';
2579 $result = $this->sendConfirmationMail( $type );
2580 if ( $result->isGood() ) {
2581 // Say to the caller that a confirmation mail has been sent
2582 $result->value
= 'eauth';
2585 $result = Status
::newGood( true );
2592 * Get the user's real name
2593 * @return string User's real name
2595 public function getRealName() {
2596 if ( !$this->isItemLoaded( 'realname' ) ) {
2600 return $this->mRealName
;
2604 * Set the user's real name
2605 * @param string $str New real name
2607 public function setRealName( $str ) {
2609 $this->mRealName
= $str;
2613 * Get the user's current setting for a given option.
2615 * @param string $oname The option to check
2616 * @param string $defaultOverride A default value returned if the option does not exist
2617 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2618 * @return string User's current value for the option
2619 * @see getBoolOption()
2620 * @see getIntOption()
2622 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2623 global $wgHiddenPrefs;
2624 $this->loadOptions();
2626 # We want 'disabled' preferences to always behave as the default value for
2627 # users, even if they have set the option explicitly in their settings (ie they
2628 # set it, and then it was disabled removing their ability to change it). But
2629 # we don't want to erase the preferences in the database in case the preference
2630 # is re-enabled again. So don't touch $mOptions, just override the returned value
2631 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2632 return self
::getDefaultOption( $oname );
2635 if ( array_key_exists( $oname, $this->mOptions
) ) {
2636 return $this->mOptions
[$oname];
2638 return $defaultOverride;
2643 * Get all user's options
2645 * @param int $flags Bitwise combination of:
2646 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2647 * to the default value. (Since 1.25)
2650 public function getOptions( $flags = 0 ) {
2651 global $wgHiddenPrefs;
2652 $this->loadOptions();
2653 $options = $this->mOptions
;
2655 # We want 'disabled' preferences to always behave as the default value for
2656 # users, even if they have set the option explicitly in their settings (ie they
2657 # set it, and then it was disabled removing their ability to change it). But
2658 # we don't want to erase the preferences in the database in case the preference
2659 # is re-enabled again. So don't touch $mOptions, just override the returned value
2660 foreach ( $wgHiddenPrefs as $pref ) {
2661 $default = self
::getDefaultOption( $pref );
2662 if ( $default !== null ) {
2663 $options[$pref] = $default;
2667 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2668 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2675 * Get the user's current setting for a given option, as a boolean value.
2677 * @param string $oname The option to check
2678 * @return bool User's current value for the option
2681 public function getBoolOption( $oname ) {
2682 return (bool)$this->getOption( $oname );
2686 * Get the user's current setting for a given option, as an integer value.
2688 * @param string $oname The option to check
2689 * @param int $defaultOverride A default value returned if the option does not exist
2690 * @return int User's current value for the option
2693 public function getIntOption( $oname, $defaultOverride = 0 ) {
2694 $val = $this->getOption( $oname );
2696 $val = $defaultOverride;
2698 return intval( $val );
2702 * Set the given option for a user.
2704 * You need to call saveSettings() to actually write to the database.
2706 * @param string $oname The option to set
2707 * @param mixed $val New value to set
2709 public function setOption( $oname, $val ) {
2710 $this->loadOptions();
2712 // Explicitly NULL values should refer to defaults
2713 if ( is_null( $val ) ) {
2714 $val = self
::getDefaultOption( $oname );
2717 $this->mOptions
[$oname] = $val;
2721 * Get a token stored in the preferences (like the watchlist one),
2722 * resetting it if it's empty (and saving changes).
2724 * @param string $oname The option name to retrieve the token from
2725 * @return string|bool User's current value for the option, or false if this option is disabled.
2726 * @see resetTokenFromOption()
2728 * @deprecated 1.26 Applications should use the OAuth extension
2730 public function getTokenFromOption( $oname ) {
2731 global $wgHiddenPrefs;
2733 $id = $this->getId();
2734 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2738 $token = $this->getOption( $oname );
2740 // Default to a value based on the user token to avoid space
2741 // wasted on storing tokens for all users. When this option
2742 // is set manually by the user, only then is it stored.
2743 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2750 * Reset a token stored in the preferences (like the watchlist one).
2751 * *Does not* save user's preferences (similarly to setOption()).
2753 * @param string $oname The option name to reset the token in
2754 * @return string|bool New token value, or false if this option is disabled.
2755 * @see getTokenFromOption()
2758 public function resetTokenFromOption( $oname ) {
2759 global $wgHiddenPrefs;
2760 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2764 $token = MWCryptRand
::generateHex( 40 );
2765 $this->setOption( $oname, $token );
2770 * Return a list of the types of user options currently returned by
2771 * User::getOptionKinds().
2773 * Currently, the option kinds are:
2774 * - 'registered' - preferences which are registered in core MediaWiki or
2775 * by extensions using the UserGetDefaultOptions hook.
2776 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2777 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2778 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2779 * be used by user scripts.
2780 * - 'special' - "preferences" that are not accessible via User::getOptions
2781 * or User::setOptions.
2782 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2783 * These are usually legacy options, removed in newer versions.
2785 * The API (and possibly others) use this function to determine the possible
2786 * option types for validation purposes, so make sure to update this when a
2787 * new option kind is added.
2789 * @see User::getOptionKinds
2790 * @return array Option kinds
2792 public static function listOptionKinds() {
2795 'registered-multiselect',
2796 'registered-checkmatrix',
2804 * Return an associative array mapping preferences keys to the kind of a preference they're
2805 * used for. Different kinds are handled differently when setting or reading preferences.
2807 * See User::listOptionKinds for the list of valid option types that can be provided.
2809 * @see User::listOptionKinds
2810 * @param IContextSource $context
2811 * @param array $options Assoc. array with options keys to check as keys.
2812 * Defaults to $this->mOptions.
2813 * @return array The key => kind mapping data
2815 public function getOptionKinds( IContextSource
$context, $options = null ) {
2816 $this->loadOptions();
2817 if ( $options === null ) {
2818 $options = $this->mOptions
;
2821 $prefs = Preferences
::getPreferences( $this, $context );
2824 // Pull out the "special" options, so they don't get converted as
2825 // multiselect or checkmatrix.
2826 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2827 foreach ( $specialOptions as $name => $value ) {
2828 unset( $prefs[$name] );
2831 // Multiselect and checkmatrix options are stored in the database with
2832 // one key per option, each having a boolean value. Extract those keys.
2833 $multiselectOptions = array();
2834 foreach ( $prefs as $name => $info ) {
2835 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2836 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2837 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2838 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2840 foreach ( $opts as $value ) {
2841 $multiselectOptions["$prefix$value"] = true;
2844 unset( $prefs[$name] );
2847 $checkmatrixOptions = array();
2848 foreach ( $prefs as $name => $info ) {
2849 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2850 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2851 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2852 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2853 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2855 foreach ( $columns as $column ) {
2856 foreach ( $rows as $row ) {
2857 $checkmatrixOptions["$prefix$column-$row"] = true;
2861 unset( $prefs[$name] );
2865 // $value is ignored
2866 foreach ( $options as $key => $value ) {
2867 if ( isset( $prefs[$key] ) ) {
2868 $mapping[$key] = 'registered';
2869 } elseif ( isset( $multiselectOptions[$key] ) ) {
2870 $mapping[$key] = 'registered-multiselect';
2871 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2872 $mapping[$key] = 'registered-checkmatrix';
2873 } elseif ( isset( $specialOptions[$key] ) ) {
2874 $mapping[$key] = 'special';
2875 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2876 $mapping[$key] = 'userjs';
2878 $mapping[$key] = 'unused';
2886 * Reset certain (or all) options to the site defaults
2888 * The optional parameter determines which kinds of preferences will be reset.
2889 * Supported values are everything that can be reported by getOptionKinds()
2890 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2892 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2893 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2894 * for backwards-compatibility.
2895 * @param IContextSource|null $context Context source used when $resetKinds
2896 * does not contain 'all', passed to getOptionKinds().
2897 * Defaults to RequestContext::getMain() when null.
2899 public function resetOptions(
2900 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2901 IContextSource
$context = null
2904 $defaultOptions = self
::getDefaultOptions();
2906 if ( !is_array( $resetKinds ) ) {
2907 $resetKinds = array( $resetKinds );
2910 if ( in_array( 'all', $resetKinds ) ) {
2911 $newOptions = $defaultOptions;
2913 if ( $context === null ) {
2914 $context = RequestContext
::getMain();
2917 $optionKinds = $this->getOptionKinds( $context );
2918 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2919 $newOptions = array();
2921 // Use default values for the options that should be deleted, and
2922 // copy old values for the ones that shouldn't.
2923 foreach ( $this->mOptions
as $key => $value ) {
2924 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2925 if ( array_key_exists( $key, $defaultOptions ) ) {
2926 $newOptions[$key] = $defaultOptions[$key];
2929 $newOptions[$key] = $value;
2934 Hooks
::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2936 $this->mOptions
= $newOptions;
2937 $this->mOptionsLoaded
= true;
2941 * Get the user's preferred date format.
2942 * @return string User's preferred date format
2944 public function getDatePreference() {
2945 // Important migration for old data rows
2946 if ( is_null( $this->mDatePreference
) ) {
2948 $value = $this->getOption( 'date' );
2949 $map = $wgLang->getDatePreferenceMigrationMap();
2950 if ( isset( $map[$value] ) ) {
2951 $value = $map[$value];
2953 $this->mDatePreference
= $value;
2955 return $this->mDatePreference
;
2959 * Determine based on the wiki configuration and the user's options,
2960 * whether this user must be over HTTPS no matter what.
2964 public function requiresHTTPS() {
2965 global $wgSecureLogin;
2966 if ( !$wgSecureLogin ) {
2969 $https = $this->getBoolOption( 'prefershttps' );
2970 Hooks
::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2972 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2979 * Get the user preferred stub threshold
2983 public function getStubThreshold() {
2984 global $wgMaxArticleSize; # Maximum article size, in Kb
2985 $threshold = $this->getIntOption( 'stubthreshold' );
2986 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2987 // If they have set an impossible value, disable the preference
2988 // so we can use the parser cache again.
2995 * Get the permissions this user has.
2996 * @return array Array of String permission names
2998 public function getRights() {
2999 if ( is_null( $this->mRights
) ) {
3000 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3001 Hooks
::run( 'UserGetRights', array( $this, &$this->mRights
) );
3002 // Force reindexation of rights when a hook has unset one of them
3003 $this->mRights
= array_values( array_unique( $this->mRights
) );
3005 return $this->mRights
;
3009 * Get the list of explicit group memberships this user has.
3010 * The implicit * and user groups are not included.
3011 * @return array Array of String internal group names
3013 public function getGroups() {
3015 $this->loadGroups();
3016 return $this->mGroups
;
3020 * Get the list of implicit group memberships this user has.
3021 * This includes all explicit groups, plus 'user' if logged in,
3022 * '*' for all accounts, and autopromoted groups
3023 * @param bool $recache Whether to avoid the cache
3024 * @return array Array of String internal group names
3026 public function getEffectiveGroups( $recache = false ) {
3027 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3028 $this->mEffectiveGroups
= array_unique( array_merge(
3029 $this->getGroups(), // explicit groups
3030 $this->getAutomaticGroups( $recache ) // implicit groups
3032 // Hook for additional groups
3033 Hooks
::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
3034 // Force reindexation of groups when a hook has unset one of them
3035 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3037 return $this->mEffectiveGroups
;
3041 * Get the list of implicit group memberships this user has.
3042 * This includes 'user' if logged in, '*' for all accounts,
3043 * and autopromoted groups
3044 * @param bool $recache Whether to avoid the cache
3045 * @return array Array of String internal group names
3047 public function getAutomaticGroups( $recache = false ) {
3048 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3049 $this->mImplicitGroups
= array( '*' );
3050 if ( $this->getId() ) {
3051 $this->mImplicitGroups
[] = 'user';
3053 $this->mImplicitGroups
= array_unique( array_merge(
3054 $this->mImplicitGroups
,
3055 Autopromote
::getAutopromoteGroups( $this )
3059 // Assure data consistency with rights/groups,
3060 // as getEffectiveGroups() depends on this function
3061 $this->mEffectiveGroups
= null;
3064 return $this->mImplicitGroups
;
3068 * Returns the groups the user has belonged to.
3070 * The user may still belong to the returned groups. Compare with getGroups().
3072 * The function will not return groups the user had belonged to before MW 1.17
3074 * @return array Names of the groups the user has belonged to.
3076 public function getFormerGroups() {
3079 if ( is_null( $this->mFormerGroups
) ) {
3080 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3081 ?
wfGetDB( DB_MASTER
)
3082 : wfGetDB( DB_SLAVE
);
3083 $res = $db->select( 'user_former_groups',
3084 array( 'ufg_group' ),
3085 array( 'ufg_user' => $this->mId
),
3087 $this->mFormerGroups
= array();
3088 foreach ( $res as $row ) {
3089 $this->mFormerGroups
[] = $row->ufg_group
;
3093 return $this->mFormerGroups
;
3097 * Get the user's edit count.
3098 * @return int|null Null for anonymous users
3100 public function getEditCount() {
3101 if ( !$this->getId() ) {
3105 if ( $this->mEditCount
=== null ) {
3106 /* Populate the count, if it has not been populated yet */
3107 $dbr = wfGetDB( DB_SLAVE
);
3108 // check if the user_editcount field has been initialized
3109 $count = $dbr->selectField(
3110 'user', 'user_editcount',
3111 array( 'user_id' => $this->mId
),
3115 if ( $count === null ) {
3116 // it has not been initialized. do so.
3117 $count = $this->initEditCount();
3119 $this->mEditCount
= $count;
3121 return (int)$this->mEditCount
;
3125 * Add the user to the given group.
3126 * This takes immediate effect.
3127 * @param string $group Name of the group to add
3130 public function addGroup( $group ) {
3133 if ( !Hooks
::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3137 $dbw = wfGetDB( DB_MASTER
);
3138 if ( $this->getId() ) {
3139 $dbw->insert( 'user_groups',
3141 'ug_user' => $this->getID(),
3142 'ug_group' => $group,
3145 array( 'IGNORE' ) );
3148 $this->loadGroups();
3149 $this->mGroups
[] = $group;
3150 // In case loadGroups was not called before, we now have the right twice.
3151 // Get rid of the duplicate.
3152 $this->mGroups
= array_unique( $this->mGroups
);
3154 // Refresh the groups caches, and clear the rights cache so it will be
3155 // refreshed on the next call to $this->getRights().
3156 $this->getEffectiveGroups( true );
3157 $this->mRights
= null;
3159 $this->invalidateCache();
3165 * Remove the user from the given group.
3166 * This takes immediate effect.
3167 * @param string $group Name of the group to remove
3170 public function removeGroup( $group ) {
3172 if ( !Hooks
::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3176 $dbw = wfGetDB( DB_MASTER
);
3177 $dbw->delete( 'user_groups',
3179 'ug_user' => $this->getID(),
3180 'ug_group' => $group,
3183 // Remember that the user was in this group
3184 $dbw->insert( 'user_former_groups',
3186 'ufg_user' => $this->getID(),
3187 'ufg_group' => $group,
3193 $this->loadGroups();
3194 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3196 // Refresh the groups caches, and clear the rights cache so it will be
3197 // refreshed on the next call to $this->getRights().
3198 $this->getEffectiveGroups( true );
3199 $this->mRights
= null;
3201 $this->invalidateCache();
3207 * Get whether the user is logged in
3210 public function isLoggedIn() {
3211 return $this->getID() != 0;
3215 * Get whether the user is anonymous
3218 public function isAnon() {
3219 return !$this->isLoggedIn();
3223 * Check if user is allowed to access a feature / make an action
3225 * @param string ... Permissions to test
3226 * @return bool True if user is allowed to perform *any* of the given actions
3228 public function isAllowedAny() {
3229 $permissions = func_get_args();
3230 foreach ( $permissions as $permission ) {
3231 if ( $this->isAllowed( $permission ) ) {
3240 * @param string ... Permissions to test
3241 * @return bool True if the user is allowed to perform *all* of the given actions
3243 public function isAllowedAll() {
3244 $permissions = func_get_args();
3245 foreach ( $permissions as $permission ) {
3246 if ( !$this->isAllowed( $permission ) ) {
3254 * Internal mechanics of testing a permission
3255 * @param string $action
3258 public function isAllowed( $action = '' ) {
3259 if ( $action === '' ) {
3260 return true; // In the spirit of DWIM
3262 // Patrolling may not be enabled
3263 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3264 global $wgUseRCPatrol, $wgUseNPPatrol;
3265 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3269 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3270 // by misconfiguration: 0 == 'foo'
3271 return in_array( $action, $this->getRights(), true );
3275 * Check whether to enable recent changes patrol features for this user
3276 * @return bool True or false
3278 public function useRCPatrol() {
3279 global $wgUseRCPatrol;
3280 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3284 * Check whether to enable new pages patrol features for this user
3285 * @return bool True or false
3287 public function useNPPatrol() {
3288 global $wgUseRCPatrol, $wgUseNPPatrol;
3290 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3291 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3296 * Get the WebRequest object to use with this object
3298 * @return WebRequest
3300 public function getRequest() {
3301 if ( $this->mRequest
) {
3302 return $this->mRequest
;
3310 * Get the current skin, loading it if required
3311 * @return Skin The current skin
3312 * @todo FIXME: Need to check the old failback system [AV]
3313 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3315 public function getSkin() {
3316 wfDeprecated( __METHOD__
, '1.18' );
3317 return RequestContext
::getMain()->getSkin();
3321 * Get a WatchedItem for this user and $title.
3323 * @since 1.22 $checkRights parameter added
3324 * @param Title $title
3325 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3326 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3327 * @return WatchedItem
3329 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3330 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3332 if ( isset( $this->mWatchedItems
[$key] ) ) {
3333 return $this->mWatchedItems
[$key];
3336 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3337 $this->mWatchedItems
= array();
3340 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3341 return $this->mWatchedItems
[$key];
3345 * Check the watched status of an article.
3346 * @since 1.22 $checkRights parameter added
3347 * @param Title $title Title of the article to look at
3348 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3349 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3352 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3353 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3358 * @since 1.22 $checkRights parameter added
3359 * @param Title $title Title of the article to look at
3360 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3361 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3363 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3364 $this->getWatchedItem( $title, $checkRights )->addWatch();
3365 $this->invalidateCache();
3369 * Stop watching an article.
3370 * @since 1.22 $checkRights parameter added
3371 * @param Title $title Title of the article to look at
3372 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3373 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3375 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3376 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3377 $this->invalidateCache();
3381 * Clear the user's notification timestamp for the given title.
3382 * If e-notif e-mails are on, they will receive notification mails on
3383 * the next change of the page if it's watched etc.
3384 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3385 * @param Title $title Title of the article to look at
3386 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3388 public function clearNotification( &$title, $oldid = 0 ) {
3389 global $wgUseEnotif, $wgShowUpdatedMarker;
3391 // Do nothing if the database is locked to writes
3392 if ( wfReadOnly() ) {
3396 // Do nothing if not allowed to edit the watchlist
3397 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3401 // If we're working on user's talk page, we should update the talk page message indicator
3402 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3403 if ( !Hooks
::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3408 // Try to update the DB post-send and only if needed...
3409 DeferredUpdates
::addCallableUpdate( function() use ( $that, $title, $oldid ) {
3410 if ( !$that->getNewtalk() ) {
3411 return; // no notifications to clear
3414 // Delete the last notifications (they stack up)
3415 $that->setNewtalk( false );
3417 // If there is a new, unseen, revision, use its timestamp
3419 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3422 $that->setNewtalk( true, Revision
::newFromId( $nextid ) );
3427 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3431 if ( $this->isAnon() ) {
3432 // Nothing else to do...
3436 // Only update the timestamp if the page is being watched.
3437 // The query to find out if it is watched is cached both in memcached and per-invocation,
3438 // and when it does have to be executed, it can be on a slave
3439 // If this is the user's newtalk page, we always update the timestamp
3441 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3445 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3446 $force, $oldid, WatchedItem
::DEFERRED
3451 * Resets all of the given user's page-change notification timestamps.
3452 * If e-notif e-mails are on, they will receive notification mails on
3453 * the next change of any watched page.
3454 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3456 public function clearAllNotifications() {
3457 if ( wfReadOnly() ) {
3461 // Do nothing if not allowed to edit the watchlist
3462 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3466 global $wgUseEnotif, $wgShowUpdatedMarker;
3467 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3468 $this->setNewtalk( false );
3471 $id = $this->getId();
3473 $dbw = wfGetDB( DB_MASTER
);
3474 $dbw->update( 'watchlist',
3475 array( /* SET */ 'wl_notificationtimestamp' => null ),
3476 array( /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ),
3479 // We also need to clear here the "you have new message" notification for the own user_talk page;
3480 // it's cleared one page view later in WikiPage::doViewUpdates().
3485 * Set a cookie on the user's client. Wrapper for
3486 * WebResponse::setCookie
3487 * @param string $name Name of the cookie to set
3488 * @param string $value Value to set
3489 * @param int $exp Expiration time, as a UNIX time value;
3490 * if 0 or not specified, use the default $wgCookieExpiration
3491 * @param bool $secure
3492 * true: Force setting the secure attribute when setting the cookie
3493 * false: Force NOT setting the secure attribute when setting the cookie
3494 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3495 * @param array $params Array of options sent passed to WebResponse::setcookie()
3496 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3499 protected function setCookie(
3500 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3502 if ( $request === null ) {
3503 $request = $this->getRequest();
3505 $params['secure'] = $secure;
3506 $request->response()->setCookie( $name, $value, $exp, $params );
3510 * Clear a cookie on the user's client
3511 * @param string $name Name of the cookie to clear
3512 * @param bool $secure
3513 * true: Force setting the secure attribute when setting the cookie
3514 * false: Force NOT setting the secure attribute when setting the cookie
3515 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3516 * @param array $params Array of options sent passed to WebResponse::setcookie()
3518 protected function clearCookie( $name, $secure = null, $params = array() ) {
3519 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3523 * Set an extended login cookie on the user's client. The expiry of the cookie
3524 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3527 * @see User::setCookie
3529 * @param string $name Name of the cookie to set
3530 * @param string $value Value to set
3531 * @param bool $secure
3532 * true: Force setting the secure attribute when setting the cookie
3533 * false: Force NOT setting the secure attribute when setting the cookie
3534 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3536 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3537 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3540 $exp +
= $wgExtendedLoginCookieExpiration !== null
3541 ?
$wgExtendedLoginCookieExpiration
3542 : $wgCookieExpiration;
3544 $this->setCookie( $name, $value, $exp, $secure );
3548 * Set the default cookies for this session on the user's client.
3550 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3552 * @param bool $secure Whether to force secure/insecure cookies or use default
3553 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3555 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3556 global $wgExtendedLoginCookies;
3558 if ( $request === null ) {
3559 $request = $this->getRequest();
3563 if ( 0 == $this->mId
) {
3566 if ( !$this->mToken
) {
3567 // When token is empty or NULL generate a new one and then save it to the database
3568 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3569 // Simply by setting every cell in the user_token column to NULL and letting them be
3570 // regenerated as users log back into the wiki.
3572 if ( !wfReadOnly() ) {
3573 $this->saveSettings();
3577 'wsUserID' => $this->mId
,
3578 'wsToken' => $this->mToken
,
3579 'wsUserName' => $this->getName()
3582 'UserID' => $this->mId
,
3583 'UserName' => $this->getName(),
3585 if ( $rememberMe ) {
3586 $cookies['Token'] = $this->mToken
;
3588 $cookies['Token'] = false;
3591 Hooks
::run( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3593 foreach ( $session as $name => $value ) {
3594 $request->setSessionData( $name, $value );
3596 foreach ( $cookies as $name => $value ) {
3597 if ( $value === false ) {
3598 $this->clearCookie( $name );
3599 } elseif ( $rememberMe && in_array( $name, $wgExtendedLoginCookies ) ) {
3600 $this->setExtendedLoginCookie( $name, $value, $secure );
3602 $this->setCookie( $name, $value, 0, $secure, array(), $request );
3607 * If wpStickHTTPS was selected, also set an insecure cookie that
3608 * will cause the site to redirect the user to HTTPS, if they access
3609 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3610 * as the one set by centralauth (bug 53538). Also set it to session, or
3611 * standard time setting, based on if rememberme was set.
3613 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3617 $rememberMe ?
0 : null,
3619 array( 'prefix' => '' ) // no prefix
3625 * Log this user out.
3627 public function logout() {
3628 if ( Hooks
::run( 'UserLogout', array( &$this ) ) ) {
3634 * Clear the user's cookies and session, and reset the instance cache.
3637 public function doLogout() {
3638 $this->clearInstanceCache( 'defaults' );
3640 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3642 $this->clearCookie( 'UserID' );
3643 $this->clearCookie( 'Token' );
3644 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3646 // Remember when user logged out, to prevent seeing cached pages
3647 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3651 * Save this user's settings into the database.
3652 * @todo Only rarely do all these fields need to be set!
3654 public function saveSettings() {
3655 if ( wfReadOnly() ) {
3656 // @TODO: caller should deal with this instead!
3657 // This should really just be an exception.
3658 MWExceptionHandler
::logException( new DBExpectedError(
3660 "Could not update user with ID '{$this->mId}'; DB is read-only."
3666 if ( 0 == $this->mId
) {
3670 // Get a new user_touched that is higher than the old one.
3671 // This will be used for a CAS check as a last-resort safety
3672 // check against race conditions and slave lag.
3673 $oldTouched = $this->mTouched
;
3674 $newTouched = $this->newTouchedTimestamp();
3676 $dbw = wfGetDB( DB_MASTER
);
3677 $dbw->update( 'user',
3679 'user_name' => $this->mName
,
3680 'user_real_name' => $this->mRealName
,
3681 'user_email' => $this->mEmail
,
3682 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3683 'user_touched' => $dbw->timestamp( $newTouched ),
3684 'user_token' => strval( $this->mToken
),
3685 'user_email_token' => $this->mEmailToken
,
3686 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3687 ), array( /* WHERE */
3688 'user_id' => $this->mId
,
3689 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3693 if ( !$dbw->affectedRows() ) {
3694 // Maybe the problem was a missed cache update; clear it to be safe
3695 $this->clearSharedCache( 'refresh' );
3696 // User was changed in the meantime or loaded with stale data
3697 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3698 throw new MWException(
3699 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3700 " the version of the user to be saved is older than the current version."
3704 $this->mTouched
= $newTouched;
3705 $this->saveOptions();
3707 Hooks
::run( 'UserSaveSettings', array( $this ) );
3708 $this->clearSharedCache();
3709 $this->getUserPage()->invalidateCache();
3713 * If only this user's username is known, and it exists, return the user ID.
3715 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3718 public function idForName( $flags = 0 ) {
3719 $s = trim( $this->getName() );
3724 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3725 ?
wfGetDB( DB_MASTER
)
3726 : wfGetDB( DB_SLAVE
);
3728 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3729 ?
array( 'LOCK IN SHARE MODE' )
3732 $id = $db->selectField( 'user',
3733 'user_id', array( 'user_name' => $s ), __METHOD__
, $options );
3739 * Add a user to the database, return the user object
3741 * @param string $name Username to add
3742 * @param array $params Array of Strings Non-default parameters to save to
3743 * the database as user_* fields:
3744 * - email: The user's email address.
3745 * - email_authenticated: The email authentication timestamp.
3746 * - real_name: The user's real name.
3747 * - options: An associative array of non-default options.
3748 * - token: Random authentication token. Do not set.
3749 * - registration: Registration timestamp. Do not set.
3751 * @return User|null User object, or null if the username already exists.
3753 public static function createNew( $name, $params = array() ) {
3754 foreach ( array( 'password', 'newpassword', 'newpass_time', 'password_expires' ) as $field ) {
3755 if ( isset( $params[$field] ) ) {
3756 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3757 unset( $params[$field] );
3763 $user->setToken(); // init token
3764 if ( isset( $params['options'] ) ) {
3765 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3766 unset( $params['options'] );
3768 $dbw = wfGetDB( DB_MASTER
);
3769 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3771 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3774 'user_id' => $seqVal,
3775 'user_name' => $name,
3776 'user_password' => $noPass,
3777 'user_newpassword' => $noPass,
3778 'user_email' => $user->mEmail
,
3779 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3780 'user_real_name' => $user->mRealName
,
3781 'user_token' => strval( $user->mToken
),
3782 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3783 'user_editcount' => 0,
3784 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3786 foreach ( $params as $name => $value ) {
3787 $fields["user_$name"] = $value;
3789 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3790 if ( $dbw->affectedRows() ) {
3791 $newUser = User
::newFromId( $dbw->insertId() );
3799 * Add this existing user object to the database. If the user already
3800 * exists, a fatal status object is returned, and the user object is
3801 * initialised with the data from the database.
3803 * Previously, this function generated a DB error due to a key conflict
3804 * if the user already existed. Many extension callers use this function
3805 * in code along the lines of:
3807 * $user = User::newFromName( $name );
3808 * if ( !$user->isLoggedIn() ) {
3809 * $user->addToDatabase();
3811 * // do something with $user...
3813 * However, this was vulnerable to a race condition (bug 16020). By
3814 * initialising the user object if the user exists, we aim to support this
3815 * calling sequence as far as possible.
3817 * Note that if the user exists, this function will acquire a write lock,
3818 * so it is still advisable to make the call conditional on isLoggedIn(),
3819 * and to commit the transaction after calling.
3821 * @throws MWException
3824 public function addToDatabase() {
3826 if ( !$this->mToken
) {
3827 $this->setToken(); // init token
3830 $this->mTouched
= $this->newTouchedTimestamp();
3832 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3834 $dbw = wfGetDB( DB_MASTER
);
3835 $inWrite = $dbw->writesOrCallbacksPending();
3836 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3837 $dbw->insert( 'user',
3839 'user_id' => $seqVal,
3840 'user_name' => $this->mName
,
3841 'user_password' => $noPass,
3842 'user_newpassword' => $noPass,
3843 'user_email' => $this->mEmail
,
3844 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3845 'user_real_name' => $this->mRealName
,
3846 'user_token' => strval( $this->mToken
),
3847 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3848 'user_editcount' => 0,
3849 'user_touched' => $dbw->timestamp( $this->mTouched
),
3853 if ( !$dbw->affectedRows() ) {
3854 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3855 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3857 // Can't commit due to pending writes that may need atomicity.
3858 // This may cause some lock contention unlike the case below.
3859 $options = array( 'LOCK IN SHARE MODE' );
3860 $flags = self
::READ_LOCKING
;
3862 // Often, this case happens early in views before any writes when
3863 // using CentralAuth. It's should be OK to commit and break the snapshot.
3864 $dbw->commit( __METHOD__
, 'flush' );
3866 $flags = self
::READ_LATEST
;
3868 $this->mId
= $dbw->selectField( 'user', 'user_id',
3869 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3872 if ( $this->loadFromDatabase( $flags ) ) {
3877 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3878 "to insert user '{$this->mName}' row, but it was not present in select!" );
3880 return Status
::newFatal( 'userexists' );
3882 $this->mId
= $dbw->insertId();
3884 // Set the password now that it's in the DB, if applicable
3885 if ( $this->mPassword
!== null ) {
3886 $this->setPasswordInternal( $this->mPassword
);
3889 // Clear instance cache other than user table data, which is already accurate
3890 $this->clearInstanceCache();
3892 $this->saveOptions();
3893 return Status
::newGood();
3897 * If this user is logged-in and blocked,
3898 * block any IP address they've successfully logged in from.
3899 * @return bool A block was spread
3901 public function spreadAnyEditBlock() {
3902 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3903 return $this->spreadBlock();
3909 * If this (non-anonymous) user is blocked,
3910 * block the IP address they've successfully logged in from.
3911 * @return bool A block was spread
3913 protected function spreadBlock() {
3914 wfDebug( __METHOD__
. "()\n" );
3916 if ( $this->mId
== 0 ) {
3920 $userblock = Block
::newFromTarget( $this->getName() );
3921 if ( !$userblock ) {
3925 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3929 * Get whether the user is explicitly blocked from account creation.
3930 * @return bool|Block
3932 public function isBlockedFromCreateAccount() {
3933 $this->getBlockedStatus();
3934 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3935 return $this->mBlock
;
3938 # bug 13611: if the IP address the user is trying to create an account from is
3939 # blocked with createaccount disabled, prevent new account creation there even
3940 # when the user is logged in
3941 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3942 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3944 return $this->mBlockedFromCreateAccount
instanceof Block
3945 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3946 ?
$this->mBlockedFromCreateAccount
3951 * Get whether the user is blocked from using Special:Emailuser.
3954 public function isBlockedFromEmailuser() {
3955 $this->getBlockedStatus();
3956 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3960 * Get whether the user is allowed to create an account.
3963 public function isAllowedToCreateAccount() {
3964 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3968 * Get this user's personal page title.
3970 * @return Title User's personal page title
3972 public function getUserPage() {
3973 return Title
::makeTitle( NS_USER
, $this->getName() );
3977 * Get this user's talk page title.
3979 * @return Title User's talk page title
3981 public function getTalkPage() {
3982 $title = $this->getUserPage();
3983 return $title->getTalkPage();
3987 * Determine whether the user is a newbie. Newbies are either
3988 * anonymous IPs, or the most recently created accounts.
3991 public function isNewbie() {
3992 return !$this->isAllowed( 'autoconfirmed' );
3996 * Check to see if the given clear-text password is one of the accepted passwords
3997 * @deprecated since 1.27. AuthManager is coming.
3998 * @param string $password User password
3999 * @return bool True if the given password is correct, otherwise False
4001 public function checkPassword( $password ) {
4002 global $wgAuth, $wgLegacyEncoding;
4006 // Some passwords will give a fatal Status, which means there is
4007 // some sort of technical or security reason for this password to
4008 // be completely invalid and should never be checked (e.g., T64685)
4009 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4013 // Certain authentication plugins do NOT want to save
4014 // domain passwords in a mysql database, so we should
4015 // check this (in case $wgAuth->strict() is false).
4016 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4018 } elseif ( $wgAuth->strict() ) {
4019 // Auth plugin doesn't allow local authentication
4021 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4022 // Auth plugin doesn't allow local authentication for this user name
4026 $passwordFactory = new PasswordFactory();
4027 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4028 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4029 ?
wfGetDB( DB_MASTER
)
4030 : wfGetDB( DB_SLAVE
);
4033 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4034 'user', 'user_password', array( 'user_id' => $this->getId() ), __METHOD__
4036 } catch ( PasswordError
$e ) {
4037 wfDebug( 'Invalid password hash found in database.' );
4038 $mPassword = PasswordFactory
::newInvalidPassword();
4041 if ( !$mPassword->equals( $password ) ) {
4042 if ( $wgLegacyEncoding ) {
4043 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4044 // Check for this with iconv
4045 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4046 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4054 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4055 $this->setPasswordInternal( $password );
4062 * Check if the given clear-text password matches the temporary password
4063 * sent by e-mail for password reset operations.
4065 * @deprecated since 1.27. AuthManager is coming.
4066 * @param string $plaintext
4067 * @return bool True if matches, false otherwise
4069 public function checkTemporaryPassword( $plaintext ) {
4070 global $wgNewPasswordExpiry;
4074 $passwordFactory = new PasswordFactory();
4075 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4076 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4077 ?
wfGetDB( DB_MASTER
)
4078 : wfGetDB( DB_SLAVE
);
4080 $row = $db->selectRow(
4082 array( 'user_newpassword', 'user_newpass_time' ),
4083 array( 'user_id' => $this->getId() ),
4087 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4088 } catch ( PasswordError
$e ) {
4089 wfDebug( 'Invalid password hash found in database.' );
4090 $newPassword = PasswordFactory
::newInvalidPassword();
4093 if ( $newPassword->equals( $plaintext ) ) {
4094 if ( is_null( $row->user_newpass_time
) ) {
4097 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4098 return ( time() < $expiry );
4105 * Alias for getEditToken.
4106 * @deprecated since 1.19, use getEditToken instead.
4108 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4109 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4110 * @return string The new edit token
4112 public function editToken( $salt = '', $request = null ) {
4113 wfDeprecated( __METHOD__
, '1.19' );
4114 return $this->getEditToken( $salt, $request );
4118 * Internal implementation for self::getEditToken() and
4119 * self::matchEditToken().
4121 * @param string|array $salt
4122 * @param WebRequest $request
4123 * @param string|int $timestamp
4126 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
4127 if ( $this->isAnon() ) {
4128 return self
::EDIT_TOKEN_SUFFIX
;
4130 $token = $request->getSessionData( 'wsEditToken' );
4131 if ( $token === null ) {
4132 $token = MWCryptRand
::generateHex( 32 );
4133 $request->setSessionData( 'wsEditToken', $token );
4135 if ( is_array( $salt ) ) {
4136 $salt = implode( '|', $salt );
4138 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
4139 dechex( $timestamp ) .
4140 self
::EDIT_TOKEN_SUFFIX
;
4145 * Initialize (if necessary) and return a session token value
4146 * which can be used in edit forms to show that the user's
4147 * login credentials aren't being hijacked with a foreign form
4152 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4153 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4154 * @return string The new edit token
4156 public function getEditToken( $salt = '', $request = null ) {
4157 return $this->getEditTokenAtTimestamp(
4158 $salt, $request ?
: $this->getRequest(), wfTimestamp()
4163 * Generate a looking random token for various uses.
4165 * @return string The new random token
4166 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
4167 * wfRandomString for pseudo-randomness.
4169 public static function generateToken() {
4170 return MWCryptRand
::generateHex( 32 );
4174 * Get the embedded timestamp from a token.
4175 * @param string $val Input token
4178 public static function getEditTokenTimestamp( $val ) {
4179 $suffixLen = strlen( self
::EDIT_TOKEN_SUFFIX
);
4180 if ( strlen( $val ) <= 32 +
$suffixLen ) {
4184 return hexdec( substr( $val, 32, -$suffixLen ) );
4188 * Check given value against the token value stored in the session.
4189 * A match should confirm that the form was submitted from the
4190 * user's own login session, not a form submission from a third-party
4193 * @param string $val Input value to compare
4194 * @param string $salt Optional function-specific data for hashing
4195 * @param WebRequest|null $request Object to use or null to use $wgRequest
4196 * @param int $maxage Fail tokens older than this, in seconds
4197 * @return bool Whether the token matches
4199 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4200 if ( $this->isAnon() ) {
4201 return $val === self
::EDIT_TOKEN_SUFFIX
;
4204 $timestamp = self
::getEditTokenTimestamp( $val );
4205 if ( $timestamp === null ) {
4208 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
4213 $sessionToken = $this->getEditTokenAtTimestamp(
4214 $salt, $request ?
: $this->getRequest(), $timestamp
4217 if ( $val != $sessionToken ) {
4218 wfDebug( "User::matchEditToken: broken session data\n" );
4221 return hash_equals( $sessionToken, $val );
4225 * Check given value against the token value stored in the session,
4226 * ignoring the suffix.
4228 * @param string $val Input value to compare
4229 * @param string $salt Optional function-specific data for hashing
4230 * @param WebRequest|null $request Object to use or null to use $wgRequest
4231 * @param int $maxage Fail tokens older than this, in seconds
4232 * @return bool Whether the token matches
4234 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4235 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4236 return $this->matchEditToken( $val, $salt, $request, $maxage );
4240 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4241 * mail to the user's given address.
4243 * @param string $type Message to send, either "created", "changed" or "set"
4246 public function sendConfirmationMail( $type = 'created' ) {
4248 $expiration = null; // gets passed-by-ref and defined in next line.
4249 $token = $this->confirmationToken( $expiration );
4250 $url = $this->confirmationTokenUrl( $token );
4251 $invalidateURL = $this->invalidationTokenUrl( $token );
4252 $this->saveSettings();
4254 if ( $type == 'created' ||
$type === false ) {
4255 $message = 'confirmemail_body';
4256 } elseif ( $type === true ) {
4257 $message = 'confirmemail_body_changed';
4259 // Messages: confirmemail_body_changed, confirmemail_body_set
4260 $message = 'confirmemail_body_' . $type;
4263 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4264 wfMessage( $message,
4265 $this->getRequest()->getIP(),
4268 $wgLang->timeanddate( $expiration, false ),
4270 $wgLang->date( $expiration, false ),
4271 $wgLang->time( $expiration, false ) )->text() );
4275 * Send an e-mail to this user's account. Does not check for
4276 * confirmed status or validity.
4278 * @param string $subject Message subject
4279 * @param string $body Message body
4280 * @param User|null $from Optional sending user; if unspecified, default
4281 * $wgPasswordSender will be used.
4282 * @param string $replyto Reply-To address
4285 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4286 global $wgPasswordSender;
4288 if ( $from instanceof User
) {
4289 $sender = MailAddress
::newFromUser( $from );
4291 $sender = new MailAddress( $wgPasswordSender,
4292 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4294 $to = MailAddress
::newFromUser( $this );
4296 return UserMailer
::send( $to, $sender, $subject, $body, array(
4297 'replyTo' => $replyto,
4302 * Generate, store, and return a new e-mail confirmation code.
4303 * A hash (unsalted, since it's used as a key) is stored.
4305 * @note Call saveSettings() after calling this function to commit
4306 * this change to the database.
4308 * @param string &$expiration Accepts the expiration time
4309 * @return string New token
4311 protected function confirmationToken( &$expiration ) {
4312 global $wgUserEmailConfirmationTokenExpiry;
4314 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4315 $expiration = wfTimestamp( TS_MW
, $expires );
4317 $token = MWCryptRand
::generateHex( 32 );
4318 $hash = md5( $token );
4319 $this->mEmailToken
= $hash;
4320 $this->mEmailTokenExpires
= $expiration;
4325 * Return a URL the user can use to confirm their email address.
4326 * @param string $token Accepts the email confirmation token
4327 * @return string New token URL
4329 protected function confirmationTokenUrl( $token ) {
4330 return $this->getTokenUrl( 'ConfirmEmail', $token );
4334 * Return a URL the user can use to invalidate their email address.
4335 * @param string $token Accepts the email confirmation token
4336 * @return string New token URL
4338 protected function invalidationTokenUrl( $token ) {
4339 return $this->getTokenUrl( 'InvalidateEmail', $token );
4343 * Internal function to format the e-mail validation/invalidation URLs.
4344 * This uses a quickie hack to use the
4345 * hardcoded English names of the Special: pages, for ASCII safety.
4347 * @note Since these URLs get dropped directly into emails, using the
4348 * short English names avoids insanely long URL-encoded links, which
4349 * also sometimes can get corrupted in some browsers/mailers
4350 * (bug 6957 with Gmail and Internet Explorer).
4352 * @param string $page Special page
4353 * @param string $token Token
4354 * @return string Formatted URL
4356 protected function getTokenUrl( $page, $token ) {
4357 // Hack to bypass localization of 'Special:'
4358 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4359 return $title->getCanonicalURL();
4363 * Mark the e-mail address confirmed.
4365 * @note Call saveSettings() after calling this function to commit the change.
4369 public function confirmEmail() {
4370 // Check if it's already confirmed, so we don't touch the database
4371 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4372 if ( !$this->isEmailConfirmed() ) {
4373 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4374 Hooks
::run( 'ConfirmEmailComplete', array( $this ) );
4380 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4381 * address if it was already confirmed.
4383 * @note Call saveSettings() after calling this function to commit the change.
4384 * @return bool Returns true
4386 public function invalidateEmail() {
4388 $this->mEmailToken
= null;
4389 $this->mEmailTokenExpires
= null;
4390 $this->setEmailAuthenticationTimestamp( null );
4392 Hooks
::run( 'InvalidateEmailComplete', array( $this ) );
4397 * Set the e-mail authentication timestamp.
4398 * @param string $timestamp TS_MW timestamp
4400 public function setEmailAuthenticationTimestamp( $timestamp ) {
4402 $this->mEmailAuthenticated
= $timestamp;
4403 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4407 * Is this user allowed to send e-mails within limits of current
4408 * site configuration?
4411 public function canSendEmail() {
4412 global $wgEnableEmail, $wgEnableUserEmail;
4413 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4416 $canSend = $this->isEmailConfirmed();
4417 Hooks
::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4422 * Is this user allowed to receive e-mails within limits of current
4423 * site configuration?
4426 public function canReceiveEmail() {
4427 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4431 * Is this user's e-mail address valid-looking and confirmed within
4432 * limits of the current site configuration?
4434 * @note If $wgEmailAuthentication is on, this may require the user to have
4435 * confirmed their address by returning a code or using a password
4436 * sent to the address from the wiki.
4440 public function isEmailConfirmed() {
4441 global $wgEmailAuthentication;
4444 if ( Hooks
::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4445 if ( $this->isAnon() ) {
4448 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4451 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4461 * Check whether there is an outstanding request for e-mail confirmation.
4464 public function isEmailConfirmationPending() {
4465 global $wgEmailAuthentication;
4466 return $wgEmailAuthentication &&
4467 !$this->isEmailConfirmed() &&
4468 $this->mEmailToken
&&
4469 $this->mEmailTokenExpires
> wfTimestamp();
4473 * Get the timestamp of account creation.
4475 * @return string|bool|null Timestamp of account creation, false for
4476 * non-existent/anonymous user accounts, or null if existing account
4477 * but information is not in database.
4479 public function getRegistration() {
4480 if ( $this->isAnon() ) {
4484 return $this->mRegistration
;
4488 * Get the timestamp of the first edit
4490 * @return string|bool Timestamp of first edit, or false for
4491 * non-existent/anonymous user accounts.
4493 public function getFirstEditTimestamp() {
4494 if ( $this->getId() == 0 ) {
4495 return false; // anons
4497 $dbr = wfGetDB( DB_SLAVE
);
4498 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4499 array( 'rev_user' => $this->getId() ),
4501 array( 'ORDER BY' => 'rev_timestamp ASC' )
4504 return false; // no edits
4506 return wfTimestamp( TS_MW
, $time );
4510 * Get the permissions associated with a given list of groups
4512 * @param array $groups Array of Strings List of internal group names
4513 * @return array Array of Strings List of permission key names for given groups combined
4515 public static function getGroupPermissions( $groups ) {
4516 global $wgGroupPermissions, $wgRevokePermissions;
4518 // grant every granted permission first
4519 foreach ( $groups as $group ) {
4520 if ( isset( $wgGroupPermissions[$group] ) ) {
4521 $rights = array_merge( $rights,
4522 // array_filter removes empty items
4523 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4526 // now revoke the revoked permissions
4527 foreach ( $groups as $group ) {
4528 if ( isset( $wgRevokePermissions[$group] ) ) {
4529 $rights = array_diff( $rights,
4530 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4533 return array_unique( $rights );
4537 * Get all the groups who have a given permission
4539 * @param string $role Role to check
4540 * @return array Array of Strings List of internal group names with the given permission
4542 public static function getGroupsWithPermission( $role ) {
4543 global $wgGroupPermissions;
4544 $allowedGroups = array();
4545 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4546 if ( self
::groupHasPermission( $group, $role ) ) {
4547 $allowedGroups[] = $group;
4550 return $allowedGroups;
4554 * Check, if the given group has the given permission
4556 * If you're wanting to check whether all users have a permission, use
4557 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4561 * @param string $group Group to check
4562 * @param string $role Role to check
4565 public static function groupHasPermission( $group, $role ) {
4566 global $wgGroupPermissions, $wgRevokePermissions;
4567 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4568 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4572 * Check if all users have the given permission
4575 * @param string $right Right to check
4578 public static function isEveryoneAllowed( $right ) {
4579 global $wgGroupPermissions, $wgRevokePermissions;
4580 static $cache = array();
4582 // Use the cached results, except in unit tests which rely on
4583 // being able change the permission mid-request
4584 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4585 return $cache[$right];
4588 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4589 $cache[$right] = false;
4593 // If it's revoked anywhere, then everyone doesn't have it
4594 foreach ( $wgRevokePermissions as $rights ) {
4595 if ( isset( $rights[$right] ) && $rights[$right] ) {
4596 $cache[$right] = false;
4601 // Allow extensions (e.g. OAuth) to say false
4602 if ( !Hooks
::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4603 $cache[$right] = false;
4607 $cache[$right] = true;
4612 * Get the localized descriptive name for a group, if it exists
4614 * @param string $group Internal group name
4615 * @return string Localized descriptive group name
4617 public static function getGroupName( $group ) {
4618 $msg = wfMessage( "group-$group" );
4619 return $msg->isBlank() ?
$group : $msg->text();
4623 * Get the localized descriptive name for a member of a group, if it exists
4625 * @param string $group Internal group name
4626 * @param string $username Username for gender (since 1.19)
4627 * @return string Localized name for group member
4629 public static function getGroupMember( $group, $username = '#' ) {
4630 $msg = wfMessage( "group-$group-member", $username );
4631 return $msg->isBlank() ?
$group : $msg->text();
4635 * Return the set of defined explicit groups.
4636 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4637 * are not included, as they are defined automatically, not in the database.
4638 * @return array Array of internal group names
4640 public static function getAllGroups() {
4641 global $wgGroupPermissions, $wgRevokePermissions;
4643 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4644 self
::getImplicitGroups()
4649 * Get a list of all available permissions.
4650 * @return string[] Array of permission names
4652 public static function getAllRights() {
4653 if ( self
::$mAllRights === false ) {
4654 global $wgAvailableRights;
4655 if ( count( $wgAvailableRights ) ) {
4656 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4658 self
::$mAllRights = self
::$mCoreRights;
4660 Hooks
::run( 'UserGetAllRights', array( &self
::$mAllRights ) );
4662 return self
::$mAllRights;
4666 * Get a list of implicit groups
4667 * @return array Array of Strings Array of internal group names
4669 public static function getImplicitGroups() {
4670 global $wgImplicitGroups;
4672 $groups = $wgImplicitGroups;
4673 # Deprecated, use $wgImplicitGroups instead
4674 Hooks
::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4680 * Get the title of a page describing a particular group
4682 * @param string $group Internal group name
4683 * @return Title|bool Title of the page if it exists, false otherwise
4685 public static function getGroupPage( $group ) {
4686 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4687 if ( $msg->exists() ) {
4688 $title = Title
::newFromText( $msg->text() );
4689 if ( is_object( $title ) ) {
4697 * Create a link to the group in HTML, if available;
4698 * else return the group name.
4700 * @param string $group Internal name of the group
4701 * @param string $text The text of the link
4702 * @return string HTML link to the group
4704 public static function makeGroupLinkHTML( $group, $text = '' ) {
4705 if ( $text == '' ) {
4706 $text = self
::getGroupName( $group );
4708 $title = self
::getGroupPage( $group );
4710 return Linker
::link( $title, htmlspecialchars( $text ) );
4712 return htmlspecialchars( $text );
4717 * Create a link to the group in Wikitext, if available;
4718 * else return the group name.
4720 * @param string $group Internal name of the group
4721 * @param string $text The text of the link
4722 * @return string Wikilink to the group
4724 public static function makeGroupLinkWiki( $group, $text = '' ) {
4725 if ( $text == '' ) {
4726 $text = self
::getGroupName( $group );
4728 $title = self
::getGroupPage( $group );
4730 $page = $title->getFullText();
4731 return "[[$page|$text]]";
4738 * Returns an array of the groups that a particular group can add/remove.
4740 * @param string $group The group to check for whether it can add/remove
4741 * @return array Array( 'add' => array( addablegroups ),
4742 * 'remove' => array( removablegroups ),
4743 * 'add-self' => array( addablegroups to self),
4744 * 'remove-self' => array( removable groups from self) )
4746 public static function changeableByGroup( $group ) {
4747 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4751 'remove' => array(),
4752 'add-self' => array(),
4753 'remove-self' => array()
4756 if ( empty( $wgAddGroups[$group] ) ) {
4757 // Don't add anything to $groups
4758 } elseif ( $wgAddGroups[$group] === true ) {
4759 // You get everything
4760 $groups['add'] = self
::getAllGroups();
4761 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4762 $groups['add'] = $wgAddGroups[$group];
4765 // Same thing for remove
4766 if ( empty( $wgRemoveGroups[$group] ) ) {
4768 } elseif ( $wgRemoveGroups[$group] === true ) {
4769 $groups['remove'] = self
::getAllGroups();
4770 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4771 $groups['remove'] = $wgRemoveGroups[$group];
4774 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4775 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4776 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4777 if ( is_int( $key ) ) {
4778 $wgGroupsAddToSelf['user'][] = $value;
4783 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4784 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4785 if ( is_int( $key ) ) {
4786 $wgGroupsRemoveFromSelf['user'][] = $value;
4791 // Now figure out what groups the user can add to him/herself
4792 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4794 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4795 // No idea WHY this would be used, but it's there
4796 $groups['add-self'] = User
::getAllGroups();
4797 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4798 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4801 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4803 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4804 $groups['remove-self'] = User
::getAllGroups();
4805 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4806 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4813 * Returns an array of groups that this user can add and remove
4814 * @return array Array( 'add' => array( addablegroups ),
4815 * 'remove' => array( removablegroups ),
4816 * 'add-self' => array( addablegroups to self),
4817 * 'remove-self' => array( removable groups from self) )
4819 public function changeableGroups() {
4820 if ( $this->isAllowed( 'userrights' ) ) {
4821 // This group gives the right to modify everything (reverse-
4822 // compatibility with old "userrights lets you change
4824 // Using array_merge to make the groups reindexed
4825 $all = array_merge( User
::getAllGroups() );
4829 'add-self' => array(),
4830 'remove-self' => array()
4834 // Okay, it's not so simple, we will have to go through the arrays
4837 'remove' => array(),
4838 'add-self' => array(),
4839 'remove-self' => array()
4841 $addergroups = $this->getEffectiveGroups();
4843 foreach ( $addergroups as $addergroup ) {
4844 $groups = array_merge_recursive(
4845 $groups, $this->changeableByGroup( $addergroup )
4847 $groups['add'] = array_unique( $groups['add'] );
4848 $groups['remove'] = array_unique( $groups['remove'] );
4849 $groups['add-self'] = array_unique( $groups['add-self'] );
4850 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4856 * Deferred version of incEditCountImmediate()
4858 public function incEditCount() {
4860 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $that ) {
4861 $that->incEditCountImmediate();
4866 * Increment the user's edit-count field.
4867 * Will have no effect for anonymous users.
4870 public function incEditCountImmediate() {
4871 if ( $this->isAnon() ) {
4875 $dbw = wfGetDB( DB_MASTER
);
4876 // No rows will be "affected" if user_editcount is NULL
4879 array( 'user_editcount=user_editcount+1' ),
4880 array( 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ),
4883 // Lazy initialization check...
4884 if ( $dbw->affectedRows() == 0 ) {
4885 // Now here's a goddamn hack...
4886 $dbr = wfGetDB( DB_SLAVE
);
4887 if ( $dbr !== $dbw ) {
4888 // If we actually have a slave server, the count is
4889 // at least one behind because the current transaction
4890 // has not been committed and replicated.
4891 $this->initEditCount( 1 );
4893 // But if DB_SLAVE is selecting the master, then the
4894 // count we just read includes the revision that was
4895 // just added in the working transaction.
4896 $this->initEditCount();
4899 // Edit count in user cache too
4900 $this->invalidateCache();
4904 * Initialize user_editcount from data out of the revision table
4906 * @param int $add Edits to add to the count from the revision table
4907 * @return int Number of edits
4909 protected function initEditCount( $add = 0 ) {
4910 // Pull from a slave to be less cruel to servers
4911 // Accuracy isn't the point anyway here
4912 $dbr = wfGetDB( DB_SLAVE
);
4913 $count = (int)$dbr->selectField(
4916 array( 'rev_user' => $this->getId() ),
4919 $count = $count +
$add;
4921 $dbw = wfGetDB( DB_MASTER
);
4924 array( 'user_editcount' => $count ),
4925 array( 'user_id' => $this->getId() ),
4933 * Get the description of a given right
4935 * @param string $right Right to query
4936 * @return string Localized description of the right
4938 public static function getRightDescription( $right ) {
4939 $key = "right-$right";
4940 $msg = wfMessage( $key );
4941 return $msg->isBlank() ?
$right : $msg->text();
4945 * Make a new-style password hash
4947 * @param string $password Plain-text password
4948 * @param bool|string $salt Optional salt, may be random or the user ID.
4949 * If unspecified or false, will generate one automatically
4950 * @return string Password hash
4951 * @deprecated since 1.24, use Password class
4953 public static function crypt( $password, $salt = false ) {
4954 wfDeprecated( __METHOD__
, '1.24' );
4955 $passwordFactory = new PasswordFactory();
4956 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4957 $hash = $passwordFactory->newFromPlaintext( $password );
4958 return $hash->toString();
4962 * Compare a password hash with a plain-text password. Requires the user
4963 * ID if there's a chance that the hash is an old-style hash.
4965 * @param string $hash Password hash
4966 * @param string $password Plain-text password to compare
4967 * @param string|bool $userId User ID for old-style password salt
4970 * @deprecated since 1.24, use Password class
4972 public static function comparePasswords( $hash, $password, $userId = false ) {
4973 wfDeprecated( __METHOD__
, '1.24' );
4975 // Check for *really* old password hashes that don't even have a type
4976 // The old hash format was just an md5 hex hash, with no type information
4977 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4978 global $wgPasswordSalt;
4979 if ( $wgPasswordSalt ) {
4980 $password = ":B:{$userId}:{$hash}";
4982 $password = ":A:{$hash}";
4986 $passwordFactory = new PasswordFactory();
4987 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4988 $hash = $passwordFactory->newFromCiphertext( $hash );
4989 return $hash->equals( $password );
4993 * Add a newuser log entry for this user.
4994 * Before 1.19 the return value was always true.
4996 * @param string|bool $action Account creation type.
4997 * - String, one of the following values:
4998 * - 'create' for an anonymous user creating an account for himself.
4999 * This will force the action's performer to be the created user itself,
5000 * no matter the value of $wgUser
5001 * - 'create2' for a logged in user creating an account for someone else
5002 * - 'byemail' when the created user will receive its password by e-mail
5003 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5004 * - Boolean means whether the account was created by e-mail (deprecated):
5005 * - true will be converted to 'byemail'
5006 * - false will be converted to 'create' if this object is the same as
5007 * $wgUser and to 'create2' otherwise
5009 * @param string $reason User supplied reason
5011 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
5013 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5014 global $wgUser, $wgNewUserLog;
5015 if ( empty( $wgNewUserLog ) ) {
5016 return true; // disabled
5019 if ( $action === true ) {
5020 $action = 'byemail';
5021 } elseif ( $action === false ) {
5022 if ( $this->equals( $wgUser ) ) {
5025 $action = 'create2';
5029 if ( $action === 'create' ||
$action === 'autocreate' ) {
5032 $performer = $wgUser;
5035 $logEntry = new ManualLogEntry( 'newusers', $action );
5036 $logEntry->setPerformer( $performer );
5037 $logEntry->setTarget( $this->getUserPage() );
5038 $logEntry->setComment( $reason );
5039 $logEntry->setParameters( array(
5040 '4::userid' => $this->getId(),
5042 $logid = $logEntry->insert();
5044 if ( $action !== 'autocreate' ) {
5045 $logEntry->publish( $logid );
5052 * Add an autocreate newuser log entry for this user
5053 * Used by things like CentralAuth and perhaps other authplugins.
5054 * Consider calling addNewUserLogEntry() directly instead.
5058 public function addNewUserLogEntryAutoCreate() {
5059 $this->addNewUserLogEntry( 'autocreate' );
5065 * Load the user options either from cache, the database or an array
5067 * @param array $data Rows for the current user out of the user_properties table
5069 protected function loadOptions( $data = null ) {
5074 if ( $this->mOptionsLoaded
) {
5078 $this->mOptions
= self
::getDefaultOptions();
5080 if ( !$this->getId() ) {
5081 // For unlogged-in users, load language/variant options from request.
5082 // There's no need to do it for logged-in users: they can set preferences,
5083 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5084 // so don't override user's choice (especially when the user chooses site default).
5085 $variant = $wgContLang->getDefaultVariant();
5086 $this->mOptions
['variant'] = $variant;
5087 $this->mOptions
['language'] = $variant;
5088 $this->mOptionsLoaded
= true;
5092 // Maybe load from the object
5093 if ( !is_null( $this->mOptionOverrides
) ) {
5094 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5095 foreach ( $this->mOptionOverrides
as $key => $value ) {
5096 $this->mOptions
[$key] = $value;
5099 if ( !is_array( $data ) ) {
5100 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5101 // Load from database
5102 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5103 ?
wfGetDB( DB_MASTER
)
5104 : wfGetDB( DB_SLAVE
);
5106 $res = $dbr->select(
5108 array( 'up_property', 'up_value' ),
5109 array( 'up_user' => $this->getId() ),
5113 $this->mOptionOverrides
= array();
5115 foreach ( $res as $row ) {
5116 $data[$row->up_property
] = $row->up_value
;
5119 foreach ( $data as $property => $value ) {
5120 $this->mOptionOverrides
[$property] = $value;
5121 $this->mOptions
[$property] = $value;
5125 $this->mOptionsLoaded
= true;
5127 Hooks
::run( 'UserLoadOptions', array( $this, &$this->mOptions
) );
5131 * Saves the non-default options for this user, as previously set e.g. via
5132 * setOption(), in the database's "user_properties" (preferences) table.
5133 * Usually used via saveSettings().
5135 protected function saveOptions() {
5136 $this->loadOptions();
5138 // Not using getOptions(), to keep hidden preferences in database
5139 $saveOptions = $this->mOptions
;
5141 // Allow hooks to abort, for instance to save to a global profile.
5142 // Reset options to default state before saving.
5143 if ( !Hooks
::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5147 $userId = $this->getId();
5149 $insert_rows = array(); // all the new preference rows
5150 foreach ( $saveOptions as $key => $value ) {
5151 // Don't bother storing default values
5152 $defaultOption = self
::getDefaultOption( $key );
5153 if ( ( $defaultOption === null && $value !== false && $value !== null )
5154 ||
$value != $defaultOption
5156 $insert_rows[] = array(
5157 'up_user' => $userId,
5158 'up_property' => $key,
5159 'up_value' => $value,
5164 $dbw = wfGetDB( DB_MASTER
);
5166 $res = $dbw->select( 'user_properties',
5167 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
5169 // Find prior rows that need to be removed or updated. These rows will
5170 // all be deleted (the later so that INSERT IGNORE applies the new values).
5171 $keysDelete = array();
5172 foreach ( $res as $row ) {
5173 if ( !isset( $saveOptions[$row->up_property
] )
5174 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5176 $keysDelete[] = $row->up_property
;
5180 if ( count( $keysDelete ) ) {
5181 // Do the DELETE by PRIMARY KEY for prior rows.
5182 // In the past a very large portion of calls to this function are for setting
5183 // 'rememberpassword' for new accounts (a preference that has since been removed).
5184 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5185 // caused gap locks on [max user ID,+infinity) which caused high contention since
5186 // updates would pile up on each other as they are for higher (newer) user IDs.
5187 // It might not be necessary these days, but it shouldn't hurt either.
5188 $dbw->delete( 'user_properties',
5189 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
5191 // Insert the new preference rows
5192 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
5196 * Lazily instantiate and return a factory object for making passwords
5198 * @deprecated since 1.27, create a PasswordFactory directly instead
5199 * @return PasswordFactory
5201 public static function getPasswordFactory() {
5202 wfDeprecated( __METHOD__
, '1.27' );
5203 $ret = new PasswordFactory();
5204 $ret->init( RequestContext
::getMain()->getConfig() );
5209 * Provide an array of HTML5 attributes to put on an input element
5210 * intended for the user to enter a new password. This may include
5211 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5213 * Do *not* use this when asking the user to enter his current password!
5214 * Regardless of configuration, users may have invalid passwords for whatever
5215 * reason (e.g., they were set before requirements were tightened up).
5216 * Only use it when asking for a new password, like on account creation or
5219 * Obviously, you still need to do server-side checking.
5221 * NOTE: A combination of bugs in various browsers means that this function
5222 * actually just returns array() unconditionally at the moment. May as
5223 * well keep it around for when the browser bugs get fixed, though.
5225 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5227 * @deprecated since 1.27
5228 * @return array Array of HTML attributes suitable for feeding to
5229 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5230 * That will get confused by the boolean attribute syntax used.)
5232 public static function passwordChangeInputAttribs() {
5233 global $wgMinimalPasswordLength;
5235 if ( $wgMinimalPasswordLength == 0 ) {
5239 # Note that the pattern requirement will always be satisfied if the
5240 # input is empty, so we need required in all cases.
5242 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5243 # if e-mail confirmation is being used. Since HTML5 input validation
5244 # is b0rked anyway in some browsers, just return nothing. When it's
5245 # re-enabled, fix this code to not output required for e-mail
5247 # $ret = array( 'required' );
5250 # We can't actually do this right now, because Opera 9.6 will print out
5251 # the entered password visibly in its error message! When other
5252 # browsers add support for this attribute, or Opera fixes its support,
5253 # we can add support with a version check to avoid doing this on Opera
5254 # versions where it will be a problem. Reported to Opera as
5255 # DSK-262266, but they don't have a public bug tracker for us to follow.
5257 if ( $wgMinimalPasswordLength > 1 ) {
5258 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5259 $ret['title'] = wfMessage( 'passwordtooshort' )
5260 ->numParams( $wgMinimalPasswordLength )->text();
5268 * Return the list of user fields that should be selected to create
5269 * a new user object.
5272 public static function selectFields() {
5280 'user_email_authenticated',
5282 'user_email_token_expires',
5283 'user_registration',
5289 * Factory function for fatal permission-denied errors
5292 * @param string $permission User right required
5295 static function newFatalPermissionDeniedStatus( $permission ) {
5298 $groups = array_map(
5299 array( 'User', 'makeGroupLinkWiki' ),
5300 User
::getGroupsWithPermission( $permission )
5304 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5306 return Status
::newFatal( 'badaccess-group0' );
5311 * Checks if two user objects point to the same user.
5317 public function equals( User
$user ) {
5318 return $this->getName() === $user->getName();