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 */
190 * These fields were marked "@private", but were defined as public to
191 * maintain compatibility with PHP4 code since PHP4 didn't support access
192 * restrictions. AuthManager makes password handling pluggable, meaning
193 * these fields don't make sense anymore. If this broke something, see
194 * T89459 for the context of the change.
195 * @deprecated These are mostly unused, but kept for now to raise errors on attempted access.
198 private $mPassword = null;
199 private $mNewpassword;
200 private $mNewpassTime;
201 private $mPasswordExpires;
206 /** @var string TS_MW timestamp from the DB */
208 /** @var string TS_MW timestamp from cache */
209 protected $mQuickTouched;
213 public $mEmailAuthenticated;
215 protected $mEmailToken;
217 protected $mEmailTokenExpires;
219 protected $mRegistration;
221 protected $mEditCount;
225 protected $mOptionOverrides;
229 * Bool Whether the cache variables have been loaded.
232 public $mOptionsLoaded;
235 * Array with already loaded items or true if all items have been loaded.
237 protected $mLoadedItems = array();
241 * String Initialization data source if mLoadedItems!==true. May be one of:
242 * - 'defaults' anonymous user initialised from class defaults
243 * - 'name' initialise from mName
244 * - 'id' initialise from mId
245 * - 'session' log in from cookies or session if possible
247 * Use the User::newFrom*() family of functions to set this.
252 * Lazy-initialized variables, invalidated with clearInstanceCache
256 protected $mDatePreference;
264 protected $mBlockreason;
266 protected $mEffectiveGroups;
268 protected $mImplicitGroups;
270 protected $mFormerGroups;
272 protected $mBlockedGlobally;
289 protected $mAllowUsertalk;
292 private $mBlockedFromCreateAccount = false;
295 private $mWatchedItems = array();
297 /** @var integer User::READ_* constant bitfield used to load data */
298 protected $queryFlagsUsed = self
::READ_NORMAL
;
300 public static $idCacheByName = array();
303 * Lightweight constructor for an anonymous user.
304 * Use the User::newFrom* factory functions for other kinds of users.
308 * @see newFromConfirmationCode()
309 * @see newFromSession()
312 public function __construct() {
313 $this->clearInstanceCache( 'defaults' );
319 public function __toString() {
320 return $this->getName();
324 * Load the user table data for this object from the source given by mFrom.
326 * @param integer $flags User::READ_* constant bitfield
328 public function load( $flags = self
::READ_NORMAL
) {
329 if ( $this->mLoadedItems
=== true ) {
333 // Set it now to avoid infinite recursion in accessors
334 $this->mLoadedItems
= true;
335 $this->queryFlagsUsed
= $flags;
337 switch ( $this->mFrom
) {
339 $this->loadDefaults();
342 // Make sure this thread sees its own changes
343 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
344 $flags |
= self
::READ_LATEST
;
345 $this->queryFlagsUsed
= $flags;
348 $this->mId
= self
::idFromName( $this->mName
, $flags );
350 // Nonexistent user placeholder object
351 $this->loadDefaults( $this->mName
);
353 $this->loadFromId( $flags );
357 $this->loadFromId( $flags );
360 if ( !$this->loadFromSession() ) {
361 // Loading from session failed. Load defaults.
362 $this->loadDefaults();
364 Hooks
::run( 'UserLoadAfterLoadFromSession', array( $this ) );
367 throw new UnexpectedValueException(
368 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
373 * Load user table data, given mId has already been set.
374 * @param integer $flags User::READ_* constant bitfield
375 * @return bool False if the ID does not exist, true otherwise
377 public function loadFromId( $flags = self
::READ_NORMAL
) {
378 if ( $this->mId
== 0 ) {
379 $this->loadDefaults();
383 // Try cache (unless this needs data from the master DB).
384 // NOTE: if this thread called saveSettings(), the cache was cleared.
385 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
386 if ( $latest ||
!$this->loadFromCache() ) {
387 wfDebug( "User: cache miss for user {$this->mId}\n" );
388 // Load from DB (make sure this thread sees its own changes)
389 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
390 $flags |
= self
::READ_LATEST
;
392 if ( !$this->loadFromDatabase( $flags ) ) {
393 // Can't load from ID, user is anonymous
396 $this->saveToCache();
399 $this->mLoadedItems
= true;
400 $this->queryFlagsUsed
= $flags;
406 * Load user data from shared cache, given mId has already been set.
408 * @return bool false if the ID does not exist or data is invalid, true otherwise
411 protected function loadFromCache() {
412 if ( $this->mId
== 0 ) {
413 $this->loadDefaults();
417 $key = wfMemcKey( 'user', 'id', $this->mId
);
418 $data = ObjectCache
::getMainWANInstance()->get( $key );
419 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
424 wfDebug( "User: got user {$this->mId} from cache\n" );
426 // Restore from cache
427 foreach ( self
::$mCacheVars as $name ) {
428 $this->$name = $data[$name];
435 * Save user data to the shared cache
437 * This method should not be called outside the User class
439 public function saveToCache() {
442 $this->loadOptions();
444 if ( $this->isAnon() ) {
445 // Anonymous users are uncached
450 foreach ( self
::$mCacheVars as $name ) {
451 $data[$name] = $this->$name;
453 $data['mVersion'] = self
::VERSION
;
454 $key = wfMemcKey( 'user', 'id', $this->mId
);
456 $opts = Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
457 ObjectCache
::getMainWANInstance()->set( $key, $data, 3600, $opts );
460 /** @name newFrom*() static factory methods */
464 * Static factory method for creation from username.
466 * This is slightly less efficient than newFromId(), so use newFromId() if
467 * you have both an ID and a name handy.
469 * @param string $name Username, validated by Title::newFromText()
470 * @param string|bool $validate Validate username. Takes the same parameters as
471 * User::getCanonicalName(), except that true is accepted as an alias
472 * for 'valid', for BC.
474 * @return User|bool User object, or false if the username is invalid
475 * (e.g. if it contains illegal characters or is an IP address). If the
476 * username is not present in the database, the result will be a user object
477 * with a name, zero user ID and default settings.
479 public static function newFromName( $name, $validate = 'valid' ) {
480 if ( $validate === true ) {
483 $name = self
::getCanonicalName( $name, $validate );
484 if ( $name === false ) {
487 // Create unloaded user object
491 $u->setItemLoaded( 'name' );
497 * Static factory method for creation from a given user ID.
499 * @param int $id Valid user ID
500 * @return User The corresponding User object
502 public static function newFromId( $id ) {
506 $u->setItemLoaded( 'id' );
511 * Factory method to fetch whichever user has a given email confirmation code.
512 * This code is generated when an account is created or its e-mail address
515 * If the code is invalid or has expired, returns NULL.
517 * @param string $code Confirmation code
518 * @param int $flags User::READ_* bitfield
521 public static function newFromConfirmationCode( $code, $flags = 0 ) {
522 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
523 ?
wfGetDB( DB_MASTER
)
524 : wfGetDB( DB_SLAVE
);
526 $id = $db->selectField(
530 'user_email_token' => md5( $code ),
531 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
535 return $id ? User
::newFromId( $id ) : null;
539 * Create a new user object using data from session or cookies. If the
540 * login credentials are invalid, the result is an anonymous user.
542 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
545 public static function newFromSession( WebRequest
$request = null ) {
547 $user->mFrom
= 'session';
548 $user->mRequest
= $request;
553 * Create a new user object from a user row.
554 * The row should have the following fields from the user table in it:
555 * - either user_name or user_id to load further data if needed (or both)
557 * - all other fields (email, etc.)
558 * It is useless to provide the remaining fields if either user_id,
559 * user_name and user_real_name are not provided because the whole row
560 * will be loaded once more from the database when accessing them.
562 * @param stdClass $row A row from the user table
563 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
566 public static function newFromRow( $row, $data = null ) {
568 $user->loadFromRow( $row, $data );
573 * Static factory method for creation of a "system" user from username.
575 * A "system" user is an account that's used to attribute logged actions
576 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
577 * might include the 'Maintenance script' or 'Conversion script' accounts
578 * used by various scripts in the maintenance/ directory or accounts such
579 * as 'MediaWiki message delivery' used by the MassMessage extension.
581 * This can optionally create the user if it doesn't exist, and "steal" the
582 * account if it does exist.
584 * @param string $name Username
585 * @param array $options Options are:
586 * - validate: As for User::getCanonicalName(), default 'valid'
587 * - create: Whether to create the user if it doesn't already exist, default true
588 * - steal: Whether to reset the account's password and email if it
589 * already exists, default false
592 public static function newSystemUser( $name, $options = array() ) {
594 'validate' => 'valid',
599 $name = self
::getCanonicalName( $name, $options['validate'] );
600 if ( $name === false ) {
604 $dbw = wfGetDB( DB_MASTER
);
605 $row = $dbw->selectRow(
608 self
::selectFields(),
609 array( 'user_password', 'user_newpassword' )
611 array( 'user_name' => $name ),
615 // No user. Create it?
616 return $options['create'] ? self
::createNew( $name ) : null;
618 $user = self
::newFromRow( $row );
620 // A user is considered to exist as a non-system user if it has a
621 // password set, or a temporary password set, or an email set.
622 $passwordFactory = new PasswordFactory();
623 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
625 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
626 } catch ( PasswordError
$e ) {
627 wfDebug( 'Invalid password hash found in database.' );
628 $password = PasswordFactory
::newInvalidPassword();
631 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
632 } catch ( PasswordError
$e ) {
633 wfDebug( 'Invalid password hash found in database.' );
634 $newpassword = PasswordFactory
::newInvalidPassword();
636 if ( !$password instanceof InvalidPassword ||
!$newpassword instanceof InvalidPassword
639 // User exists. Steal it?
640 if ( !$options['steal'] ) {
644 $nopass = PasswordFactory
::newInvalidPassword()->toString();
649 'user_password' => $nopass,
650 'user_newpassword' => $nopass,
651 'user_newpass_time' => null,
653 array( 'user_id' => $user->getId() ),
656 $user->invalidateEmail();
657 $user->saveSettings();
666 * Get the username corresponding to a given user ID
667 * @param int $id User ID
668 * @return string|bool The corresponding username
670 public static function whoIs( $id ) {
671 return UserCache
::singleton()->getProp( $id, 'name' );
675 * Get the real name of a user given their user ID
677 * @param int $id User ID
678 * @return string|bool The corresponding user's real name
680 public static function whoIsReal( $id ) {
681 return UserCache
::singleton()->getProp( $id, 'real_name' );
685 * Get database id given a user name
686 * @param string $name Username
687 * @param integer $flags User::READ_* constant bitfield
688 * @return int|null The corresponding user's ID, or null if user is nonexistent
690 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
691 $nt = Title
::makeTitleSafe( NS_USER
, $name );
692 if ( is_null( $nt ) ) {
697 if ( isset( self
::$idCacheByName[$name] ) ) {
698 return self
::$idCacheByName[$name];
701 $db = ( $flags & self
::READ_LATEST
)
702 ?
wfGetDB( DB_MASTER
)
703 : wfGetDB( DB_SLAVE
);
708 array( 'user_name' => $nt->getText() ),
712 if ( $s === false ) {
715 $result = $s->user_id
;
718 self
::$idCacheByName[$name] = $result;
720 if ( count( self
::$idCacheByName ) > 1000 ) {
721 self
::$idCacheByName = array();
728 * Reset the cache used in idFromName(). For use in tests.
730 public static function resetIdByNameCache() {
731 self
::$idCacheByName = array();
735 * Does the string match an anonymous IPv4 address?
737 * This function exists for username validation, in order to reject
738 * usernames which are similar in form to IP addresses. Strings such
739 * as 300.300.300.300 will return true because it looks like an IP
740 * address, despite not being strictly valid.
742 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
743 * address because the usemod software would "cloak" anonymous IP
744 * addresses like this, if we allowed accounts like this to be created
745 * new users could get the old edits of these anonymous users.
747 * @param string $name Name to match
750 public static function isIP( $name ) {
751 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
752 || IP
::isIPv6( $name );
756 * Is the input a valid username?
758 * Checks if the input is a valid username, we don't want an empty string,
759 * an IP address, anything that contains slashes (would mess up subpages),
760 * is longer than the maximum allowed username size or doesn't begin with
763 * @param string $name Name to match
766 public static function isValidUserName( $name ) {
767 global $wgContLang, $wgMaxNameChars;
770 || User
::isIP( $name )
771 ||
strpos( $name, '/' ) !== false
772 ||
strlen( $name ) > $wgMaxNameChars
773 ||
$name != $wgContLang->ucfirst( $name )
775 wfDebugLog( 'username', __METHOD__
.
776 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
780 // Ensure that the name can't be misresolved as a different title,
781 // such as with extra namespace keys at the start.
782 $parsed = Title
::newFromText( $name );
783 if ( is_null( $parsed )
784 ||
$parsed->getNamespace()
785 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
786 wfDebugLog( 'username', __METHOD__
.
787 ": '$name' invalid due to ambiguous prefixes" );
791 // Check an additional blacklist of troublemaker characters.
792 // Should these be merged into the title char list?
793 $unicodeBlacklist = '/[' .
794 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
795 '\x{00a0}' . # non-breaking space
796 '\x{2000}-\x{200f}' . # various whitespace
797 '\x{2028}-\x{202f}' . # breaks and control chars
798 '\x{3000}' . # ideographic space
799 '\x{e000}-\x{f8ff}' . # private use
801 if ( preg_match( $unicodeBlacklist, $name ) ) {
802 wfDebugLog( 'username', __METHOD__
.
803 ": '$name' invalid due to blacklisted characters" );
811 * Usernames which fail to pass this function will be blocked
812 * from user login and new account registrations, but may be used
813 * internally by batch processes.
815 * If an account already exists in this form, login will be blocked
816 * by a failure to pass this function.
818 * @param string $name Name to match
821 public static function isUsableName( $name ) {
822 global $wgReservedUsernames;
823 // Must be a valid username, obviously ;)
824 if ( !self
::isValidUserName( $name ) ) {
828 static $reservedUsernames = false;
829 if ( !$reservedUsernames ) {
830 $reservedUsernames = $wgReservedUsernames;
831 Hooks
::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
834 // Certain names may be reserved for batch processes.
835 foreach ( $reservedUsernames as $reserved ) {
836 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
837 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
839 if ( $reserved == $name ) {
847 * Usernames which fail to pass this function will be blocked
848 * from new account registrations, but may be used internally
849 * either by batch processes or by user accounts which have
850 * already been created.
852 * Additional blacklisting may be added here rather than in
853 * isValidUserName() to avoid disrupting existing accounts.
855 * @param string $name String to match
858 public static function isCreatableName( $name ) {
859 global $wgInvalidUsernameCharacters;
861 // Ensure that the username isn't longer than 235 bytes, so that
862 // (at least for the builtin skins) user javascript and css files
863 // will work. (bug 23080)
864 if ( strlen( $name ) > 235 ) {
865 wfDebugLog( 'username', __METHOD__
.
866 ": '$name' invalid due to length" );
870 // Preg yells if you try to give it an empty string
871 if ( $wgInvalidUsernameCharacters !== '' ) {
872 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
873 wfDebugLog( 'username', __METHOD__
.
874 ": '$name' invalid due to wgInvalidUsernameCharacters" );
879 return self
::isUsableName( $name );
883 * Is the input a valid password for this user?
885 * @param string $password Desired password
888 public function isValidPassword( $password ) {
889 // simple boolean wrapper for getPasswordValidity
890 return $this->getPasswordValidity( $password ) === true;
895 * Given unvalidated password input, return error message on failure.
897 * @param string $password Desired password
898 * @return bool|string|array True on success, string or array of error message on failure
900 public function getPasswordValidity( $password ) {
901 $result = $this->checkPasswordValidity( $password );
902 if ( $result->isGood() ) {
906 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
907 $messages[] = $error['message'];
909 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
910 $messages[] = $warning['message'];
912 if ( count( $messages ) === 1 ) {
920 * Check if this is a valid password for this user
922 * Create a Status object based on the password's validity.
923 * The Status should be set to fatal if the user should not
924 * be allowed to log in, and should have any errors that
925 * would block changing the password.
927 * If the return value of this is not OK, the password
928 * should not be checked. If the return value is not Good,
929 * the password can be checked, but the user should not be
930 * able to set their password to this.
932 * @param string $password Desired password
933 * @param string $purpose one of 'login', 'create', 'reset'
937 public function checkPasswordValidity( $password, $purpose = 'login' ) {
938 global $wgPasswordPolicy;
940 $upp = new UserPasswordPolicy(
941 $wgPasswordPolicy['policies'],
942 $wgPasswordPolicy['checks']
945 $status = Status
::newGood();
946 $result = false; // init $result to false for the internal checks
948 if ( !Hooks
::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
949 $status->error( $result );
953 if ( $result === false ) {
954 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
956 } elseif ( $result === true ) {
959 $status->error( $result );
960 return $status; // the isValidPassword hook set a string $result and returned true
965 * Given unvalidated user input, return a canonical username, or false if
966 * the username is invalid.
967 * @param string $name User input
968 * @param string|bool $validate Type of validation to use:
969 * - false No validation
970 * - 'valid' Valid for batch processes
971 * - 'usable' Valid for batch processes and login
972 * - 'creatable' Valid for batch processes, login and account creation
974 * @throws InvalidArgumentException
975 * @return bool|string
977 public static function getCanonicalName( $name, $validate = 'valid' ) {
978 // Force usernames to capital
980 $name = $wgContLang->ucfirst( $name );
982 # Reject names containing '#'; these will be cleaned up
983 # with title normalisation, but then it's too late to
985 if ( strpos( $name, '#' ) !== false ) {
989 // Clean up name according to title rules,
990 // but only when validation is requested (bug 12654)
991 $t = ( $validate !== false ) ?
992 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
993 // Check for invalid titles
994 if ( is_null( $t ) ) {
998 // Reject various classes of invalid names
1000 $name = $wgAuth->getCanonicalName( $t->getText() );
1002 switch ( $validate ) {
1006 if ( !User
::isValidUserName( $name ) ) {
1011 if ( !User
::isUsableName( $name ) ) {
1016 if ( !User
::isCreatableName( $name ) ) {
1021 throw new InvalidArgumentException(
1022 'Invalid parameter value for $validate in ' . __METHOD__
);
1028 * Count the number of edits of a user
1030 * @param int $uid User ID to check
1031 * @return int The user's edit count
1033 * @deprecated since 1.21 in favour of User::getEditCount
1035 public static function edits( $uid ) {
1036 wfDeprecated( __METHOD__
, '1.21' );
1037 $user = self
::newFromId( $uid );
1038 return $user->getEditCount();
1042 * Return a random password.
1044 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1045 * @return string New random password
1047 public static function randomPassword() {
1048 global $wgMinimalPasswordLength;
1049 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1053 * Set cached properties to default.
1055 * @note This no longer clears uncached lazy-initialised properties;
1056 * the constructor does that instead.
1058 * @param string|bool $name
1060 public function loadDefaults( $name = false ) {
1062 $this->mName
= $name;
1063 $this->mRealName
= '';
1065 $this->mOptionOverrides
= null;
1066 $this->mOptionsLoaded
= false;
1068 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1069 if ( $loggedOut !== null ) {
1070 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1072 $this->mTouched
= '1'; # Allow any pages to be cached
1075 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1076 $this->mEmailAuthenticated
= null;
1077 $this->mEmailToken
= '';
1078 $this->mEmailTokenExpires
= null;
1079 $this->mRegistration
= wfTimestamp( TS_MW
);
1080 $this->mGroups
= array();
1082 Hooks
::run( 'UserLoadDefaults', array( $this, $name ) );
1086 * Return whether an item has been loaded.
1088 * @param string $item Item to check. Current possibilities:
1092 * @param string $all 'all' to check if the whole object has been loaded
1093 * or any other string to check if only the item is available (e.g.
1097 public function isItemLoaded( $item, $all = 'all' ) {
1098 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1099 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1103 * Set that an item has been loaded
1105 * @param string $item
1107 protected function setItemLoaded( $item ) {
1108 if ( is_array( $this->mLoadedItems
) ) {
1109 $this->mLoadedItems
[$item] = true;
1114 * Load user data from the session or login cookie.
1116 * @return bool True if the user is logged in, false otherwise.
1118 private function loadFromSession() {
1120 Hooks
::run( 'UserLoadFromSession', array( $this, &$result ) );
1121 if ( $result !== null ) {
1125 $request = $this->getRequest();
1127 $cookieId = $request->getCookie( 'UserID' );
1128 $sessId = $request->getSessionData( 'wsUserID' );
1130 if ( $cookieId !== null ) {
1131 $sId = intval( $cookieId );
1132 if ( $sessId !== null && $cookieId != $sessId ) {
1133 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1134 cookie user ID ($sId) don't match!" );
1137 $request->setSessionData( 'wsUserID', $sId );
1138 } elseif ( $sessId !== null && $sessId != 0 ) {
1144 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1145 $sName = $request->getSessionData( 'wsUserName' );
1146 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1147 $sName = $request->getCookie( 'UserName' );
1148 $request->setSessionData( 'wsUserName', $sName );
1153 $proposedUser = User
::newFromId( $sId );
1154 if ( !$proposedUser->isLoggedIn() ) {
1159 global $wgBlockDisablesLogin;
1160 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1161 // User blocked and we've disabled blocked user logins
1165 if ( $request->getSessionData( 'wsToken' ) ) {
1167 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1169 } elseif ( $request->getCookie( 'Token' ) ) {
1170 # Get the token from DB/cache and clean it up to remove garbage padding.
1171 # This deals with historical problems with bugs and the default column value.
1172 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1173 // Make comparison in constant time (bug 61346)
1174 $passwordCorrect = strlen( $token )
1175 && hash_equals( $token, $request->getCookie( 'Token' ) );
1178 // No session or persistent login cookie
1182 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1183 $this->loadFromUserObject( $proposedUser );
1184 $request->setSessionData( 'wsToken', $this->mToken
);
1185 wfDebug( "User: logged in from $from\n" );
1188 // Invalid credentials
1189 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1195 * Load user and user_group data from the database.
1196 * $this->mId must be set, this is how the user is identified.
1198 * @param integer $flags User::READ_* constant bitfield
1199 * @return bool True if the user exists, false if the user is anonymous
1201 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1203 $this->mId
= intval( $this->mId
);
1206 if ( !$this->mId
) {
1207 $this->loadDefaults();
1211 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1212 $db = wfGetDB( $index );
1214 $s = $db->selectRow(
1216 self
::selectFields(),
1217 array( 'user_id' => $this->mId
),
1222 $this->queryFlagsUsed
= $flags;
1223 Hooks
::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1225 if ( $s !== false ) {
1226 // Initialise user table data
1227 $this->loadFromRow( $s );
1228 $this->mGroups
= null; // deferred
1229 $this->getEditCount(); // revalidation for nulls
1234 $this->loadDefaults();
1240 * Initialize this object from a row from the user table.
1242 * @param stdClass $row Row from the user table to load.
1243 * @param array $data Further user data to load into the object
1245 * user_groups Array with groups out of the user_groups table
1246 * user_properties Array with properties out of the user_properties table
1248 protected function loadFromRow( $row, $data = null ) {
1251 $this->mGroups
= null; // deferred
1253 if ( isset( $row->user_name
) ) {
1254 $this->mName
= $row->user_name
;
1255 $this->mFrom
= 'name';
1256 $this->setItemLoaded( 'name' );
1261 if ( isset( $row->user_real_name
) ) {
1262 $this->mRealName
= $row->user_real_name
;
1263 $this->setItemLoaded( 'realname' );
1268 if ( isset( $row->user_id
) ) {
1269 $this->mId
= intval( $row->user_id
);
1270 $this->mFrom
= 'id';
1271 $this->setItemLoaded( 'id' );
1276 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1277 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1280 if ( isset( $row->user_editcount
) ) {
1281 $this->mEditCount
= $row->user_editcount
;
1286 if ( isset( $row->user_email
) ) {
1287 $this->mEmail
= $row->user_email
;
1288 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1289 $this->mToken
= $row->user_token
;
1290 if ( $this->mToken
== '' ) {
1291 $this->mToken
= null;
1293 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1294 $this->mEmailToken
= $row->user_email_token
;
1295 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1296 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1302 $this->mLoadedItems
= true;
1305 if ( is_array( $data ) ) {
1306 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1307 $this->mGroups
= $data['user_groups'];
1309 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1310 $this->loadOptions( $data['user_properties'] );
1316 * Load the data for this user object from another user object.
1320 protected function loadFromUserObject( $user ) {
1322 $user->loadGroups();
1323 $user->loadOptions();
1324 foreach ( self
::$mCacheVars as $var ) {
1325 $this->$var = $user->$var;
1330 * Load the groups from the database if they aren't already loaded.
1332 private function loadGroups() {
1333 if ( is_null( $this->mGroups
) ) {
1334 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1335 ?
wfGetDB( DB_MASTER
)
1336 : wfGetDB( DB_SLAVE
);
1337 $res = $db->select( 'user_groups',
1338 array( 'ug_group' ),
1339 array( 'ug_user' => $this->mId
),
1341 $this->mGroups
= array();
1342 foreach ( $res as $row ) {
1343 $this->mGroups
[] = $row->ug_group
;
1349 * Add the user to the group if he/she meets given criteria.
1351 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1352 * possible to remove manually via Special:UserRights. In such case it
1353 * will not be re-added automatically. The user will also not lose the
1354 * group if they no longer meet the criteria.
1356 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1358 * @return array Array of groups the user has been promoted to.
1360 * @see $wgAutopromoteOnce
1362 public function addAutopromoteOnceGroups( $event ) {
1363 global $wgAutopromoteOnceLogInRC, $wgAuth;
1365 if ( wfReadOnly() ||
!$this->getId() ) {
1369 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1370 if ( !count( $toPromote ) ) {
1374 if ( !$this->checkAndSetTouched() ) {
1375 return array(); // raced out (bug T48834)
1378 $oldGroups = $this->getGroups(); // previous groups
1379 foreach ( $toPromote as $group ) {
1380 $this->addGroup( $group );
1382 // update groups in external authentication database
1383 Hooks
::run( 'UserGroupsChanged', array( $this, $toPromote, array(), false ) );
1384 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1386 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1388 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1389 $logEntry->setPerformer( $this );
1390 $logEntry->setTarget( $this->getUserPage() );
1391 $logEntry->setParameters( array(
1392 '4::oldgroups' => $oldGroups,
1393 '5::newgroups' => $newGroups,
1395 $logid = $logEntry->insert();
1396 if ( $wgAutopromoteOnceLogInRC ) {
1397 $logEntry->publish( $logid );
1404 * Bump user_touched if it didn't change since this object was loaded
1406 * On success, the mTouched field is updated.
1407 * The user serialization cache is always cleared.
1409 * @return bool Whether user_touched was actually updated
1412 protected function checkAndSetTouched() {
1415 if ( !$this->mId
) {
1416 return false; // anon
1419 // Get a new user_touched that is higher than the old one
1420 $oldTouched = $this->mTouched
;
1421 $newTouched = $this->newTouchedTimestamp();
1423 $dbw = wfGetDB( DB_MASTER
);
1424 $dbw->update( 'user',
1425 array( 'user_touched' => $dbw->timestamp( $newTouched ) ),
1427 'user_id' => $this->mId
,
1428 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1432 $success = ( $dbw->affectedRows() > 0 );
1435 $this->mTouched
= $newTouched;
1436 $this->clearSharedCache();
1438 // Clears on failure too since that is desired if the cache is stale
1439 $this->clearSharedCache( 'refresh' );
1446 * Clear various cached data stored in this object. The cache of the user table
1447 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1449 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1450 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1452 public function clearInstanceCache( $reloadFrom = false ) {
1453 $this->mNewtalk
= -1;
1454 $this->mDatePreference
= null;
1455 $this->mBlockedby
= -1; # Unset
1456 $this->mHash
= false;
1457 $this->mRights
= null;
1458 $this->mEffectiveGroups
= null;
1459 $this->mImplicitGroups
= null;
1460 $this->mGroups
= null;
1461 $this->mOptions
= null;
1462 $this->mOptionsLoaded
= false;
1463 $this->mEditCount
= null;
1465 if ( $reloadFrom ) {
1466 $this->mLoadedItems
= array();
1467 $this->mFrom
= $reloadFrom;
1472 * Combine the language default options with any site-specific options
1473 * and add the default language variants.
1475 * @return array Array of String options
1477 public static function getDefaultOptions() {
1478 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1480 static $defOpt = null;
1481 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1482 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1483 // mid-request and see that change reflected in the return value of this function.
1484 // Which is insane and would never happen during normal MW operation
1488 $defOpt = $wgDefaultUserOptions;
1489 // Default language setting
1490 $defOpt['language'] = $wgContLang->getCode();
1491 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1492 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1494 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1495 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1497 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1499 Hooks
::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1505 * Get a given default option value.
1507 * @param string $opt Name of option to retrieve
1508 * @return string Default option value
1510 public static function getDefaultOption( $opt ) {
1511 $defOpts = self
::getDefaultOptions();
1512 if ( isset( $defOpts[$opt] ) ) {
1513 return $defOpts[$opt];
1520 * Get blocking information
1521 * @param bool $bFromSlave Whether to check the slave database first.
1522 * To improve performance, non-critical checks are done against slaves.
1523 * Check when actually saving should be done against master.
1525 private function getBlockedStatus( $bFromSlave = true ) {
1526 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1528 if ( -1 != $this->mBlockedby
) {
1532 wfDebug( __METHOD__
. ": checking...\n" );
1534 // Initialize data...
1535 // Otherwise something ends up stomping on $this->mBlockedby when
1536 // things get lazy-loaded later, causing false positive block hits
1537 // due to -1 !== 0. Probably session-related... Nothing should be
1538 // overwriting mBlockedby, surely?
1541 # We only need to worry about passing the IP address to the Block generator if the
1542 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1543 # know which IP address they're actually coming from
1544 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->equals( $wgUser ) ) {
1545 $ip = $this->getRequest()->getIP();
1551 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1554 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1555 && !in_array( $ip, $wgProxyWhitelist )
1558 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1560 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1561 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1562 $block->setTarget( $ip );
1563 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1565 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1566 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1567 $block->setTarget( $ip );
1571 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1572 if ( !$block instanceof Block
1573 && $wgApplyIpBlocksToXff
1575 && !$this->isAllowed( 'proxyunbannable' )
1576 && !in_array( $ip, $wgProxyWhitelist )
1578 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1579 $xff = array_map( 'trim', explode( ',', $xff ) );
1580 $xff = array_diff( $xff, array( $ip ) );
1581 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1582 $block = Block
::chooseBlock( $xffblocks, $xff );
1583 if ( $block instanceof Block
) {
1584 # Mangle the reason to alert the user that the block
1585 # originated from matching the X-Forwarded-For header.
1586 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1590 if ( $block instanceof Block
) {
1591 wfDebug( __METHOD__
. ": Found block.\n" );
1592 $this->mBlock
= $block;
1593 $this->mBlockedby
= $block->getByName();
1594 $this->mBlockreason
= $block->mReason
;
1595 $this->mHideName
= $block->mHideName
;
1596 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1598 $this->mBlockedby
= '';
1599 $this->mHideName
= 0;
1600 $this->mAllowUsertalk
= false;
1604 Hooks
::run( 'GetBlockedStatus', array( &$this ) );
1609 * Whether the given IP is in a DNS blacklist.
1611 * @param string $ip IP to check
1612 * @param bool $checkWhitelist Whether to check the whitelist first
1613 * @return bool True if blacklisted.
1615 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1616 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1618 if ( !$wgEnableDnsBlacklist ) {
1622 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1626 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1630 * Whether the given IP is in a given DNS blacklist.
1632 * @param string $ip IP to check
1633 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1634 * @return bool True if blacklisted.
1636 public function inDnsBlacklist( $ip, $bases ) {
1639 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1640 if ( IP
::isIPv4( $ip ) ) {
1641 // Reverse IP, bug 21255
1642 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1644 foreach ( (array)$bases as $base ) {
1646 // If we have an access key, use that too (ProjectHoneypot, etc.)
1648 if ( is_array( $base ) ) {
1649 if ( count( $base ) >= 2 ) {
1650 // Access key is 1, base URL is 0
1651 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1653 $host = "$ipReversed.{$base[0]}";
1655 $basename = $base[0];
1657 $host = "$ipReversed.$base";
1661 $ipList = gethostbynamel( $host );
1664 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1668 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1677 * Check if an IP address is in the local proxy list
1683 public static function isLocallyBlockedProxy( $ip ) {
1684 global $wgProxyList;
1686 if ( !$wgProxyList ) {
1690 if ( !is_array( $wgProxyList ) ) {
1691 // Load from the specified file
1692 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1695 if ( !is_array( $wgProxyList ) ) {
1697 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1699 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1700 // Old-style flipped proxy list
1709 * Is this user subject to rate limiting?
1711 * @return bool True if rate limited
1713 public function isPingLimitable() {
1714 global $wgRateLimitsExcludedIPs;
1715 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1716 // No other good way currently to disable rate limits
1717 // for specific IPs. :P
1718 // But this is a crappy hack and should die.
1721 return !$this->isAllowed( 'noratelimit' );
1725 * Primitive rate limits: enforce maximum actions per time period
1726 * to put a brake on flooding.
1728 * The method generates both a generic profiling point and a per action one
1729 * (suffix being "-$action".
1731 * @note When using a shared cache like memcached, IP-address
1732 * last-hit counters will be shared across wikis.
1734 * @param string $action Action to enforce; 'edit' if unspecified
1735 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1736 * @return bool True if a rate limiter was tripped
1738 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1739 // Call the 'PingLimiter' hook
1741 if ( !Hooks
::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1745 global $wgRateLimits;
1746 if ( !isset( $wgRateLimits[$action] ) ) {
1750 // Some groups shouldn't trigger the ping limiter, ever
1751 if ( !$this->isPingLimitable() ) {
1757 $limits = $wgRateLimits[$action];
1759 $id = $this->getId();
1762 if ( isset( $limits['anon'] ) && $id == 0 ) {
1763 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1766 if ( isset( $limits['user'] ) && $id != 0 ) {
1767 $userLimit = $limits['user'];
1769 if ( $this->isNewbie() ) {
1770 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1771 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1773 if ( isset( $limits['ip'] ) ) {
1774 $ip = $this->getRequest()->getIP();
1775 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1777 if ( isset( $limits['subnet'] ) ) {
1778 $ip = $this->getRequest()->getIP();
1781 if ( IP
::isIPv6( $ip ) ) {
1782 $parts = IP
::parseRange( "$ip/64" );
1783 $subnet = $parts[0];
1784 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1786 $subnet = $matches[1];
1788 if ( $subnet !== false ) {
1789 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1793 // Check for group-specific permissions
1794 // If more than one group applies, use the group with the highest limit
1795 foreach ( $this->getGroups() as $group ) {
1796 if ( isset( $limits[$group] ) ) {
1797 if ( $userLimit === false
1798 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1800 $userLimit = $limits[$group];
1804 // Set the user limit key
1805 if ( $userLimit !== false ) {
1806 list( $max, $period ) = $userLimit;
1807 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1808 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1812 foreach ( $keys as $key => $limit ) {
1813 list( $max, $period ) = $limit;
1814 $summary = "(limit $max in {$period}s)";
1815 $count = $wgMemc->get( $key );
1818 if ( $count >= $max ) {
1819 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1820 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1823 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1826 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1827 if ( $incrBy > 0 ) {
1828 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1831 if ( $incrBy > 0 ) {
1832 $wgMemc->incr( $key, $incrBy );
1840 * Check if user is blocked
1842 * @param bool $bFromSlave Whether to check the slave database instead of
1843 * the master. Hacked from false due to horrible probs on site.
1844 * @return bool True if blocked, false otherwise
1846 public function isBlocked( $bFromSlave = true ) {
1847 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1851 * Get the block affecting the user, or null if the user is not blocked
1853 * @param bool $bFromSlave Whether to check the slave database instead of the master
1854 * @return Block|null
1856 public function getBlock( $bFromSlave = true ) {
1857 $this->getBlockedStatus( $bFromSlave );
1858 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1862 * Check if user is blocked from editing a particular article
1864 * @param Title $title Title to check
1865 * @param bool $bFromSlave Whether to check the slave database instead of the master
1868 public function isBlockedFrom( $title, $bFromSlave = false ) {
1869 global $wgBlockAllowsUTEdit;
1871 $blocked = $this->isBlocked( $bFromSlave );
1872 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1873 // If a user's name is suppressed, they cannot make edits anywhere
1874 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1875 && $title->getNamespace() == NS_USER_TALK
) {
1877 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1880 Hooks
::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1886 * If user is blocked, return the name of the user who placed the block
1887 * @return string Name of blocker
1889 public function blockedBy() {
1890 $this->getBlockedStatus();
1891 return $this->mBlockedby
;
1895 * If user is blocked, return the specified reason for the block
1896 * @return string Blocking reason
1898 public function blockedFor() {
1899 $this->getBlockedStatus();
1900 return $this->mBlockreason
;
1904 * If user is blocked, return the ID for the block
1905 * @return int Block ID
1907 public function getBlockId() {
1908 $this->getBlockedStatus();
1909 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1913 * Check if user is blocked on all wikis.
1914 * Do not use for actual edit permission checks!
1915 * This is intended for quick UI checks.
1917 * @param string $ip IP address, uses current client if none given
1918 * @return bool True if blocked, false otherwise
1920 public function isBlockedGlobally( $ip = '' ) {
1921 if ( $this->mBlockedGlobally
!== null ) {
1922 return $this->mBlockedGlobally
;
1924 // User is already an IP?
1925 if ( IP
::isIPAddress( $this->getName() ) ) {
1926 $ip = $this->getName();
1928 $ip = $this->getRequest()->getIP();
1931 Hooks
::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1932 $this->mBlockedGlobally
= (bool)$blocked;
1933 return $this->mBlockedGlobally
;
1937 * Check if user account is locked
1939 * @return bool True if locked, false otherwise
1941 public function isLocked() {
1942 if ( $this->mLocked
!== null ) {
1943 return $this->mLocked
;
1946 $authUser = $wgAuth->getUserInstance( $this );
1947 $this->mLocked
= (bool)$authUser->isLocked();
1948 Hooks
::run( 'UserIsLocked', array( $this, &$this->mLocked
) );
1949 return $this->mLocked
;
1953 * Check if user account is hidden
1955 * @return bool True if hidden, false otherwise
1957 public function isHidden() {
1958 if ( $this->mHideName
!== null ) {
1959 return $this->mHideName
;
1961 $this->getBlockedStatus();
1962 if ( !$this->mHideName
) {
1964 $authUser = $wgAuth->getUserInstance( $this );
1965 $this->mHideName
= (bool)$authUser->isHidden();
1966 Hooks
::run( 'UserIsHidden', array( $this, &$this->mHideName
) );
1968 return $this->mHideName
;
1972 * Get the user's ID.
1973 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1975 public function getId() {
1976 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1977 // Special case, we know the user is anonymous
1979 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1980 // Don't load if this was initialized from an ID
1987 * Set the user and reload all fields according to a given ID
1988 * @param int $v User ID to reload
1990 public function setId( $v ) {
1992 $this->clearInstanceCache( 'id' );
1996 * Get the user name, or the IP of an anonymous user
1997 * @return string User's name or IP address
1999 public function getName() {
2000 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2001 // Special case optimisation
2002 return $this->mName
;
2005 if ( $this->mName
=== false ) {
2007 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2009 return $this->mName
;
2014 * Set the user name.
2016 * This does not reload fields from the database according to the given
2017 * name. Rather, it is used to create a temporary "nonexistent user" for
2018 * later addition to the database. It can also be used to set the IP
2019 * address for an anonymous user to something other than the current
2022 * @note User::newFromName() has roughly the same function, when the named user
2024 * @param string $str New user name to set
2026 public function setName( $str ) {
2028 $this->mName
= $str;
2032 * Get the user's name escaped by underscores.
2033 * @return string Username escaped by underscores.
2035 public function getTitleKey() {
2036 return str_replace( ' ', '_', $this->getName() );
2040 * Check if the user has new messages.
2041 * @return bool True if the user has new messages
2043 public function getNewtalk() {
2046 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2047 if ( $this->mNewtalk
=== -1 ) {
2048 $this->mNewtalk
= false; # reset talk page status
2050 // Check memcached separately for anons, who have no
2051 // entire User object stored in there.
2052 if ( !$this->mId
) {
2053 global $wgDisableAnonTalk;
2054 if ( $wgDisableAnonTalk ) {
2055 // Anon newtalk disabled by configuration.
2056 $this->mNewtalk
= false;
2058 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2061 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2065 return (bool)$this->mNewtalk
;
2069 * Return the data needed to construct links for new talk page message
2070 * alerts. If there are new messages, this will return an associative array
2071 * with the following data:
2072 * wiki: The database name of the wiki
2073 * link: Root-relative link to the user's talk page
2074 * rev: The last talk page revision that the user has seen or null. This
2075 * is useful for building diff links.
2076 * If there are no new messages, it returns an empty array.
2077 * @note This function was designed to accomodate multiple talk pages, but
2078 * currently only returns a single link and revision.
2081 public function getNewMessageLinks() {
2083 if ( !Hooks
::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2085 } elseif ( !$this->getNewtalk() ) {
2088 $utp = $this->getTalkPage();
2089 $dbr = wfGetDB( DB_SLAVE
);
2090 // Get the "last viewed rev" timestamp from the oldest message notification
2091 $timestamp = $dbr->selectField( 'user_newtalk',
2092 'MIN(user_last_timestamp)',
2093 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2095 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2096 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2100 * Get the revision ID for the last talk page revision viewed by the talk
2102 * @return int|null Revision ID or null
2104 public function getNewMessageRevisionId() {
2105 $newMessageRevisionId = null;
2106 $newMessageLinks = $this->getNewMessageLinks();
2107 if ( $newMessageLinks ) {
2108 // Note: getNewMessageLinks() never returns more than a single link
2109 // and it is always for the same wiki, but we double-check here in
2110 // case that changes some time in the future.
2111 if ( count( $newMessageLinks ) === 1
2112 && $newMessageLinks[0]['wiki'] === wfWikiID()
2113 && $newMessageLinks[0]['rev']
2115 /** @var Revision $newMessageRevision */
2116 $newMessageRevision = $newMessageLinks[0]['rev'];
2117 $newMessageRevisionId = $newMessageRevision->getId();
2120 return $newMessageRevisionId;
2124 * Internal uncached check for new messages
2127 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2128 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2129 * @return bool True if the user has new messages
2131 protected function checkNewtalk( $field, $id ) {
2132 $dbr = wfGetDB( DB_SLAVE
);
2134 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__
);
2136 return $ok !== false;
2140 * Add or update the new messages flag
2141 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2142 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2143 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2144 * @return bool True if successful, false otherwise
2146 protected function updateNewtalk( $field, $id, $curRev = null ) {
2147 // Get timestamp of the talk page revision prior to the current one
2148 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2149 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2150 // Mark the user as having new messages since this revision
2151 $dbw = wfGetDB( DB_MASTER
);
2152 $dbw->insert( 'user_newtalk',
2153 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2156 if ( $dbw->affectedRows() ) {
2157 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2160 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2166 * Clear the new messages flag for the given user
2167 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2168 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2169 * @return bool True if successful, false otherwise
2171 protected function deleteNewtalk( $field, $id ) {
2172 $dbw = wfGetDB( DB_MASTER
);
2173 $dbw->delete( 'user_newtalk',
2174 array( $field => $id ),
2176 if ( $dbw->affectedRows() ) {
2177 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2180 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2186 * Update the 'You have new messages!' status.
2187 * @param bool $val Whether the user has new messages
2188 * @param Revision $curRev New, as yet unseen revision of the user talk
2189 * page. Ignored if null or !$val.
2191 public function setNewtalk( $val, $curRev = null ) {
2192 if ( wfReadOnly() ) {
2197 $this->mNewtalk
= $val;
2199 if ( $this->isAnon() ) {
2201 $id = $this->getName();
2204 $id = $this->getId();
2208 $changed = $this->updateNewtalk( $field, $id, $curRev );
2210 $changed = $this->deleteNewtalk( $field, $id );
2214 $this->invalidateCache();
2219 * Generate a current or new-future timestamp to be stored in the
2220 * user_touched field when we update things.
2221 * @return string Timestamp in TS_MW format
2223 private function newTouchedTimestamp() {
2224 global $wgClockSkewFudge;
2226 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2227 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2228 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2235 * Clear user data from memcached
2237 * Use after applying updates to the database; caller's
2238 * responsibility to update user_touched if appropriate.
2240 * Called implicitly from invalidateCache() and saveSettings().
2242 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2244 public function clearSharedCache( $mode = 'changed' ) {
2245 $id = $this->getId();
2250 $key = wfMemcKey( 'user', 'id', $id );
2251 if ( $mode === 'refresh' ) {
2252 ObjectCache
::getMainWANInstance()->delete( $key, 1 );
2254 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $key ) {
2255 ObjectCache
::getMainWANInstance()->delete( $key );
2261 * Immediately touch the user data cache for this account
2263 * Calls touch() and removes account data from memcached
2265 public function invalidateCache() {
2267 $this->clearSharedCache();
2271 * Update the "touched" timestamp for the user
2273 * This is useful on various login/logout events when making sure that
2274 * a browser or proxy that has multiple tenants does not suffer cache
2275 * pollution where the new user sees the old users content. The value
2276 * of getTouched() is checked when determining 304 vs 200 responses.
2277 * Unlike invalidateCache(), this preserves the User object cache and
2278 * avoids database writes.
2282 public function touch() {
2283 $id = $this->getId();
2285 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2286 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2287 $this->mQuickTouched
= null;
2292 * Validate the cache for this account.
2293 * @param string $timestamp A timestamp in TS_MW format
2296 public function validateCache( $timestamp ) {
2297 return ( $timestamp >= $this->getTouched() );
2301 * Get the user touched timestamp
2303 * Use this value only to validate caches via inequalities
2304 * such as in the case of HTTP If-Modified-Since response logic
2306 * @return string TS_MW Timestamp
2308 public function getTouched() {
2312 if ( $this->mQuickTouched
=== null ) {
2313 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2314 $cache = ObjectCache
::getMainWANInstance();
2316 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2319 return max( $this->mTouched
, $this->mQuickTouched
);
2322 return $this->mTouched
;
2326 * Get the user_touched timestamp field (time of last DB updates)
2327 * @return string TS_MW Timestamp
2330 public function getDBTouched() {
2333 return $this->mTouched
;
2337 * @deprecated Removed in 1.27.
2341 public function getPassword() {
2342 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2346 * @deprecated Removed in 1.27.
2350 public function getTemporaryPassword() {
2351 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2355 * Set the password and reset the random token.
2356 * Calls through to authentication plugin if necessary;
2357 * will have no effect if the auth plugin refuses to
2358 * pass the change through or if the legal password
2361 * As a special case, setting the password to null
2362 * wipes it, so the account cannot be logged in until
2363 * a new password is set, for instance via e-mail.
2365 * @deprecated since 1.27. AuthManager is coming.
2366 * @param string $str New password to set
2367 * @throws PasswordError On failure
2370 public function setPassword( $str ) {
2373 if ( $str !== null ) {
2374 if ( !$wgAuth->allowPasswordChange() ) {
2375 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2378 $status = $this->checkPasswordValidity( $str );
2379 if ( !$status->isGood() ) {
2380 throw new PasswordError( $status->getMessage()->text() );
2384 if ( !$wgAuth->setPassword( $this, $str ) ) {
2385 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2389 $this->setOption( 'watchlisttoken', false );
2390 $this->setPasswordInternal( $str );
2396 * Set the password and reset the random token unconditionally.
2398 * @deprecated since 1.27. AuthManager is coming.
2399 * @param string|null $str New password to set or null to set an invalid
2400 * password hash meaning that the user will not be able to log in
2401 * through the web interface.
2403 public function setInternalPassword( $str ) {
2406 if ( $wgAuth->allowSetLocalPassword() ) {
2408 $this->setOption( 'watchlisttoken', false );
2409 $this->setPasswordInternal( $str );
2414 * Actually set the password and such
2415 * @param string|null $str New password to set or null to set an invalid
2416 * password hash meaning that the user will not be able to log in
2417 * through the web interface.
2419 private function setPasswordInternal( $str ) {
2420 $id = self
::idFromName( $this->getName() );
2422 $passwordFactory = new PasswordFactory();
2423 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2424 $dbw = wfGetDB( DB_MASTER
);
2428 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2429 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2430 'user_newpass_time' => $dbw->timestampOrNull( null ),
2437 $this->mPassword
= null;
2439 $this->mPassword
= $str;
2444 * Get the user's current token.
2445 * @param bool $forceCreation Force the generation of a new token if the
2446 * user doesn't have one (default=true for backwards compatibility).
2447 * @return string Token
2449 public function getToken( $forceCreation = true ) {
2451 if ( !$this->mToken
&& $forceCreation ) {
2454 return $this->mToken
;
2458 * Set the random token (used for persistent authentication)
2459 * Called from loadDefaults() among other places.
2461 * @param string|bool $token If specified, set the token to this value
2463 public function setToken( $token = false ) {
2466 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2468 $this->mToken
= $token;
2473 * Set the password for a password reminder or new account email
2475 * @deprecated since 1.27, AuthManager is coming
2476 * @param string $str New password to set or null to set an invalid
2477 * password hash meaning that the user will not be able to use it
2478 * @param bool $throttle If true, reset the throttle timestamp to the present
2480 public function setNewpassword( $str, $throttle = true ) {
2481 $id = $this->getId();
2483 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2486 $dbw = wfGetDB( DB_MASTER
);
2488 $passwordFactory = new PasswordFactory();
2489 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2491 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2494 if ( $str === null ) {
2495 $update['user_newpass_time'] = null;
2496 } elseif ( $throttle ) {
2497 $update['user_newpass_time'] = $dbw->timestamp();
2500 $dbw->update( 'user', $update, array( 'user_id' => $id ), __METHOD__
);
2504 * Has password reminder email been sent within the last
2505 * $wgPasswordReminderResendTime hours?
2508 public function isPasswordReminderThrottled() {
2509 global $wgPasswordReminderResendTime;
2511 if ( !$wgPasswordReminderResendTime ) {
2517 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2518 ?
wfGetDB( DB_MASTER
)
2519 : wfGetDB( DB_SLAVE
);
2520 $newpassTime = $db->selectField(
2522 'user_newpass_time',
2523 array( 'user_id' => $this->getId() ),
2527 if ( $newpassTime === null ) {
2530 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2531 return time() < $expiry;
2535 * Get the user's e-mail address
2536 * @return string User's email address
2538 public function getEmail() {
2540 Hooks
::run( 'UserGetEmail', array( $this, &$this->mEmail
) );
2541 return $this->mEmail
;
2545 * Get the timestamp of the user's e-mail authentication
2546 * @return string TS_MW timestamp
2548 public function getEmailAuthenticationTimestamp() {
2550 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2551 return $this->mEmailAuthenticated
;
2555 * Set the user's e-mail address
2556 * @param string $str New e-mail address
2558 public function setEmail( $str ) {
2560 if ( $str == $this->mEmail
) {
2563 $this->invalidateEmail();
2564 $this->mEmail
= $str;
2565 Hooks
::run( 'UserSetEmail', array( $this, &$this->mEmail
) );
2569 * Set the user's e-mail address and a confirmation mail if needed.
2572 * @param string $str New e-mail address
2575 public function setEmailWithConfirmation( $str ) {
2576 global $wgEnableEmail, $wgEmailAuthentication;
2578 if ( !$wgEnableEmail ) {
2579 return Status
::newFatal( 'emaildisabled' );
2582 $oldaddr = $this->getEmail();
2583 if ( $str === $oldaddr ) {
2584 return Status
::newGood( true );
2587 $this->setEmail( $str );
2589 if ( $str !== '' && $wgEmailAuthentication ) {
2590 // Send a confirmation request to the new address if needed
2591 $type = $oldaddr != '' ?
'changed' : 'set';
2592 $result = $this->sendConfirmationMail( $type );
2593 if ( $result->isGood() ) {
2594 // Say to the caller that a confirmation mail has been sent
2595 $result->value
= 'eauth';
2598 $result = Status
::newGood( true );
2605 * Get the user's real name
2606 * @return string User's real name
2608 public function getRealName() {
2609 if ( !$this->isItemLoaded( 'realname' ) ) {
2613 return $this->mRealName
;
2617 * Set the user's real name
2618 * @param string $str New real name
2620 public function setRealName( $str ) {
2622 $this->mRealName
= $str;
2626 * Get the user's current setting for a given option.
2628 * @param string $oname The option to check
2629 * @param string $defaultOverride A default value returned if the option does not exist
2630 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2631 * @return string User's current value for the option
2632 * @see getBoolOption()
2633 * @see getIntOption()
2635 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2636 global $wgHiddenPrefs;
2637 $this->loadOptions();
2639 # We want 'disabled' preferences to always behave as the default value for
2640 # users, even if they have set the option explicitly in their settings (ie they
2641 # set it, and then it was disabled removing their ability to change it). But
2642 # we don't want to erase the preferences in the database in case the preference
2643 # is re-enabled again. So don't touch $mOptions, just override the returned value
2644 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2645 return self
::getDefaultOption( $oname );
2648 if ( array_key_exists( $oname, $this->mOptions
) ) {
2649 return $this->mOptions
[$oname];
2651 return $defaultOverride;
2656 * Get all user's options
2658 * @param int $flags Bitwise combination of:
2659 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2660 * to the default value. (Since 1.25)
2663 public function getOptions( $flags = 0 ) {
2664 global $wgHiddenPrefs;
2665 $this->loadOptions();
2666 $options = $this->mOptions
;
2668 # We want 'disabled' preferences to always behave as the default value for
2669 # users, even if they have set the option explicitly in their settings (ie they
2670 # set it, and then it was disabled removing their ability to change it). But
2671 # we don't want to erase the preferences in the database in case the preference
2672 # is re-enabled again. So don't touch $mOptions, just override the returned value
2673 foreach ( $wgHiddenPrefs as $pref ) {
2674 $default = self
::getDefaultOption( $pref );
2675 if ( $default !== null ) {
2676 $options[$pref] = $default;
2680 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2681 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2688 * Get the user's current setting for a given option, as a boolean value.
2690 * @param string $oname The option to check
2691 * @return bool User's current value for the option
2694 public function getBoolOption( $oname ) {
2695 return (bool)$this->getOption( $oname );
2699 * Get the user's current setting for a given option, as an integer value.
2701 * @param string $oname The option to check
2702 * @param int $defaultOverride A default value returned if the option does not exist
2703 * @return int User's current value for the option
2706 public function getIntOption( $oname, $defaultOverride = 0 ) {
2707 $val = $this->getOption( $oname );
2709 $val = $defaultOverride;
2711 return intval( $val );
2715 * Set the given option for a user.
2717 * You need to call saveSettings() to actually write to the database.
2719 * @param string $oname The option to set
2720 * @param mixed $val New value to set
2722 public function setOption( $oname, $val ) {
2723 $this->loadOptions();
2725 // Explicitly NULL values should refer to defaults
2726 if ( is_null( $val ) ) {
2727 $val = self
::getDefaultOption( $oname );
2730 $this->mOptions
[$oname] = $val;
2734 * Get a token stored in the preferences (like the watchlist one),
2735 * resetting it if it's empty (and saving changes).
2737 * @param string $oname The option name to retrieve the token from
2738 * @return string|bool User's current value for the option, or false if this option is disabled.
2739 * @see resetTokenFromOption()
2741 * @deprecated 1.26 Applications should use the OAuth extension
2743 public function getTokenFromOption( $oname ) {
2744 global $wgHiddenPrefs;
2746 $id = $this->getId();
2747 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2751 $token = $this->getOption( $oname );
2753 // Default to a value based on the user token to avoid space
2754 // wasted on storing tokens for all users. When this option
2755 // is set manually by the user, only then is it stored.
2756 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2763 * Reset a token stored in the preferences (like the watchlist one).
2764 * *Does not* save user's preferences (similarly to setOption()).
2766 * @param string $oname The option name to reset the token in
2767 * @return string|bool New token value, or false if this option is disabled.
2768 * @see getTokenFromOption()
2771 public function resetTokenFromOption( $oname ) {
2772 global $wgHiddenPrefs;
2773 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2777 $token = MWCryptRand
::generateHex( 40 );
2778 $this->setOption( $oname, $token );
2783 * Return a list of the types of user options currently returned by
2784 * User::getOptionKinds().
2786 * Currently, the option kinds are:
2787 * - 'registered' - preferences which are registered in core MediaWiki or
2788 * by extensions using the UserGetDefaultOptions hook.
2789 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2790 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2791 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2792 * be used by user scripts.
2793 * - 'special' - "preferences" that are not accessible via User::getOptions
2794 * or User::setOptions.
2795 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2796 * These are usually legacy options, removed in newer versions.
2798 * The API (and possibly others) use this function to determine the possible
2799 * option types for validation purposes, so make sure to update this when a
2800 * new option kind is added.
2802 * @see User::getOptionKinds
2803 * @return array Option kinds
2805 public static function listOptionKinds() {
2808 'registered-multiselect',
2809 'registered-checkmatrix',
2817 * Return an associative array mapping preferences keys to the kind of a preference they're
2818 * used for. Different kinds are handled differently when setting or reading preferences.
2820 * See User::listOptionKinds for the list of valid option types that can be provided.
2822 * @see User::listOptionKinds
2823 * @param IContextSource $context
2824 * @param array $options Assoc. array with options keys to check as keys.
2825 * Defaults to $this->mOptions.
2826 * @return array The key => kind mapping data
2828 public function getOptionKinds( IContextSource
$context, $options = null ) {
2829 $this->loadOptions();
2830 if ( $options === null ) {
2831 $options = $this->mOptions
;
2834 $prefs = Preferences
::getPreferences( $this, $context );
2837 // Pull out the "special" options, so they don't get converted as
2838 // multiselect or checkmatrix.
2839 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2840 foreach ( $specialOptions as $name => $value ) {
2841 unset( $prefs[$name] );
2844 // Multiselect and checkmatrix options are stored in the database with
2845 // one key per option, each having a boolean value. Extract those keys.
2846 $multiselectOptions = array();
2847 foreach ( $prefs as $name => $info ) {
2848 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2849 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2850 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2851 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2853 foreach ( $opts as $value ) {
2854 $multiselectOptions["$prefix$value"] = true;
2857 unset( $prefs[$name] );
2860 $checkmatrixOptions = array();
2861 foreach ( $prefs as $name => $info ) {
2862 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2863 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2864 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2865 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2866 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2868 foreach ( $columns as $column ) {
2869 foreach ( $rows as $row ) {
2870 $checkmatrixOptions["$prefix$column-$row"] = true;
2874 unset( $prefs[$name] );
2878 // $value is ignored
2879 foreach ( $options as $key => $value ) {
2880 if ( isset( $prefs[$key] ) ) {
2881 $mapping[$key] = 'registered';
2882 } elseif ( isset( $multiselectOptions[$key] ) ) {
2883 $mapping[$key] = 'registered-multiselect';
2884 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2885 $mapping[$key] = 'registered-checkmatrix';
2886 } elseif ( isset( $specialOptions[$key] ) ) {
2887 $mapping[$key] = 'special';
2888 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2889 $mapping[$key] = 'userjs';
2891 $mapping[$key] = 'unused';
2899 * Reset certain (or all) options to the site defaults
2901 * The optional parameter determines which kinds of preferences will be reset.
2902 * Supported values are everything that can be reported by getOptionKinds()
2903 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2905 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2906 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2907 * for backwards-compatibility.
2908 * @param IContextSource|null $context Context source used when $resetKinds
2909 * does not contain 'all', passed to getOptionKinds().
2910 * Defaults to RequestContext::getMain() when null.
2912 public function resetOptions(
2913 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2914 IContextSource
$context = null
2917 $defaultOptions = self
::getDefaultOptions();
2919 if ( !is_array( $resetKinds ) ) {
2920 $resetKinds = array( $resetKinds );
2923 if ( in_array( 'all', $resetKinds ) ) {
2924 $newOptions = $defaultOptions;
2926 if ( $context === null ) {
2927 $context = RequestContext
::getMain();
2930 $optionKinds = $this->getOptionKinds( $context );
2931 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2932 $newOptions = array();
2934 // Use default values for the options that should be deleted, and
2935 // copy old values for the ones that shouldn't.
2936 foreach ( $this->mOptions
as $key => $value ) {
2937 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2938 if ( array_key_exists( $key, $defaultOptions ) ) {
2939 $newOptions[$key] = $defaultOptions[$key];
2942 $newOptions[$key] = $value;
2947 Hooks
::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2949 $this->mOptions
= $newOptions;
2950 $this->mOptionsLoaded
= true;
2954 * Get the user's preferred date format.
2955 * @return string User's preferred date format
2957 public function getDatePreference() {
2958 // Important migration for old data rows
2959 if ( is_null( $this->mDatePreference
) ) {
2961 $value = $this->getOption( 'date' );
2962 $map = $wgLang->getDatePreferenceMigrationMap();
2963 if ( isset( $map[$value] ) ) {
2964 $value = $map[$value];
2966 $this->mDatePreference
= $value;
2968 return $this->mDatePreference
;
2972 * Determine based on the wiki configuration and the user's options,
2973 * whether this user must be over HTTPS no matter what.
2977 public function requiresHTTPS() {
2978 global $wgSecureLogin;
2979 if ( !$wgSecureLogin ) {
2982 $https = $this->getBoolOption( 'prefershttps' );
2983 Hooks
::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2985 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2992 * Get the user preferred stub threshold
2996 public function getStubThreshold() {
2997 global $wgMaxArticleSize; # Maximum article size, in Kb
2998 $threshold = $this->getIntOption( 'stubthreshold' );
2999 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3000 // If they have set an impossible value, disable the preference
3001 // so we can use the parser cache again.
3008 * Get the permissions this user has.
3009 * @return array Array of String permission names
3011 public function getRights() {
3012 if ( is_null( $this->mRights
) ) {
3013 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3014 Hooks
::run( 'UserGetRights', array( $this, &$this->mRights
) );
3015 // Force reindexation of rights when a hook has unset one of them
3016 $this->mRights
= array_values( array_unique( $this->mRights
) );
3018 return $this->mRights
;
3022 * Get the list of explicit group memberships this user has.
3023 * The implicit * and user groups are not included.
3024 * @return array Array of String internal group names
3026 public function getGroups() {
3028 $this->loadGroups();
3029 return $this->mGroups
;
3033 * Get the list of implicit group memberships this user has.
3034 * This includes all explicit groups, plus 'user' if logged in,
3035 * '*' for all accounts, and autopromoted groups
3036 * @param bool $recache Whether to avoid the cache
3037 * @return array Array of String internal group names
3039 public function getEffectiveGroups( $recache = false ) {
3040 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3041 $this->mEffectiveGroups
= array_unique( array_merge(
3042 $this->getGroups(), // explicit groups
3043 $this->getAutomaticGroups( $recache ) // implicit groups
3045 // Hook for additional groups
3046 Hooks
::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
3047 // Force reindexation of groups when a hook has unset one of them
3048 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3050 return $this->mEffectiveGroups
;
3054 * Get the list of implicit group memberships this user has.
3055 * This includes 'user' if logged in, '*' for all accounts,
3056 * and autopromoted groups
3057 * @param bool $recache Whether to avoid the cache
3058 * @return array Array of String internal group names
3060 public function getAutomaticGroups( $recache = false ) {
3061 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3062 $this->mImplicitGroups
= array( '*' );
3063 if ( $this->getId() ) {
3064 $this->mImplicitGroups
[] = 'user';
3066 $this->mImplicitGroups
= array_unique( array_merge(
3067 $this->mImplicitGroups
,
3068 Autopromote
::getAutopromoteGroups( $this )
3072 // Assure data consistency with rights/groups,
3073 // as getEffectiveGroups() depends on this function
3074 $this->mEffectiveGroups
= null;
3077 return $this->mImplicitGroups
;
3081 * Returns the groups the user has belonged to.
3083 * The user may still belong to the returned groups. Compare with getGroups().
3085 * The function will not return groups the user had belonged to before MW 1.17
3087 * @return array Names of the groups the user has belonged to.
3089 public function getFormerGroups() {
3092 if ( is_null( $this->mFormerGroups
) ) {
3093 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3094 ?
wfGetDB( DB_MASTER
)
3095 : wfGetDB( DB_SLAVE
);
3096 $res = $db->select( 'user_former_groups',
3097 array( 'ufg_group' ),
3098 array( 'ufg_user' => $this->mId
),
3100 $this->mFormerGroups
= array();
3101 foreach ( $res as $row ) {
3102 $this->mFormerGroups
[] = $row->ufg_group
;
3106 return $this->mFormerGroups
;
3110 * Get the user's edit count.
3111 * @return int|null Null for anonymous users
3113 public function getEditCount() {
3114 if ( !$this->getId() ) {
3118 if ( $this->mEditCount
=== null ) {
3119 /* Populate the count, if it has not been populated yet */
3120 $dbr = wfGetDB( DB_SLAVE
);
3121 // check if the user_editcount field has been initialized
3122 $count = $dbr->selectField(
3123 'user', 'user_editcount',
3124 array( 'user_id' => $this->mId
),
3128 if ( $count === null ) {
3129 // it has not been initialized. do so.
3130 $count = $this->initEditCount();
3132 $this->mEditCount
= $count;
3134 return (int)$this->mEditCount
;
3138 * Add the user to the given group.
3139 * This takes immediate effect.
3140 * @param string $group Name of the group to add
3143 public function addGroup( $group ) {
3146 if ( !Hooks
::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3150 $dbw = wfGetDB( DB_MASTER
);
3151 if ( $this->getId() ) {
3152 $dbw->insert( 'user_groups',
3154 'ug_user' => $this->getID(),
3155 'ug_group' => $group,
3158 array( 'IGNORE' ) );
3161 $this->loadGroups();
3162 $this->mGroups
[] = $group;
3163 // In case loadGroups was not called before, we now have the right twice.
3164 // Get rid of the duplicate.
3165 $this->mGroups
= array_unique( $this->mGroups
);
3167 // Refresh the groups caches, and clear the rights cache so it will be
3168 // refreshed on the next call to $this->getRights().
3169 $this->getEffectiveGroups( true );
3170 $this->mRights
= null;
3172 $this->invalidateCache();
3178 * Remove the user from the given group.
3179 * This takes immediate effect.
3180 * @param string $group Name of the group to remove
3183 public function removeGroup( $group ) {
3185 if ( !Hooks
::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3189 $dbw = wfGetDB( DB_MASTER
);
3190 $dbw->delete( 'user_groups',
3192 'ug_user' => $this->getID(),
3193 'ug_group' => $group,
3196 // Remember that the user was in this group
3197 $dbw->insert( 'user_former_groups',
3199 'ufg_user' => $this->getID(),
3200 'ufg_group' => $group,
3206 $this->loadGroups();
3207 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3209 // Refresh the groups caches, and clear the rights cache so it will be
3210 // refreshed on the next call to $this->getRights().
3211 $this->getEffectiveGroups( true );
3212 $this->mRights
= null;
3214 $this->invalidateCache();
3220 * Get whether the user is logged in
3223 public function isLoggedIn() {
3224 return $this->getID() != 0;
3228 * Get whether the user is anonymous
3231 public function isAnon() {
3232 return !$this->isLoggedIn();
3236 * Check if user is allowed to access a feature / make an action
3238 * @param string ... Permissions to test
3239 * @return bool True if user is allowed to perform *any* of the given actions
3241 public function isAllowedAny() {
3242 $permissions = func_get_args();
3243 foreach ( $permissions as $permission ) {
3244 if ( $this->isAllowed( $permission ) ) {
3253 * @param string ... Permissions to test
3254 * @return bool True if the user is allowed to perform *all* of the given actions
3256 public function isAllowedAll() {
3257 $permissions = func_get_args();
3258 foreach ( $permissions as $permission ) {
3259 if ( !$this->isAllowed( $permission ) ) {
3267 * Internal mechanics of testing a permission
3268 * @param string $action
3271 public function isAllowed( $action = '' ) {
3272 if ( $action === '' ) {
3273 return true; // In the spirit of DWIM
3275 // Patrolling may not be enabled
3276 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3277 global $wgUseRCPatrol, $wgUseNPPatrol;
3278 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3282 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3283 // by misconfiguration: 0 == 'foo'
3284 return in_array( $action, $this->getRights(), true );
3288 * Check whether to enable recent changes patrol features for this user
3289 * @return bool True or false
3291 public function useRCPatrol() {
3292 global $wgUseRCPatrol;
3293 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3297 * Check whether to enable new pages patrol features for this user
3298 * @return bool True or false
3300 public function useNPPatrol() {
3301 global $wgUseRCPatrol, $wgUseNPPatrol;
3303 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3304 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3309 * Get the WebRequest object to use with this object
3311 * @return WebRequest
3313 public function getRequest() {
3314 if ( $this->mRequest
) {
3315 return $this->mRequest
;
3323 * Get the current skin, loading it if required
3324 * @return Skin The current skin
3325 * @todo FIXME: Need to check the old failback system [AV]
3326 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3328 public function getSkin() {
3329 wfDeprecated( __METHOD__
, '1.18' );
3330 return RequestContext
::getMain()->getSkin();
3334 * Get a WatchedItem for this user and $title.
3336 * @since 1.22 $checkRights parameter added
3337 * @param Title $title
3338 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3339 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3340 * @return WatchedItem
3342 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3343 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3345 if ( isset( $this->mWatchedItems
[$key] ) ) {
3346 return $this->mWatchedItems
[$key];
3349 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3350 $this->mWatchedItems
= array();
3353 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3354 return $this->mWatchedItems
[$key];
3358 * Check the watched status of an article.
3359 * @since 1.22 $checkRights parameter added
3360 * @param Title $title Title of the article to look at
3361 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3362 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3365 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3366 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3371 * @since 1.22 $checkRights parameter added
3372 * @param Title $title Title of the article to look at
3373 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3374 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3376 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3377 $this->getWatchedItem( $title, $checkRights )->addWatch();
3378 $this->invalidateCache();
3382 * Stop watching an article.
3383 * @since 1.22 $checkRights parameter added
3384 * @param Title $title Title of the article to look at
3385 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3386 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3388 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3389 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3390 $this->invalidateCache();
3394 * Clear the user's notification timestamp for the given title.
3395 * If e-notif e-mails are on, they will receive notification mails on
3396 * the next change of the page if it's watched etc.
3397 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3398 * @param Title $title Title of the article to look at
3399 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3401 public function clearNotification( &$title, $oldid = 0 ) {
3402 global $wgUseEnotif, $wgShowUpdatedMarker;
3404 // Do nothing if the database is locked to writes
3405 if ( wfReadOnly() ) {
3409 // Do nothing if not allowed to edit the watchlist
3410 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3414 // If we're working on user's talk page, we should update the talk page message indicator
3415 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3416 if ( !Hooks
::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3421 // Try to update the DB post-send and only if needed...
3422 DeferredUpdates
::addCallableUpdate( function() use ( $that, $title, $oldid ) {
3423 if ( !$that->getNewtalk() ) {
3424 return; // no notifications to clear
3427 // Delete the last notifications (they stack up)
3428 $that->setNewtalk( false );
3430 // If there is a new, unseen, revision, use its timestamp
3432 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3435 $that->setNewtalk( true, Revision
::newFromId( $nextid ) );
3440 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3444 if ( $this->isAnon() ) {
3445 // Nothing else to do...
3449 // Only update the timestamp if the page is being watched.
3450 // The query to find out if it is watched is cached both in memcached and per-invocation,
3451 // and when it does have to be executed, it can be on a slave
3452 // If this is the user's newtalk page, we always update the timestamp
3454 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3458 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3459 $force, $oldid, WatchedItem
::DEFERRED
3464 * Resets all of the given user's page-change notification timestamps.
3465 * If e-notif e-mails are on, they will receive notification mails on
3466 * the next change of any watched page.
3467 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3469 public function clearAllNotifications() {
3470 if ( wfReadOnly() ) {
3474 // Do nothing if not allowed to edit the watchlist
3475 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3479 global $wgUseEnotif, $wgShowUpdatedMarker;
3480 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3481 $this->setNewtalk( false );
3484 $id = $this->getId();
3486 $dbw = wfGetDB( DB_MASTER
);
3487 $dbw->update( 'watchlist',
3488 array( /* SET */ 'wl_notificationtimestamp' => null ),
3489 array( /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ),
3492 // We also need to clear here the "you have new message" notification for the own user_talk page;
3493 // it's cleared one page view later in WikiPage::doViewUpdates().
3498 * Set a cookie on the user's client. Wrapper for
3499 * WebResponse::setCookie
3500 * @param string $name Name of the cookie to set
3501 * @param string $value Value to set
3502 * @param int $exp Expiration time, as a UNIX time value;
3503 * if 0 or not specified, use the default $wgCookieExpiration
3504 * @param bool $secure
3505 * true: Force setting the secure attribute when setting the cookie
3506 * false: Force NOT setting the secure attribute when setting the cookie
3507 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3508 * @param array $params Array of options sent passed to WebResponse::setcookie()
3509 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3512 protected function setCookie(
3513 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3515 if ( $request === null ) {
3516 $request = $this->getRequest();
3518 $params['secure'] = $secure;
3519 $request->response()->setCookie( $name, $value, $exp, $params );
3523 * Clear a cookie on the user's client
3524 * @param string $name Name of the cookie to clear
3525 * @param bool $secure
3526 * true: Force setting the secure attribute when setting the cookie
3527 * false: Force NOT setting the secure attribute when setting the cookie
3528 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3529 * @param array $params Array of options sent passed to WebResponse::setcookie()
3531 protected function clearCookie( $name, $secure = null, $params = array() ) {
3532 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3536 * Set an extended login cookie on the user's client. The expiry of the cookie
3537 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3540 * @see User::setCookie
3542 * @param string $name Name of the cookie to set
3543 * @param string $value Value to set
3544 * @param bool $secure
3545 * true: Force setting the secure attribute when setting the cookie
3546 * false: Force NOT setting the secure attribute when setting the cookie
3547 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3549 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3550 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3553 $exp +
= $wgExtendedLoginCookieExpiration !== null
3554 ?
$wgExtendedLoginCookieExpiration
3555 : $wgCookieExpiration;
3557 $this->setCookie( $name, $value, $exp, $secure );
3561 * Set the default cookies for this session on the user's client.
3563 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3565 * @param bool $secure Whether to force secure/insecure cookies or use default
3566 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3568 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3569 global $wgExtendedLoginCookies;
3571 if ( $request === null ) {
3572 $request = $this->getRequest();
3576 if ( 0 == $this->mId
) {
3579 if ( !$this->mToken
) {
3580 // When token is empty or NULL generate a new one and then save it to the database
3581 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3582 // Simply by setting every cell in the user_token column to NULL and letting them be
3583 // regenerated as users log back into the wiki.
3585 if ( !wfReadOnly() ) {
3586 $this->saveSettings();
3590 'wsUserID' => $this->mId
,
3591 'wsToken' => $this->mToken
,
3592 'wsUserName' => $this->getName()
3595 'UserID' => $this->mId
,
3596 'UserName' => $this->getName(),
3598 if ( $rememberMe ) {
3599 $cookies['Token'] = $this->mToken
;
3601 $cookies['Token'] = false;
3604 Hooks
::run( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3606 foreach ( $session as $name => $value ) {
3607 $request->setSessionData( $name, $value );
3609 foreach ( $cookies as $name => $value ) {
3610 if ( $value === false ) {
3611 $this->clearCookie( $name );
3612 } elseif ( $rememberMe && in_array( $name, $wgExtendedLoginCookies ) ) {
3613 $this->setExtendedLoginCookie( $name, $value, $secure );
3615 $this->setCookie( $name, $value, 0, $secure, array(), $request );
3620 * If wpStickHTTPS was selected, also set an insecure cookie that
3621 * will cause the site to redirect the user to HTTPS, if they access
3622 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3623 * as the one set by centralauth (bug 53538). Also set it to session, or
3624 * standard time setting, based on if rememberme was set.
3626 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3630 $rememberMe ?
0 : null,
3632 array( 'prefix' => '' ) // no prefix
3638 * Log this user out.
3640 public function logout() {
3641 if ( Hooks
::run( 'UserLogout', array( &$this ) ) ) {
3647 * Clear the user's cookies and session, and reset the instance cache.
3650 public function doLogout() {
3651 $this->clearInstanceCache( 'defaults' );
3653 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3655 $this->clearCookie( 'UserID' );
3656 $this->clearCookie( 'Token' );
3657 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3659 // Remember when user logged out, to prevent seeing cached pages
3660 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3664 * Save this user's settings into the database.
3665 * @todo Only rarely do all these fields need to be set!
3667 public function saveSettings() {
3668 if ( wfReadOnly() ) {
3669 // @TODO: caller should deal with this instead!
3670 // This should really just be an exception.
3671 MWExceptionHandler
::logException( new DBExpectedError(
3673 "Could not update user with ID '{$this->mId}'; DB is read-only."
3679 if ( 0 == $this->mId
) {
3683 // Get a new user_touched that is higher than the old one.
3684 // This will be used for a CAS check as a last-resort safety
3685 // check against race conditions and slave lag.
3686 $oldTouched = $this->mTouched
;
3687 $newTouched = $this->newTouchedTimestamp();
3689 $dbw = wfGetDB( DB_MASTER
);
3690 $dbw->update( 'user',
3692 'user_name' => $this->mName
,
3693 'user_real_name' => $this->mRealName
,
3694 'user_email' => $this->mEmail
,
3695 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3696 'user_touched' => $dbw->timestamp( $newTouched ),
3697 'user_token' => strval( $this->mToken
),
3698 'user_email_token' => $this->mEmailToken
,
3699 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3700 ), array( /* WHERE */
3701 'user_id' => $this->mId
,
3702 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3706 if ( !$dbw->affectedRows() ) {
3707 // Maybe the problem was a missed cache update; clear it to be safe
3708 $this->clearSharedCache( 'refresh' );
3709 // User was changed in the meantime or loaded with stale data
3710 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3711 throw new MWException(
3712 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3713 " the version of the user to be saved is older than the current version."
3717 $this->mTouched
= $newTouched;
3718 $this->saveOptions();
3720 Hooks
::run( 'UserSaveSettings', array( $this ) );
3721 $this->clearSharedCache();
3722 $this->getUserPage()->invalidateCache();
3726 * If only this user's username is known, and it exists, return the user ID.
3728 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3731 public function idForName( $flags = 0 ) {
3732 $s = trim( $this->getName() );
3737 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3738 ?
wfGetDB( DB_MASTER
)
3739 : wfGetDB( DB_SLAVE
);
3741 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3742 ?
array( 'LOCK IN SHARE MODE' )
3745 $id = $db->selectField( 'user',
3746 'user_id', array( 'user_name' => $s ), __METHOD__
, $options );
3752 * Add a user to the database, return the user object
3754 * @param string $name Username to add
3755 * @param array $params Array of Strings Non-default parameters to save to
3756 * the database as user_* fields:
3757 * - email: The user's email address.
3758 * - email_authenticated: The email authentication timestamp.
3759 * - real_name: The user's real name.
3760 * - options: An associative array of non-default options.
3761 * - token: Random authentication token. Do not set.
3762 * - registration: Registration timestamp. Do not set.
3764 * @return User|null User object, or null if the username already exists.
3766 public static function createNew( $name, $params = array() ) {
3767 foreach ( array( 'password', 'newpassword', 'newpass_time', 'password_expires' ) as $field ) {
3768 if ( isset( $params[$field] ) ) {
3769 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3770 unset( $params[$field] );
3776 $user->setToken(); // init token
3777 if ( isset( $params['options'] ) ) {
3778 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3779 unset( $params['options'] );
3781 $dbw = wfGetDB( DB_MASTER
);
3782 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3784 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3787 'user_id' => $seqVal,
3788 'user_name' => $name,
3789 'user_password' => $noPass,
3790 'user_newpassword' => $noPass,
3791 'user_email' => $user->mEmail
,
3792 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3793 'user_real_name' => $user->mRealName
,
3794 'user_token' => strval( $user->mToken
),
3795 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3796 'user_editcount' => 0,
3797 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3799 foreach ( $params as $name => $value ) {
3800 $fields["user_$name"] = $value;
3802 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3803 if ( $dbw->affectedRows() ) {
3804 $newUser = User
::newFromId( $dbw->insertId() );
3812 * Add this existing user object to the database. If the user already
3813 * exists, a fatal status object is returned, and the user object is
3814 * initialised with the data from the database.
3816 * Previously, this function generated a DB error due to a key conflict
3817 * if the user already existed. Many extension callers use this function
3818 * in code along the lines of:
3820 * $user = User::newFromName( $name );
3821 * if ( !$user->isLoggedIn() ) {
3822 * $user->addToDatabase();
3824 * // do something with $user...
3826 * However, this was vulnerable to a race condition (bug 16020). By
3827 * initialising the user object if the user exists, we aim to support this
3828 * calling sequence as far as possible.
3830 * Note that if the user exists, this function will acquire a write lock,
3831 * so it is still advisable to make the call conditional on isLoggedIn(),
3832 * and to commit the transaction after calling.
3834 * @throws MWException
3837 public function addToDatabase() {
3839 if ( !$this->mToken
) {
3840 $this->setToken(); // init token
3843 $this->mTouched
= $this->newTouchedTimestamp();
3845 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3847 $dbw = wfGetDB( DB_MASTER
);
3848 $inWrite = $dbw->writesOrCallbacksPending();
3849 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3850 $dbw->insert( 'user',
3852 'user_id' => $seqVal,
3853 'user_name' => $this->mName
,
3854 'user_password' => $noPass,
3855 'user_newpassword' => $noPass,
3856 'user_email' => $this->mEmail
,
3857 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3858 'user_real_name' => $this->mRealName
,
3859 'user_token' => strval( $this->mToken
),
3860 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3861 'user_editcount' => 0,
3862 'user_touched' => $dbw->timestamp( $this->mTouched
),
3866 if ( !$dbw->affectedRows() ) {
3867 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3868 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3870 // Can't commit due to pending writes that may need atomicity.
3871 // This may cause some lock contention unlike the case below.
3872 $options = array( 'LOCK IN SHARE MODE' );
3873 $flags = self
::READ_LOCKING
;
3875 // Often, this case happens early in views before any writes when
3876 // using CentralAuth. It's should be OK to commit and break the snapshot.
3877 $dbw->commit( __METHOD__
, 'flush' );
3879 $flags = self
::READ_LATEST
;
3881 $this->mId
= $dbw->selectField( 'user', 'user_id',
3882 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3885 if ( $this->loadFromDatabase( $flags ) ) {
3890 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3891 "to insert user '{$this->mName}' row, but it was not present in select!" );
3893 return Status
::newFatal( 'userexists' );
3895 $this->mId
= $dbw->insertId();
3897 // Set the password now that it's in the DB, if applicable
3898 if ( $this->mPassword
!== null ) {
3899 $this->setPasswordInternal( $this->mPassword
);
3902 // Clear instance cache other than user table data, which is already accurate
3903 $this->clearInstanceCache();
3905 $this->saveOptions();
3906 return Status
::newGood();
3910 * If this user is logged-in and blocked,
3911 * block any IP address they've successfully logged in from.
3912 * @return bool A block was spread
3914 public function spreadAnyEditBlock() {
3915 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3916 return $this->spreadBlock();
3922 * If this (non-anonymous) user is blocked,
3923 * block the IP address they've successfully logged in from.
3924 * @return bool A block was spread
3926 protected function spreadBlock() {
3927 wfDebug( __METHOD__
. "()\n" );
3929 if ( $this->mId
== 0 ) {
3933 $userblock = Block
::newFromTarget( $this->getName() );
3934 if ( !$userblock ) {
3938 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3942 * Get whether the user is explicitly blocked from account creation.
3943 * @return bool|Block
3945 public function isBlockedFromCreateAccount() {
3946 $this->getBlockedStatus();
3947 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3948 return $this->mBlock
;
3951 # bug 13611: if the IP address the user is trying to create an account from is
3952 # blocked with createaccount disabled, prevent new account creation there even
3953 # when the user is logged in
3954 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3955 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3957 return $this->mBlockedFromCreateAccount
instanceof Block
3958 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3959 ?
$this->mBlockedFromCreateAccount
3964 * Get whether the user is blocked from using Special:Emailuser.
3967 public function isBlockedFromEmailuser() {
3968 $this->getBlockedStatus();
3969 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3973 * Get whether the user is allowed to create an account.
3976 public function isAllowedToCreateAccount() {
3977 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3981 * Get this user's personal page title.
3983 * @return Title User's personal page title
3985 public function getUserPage() {
3986 return Title
::makeTitle( NS_USER
, $this->getName() );
3990 * Get this user's talk page title.
3992 * @return Title User's talk page title
3994 public function getTalkPage() {
3995 $title = $this->getUserPage();
3996 return $title->getTalkPage();
4000 * Determine whether the user is a newbie. Newbies are either
4001 * anonymous IPs, or the most recently created accounts.
4004 public function isNewbie() {
4005 return !$this->isAllowed( 'autoconfirmed' );
4009 * Check to see if the given clear-text password is one of the accepted passwords
4010 * @deprecated since 1.27. AuthManager is coming.
4011 * @param string $password User password
4012 * @return bool True if the given password is correct, otherwise False
4014 public function checkPassword( $password ) {
4015 global $wgAuth, $wgLegacyEncoding;
4019 // Some passwords will give a fatal Status, which means there is
4020 // some sort of technical or security reason for this password to
4021 // be completely invalid and should never be checked (e.g., T64685)
4022 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4026 // Certain authentication plugins do NOT want to save
4027 // domain passwords in a mysql database, so we should
4028 // check this (in case $wgAuth->strict() is false).
4029 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4031 } elseif ( $wgAuth->strict() ) {
4032 // Auth plugin doesn't allow local authentication
4034 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4035 // Auth plugin doesn't allow local authentication for this user name
4039 $passwordFactory = new PasswordFactory();
4040 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4041 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4042 ?
wfGetDB( DB_MASTER
)
4043 : wfGetDB( DB_SLAVE
);
4046 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4047 'user', 'user_password', array( 'user_id' => $this->getId() ), __METHOD__
4049 } catch ( PasswordError
$e ) {
4050 wfDebug( 'Invalid password hash found in database.' );
4051 $mPassword = PasswordFactory
::newInvalidPassword();
4054 if ( !$mPassword->equals( $password ) ) {
4055 if ( $wgLegacyEncoding ) {
4056 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4057 // Check for this with iconv
4058 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4059 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4067 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4068 $this->setPasswordInternal( $password );
4075 * Check if the given clear-text password matches the temporary password
4076 * sent by e-mail for password reset operations.
4078 * @deprecated since 1.27. AuthManager is coming.
4079 * @param string $plaintext
4080 * @return bool True if matches, false otherwise
4082 public function checkTemporaryPassword( $plaintext ) {
4083 global $wgNewPasswordExpiry;
4087 $passwordFactory = new PasswordFactory();
4088 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4089 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4090 ?
wfGetDB( DB_MASTER
)
4091 : wfGetDB( DB_SLAVE
);
4093 $row = $db->selectRow(
4095 array( 'user_newpassword', 'user_newpass_time' ),
4096 array( 'user_id' => $this->getId() ),
4100 $mNewpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4101 } catch ( PasswordError
$e ) {
4102 wfDebug( 'Invalid password hash found in database.' );
4103 $mNewpassword = PasswordFactory
::newInvalidPassword();
4106 if ( $mNewpassword->equals( $plaintext ) ) {
4107 if ( is_null( $row->user_newpass_time
) ) {
4110 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4111 return ( time() < $expiry );
4118 * Alias for getEditToken.
4119 * @deprecated since 1.19, use getEditToken instead.
4121 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4122 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4123 * @return string The new edit token
4125 public function editToken( $salt = '', $request = null ) {
4126 wfDeprecated( __METHOD__
, '1.19' );
4127 return $this->getEditToken( $salt, $request );
4131 * Internal implementation for self::getEditToken() and
4132 * self::matchEditToken().
4134 * @param string|array $salt
4135 * @param WebRequest $request
4136 * @param string|int $timestamp
4139 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
4140 if ( $this->isAnon() ) {
4141 return self
::EDIT_TOKEN_SUFFIX
;
4143 $token = $request->getSessionData( 'wsEditToken' );
4144 if ( $token === null ) {
4145 $token = MWCryptRand
::generateHex( 32 );
4146 $request->setSessionData( 'wsEditToken', $token );
4148 if ( is_array( $salt ) ) {
4149 $salt = implode( '|', $salt );
4151 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
4152 dechex( $timestamp ) .
4153 self
::EDIT_TOKEN_SUFFIX
;
4158 * Initialize (if necessary) and return a session token value
4159 * which can be used in edit forms to show that the user's
4160 * login credentials aren't being hijacked with a foreign form
4165 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4166 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4167 * @return string The new edit token
4169 public function getEditToken( $salt = '', $request = null ) {
4170 return $this->getEditTokenAtTimestamp(
4171 $salt, $request ?
: $this->getRequest(), wfTimestamp()
4176 * Generate a looking random token for various uses.
4178 * @return string The new random token
4179 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
4180 * wfRandomString for pseudo-randomness.
4182 public static function generateToken() {
4183 return MWCryptRand
::generateHex( 32 );
4187 * Get the embedded timestamp from a token.
4188 * @param string $val Input token
4191 public static function getEditTokenTimestamp( $val ) {
4192 $suffixLen = strlen( self
::EDIT_TOKEN_SUFFIX
);
4193 if ( strlen( $val ) <= 32 +
$suffixLen ) {
4197 return hexdec( substr( $val, 32, -$suffixLen ) );
4201 * Check given value against the token value stored in the session.
4202 * A match should confirm that the form was submitted from the
4203 * user's own login session, not a form submission from a third-party
4206 * @param string $val Input value to compare
4207 * @param string $salt Optional function-specific data for hashing
4208 * @param WebRequest|null $request Object to use or null to use $wgRequest
4209 * @param int $maxage Fail tokens older than this, in seconds
4210 * @return bool Whether the token matches
4212 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4213 if ( $this->isAnon() ) {
4214 return $val === self
::EDIT_TOKEN_SUFFIX
;
4217 $timestamp = self
::getEditTokenTimestamp( $val );
4218 if ( $timestamp === null ) {
4221 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
4226 $sessionToken = $this->getEditTokenAtTimestamp(
4227 $salt, $request ?
: $this->getRequest(), $timestamp
4230 if ( $val != $sessionToken ) {
4231 wfDebug( "User::matchEditToken: broken session data\n" );
4234 return hash_equals( $sessionToken, $val );
4238 * Check given value against the token value stored in the session,
4239 * ignoring the suffix.
4241 * @param string $val Input value to compare
4242 * @param string $salt Optional function-specific data for hashing
4243 * @param WebRequest|null $request Object to use or null to use $wgRequest
4244 * @param int $maxage Fail tokens older than this, in seconds
4245 * @return bool Whether the token matches
4247 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4248 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4249 return $this->matchEditToken( $val, $salt, $request, $maxage );
4253 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4254 * mail to the user's given address.
4256 * @param string $type Message to send, either "created", "changed" or "set"
4259 public function sendConfirmationMail( $type = 'created' ) {
4261 $expiration = null; // gets passed-by-ref and defined in next line.
4262 $token = $this->confirmationToken( $expiration );
4263 $url = $this->confirmationTokenUrl( $token );
4264 $invalidateURL = $this->invalidationTokenUrl( $token );
4265 $this->saveSettings();
4267 if ( $type == 'created' ||
$type === false ) {
4268 $message = 'confirmemail_body';
4269 } elseif ( $type === true ) {
4270 $message = 'confirmemail_body_changed';
4272 // Messages: confirmemail_body_changed, confirmemail_body_set
4273 $message = 'confirmemail_body_' . $type;
4276 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4277 wfMessage( $message,
4278 $this->getRequest()->getIP(),
4281 $wgLang->timeanddate( $expiration, false ),
4283 $wgLang->date( $expiration, false ),
4284 $wgLang->time( $expiration, false ) )->text() );
4288 * Send an e-mail to this user's account. Does not check for
4289 * confirmed status or validity.
4291 * @param string $subject Message subject
4292 * @param string $body Message body
4293 * @param User|null $from Optional sending user; if unspecified, default
4294 * $wgPasswordSender will be used.
4295 * @param string $replyto Reply-To address
4298 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4299 global $wgPasswordSender;
4301 if ( $from instanceof User
) {
4302 $sender = MailAddress
::newFromUser( $from );
4304 $sender = new MailAddress( $wgPasswordSender,
4305 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4307 $to = MailAddress
::newFromUser( $this );
4309 return UserMailer
::send( $to, $sender, $subject, $body, array(
4310 'replyTo' => $replyto,
4315 * Generate, store, and return a new e-mail confirmation code.
4316 * A hash (unsalted, since it's used as a key) is stored.
4318 * @note Call saveSettings() after calling this function to commit
4319 * this change to the database.
4321 * @param string &$expiration Accepts the expiration time
4322 * @return string New token
4324 protected function confirmationToken( &$expiration ) {
4325 global $wgUserEmailConfirmationTokenExpiry;
4327 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4328 $expiration = wfTimestamp( TS_MW
, $expires );
4330 $token = MWCryptRand
::generateHex( 32 );
4331 $hash = md5( $token );
4332 $this->mEmailToken
= $hash;
4333 $this->mEmailTokenExpires
= $expiration;
4338 * Return a URL the user can use to confirm their email address.
4339 * @param string $token Accepts the email confirmation token
4340 * @return string New token URL
4342 protected function confirmationTokenUrl( $token ) {
4343 return $this->getTokenUrl( 'ConfirmEmail', $token );
4347 * Return a URL the user can use to invalidate their email address.
4348 * @param string $token Accepts the email confirmation token
4349 * @return string New token URL
4351 protected function invalidationTokenUrl( $token ) {
4352 return $this->getTokenUrl( 'InvalidateEmail', $token );
4356 * Internal function to format the e-mail validation/invalidation URLs.
4357 * This uses a quickie hack to use the
4358 * hardcoded English names of the Special: pages, for ASCII safety.
4360 * @note Since these URLs get dropped directly into emails, using the
4361 * short English names avoids insanely long URL-encoded links, which
4362 * also sometimes can get corrupted in some browsers/mailers
4363 * (bug 6957 with Gmail and Internet Explorer).
4365 * @param string $page Special page
4366 * @param string $token Token
4367 * @return string Formatted URL
4369 protected function getTokenUrl( $page, $token ) {
4370 // Hack to bypass localization of 'Special:'
4371 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4372 return $title->getCanonicalURL();
4376 * Mark the e-mail address confirmed.
4378 * @note Call saveSettings() after calling this function to commit the change.
4382 public function confirmEmail() {
4383 // Check if it's already confirmed, so we don't touch the database
4384 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4385 if ( !$this->isEmailConfirmed() ) {
4386 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4387 Hooks
::run( 'ConfirmEmailComplete', array( $this ) );
4393 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4394 * address if it was already confirmed.
4396 * @note Call saveSettings() after calling this function to commit the change.
4397 * @return bool Returns true
4399 public function invalidateEmail() {
4401 $this->mEmailToken
= null;
4402 $this->mEmailTokenExpires
= null;
4403 $this->setEmailAuthenticationTimestamp( null );
4405 Hooks
::run( 'InvalidateEmailComplete', array( $this ) );
4410 * Set the e-mail authentication timestamp.
4411 * @param string $timestamp TS_MW timestamp
4413 public function setEmailAuthenticationTimestamp( $timestamp ) {
4415 $this->mEmailAuthenticated
= $timestamp;
4416 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4420 * Is this user allowed to send e-mails within limits of current
4421 * site configuration?
4424 public function canSendEmail() {
4425 global $wgEnableEmail, $wgEnableUserEmail;
4426 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4429 $canSend = $this->isEmailConfirmed();
4430 Hooks
::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4435 * Is this user allowed to receive e-mails within limits of current
4436 * site configuration?
4439 public function canReceiveEmail() {
4440 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4444 * Is this user's e-mail address valid-looking and confirmed within
4445 * limits of the current site configuration?
4447 * @note If $wgEmailAuthentication is on, this may require the user to have
4448 * confirmed their address by returning a code or using a password
4449 * sent to the address from the wiki.
4453 public function isEmailConfirmed() {
4454 global $wgEmailAuthentication;
4457 if ( Hooks
::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4458 if ( $this->isAnon() ) {
4461 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4464 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4474 * Check whether there is an outstanding request for e-mail confirmation.
4477 public function isEmailConfirmationPending() {
4478 global $wgEmailAuthentication;
4479 return $wgEmailAuthentication &&
4480 !$this->isEmailConfirmed() &&
4481 $this->mEmailToken
&&
4482 $this->mEmailTokenExpires
> wfTimestamp();
4486 * Get the timestamp of account creation.
4488 * @return string|bool|null Timestamp of account creation, false for
4489 * non-existent/anonymous user accounts, or null if existing account
4490 * but information is not in database.
4492 public function getRegistration() {
4493 if ( $this->isAnon() ) {
4497 return $this->mRegistration
;
4501 * Get the timestamp of the first edit
4503 * @return string|bool Timestamp of first edit, or false for
4504 * non-existent/anonymous user accounts.
4506 public function getFirstEditTimestamp() {
4507 if ( $this->getId() == 0 ) {
4508 return false; // anons
4510 $dbr = wfGetDB( DB_SLAVE
);
4511 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4512 array( 'rev_user' => $this->getId() ),
4514 array( 'ORDER BY' => 'rev_timestamp ASC' )
4517 return false; // no edits
4519 return wfTimestamp( TS_MW
, $time );
4523 * Get the permissions associated with a given list of groups
4525 * @param array $groups Array of Strings List of internal group names
4526 * @return array Array of Strings List of permission key names for given groups combined
4528 public static function getGroupPermissions( $groups ) {
4529 global $wgGroupPermissions, $wgRevokePermissions;
4531 // grant every granted permission first
4532 foreach ( $groups as $group ) {
4533 if ( isset( $wgGroupPermissions[$group] ) ) {
4534 $rights = array_merge( $rights,
4535 // array_filter removes empty items
4536 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4539 // now revoke the revoked permissions
4540 foreach ( $groups as $group ) {
4541 if ( isset( $wgRevokePermissions[$group] ) ) {
4542 $rights = array_diff( $rights,
4543 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4546 return array_unique( $rights );
4550 * Get all the groups who have a given permission
4552 * @param string $role Role to check
4553 * @return array Array of Strings List of internal group names with the given permission
4555 public static function getGroupsWithPermission( $role ) {
4556 global $wgGroupPermissions;
4557 $allowedGroups = array();
4558 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4559 if ( self
::groupHasPermission( $group, $role ) ) {
4560 $allowedGroups[] = $group;
4563 return $allowedGroups;
4567 * Check, if the given group has the given permission
4569 * If you're wanting to check whether all users have a permission, use
4570 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4574 * @param string $group Group to check
4575 * @param string $role Role to check
4578 public static function groupHasPermission( $group, $role ) {
4579 global $wgGroupPermissions, $wgRevokePermissions;
4580 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4581 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4585 * Check if all users have the given permission
4588 * @param string $right Right to check
4591 public static function isEveryoneAllowed( $right ) {
4592 global $wgGroupPermissions, $wgRevokePermissions;
4593 static $cache = array();
4595 // Use the cached results, except in unit tests which rely on
4596 // being able change the permission mid-request
4597 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4598 return $cache[$right];
4601 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4602 $cache[$right] = false;
4606 // If it's revoked anywhere, then everyone doesn't have it
4607 foreach ( $wgRevokePermissions as $rights ) {
4608 if ( isset( $rights[$right] ) && $rights[$right] ) {
4609 $cache[$right] = false;
4614 // Allow extensions (e.g. OAuth) to say false
4615 if ( !Hooks
::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4616 $cache[$right] = false;
4620 $cache[$right] = true;
4625 * Get the localized descriptive name for a group, if it exists
4627 * @param string $group Internal group name
4628 * @return string Localized descriptive group name
4630 public static function getGroupName( $group ) {
4631 $msg = wfMessage( "group-$group" );
4632 return $msg->isBlank() ?
$group : $msg->text();
4636 * Get the localized descriptive name for a member of a group, if it exists
4638 * @param string $group Internal group name
4639 * @param string $username Username for gender (since 1.19)
4640 * @return string Localized name for group member
4642 public static function getGroupMember( $group, $username = '#' ) {
4643 $msg = wfMessage( "group-$group-member", $username );
4644 return $msg->isBlank() ?
$group : $msg->text();
4648 * Return the set of defined explicit groups.
4649 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4650 * are not included, as they are defined automatically, not in the database.
4651 * @return array Array of internal group names
4653 public static function getAllGroups() {
4654 global $wgGroupPermissions, $wgRevokePermissions;
4656 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4657 self
::getImplicitGroups()
4662 * Get a list of all available permissions.
4663 * @return string[] Array of permission names
4665 public static function getAllRights() {
4666 if ( self
::$mAllRights === false ) {
4667 global $wgAvailableRights;
4668 if ( count( $wgAvailableRights ) ) {
4669 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4671 self
::$mAllRights = self
::$mCoreRights;
4673 Hooks
::run( 'UserGetAllRights', array( &self
::$mAllRights ) );
4675 return self
::$mAllRights;
4679 * Get a list of implicit groups
4680 * @return array Array of Strings Array of internal group names
4682 public static function getImplicitGroups() {
4683 global $wgImplicitGroups;
4685 $groups = $wgImplicitGroups;
4686 # Deprecated, use $wgImplicitGroups instead
4687 Hooks
::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4693 * Get the title of a page describing a particular group
4695 * @param string $group Internal group name
4696 * @return Title|bool Title of the page if it exists, false otherwise
4698 public static function getGroupPage( $group ) {
4699 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4700 if ( $msg->exists() ) {
4701 $title = Title
::newFromText( $msg->text() );
4702 if ( is_object( $title ) ) {
4710 * Create a link to the group in HTML, if available;
4711 * else return the group name.
4713 * @param string $group Internal name of the group
4714 * @param string $text The text of the link
4715 * @return string HTML link to the group
4717 public static function makeGroupLinkHTML( $group, $text = '' ) {
4718 if ( $text == '' ) {
4719 $text = self
::getGroupName( $group );
4721 $title = self
::getGroupPage( $group );
4723 return Linker
::link( $title, htmlspecialchars( $text ) );
4725 return htmlspecialchars( $text );
4730 * Create a link to the group in Wikitext, if available;
4731 * else return the group name.
4733 * @param string $group Internal name of the group
4734 * @param string $text The text of the link
4735 * @return string Wikilink to the group
4737 public static function makeGroupLinkWiki( $group, $text = '' ) {
4738 if ( $text == '' ) {
4739 $text = self
::getGroupName( $group );
4741 $title = self
::getGroupPage( $group );
4743 $page = $title->getFullText();
4744 return "[[$page|$text]]";
4751 * Returns an array of the groups that a particular group can add/remove.
4753 * @param string $group The group to check for whether it can add/remove
4754 * @return array Array( 'add' => array( addablegroups ),
4755 * 'remove' => array( removablegroups ),
4756 * 'add-self' => array( addablegroups to self),
4757 * 'remove-self' => array( removable groups from self) )
4759 public static function changeableByGroup( $group ) {
4760 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4764 'remove' => array(),
4765 'add-self' => array(),
4766 'remove-self' => array()
4769 if ( empty( $wgAddGroups[$group] ) ) {
4770 // Don't add anything to $groups
4771 } elseif ( $wgAddGroups[$group] === true ) {
4772 // You get everything
4773 $groups['add'] = self
::getAllGroups();
4774 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4775 $groups['add'] = $wgAddGroups[$group];
4778 // Same thing for remove
4779 if ( empty( $wgRemoveGroups[$group] ) ) {
4781 } elseif ( $wgRemoveGroups[$group] === true ) {
4782 $groups['remove'] = self
::getAllGroups();
4783 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4784 $groups['remove'] = $wgRemoveGroups[$group];
4787 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4788 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4789 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4790 if ( is_int( $key ) ) {
4791 $wgGroupsAddToSelf['user'][] = $value;
4796 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4797 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4798 if ( is_int( $key ) ) {
4799 $wgGroupsRemoveFromSelf['user'][] = $value;
4804 // Now figure out what groups the user can add to him/herself
4805 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4807 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4808 // No idea WHY this would be used, but it's there
4809 $groups['add-self'] = User
::getAllGroups();
4810 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4811 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4814 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4816 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4817 $groups['remove-self'] = User
::getAllGroups();
4818 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4819 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4826 * Returns an array of groups that this user can add and remove
4827 * @return array Array( 'add' => array( addablegroups ),
4828 * 'remove' => array( removablegroups ),
4829 * 'add-self' => array( addablegroups to self),
4830 * 'remove-self' => array( removable groups from self) )
4832 public function changeableGroups() {
4833 if ( $this->isAllowed( 'userrights' ) ) {
4834 // This group gives the right to modify everything (reverse-
4835 // compatibility with old "userrights lets you change
4837 // Using array_merge to make the groups reindexed
4838 $all = array_merge( User
::getAllGroups() );
4842 'add-self' => array(),
4843 'remove-self' => array()
4847 // Okay, it's not so simple, we will have to go through the arrays
4850 'remove' => array(),
4851 'add-self' => array(),
4852 'remove-self' => array()
4854 $addergroups = $this->getEffectiveGroups();
4856 foreach ( $addergroups as $addergroup ) {
4857 $groups = array_merge_recursive(
4858 $groups, $this->changeableByGroup( $addergroup )
4860 $groups['add'] = array_unique( $groups['add'] );
4861 $groups['remove'] = array_unique( $groups['remove'] );
4862 $groups['add-self'] = array_unique( $groups['add-self'] );
4863 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4869 * Deferred version of incEditCountImmediate()
4871 public function incEditCount() {
4873 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $that ) {
4874 $that->incEditCountImmediate();
4879 * Increment the user's edit-count field.
4880 * Will have no effect for anonymous users.
4883 public function incEditCountImmediate() {
4884 if ( $this->isAnon() ) {
4888 $dbw = wfGetDB( DB_MASTER
);
4889 // No rows will be "affected" if user_editcount is NULL
4892 array( 'user_editcount=user_editcount+1' ),
4893 array( 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ),
4896 // Lazy initialization check...
4897 if ( $dbw->affectedRows() == 0 ) {
4898 // Now here's a goddamn hack...
4899 $dbr = wfGetDB( DB_SLAVE
);
4900 if ( $dbr !== $dbw ) {
4901 // If we actually have a slave server, the count is
4902 // at least one behind because the current transaction
4903 // has not been committed and replicated.
4904 $this->initEditCount( 1 );
4906 // But if DB_SLAVE is selecting the master, then the
4907 // count we just read includes the revision that was
4908 // just added in the working transaction.
4909 $this->initEditCount();
4912 // Edit count in user cache too
4913 $this->invalidateCache();
4917 * Initialize user_editcount from data out of the revision table
4919 * @param int $add Edits to add to the count from the revision table
4920 * @return int Number of edits
4922 protected function initEditCount( $add = 0 ) {
4923 // Pull from a slave to be less cruel to servers
4924 // Accuracy isn't the point anyway here
4925 $dbr = wfGetDB( DB_SLAVE
);
4926 $count = (int)$dbr->selectField(
4929 array( 'rev_user' => $this->getId() ),
4932 $count = $count +
$add;
4934 $dbw = wfGetDB( DB_MASTER
);
4937 array( 'user_editcount' => $count ),
4938 array( 'user_id' => $this->getId() ),
4946 * Get the description of a given right
4948 * @param string $right Right to query
4949 * @return string Localized description of the right
4951 public static function getRightDescription( $right ) {
4952 $key = "right-$right";
4953 $msg = wfMessage( $key );
4954 return $msg->isBlank() ?
$right : $msg->text();
4958 * Make a new-style password hash
4960 * @param string $password Plain-text password
4961 * @param bool|string $salt Optional salt, may be random or the user ID.
4962 * If unspecified or false, will generate one automatically
4963 * @return string Password hash
4964 * @deprecated since 1.24, use Password class
4966 public static function crypt( $password, $salt = false ) {
4967 wfDeprecated( __METHOD__
, '1.24' );
4968 $passwordFactory = new PasswordFactory();
4969 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4970 $hash = $passwordFactory->newFromPlaintext( $password );
4971 return $hash->toString();
4975 * Compare a password hash with a plain-text password. Requires the user
4976 * ID if there's a chance that the hash is an old-style hash.
4978 * @param string $hash Password hash
4979 * @param string $password Plain-text password to compare
4980 * @param string|bool $userId User ID for old-style password salt
4983 * @deprecated since 1.24, use Password class
4985 public static function comparePasswords( $hash, $password, $userId = false ) {
4986 wfDeprecated( __METHOD__
, '1.24' );
4988 // Check for *really* old password hashes that don't even have a type
4989 // The old hash format was just an md5 hex hash, with no type information
4990 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4991 global $wgPasswordSalt;
4992 if ( $wgPasswordSalt ) {
4993 $password = ":B:{$userId}:{$hash}";
4995 $password = ":A:{$hash}";
4999 $passwordFactory = new PasswordFactory();
5000 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5001 $hash = $passwordFactory->newFromCiphertext( $hash );
5002 return $hash->equals( $password );
5006 * Add a newuser log entry for this user.
5007 * Before 1.19 the return value was always true.
5009 * @param string|bool $action Account creation type.
5010 * - String, one of the following values:
5011 * - 'create' for an anonymous user creating an account for himself.
5012 * This will force the action's performer to be the created user itself,
5013 * no matter the value of $wgUser
5014 * - 'create2' for a logged in user creating an account for someone else
5015 * - 'byemail' when the created user will receive its password by e-mail
5016 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5017 * - Boolean means whether the account was created by e-mail (deprecated):
5018 * - true will be converted to 'byemail'
5019 * - false will be converted to 'create' if this object is the same as
5020 * $wgUser and to 'create2' otherwise
5022 * @param string $reason User supplied reason
5024 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
5026 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5027 global $wgUser, $wgNewUserLog;
5028 if ( empty( $wgNewUserLog ) ) {
5029 return true; // disabled
5032 if ( $action === true ) {
5033 $action = 'byemail';
5034 } elseif ( $action === false ) {
5035 if ( $this->equals( $wgUser ) ) {
5038 $action = 'create2';
5042 if ( $action === 'create' ||
$action === 'autocreate' ) {
5045 $performer = $wgUser;
5048 $logEntry = new ManualLogEntry( 'newusers', $action );
5049 $logEntry->setPerformer( $performer );
5050 $logEntry->setTarget( $this->getUserPage() );
5051 $logEntry->setComment( $reason );
5052 $logEntry->setParameters( array(
5053 '4::userid' => $this->getId(),
5055 $logid = $logEntry->insert();
5057 if ( $action !== 'autocreate' ) {
5058 $logEntry->publish( $logid );
5065 * Add an autocreate newuser log entry for this user
5066 * Used by things like CentralAuth and perhaps other authplugins.
5067 * Consider calling addNewUserLogEntry() directly instead.
5071 public function addNewUserLogEntryAutoCreate() {
5072 $this->addNewUserLogEntry( 'autocreate' );
5078 * Load the user options either from cache, the database or an array
5080 * @param array $data Rows for the current user out of the user_properties table
5082 protected function loadOptions( $data = null ) {
5087 if ( $this->mOptionsLoaded
) {
5091 $this->mOptions
= self
::getDefaultOptions();
5093 if ( !$this->getId() ) {
5094 // For unlogged-in users, load language/variant options from request.
5095 // There's no need to do it for logged-in users: they can set preferences,
5096 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5097 // so don't override user's choice (especially when the user chooses site default).
5098 $variant = $wgContLang->getDefaultVariant();
5099 $this->mOptions
['variant'] = $variant;
5100 $this->mOptions
['language'] = $variant;
5101 $this->mOptionsLoaded
= true;
5105 // Maybe load from the object
5106 if ( !is_null( $this->mOptionOverrides
) ) {
5107 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5108 foreach ( $this->mOptionOverrides
as $key => $value ) {
5109 $this->mOptions
[$key] = $value;
5112 if ( !is_array( $data ) ) {
5113 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5114 // Load from database
5115 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5116 ?
wfGetDB( DB_MASTER
)
5117 : wfGetDB( DB_SLAVE
);
5119 $res = $dbr->select(
5121 array( 'up_property', 'up_value' ),
5122 array( 'up_user' => $this->getId() ),
5126 $this->mOptionOverrides
= array();
5128 foreach ( $res as $row ) {
5129 $data[$row->up_property
] = $row->up_value
;
5132 foreach ( $data as $property => $value ) {
5133 $this->mOptionOverrides
[$property] = $value;
5134 $this->mOptions
[$property] = $value;
5138 $this->mOptionsLoaded
= true;
5140 Hooks
::run( 'UserLoadOptions', array( $this, &$this->mOptions
) );
5144 * Saves the non-default options for this user, as previously set e.g. via
5145 * setOption(), in the database's "user_properties" (preferences) table.
5146 * Usually used via saveSettings().
5148 protected function saveOptions() {
5149 $this->loadOptions();
5151 // Not using getOptions(), to keep hidden preferences in database
5152 $saveOptions = $this->mOptions
;
5154 // Allow hooks to abort, for instance to save to a global profile.
5155 // Reset options to default state before saving.
5156 if ( !Hooks
::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5160 $userId = $this->getId();
5162 $insert_rows = array(); // all the new preference rows
5163 foreach ( $saveOptions as $key => $value ) {
5164 // Don't bother storing default values
5165 $defaultOption = self
::getDefaultOption( $key );
5166 if ( ( $defaultOption === null && $value !== false && $value !== null )
5167 ||
$value != $defaultOption
5169 $insert_rows[] = array(
5170 'up_user' => $userId,
5171 'up_property' => $key,
5172 'up_value' => $value,
5177 $dbw = wfGetDB( DB_MASTER
);
5179 $res = $dbw->select( 'user_properties',
5180 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
5182 // Find prior rows that need to be removed or updated. These rows will
5183 // all be deleted (the later so that INSERT IGNORE applies the new values).
5184 $keysDelete = array();
5185 foreach ( $res as $row ) {
5186 if ( !isset( $saveOptions[$row->up_property
] )
5187 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5189 $keysDelete[] = $row->up_property
;
5193 if ( count( $keysDelete ) ) {
5194 // Do the DELETE by PRIMARY KEY for prior rows.
5195 // In the past a very large portion of calls to this function are for setting
5196 // 'rememberpassword' for new accounts (a preference that has since been removed).
5197 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5198 // caused gap locks on [max user ID,+infinity) which caused high contention since
5199 // updates would pile up on each other as they are for higher (newer) user IDs.
5200 // It might not be necessary these days, but it shouldn't hurt either.
5201 $dbw->delete( 'user_properties',
5202 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
5204 // Insert the new preference rows
5205 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
5209 * Lazily instantiate and return a factory object for making passwords
5211 * @deprecated since 1.27, create a PasswordFactory directly instead
5212 * @return PasswordFactory
5214 public static function getPasswordFactory() {
5215 wfDeprecated( __METHOD__
, '1.27' );
5216 $ret = new PasswordFactory();
5217 $ret->init( RequestContext
::getMain()->getConfig() );
5222 * Provide an array of HTML5 attributes to put on an input element
5223 * intended for the user to enter a new password. This may include
5224 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5226 * Do *not* use this when asking the user to enter his current password!
5227 * Regardless of configuration, users may have invalid passwords for whatever
5228 * reason (e.g., they were set before requirements were tightened up).
5229 * Only use it when asking for a new password, like on account creation or
5232 * Obviously, you still need to do server-side checking.
5234 * NOTE: A combination of bugs in various browsers means that this function
5235 * actually just returns array() unconditionally at the moment. May as
5236 * well keep it around for when the browser bugs get fixed, though.
5238 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5240 * @deprecated since 1.27
5241 * @return array Array of HTML attributes suitable for feeding to
5242 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5243 * That will get confused by the boolean attribute syntax used.)
5245 public static function passwordChangeInputAttribs() {
5246 global $wgMinimalPasswordLength;
5248 if ( $wgMinimalPasswordLength == 0 ) {
5252 # Note that the pattern requirement will always be satisfied if the
5253 # input is empty, so we need required in all cases.
5255 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5256 # if e-mail confirmation is being used. Since HTML5 input validation
5257 # is b0rked anyway in some browsers, just return nothing. When it's
5258 # re-enabled, fix this code to not output required for e-mail
5260 # $ret = array( 'required' );
5263 # We can't actually do this right now, because Opera 9.6 will print out
5264 # the entered password visibly in its error message! When other
5265 # browsers add support for this attribute, or Opera fixes its support,
5266 # we can add support with a version check to avoid doing this on Opera
5267 # versions where it will be a problem. Reported to Opera as
5268 # DSK-262266, but they don't have a public bug tracker for us to follow.
5270 if ( $wgMinimalPasswordLength > 1 ) {
5271 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5272 $ret['title'] = wfMessage( 'passwordtooshort' )
5273 ->numParams( $wgMinimalPasswordLength )->text();
5281 * Return the list of user fields that should be selected to create
5282 * a new user object.
5285 public static function selectFields() {
5293 'user_email_authenticated',
5295 'user_email_token_expires',
5296 'user_registration',
5302 * Factory function for fatal permission-denied errors
5305 * @param string $permission User right required
5308 static function newFatalPermissionDeniedStatus( $permission ) {
5311 $groups = array_map(
5312 array( 'User', 'makeGroupLinkWiki' ),
5313 User
::getGroupsWithPermission( $permission )
5317 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5319 return Status
::newFatal( 'badaccess-group0' );
5324 * Checks if two user objects point to the same user.
5330 public function equals( User
$user ) {
5331 return $this->getName() === $user->getName();