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, password, 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 * @var PasswordFactory Lazily loaded factory object for passwords
64 private static $mPasswordFactory = null;
67 * Array of Strings List of member variables which are saved to the
68 * shared cache (memcached). Any operation which changes the
69 * corresponding database fields must call a cache-clearing function.
72 protected static $mCacheVars = array(
80 'mEmailAuthenticated',
87 // user_properties table
92 * Array of Strings Core rights.
93 * Each of these should have a corresponding message of the form
97 protected static $mCoreRights = array(
123 'editusercssjs', #deprecated
135 'move-categorypages',
136 'move-rootuserpages',
140 'override-export-depth',
164 'userrights-interwiki',
172 * String Cached results of getAllRights()
174 protected static $mAllRights = false;
176 /** @name Cache variables */
185 * @todo Make this actually private
191 * @todo Make this actually private
194 public $mNewpassword;
196 public $mNewpassTime;
204 public $mEmailAuthenticated;
206 protected $mEmailToken;
208 protected $mEmailTokenExpires;
210 protected $mRegistration;
212 protected $mEditCount;
216 protected $mOptionOverrides;
218 protected $mPasswordExpires;
222 * Bool Whether the cache variables have been loaded.
225 public $mOptionsLoaded;
228 * Array with already loaded items or true if all items have been loaded.
230 protected $mLoadedItems = array();
234 * String Initialization data source if mLoadedItems!==true. May be one of:
235 * - 'defaults' anonymous user initialised from class defaults
236 * - 'name' initialise from mName
237 * - 'id' initialise from mId
238 * - 'session' log in from cookies or session if possible
240 * Use the User::newFrom*() family of functions to set this.
245 * Lazy-initialized variables, invalidated with clearInstanceCache
249 protected $mDatePreference;
257 protected $mBlockreason;
259 protected $mEffectiveGroups;
261 protected $mImplicitGroups;
263 protected $mFormerGroups;
265 protected $mBlockedGlobally;
282 protected $mAllowUsertalk;
285 private $mBlockedFromCreateAccount = false;
288 private $mWatchedItems = array();
290 public static $idCacheByName = array();
293 * Lightweight constructor for an anonymous user.
294 * Use the User::newFrom* factory functions for other kinds of users.
298 * @see newFromConfirmationCode()
299 * @see newFromSession()
302 public function __construct() {
303 $this->clearInstanceCache( 'defaults' );
309 public function __toString() {
310 return $this->getName();
314 * Load the user table data for this object from the source given by mFrom.
316 public function load() {
317 if ( $this->mLoadedItems
=== true ) {
320 wfProfileIn( __METHOD__
);
322 // Set it now to avoid infinite recursion in accessors
323 $this->mLoadedItems
= true;
325 switch ( $this->mFrom
) {
327 $this->loadDefaults();
330 $this->mId
= self
::idFromName( $this->mName
);
332 // Nonexistent user placeholder object
333 $this->loadDefaults( $this->mName
);
342 if ( !$this->loadFromSession() ) {
343 // Loading from session failed. Load defaults.
344 $this->loadDefaults();
346 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
349 wfProfileOut( __METHOD__
);
350 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
352 wfProfileOut( __METHOD__
);
356 * Load user table data, given mId has already been set.
357 * @return bool False if the ID does not exist, true otherwise
359 public function loadFromId() {
360 if ( $this->mId
== 0 ) {
361 $this->loadDefaults();
366 $cache = $this->loadFromCache();
368 wfDebug( "User: cache miss for user {$this->mId}\n" );
370 if ( !$this->loadFromDatabase() ) {
371 // Can't load from ID, user is anonymous
374 $this->saveToCache();
377 $this->mLoadedItems
= true;
383 * Load user data from shared cache, given mId has already been set.
385 * @return bool false if the ID does not exist or data is invalid, true otherwise
388 public function loadFromCache() {
391 if ( $this->mId
== 0 ) {
392 $this->loadDefaults();
396 $key = wfMemcKey( 'user', 'id', $this->mId
);
397 $data = $wgMemc->get( $key );
398 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
403 wfDebug( "User: got user {$this->mId} from cache\n" );
405 // Restore from cache
406 foreach ( self
::$mCacheVars as $name ) {
407 $this->$name = $data[$name];
414 * Save user data to the shared cache
416 public function saveToCache() {
419 $this->loadOptions();
420 if ( $this->isAnon() ) {
421 // Anonymous users are uncached
425 foreach ( self
::$mCacheVars as $name ) {
426 $data[$name] = $this->$name;
428 $data['mVersion'] = self
::VERSION
;
429 $key = wfMemcKey( 'user', 'id', $this->mId
);
431 $wgMemc->set( $key, $data );
434 /** @name newFrom*() static factory methods */
438 * Static factory method for creation from username.
440 * This is slightly less efficient than newFromId(), so use newFromId() if
441 * you have both an ID and a name handy.
443 * @param string $name Username, validated by Title::newFromText()
444 * @param string|bool $validate Validate username. Takes the same parameters as
445 * User::getCanonicalName(), except that true is accepted as an alias
446 * for 'valid', for BC.
448 * @return User|bool User object, or false if the username is invalid
449 * (e.g. if it contains illegal characters or is an IP address). If the
450 * username is not present in the database, the result will be a user object
451 * with a name, zero user ID and default settings.
453 public static function newFromName( $name, $validate = 'valid' ) {
454 if ( $validate === true ) {
457 $name = self
::getCanonicalName( $name, $validate );
458 if ( $name === false ) {
461 // Create unloaded user object
465 $u->setItemLoaded( 'name' );
471 * Static factory method for creation from a given user ID.
473 * @param int $id Valid user ID
474 * @return User The corresponding User object
476 public static function newFromId( $id ) {
480 $u->setItemLoaded( 'id' );
485 * Factory method to fetch whichever user has a given email confirmation code.
486 * This code is generated when an account is created or its e-mail address
489 * If the code is invalid or has expired, returns NULL.
491 * @param string $code Confirmation code
494 public static function newFromConfirmationCode( $code ) {
495 $dbr = wfGetDB( DB_SLAVE
);
496 $id = $dbr->selectField( 'user', 'user_id', array(
497 'user_email_token' => md5( $code ),
498 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
500 if ( $id !== false ) {
501 return User
::newFromId( $id );
508 * Create a new user object using data from session or cookies. If the
509 * login credentials are invalid, the result is an anonymous user.
511 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
514 public static function newFromSession( WebRequest
$request = null ) {
516 $user->mFrom
= 'session';
517 $user->mRequest
= $request;
522 * Create a new user object from a user row.
523 * The row should have the following fields from the user table in it:
524 * - either user_name or user_id to load further data if needed (or both)
526 * - all other fields (email, password, etc.)
527 * It is useless to provide the remaining fields if either user_id,
528 * user_name and user_real_name are not provided because the whole row
529 * will be loaded once more from the database when accessing them.
531 * @param stdClass $row A row from the user table
532 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
535 public static function newFromRow( $row, $data = null ) {
537 $user->loadFromRow( $row, $data );
544 * Get the username corresponding to a given user ID
545 * @param int $id User ID
546 * @return string|bool The corresponding username
548 public static function whoIs( $id ) {
549 return UserCache
::singleton()->getProp( $id, 'name' );
553 * Get the real name of a user given their user ID
555 * @param int $id User ID
556 * @return string|bool The corresponding user's real name
558 public static function whoIsReal( $id ) {
559 return UserCache
::singleton()->getProp( $id, 'real_name' );
563 * Get database id given a user name
564 * @param string $name Username
565 * @return int|null The corresponding user's ID, or null if user is nonexistent
567 public static function idFromName( $name ) {
568 // We don't want to call Title::makeTitleSafe yet, since that call path
569 // ends up needing the user language, which ends up trying to load the
570 // user object, which ends up back here (bug 54193).
571 $nt = Title
::makeTitle( NS_USER
, $name );
572 if ( isset( self
::$idCacheByName[$name] ) ) {
573 return self
::$idCacheByName[$name];
576 $dbr = wfGetDB( DB_SLAVE
);
577 $s = $dbr->selectRow(
580 array( 'user_name' => $nt->getText() ),
584 if ( $s === false ) {
587 $result = $s->user_id
;
590 self
::$idCacheByName[$name] = $result;
592 if ( count( self
::$idCacheByName ) > 1000 ) {
593 self
::$idCacheByName = array();
600 * Reset the cache used in idFromName(). For use in tests.
602 public static function resetIdByNameCache() {
603 self
::$idCacheByName = array();
607 * Does the string match an anonymous IPv4 address?
609 * This function exists for username validation, in order to reject
610 * usernames which are similar in form to IP addresses. Strings such
611 * as 300.300.300.300 will return true because it looks like an IP
612 * address, despite not being strictly valid.
614 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
615 * address because the usemod software would "cloak" anonymous IP
616 * addresses like this, if we allowed accounts like this to be created
617 * new users could get the old edits of these anonymous users.
619 * @param string $name Name to match
622 public static function isIP( $name ) {
623 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
624 || IP
::isIPv6( $name );
628 * Is the input a valid username?
630 * Checks if the input is a valid username, we don't want an empty string,
631 * an IP address, anything that contains slashes (would mess up subpages),
632 * is longer than the maximum allowed username size or doesn't begin with
635 * @param string $name Name to match
638 public static function isValidUserName( $name ) {
639 global $wgContLang, $wgMaxNameChars;
642 || User
::isIP( $name )
643 ||
strpos( $name, '/' ) !== false
644 ||
strlen( $name ) > $wgMaxNameChars
645 ||
$name != $wgContLang->ucfirst( $name )
647 wfDebugLog( 'username', __METHOD__
.
648 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
652 // Ensure that the name can't be misresolved as a different title,
653 // such as with extra namespace keys at the start.
654 $parsed = Title
::newFromText( $name );
655 if ( is_null( $parsed )
656 ||
$parsed->getNamespace()
657 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
658 wfDebugLog( 'username', __METHOD__
.
659 ": '$name' invalid due to ambiguous prefixes" );
663 // Check an additional blacklist of troublemaker characters.
664 // Should these be merged into the title char list?
665 $unicodeBlacklist = '/[' .
666 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
667 '\x{00a0}' . # non-breaking space
668 '\x{2000}-\x{200f}' . # various whitespace
669 '\x{2028}-\x{202f}' . # breaks and control chars
670 '\x{3000}' . # ideographic space
671 '\x{e000}-\x{f8ff}' . # private use
673 if ( preg_match( $unicodeBlacklist, $name ) ) {
674 wfDebugLog( 'username', __METHOD__
.
675 ": '$name' invalid due to blacklisted characters" );
683 * Usernames which fail to pass this function will be blocked
684 * from user login and new account registrations, but may be used
685 * internally by batch processes.
687 * If an account already exists in this form, login will be blocked
688 * by a failure to pass this function.
690 * @param string $name Name to match
693 public static function isUsableName( $name ) {
694 global $wgReservedUsernames;
695 // Must be a valid username, obviously ;)
696 if ( !self
::isValidUserName( $name ) ) {
700 static $reservedUsernames = false;
701 if ( !$reservedUsernames ) {
702 $reservedUsernames = $wgReservedUsernames;
703 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
706 // Certain names may be reserved for batch processes.
707 foreach ( $reservedUsernames as $reserved ) {
708 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
709 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
711 if ( $reserved == $name ) {
719 * Usernames which fail to pass this function will be blocked
720 * from new account registrations, but may be used internally
721 * either by batch processes or by user accounts which have
722 * already been created.
724 * Additional blacklisting may be added here rather than in
725 * isValidUserName() to avoid disrupting existing accounts.
727 * @param string $name String to match
730 public static function isCreatableName( $name ) {
731 global $wgInvalidUsernameCharacters;
733 // Ensure that the username isn't longer than 235 bytes, so that
734 // (at least for the builtin skins) user javascript and css files
735 // will work. (bug 23080)
736 if ( strlen( $name ) > 235 ) {
737 wfDebugLog( 'username', __METHOD__
.
738 ": '$name' invalid due to length" );
742 // Preg yells if you try to give it an empty string
743 if ( $wgInvalidUsernameCharacters !== '' ) {
744 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
745 wfDebugLog( 'username', __METHOD__
.
746 ": '$name' invalid due to wgInvalidUsernameCharacters" );
751 return self
::isUsableName( $name );
755 * Is the input a valid password for this user?
757 * @param string $password Desired password
760 public function isValidPassword( $password ) {
761 //simple boolean wrapper for getPasswordValidity
762 return $this->getPasswordValidity( $password ) === true;
767 * Given unvalidated password input, return error message on failure.
769 * @param string $password Desired password
770 * @return bool|string|array True on success, string or array of error message on failure
772 public function getPasswordValidity( $password ) {
773 $result = $this->checkPasswordValidity( $password );
774 if ( $result->isGood() ) {
778 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
779 $messages[] = $error['message'];
781 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
782 $messages[] = $warning['message'];
784 if ( count( $messages ) === 1 ) {
792 * Check if this is a valid password for this user. Status will be good if
793 * the password is valid, or have an array of error messages if not.
795 * @param string $password Desired password
799 public function checkPasswordValidity( $password ) {
800 global $wgMinimalPasswordLength, $wgContLang;
802 static $blockedLogins = array(
803 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
804 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
807 $status = Status
::newGood();
809 $result = false; //init $result to false for the internal checks
811 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
812 $status->error( $result );
816 if ( $result === false ) {
817 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
818 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
820 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
821 $status->error( 'password-name-match' );
823 } elseif ( isset( $blockedLogins[$this->getName()] )
824 && $password == $blockedLogins[$this->getName()]
826 $status->error( 'password-login-forbidden' );
829 //it seems weird returning a Good status here, but this is because of the
830 //initialization of $result to false above. If the hook is never run or it
831 //doesn't modify $result, then we will likely get down into this if with
835 } elseif ( $result === true ) {
838 $status->error( $result );
839 return $status; //the isValidPassword hook set a string $result and returned true
844 * Expire a user's password
846 * @param int $ts Optional timestamp to convert, default 0 for the current time
848 public function expirePassword( $ts = 0 ) {
849 $this->loadPasswords();
850 $timestamp = wfTimestamp( TS_MW
, $ts );
851 $this->mPasswordExpires
= $timestamp;
852 $this->saveSettings();
856 * Clear the password expiration for a user
858 * @param bool $load Ensure user object is loaded first
860 public function resetPasswordExpiration( $load = true ) {
861 global $wgPasswordExpirationDays;
866 if ( $wgPasswordExpirationDays ) {
867 $newExpire = wfTimestamp(
869 time() +
( $wgPasswordExpirationDays * 24 * 3600 )
872 // Give extensions a chance to force an expiration
873 wfRunHooks( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
874 $this->mPasswordExpires
= $newExpire;
878 * Check if the user's password is expired.
879 * TODO: Put this and password length into a PasswordPolicy object
881 * @return string|bool The expiration type, or false if not expired
882 * hard: A password change is required to login
883 * soft: Allow login, but encourage password change
884 * false: Password is not expired
886 public function getPasswordExpired() {
887 global $wgPasswordExpireGrace;
889 $now = wfTimestamp();
890 $expiration = $this->getPasswordExpireDate();
891 $expUnix = wfTimestamp( TS_UNIX
, $expiration );
892 if ( $expiration !== null && $expUnix < $now ) {
893 $expired = ( $expUnix +
$wgPasswordExpireGrace < $now ) ?
'hard' : 'soft';
899 * Get this user's password expiration date. Since this may be using
900 * the cached User object, we assume that whatever mechanism is setting
901 * the expiration date is also expiring the User cache.
903 * @return string|bool The datestamp of the expiration, or null if not set
905 public function getPasswordExpireDate() {
907 return $this->mPasswordExpires
;
911 * Given unvalidated user input, return a canonical username, or false if
912 * the username is invalid.
913 * @param string $name User input
914 * @param string|bool $validate Type of validation to use:
915 * - false No validation
916 * - 'valid' Valid for batch processes
917 * - 'usable' Valid for batch processes and login
918 * - 'creatable' Valid for batch processes, login and account creation
920 * @throws MWException
921 * @return bool|string
923 public static function getCanonicalName( $name, $validate = 'valid' ) {
924 // Force usernames to capital
926 $name = $wgContLang->ucfirst( $name );
928 # Reject names containing '#'; these will be cleaned up
929 # with title normalisation, but then it's too late to
931 if ( strpos( $name, '#' ) !== false ) {
935 // Clean up name according to title rules,
936 // but only when validation is requested (bug 12654)
937 $t = ( $validate !== false ) ?
938 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
939 // Check for invalid titles
940 if ( is_null( $t ) ) {
944 // Reject various classes of invalid names
946 $name = $wgAuth->getCanonicalName( $t->getText() );
948 switch ( $validate ) {
952 if ( !User
::isValidUserName( $name ) ) {
957 if ( !User
::isUsableName( $name ) ) {
962 if ( !User
::isCreatableName( $name ) ) {
967 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
973 * Count the number of edits of a user
975 * @param int $uid User ID to check
976 * @return int The user's edit count
978 * @deprecated since 1.21 in favour of User::getEditCount
980 public static function edits( $uid ) {
981 wfDeprecated( __METHOD__
, '1.21' );
982 $user = self
::newFromId( $uid );
983 return $user->getEditCount();
987 * Return a random password.
989 * @return string New random password
991 public static function randomPassword() {
992 global $wgMinimalPasswordLength;
993 // Decide the final password length based on our min password length,
994 // stopping at a minimum of 10 chars.
995 $length = max( 10, $wgMinimalPasswordLength );
996 // Multiply by 1.25 to get the number of hex characters we need
997 $length = $length * 1.25;
998 // Generate random hex chars
999 $hex = MWCryptRand
::generateHex( $length );
1000 // Convert from base 16 to base 32 to get a proper password like string
1001 return wfBaseConvert( $hex, 16, 32 );
1005 * Set cached properties to default.
1007 * @note This no longer clears uncached lazy-initialised properties;
1008 * the constructor does that instead.
1010 * @param string|bool $name
1012 public function loadDefaults( $name = false ) {
1013 wfProfileIn( __METHOD__
);
1015 $passwordFactory = self
::getPasswordFactory();
1018 $this->mName
= $name;
1019 $this->mRealName
= '';
1020 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1021 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1022 $this->mNewpassTime
= null;
1024 $this->mOptionOverrides
= null;
1025 $this->mOptionsLoaded
= false;
1027 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1028 if ( $loggedOut !== null ) {
1029 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1031 $this->mTouched
= '1'; # Allow any pages to be cached
1034 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1035 $this->mEmailAuthenticated
= null;
1036 $this->mEmailToken
= '';
1037 $this->mEmailTokenExpires
= null;
1038 $this->mPasswordExpires
= null;
1039 $this->resetPasswordExpiration( false );
1040 $this->mRegistration
= wfTimestamp( TS_MW
);
1041 $this->mGroups
= array();
1043 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
1045 wfProfileOut( __METHOD__
);
1049 * Return whether an item has been loaded.
1051 * @param string $item Item to check. Current possibilities:
1055 * @param string $all 'all' to check if the whole object has been loaded
1056 * or any other string to check if only the item is available (e.g.
1060 public function isItemLoaded( $item, $all = 'all' ) {
1061 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1062 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1066 * Set that an item has been loaded
1068 * @param string $item
1070 protected function setItemLoaded( $item ) {
1071 if ( is_array( $this->mLoadedItems
) ) {
1072 $this->mLoadedItems
[$item] = true;
1077 * Load user data from the session or login cookie.
1078 * @return bool True if the user is logged in, false otherwise.
1080 private function loadFromSession() {
1082 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
1083 if ( $result !== null ) {
1087 $request = $this->getRequest();
1089 $cookieId = $request->getCookie( 'UserID' );
1090 $sessId = $request->getSessionData( 'wsUserID' );
1092 if ( $cookieId !== null ) {
1093 $sId = intval( $cookieId );
1094 if ( $sessId !== null && $cookieId != $sessId ) {
1095 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1096 cookie user ID ($sId) don't match!" );
1099 $request->setSessionData( 'wsUserID', $sId );
1100 } elseif ( $sessId !== null && $sessId != 0 ) {
1106 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1107 $sName = $request->getSessionData( 'wsUserName' );
1108 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1109 $sName = $request->getCookie( 'UserName' );
1110 $request->setSessionData( 'wsUserName', $sName );
1115 $proposedUser = User
::newFromId( $sId );
1116 if ( !$proposedUser->isLoggedIn() ) {
1121 global $wgBlockDisablesLogin;
1122 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1123 // User blocked and we've disabled blocked user logins
1127 if ( $request->getSessionData( 'wsToken' ) ) {
1129 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1131 } elseif ( $request->getCookie( 'Token' ) ) {
1132 # Get the token from DB/cache and clean it up to remove garbage padding.
1133 # This deals with historical problems with bugs and the default column value.
1134 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1135 // Make comparison in constant time (bug 61346)
1136 $passwordCorrect = strlen( $token )
1137 && hash_equals( $token, $request->getCookie( 'Token' ) );
1140 // No session or persistent login cookie
1144 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1145 $this->loadFromUserObject( $proposedUser );
1146 $request->setSessionData( 'wsToken', $this->mToken
);
1147 wfDebug( "User: logged in from $from\n" );
1150 // Invalid credentials
1151 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1157 * Load user and user_group data from the database.
1158 * $this->mId must be set, this is how the user is identified.
1160 * @param int $flags Supports User::READ_LOCKING
1161 * @return bool True if the user exists, false if the user is anonymous
1163 public function loadFromDatabase( $flags = 0 ) {
1165 $this->mId
= intval( $this->mId
);
1168 if ( !$this->mId
) {
1169 $this->loadDefaults();
1173 $dbr = wfGetDB( DB_MASTER
);
1174 $s = $dbr->selectRow(
1176 self
::selectFields(),
1177 array( 'user_id' => $this->mId
),
1179 ( $flags & self
::READ_LOCKING
== self
::READ_LOCKING
)
1180 ?
array( 'LOCK IN SHARE MODE' )
1184 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1186 if ( $s !== false ) {
1187 // Initialise user table data
1188 $this->loadFromRow( $s );
1189 $this->mGroups
= null; // deferred
1190 $this->getEditCount(); // revalidation for nulls
1195 $this->loadDefaults();
1201 * Initialize this object from a row from the user table.
1203 * @param stdClass $row Row from the user table to load.
1204 * @param array $data Further user data to load into the object
1206 * user_groups Array with groups out of the user_groups table
1207 * user_properties Array with properties out of the user_properties table
1209 public function loadFromRow( $row, $data = null ) {
1211 $passwordFactory = self
::getPasswordFactory();
1213 $this->mGroups
= null; // deferred
1215 if ( isset( $row->user_name
) ) {
1216 $this->mName
= $row->user_name
;
1217 $this->mFrom
= 'name';
1218 $this->setItemLoaded( 'name' );
1223 if ( isset( $row->user_real_name
) ) {
1224 $this->mRealName
= $row->user_real_name
;
1225 $this->setItemLoaded( 'realname' );
1230 if ( isset( $row->user_id
) ) {
1231 $this->mId
= intval( $row->user_id
);
1232 $this->mFrom
= 'id';
1233 $this->setItemLoaded( 'id' );
1238 if ( isset( $row->user_editcount
) ) {
1239 $this->mEditCount
= $row->user_editcount
;
1244 if ( isset( $row->user_password
) ) {
1245 // Check for *really* old password hashes that don't even have a type
1246 // The old hash format was just an md5 hex hash, with no type information
1247 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password
) ) {
1248 $row->user_password
= ":A:{$this->mId}:{$row->user_password}";
1252 $this->mPassword
= $passwordFactory->newFromCiphertext( $row->user_password
);
1253 } catch ( PasswordError
$e ) {
1254 wfDebug( 'Invalid password hash found in database.' );
1255 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1259 $this->mNewpassword
= $passwordFactory->newFromCiphertext( $row->user_newpassword
);
1260 } catch ( PasswordError
$e ) {
1261 wfDebug( 'Invalid password hash found in database.' );
1262 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1265 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1266 $this->mPasswordExpires
= wfTimestampOrNull( TS_MW
, $row->user_password_expires
);
1269 if ( isset( $row->user_email
) ) {
1270 $this->mEmail
= $row->user_email
;
1271 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1272 $this->mToken
= $row->user_token
;
1273 if ( $this->mToken
== '' ) {
1274 $this->mToken
= null;
1276 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1277 $this->mEmailToken
= $row->user_email_token
;
1278 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1279 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1285 $this->mLoadedItems
= true;
1288 if ( is_array( $data ) ) {
1289 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1290 $this->mGroups
= $data['user_groups'];
1292 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1293 $this->loadOptions( $data['user_properties'] );
1299 * Load the data for this user object from another user object.
1303 protected function loadFromUserObject( $user ) {
1305 $user->loadGroups();
1306 $user->loadOptions();
1307 foreach ( self
::$mCacheVars as $var ) {
1308 $this->$var = $user->$var;
1313 * Load the groups from the database if they aren't already loaded.
1315 private function loadGroups() {
1316 if ( is_null( $this->mGroups
) ) {
1317 $dbr = wfGetDB( DB_MASTER
);
1318 $res = $dbr->select( 'user_groups',
1319 array( 'ug_group' ),
1320 array( 'ug_user' => $this->mId
),
1322 $this->mGroups
= array();
1323 foreach ( $res as $row ) {
1324 $this->mGroups
[] = $row->ug_group
;
1330 * Load the user's password hashes from the database
1332 * This is usually called in a scenario where the actual User object was
1333 * loaded from the cache, and then password comparison needs to be performed.
1334 * Password hashes are not stored in memcached.
1338 private function loadPasswords() {
1339 if ( $this->getId() !== 0 && ( $this->mPassword
=== null ||
$this->mNewpassword
=== null ) ) {
1340 $this->loadFromRow( wfGetDB( DB_MASTER
)->selectRow(
1342 array( 'user_password', 'user_newpassword', 'user_newpass_time', 'user_password_expires' ),
1343 array( 'user_id' => $this->getId() ),
1350 * Add the user to the group if he/she meets given criteria.
1352 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1353 * possible to remove manually via Special:UserRights. In such case it
1354 * will not be re-added automatically. The user will also not lose the
1355 * group if they no longer meet the criteria.
1357 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1359 * @return array Array of groups the user has been promoted to.
1361 * @see $wgAutopromoteOnce
1363 public function addAutopromoteOnceGroups( $event ) {
1364 global $wgAutopromoteOnceLogInRC, $wgAuth;
1366 $toPromote = array();
1367 if ( $this->getId() ) {
1368 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1369 if ( count( $toPromote ) ) {
1370 $oldGroups = $this->getGroups(); // previous groups
1372 foreach ( $toPromote as $group ) {
1373 $this->addGroup( $group );
1375 // update groups in external authentication database
1376 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1378 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1380 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1381 $logEntry->setPerformer( $this );
1382 $logEntry->setTarget( $this->getUserPage() );
1383 $logEntry->setParameters( array(
1384 '4::oldgroups' => $oldGroups,
1385 '5::newgroups' => $newGroups,
1387 $logid = $logEntry->insert();
1388 if ( $wgAutopromoteOnceLogInRC ) {
1389 $logEntry->publish( $logid );
1397 * Clear various cached data stored in this object. The cache of the user table
1398 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1400 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1401 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1403 public function clearInstanceCache( $reloadFrom = false ) {
1404 $this->mNewtalk
= -1;
1405 $this->mDatePreference
= null;
1406 $this->mBlockedby
= -1; # Unset
1407 $this->mHash
= false;
1408 $this->mRights
= null;
1409 $this->mEffectiveGroups
= null;
1410 $this->mImplicitGroups
= null;
1411 $this->mGroups
= null;
1412 $this->mOptions
= null;
1413 $this->mOptionsLoaded
= false;
1414 $this->mEditCount
= null;
1416 if ( $reloadFrom ) {
1417 $this->mLoadedItems
= array();
1418 $this->mFrom
= $reloadFrom;
1423 * Combine the language default options with any site-specific options
1424 * and add the default language variants.
1426 * @return array Array of String options
1428 public static function getDefaultOptions() {
1429 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1431 static $defOpt = null;
1432 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1433 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1434 // mid-request and see that change reflected in the return value of this function.
1435 // Which is insane and would never happen during normal MW operation
1439 $defOpt = $wgDefaultUserOptions;
1440 // Default language setting
1441 $defOpt['language'] = $wgContLang->getCode();
1442 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1443 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1445 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1446 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1448 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1450 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1456 * Get a given default option value.
1458 * @param string $opt Name of option to retrieve
1459 * @return string Default option value
1461 public static function getDefaultOption( $opt ) {
1462 $defOpts = self
::getDefaultOptions();
1463 if ( isset( $defOpts[$opt] ) ) {
1464 return $defOpts[$opt];
1471 * Get blocking information
1472 * @param bool $bFromSlave Whether to check the slave database first.
1473 * To improve performance, non-critical checks are done against slaves.
1474 * Check when actually saving should be done against master.
1476 private function getBlockedStatus( $bFromSlave = true ) {
1477 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1479 if ( -1 != $this->mBlockedby
) {
1483 wfProfileIn( __METHOD__
);
1484 wfDebug( __METHOD__
. ": checking...\n" );
1486 // Initialize data...
1487 // Otherwise something ends up stomping on $this->mBlockedby when
1488 // things get lazy-loaded later, causing false positive block hits
1489 // due to -1 !== 0. Probably session-related... Nothing should be
1490 // overwriting mBlockedby, surely?
1493 # We only need to worry about passing the IP address to the Block generator if the
1494 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1495 # know which IP address they're actually coming from
1496 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1497 $ip = $this->getRequest()->getIP();
1503 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1506 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1507 && !in_array( $ip, $wgProxyWhitelist )
1510 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1512 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1513 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1514 $block->setTarget( $ip );
1515 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1517 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1518 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1519 $block->setTarget( $ip );
1523 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1524 if ( !$block instanceof Block
1525 && $wgApplyIpBlocksToXff
1527 && !$this->isAllowed( 'proxyunbannable' )
1528 && !in_array( $ip, $wgProxyWhitelist )
1530 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1531 $xff = array_map( 'trim', explode( ',', $xff ) );
1532 $xff = array_diff( $xff, array( $ip ) );
1533 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1534 $block = Block
::chooseBlock( $xffblocks, $xff );
1535 if ( $block instanceof Block
) {
1536 # Mangle the reason to alert the user that the block
1537 # originated from matching the X-Forwarded-For header.
1538 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1542 if ( $block instanceof Block
) {
1543 wfDebug( __METHOD__
. ": Found block.\n" );
1544 $this->mBlock
= $block;
1545 $this->mBlockedby
= $block->getByName();
1546 $this->mBlockreason
= $block->mReason
;
1547 $this->mHideName
= $block->mHideName
;
1548 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1550 $this->mBlockedby
= '';
1551 $this->mHideName
= 0;
1552 $this->mAllowUsertalk
= false;
1556 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1558 wfProfileOut( __METHOD__
);
1562 * Whether the given IP is in a DNS blacklist.
1564 * @param string $ip IP to check
1565 * @param bool $checkWhitelist Whether to check the whitelist first
1566 * @return bool True if blacklisted.
1568 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1569 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1571 if ( !$wgEnableDnsBlacklist ) {
1575 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1579 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1583 * Whether the given IP is in a given DNS blacklist.
1585 * @param string $ip IP to check
1586 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1587 * @return bool True if blacklisted.
1589 public function inDnsBlacklist( $ip, $bases ) {
1590 wfProfileIn( __METHOD__
);
1593 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1594 if ( IP
::isIPv4( $ip ) ) {
1595 // Reverse IP, bug 21255
1596 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1598 foreach ( (array)$bases as $base ) {
1600 // If we have an access key, use that too (ProjectHoneypot, etc.)
1601 if ( is_array( $base ) ) {
1602 if ( count( $base ) >= 2 ) {
1603 // Access key is 1, base URL is 0
1604 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1606 $host = "$ipReversed.{$base[0]}";
1609 $host = "$ipReversed.$base";
1613 $ipList = gethostbynamel( $host );
1616 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1620 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1625 wfProfileOut( __METHOD__
);
1630 * Check if an IP address is in the local proxy list
1636 public static function isLocallyBlockedProxy( $ip ) {
1637 global $wgProxyList;
1639 if ( !$wgProxyList ) {
1642 wfProfileIn( __METHOD__
);
1644 if ( !is_array( $wgProxyList ) ) {
1645 // Load from the specified file
1646 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1649 if ( !is_array( $wgProxyList ) ) {
1651 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1653 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1654 // Old-style flipped proxy list
1659 wfProfileOut( __METHOD__
);
1664 * Is this user subject to rate limiting?
1666 * @return bool True if rate limited
1668 public function isPingLimitable() {
1669 global $wgRateLimitsExcludedIPs;
1670 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1671 // No other good way currently to disable rate limits
1672 // for specific IPs. :P
1673 // But this is a crappy hack and should die.
1676 return !$this->isAllowed( 'noratelimit' );
1680 * Primitive rate limits: enforce maximum actions per time period
1681 * to put a brake on flooding.
1683 * The method generates both a generic profiling point and a per action one
1684 * (suffix being "-$action".
1686 * @note When using a shared cache like memcached, IP-address
1687 * last-hit counters will be shared across wikis.
1689 * @param string $action Action to enforce; 'edit' if unspecified
1690 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1691 * @return bool True if a rate limiter was tripped
1693 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1694 // Call the 'PingLimiter' hook
1696 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1700 global $wgRateLimits;
1701 if ( !isset( $wgRateLimits[$action] ) ) {
1705 // Some groups shouldn't trigger the ping limiter, ever
1706 if ( !$this->isPingLimitable() ) {
1711 wfProfileIn( __METHOD__
);
1712 wfProfileIn( __METHOD__
. '-' . $action );
1714 $limits = $wgRateLimits[$action];
1716 $id = $this->getId();
1719 if ( isset( $limits['anon'] ) && $id == 0 ) {
1720 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1723 if ( isset( $limits['user'] ) && $id != 0 ) {
1724 $userLimit = $limits['user'];
1726 if ( $this->isNewbie() ) {
1727 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1728 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1730 if ( isset( $limits['ip'] ) ) {
1731 $ip = $this->getRequest()->getIP();
1732 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1734 if ( isset( $limits['subnet'] ) ) {
1735 $ip = $this->getRequest()->getIP();
1738 if ( IP
::isIPv6( $ip ) ) {
1739 $parts = IP
::parseRange( "$ip/64" );
1740 $subnet = $parts[0];
1741 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1743 $subnet = $matches[1];
1745 if ( $subnet !== false ) {
1746 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1750 // Check for group-specific permissions
1751 // If more than one group applies, use the group with the highest limit
1752 foreach ( $this->getGroups() as $group ) {
1753 if ( isset( $limits[$group] ) ) {
1754 if ( $userLimit === false
1755 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1757 $userLimit = $limits[$group];
1761 // Set the user limit key
1762 if ( $userLimit !== false ) {
1763 list( $max, $period ) = $userLimit;
1764 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1765 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1769 foreach ( $keys as $key => $limit ) {
1770 list( $max, $period ) = $limit;
1771 $summary = "(limit $max in {$period}s)";
1772 $count = $wgMemc->get( $key );
1775 if ( $count >= $max ) {
1776 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1777 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1780 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1783 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1784 if ( $incrBy > 0 ) {
1785 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1788 if ( $incrBy > 0 ) {
1789 $wgMemc->incr( $key, $incrBy );
1793 wfProfileOut( __METHOD__
. '-' . $action );
1794 wfProfileOut( __METHOD__
);
1799 * Check if user is blocked
1801 * @param bool $bFromSlave Whether to check the slave database instead of
1802 * the master. Hacked from false due to horrible probs on site.
1803 * @return bool True if blocked, false otherwise
1805 public function isBlocked( $bFromSlave = true ) {
1806 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1810 * Get the block affecting the user, or null if the user is not blocked
1812 * @param bool $bFromSlave Whether to check the slave database instead of the master
1813 * @return Block|null
1815 public function getBlock( $bFromSlave = true ) {
1816 $this->getBlockedStatus( $bFromSlave );
1817 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1821 * Check if user is blocked from editing a particular article
1823 * @param Title $title Title to check
1824 * @param bool $bFromSlave Whether to check the slave database instead of the master
1827 public function isBlockedFrom( $title, $bFromSlave = false ) {
1828 global $wgBlockAllowsUTEdit;
1829 wfProfileIn( __METHOD__
);
1831 $blocked = $this->isBlocked( $bFromSlave );
1832 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1833 // If a user's name is suppressed, they cannot make edits anywhere
1834 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1835 && $title->getNamespace() == NS_USER_TALK
) {
1837 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1840 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1842 wfProfileOut( __METHOD__
);
1847 * If user is blocked, return the name of the user who placed the block
1848 * @return string Name of blocker
1850 public function blockedBy() {
1851 $this->getBlockedStatus();
1852 return $this->mBlockedby
;
1856 * If user is blocked, return the specified reason for the block
1857 * @return string Blocking reason
1859 public function blockedFor() {
1860 $this->getBlockedStatus();
1861 return $this->mBlockreason
;
1865 * If user is blocked, return the ID for the block
1866 * @return int Block ID
1868 public function getBlockId() {
1869 $this->getBlockedStatus();
1870 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1874 * Check if user is blocked on all wikis.
1875 * Do not use for actual edit permission checks!
1876 * This is intended for quick UI checks.
1878 * @param string $ip IP address, uses current client if none given
1879 * @return bool True if blocked, false otherwise
1881 public function isBlockedGlobally( $ip = '' ) {
1882 if ( $this->mBlockedGlobally
!== null ) {
1883 return $this->mBlockedGlobally
;
1885 // User is already an IP?
1886 if ( IP
::isIPAddress( $this->getName() ) ) {
1887 $ip = $this->getName();
1889 $ip = $this->getRequest()->getIP();
1892 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1893 $this->mBlockedGlobally
= (bool)$blocked;
1894 return $this->mBlockedGlobally
;
1898 * Check if user account is locked
1900 * @return bool True if locked, false otherwise
1902 public function isLocked() {
1903 if ( $this->mLocked
!== null ) {
1904 return $this->mLocked
;
1907 $authUser = $wgAuth->getUserInstance( $this );
1908 $this->mLocked
= (bool)$authUser->isLocked();
1909 return $this->mLocked
;
1913 * Check if user account is hidden
1915 * @return bool True if hidden, false otherwise
1917 public function isHidden() {
1918 if ( $this->mHideName
!== null ) {
1919 return $this->mHideName
;
1921 $this->getBlockedStatus();
1922 if ( !$this->mHideName
) {
1924 $authUser = $wgAuth->getUserInstance( $this );
1925 $this->mHideName
= (bool)$authUser->isHidden();
1927 return $this->mHideName
;
1931 * Get the user's ID.
1932 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1934 public function getId() {
1935 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1936 // Special case, we know the user is anonymous
1938 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1939 // Don't load if this was initialized from an ID
1946 * Set the user and reload all fields according to a given ID
1947 * @param int $v User ID to reload
1949 public function setId( $v ) {
1951 $this->clearInstanceCache( 'id' );
1955 * Get the user name, or the IP of an anonymous user
1956 * @return string User's name or IP address
1958 public function getName() {
1959 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1960 // Special case optimisation
1961 return $this->mName
;
1964 if ( $this->mName
=== false ) {
1966 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1968 return $this->mName
;
1973 * Set the user name.
1975 * This does not reload fields from the database according to the given
1976 * name. Rather, it is used to create a temporary "nonexistent user" for
1977 * later addition to the database. It can also be used to set the IP
1978 * address for an anonymous user to something other than the current
1981 * @note User::newFromName() has roughly the same function, when the named user
1983 * @param string $str New user name to set
1985 public function setName( $str ) {
1987 $this->mName
= $str;
1991 * Get the user's name escaped by underscores.
1992 * @return string Username escaped by underscores.
1994 public function getTitleKey() {
1995 return str_replace( ' ', '_', $this->getName() );
1999 * Check if the user has new messages.
2000 * @return bool True if the user has new messages
2002 public function getNewtalk() {
2005 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2006 if ( $this->mNewtalk
=== -1 ) {
2007 $this->mNewtalk
= false; # reset talk page status
2009 // Check memcached separately for anons, who have no
2010 // entire User object stored in there.
2011 if ( !$this->mId
) {
2012 global $wgDisableAnonTalk;
2013 if ( $wgDisableAnonTalk ) {
2014 // Anon newtalk disabled by configuration.
2015 $this->mNewtalk
= false;
2018 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
2019 $newtalk = $wgMemc->get( $key );
2020 if ( strval( $newtalk ) !== '' ) {
2021 $this->mNewtalk
= (bool)$newtalk;
2023 // Since we are caching this, make sure it is up to date by getting it
2025 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
2026 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
2030 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2034 return (bool)$this->mNewtalk
;
2038 * Return the data needed to construct links for new talk page message
2039 * alerts. If there are new messages, this will return an associative array
2040 * with the following data:
2041 * wiki: The database name of the wiki
2042 * link: Root-relative link to the user's talk page
2043 * rev: The last talk page revision that the user has seen or null. This
2044 * is useful for building diff links.
2045 * If there are no new messages, it returns an empty array.
2046 * @note This function was designed to accomodate multiple talk pages, but
2047 * currently only returns a single link and revision.
2050 public function getNewMessageLinks() {
2052 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2054 } elseif ( !$this->getNewtalk() ) {
2057 $utp = $this->getTalkPage();
2058 $dbr = wfGetDB( DB_SLAVE
);
2059 // Get the "last viewed rev" timestamp from the oldest message notification
2060 $timestamp = $dbr->selectField( 'user_newtalk',
2061 'MIN(user_last_timestamp)',
2062 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2064 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2065 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2069 * Get the revision ID for the last talk page revision viewed by the talk
2071 * @return int|null Revision ID or null
2073 public function getNewMessageRevisionId() {
2074 $newMessageRevisionId = null;
2075 $newMessageLinks = $this->getNewMessageLinks();
2076 if ( $newMessageLinks ) {
2077 // Note: getNewMessageLinks() never returns more than a single link
2078 // and it is always for the same wiki, but we double-check here in
2079 // case that changes some time in the future.
2080 if ( count( $newMessageLinks ) === 1
2081 && $newMessageLinks[0]['wiki'] === wfWikiID()
2082 && $newMessageLinks[0]['rev']
2084 $newMessageRevision = $newMessageLinks[0]['rev'];
2085 $newMessageRevisionId = $newMessageRevision->getId();
2088 return $newMessageRevisionId;
2092 * Internal uncached check for new messages
2095 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2096 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2097 * @param bool $fromMaster True to fetch from the master, false for a slave
2098 * @return bool True if the user has new messages
2100 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2101 if ( $fromMaster ) {
2102 $db = wfGetDB( DB_MASTER
);
2104 $db = wfGetDB( DB_SLAVE
);
2106 $ok = $db->selectField( 'user_newtalk', $field,
2107 array( $field => $id ), __METHOD__
);
2108 return $ok !== false;
2112 * Add or update the new messages flag
2113 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2114 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2115 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2116 * @return bool True if successful, false otherwise
2118 protected function updateNewtalk( $field, $id, $curRev = null ) {
2119 // Get timestamp of the talk page revision prior to the current one
2120 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2121 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2122 // Mark the user as having new messages since this revision
2123 $dbw = wfGetDB( DB_MASTER
);
2124 $dbw->insert( 'user_newtalk',
2125 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2128 if ( $dbw->affectedRows() ) {
2129 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2132 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2138 * Clear the new messages flag for the given user
2139 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2140 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2141 * @return bool True if successful, false otherwise
2143 protected function deleteNewtalk( $field, $id ) {
2144 $dbw = wfGetDB( DB_MASTER
);
2145 $dbw->delete( 'user_newtalk',
2146 array( $field => $id ),
2148 if ( $dbw->affectedRows() ) {
2149 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2152 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2158 * Update the 'You have new messages!' status.
2159 * @param bool $val Whether the user has new messages
2160 * @param Revision $curRev New, as yet unseen revision of the user talk
2161 * page. Ignored if null or !$val.
2163 public function setNewtalk( $val, $curRev = null ) {
2164 if ( wfReadOnly() ) {
2169 $this->mNewtalk
= $val;
2171 if ( $this->isAnon() ) {
2173 $id = $this->getName();
2176 $id = $this->getId();
2181 $changed = $this->updateNewtalk( $field, $id, $curRev );
2183 $changed = $this->deleteNewtalk( $field, $id );
2186 if ( $this->isAnon() ) {
2187 // Anons have a separate memcached space, since
2188 // user records aren't kept for them.
2189 $key = wfMemcKey( 'newtalk', 'ip', $id );
2190 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
2193 $this->invalidateCache();
2198 * Generate a current or new-future timestamp to be stored in the
2199 * user_touched field when we update things.
2200 * @return string Timestamp in TS_MW format
2202 private static function newTouchedTimestamp() {
2203 global $wgClockSkewFudge;
2204 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2208 * Clear user data from memcached.
2209 * Use after applying fun updates to the database; caller's
2210 * responsibility to update user_touched if appropriate.
2212 * Called implicitly from invalidateCache() and saveSettings().
2214 public function clearSharedCache() {
2218 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
2223 * Immediately touch the user data cache for this account.
2224 * Updates user_touched field, and removes account data from memcached
2225 * for reload on the next hit.
2227 public function invalidateCache() {
2228 if ( wfReadOnly() ) {
2233 $this->mTouched
= self
::newTouchedTimestamp();
2235 $dbw = wfGetDB( DB_MASTER
);
2236 $userid = $this->mId
;
2237 $touched = $this->mTouched
;
2238 $method = __METHOD__
;
2239 $dbw->onTransactionIdle( function () use ( $dbw, $userid, $touched, $method ) {
2240 // Prevent contention slams by checking user_touched first
2241 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2242 $needsPurge = $dbw->selectField( 'user', '1',
2243 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2244 if ( $needsPurge ) {
2245 $dbw->update( 'user',
2246 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2247 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2252 $this->clearSharedCache();
2257 * Validate the cache for this account.
2258 * @param string $timestamp A timestamp in TS_MW format
2261 public function validateCache( $timestamp ) {
2263 return ( $timestamp >= $this->mTouched
);
2267 * Get the user touched timestamp
2268 * @return string Timestamp
2270 public function getTouched() {
2272 return $this->mTouched
;
2279 public function getPassword() {
2280 $this->loadPasswords();
2282 return $this->mPassword
;
2289 public function getTemporaryPassword() {
2290 $this->loadPasswords();
2292 return $this->mNewpassword
;
2296 * Set the password and reset the random token.
2297 * Calls through to authentication plugin if necessary;
2298 * will have no effect if the auth plugin refuses to
2299 * pass the change through or if the legal password
2302 * As a special case, setting the password to null
2303 * wipes it, so the account cannot be logged in until
2304 * a new password is set, for instance via e-mail.
2306 * @param string $str New password to set
2307 * @throws PasswordError On failure
2311 public function setPassword( $str ) {
2314 $this->loadPasswords();
2316 if ( $str !== null ) {
2317 if ( !$wgAuth->allowPasswordChange() ) {
2318 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2321 if ( !$this->isValidPassword( $str ) ) {
2322 global $wgMinimalPasswordLength;
2323 $valid = $this->getPasswordValidity( $str );
2324 if ( is_array( $valid ) ) {
2325 $message = array_shift( $valid );
2329 $params = array( $wgMinimalPasswordLength );
2331 throw new PasswordError( wfMessage( $message, $params )->text() );
2335 if ( !$wgAuth->setPassword( $this, $str ) ) {
2336 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2339 $this->setInternalPassword( $str );
2345 * Set the password and reset the random token unconditionally.
2347 * @param string|null $str New password to set or null to set an invalid
2348 * password hash meaning that the user will not be able to log in
2349 * through the web interface.
2351 public function setInternalPassword( $str ) {
2354 $passwordFactory = self
::getPasswordFactory();
2355 $this->mPassword
= $passwordFactory->newFromPlaintext( $str );
2357 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
2358 $this->mNewpassTime
= null;
2362 * Get the user's current token.
2363 * @param bool $forceCreation Force the generation of a new token if the
2364 * user doesn't have one (default=true for backwards compatibility).
2365 * @return string Token
2367 public function getToken( $forceCreation = true ) {
2369 if ( !$this->mToken
&& $forceCreation ) {
2372 return $this->mToken
;
2376 * Set the random token (used for persistent authentication)
2377 * Called from loadDefaults() among other places.
2379 * @param string|bool $token If specified, set the token to this value
2381 public function setToken( $token = false ) {
2384 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2386 $this->mToken
= $token;
2391 * Set the password for a password reminder or new account email
2393 * @param string $str New password to set or null to set an invalid
2394 * password hash meaning that the user will not be able to use it
2395 * @param bool $throttle If true, reset the throttle timestamp to the present
2397 public function setNewpassword( $str, $throttle = true ) {
2398 $this->loadPasswords();
2400 $this->mNewpassword
= self
::getPasswordFactory()->newFromPlaintext( $str );
2401 if ( $str === null ) {
2402 $this->mNewpassTime
= null;
2403 } elseif ( $throttle ) {
2404 $this->mNewpassTime
= wfTimestampNow();
2409 * Has password reminder email been sent within the last
2410 * $wgPasswordReminderResendTime hours?
2413 public function isPasswordReminderThrottled() {
2414 global $wgPasswordReminderResendTime;
2416 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2419 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2420 return time() < $expiry;
2424 * Get the user's e-mail address
2425 * @return string User's email address
2427 public function getEmail() {
2429 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
2430 return $this->mEmail
;
2434 * Get the timestamp of the user's e-mail authentication
2435 * @return string TS_MW timestamp
2437 public function getEmailAuthenticationTimestamp() {
2439 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2440 return $this->mEmailAuthenticated
;
2444 * Set the user's e-mail address
2445 * @param string $str New e-mail address
2447 public function setEmail( $str ) {
2449 if ( $str == $this->mEmail
) {
2452 $this->invalidateEmail();
2453 $this->mEmail
= $str;
2454 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
2458 * Set the user's e-mail address and a confirmation mail if needed.
2461 * @param string $str New e-mail address
2464 public function setEmailWithConfirmation( $str ) {
2465 global $wgEnableEmail, $wgEmailAuthentication;
2467 if ( !$wgEnableEmail ) {
2468 return Status
::newFatal( 'emaildisabled' );
2471 $oldaddr = $this->getEmail();
2472 if ( $str === $oldaddr ) {
2473 return Status
::newGood( true );
2476 $this->setEmail( $str );
2478 if ( $str !== '' && $wgEmailAuthentication ) {
2479 // Send a confirmation request to the new address if needed
2480 $type = $oldaddr != '' ?
'changed' : 'set';
2481 $result = $this->sendConfirmationMail( $type );
2482 if ( $result->isGood() ) {
2483 // Say the the caller that a confirmation mail has been sent
2484 $result->value
= 'eauth';
2487 $result = Status
::newGood( true );
2494 * Get the user's real name
2495 * @return string User's real name
2497 public function getRealName() {
2498 if ( !$this->isItemLoaded( 'realname' ) ) {
2502 return $this->mRealName
;
2506 * Set the user's real name
2507 * @param string $str New real name
2509 public function setRealName( $str ) {
2511 $this->mRealName
= $str;
2515 * Get the user's current setting for a given option.
2517 * @param string $oname The option to check
2518 * @param string $defaultOverride A default value returned if the option does not exist
2519 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2520 * @return string User's current value for the option
2521 * @see getBoolOption()
2522 * @see getIntOption()
2524 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2525 global $wgHiddenPrefs;
2526 $this->loadOptions();
2528 # We want 'disabled' preferences to always behave as the default value for
2529 # users, even if they have set the option explicitly in their settings (ie they
2530 # set it, and then it was disabled removing their ability to change it). But
2531 # we don't want to erase the preferences in the database in case the preference
2532 # is re-enabled again. So don't touch $mOptions, just override the returned value
2533 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2534 return self
::getDefaultOption( $oname );
2537 if ( array_key_exists( $oname, $this->mOptions
) ) {
2538 return $this->mOptions
[$oname];
2540 return $defaultOverride;
2545 * Get all user's options
2549 public function getOptions() {
2550 global $wgHiddenPrefs;
2551 $this->loadOptions();
2552 $options = $this->mOptions
;
2554 # We want 'disabled' preferences to always behave as the default value for
2555 # users, even if they have set the option explicitly in their settings (ie they
2556 # set it, and then it was disabled removing their ability to change it). But
2557 # we don't want to erase the preferences in the database in case the preference
2558 # is re-enabled again. So don't touch $mOptions, just override the returned value
2559 foreach ( $wgHiddenPrefs as $pref ) {
2560 $default = self
::getDefaultOption( $pref );
2561 if ( $default !== null ) {
2562 $options[$pref] = $default;
2570 * Get the user's current setting for a given option, as a boolean value.
2572 * @param string $oname The option to check
2573 * @return bool User's current value for the option
2576 public function getBoolOption( $oname ) {
2577 return (bool)$this->getOption( $oname );
2581 * Get the user's current setting for a given option, as an integer value.
2583 * @param string $oname The option to check
2584 * @param int $defaultOverride A default value returned if the option does not exist
2585 * @return int User's current value for the option
2588 public function getIntOption( $oname, $defaultOverride = 0 ) {
2589 $val = $this->getOption( $oname );
2591 $val = $defaultOverride;
2593 return intval( $val );
2597 * Set the given option for a user.
2599 * You need to call saveSettings() to actually write to the database.
2601 * @param string $oname The option to set
2602 * @param mixed $val New value to set
2604 public function setOption( $oname, $val ) {
2605 $this->loadOptions();
2607 // Explicitly NULL values should refer to defaults
2608 if ( is_null( $val ) ) {
2609 $val = self
::getDefaultOption( $oname );
2612 $this->mOptions
[$oname] = $val;
2616 * Get a token stored in the preferences (like the watchlist one),
2617 * resetting it if it's empty (and saving changes).
2619 * @param string $oname The option name to retrieve the token from
2620 * @return string|bool User's current value for the option, or false if this option is disabled.
2621 * @see resetTokenFromOption()
2624 public function getTokenFromOption( $oname ) {
2625 global $wgHiddenPrefs;
2626 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2630 $token = $this->getOption( $oname );
2632 $token = $this->resetTokenFromOption( $oname );
2633 $this->saveSettings();
2639 * Reset a token stored in the preferences (like the watchlist one).
2640 * *Does not* save user's preferences (similarly to setOption()).
2642 * @param string $oname The option name to reset the token in
2643 * @return string|bool New token value, or false if this option is disabled.
2644 * @see getTokenFromOption()
2647 public function resetTokenFromOption( $oname ) {
2648 global $wgHiddenPrefs;
2649 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2653 $token = MWCryptRand
::generateHex( 40 );
2654 $this->setOption( $oname, $token );
2659 * Return a list of the types of user options currently returned by
2660 * User::getOptionKinds().
2662 * Currently, the option kinds are:
2663 * - 'registered' - preferences which are registered in core MediaWiki or
2664 * by extensions using the UserGetDefaultOptions hook.
2665 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2666 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2667 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2668 * be used by user scripts.
2669 * - 'special' - "preferences" that are not accessible via User::getOptions
2670 * or User::setOptions.
2671 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2672 * These are usually legacy options, removed in newer versions.
2674 * The API (and possibly others) use this function to determine the possible
2675 * option types for validation purposes, so make sure to update this when a
2676 * new option kind is added.
2678 * @see User::getOptionKinds
2679 * @return array Option kinds
2681 public static function listOptionKinds() {
2684 'registered-multiselect',
2685 'registered-checkmatrix',
2693 * Return an associative array mapping preferences keys to the kind of a preference they're
2694 * used for. Different kinds are handled differently when setting or reading preferences.
2696 * See User::listOptionKinds for the list of valid option types that can be provided.
2698 * @see User::listOptionKinds
2699 * @param IContextSource $context
2700 * @param array $options Assoc. array with options keys to check as keys.
2701 * Defaults to $this->mOptions.
2702 * @return array The key => kind mapping data
2704 public function getOptionKinds( IContextSource
$context, $options = null ) {
2705 $this->loadOptions();
2706 if ( $options === null ) {
2707 $options = $this->mOptions
;
2710 $prefs = Preferences
::getPreferences( $this, $context );
2713 // Pull out the "special" options, so they don't get converted as
2714 // multiselect or checkmatrix.
2715 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2716 foreach ( $specialOptions as $name => $value ) {
2717 unset( $prefs[$name] );
2720 // Multiselect and checkmatrix options are stored in the database with
2721 // one key per option, each having a boolean value. Extract those keys.
2722 $multiselectOptions = array();
2723 foreach ( $prefs as $name => $info ) {
2724 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2725 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2726 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2727 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2729 foreach ( $opts as $value ) {
2730 $multiselectOptions["$prefix$value"] = true;
2733 unset( $prefs[$name] );
2736 $checkmatrixOptions = array();
2737 foreach ( $prefs as $name => $info ) {
2738 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2739 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2740 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2741 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2742 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2744 foreach ( $columns as $column ) {
2745 foreach ( $rows as $row ) {
2746 $checkmatrixOptions["$prefix$column-$row"] = true;
2750 unset( $prefs[$name] );
2754 // $value is ignored
2755 foreach ( $options as $key => $value ) {
2756 if ( isset( $prefs[$key] ) ) {
2757 $mapping[$key] = 'registered';
2758 } elseif ( isset( $multiselectOptions[$key] ) ) {
2759 $mapping[$key] = 'registered-multiselect';
2760 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2761 $mapping[$key] = 'registered-checkmatrix';
2762 } elseif ( isset( $specialOptions[$key] ) ) {
2763 $mapping[$key] = 'special';
2764 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2765 $mapping[$key] = 'userjs';
2767 $mapping[$key] = 'unused';
2775 * Reset certain (or all) options to the site defaults
2777 * The optional parameter determines which kinds of preferences will be reset.
2778 * Supported values are everything that can be reported by getOptionKinds()
2779 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2781 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2782 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2783 * for backwards-compatibility.
2784 * @param IContextSource|null $context Context source used when $resetKinds
2785 * does not contain 'all', passed to getOptionKinds().
2786 * Defaults to RequestContext::getMain() when null.
2788 public function resetOptions(
2789 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2790 IContextSource
$context = null
2793 $defaultOptions = self
::getDefaultOptions();
2795 if ( !is_array( $resetKinds ) ) {
2796 $resetKinds = array( $resetKinds );
2799 if ( in_array( 'all', $resetKinds ) ) {
2800 $newOptions = $defaultOptions;
2802 if ( $context === null ) {
2803 $context = RequestContext
::getMain();
2806 $optionKinds = $this->getOptionKinds( $context );
2807 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2808 $newOptions = array();
2810 // Use default values for the options that should be deleted, and
2811 // copy old values for the ones that shouldn't.
2812 foreach ( $this->mOptions
as $key => $value ) {
2813 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2814 if ( array_key_exists( $key, $defaultOptions ) ) {
2815 $newOptions[$key] = $defaultOptions[$key];
2818 $newOptions[$key] = $value;
2823 wfRunHooks( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2825 $this->mOptions
= $newOptions;
2826 $this->mOptionsLoaded
= true;
2830 * Get the user's preferred date format.
2831 * @return string User's preferred date format
2833 public function getDatePreference() {
2834 // Important migration for old data rows
2835 if ( is_null( $this->mDatePreference
) ) {
2837 $value = $this->getOption( 'date' );
2838 $map = $wgLang->getDatePreferenceMigrationMap();
2839 if ( isset( $map[$value] ) ) {
2840 $value = $map[$value];
2842 $this->mDatePreference
= $value;
2844 return $this->mDatePreference
;
2848 * Determine based on the wiki configuration and the user's options,
2849 * whether this user must be over HTTPS no matter what.
2853 public function requiresHTTPS() {
2854 global $wgSecureLogin;
2855 if ( !$wgSecureLogin ) {
2858 $https = $this->getBoolOption( 'prefershttps' );
2859 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2861 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2868 * Get the user preferred stub threshold
2872 public function getStubThreshold() {
2873 global $wgMaxArticleSize; # Maximum article size, in Kb
2874 $threshold = $this->getIntOption( 'stubthreshold' );
2875 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2876 // If they have set an impossible value, disable the preference
2877 // so we can use the parser cache again.
2884 * Get the permissions this user has.
2885 * @return array Array of String permission names
2887 public function getRights() {
2888 if ( is_null( $this->mRights
) ) {
2889 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2890 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2891 // Force reindexation of rights when a hook has unset one of them
2892 $this->mRights
= array_values( array_unique( $this->mRights
) );
2894 return $this->mRights
;
2898 * Get the list of explicit group memberships this user has.
2899 * The implicit * and user groups are not included.
2900 * @return array Array of String internal group names
2902 public function getGroups() {
2904 $this->loadGroups();
2905 return $this->mGroups
;
2909 * Get the list of implicit group memberships this user has.
2910 * This includes all explicit groups, plus 'user' if logged in,
2911 * '*' for all accounts, and autopromoted groups
2912 * @param bool $recache Whether to avoid the cache
2913 * @return array Array of String internal group names
2915 public function getEffectiveGroups( $recache = false ) {
2916 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2917 wfProfileIn( __METHOD__
);
2918 $this->mEffectiveGroups
= array_unique( array_merge(
2919 $this->getGroups(), // explicit groups
2920 $this->getAutomaticGroups( $recache ) // implicit groups
2922 // Hook for additional groups
2923 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2924 // Force reindexation of groups when a hook has unset one of them
2925 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
2926 wfProfileOut( __METHOD__
);
2928 return $this->mEffectiveGroups
;
2932 * Get the list of implicit group memberships this user has.
2933 * This includes 'user' if logged in, '*' for all accounts,
2934 * and autopromoted groups
2935 * @param bool $recache Whether to avoid the cache
2936 * @return array Array of String internal group names
2938 public function getAutomaticGroups( $recache = false ) {
2939 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
2940 wfProfileIn( __METHOD__
);
2941 $this->mImplicitGroups
= array( '*' );
2942 if ( $this->getId() ) {
2943 $this->mImplicitGroups
[] = 'user';
2945 $this->mImplicitGroups
= array_unique( array_merge(
2946 $this->mImplicitGroups
,
2947 Autopromote
::getAutopromoteGroups( $this )
2951 // Assure data consistency with rights/groups,
2952 // as getEffectiveGroups() depends on this function
2953 $this->mEffectiveGroups
= null;
2955 wfProfileOut( __METHOD__
);
2957 return $this->mImplicitGroups
;
2961 * Returns the groups the user has belonged to.
2963 * The user may still belong to the returned groups. Compare with getGroups().
2965 * The function will not return groups the user had belonged to before MW 1.17
2967 * @return array Names of the groups the user has belonged to.
2969 public function getFormerGroups() {
2970 if ( is_null( $this->mFormerGroups
) ) {
2971 $dbr = wfGetDB( DB_MASTER
);
2972 $res = $dbr->select( 'user_former_groups',
2973 array( 'ufg_group' ),
2974 array( 'ufg_user' => $this->mId
),
2976 $this->mFormerGroups
= array();
2977 foreach ( $res as $row ) {
2978 $this->mFormerGroups
[] = $row->ufg_group
;
2981 return $this->mFormerGroups
;
2985 * Get the user's edit count.
2986 * @return int|null Null for anonymous users
2988 public function getEditCount() {
2989 if ( !$this->getId() ) {
2993 if ( $this->mEditCount
=== null ) {
2994 /* Populate the count, if it has not been populated yet */
2995 wfProfileIn( __METHOD__
);
2996 $dbr = wfGetDB( DB_SLAVE
);
2997 // check if the user_editcount field has been initialized
2998 $count = $dbr->selectField(
2999 'user', 'user_editcount',
3000 array( 'user_id' => $this->mId
),
3004 if ( $count === null ) {
3005 // it has not been initialized. do so.
3006 $count = $this->initEditCount();
3008 $this->mEditCount
= $count;
3009 wfProfileOut( __METHOD__
);
3011 return (int)$this->mEditCount
;
3015 * Add the user to the given group.
3016 * This takes immediate effect.
3017 * @param string $group Name of the group to add
3019 public function addGroup( $group ) {
3020 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
3021 $dbw = wfGetDB( DB_MASTER
);
3022 if ( $this->getId() ) {
3023 $dbw->insert( 'user_groups',
3025 'ug_user' => $this->getID(),
3026 'ug_group' => $group,
3029 array( 'IGNORE' ) );
3032 $this->loadGroups();
3033 $this->mGroups
[] = $group;
3034 // In case loadGroups was not called before, we now have the right twice.
3035 // Get rid of the duplicate.
3036 $this->mGroups
= array_unique( $this->mGroups
);
3038 // Refresh the groups caches, and clear the rights cache so it will be
3039 // refreshed on the next call to $this->getRights().
3040 $this->getEffectiveGroups( true );
3041 $this->mRights
= null;
3043 $this->invalidateCache();
3047 * Remove the user from the given group.
3048 * This takes immediate effect.
3049 * @param string $group Name of the group to remove
3051 public function removeGroup( $group ) {
3053 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3054 $dbw = wfGetDB( DB_MASTER
);
3055 $dbw->delete( 'user_groups',
3057 'ug_user' => $this->getID(),
3058 'ug_group' => $group,
3060 // Remember that the user was in this group
3061 $dbw->insert( 'user_former_groups',
3063 'ufg_user' => $this->getID(),
3064 'ufg_group' => $group,
3067 array( 'IGNORE' ) );
3069 $this->loadGroups();
3070 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3072 // Refresh the groups caches, and clear the rights cache so it will be
3073 // refreshed on the next call to $this->getRights().
3074 $this->getEffectiveGroups( true );
3075 $this->mRights
= null;
3077 $this->invalidateCache();
3081 * Get whether the user is logged in
3084 public function isLoggedIn() {
3085 return $this->getID() != 0;
3089 * Get whether the user is anonymous
3092 public function isAnon() {
3093 return !$this->isLoggedIn();
3097 * Check if user is allowed to access a feature / make an action
3099 * @param string $permissions,... Permissions to test
3100 * @return bool True if user is allowed to perform *any* of the given actions
3102 public function isAllowedAny( /*...*/ ) {
3103 $permissions = func_get_args();
3104 foreach ( $permissions as $permission ) {
3105 if ( $this->isAllowed( $permission ) ) {
3114 * @param string $permissions,... Permissions to test
3115 * @return bool True if the user is allowed to perform *all* of the given actions
3117 public function isAllowedAll( /*...*/ ) {
3118 $permissions = func_get_args();
3119 foreach ( $permissions as $permission ) {
3120 if ( !$this->isAllowed( $permission ) ) {
3128 * Internal mechanics of testing a permission
3129 * @param string $action
3132 public function isAllowed( $action = '' ) {
3133 if ( $action === '' ) {
3134 return true; // In the spirit of DWIM
3136 // Patrolling may not be enabled
3137 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3138 global $wgUseRCPatrol, $wgUseNPPatrol;
3139 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3143 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3144 // by misconfiguration: 0 == 'foo'
3145 return in_array( $action, $this->getRights(), true );
3149 * Check whether to enable recent changes patrol features for this user
3150 * @return bool True or false
3152 public function useRCPatrol() {
3153 global $wgUseRCPatrol;
3154 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3158 * Check whether to enable new pages patrol features for this user
3159 * @return bool True or false
3161 public function useNPPatrol() {
3162 global $wgUseRCPatrol, $wgUseNPPatrol;
3164 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3165 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3170 * Get the WebRequest object to use with this object
3172 * @return WebRequest
3174 public function getRequest() {
3175 if ( $this->mRequest
) {
3176 return $this->mRequest
;
3184 * Get the current skin, loading it if required
3185 * @return Skin The current skin
3186 * @todo FIXME: Need to check the old failback system [AV]
3187 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3189 public function getSkin() {
3190 wfDeprecated( __METHOD__
, '1.18' );
3191 return RequestContext
::getMain()->getSkin();
3195 * Get a WatchedItem for this user and $title.
3197 * @since 1.22 $checkRights parameter added
3198 * @param Title $title
3199 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3200 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3201 * @return WatchedItem
3203 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3204 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3206 if ( isset( $this->mWatchedItems
[$key] ) ) {
3207 return $this->mWatchedItems
[$key];
3210 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3211 $this->mWatchedItems
= array();
3214 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3215 return $this->mWatchedItems
[$key];
3219 * Check the watched status of an article.
3220 * @since 1.22 $checkRights parameter added
3221 * @param Title $title Title of the article to look at
3222 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3223 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3226 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3227 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3232 * @since 1.22 $checkRights parameter added
3233 * @param Title $title Title of the article to look at
3234 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3235 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3237 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3238 $this->getWatchedItem( $title, $checkRights )->addWatch();
3239 $this->invalidateCache();
3243 * Stop watching an article.
3244 * @since 1.22 $checkRights parameter added
3245 * @param Title $title Title of the article to look at
3246 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3247 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3249 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3250 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3251 $this->invalidateCache();
3255 * Clear the user's notification timestamp for the given title.
3256 * If e-notif e-mails are on, they will receive notification mails on
3257 * the next change of the page if it's watched etc.
3258 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3259 * @param Title $title Title of the article to look at
3260 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3262 public function clearNotification( &$title, $oldid = 0 ) {
3263 global $wgUseEnotif, $wgShowUpdatedMarker;
3265 // Do nothing if the database is locked to writes
3266 if ( wfReadOnly() ) {
3270 // Do nothing if not allowed to edit the watchlist
3271 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3275 // If we're working on user's talk page, we should update the talk page message indicator
3276 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3277 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3281 $nextid = $oldid ?
$title->getNextRevisionID( $oldid ) : null;
3283 if ( !$oldid ||
!$nextid ) {
3284 // If we're looking at the latest revision, we should definitely clear it
3285 $this->setNewtalk( false );
3287 // Otherwise we should update its revision, if it's present
3288 if ( $this->getNewtalk() ) {
3289 // Naturally the other one won't clear by itself
3290 $this->setNewtalk( false );
3291 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3296 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3300 if ( $this->isAnon() ) {
3301 // Nothing else to do...
3305 // Only update the timestamp if the page is being watched.
3306 // The query to find out if it is watched is cached both in memcached and per-invocation,
3307 // and when it does have to be executed, it can be on a slave
3308 // If this is the user's newtalk page, we always update the timestamp
3310 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3314 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3318 * Resets all of the given user's page-change notification timestamps.
3319 * If e-notif e-mails are on, they will receive notification mails on
3320 * the next change of any watched page.
3321 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3323 public function clearAllNotifications() {
3324 if ( wfReadOnly() ) {
3328 // Do nothing if not allowed to edit the watchlist
3329 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3333 global $wgUseEnotif, $wgShowUpdatedMarker;
3334 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3335 $this->setNewtalk( false );
3338 $id = $this->getId();
3340 $dbw = wfGetDB( DB_MASTER
);
3341 $dbw->update( 'watchlist',
3342 array( /* SET */ 'wl_notificationtimestamp' => null ),
3343 array( /* WHERE */ 'wl_user' => $id ),
3346 // We also need to clear here the "you have new message" notification for the own user_talk page;
3347 // it's cleared one page view later in WikiPage::doViewUpdates().
3352 * Set a cookie on the user's client. Wrapper for
3353 * WebResponse::setCookie
3354 * @param string $name Name of the cookie to set
3355 * @param string $value Value to set
3356 * @param int $exp Expiration time, as a UNIX time value;
3357 * if 0 or not specified, use the default $wgCookieExpiration
3358 * @param bool $secure
3359 * true: Force setting the secure attribute when setting the cookie
3360 * false: Force NOT setting the secure attribute when setting the cookie
3361 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3362 * @param array $params Array of options sent passed to WebResponse::setcookie()
3364 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3365 $params['secure'] = $secure;
3366 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3370 * Clear a cookie on the user's client
3371 * @param string $name Name of the cookie to clear
3372 * @param bool $secure
3373 * true: Force setting the secure attribute when setting the cookie
3374 * false: Force NOT setting the secure attribute when setting the cookie
3375 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3376 * @param array $params Array of options sent passed to WebResponse::setcookie()
3378 protected function clearCookie( $name, $secure = null, $params = array() ) {
3379 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3383 * Set the default cookies for this session on the user's client.
3385 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3387 * @param bool $secure Whether to force secure/insecure cookies or use default
3388 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3390 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3391 if ( $request === null ) {
3392 $request = $this->getRequest();
3396 if ( 0 == $this->mId
) {
3399 if ( !$this->mToken
) {
3400 // When token is empty or NULL generate a new one and then save it to the database
3401 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3402 // Simply by setting every cell in the user_token column to NULL and letting them be
3403 // regenerated as users log back into the wiki.
3405 $this->saveSettings();
3408 'wsUserID' => $this->mId
,
3409 'wsToken' => $this->mToken
,
3410 'wsUserName' => $this->getName()
3413 'UserID' => $this->mId
,
3414 'UserName' => $this->getName(),
3416 if ( $rememberMe ) {
3417 $cookies['Token'] = $this->mToken
;
3419 $cookies['Token'] = false;
3422 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3424 foreach ( $session as $name => $value ) {
3425 $request->setSessionData( $name, $value );
3427 foreach ( $cookies as $name => $value ) {
3428 if ( $value === false ) {
3429 $this->clearCookie( $name );
3431 $this->setCookie( $name, $value, 0, $secure );
3436 * If wpStickHTTPS was selected, also set an insecure cookie that
3437 * will cause the site to redirect the user to HTTPS, if they access
3438 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3439 * as the one set by centralauth (bug 53538). Also set it to session, or
3440 * standard time setting, based on if rememberme was set.
3442 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3446 $rememberMe ?
0 : null,
3448 array( 'prefix' => '' ) // no prefix
3454 * Log this user out.
3456 public function logout() {
3457 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3463 * Clear the user's cookies and session, and reset the instance cache.
3466 public function doLogout() {
3467 $this->clearInstanceCache( 'defaults' );
3469 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3471 $this->clearCookie( 'UserID' );
3472 $this->clearCookie( 'Token' );
3473 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3475 // Remember when user logged out, to prevent seeing cached pages
3476 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3480 * Save this user's settings into the database.
3481 * @todo Only rarely do all these fields need to be set!
3483 public function saveSettings() {
3487 $this->loadPasswords();
3488 if ( wfReadOnly() ) {
3491 if ( 0 == $this->mId
) {
3495 $this->mTouched
= self
::newTouchedTimestamp();
3496 if ( !$wgAuth->allowSetLocalPassword() ) {
3497 $this->mPassword
= self
::getPasswordFactory()->newFromCiphertext( null );
3500 $dbw = wfGetDB( DB_MASTER
);
3501 $dbw->update( 'user',
3503 'user_name' => $this->mName
,
3504 'user_password' => $this->mPassword
->toString(),
3505 'user_newpassword' => $this->mNewpassword
->toString(),
3506 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3507 'user_real_name' => $this->mRealName
,
3508 'user_email' => $this->mEmail
,
3509 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3510 'user_touched' => $dbw->timestamp( $this->mTouched
),
3511 'user_token' => strval( $this->mToken
),
3512 'user_email_token' => $this->mEmailToken
,
3513 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3514 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires
),
3515 ), array( /* WHERE */
3516 'user_id' => $this->mId
3520 $this->saveOptions();
3522 wfRunHooks( 'UserSaveSettings', array( $this ) );
3523 $this->clearSharedCache();
3524 $this->getUserPage()->invalidateCache();
3528 * If only this user's username is known, and it exists, return the user ID.
3531 public function idForName() {
3532 $s = trim( $this->getName() );
3537 $dbr = wfGetDB( DB_SLAVE
);
3538 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
3539 if ( $id === false ) {
3546 * Add a user to the database, return the user object
3548 * @param string $name Username to add
3549 * @param array $params Array of Strings Non-default parameters to save to
3550 * the database as user_* fields:
3551 * - password: The user's password hash. Password logins will be disabled
3552 * if this is omitted.
3553 * - newpassword: Hash for a temporary password that has been mailed to
3555 * - email: The user's email address.
3556 * - email_authenticated: The email authentication timestamp.
3557 * - real_name: The user's real name.
3558 * - options: An associative array of non-default options.
3559 * - token: Random authentication token. Do not set.
3560 * - registration: Registration timestamp. Do not set.
3562 * @return User|null User object, or null if the username already exists.
3564 public static function createNew( $name, $params = array() ) {
3567 $user->loadPasswords();
3568 $user->setToken(); // init token
3569 if ( isset( $params['options'] ) ) {
3570 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3571 unset( $params['options'] );
3573 $dbw = wfGetDB( DB_MASTER
);
3574 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3577 'user_id' => $seqVal,
3578 'user_name' => $name,
3579 'user_password' => $user->mPassword
->toString(),
3580 'user_newpassword' => $user->mNewpassword
->toString(),
3581 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3582 'user_email' => $user->mEmail
,
3583 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3584 'user_real_name' => $user->mRealName
,
3585 'user_token' => strval( $user->mToken
),
3586 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3587 'user_editcount' => 0,
3588 'user_touched' => $dbw->timestamp( self
::newTouchedTimestamp() ),
3590 foreach ( $params as $name => $value ) {
3591 $fields["user_$name"] = $value;
3593 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3594 if ( $dbw->affectedRows() ) {
3595 $newUser = User
::newFromId( $dbw->insertId() );
3603 * Add this existing user object to the database. If the user already
3604 * exists, a fatal status object is returned, and the user object is
3605 * initialised with the data from the database.
3607 * Previously, this function generated a DB error due to a key conflict
3608 * if the user already existed. Many extension callers use this function
3609 * in code along the lines of:
3611 * $user = User::newFromName( $name );
3612 * if ( !$user->isLoggedIn() ) {
3613 * $user->addToDatabase();
3615 * // do something with $user...
3617 * However, this was vulnerable to a race condition (bug 16020). By
3618 * initialising the user object if the user exists, we aim to support this
3619 * calling sequence as far as possible.
3621 * Note that if the user exists, this function will acquire a write lock,
3622 * so it is still advisable to make the call conditional on isLoggedIn(),
3623 * and to commit the transaction after calling.
3625 * @throws MWException
3628 public function addToDatabase() {
3630 $this->loadPasswords();
3631 if ( !$this->mToken
) {
3632 $this->setToken(); // init token
3635 $this->mTouched
= self
::newTouchedTimestamp();
3637 $dbw = wfGetDB( DB_MASTER
);
3638 $inWrite = $dbw->writesOrCallbacksPending();
3639 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3640 $dbw->insert( 'user',
3642 'user_id' => $seqVal,
3643 'user_name' => $this->mName
,
3644 'user_password' => $this->mPassword
->toString(),
3645 'user_newpassword' => $this->mNewpassword
->toString(),
3646 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3647 'user_email' => $this->mEmail
,
3648 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3649 'user_real_name' => $this->mRealName
,
3650 'user_token' => strval( $this->mToken
),
3651 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3652 'user_editcount' => 0,
3653 'user_touched' => $dbw->timestamp( $this->mTouched
),
3657 if ( !$dbw->affectedRows() ) {
3658 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3659 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3661 // Can't commit due to pending writes that may need atomicity.
3662 // This may cause some lock contention unlike the case below.
3663 $options = array( 'LOCK IN SHARE MODE' );
3664 $flags = self
::READ_LOCKING
;
3666 // Often, this case happens early in views before any writes when
3667 // using CentralAuth. It's should be OK to commit and break the snapshot.
3668 $dbw->commit( __METHOD__
, 'flush' );
3672 $this->mId
= $dbw->selectField( 'user', 'user_id',
3673 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3676 if ( $this->loadFromDatabase( $flags ) ) {
3681 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3682 "to insert user '{$this->mName}' row, but it was not present in select!" );
3684 return Status
::newFatal( 'userexists' );
3686 $this->mId
= $dbw->insertId();
3688 // Clear instance cache other than user table data, which is already accurate
3689 $this->clearInstanceCache();
3691 $this->saveOptions();
3692 return Status
::newGood();
3696 * If this user is logged-in and blocked,
3697 * block any IP address they've successfully logged in from.
3698 * @return bool A block was spread
3700 public function spreadAnyEditBlock() {
3701 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3702 return $this->spreadBlock();
3708 * If this (non-anonymous) user is blocked,
3709 * block the IP address they've successfully logged in from.
3710 * @return bool A block was spread
3712 protected function spreadBlock() {
3713 wfDebug( __METHOD__
. "()\n" );
3715 if ( $this->mId
== 0 ) {
3719 $userblock = Block
::newFromTarget( $this->getName() );
3720 if ( !$userblock ) {
3724 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3728 * Get whether the user is explicitly blocked from account creation.
3729 * @return bool|Block
3731 public function isBlockedFromCreateAccount() {
3732 $this->getBlockedStatus();
3733 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3734 return $this->mBlock
;
3737 # bug 13611: if the IP address the user is trying to create an account from is
3738 # blocked with createaccount disabled, prevent new account creation there even
3739 # when the user is logged in
3740 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3741 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3743 return $this->mBlockedFromCreateAccount
instanceof Block
3744 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3745 ?
$this->mBlockedFromCreateAccount
3750 * Get whether the user is blocked from using Special:Emailuser.
3753 public function isBlockedFromEmailuser() {
3754 $this->getBlockedStatus();
3755 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3759 * Get whether the user is allowed to create an account.
3762 public function isAllowedToCreateAccount() {
3763 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3767 * Get this user's personal page title.
3769 * @return Title User's personal page title
3771 public function getUserPage() {
3772 return Title
::makeTitle( NS_USER
, $this->getName() );
3776 * Get this user's talk page title.
3778 * @return Title User's talk page title
3780 public function getTalkPage() {
3781 $title = $this->getUserPage();
3782 return $title->getTalkPage();
3786 * Determine whether the user is a newbie. Newbies are either
3787 * anonymous IPs, or the most recently created accounts.
3790 public function isNewbie() {
3791 return !$this->isAllowed( 'autoconfirmed' );
3795 * Check to see if the given clear-text password is one of the accepted passwords
3796 * @param string $password User password
3797 * @return bool True if the given password is correct, otherwise False
3799 public function checkPassword( $password ) {
3800 global $wgAuth, $wgLegacyEncoding;
3802 $section = new ProfileSection( __METHOD__
);
3804 $this->loadPasswords();
3806 // Certain authentication plugins do NOT want to save
3807 // domain passwords in a mysql database, so we should
3808 // check this (in case $wgAuth->strict() is false).
3809 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3811 } elseif ( $wgAuth->strict() ) {
3812 // Auth plugin doesn't allow local authentication
3814 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3815 // Auth plugin doesn't allow local authentication for this user name
3819 if ( !$this->mPassword
->equals( $password ) ) {
3820 if ( $wgLegacyEncoding ) {
3821 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3822 // Check for this with iconv
3823 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3824 if ( $cp1252Password === $password ||
!$this->mPassword
->equals( $cp1252Password ) ) {
3832 $passwordFactory = self
::getPasswordFactory();
3833 if ( $passwordFactory->needsUpdate( $this->mPassword
) ) {
3834 $this->mPassword
= $passwordFactory->newFromPlaintext( $password );
3835 $this->saveSettings();
3842 * Check if the given clear-text password matches the temporary password
3843 * sent by e-mail for password reset operations.
3845 * @param string $plaintext
3847 * @return bool True if matches, false otherwise
3849 public function checkTemporaryPassword( $plaintext ) {
3850 global $wgNewPasswordExpiry;
3853 $this->loadPasswords();
3854 if ( $this->mNewpassword
->equals( $plaintext ) ) {
3855 if ( is_null( $this->mNewpassTime
) ) {
3858 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3859 return ( time() < $expiry );
3866 * Alias for getEditToken.
3867 * @deprecated since 1.19, use getEditToken instead.
3869 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3870 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3871 * @return string The new edit token
3873 public function editToken( $salt = '', $request = null ) {
3874 wfDeprecated( __METHOD__
, '1.19' );
3875 return $this->getEditToken( $salt, $request );
3879 * Internal implementation for self::getEditToken() and
3880 * self::matchEditToken().
3882 * @param string|array $salt
3883 * @param WebRequest $request
3884 * @param string|int $timestamp
3887 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
3888 if ( $this->isAnon() ) {
3889 return self
::EDIT_TOKEN_SUFFIX
;
3891 $token = $request->getSessionData( 'wsEditToken' );
3892 if ( $token === null ) {
3893 $token = MWCryptRand
::generateHex( 32 );
3894 $request->setSessionData( 'wsEditToken', $token );
3896 if ( is_array( $salt ) ) {
3897 $salt = implode( '|', $salt );
3899 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
3900 dechex( $timestamp ) .
3901 self
::EDIT_TOKEN_SUFFIX
;
3906 * Initialize (if necessary) and return a session token value
3907 * which can be used in edit forms to show that the user's
3908 * login credentials aren't being hijacked with a foreign form
3913 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3914 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3915 * @return string The new edit token
3917 public function getEditToken( $salt = '', $request = null ) {
3918 return $this->getEditTokenAtTimestamp(
3919 $salt, $request ?
: $this->getRequest(), wfTimestamp()
3924 * Generate a looking random token for various uses.
3926 * @return string The new random token
3927 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
3928 * wfRandomString for pseudo-randomness.
3930 public static function generateToken() {
3931 return MWCryptRand
::generateHex( 32 );
3935 * Check given value against the token value stored in the session.
3936 * A match should confirm that the form was submitted from the
3937 * user's own login session, not a form submission from a third-party
3940 * @param string $val Input value to compare
3941 * @param string $salt Optional function-specific data for hashing
3942 * @param WebRequest|null $request Object to use or null to use $wgRequest
3943 * @param int $maxage Fail tokens older than this, in seconds
3944 * @return bool Whether the token matches
3946 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
3947 if ( $this->isAnon() ) {
3948 return $val === self
::EDIT_TOKEN_SUFFIX
;
3951 $suffixLen = strlen( self
::EDIT_TOKEN_SUFFIX
);
3952 if ( strlen( $val ) <= 32 +
$suffixLen ) {
3956 $timestamp = hexdec( substr( $val, 32, -$suffixLen ) );
3957 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
3962 $sessionToken = $this->getEditTokenAtTimestamp(
3963 $salt, $request ?
: $this->getRequest(), $timestamp
3966 if ( $val != $sessionToken ) {
3967 wfDebug( "User::matchEditToken: broken session data\n" );
3970 return hash_equals( $sessionToken, $val );
3974 * Check given value against the token value stored in the session,
3975 * ignoring the suffix.
3977 * @param string $val Input value to compare
3978 * @param string $salt Optional function-specific data for hashing
3979 * @param WebRequest|null $request Object to use or null to use $wgRequest
3980 * @param int $maxage Fail tokens older than this, in seconds
3981 * @return bool Whether the token matches
3983 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
3984 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
3985 return $this->matchEditToken( $val, $salt, $request, $maxage );
3989 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3990 * mail to the user's given address.
3992 * @param string $type Message to send, either "created", "changed" or "set"
3995 public function sendConfirmationMail( $type = 'created' ) {
3997 $expiration = null; // gets passed-by-ref and defined in next line.
3998 $token = $this->confirmationToken( $expiration );
3999 $url = $this->confirmationTokenUrl( $token );
4000 $invalidateURL = $this->invalidationTokenUrl( $token );
4001 $this->saveSettings();
4003 if ( $type == 'created' ||
$type === false ) {
4004 $message = 'confirmemail_body';
4005 } elseif ( $type === true ) {
4006 $message = 'confirmemail_body_changed';
4008 // Messages: confirmemail_body_changed, confirmemail_body_set
4009 $message = 'confirmemail_body_' . $type;
4012 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4013 wfMessage( $message,
4014 $this->getRequest()->getIP(),
4017 $wgLang->timeanddate( $expiration, false ),
4019 $wgLang->date( $expiration, false ),
4020 $wgLang->time( $expiration, false ) )->text() );
4024 * Send an e-mail to this user's account. Does not check for
4025 * confirmed status or validity.
4027 * @param string $subject Message subject
4028 * @param string $body Message body
4029 * @param string $from Optional From address; if unspecified, default
4030 * $wgPasswordSender will be used.
4031 * @param string $replyto Reply-To address
4034 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4035 if ( is_null( $from ) ) {
4036 global $wgPasswordSender;
4037 $sender = new MailAddress( $wgPasswordSender,
4038 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4040 $sender = MailAddress
::newFromUser( $from );
4043 $to = MailAddress
::newFromUser( $this );
4044 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
4048 * Generate, store, and return a new e-mail confirmation code.
4049 * A hash (unsalted, since it's used as a key) is stored.
4051 * @note Call saveSettings() after calling this function to commit
4052 * this change to the database.
4054 * @param string &$expiration Accepts the expiration time
4055 * @return string New token
4057 protected function confirmationToken( &$expiration ) {
4058 global $wgUserEmailConfirmationTokenExpiry;
4060 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4061 $expiration = wfTimestamp( TS_MW
, $expires );
4063 $token = MWCryptRand
::generateHex( 32 );
4064 $hash = md5( $token );
4065 $this->mEmailToken
= $hash;
4066 $this->mEmailTokenExpires
= $expiration;
4071 * Return a URL the user can use to confirm their email address.
4072 * @param string $token Accepts the email confirmation token
4073 * @return string New token URL
4075 protected function confirmationTokenUrl( $token ) {
4076 return $this->getTokenUrl( 'ConfirmEmail', $token );
4080 * Return a URL the user can use to invalidate their email address.
4081 * @param string $token Accepts the email confirmation token
4082 * @return string New token URL
4084 protected function invalidationTokenUrl( $token ) {
4085 return $this->getTokenUrl( 'InvalidateEmail', $token );
4089 * Internal function to format the e-mail validation/invalidation URLs.
4090 * This uses a quickie hack to use the
4091 * hardcoded English names of the Special: pages, for ASCII safety.
4093 * @note Since these URLs get dropped directly into emails, using the
4094 * short English names avoids insanely long URL-encoded links, which
4095 * also sometimes can get corrupted in some browsers/mailers
4096 * (bug 6957 with Gmail and Internet Explorer).
4098 * @param string $page Special page
4099 * @param string $token Token
4100 * @return string Formatted URL
4102 protected function getTokenUrl( $page, $token ) {
4103 // Hack to bypass localization of 'Special:'
4104 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4105 return $title->getCanonicalURL();
4109 * Mark the e-mail address confirmed.
4111 * @note Call saveSettings() after calling this function to commit the change.
4115 public function confirmEmail() {
4116 // Check if it's already confirmed, so we don't touch the database
4117 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4118 if ( !$this->isEmailConfirmed() ) {
4119 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4120 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
4126 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4127 * address if it was already confirmed.
4129 * @note Call saveSettings() after calling this function to commit the change.
4130 * @return bool Returns true
4132 public function invalidateEmail() {
4134 $this->mEmailToken
= null;
4135 $this->mEmailTokenExpires
= null;
4136 $this->setEmailAuthenticationTimestamp( null );
4138 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
4143 * Set the e-mail authentication timestamp.
4144 * @param string $timestamp TS_MW timestamp
4146 public function setEmailAuthenticationTimestamp( $timestamp ) {
4148 $this->mEmailAuthenticated
= $timestamp;
4149 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4153 * Is this user allowed to send e-mails within limits of current
4154 * site configuration?
4157 public function canSendEmail() {
4158 global $wgEnableEmail, $wgEnableUserEmail;
4159 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4162 $canSend = $this->isEmailConfirmed();
4163 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4168 * Is this user allowed to receive e-mails within limits of current
4169 * site configuration?
4172 public function canReceiveEmail() {
4173 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4177 * Is this user's e-mail address valid-looking and confirmed within
4178 * limits of the current site configuration?
4180 * @note If $wgEmailAuthentication is on, this may require the user to have
4181 * confirmed their address by returning a code or using a password
4182 * sent to the address from the wiki.
4186 public function isEmailConfirmed() {
4187 global $wgEmailAuthentication;
4190 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4191 if ( $this->isAnon() ) {
4194 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4197 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4207 * Check whether there is an outstanding request for e-mail confirmation.
4210 public function isEmailConfirmationPending() {
4211 global $wgEmailAuthentication;
4212 return $wgEmailAuthentication &&
4213 !$this->isEmailConfirmed() &&
4214 $this->mEmailToken
&&
4215 $this->mEmailTokenExpires
> wfTimestamp();
4219 * Get the timestamp of account creation.
4221 * @return string|bool|null Timestamp of account creation, false for
4222 * non-existent/anonymous user accounts, or null if existing account
4223 * but information is not in database.
4225 public function getRegistration() {
4226 if ( $this->isAnon() ) {
4230 return $this->mRegistration
;
4234 * Get the timestamp of the first edit
4236 * @return string|bool Timestamp of first edit, or false for
4237 * non-existent/anonymous user accounts.
4239 public function getFirstEditTimestamp() {
4240 if ( $this->getId() == 0 ) {
4241 return false; // anons
4243 $dbr = wfGetDB( DB_SLAVE
);
4244 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4245 array( 'rev_user' => $this->getId() ),
4247 array( 'ORDER BY' => 'rev_timestamp ASC' )
4250 return false; // no edits
4252 return wfTimestamp( TS_MW
, $time );
4256 * Get the permissions associated with a given list of groups
4258 * @param array $groups Array of Strings List of internal group names
4259 * @return array Array of Strings List of permission key names for given groups combined
4261 public static function getGroupPermissions( $groups ) {
4262 global $wgGroupPermissions, $wgRevokePermissions;
4264 // grant every granted permission first
4265 foreach ( $groups as $group ) {
4266 if ( isset( $wgGroupPermissions[$group] ) ) {
4267 $rights = array_merge( $rights,
4268 // array_filter removes empty items
4269 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4272 // now revoke the revoked permissions
4273 foreach ( $groups as $group ) {
4274 if ( isset( $wgRevokePermissions[$group] ) ) {
4275 $rights = array_diff( $rights,
4276 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4279 return array_unique( $rights );
4283 * Get all the groups who have a given permission
4285 * @param string $role Role to check
4286 * @return array Array of Strings List of internal group names with the given permission
4288 public static function getGroupsWithPermission( $role ) {
4289 global $wgGroupPermissions;
4290 $allowedGroups = array();
4291 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4292 if ( self
::groupHasPermission( $group, $role ) ) {
4293 $allowedGroups[] = $group;
4296 return $allowedGroups;
4300 * Check, if the given group has the given permission
4302 * If you're wanting to check whether all users have a permission, use
4303 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4307 * @param string $group Group to check
4308 * @param string $role Role to check
4311 public static function groupHasPermission( $group, $role ) {
4312 global $wgGroupPermissions, $wgRevokePermissions;
4313 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4314 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4318 * Check if all users have the given permission
4321 * @param string $right Right to check
4324 public static function isEveryoneAllowed( $right ) {
4325 global $wgGroupPermissions, $wgRevokePermissions;
4326 static $cache = array();
4328 // Use the cached results, except in unit tests which rely on
4329 // being able change the permission mid-request
4330 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4331 return $cache[$right];
4334 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4335 $cache[$right] = false;
4339 // If it's revoked anywhere, then everyone doesn't have it
4340 foreach ( $wgRevokePermissions as $rights ) {
4341 if ( isset( $rights[$right] ) && $rights[$right] ) {
4342 $cache[$right] = false;
4347 // Allow extensions (e.g. OAuth) to say false
4348 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4349 $cache[$right] = false;
4353 $cache[$right] = true;
4358 * Get the localized descriptive name for a group, if it exists
4360 * @param string $group Internal group name
4361 * @return string Localized descriptive group name
4363 public static function getGroupName( $group ) {
4364 $msg = wfMessage( "group-$group" );
4365 return $msg->isBlank() ?
$group : $msg->text();
4369 * Get the localized descriptive name for a member of a group, if it exists
4371 * @param string $group Internal group name
4372 * @param string $username Username for gender (since 1.19)
4373 * @return string Localized name for group member
4375 public static function getGroupMember( $group, $username = '#' ) {
4376 $msg = wfMessage( "group-$group-member", $username );
4377 return $msg->isBlank() ?
$group : $msg->text();
4381 * Return the set of defined explicit groups.
4382 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4383 * are not included, as they are defined automatically, not in the database.
4384 * @return array Array of internal group names
4386 public static function getAllGroups() {
4387 global $wgGroupPermissions, $wgRevokePermissions;
4389 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4390 self
::getImplicitGroups()
4395 * Get a list of all available permissions.
4396 * @return array Array of permission names
4398 public static function getAllRights() {
4399 if ( self
::$mAllRights === false ) {
4400 global $wgAvailableRights;
4401 if ( count( $wgAvailableRights ) ) {
4402 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4404 self
::$mAllRights = self
::$mCoreRights;
4406 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
4408 return self
::$mAllRights;
4412 * Get a list of implicit groups
4413 * @return array Array of Strings Array of internal group names
4415 public static function getImplicitGroups() {
4416 global $wgImplicitGroups;
4418 $groups = $wgImplicitGroups;
4419 # Deprecated, use $wgImplictGroups instead
4420 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) );
4426 * Get the title of a page describing a particular group
4428 * @param string $group Internal group name
4429 * @return Title|bool Title of the page if it exists, false otherwise
4431 public static function getGroupPage( $group ) {
4432 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4433 if ( $msg->exists() ) {
4434 $title = Title
::newFromText( $msg->text() );
4435 if ( is_object( $title ) ) {
4443 * Create a link to the group in HTML, if available;
4444 * else return the group name.
4446 * @param string $group Internal name of the group
4447 * @param string $text The text of the link
4448 * @return string HTML link to the group
4450 public static function makeGroupLinkHTML( $group, $text = '' ) {
4451 if ( $text == '' ) {
4452 $text = self
::getGroupName( $group );
4454 $title = self
::getGroupPage( $group );
4456 return Linker
::link( $title, htmlspecialchars( $text ) );
4463 * Create a link to the group in Wikitext, if available;
4464 * else return the group name.
4466 * @param string $group Internal name of the group
4467 * @param string $text The text of the link
4468 * @return string Wikilink to the group
4470 public static function makeGroupLinkWiki( $group, $text = '' ) {
4471 if ( $text == '' ) {
4472 $text = self
::getGroupName( $group );
4474 $title = self
::getGroupPage( $group );
4476 $page = $title->getPrefixedText();
4477 return "[[$page|$text]]";
4484 * Returns an array of the groups that a particular group can add/remove.
4486 * @param string $group The group to check for whether it can add/remove
4487 * @return array Array( 'add' => array( addablegroups ),
4488 * 'remove' => array( removablegroups ),
4489 * 'add-self' => array( addablegroups to self),
4490 * 'remove-self' => array( removable groups from self) )
4492 public static function changeableByGroup( $group ) {
4493 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4497 'remove' => array(),
4498 'add-self' => array(),
4499 'remove-self' => array()
4502 if ( empty( $wgAddGroups[$group] ) ) {
4503 // Don't add anything to $groups
4504 } elseif ( $wgAddGroups[$group] === true ) {
4505 // You get everything
4506 $groups['add'] = self
::getAllGroups();
4507 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4508 $groups['add'] = $wgAddGroups[$group];
4511 // Same thing for remove
4512 if ( empty( $wgRemoveGroups[$group] ) ) {
4514 } elseif ( $wgRemoveGroups[$group] === true ) {
4515 $groups['remove'] = self
::getAllGroups();
4516 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4517 $groups['remove'] = $wgRemoveGroups[$group];
4520 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4521 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4522 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4523 if ( is_int( $key ) ) {
4524 $wgGroupsAddToSelf['user'][] = $value;
4529 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4530 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4531 if ( is_int( $key ) ) {
4532 $wgGroupsRemoveFromSelf['user'][] = $value;
4537 // Now figure out what groups the user can add to him/herself
4538 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4540 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4541 // No idea WHY this would be used, but it's there
4542 $groups['add-self'] = User
::getAllGroups();
4543 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4544 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4547 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4549 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4550 $groups['remove-self'] = User
::getAllGroups();
4551 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4552 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4559 * Returns an array of groups that this user can add and remove
4560 * @return array Array( 'add' => array( addablegroups ),
4561 * 'remove' => array( removablegroups ),
4562 * 'add-self' => array( addablegroups to self),
4563 * 'remove-self' => array( removable groups from self) )
4565 public function changeableGroups() {
4566 if ( $this->isAllowed( 'userrights' ) ) {
4567 // This group gives the right to modify everything (reverse-
4568 // compatibility with old "userrights lets you change
4570 // Using array_merge to make the groups reindexed
4571 $all = array_merge( User
::getAllGroups() );
4575 'add-self' => array(),
4576 'remove-self' => array()
4580 // Okay, it's not so simple, we will have to go through the arrays
4583 'remove' => array(),
4584 'add-self' => array(),
4585 'remove-self' => array()
4587 $addergroups = $this->getEffectiveGroups();
4589 foreach ( $addergroups as $addergroup ) {
4590 $groups = array_merge_recursive(
4591 $groups, $this->changeableByGroup( $addergroup )
4593 $groups['add'] = array_unique( $groups['add'] );
4594 $groups['remove'] = array_unique( $groups['remove'] );
4595 $groups['add-self'] = array_unique( $groups['add-self'] );
4596 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4602 * Increment the user's edit-count field.
4603 * Will have no effect for anonymous users.
4605 public function incEditCount() {
4606 if ( !$this->isAnon() ) {
4607 $dbw = wfGetDB( DB_MASTER
);
4610 array( 'user_editcount=user_editcount+1' ),
4611 array( 'user_id' => $this->getId() ),
4615 // Lazy initialization check...
4616 if ( $dbw->affectedRows() == 0 ) {
4617 // Now here's a goddamn hack...
4618 $dbr = wfGetDB( DB_SLAVE
);
4619 if ( $dbr !== $dbw ) {
4620 // If we actually have a slave server, the count is
4621 // at least one behind because the current transaction
4622 // has not been committed and replicated.
4623 $this->initEditCount( 1 );
4625 // But if DB_SLAVE is selecting the master, then the
4626 // count we just read includes the revision that was
4627 // just added in the working transaction.
4628 $this->initEditCount();
4632 // edit count in user cache too
4633 $this->invalidateCache();
4637 * Initialize user_editcount from data out of the revision table
4639 * @param int $add Edits to add to the count from the revision table
4640 * @return int Number of edits
4642 protected function initEditCount( $add = 0 ) {
4643 // Pull from a slave to be less cruel to servers
4644 // Accuracy isn't the point anyway here
4645 $dbr = wfGetDB( DB_SLAVE
);
4646 $count = (int)$dbr->selectField(
4649 array( 'rev_user' => $this->getId() ),
4652 $count = $count +
$add;
4654 $dbw = wfGetDB( DB_MASTER
);
4657 array( 'user_editcount' => $count ),
4658 array( 'user_id' => $this->getId() ),
4666 * Get the description of a given right
4668 * @param string $right Right to query
4669 * @return string Localized description of the right
4671 public static function getRightDescription( $right ) {
4672 $key = "right-$right";
4673 $msg = wfMessage( $key );
4674 return $msg->isBlank() ?
$right : $msg->text();
4678 * Make a new-style password hash
4680 * @param string $password Plain-text password
4681 * @param bool|string $salt Optional salt, may be random or the user ID.
4682 * If unspecified or false, will generate one automatically
4683 * @return string Password hash
4684 * @deprecated since 1.24, use Password class
4686 public static function crypt( $password, $salt = false ) {
4687 wfDeprecated( __METHOD__
, '1.24' );
4688 $hash = self
::getPasswordFactory()->newFromPlaintext( $password );
4689 return $hash->toString();
4693 * Compare a password hash with a plain-text password. Requires the user
4694 * ID if there's a chance that the hash is an old-style hash.
4696 * @param string $hash Password hash
4697 * @param string $password Plain-text password to compare
4698 * @param string|bool $userId User ID for old-style password salt
4701 * @deprecated since 1.24, use Password class
4703 public static function comparePasswords( $hash, $password, $userId = false ) {
4704 wfDeprecated( __METHOD__
, '1.24' );
4706 // Check for *really* old password hashes that don't even have a type
4707 // The old hash format was just an md5 hex hash, with no type information
4708 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4709 global $wgPasswordSalt;
4710 if ( $wgPasswordSalt ) {
4711 $password = ":B:{$userId}:{$hash}";
4713 $password = ":A:{$hash}";
4717 $hash = self
::getPasswordFactory()->newFromCiphertext( $hash );
4718 return $hash->equals( $password );
4722 * Add a newuser log entry for this user.
4723 * Before 1.19 the return value was always true.
4725 * @param string|bool $action Account creation type.
4726 * - String, one of the following values:
4727 * - 'create' for an anonymous user creating an account for himself.
4728 * This will force the action's performer to be the created user itself,
4729 * no matter the value of $wgUser
4730 * - 'create2' for a logged in user creating an account for someone else
4731 * - 'byemail' when the created user will receive its password by e-mail
4732 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4733 * - Boolean means whether the account was created by e-mail (deprecated):
4734 * - true will be converted to 'byemail'
4735 * - false will be converted to 'create' if this object is the same as
4736 * $wgUser and to 'create2' otherwise
4738 * @param string $reason User supplied reason
4740 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4742 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4743 global $wgUser, $wgNewUserLog;
4744 if ( empty( $wgNewUserLog ) ) {
4745 return true; // disabled
4748 if ( $action === true ) {
4749 $action = 'byemail';
4750 } elseif ( $action === false ) {
4751 if ( $this->getName() == $wgUser->getName() ) {
4754 $action = 'create2';
4758 if ( $action === 'create' ||
$action === 'autocreate' ) {
4761 $performer = $wgUser;
4764 $logEntry = new ManualLogEntry( 'newusers', $action );
4765 $logEntry->setPerformer( $performer );
4766 $logEntry->setTarget( $this->getUserPage() );
4767 $logEntry->setComment( $reason );
4768 $logEntry->setParameters( array(
4769 '4::userid' => $this->getId(),
4771 $logid = $logEntry->insert();
4773 if ( $action !== 'autocreate' ) {
4774 $logEntry->publish( $logid );
4781 * Add an autocreate newuser log entry for this user
4782 * Used by things like CentralAuth and perhaps other authplugins.
4783 * Consider calling addNewUserLogEntry() directly instead.
4787 public function addNewUserLogEntryAutoCreate() {
4788 $this->addNewUserLogEntry( 'autocreate' );
4794 * Load the user options either from cache, the database or an array
4796 * @param array $data Rows for the current user out of the user_properties table
4798 protected function loadOptions( $data = null ) {
4803 if ( $this->mOptionsLoaded
) {
4807 $this->mOptions
= self
::getDefaultOptions();
4809 if ( !$this->getId() ) {
4810 // For unlogged-in users, load language/variant options from request.
4811 // There's no need to do it for logged-in users: they can set preferences,
4812 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4813 // so don't override user's choice (especially when the user chooses site default).
4814 $variant = $wgContLang->getDefaultVariant();
4815 $this->mOptions
['variant'] = $variant;
4816 $this->mOptions
['language'] = $variant;
4817 $this->mOptionsLoaded
= true;
4821 // Maybe load from the object
4822 if ( !is_null( $this->mOptionOverrides
) ) {
4823 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4824 foreach ( $this->mOptionOverrides
as $key => $value ) {
4825 $this->mOptions
[$key] = $value;
4828 if ( !is_array( $data ) ) {
4829 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4830 // Load from database
4831 $dbr = wfGetDB( DB_SLAVE
);
4833 $res = $dbr->select(
4835 array( 'up_property', 'up_value' ),
4836 array( 'up_user' => $this->getId() ),
4840 $this->mOptionOverrides
= array();
4842 foreach ( $res as $row ) {
4843 $data[$row->up_property
] = $row->up_value
;
4846 foreach ( $data as $property => $value ) {
4847 $this->mOptionOverrides
[$property] = $value;
4848 $this->mOptions
[$property] = $value;
4852 $this->mOptionsLoaded
= true;
4854 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
4858 * Saves the non-default options for this user, as previously set e.g. via
4859 * setOption(), in the database's "user_properties" (preferences) table.
4860 * Usually used via saveSettings().
4862 protected function saveOptions() {
4863 $this->loadOptions();
4865 // Not using getOptions(), to keep hidden preferences in database
4866 $saveOptions = $this->mOptions
;
4868 // Allow hooks to abort, for instance to save to a global profile.
4869 // Reset options to default state before saving.
4870 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4874 $userId = $this->getId();
4876 $insert_rows = array(); // all the new preference rows
4877 foreach ( $saveOptions as $key => $value ) {
4878 // Don't bother storing default values
4879 $defaultOption = self
::getDefaultOption( $key );
4880 if ( ( $defaultOption === null && $value !== false && $value !== null )
4881 ||
$value != $defaultOption
4883 $insert_rows[] = array(
4884 'up_user' => $userId,
4885 'up_property' => $key,
4886 'up_value' => $value,
4891 $dbw = wfGetDB( DB_MASTER
);
4893 $res = $dbw->select( 'user_properties',
4894 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
4896 // Find prior rows that need to be removed or updated. These rows will
4897 // all be deleted (the later so that INSERT IGNORE applies the new values).
4898 $keysDelete = array();
4899 foreach ( $res as $row ) {
4900 if ( !isset( $saveOptions[$row->up_property
] )
4901 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
4903 $keysDelete[] = $row->up_property
;
4907 if ( count( $keysDelete ) ) {
4908 // Do the DELETE by PRIMARY KEY for prior rows.
4909 // In the past a very large portion of calls to this function are for setting
4910 // 'rememberpassword' for new accounts (a preference that has since been removed).
4911 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4912 // caused gap locks on [max user ID,+infinity) which caused high contention since
4913 // updates would pile up on each other as they are for higher (newer) user IDs.
4914 // It might not be necessary these days, but it shouldn't hurt either.
4915 $dbw->delete( 'user_properties',
4916 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
4918 // Insert the new preference rows
4919 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
4923 * Lazily instantiate and return a factory object for making passwords
4925 * @return PasswordFactory
4927 public static function getPasswordFactory() {
4928 if ( self
::$mPasswordFactory === null ) {
4929 self
::$mPasswordFactory = new PasswordFactory();
4930 self
::$mPasswordFactory->init( RequestContext
::getMain()->getConfig() );
4933 return self
::$mPasswordFactory;
4937 * Provide an array of HTML5 attributes to put on an input element
4938 * intended for the user to enter a new password. This may include
4939 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4941 * Do *not* use this when asking the user to enter his current password!
4942 * Regardless of configuration, users may have invalid passwords for whatever
4943 * reason (e.g., they were set before requirements were tightened up).
4944 * Only use it when asking for a new password, like on account creation or
4947 * Obviously, you still need to do server-side checking.
4949 * NOTE: A combination of bugs in various browsers means that this function
4950 * actually just returns array() unconditionally at the moment. May as
4951 * well keep it around for when the browser bugs get fixed, though.
4953 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4955 * @return array Array of HTML attributes suitable for feeding to
4956 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4957 * That will get confused by the boolean attribute syntax used.)
4959 public static function passwordChangeInputAttribs() {
4960 global $wgMinimalPasswordLength;
4962 if ( $wgMinimalPasswordLength == 0 ) {
4966 # Note that the pattern requirement will always be satisfied if the
4967 # input is empty, so we need required in all cases.
4969 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4970 # if e-mail confirmation is being used. Since HTML5 input validation
4971 # is b0rked anyway in some browsers, just return nothing. When it's
4972 # re-enabled, fix this code to not output required for e-mail
4974 #$ret = array( 'required' );
4977 # We can't actually do this right now, because Opera 9.6 will print out
4978 # the entered password visibly in its error message! When other
4979 # browsers add support for this attribute, or Opera fixes its support,
4980 # we can add support with a version check to avoid doing this on Opera
4981 # versions where it will be a problem. Reported to Opera as
4982 # DSK-262266, but they don't have a public bug tracker for us to follow.
4984 if ( $wgMinimalPasswordLength > 1 ) {
4985 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4986 $ret['title'] = wfMessage( 'passwordtooshort' )
4987 ->numParams( $wgMinimalPasswordLength )->text();
4995 * Return the list of user fields that should be selected to create
4996 * a new user object.
4999 public static function selectFields() {
5007 'user_email_authenticated',
5009 'user_email_token_expires',
5010 'user_registration',
5016 * Factory function for fatal permission-denied errors
5019 * @param string $permission User right required
5022 static function newFatalPermissionDeniedStatus( $permission ) {
5025 $groups = array_map(
5026 array( 'User', 'makeGroupLinkWiki' ),
5027 User
::getGroupsWithPermission( $permission )
5031 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5033 return Status
::newFatal( 'badaccess-group0' );