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 * Exclude user options that are set to their default value.
65 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
68 * @var PasswordFactory Lazily loaded factory object for passwords
70 private static $mPasswordFactory = null;
73 * Array of Strings List of member variables which are saved to the
74 * shared cache (memcached). Any operation which changes the
75 * corresponding database fields must call a cache-clearing function.
78 protected static $mCacheVars = array(
86 'mEmailAuthenticated',
93 // user_properties table
98 * Array of Strings Core rights.
99 * Each of these should have a corresponding message of the form
103 protected static $mCoreRights = array(
130 'editusercssjs', #deprecated
143 'move-categorypages',
144 'move-rootuserpages',
148 'override-export-depth',
172 'userrights-interwiki',
180 * String Cached results of getAllRights()
182 protected static $mAllRights = false;
184 /** @name Cache variables */
193 * @todo Make this actually private
199 * @todo Make this actually private
202 public $mNewpassword;
204 public $mNewpassTime;
207 /** @var string TS_MW timestamp from the DB */
209 /** @var string TS_MW timestamp from cache */
210 protected $mQuickTouched;
214 public $mEmailAuthenticated;
216 protected $mEmailToken;
218 protected $mEmailTokenExpires;
220 protected $mRegistration;
222 protected $mEditCount;
226 protected $mOptionOverrides;
228 protected $mPasswordExpires;
232 * Bool Whether the cache variables have been loaded.
235 public $mOptionsLoaded;
238 * Array with already loaded items or true if all items have been loaded.
240 protected $mLoadedItems = array();
244 * String Initialization data source if mLoadedItems!==true. May be one of:
245 * - 'defaults' anonymous user initialised from class defaults
246 * - 'name' initialise from mName
247 * - 'id' initialise from mId
248 * - 'session' log in from cookies or session if possible
250 * Use the User::newFrom*() family of functions to set this.
255 * Lazy-initialized variables, invalidated with clearInstanceCache
259 protected $mDatePreference;
267 protected $mBlockreason;
269 protected $mEffectiveGroups;
271 protected $mImplicitGroups;
273 protected $mFormerGroups;
275 protected $mBlockedGlobally;
292 protected $mAllowUsertalk;
295 private $mBlockedFromCreateAccount = false;
298 private $mWatchedItems = array();
300 public static $idCacheByName = array();
303 * Lightweight constructor for an anonymous user.
304 * Use the User::newFrom* factory functions for other kinds of users.
308 * @see newFromConfirmationCode()
309 * @see newFromSession()
312 public function __construct() {
313 $this->clearInstanceCache( 'defaults' );
319 public function __toString() {
320 return $this->getName();
324 * Load the user table data for this object from the source given by mFrom.
326 * @param integer $flags User::READ_* constant bitfield
328 public function load( $flags = self
::READ_LATEST
) {
329 if ( $this->mLoadedItems
=== true ) {
333 // Set it now to avoid infinite recursion in accessors
334 $this->mLoadedItems
= true;
336 switch ( $this->mFrom
) {
338 $this->loadDefaults();
341 // @TODO: this gets the ID from a slave, assuming renames
342 // are rare. This should be controllable and more consistent.
343 $this->mId
= self
::idFromName( $this->mName
);
345 // Nonexistent user placeholder object
346 $this->loadDefaults( $this->mName
);
348 $this->loadFromId( $flags );
352 $this->loadFromId( $flags );
355 if ( !$this->loadFromSession() ) {
356 // Loading from session failed. Load defaults.
357 $this->loadDefaults();
359 Hooks
::run( 'UserLoadAfterLoadFromSession', array( $this ) );
362 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
367 * Load user table data, given mId has already been set.
368 * @param integer $flags User::READ_* constant bitfield
369 * @return bool False if the ID does not exist, true otherwise
371 public function loadFromId( $flags = self
::READ_LATEST
) {
372 if ( $this->mId
== 0 ) {
373 $this->loadDefaults();
378 $cache = $this->loadFromCache();
380 wfDebug( "User: cache miss for user {$this->mId}\n" );
382 if ( !$this->loadFromDatabase( $flags ) ) {
383 // Can't load from ID, user is anonymous
386 if ( $flags & self
::READ_LATEST
) {
387 // Only save master data back to the cache to keep it consistent.
388 // @TODO: save it anyway and have callers specifiy $flags and have
389 // load() called as needed. That requires updating MANY callers...
390 $this->saveToCache();
394 $this->mLoadedItems
= true;
400 * Load user data from shared cache, given mId has already been set.
402 * @return bool false if the ID does not exist or data is invalid, true otherwise
405 public function loadFromCache() {
408 if ( $this->mId
== 0 ) {
409 $this->loadDefaults();
413 $key = wfMemcKey( 'user', 'id', $this->mId
);
414 $data = $wgMemc->get( $key );
415 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
420 wfDebug( "User: got user {$this->mId} from cache\n" );
422 // Restore from cache
423 foreach ( self
::$mCacheVars as $name ) {
424 $this->$name = $data[$name];
431 * Save user data to the shared cache
433 public function saveToCache() {
438 $this->loadOptions();
439 if ( $this->isAnon() ) {
440 // Anonymous users are uncached
444 foreach ( self
::$mCacheVars as $name ) {
445 $data[$name] = $this->$name;
447 $data['mVersion'] = self
::VERSION
;
448 $key = wfMemcKey( 'user', 'id', $this->mId
);
450 $wgMemc->set( $key, $data );
453 /** @name newFrom*() static factory methods */
457 * Static factory method for creation from username.
459 * This is slightly less efficient than newFromId(), so use newFromId() if
460 * you have both an ID and a name handy.
462 * @param string $name Username, validated by Title::newFromText()
463 * @param string|bool $validate Validate username. Takes the same parameters as
464 * User::getCanonicalName(), except that true is accepted as an alias
465 * for 'valid', for BC.
467 * @return User|bool User object, or false if the username is invalid
468 * (e.g. if it contains illegal characters or is an IP address). If the
469 * username is not present in the database, the result will be a user object
470 * with a name, zero user ID and default settings.
472 public static function newFromName( $name, $validate = 'valid' ) {
473 if ( $validate === true ) {
476 $name = self
::getCanonicalName( $name, $validate );
477 if ( $name === false ) {
480 // Create unloaded user object
484 $u->setItemLoaded( 'name' );
490 * Static factory method for creation from a given user ID.
492 * @param int $id Valid user ID
493 * @return User The corresponding User object
495 public static function newFromId( $id ) {
499 $u->setItemLoaded( 'id' );
504 * Factory method to fetch whichever user has a given email confirmation code.
505 * This code is generated when an account is created or its e-mail address
508 * If the code is invalid or has expired, returns NULL.
510 * @param string $code Confirmation code
513 public static function newFromConfirmationCode( $code ) {
514 $dbr = wfGetDB( DB_SLAVE
);
515 $id = $dbr->selectField( 'user', 'user_id', array(
516 'user_email_token' => md5( $code ),
517 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
519 if ( $id !== false ) {
520 return User
::newFromId( $id );
527 * Create a new user object using data from session or cookies. If the
528 * login credentials are invalid, the result is an anonymous user.
530 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
533 public static function newFromSession( WebRequest
$request = null ) {
535 $user->mFrom
= 'session';
536 $user->mRequest
= $request;
541 * Create a new user object from a user row.
542 * The row should have the following fields from the user table in it:
543 * - either user_name or user_id to load further data if needed (or both)
545 * - all other fields (email, password, etc.)
546 * It is useless to provide the remaining fields if either user_id,
547 * user_name and user_real_name are not provided because the whole row
548 * will be loaded once more from the database when accessing them.
550 * @param stdClass $row A row from the user table
551 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
554 public static function newFromRow( $row, $data = null ) {
556 $user->loadFromRow( $row, $data );
563 * Get the username corresponding to a given user ID
564 * @param int $id User ID
565 * @return string|bool The corresponding username
567 public static function whoIs( $id ) {
568 return UserCache
::singleton()->getProp( $id, 'name' );
572 * Get the real name of a user given their user ID
574 * @param int $id User ID
575 * @return string|bool The corresponding user's real name
577 public static function whoIsReal( $id ) {
578 return UserCache
::singleton()->getProp( $id, 'real_name' );
582 * Get database id given a user name
583 * @param string $name Username
584 * @return int|null The corresponding user's ID, or null if user is nonexistent
586 public static function idFromName( $name ) {
587 $nt = Title
::makeTitleSafe( NS_USER
, $name );
588 if ( is_null( $nt ) ) {
593 if ( isset( self
::$idCacheByName[$name] ) ) {
594 return self
::$idCacheByName[$name];
597 $dbr = wfGetDB( DB_SLAVE
);
598 $s = $dbr->selectRow(
601 array( 'user_name' => $nt->getText() ),
605 if ( $s === false ) {
608 $result = $s->user_id
;
611 self
::$idCacheByName[$name] = $result;
613 if ( count( self
::$idCacheByName ) > 1000 ) {
614 self
::$idCacheByName = array();
621 * Reset the cache used in idFromName(). For use in tests.
623 public static function resetIdByNameCache() {
624 self
::$idCacheByName = array();
628 * Does the string match an anonymous IPv4 address?
630 * This function exists for username validation, in order to reject
631 * usernames which are similar in form to IP addresses. Strings such
632 * as 300.300.300.300 will return true because it looks like an IP
633 * address, despite not being strictly valid.
635 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
636 * address because the usemod software would "cloak" anonymous IP
637 * addresses like this, if we allowed accounts like this to be created
638 * new users could get the old edits of these anonymous users.
640 * @param string $name Name to match
643 public static function isIP( $name ) {
644 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
645 || IP
::isIPv6( $name );
649 * Is the input a valid username?
651 * Checks if the input is a valid username, we don't want an empty string,
652 * an IP address, anything that contains slashes (would mess up subpages),
653 * is longer than the maximum allowed username size or doesn't begin with
656 * @param string $name Name to match
659 public static function isValidUserName( $name ) {
660 global $wgContLang, $wgMaxNameChars;
663 || User
::isIP( $name )
664 ||
strpos( $name, '/' ) !== false
665 ||
strlen( $name ) > $wgMaxNameChars
666 ||
$name != $wgContLang->ucfirst( $name )
668 wfDebugLog( 'username', __METHOD__
.
669 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
673 // Ensure that the name can't be misresolved as a different title,
674 // such as with extra namespace keys at the start.
675 $parsed = Title
::newFromText( $name );
676 if ( is_null( $parsed )
677 ||
$parsed->getNamespace()
678 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
679 wfDebugLog( 'username', __METHOD__
.
680 ": '$name' invalid due to ambiguous prefixes" );
684 // Check an additional blacklist of troublemaker characters.
685 // Should these be merged into the title char list?
686 $unicodeBlacklist = '/[' .
687 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
688 '\x{00a0}' . # non-breaking space
689 '\x{2000}-\x{200f}' . # various whitespace
690 '\x{2028}-\x{202f}' . # breaks and control chars
691 '\x{3000}' . # ideographic space
692 '\x{e000}-\x{f8ff}' . # private use
694 if ( preg_match( $unicodeBlacklist, $name ) ) {
695 wfDebugLog( 'username', __METHOD__
.
696 ": '$name' invalid due to blacklisted characters" );
704 * Usernames which fail to pass this function will be blocked
705 * from user login and new account registrations, but may be used
706 * internally by batch processes.
708 * If an account already exists in this form, login will be blocked
709 * by a failure to pass this function.
711 * @param string $name Name to match
714 public static function isUsableName( $name ) {
715 global $wgReservedUsernames;
716 // Must be a valid username, obviously ;)
717 if ( !self
::isValidUserName( $name ) ) {
721 static $reservedUsernames = false;
722 if ( !$reservedUsernames ) {
723 $reservedUsernames = $wgReservedUsernames;
724 Hooks
::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
727 // Certain names may be reserved for batch processes.
728 foreach ( $reservedUsernames as $reserved ) {
729 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
730 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
732 if ( $reserved == $name ) {
740 * Usernames which fail to pass this function will be blocked
741 * from new account registrations, but may be used internally
742 * either by batch processes or by user accounts which have
743 * already been created.
745 * Additional blacklisting may be added here rather than in
746 * isValidUserName() to avoid disrupting existing accounts.
748 * @param string $name String to match
751 public static function isCreatableName( $name ) {
752 global $wgInvalidUsernameCharacters;
754 // Ensure that the username isn't longer than 235 bytes, so that
755 // (at least for the builtin skins) user javascript and css files
756 // will work. (bug 23080)
757 if ( strlen( $name ) > 235 ) {
758 wfDebugLog( 'username', __METHOD__
.
759 ": '$name' invalid due to length" );
763 // Preg yells if you try to give it an empty string
764 if ( $wgInvalidUsernameCharacters !== '' ) {
765 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
766 wfDebugLog( 'username', __METHOD__
.
767 ": '$name' invalid due to wgInvalidUsernameCharacters" );
772 return self
::isUsableName( $name );
776 * Is the input a valid password for this user?
778 * @param string $password Desired password
781 public function isValidPassword( $password ) {
782 //simple boolean wrapper for getPasswordValidity
783 return $this->getPasswordValidity( $password ) === true;
788 * Given unvalidated password input, return error message on failure.
790 * @param string $password Desired password
791 * @return bool|string|array True on success, string or array of error message on failure
793 public function getPasswordValidity( $password ) {
794 $result = $this->checkPasswordValidity( $password );
795 if ( $result->isGood() ) {
799 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
800 $messages[] = $error['message'];
802 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
803 $messages[] = $warning['message'];
805 if ( count( $messages ) === 1 ) {
813 * Check if this is a valid password for this user. Status will be good if
814 * the password is valid, or have an array of error messages if not.
816 * @param string $password Desired password
820 public function checkPasswordValidity( $password ) {
821 global $wgMinimalPasswordLength, $wgContLang;
823 static $blockedLogins = array(
824 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
825 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
828 $status = Status
::newGood();
830 $result = false; //init $result to false for the internal checks
832 if ( !Hooks
::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
833 $status->error( $result );
837 if ( $result === false ) {
838 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
839 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
841 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
842 $status->error( 'password-name-match' );
844 } elseif ( isset( $blockedLogins[$this->getName()] )
845 && $password == $blockedLogins[$this->getName()]
847 $status->error( 'password-login-forbidden' );
850 //it seems weird returning a Good status here, but this is because of the
851 //initialization of $result to false above. If the hook is never run or it
852 //doesn't modify $result, then we will likely get down into this if with
856 } elseif ( $result === true ) {
859 $status->error( $result );
860 return $status; //the isValidPassword hook set a string $result and returned true
865 * Expire a user's password
867 * @param int $ts Optional timestamp to convert, default 0 for the current time
869 public function expirePassword( $ts = 0 ) {
870 $this->loadPasswords();
871 $timestamp = wfTimestamp( TS_MW
, $ts );
872 $this->mPasswordExpires
= $timestamp;
873 $this->saveSettings();
877 * Clear the password expiration for a user
879 * @param bool $load Ensure user object is loaded first
881 public function resetPasswordExpiration( $load = true ) {
882 global $wgPasswordExpirationDays;
887 if ( $wgPasswordExpirationDays ) {
888 $newExpire = wfTimestamp(
890 time() +
( $wgPasswordExpirationDays * 24 * 3600 )
893 // Give extensions a chance to force an expiration
894 Hooks
::run( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
895 $this->mPasswordExpires
= $newExpire;
899 * Check if the user's password is expired.
900 * TODO: Put this and password length into a PasswordPolicy object
902 * @return string|bool The expiration type, or false if not expired
903 * hard: A password change is required to login
904 * soft: Allow login, but encourage password change
905 * false: Password is not expired
907 public function getPasswordExpired() {
908 global $wgPasswordExpireGrace;
910 $now = wfTimestamp();
911 $expiration = $this->getPasswordExpireDate();
912 $expUnix = wfTimestamp( TS_UNIX
, $expiration );
913 if ( $expiration !== null && $expUnix < $now ) {
914 $expired = ( $expUnix +
$wgPasswordExpireGrace < $now ) ?
'hard' : 'soft';
920 * Get this user's password expiration date. Since this may be using
921 * the cached User object, we assume that whatever mechanism is setting
922 * the expiration date is also expiring the User cache.
924 * @return string|bool The datestamp of the expiration, or null if not set
926 public function getPasswordExpireDate() {
928 return $this->mPasswordExpires
;
932 * Given unvalidated user input, return a canonical username, or false if
933 * the username is invalid.
934 * @param string $name User input
935 * @param string|bool $validate Type of validation to use:
936 * - false No validation
937 * - 'valid' Valid for batch processes
938 * - 'usable' Valid for batch processes and login
939 * - 'creatable' Valid for batch processes, login and account creation
941 * @throws MWException
942 * @return bool|string
944 public static function getCanonicalName( $name, $validate = 'valid' ) {
945 // Force usernames to capital
947 $name = $wgContLang->ucfirst( $name );
949 # Reject names containing '#'; these will be cleaned up
950 # with title normalisation, but then it's too late to
952 if ( strpos( $name, '#' ) !== false ) {
956 // Clean up name according to title rules,
957 // but only when validation is requested (bug 12654)
958 $t = ( $validate !== false ) ?
959 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
960 // Check for invalid titles
961 if ( is_null( $t ) ) {
965 // Reject various classes of invalid names
967 $name = $wgAuth->getCanonicalName( $t->getText() );
969 switch ( $validate ) {
973 if ( !User
::isValidUserName( $name ) ) {
978 if ( !User
::isUsableName( $name ) ) {
983 if ( !User
::isCreatableName( $name ) ) {
988 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
994 * Count the number of edits of a user
996 * @param int $uid User ID to check
997 * @return int The user's edit count
999 * @deprecated since 1.21 in favour of User::getEditCount
1001 public static function edits( $uid ) {
1002 wfDeprecated( __METHOD__
, '1.21' );
1003 $user = self
::newFromId( $uid );
1004 return $user->getEditCount();
1008 * Return a random password.
1010 * @return string New random password
1012 public static function randomPassword() {
1013 global $wgMinimalPasswordLength;
1014 // Decide the final password length based on our min password length,
1015 // stopping at a minimum of 10 chars.
1016 $length = max( 10, $wgMinimalPasswordLength );
1017 // Multiply by 1.25 to get the number of hex characters we need
1018 $length = $length * 1.25;
1019 // Generate random hex chars
1020 $hex = MWCryptRand
::generateHex( $length );
1021 // Convert from base 16 to base 32 to get a proper password like string
1022 return wfBaseConvert( $hex, 16, 32 );
1026 * Set cached properties to default.
1028 * @note This no longer clears uncached lazy-initialised properties;
1029 * the constructor does that instead.
1031 * @param string|bool $name
1033 public function loadDefaults( $name = false ) {
1035 $passwordFactory = self
::getPasswordFactory();
1038 $this->mName
= $name;
1039 $this->mRealName
= '';
1040 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1041 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1042 $this->mNewpassTime
= null;
1044 $this->mOptionOverrides
= null;
1045 $this->mOptionsLoaded
= false;
1047 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1048 if ( $loggedOut !== null ) {
1049 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1051 $this->mTouched
= '1'; # Allow any pages to be cached
1054 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1055 $this->mEmailAuthenticated
= null;
1056 $this->mEmailToken
= '';
1057 $this->mEmailTokenExpires
= null;
1058 $this->mPasswordExpires
= null;
1059 $this->resetPasswordExpiration( false );
1060 $this->mRegistration
= wfTimestamp( TS_MW
);
1061 $this->mGroups
= array();
1063 Hooks
::run( 'UserLoadDefaults', array( $this, $name ) );
1068 * Return whether an item has been loaded.
1070 * @param string $item Item to check. Current possibilities:
1074 * @param string $all 'all' to check if the whole object has been loaded
1075 * or any other string to check if only the item is available (e.g.
1079 public function isItemLoaded( $item, $all = 'all' ) {
1080 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1081 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1085 * Set that an item has been loaded
1087 * @param string $item
1089 protected function setItemLoaded( $item ) {
1090 if ( is_array( $this->mLoadedItems
) ) {
1091 $this->mLoadedItems
[$item] = true;
1096 * Load user data from the session or login cookie.
1098 * @return bool True if the user is logged in, false otherwise.
1100 private function loadFromSession() {
1102 Hooks
::run( 'UserLoadFromSession', array( $this, &$result ) );
1103 if ( $result !== null ) {
1107 $request = $this->getRequest();
1109 $cookieId = $request->getCookie( 'UserID' );
1110 $sessId = $request->getSessionData( 'wsUserID' );
1112 if ( $cookieId !== null ) {
1113 $sId = intval( $cookieId );
1114 if ( $sessId !== null && $cookieId != $sessId ) {
1115 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1116 cookie user ID ($sId) don't match!" );
1119 $request->setSessionData( 'wsUserID', $sId );
1120 } elseif ( $sessId !== null && $sessId != 0 ) {
1126 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1127 $sName = $request->getSessionData( 'wsUserName' );
1128 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1129 $sName = $request->getCookie( 'UserName' );
1130 $request->setSessionData( 'wsUserName', $sName );
1135 $proposedUser = User
::newFromId( $sId );
1136 $proposedUser->load( self
::READ_LATEST
);
1137 if ( !$proposedUser->isLoggedIn() ) {
1142 global $wgBlockDisablesLogin;
1143 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1144 // User blocked and we've disabled blocked user logins
1148 if ( $request->getSessionData( 'wsToken' ) ) {
1150 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1152 } elseif ( $request->getCookie( 'Token' ) ) {
1153 # Get the token from DB/cache and clean it up to remove garbage padding.
1154 # This deals with historical problems with bugs and the default column value.
1155 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1156 // Make comparison in constant time (bug 61346)
1157 $passwordCorrect = strlen( $token )
1158 && hash_equals( $token, $request->getCookie( 'Token' ) );
1161 // No session or persistent login cookie
1165 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1166 $this->loadFromUserObject( $proposedUser );
1167 $request->setSessionData( 'wsToken', $this->mToken
);
1168 wfDebug( "User: logged in from $from\n" );
1171 // Invalid credentials
1172 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1178 * Load user and user_group data from the database.
1179 * $this->mId must be set, this is how the user is identified.
1181 * @param integer $flags User::READ_* constant bitfield
1182 * @return bool True if the user exists, false if the user is anonymous
1184 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1186 $this->mId
= intval( $this->mId
);
1189 if ( !$this->mId
) {
1190 $this->loadDefaults();
1194 $db = ( $flags & self
::READ_LATEST
)
1195 ?
wfGetDB( DB_MASTER
)
1196 : wfGetDB( DB_SLAVE
);
1198 $s = $db->selectRow(
1200 self
::selectFields(),
1201 array( 'user_id' => $this->mId
),
1203 ( $flags & self
::READ_LOCKING
== self
::READ_LOCKING
)
1204 ?
array( 'LOCK IN SHARE MODE' )
1208 Hooks
::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1210 if ( $s !== false ) {
1211 // Initialise user table data
1212 $this->loadFromRow( $s );
1213 $this->mGroups
= null; // deferred
1214 $this->getEditCount(); // revalidation for nulls
1219 $this->loadDefaults();
1225 * Initialize this object from a row from the user table.
1227 * @param stdClass $row Row from the user table to load.
1228 * @param array $data Further user data to load into the object
1230 * user_groups Array with groups out of the user_groups table
1231 * user_properties Array with properties out of the user_properties table
1233 public function loadFromRow( $row, $data = null ) {
1235 $passwordFactory = self
::getPasswordFactory();
1237 $this->mGroups
= null; // deferred
1239 if ( isset( $row->user_name
) ) {
1240 $this->mName
= $row->user_name
;
1241 $this->mFrom
= 'name';
1242 $this->setItemLoaded( 'name' );
1247 if ( isset( $row->user_real_name
) ) {
1248 $this->mRealName
= $row->user_real_name
;
1249 $this->setItemLoaded( 'realname' );
1254 if ( isset( $row->user_id
) ) {
1255 $this->mId
= intval( $row->user_id
);
1256 $this->mFrom
= 'id';
1257 $this->setItemLoaded( 'id' );
1262 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1263 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1266 if ( isset( $row->user_editcount
) ) {
1267 $this->mEditCount
= $row->user_editcount
;
1272 if ( isset( $row->user_password
) ) {
1273 // Check for *really* old password hashes that don't even have a type
1274 // The old hash format was just an md5 hex hash, with no type information
1275 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password
) ) {
1276 $row->user_password
= ":A:{$this->mId}:{$row->user_password}";
1280 $this->mPassword
= $passwordFactory->newFromCiphertext( $row->user_password
);
1281 } catch ( PasswordError
$e ) {
1282 wfDebug( 'Invalid password hash found in database.' );
1283 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1287 $this->mNewpassword
= $passwordFactory->newFromCiphertext( $row->user_newpassword
);
1288 } catch ( PasswordError
$e ) {
1289 wfDebug( 'Invalid password hash found in database.' );
1290 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1293 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1294 $this->mPasswordExpires
= wfTimestampOrNull( TS_MW
, $row->user_password_expires
);
1297 if ( isset( $row->user_email
) ) {
1298 $this->mEmail
= $row->user_email
;
1299 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1300 $this->mToken
= $row->user_token
;
1301 if ( $this->mToken
== '' ) {
1302 $this->mToken
= null;
1304 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1305 $this->mEmailToken
= $row->user_email_token
;
1306 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1307 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1313 $this->mLoadedItems
= true;
1316 if ( is_array( $data ) ) {
1317 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1318 $this->mGroups
= $data['user_groups'];
1320 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1321 $this->loadOptions( $data['user_properties'] );
1327 * Load the data for this user object from another user object.
1331 protected function loadFromUserObject( $user ) {
1333 $user->loadGroups();
1334 $user->loadOptions();
1335 foreach ( self
::$mCacheVars as $var ) {
1336 $this->$var = $user->$var;
1341 * Load the groups from the database if they aren't already loaded.
1343 private function loadGroups() {
1344 if ( is_null( $this->mGroups
) ) {
1345 $dbr = wfGetDB( DB_MASTER
);
1346 $res = $dbr->select( 'user_groups',
1347 array( 'ug_group' ),
1348 array( 'ug_user' => $this->mId
),
1350 $this->mGroups
= array();
1351 foreach ( $res as $row ) {
1352 $this->mGroups
[] = $row->ug_group
;
1358 * Load the user's password hashes from the database
1360 * This is usually called in a scenario where the actual User object was
1361 * loaded from the cache, and then password comparison needs to be performed.
1362 * Password hashes are not stored in memcached.
1366 private function loadPasswords() {
1367 if ( $this->getId() !== 0 && ( $this->mPassword
=== null ||
$this->mNewpassword
=== null ) ) {
1368 $this->loadFromRow( wfGetDB( DB_MASTER
)->selectRow(
1370 array( 'user_password', 'user_newpassword', 'user_newpass_time', 'user_password_expires' ),
1371 array( 'user_id' => $this->getId() ),
1378 * Add the user to the group if he/she meets given criteria.
1380 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1381 * possible to remove manually via Special:UserRights. In such case it
1382 * will not be re-added automatically. The user will also not lose the
1383 * group if they no longer meet the criteria.
1385 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1387 * @return array Array of groups the user has been promoted to.
1389 * @see $wgAutopromoteOnce
1391 public function addAutopromoteOnceGroups( $event ) {
1392 global $wgAutopromoteOnceLogInRC, $wgAuth;
1394 $toPromote = array();
1395 if ( $this->getId() ) {
1396 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1397 if ( count( $toPromote ) ) {
1398 $oldGroups = $this->getGroups(); // previous groups
1400 foreach ( $toPromote as $group ) {
1401 $this->addGroup( $group );
1403 // update groups in external authentication database
1404 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1406 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1408 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1409 $logEntry->setPerformer( $this );
1410 $logEntry->setTarget( $this->getUserPage() );
1411 $logEntry->setParameters( array(
1412 '4::oldgroups' => $oldGroups,
1413 '5::newgroups' => $newGroups,
1415 $logid = $logEntry->insert();
1416 if ( $wgAutopromoteOnceLogInRC ) {
1417 $logEntry->publish( $logid );
1425 * Clear various cached data stored in this object. The cache of the user table
1426 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1428 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1429 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1431 public function clearInstanceCache( $reloadFrom = false ) {
1432 $this->mNewtalk
= -1;
1433 $this->mDatePreference
= null;
1434 $this->mBlockedby
= -1; # Unset
1435 $this->mHash
= false;
1436 $this->mRights
= null;
1437 $this->mEffectiveGroups
= null;
1438 $this->mImplicitGroups
= null;
1439 $this->mGroups
= null;
1440 $this->mOptions
= null;
1441 $this->mOptionsLoaded
= false;
1442 $this->mEditCount
= null;
1444 if ( $reloadFrom ) {
1445 $this->mLoadedItems
= array();
1446 $this->mFrom
= $reloadFrom;
1451 * Combine the language default options with any site-specific options
1452 * and add the default language variants.
1454 * @return array Array of String options
1456 public static function getDefaultOptions() {
1457 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1459 static $defOpt = null;
1460 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1461 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1462 // mid-request and see that change reflected in the return value of this function.
1463 // Which is insane and would never happen during normal MW operation
1467 $defOpt = $wgDefaultUserOptions;
1468 // Default language setting
1469 $defOpt['language'] = $wgContLang->getCode();
1470 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1471 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1473 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1474 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1476 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1478 Hooks
::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1484 * Get a given default option value.
1486 * @param string $opt Name of option to retrieve
1487 * @return string Default option value
1489 public static function getDefaultOption( $opt ) {
1490 $defOpts = self
::getDefaultOptions();
1491 if ( isset( $defOpts[$opt] ) ) {
1492 return $defOpts[$opt];
1499 * Get blocking information
1500 * @param bool $bFromSlave Whether to check the slave database first.
1501 * To improve performance, non-critical checks are done against slaves.
1502 * Check when actually saving should be done against master.
1504 private function getBlockedStatus( $bFromSlave = true ) {
1505 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1507 if ( -1 != $this->mBlockedby
) {
1511 wfDebug( __METHOD__
. ": checking...\n" );
1513 // Initialize data...
1514 // Otherwise something ends up stomping on $this->mBlockedby when
1515 // things get lazy-loaded later, causing false positive block hits
1516 // due to -1 !== 0. Probably session-related... Nothing should be
1517 // overwriting mBlockedby, surely?
1520 # We only need to worry about passing the IP address to the Block generator if the
1521 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1522 # know which IP address they're actually coming from
1523 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1524 $ip = $this->getRequest()->getIP();
1530 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1533 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1534 && !in_array( $ip, $wgProxyWhitelist )
1537 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1539 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1540 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1541 $block->setTarget( $ip );
1542 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1544 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1545 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1546 $block->setTarget( $ip );
1550 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1551 if ( !$block instanceof Block
1552 && $wgApplyIpBlocksToXff
1554 && !$this->isAllowed( 'proxyunbannable' )
1555 && !in_array( $ip, $wgProxyWhitelist )
1557 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1558 $xff = array_map( 'trim', explode( ',', $xff ) );
1559 $xff = array_diff( $xff, array( $ip ) );
1560 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1561 $block = Block
::chooseBlock( $xffblocks, $xff );
1562 if ( $block instanceof Block
) {
1563 # Mangle the reason to alert the user that the block
1564 # originated from matching the X-Forwarded-For header.
1565 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1569 if ( $block instanceof Block
) {
1570 wfDebug( __METHOD__
. ": Found block.\n" );
1571 $this->mBlock
= $block;
1572 $this->mBlockedby
= $block->getByName();
1573 $this->mBlockreason
= $block->mReason
;
1574 $this->mHideName
= $block->mHideName
;
1575 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1577 $this->mBlockedby
= '';
1578 $this->mHideName
= 0;
1579 $this->mAllowUsertalk
= false;
1583 Hooks
::run( 'GetBlockedStatus', array( &$this ) );
1588 * Whether the given IP is in a DNS blacklist.
1590 * @param string $ip IP to check
1591 * @param bool $checkWhitelist Whether to check the whitelist first
1592 * @return bool True if blacklisted.
1594 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1595 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1597 if ( !$wgEnableDnsBlacklist ) {
1601 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1605 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1609 * Whether the given IP is in a given DNS blacklist.
1611 * @param string $ip IP to check
1612 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1613 * @return bool True if blacklisted.
1615 public function inDnsBlacklist( $ip, $bases ) {
1618 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1619 if ( IP
::isIPv4( $ip ) ) {
1620 // Reverse IP, bug 21255
1621 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1623 foreach ( (array)$bases as $base ) {
1625 // If we have an access key, use that too (ProjectHoneypot, etc.)
1626 if ( is_array( $base ) ) {
1627 if ( count( $base ) >= 2 ) {
1628 // Access key is 1, base URL is 0
1629 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1631 $host = "$ipReversed.{$base[0]}";
1634 $host = "$ipReversed.$base";
1638 $ipList = gethostbynamel( $host );
1641 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1645 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1654 * Check if an IP address is in the local proxy list
1660 public static function isLocallyBlockedProxy( $ip ) {
1661 global $wgProxyList;
1663 if ( !$wgProxyList ) {
1667 if ( !is_array( $wgProxyList ) ) {
1668 // Load from the specified file
1669 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1672 if ( !is_array( $wgProxyList ) ) {
1674 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1676 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1677 // Old-style flipped proxy list
1686 * Is this user subject to rate limiting?
1688 * @return bool True if rate limited
1690 public function isPingLimitable() {
1691 global $wgRateLimitsExcludedIPs;
1692 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1693 // No other good way currently to disable rate limits
1694 // for specific IPs. :P
1695 // But this is a crappy hack and should die.
1698 return !$this->isAllowed( 'noratelimit' );
1702 * Primitive rate limits: enforce maximum actions per time period
1703 * to put a brake on flooding.
1705 * The method generates both a generic profiling point and a per action one
1706 * (suffix being "-$action".
1708 * @note When using a shared cache like memcached, IP-address
1709 * last-hit counters will be shared across wikis.
1711 * @param string $action Action to enforce; 'edit' if unspecified
1712 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1713 * @return bool True if a rate limiter was tripped
1715 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1716 // Call the 'PingLimiter' hook
1718 if ( !Hooks
::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1722 global $wgRateLimits;
1723 if ( !isset( $wgRateLimits[$action] ) ) {
1727 // Some groups shouldn't trigger the ping limiter, ever
1728 if ( !$this->isPingLimitable() ) {
1734 $limits = $wgRateLimits[$action];
1736 $id = $this->getId();
1739 if ( isset( $limits['anon'] ) && $id == 0 ) {
1740 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1743 if ( isset( $limits['user'] ) && $id != 0 ) {
1744 $userLimit = $limits['user'];
1746 if ( $this->isNewbie() ) {
1747 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1748 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1750 if ( isset( $limits['ip'] ) ) {
1751 $ip = $this->getRequest()->getIP();
1752 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1754 if ( isset( $limits['subnet'] ) ) {
1755 $ip = $this->getRequest()->getIP();
1758 if ( IP
::isIPv6( $ip ) ) {
1759 $parts = IP
::parseRange( "$ip/64" );
1760 $subnet = $parts[0];
1761 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1763 $subnet = $matches[1];
1765 if ( $subnet !== false ) {
1766 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1770 // Check for group-specific permissions
1771 // If more than one group applies, use the group with the highest limit
1772 foreach ( $this->getGroups() as $group ) {
1773 if ( isset( $limits[$group] ) ) {
1774 if ( $userLimit === false
1775 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1777 $userLimit = $limits[$group];
1781 // Set the user limit key
1782 if ( $userLimit !== false ) {
1783 list( $max, $period ) = $userLimit;
1784 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1785 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1789 foreach ( $keys as $key => $limit ) {
1790 list( $max, $period ) = $limit;
1791 $summary = "(limit $max in {$period}s)";
1792 $count = $wgMemc->get( $key );
1795 if ( $count >= $max ) {
1796 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1797 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1800 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1803 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1804 if ( $incrBy > 0 ) {
1805 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1808 if ( $incrBy > 0 ) {
1809 $wgMemc->incr( $key, $incrBy );
1817 * Check if user is blocked
1819 * @param bool $bFromSlave Whether to check the slave database instead of
1820 * the master. Hacked from false due to horrible probs on site.
1821 * @return bool True if blocked, false otherwise
1823 public function isBlocked( $bFromSlave = true ) {
1824 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1828 * Get the block affecting the user, or null if the user is not blocked
1830 * @param bool $bFromSlave Whether to check the slave database instead of the master
1831 * @return Block|null
1833 public function getBlock( $bFromSlave = true ) {
1834 $this->getBlockedStatus( $bFromSlave );
1835 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1839 * Check if user is blocked from editing a particular article
1841 * @param Title $title Title to check
1842 * @param bool $bFromSlave Whether to check the slave database instead of the master
1845 public function isBlockedFrom( $title, $bFromSlave = false ) {
1846 global $wgBlockAllowsUTEdit;
1848 $blocked = $this->isBlocked( $bFromSlave );
1849 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1850 // If a user's name is suppressed, they cannot make edits anywhere
1851 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1852 && $title->getNamespace() == NS_USER_TALK
) {
1854 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1857 Hooks
::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1863 * If user is blocked, return the name of the user who placed the block
1864 * @return string Name of blocker
1866 public function blockedBy() {
1867 $this->getBlockedStatus();
1868 return $this->mBlockedby
;
1872 * If user is blocked, return the specified reason for the block
1873 * @return string Blocking reason
1875 public function blockedFor() {
1876 $this->getBlockedStatus();
1877 return $this->mBlockreason
;
1881 * If user is blocked, return the ID for the block
1882 * @return int Block ID
1884 public function getBlockId() {
1885 $this->getBlockedStatus();
1886 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1890 * Check if user is blocked on all wikis.
1891 * Do not use for actual edit permission checks!
1892 * This is intended for quick UI checks.
1894 * @param string $ip IP address, uses current client if none given
1895 * @return bool True if blocked, false otherwise
1897 public function isBlockedGlobally( $ip = '' ) {
1898 if ( $this->mBlockedGlobally
!== null ) {
1899 return $this->mBlockedGlobally
;
1901 // User is already an IP?
1902 if ( IP
::isIPAddress( $this->getName() ) ) {
1903 $ip = $this->getName();
1905 $ip = $this->getRequest()->getIP();
1908 Hooks
::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1909 $this->mBlockedGlobally
= (bool)$blocked;
1910 return $this->mBlockedGlobally
;
1914 * Check if user account is locked
1916 * @return bool True if locked, false otherwise
1918 public function isLocked() {
1919 if ( $this->mLocked
!== null ) {
1920 return $this->mLocked
;
1923 $authUser = $wgAuth->getUserInstance( $this );
1924 $this->mLocked
= (bool)$authUser->isLocked();
1925 return $this->mLocked
;
1929 * Check if user account is hidden
1931 * @return bool True if hidden, false otherwise
1933 public function isHidden() {
1934 if ( $this->mHideName
!== null ) {
1935 return $this->mHideName
;
1937 $this->getBlockedStatus();
1938 if ( !$this->mHideName
) {
1940 $authUser = $wgAuth->getUserInstance( $this );
1941 $this->mHideName
= (bool)$authUser->isHidden();
1943 return $this->mHideName
;
1947 * Get the user's ID.
1948 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1950 public function getId() {
1951 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1952 // Special case, we know the user is anonymous
1954 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1955 // Don't load if this was initialized from an ID
1962 * Set the user and reload all fields according to a given ID
1963 * @param int $v User ID to reload
1965 public function setId( $v ) {
1967 $this->clearInstanceCache( 'id' );
1971 * Get the user name, or the IP of an anonymous user
1972 * @return string User's name or IP address
1974 public function getName() {
1975 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1976 // Special case optimisation
1977 return $this->mName
;
1980 if ( $this->mName
=== false ) {
1982 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1984 return $this->mName
;
1989 * Set the user name.
1991 * This does not reload fields from the database according to the given
1992 * name. Rather, it is used to create a temporary "nonexistent user" for
1993 * later addition to the database. It can also be used to set the IP
1994 * address for an anonymous user to something other than the current
1997 * @note User::newFromName() has roughly the same function, when the named user
1999 * @param string $str New user name to set
2001 public function setName( $str ) {
2003 $this->mName
= $str;
2007 * Get the user's name escaped by underscores.
2008 * @return string Username escaped by underscores.
2010 public function getTitleKey() {
2011 return str_replace( ' ', '_', $this->getName() );
2015 * Check if the user has new messages.
2016 * @return bool True if the user has new messages
2018 public function getNewtalk() {
2021 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2022 if ( $this->mNewtalk
=== -1 ) {
2023 $this->mNewtalk
= false; # reset talk page status
2025 // Check memcached separately for anons, who have no
2026 // entire User object stored in there.
2027 if ( !$this->mId
) {
2028 global $wgDisableAnonTalk;
2029 if ( $wgDisableAnonTalk ) {
2030 // Anon newtalk disabled by configuration.
2031 $this->mNewtalk
= false;
2033 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2036 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2040 return (bool)$this->mNewtalk
;
2044 * Return the data needed to construct links for new talk page message
2045 * alerts. If there are new messages, this will return an associative array
2046 * with the following data:
2047 * wiki: The database name of the wiki
2048 * link: Root-relative link to the user's talk page
2049 * rev: The last talk page revision that the user has seen or null. This
2050 * is useful for building diff links.
2051 * If there are no new messages, it returns an empty array.
2052 * @note This function was designed to accomodate multiple talk pages, but
2053 * currently only returns a single link and revision.
2056 public function getNewMessageLinks() {
2058 if ( !Hooks
::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2060 } elseif ( !$this->getNewtalk() ) {
2063 $utp = $this->getTalkPage();
2064 $dbr = wfGetDB( DB_SLAVE
);
2065 // Get the "last viewed rev" timestamp from the oldest message notification
2066 $timestamp = $dbr->selectField( 'user_newtalk',
2067 'MIN(user_last_timestamp)',
2068 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2070 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2071 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2075 * Get the revision ID for the last talk page revision viewed by the talk
2077 * @return int|null Revision ID or null
2079 public function getNewMessageRevisionId() {
2080 $newMessageRevisionId = null;
2081 $newMessageLinks = $this->getNewMessageLinks();
2082 if ( $newMessageLinks ) {
2083 // Note: getNewMessageLinks() never returns more than a single link
2084 // and it is always for the same wiki, but we double-check here in
2085 // case that changes some time in the future.
2086 if ( count( $newMessageLinks ) === 1
2087 && $newMessageLinks[0]['wiki'] === wfWikiID()
2088 && $newMessageLinks[0]['rev']
2090 $newMessageRevision = $newMessageLinks[0]['rev'];
2091 $newMessageRevisionId = $newMessageRevision->getId();
2094 return $newMessageRevisionId;
2098 * Internal uncached check for new messages
2101 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2102 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2103 * @param bool $fromMaster True to fetch from the master, false for a slave
2104 * @return bool True if the user has new messages
2106 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2107 if ( $fromMaster ) {
2108 $db = wfGetDB( DB_MASTER
);
2110 $db = wfGetDB( DB_SLAVE
);
2112 $ok = $db->selectField( 'user_newtalk', $field,
2113 array( $field => $id ), __METHOD__
);
2114 return $ok !== false;
2118 * Add or update the new messages flag
2119 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2120 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2121 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2122 * @return bool True if successful, false otherwise
2124 protected function updateNewtalk( $field, $id, $curRev = null ) {
2125 // Get timestamp of the talk page revision prior to the current one
2126 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2127 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2128 // Mark the user as having new messages since this revision
2129 $dbw = wfGetDB( DB_MASTER
);
2130 $dbw->insert( 'user_newtalk',
2131 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2134 if ( $dbw->affectedRows() ) {
2135 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2138 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2144 * Clear the new messages flag for the given user
2145 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2146 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2147 * @return bool True if successful, false otherwise
2149 protected function deleteNewtalk( $field, $id ) {
2150 $dbw = wfGetDB( DB_MASTER
);
2151 $dbw->delete( 'user_newtalk',
2152 array( $field => $id ),
2154 if ( $dbw->affectedRows() ) {
2155 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2158 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2164 * Update the 'You have new messages!' status.
2165 * @param bool $val Whether the user has new messages
2166 * @param Revision $curRev New, as yet unseen revision of the user talk
2167 * page. Ignored if null or !$val.
2169 public function setNewtalk( $val, $curRev = null ) {
2170 if ( wfReadOnly() ) {
2175 $this->mNewtalk
= $val;
2177 if ( $this->isAnon() ) {
2179 $id = $this->getName();
2182 $id = $this->getId();
2187 $changed = $this->updateNewtalk( $field, $id, $curRev );
2189 $changed = $this->deleteNewtalk( $field, $id );
2192 if ( $this->isAnon() ) {
2193 // Anons have a separate memcached space, since
2194 // user records aren't kept for them.
2195 $key = wfMemcKey( 'newtalk', 'ip', $id );
2196 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
2199 $this->invalidateCache();
2204 * Generate a current or new-future timestamp to be stored in the
2205 * user_touched field when we update things.
2206 * @return string Timestamp in TS_MW format
2208 private static function newTouchedTimestamp() {
2209 global $wgClockSkewFudge;
2210 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2214 * Clear user data from memcached.
2215 * Use after applying fun updates to the database; caller's
2216 * responsibility to update user_touched if appropriate.
2218 * Called implicitly from invalidateCache() and saveSettings().
2220 public function clearSharedCache() {
2225 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
2230 * Immediately touch the user data cache for this account.
2231 * Updates user_touched field, and removes account data from memcached
2232 * for reload on the next hit.
2234 public function invalidateCache() {
2235 if ( wfReadOnly() ) {
2240 $this->mTouched
= self
::newTouchedTimestamp();
2242 $dbw = wfGetDB( DB_MASTER
);
2243 $userid = $this->mId
;
2244 $touched = $this->mTouched
;
2245 $method = __METHOD__
;
2246 $dbw->onTransactionIdle( function () use ( $dbw, $userid, $touched, $method ) {
2247 // Prevent contention slams by checking user_touched first
2248 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2249 $needsPurge = $dbw->selectField( 'user', '1',
2250 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2251 if ( $needsPurge ) {
2252 $dbw->update( 'user',
2253 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2254 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2259 $this->clearSharedCache();
2264 * Update the "touched" timestamp for the user
2266 * This is useful on various login/logout events when making sure that
2267 * a browser or proxy that has multiple tenants does not suffer cache
2268 * pollution where the new user sees the old users content. The value
2269 * of getTouched() is checked when determining 304 vs 200 responses.
2270 * Unlike invalidateCache(), this preserves the User object cache and
2271 * avoids database writes.
2275 public function touch() {
2281 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2282 $timestamp = self
::newTouchedTimestamp();
2283 $wgMemc->set( $key, $timestamp );
2284 $this->mQuickTouched
= $timestamp;
2289 * Validate the cache for this account.
2290 * @param string $timestamp A timestamp in TS_MW format
2293 public function validateCache( $timestamp ) {
2295 return ( $timestamp >= $this->mTouched
);
2299 * Get the user touched timestamp
2300 * @return string TS_MW Timestamp
2302 public function getTouched() {
2308 if ( $this->mQuickTouched
=== null ) {
2309 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2310 $timestamp = $wgMemc->get( $key );
2311 if ( !$timestamp ) {
2312 # Set the timestamp to get HTTP 304 cache hits
2317 return max( $this->mTouched
, $this->mQuickTouched
);
2320 return $this->mTouched
;
2327 public function getPassword() {
2328 $this->loadPasswords();
2330 return $this->mPassword
;
2337 public function getTemporaryPassword() {
2338 $this->loadPasswords();
2340 return $this->mNewpassword
;
2344 * Set the password and reset the random token.
2345 * Calls through to authentication plugin if necessary;
2346 * will have no effect if the auth plugin refuses to
2347 * pass the change through or if the legal password
2350 * As a special case, setting the password to null
2351 * wipes it, so the account cannot be logged in until
2352 * a new password is set, for instance via e-mail.
2354 * @param string $str New password to set
2355 * @throws PasswordError On failure
2359 public function setPassword( $str ) {
2362 $this->loadPasswords();
2364 if ( $str !== null ) {
2365 if ( !$wgAuth->allowPasswordChange() ) {
2366 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2369 if ( !$this->isValidPassword( $str ) ) {
2370 global $wgMinimalPasswordLength;
2371 $valid = $this->getPasswordValidity( $str );
2372 if ( is_array( $valid ) ) {
2373 $message = array_shift( $valid );
2377 $params = array( $wgMinimalPasswordLength );
2379 throw new PasswordError( wfMessage( $message, $params )->text() );
2383 if ( !$wgAuth->setPassword( $this, $str ) ) {
2384 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2387 $this->setInternalPassword( $str );
2393 * Set the password and reset the random token unconditionally.
2395 * @param string|null $str New password to set or null to set an invalid
2396 * password hash meaning that the user will not be able to log in
2397 * through the web interface.
2399 public function setInternalPassword( $str ) {
2402 $passwordFactory = self
::getPasswordFactory();
2403 $this->mPassword
= $passwordFactory->newFromPlaintext( $str );
2405 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
2406 $this->mNewpassTime
= null;
2410 * Get the user's current token.
2411 * @param bool $forceCreation Force the generation of a new token if the
2412 * user doesn't have one (default=true for backwards compatibility).
2413 * @return string Token
2415 public function getToken( $forceCreation = true ) {
2417 if ( !$this->mToken
&& $forceCreation ) {
2420 return $this->mToken
;
2424 * Set the random token (used for persistent authentication)
2425 * Called from loadDefaults() among other places.
2427 * @param string|bool $token If specified, set the token to this value
2429 public function setToken( $token = false ) {
2432 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2434 $this->mToken
= $token;
2439 * Set the password for a password reminder or new account email
2441 * @param string $str New password to set or null to set an invalid
2442 * password hash meaning that the user will not be able to use it
2443 * @param bool $throttle If true, reset the throttle timestamp to the present
2445 public function setNewpassword( $str, $throttle = true ) {
2446 $this->loadPasswords();
2448 $this->mNewpassword
= self
::getPasswordFactory()->newFromPlaintext( $str );
2449 if ( $str === null ) {
2450 $this->mNewpassTime
= null;
2451 } elseif ( $throttle ) {
2452 $this->mNewpassTime
= wfTimestampNow();
2457 * Has password reminder email been sent within the last
2458 * $wgPasswordReminderResendTime hours?
2461 public function isPasswordReminderThrottled() {
2462 global $wgPasswordReminderResendTime;
2464 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2467 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2468 return time() < $expiry;
2472 * Get the user's e-mail address
2473 * @return string User's email address
2475 public function getEmail() {
2477 Hooks
::run( 'UserGetEmail', array( $this, &$this->mEmail
) );
2478 return $this->mEmail
;
2482 * Get the timestamp of the user's e-mail authentication
2483 * @return string TS_MW timestamp
2485 public function getEmailAuthenticationTimestamp() {
2487 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2488 return $this->mEmailAuthenticated
;
2492 * Set the user's e-mail address
2493 * @param string $str New e-mail address
2495 public function setEmail( $str ) {
2497 if ( $str == $this->mEmail
) {
2500 $this->invalidateEmail();
2501 $this->mEmail
= $str;
2502 Hooks
::run( 'UserSetEmail', array( $this, &$this->mEmail
) );
2506 * Set the user's e-mail address and a confirmation mail if needed.
2509 * @param string $str New e-mail address
2512 public function setEmailWithConfirmation( $str ) {
2513 global $wgEnableEmail, $wgEmailAuthentication;
2515 if ( !$wgEnableEmail ) {
2516 return Status
::newFatal( 'emaildisabled' );
2519 $oldaddr = $this->getEmail();
2520 if ( $str === $oldaddr ) {
2521 return Status
::newGood( true );
2524 $this->setEmail( $str );
2526 if ( $str !== '' && $wgEmailAuthentication ) {
2527 // Send a confirmation request to the new address if needed
2528 $type = $oldaddr != '' ?
'changed' : 'set';
2529 $result = $this->sendConfirmationMail( $type );
2530 if ( $result->isGood() ) {
2531 // Say to the caller that a confirmation mail has been sent
2532 $result->value
= 'eauth';
2535 $result = Status
::newGood( true );
2542 * Get the user's real name
2543 * @return string User's real name
2545 public function getRealName() {
2546 if ( !$this->isItemLoaded( 'realname' ) ) {
2550 return $this->mRealName
;
2554 * Set the user's real name
2555 * @param string $str New real name
2557 public function setRealName( $str ) {
2559 $this->mRealName
= $str;
2563 * Get the user's current setting for a given option.
2565 * @param string $oname The option to check
2566 * @param string $defaultOverride A default value returned if the option does not exist
2567 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2568 * @return string User's current value for the option
2569 * @see getBoolOption()
2570 * @see getIntOption()
2572 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2573 global $wgHiddenPrefs;
2574 $this->loadOptions();
2576 # We want 'disabled' preferences to always behave as the default value for
2577 # users, even if they have set the option explicitly in their settings (ie they
2578 # set it, and then it was disabled removing their ability to change it). But
2579 # we don't want to erase the preferences in the database in case the preference
2580 # is re-enabled again. So don't touch $mOptions, just override the returned value
2581 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2582 return self
::getDefaultOption( $oname );
2585 if ( array_key_exists( $oname, $this->mOptions
) ) {
2586 return $this->mOptions
[$oname];
2588 return $defaultOverride;
2593 * Get all user's options
2595 * @param int $flags Bitwise combination of:
2596 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2597 * to the default value. (Since 1.25)
2600 public function getOptions( $flags = 0 ) {
2601 global $wgHiddenPrefs;
2602 $this->loadOptions();
2603 $options = $this->mOptions
;
2605 # We want 'disabled' preferences to always behave as the default value for
2606 # users, even if they have set the option explicitly in their settings (ie they
2607 # set it, and then it was disabled removing their ability to change it). But
2608 # we don't want to erase the preferences in the database in case the preference
2609 # is re-enabled again. So don't touch $mOptions, just override the returned value
2610 foreach ( $wgHiddenPrefs as $pref ) {
2611 $default = self
::getDefaultOption( $pref );
2612 if ( $default !== null ) {
2613 $options[$pref] = $default;
2617 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2618 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2625 * Get the user's current setting for a given option, as a boolean value.
2627 * @param string $oname The option to check
2628 * @return bool User's current value for the option
2631 public function getBoolOption( $oname ) {
2632 return (bool)$this->getOption( $oname );
2636 * Get the user's current setting for a given option, as an integer value.
2638 * @param string $oname The option to check
2639 * @param int $defaultOverride A default value returned if the option does not exist
2640 * @return int User's current value for the option
2643 public function getIntOption( $oname, $defaultOverride = 0 ) {
2644 $val = $this->getOption( $oname );
2646 $val = $defaultOverride;
2648 return intval( $val );
2652 * Set the given option for a user.
2654 * You need to call saveSettings() to actually write to the database.
2656 * @param string $oname The option to set
2657 * @param mixed $val New value to set
2659 public function setOption( $oname, $val ) {
2660 $this->loadOptions();
2662 // Explicitly NULL values should refer to defaults
2663 if ( is_null( $val ) ) {
2664 $val = self
::getDefaultOption( $oname );
2667 $this->mOptions
[$oname] = $val;
2671 * Get a token stored in the preferences (like the watchlist one),
2672 * resetting it if it's empty (and saving changes).
2674 * @param string $oname The option name to retrieve the token from
2675 * @return string|bool User's current value for the option, or false if this option is disabled.
2676 * @see resetTokenFromOption()
2679 public function getTokenFromOption( $oname ) {
2680 global $wgHiddenPrefs;
2681 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2685 $token = $this->getOption( $oname );
2687 $token = $this->resetTokenFromOption( $oname );
2688 $this->saveSettings();
2694 * Reset a token stored in the preferences (like the watchlist one).
2695 * *Does not* save user's preferences (similarly to setOption()).
2697 * @param string $oname The option name to reset the token in
2698 * @return string|bool New token value, or false if this option is disabled.
2699 * @see getTokenFromOption()
2702 public function resetTokenFromOption( $oname ) {
2703 global $wgHiddenPrefs;
2704 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2708 $token = MWCryptRand
::generateHex( 40 );
2709 $this->setOption( $oname, $token );
2714 * Return a list of the types of user options currently returned by
2715 * User::getOptionKinds().
2717 * Currently, the option kinds are:
2718 * - 'registered' - preferences which are registered in core MediaWiki or
2719 * by extensions using the UserGetDefaultOptions hook.
2720 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2721 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2722 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2723 * be used by user scripts.
2724 * - 'special' - "preferences" that are not accessible via User::getOptions
2725 * or User::setOptions.
2726 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2727 * These are usually legacy options, removed in newer versions.
2729 * The API (and possibly others) use this function to determine the possible
2730 * option types for validation purposes, so make sure to update this when a
2731 * new option kind is added.
2733 * @see User::getOptionKinds
2734 * @return array Option kinds
2736 public static function listOptionKinds() {
2739 'registered-multiselect',
2740 'registered-checkmatrix',
2748 * Return an associative array mapping preferences keys to the kind of a preference they're
2749 * used for. Different kinds are handled differently when setting or reading preferences.
2751 * See User::listOptionKinds for the list of valid option types that can be provided.
2753 * @see User::listOptionKinds
2754 * @param IContextSource $context
2755 * @param array $options Assoc. array with options keys to check as keys.
2756 * Defaults to $this->mOptions.
2757 * @return array The key => kind mapping data
2759 public function getOptionKinds( IContextSource
$context, $options = null ) {
2760 $this->loadOptions();
2761 if ( $options === null ) {
2762 $options = $this->mOptions
;
2765 $prefs = Preferences
::getPreferences( $this, $context );
2768 // Pull out the "special" options, so they don't get converted as
2769 // multiselect or checkmatrix.
2770 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2771 foreach ( $specialOptions as $name => $value ) {
2772 unset( $prefs[$name] );
2775 // Multiselect and checkmatrix options are stored in the database with
2776 // one key per option, each having a boolean value. Extract those keys.
2777 $multiselectOptions = array();
2778 foreach ( $prefs as $name => $info ) {
2779 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2780 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2781 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2782 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2784 foreach ( $opts as $value ) {
2785 $multiselectOptions["$prefix$value"] = true;
2788 unset( $prefs[$name] );
2791 $checkmatrixOptions = array();
2792 foreach ( $prefs as $name => $info ) {
2793 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2794 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2795 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2796 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2797 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2799 foreach ( $columns as $column ) {
2800 foreach ( $rows as $row ) {
2801 $checkmatrixOptions["$prefix$column-$row"] = true;
2805 unset( $prefs[$name] );
2809 // $value is ignored
2810 foreach ( $options as $key => $value ) {
2811 if ( isset( $prefs[$key] ) ) {
2812 $mapping[$key] = 'registered';
2813 } elseif ( isset( $multiselectOptions[$key] ) ) {
2814 $mapping[$key] = 'registered-multiselect';
2815 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2816 $mapping[$key] = 'registered-checkmatrix';
2817 } elseif ( isset( $specialOptions[$key] ) ) {
2818 $mapping[$key] = 'special';
2819 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2820 $mapping[$key] = 'userjs';
2822 $mapping[$key] = 'unused';
2830 * Reset certain (or all) options to the site defaults
2832 * The optional parameter determines which kinds of preferences will be reset.
2833 * Supported values are everything that can be reported by getOptionKinds()
2834 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2836 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2837 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2838 * for backwards-compatibility.
2839 * @param IContextSource|null $context Context source used when $resetKinds
2840 * does not contain 'all', passed to getOptionKinds().
2841 * Defaults to RequestContext::getMain() when null.
2843 public function resetOptions(
2844 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2845 IContextSource
$context = null
2848 $defaultOptions = self
::getDefaultOptions();
2850 if ( !is_array( $resetKinds ) ) {
2851 $resetKinds = array( $resetKinds );
2854 if ( in_array( 'all', $resetKinds ) ) {
2855 $newOptions = $defaultOptions;
2857 if ( $context === null ) {
2858 $context = RequestContext
::getMain();
2861 $optionKinds = $this->getOptionKinds( $context );
2862 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2863 $newOptions = array();
2865 // Use default values for the options that should be deleted, and
2866 // copy old values for the ones that shouldn't.
2867 foreach ( $this->mOptions
as $key => $value ) {
2868 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2869 if ( array_key_exists( $key, $defaultOptions ) ) {
2870 $newOptions[$key] = $defaultOptions[$key];
2873 $newOptions[$key] = $value;
2878 Hooks
::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2880 $this->mOptions
= $newOptions;
2881 $this->mOptionsLoaded
= true;
2885 * Get the user's preferred date format.
2886 * @return string User's preferred date format
2888 public function getDatePreference() {
2889 // Important migration for old data rows
2890 if ( is_null( $this->mDatePreference
) ) {
2892 $value = $this->getOption( 'date' );
2893 $map = $wgLang->getDatePreferenceMigrationMap();
2894 if ( isset( $map[$value] ) ) {
2895 $value = $map[$value];
2897 $this->mDatePreference
= $value;
2899 return $this->mDatePreference
;
2903 * Determine based on the wiki configuration and the user's options,
2904 * whether this user must be over HTTPS no matter what.
2908 public function requiresHTTPS() {
2909 global $wgSecureLogin;
2910 if ( !$wgSecureLogin ) {
2913 $https = $this->getBoolOption( 'prefershttps' );
2914 Hooks
::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2916 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2923 * Get the user preferred stub threshold
2927 public function getStubThreshold() {
2928 global $wgMaxArticleSize; # Maximum article size, in Kb
2929 $threshold = $this->getIntOption( 'stubthreshold' );
2930 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2931 // If they have set an impossible value, disable the preference
2932 // so we can use the parser cache again.
2939 * Get the permissions this user has.
2940 * @return array Array of String permission names
2942 public function getRights() {
2943 if ( is_null( $this->mRights
) ) {
2944 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2945 Hooks
::run( 'UserGetRights', array( $this, &$this->mRights
) );
2946 // Force reindexation of rights when a hook has unset one of them
2947 $this->mRights
= array_values( array_unique( $this->mRights
) );
2949 return $this->mRights
;
2953 * Get the list of explicit group memberships this user has.
2954 * The implicit * and user groups are not included.
2955 * @return array Array of String internal group names
2957 public function getGroups() {
2959 $this->loadGroups();
2960 return $this->mGroups
;
2964 * Get the list of implicit group memberships this user has.
2965 * This includes all explicit groups, plus 'user' if logged in,
2966 * '*' for all accounts, and autopromoted groups
2967 * @param bool $recache Whether to avoid the cache
2968 * @return array Array of String internal group names
2970 public function getEffectiveGroups( $recache = false ) {
2971 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2972 $this->mEffectiveGroups
= array_unique( array_merge(
2973 $this->getGroups(), // explicit groups
2974 $this->getAutomaticGroups( $recache ) // implicit groups
2976 // Hook for additional groups
2977 Hooks
::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2978 // Force reindexation of groups when a hook has unset one of them
2979 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
2981 return $this->mEffectiveGroups
;
2985 * Get the list of implicit group memberships this user has.
2986 * This includes 'user' if logged in, '*' for all accounts,
2987 * and autopromoted groups
2988 * @param bool $recache Whether to avoid the cache
2989 * @return array Array of String internal group names
2991 public function getAutomaticGroups( $recache = false ) {
2992 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
2993 $this->mImplicitGroups
= array( '*' );
2994 if ( $this->getId() ) {
2995 $this->mImplicitGroups
[] = 'user';
2997 $this->mImplicitGroups
= array_unique( array_merge(
2998 $this->mImplicitGroups
,
2999 Autopromote
::getAutopromoteGroups( $this )
3003 // Assure data consistency with rights/groups,
3004 // as getEffectiveGroups() depends on this function
3005 $this->mEffectiveGroups
= null;
3008 return $this->mImplicitGroups
;
3012 * Returns the groups the user has belonged to.
3014 * The user may still belong to the returned groups. Compare with getGroups().
3016 * The function will not return groups the user had belonged to before MW 1.17
3018 * @return array Names of the groups the user has belonged to.
3020 public function getFormerGroups() {
3021 if ( is_null( $this->mFormerGroups
) ) {
3022 $dbr = wfGetDB( DB_MASTER
);
3023 $res = $dbr->select( 'user_former_groups',
3024 array( 'ufg_group' ),
3025 array( 'ufg_user' => $this->mId
),
3027 $this->mFormerGroups
= array();
3028 foreach ( $res as $row ) {
3029 $this->mFormerGroups
[] = $row->ufg_group
;
3032 return $this->mFormerGroups
;
3036 * Get the user's edit count.
3037 * @return int|null Null for anonymous users
3039 public function getEditCount() {
3040 if ( !$this->getId() ) {
3044 if ( $this->mEditCount
=== null ) {
3045 /* Populate the count, if it has not been populated yet */
3046 $dbr = wfGetDB( DB_SLAVE
);
3047 // check if the user_editcount field has been initialized
3048 $count = $dbr->selectField(
3049 'user', 'user_editcount',
3050 array( 'user_id' => $this->mId
),
3054 if ( $count === null ) {
3055 // it has not been initialized. do so.
3056 $count = $this->initEditCount();
3058 $this->mEditCount
= $count;
3060 return (int)$this->mEditCount
;
3064 * Add the user to the given group.
3065 * This takes immediate effect.
3066 * @param string $group Name of the group to add
3069 public function addGroup( $group ) {
3070 if ( !Hooks
::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3074 $dbw = wfGetDB( DB_MASTER
);
3075 if ( $this->getId() ) {
3076 $dbw->insert( 'user_groups',
3078 'ug_user' => $this->getID(),
3079 'ug_group' => $group,
3082 array( 'IGNORE' ) );
3085 $this->loadGroups();
3086 $this->mGroups
[] = $group;
3087 // In case loadGroups was not called before, we now have the right twice.
3088 // Get rid of the duplicate.
3089 $this->mGroups
= array_unique( $this->mGroups
);
3091 // Refresh the groups caches, and clear the rights cache so it will be
3092 // refreshed on the next call to $this->getRights().
3093 $this->getEffectiveGroups( true );
3094 $this->mRights
= null;
3096 $this->invalidateCache();
3102 * Remove the user from the given group.
3103 * This takes immediate effect.
3104 * @param string $group Name of the group to remove
3107 public function removeGroup( $group ) {
3109 if ( !Hooks
::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3113 $dbw = wfGetDB( DB_MASTER
);
3114 $dbw->delete( 'user_groups',
3116 'ug_user' => $this->getID(),
3117 'ug_group' => $group,
3120 // Remember that the user was in this group
3121 $dbw->insert( 'user_former_groups',
3123 'ufg_user' => $this->getID(),
3124 'ufg_group' => $group,
3130 $this->loadGroups();
3131 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3133 // Refresh the groups caches, and clear the rights cache so it will be
3134 // refreshed on the next call to $this->getRights().
3135 $this->getEffectiveGroups( true );
3136 $this->mRights
= null;
3138 $this->invalidateCache();
3144 * Get whether the user is logged in
3147 public function isLoggedIn() {
3148 return $this->getID() != 0;
3152 * Get whether the user is anonymous
3155 public function isAnon() {
3156 return !$this->isLoggedIn();
3160 * Check if user is allowed to access a feature / make an action
3162 * @param string $permissions,... Permissions to test
3163 * @return bool True if user is allowed to perform *any* of the given actions
3165 public function isAllowedAny( /*...*/ ) {
3166 $permissions = func_get_args();
3167 foreach ( $permissions as $permission ) {
3168 if ( $this->isAllowed( $permission ) ) {
3177 * @param string $permissions,... Permissions to test
3178 * @return bool True if the user is allowed to perform *all* of the given actions
3180 public function isAllowedAll( /*...*/ ) {
3181 $permissions = func_get_args();
3182 foreach ( $permissions as $permission ) {
3183 if ( !$this->isAllowed( $permission ) ) {
3191 * Internal mechanics of testing a permission
3192 * @param string $action
3195 public function isAllowed( $action = '' ) {
3196 if ( $action === '' ) {
3197 return true; // In the spirit of DWIM
3199 // Patrolling may not be enabled
3200 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3201 global $wgUseRCPatrol, $wgUseNPPatrol;
3202 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3206 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3207 // by misconfiguration: 0 == 'foo'
3208 return in_array( $action, $this->getRights(), true );
3212 * Check whether to enable recent changes patrol features for this user
3213 * @return bool True or false
3215 public function useRCPatrol() {
3216 global $wgUseRCPatrol;
3217 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3221 * Check whether to enable new pages patrol features for this user
3222 * @return bool True or false
3224 public function useNPPatrol() {
3225 global $wgUseRCPatrol, $wgUseNPPatrol;
3227 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3228 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3233 * Get the WebRequest object to use with this object
3235 * @return WebRequest
3237 public function getRequest() {
3238 if ( $this->mRequest
) {
3239 return $this->mRequest
;
3247 * Get the current skin, loading it if required
3248 * @return Skin The current skin
3249 * @todo FIXME: Need to check the old failback system [AV]
3250 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3252 public function getSkin() {
3253 wfDeprecated( __METHOD__
, '1.18' );
3254 return RequestContext
::getMain()->getSkin();
3258 * Get a WatchedItem for this user and $title.
3260 * @since 1.22 $checkRights parameter added
3261 * @param Title $title
3262 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3263 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3264 * @return WatchedItem
3266 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3267 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3269 if ( isset( $this->mWatchedItems
[$key] ) ) {
3270 return $this->mWatchedItems
[$key];
3273 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3274 $this->mWatchedItems
= array();
3277 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3278 return $this->mWatchedItems
[$key];
3282 * Check the watched status of an article.
3283 * @since 1.22 $checkRights parameter added
3284 * @param Title $title Title of the article to look at
3285 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3286 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3289 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3290 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3295 * @since 1.22 $checkRights parameter added
3296 * @param Title $title Title of the article to look at
3297 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3298 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3300 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3301 $this->getWatchedItem( $title, $checkRights )->addWatch();
3302 $this->invalidateCache();
3306 * Stop watching an article.
3307 * @since 1.22 $checkRights parameter added
3308 * @param Title $title Title of the article to look at
3309 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3310 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3312 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3313 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3314 $this->invalidateCache();
3318 * Clear the user's notification timestamp for the given title.
3319 * If e-notif e-mails are on, they will receive notification mails on
3320 * the next change of the page if it's watched etc.
3321 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3322 * @param Title $title Title of the article to look at
3323 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3325 public function clearNotification( &$title, $oldid = 0 ) {
3326 global $wgUseEnotif, $wgShowUpdatedMarker;
3328 // Do nothing if the database is locked to writes
3329 if ( wfReadOnly() ) {
3333 // Do nothing if not allowed to edit the watchlist
3334 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3338 // If we're working on user's talk page, we should update the talk page message indicator
3339 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3340 if ( !Hooks
::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3344 $nextid = $oldid ?
$title->getNextRevisionID( $oldid ) : null;
3346 if ( !$oldid ||
!$nextid ) {
3347 // If we're looking at the latest revision, we should definitely clear it
3348 $this->setNewtalk( false );
3350 // Otherwise we should update its revision, if it's present
3351 if ( $this->getNewtalk() ) {
3352 // Naturally the other one won't clear by itself
3353 $this->setNewtalk( false );
3354 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3359 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3363 if ( $this->isAnon() ) {
3364 // Nothing else to do...
3368 // Only update the timestamp if the page is being watched.
3369 // The query to find out if it is watched is cached both in memcached and per-invocation,
3370 // and when it does have to be executed, it can be on a slave
3371 // If this is the user's newtalk page, we always update the timestamp
3373 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3377 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3381 * Resets all of the given user's page-change notification timestamps.
3382 * If e-notif e-mails are on, they will receive notification mails on
3383 * the next change of any watched page.
3384 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3386 public function clearAllNotifications() {
3387 if ( wfReadOnly() ) {
3391 // Do nothing if not allowed to edit the watchlist
3392 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3396 global $wgUseEnotif, $wgShowUpdatedMarker;
3397 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3398 $this->setNewtalk( false );
3401 $id = $this->getId();
3403 $dbw = wfGetDB( DB_MASTER
);
3404 $dbw->update( 'watchlist',
3405 array( /* SET */ 'wl_notificationtimestamp' => null ),
3406 array( /* WHERE */ 'wl_user' => $id ),
3409 // We also need to clear here the "you have new message" notification for the own user_talk page;
3410 // it's cleared one page view later in WikiPage::doViewUpdates().
3415 * Set a cookie on the user's client. Wrapper for
3416 * WebResponse::setCookie
3417 * @param string $name Name of the cookie to set
3418 * @param string $value Value to set
3419 * @param int $exp Expiration time, as a UNIX time value;
3420 * if 0 or not specified, use the default $wgCookieExpiration
3421 * @param bool $secure
3422 * true: Force setting the secure attribute when setting the cookie
3423 * false: Force NOT setting the secure attribute when setting the cookie
3424 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3425 * @param array $params Array of options sent passed to WebResponse::setcookie()
3426 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3429 protected function setCookie(
3430 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3432 if ( $request === null ) {
3433 $request = $this->getRequest();
3435 $params['secure'] = $secure;
3436 $request->response()->setcookie( $name, $value, $exp, $params );
3440 * Clear a cookie on the user's client
3441 * @param string $name Name of the cookie to clear
3442 * @param bool $secure
3443 * true: Force setting the secure attribute when setting the cookie
3444 * false: Force NOT setting the secure attribute when setting the cookie
3445 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3446 * @param array $params Array of options sent passed to WebResponse::setcookie()
3448 protected function clearCookie( $name, $secure = null, $params = array() ) {
3449 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3453 * Set the default cookies for this session on the user's client.
3455 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3457 * @param bool $secure Whether to force secure/insecure cookies or use default
3458 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3460 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3461 if ( $request === null ) {
3462 $request = $this->getRequest();
3466 if ( 0 == $this->mId
) {
3469 if ( !$this->mToken
) {
3470 // When token is empty or NULL generate a new one and then save it to the database
3471 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3472 // Simply by setting every cell in the user_token column to NULL and letting them be
3473 // regenerated as users log back into the wiki.
3475 $this->saveSettings();
3478 'wsUserID' => $this->mId
,
3479 'wsToken' => $this->mToken
,
3480 'wsUserName' => $this->getName()
3483 'UserID' => $this->mId
,
3484 'UserName' => $this->getName(),
3486 if ( $rememberMe ) {
3487 $cookies['Token'] = $this->mToken
;
3489 $cookies['Token'] = false;
3492 Hooks
::run( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3494 foreach ( $session as $name => $value ) {
3495 $request->setSessionData( $name, $value );
3497 foreach ( $cookies as $name => $value ) {
3498 if ( $value === false ) {
3499 $this->clearCookie( $name );
3501 $this->setCookie( $name, $value, 0, $secure, array(), $request );
3506 * If wpStickHTTPS was selected, also set an insecure cookie that
3507 * will cause the site to redirect the user to HTTPS, if they access
3508 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3509 * as the one set by centralauth (bug 53538). Also set it to session, or
3510 * standard time setting, based on if rememberme was set.
3512 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3516 $rememberMe ?
0 : null,
3518 array( 'prefix' => '' ) // no prefix
3524 * Log this user out.
3526 public function logout() {
3527 if ( Hooks
::run( 'UserLogout', array( &$this ) ) ) {
3533 * Clear the user's cookies and session, and reset the instance cache.
3536 public function doLogout() {
3537 $this->clearInstanceCache( 'defaults' );
3539 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3541 $this->clearCookie( 'UserID' );
3542 $this->clearCookie( 'Token' );
3543 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3545 // Remember when user logged out, to prevent seeing cached pages
3546 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3550 * Save this user's settings into the database.
3551 * @todo Only rarely do all these fields need to be set!
3553 public function saveSettings() {
3557 $this->loadPasswords();
3558 if ( wfReadOnly() ) {
3561 if ( 0 == $this->mId
) {
3565 $this->mTouched
= self
::newTouchedTimestamp();
3566 if ( !$wgAuth->allowSetLocalPassword() ) {
3567 $this->mPassword
= self
::getPasswordFactory()->newFromCiphertext( null );
3570 $dbw = wfGetDB( DB_MASTER
);
3571 $dbw->update( 'user',
3573 'user_name' => $this->mName
,
3574 'user_password' => $this->mPassword
->toString(),
3575 'user_newpassword' => $this->mNewpassword
->toString(),
3576 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3577 'user_real_name' => $this->mRealName
,
3578 'user_email' => $this->mEmail
,
3579 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3580 'user_touched' => $dbw->timestamp( $this->mTouched
),
3581 'user_token' => strval( $this->mToken
),
3582 'user_email_token' => $this->mEmailToken
,
3583 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3584 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires
),
3585 ), array( /* WHERE */
3586 'user_id' => $this->mId
3590 $this->saveOptions();
3592 Hooks
::run( 'UserSaveSettings', array( $this ) );
3593 $this->clearSharedCache();
3594 $this->getUserPage()->invalidateCache();
3598 * If only this user's username is known, and it exists, return the user ID.
3601 public function idForName() {
3602 $s = trim( $this->getName() );
3607 $dbr = wfGetDB( DB_SLAVE
);
3608 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
3609 if ( $id === false ) {
3616 * Add a user to the database, return the user object
3618 * @param string $name Username to add
3619 * @param array $params Array of Strings Non-default parameters to save to
3620 * the database as user_* fields:
3621 * - password: The user's password hash. Password logins will be disabled
3622 * if this is omitted.
3623 * - newpassword: Hash for a temporary password that has been mailed to
3625 * - email: The user's email address.
3626 * - email_authenticated: The email authentication timestamp.
3627 * - real_name: The user's real name.
3628 * - options: An associative array of non-default options.
3629 * - token: Random authentication token. Do not set.
3630 * - registration: Registration timestamp. Do not set.
3632 * @return User|null User object, or null if the username already exists.
3634 public static function createNew( $name, $params = array() ) {
3637 $user->loadPasswords();
3638 $user->setToken(); // init token
3639 if ( isset( $params['options'] ) ) {
3640 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3641 unset( $params['options'] );
3643 $dbw = wfGetDB( DB_MASTER
);
3644 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3647 'user_id' => $seqVal,
3648 'user_name' => $name,
3649 'user_password' => $user->mPassword
->toString(),
3650 'user_newpassword' => $user->mNewpassword
->toString(),
3651 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3652 'user_email' => $user->mEmail
,
3653 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3654 'user_real_name' => $user->mRealName
,
3655 'user_token' => strval( $user->mToken
),
3656 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3657 'user_editcount' => 0,
3658 'user_touched' => $dbw->timestamp( self
::newTouchedTimestamp() ),
3660 foreach ( $params as $name => $value ) {
3661 $fields["user_$name"] = $value;
3663 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3664 if ( $dbw->affectedRows() ) {
3665 $newUser = User
::newFromId( $dbw->insertId() );
3673 * Add this existing user object to the database. If the user already
3674 * exists, a fatal status object is returned, and the user object is
3675 * initialised with the data from the database.
3677 * Previously, this function generated a DB error due to a key conflict
3678 * if the user already existed. Many extension callers use this function
3679 * in code along the lines of:
3681 * $user = User::newFromName( $name );
3682 * if ( !$user->isLoggedIn() ) {
3683 * $user->addToDatabase();
3685 * // do something with $user...
3687 * However, this was vulnerable to a race condition (bug 16020). By
3688 * initialising the user object if the user exists, we aim to support this
3689 * calling sequence as far as possible.
3691 * Note that if the user exists, this function will acquire a write lock,
3692 * so it is still advisable to make the call conditional on isLoggedIn(),
3693 * and to commit the transaction after calling.
3695 * @throws MWException
3698 public function addToDatabase() {
3700 $this->loadPasswords();
3701 if ( !$this->mToken
) {
3702 $this->setToken(); // init token
3705 $this->mTouched
= self
::newTouchedTimestamp();
3707 $dbw = wfGetDB( DB_MASTER
);
3708 $inWrite = $dbw->writesOrCallbacksPending();
3709 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3710 $dbw->insert( 'user',
3712 'user_id' => $seqVal,
3713 'user_name' => $this->mName
,
3714 'user_password' => $this->mPassword
->toString(),
3715 'user_newpassword' => $this->mNewpassword
->toString(),
3716 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3717 'user_email' => $this->mEmail
,
3718 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3719 'user_real_name' => $this->mRealName
,
3720 'user_token' => strval( $this->mToken
),
3721 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3722 'user_editcount' => 0,
3723 'user_touched' => $dbw->timestamp( $this->mTouched
),
3727 if ( !$dbw->affectedRows() ) {
3728 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3729 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3731 // Can't commit due to pending writes that may need atomicity.
3732 // This may cause some lock contention unlike the case below.
3733 $options = array( 'LOCK IN SHARE MODE' );
3734 $flags = self
::READ_LOCKING
;
3736 // Often, this case happens early in views before any writes when
3737 // using CentralAuth. It's should be OK to commit and break the snapshot.
3738 $dbw->commit( __METHOD__
, 'flush' );
3742 $this->mId
= $dbw->selectField( 'user', 'user_id',
3743 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3746 if ( $this->loadFromDatabase( $flags ) ) {
3751 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3752 "to insert user '{$this->mName}' row, but it was not present in select!" );
3754 return Status
::newFatal( 'userexists' );
3756 $this->mId
= $dbw->insertId();
3758 // Clear instance cache other than user table data, which is already accurate
3759 $this->clearInstanceCache();
3761 $this->saveOptions();
3762 return Status
::newGood();
3766 * If this user is logged-in and blocked,
3767 * block any IP address they've successfully logged in from.
3768 * @return bool A block was spread
3770 public function spreadAnyEditBlock() {
3771 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3772 return $this->spreadBlock();
3778 * If this (non-anonymous) user is blocked,
3779 * block the IP address they've successfully logged in from.
3780 * @return bool A block was spread
3782 protected function spreadBlock() {
3783 wfDebug( __METHOD__
. "()\n" );
3785 if ( $this->mId
== 0 ) {
3789 $userblock = Block
::newFromTarget( $this->getName() );
3790 if ( !$userblock ) {
3794 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3798 * Get whether the user is explicitly blocked from account creation.
3799 * @return bool|Block
3801 public function isBlockedFromCreateAccount() {
3802 $this->getBlockedStatus();
3803 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3804 return $this->mBlock
;
3807 # bug 13611: if the IP address the user is trying to create an account from is
3808 # blocked with createaccount disabled, prevent new account creation there even
3809 # when the user is logged in
3810 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3811 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3813 return $this->mBlockedFromCreateAccount
instanceof Block
3814 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3815 ?
$this->mBlockedFromCreateAccount
3820 * Get whether the user is blocked from using Special:Emailuser.
3823 public function isBlockedFromEmailuser() {
3824 $this->getBlockedStatus();
3825 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3829 * Get whether the user is allowed to create an account.
3832 public function isAllowedToCreateAccount() {
3833 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3837 * Get this user's personal page title.
3839 * @return Title User's personal page title
3841 public function getUserPage() {
3842 return Title
::makeTitle( NS_USER
, $this->getName() );
3846 * Get this user's talk page title.
3848 * @return Title User's talk page title
3850 public function getTalkPage() {
3851 $title = $this->getUserPage();
3852 return $title->getTalkPage();
3856 * Determine whether the user is a newbie. Newbies are either
3857 * anonymous IPs, or the most recently created accounts.
3860 public function isNewbie() {
3861 return !$this->isAllowed( 'autoconfirmed' );
3865 * Check to see if the given clear-text password is one of the accepted passwords
3866 * @param string $password User password
3867 * @return bool True if the given password is correct, otherwise False
3869 public function checkPassword( $password ) {
3870 global $wgAuth, $wgLegacyEncoding;
3872 $this->loadPasswords();
3874 // Certain authentication plugins do NOT want to save
3875 // domain passwords in a mysql database, so we should
3876 // check this (in case $wgAuth->strict() is false).
3877 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3879 } elseif ( $wgAuth->strict() ) {
3880 // Auth plugin doesn't allow local authentication
3882 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3883 // Auth plugin doesn't allow local authentication for this user name
3887 if ( !$this->mPassword
->equals( $password ) ) {
3888 if ( $wgLegacyEncoding ) {
3889 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3890 // Check for this with iconv
3891 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3892 if ( $cp1252Password === $password ||
!$this->mPassword
->equals( $cp1252Password ) ) {
3900 $passwordFactory = self
::getPasswordFactory();
3901 if ( $passwordFactory->needsUpdate( $this->mPassword
) ) {
3902 $this->mPassword
= $passwordFactory->newFromPlaintext( $password );
3903 $this->saveSettings();
3910 * Check if the given clear-text password matches the temporary password
3911 * sent by e-mail for password reset operations.
3913 * @param string $plaintext
3915 * @return bool True if matches, false otherwise
3917 public function checkTemporaryPassword( $plaintext ) {
3918 global $wgNewPasswordExpiry;
3921 $this->loadPasswords();
3922 if ( $this->mNewpassword
->equals( $plaintext ) ) {
3923 if ( is_null( $this->mNewpassTime
) ) {
3926 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3927 return ( time() < $expiry );
3934 * Alias for getEditToken.
3935 * @deprecated since 1.19, use getEditToken instead.
3937 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3938 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3939 * @return string The new edit token
3941 public function editToken( $salt = '', $request = null ) {
3942 wfDeprecated( __METHOD__
, '1.19' );
3943 return $this->getEditToken( $salt, $request );
3947 * Internal implementation for self::getEditToken() and
3948 * self::matchEditToken().
3950 * @param string|array $salt
3951 * @param WebRequest $request
3952 * @param string|int $timestamp
3955 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
3956 if ( $this->isAnon() ) {
3957 return self
::EDIT_TOKEN_SUFFIX
;
3959 $token = $request->getSessionData( 'wsEditToken' );
3960 if ( $token === null ) {
3961 $token = MWCryptRand
::generateHex( 32 );
3962 $request->setSessionData( 'wsEditToken', $token );
3964 if ( is_array( $salt ) ) {
3965 $salt = implode( '|', $salt );
3967 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
3968 dechex( $timestamp ) .
3969 self
::EDIT_TOKEN_SUFFIX
;
3974 * Initialize (if necessary) and return a session token value
3975 * which can be used in edit forms to show that the user's
3976 * login credentials aren't being hijacked with a foreign form
3981 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3982 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3983 * @return string The new edit token
3985 public function getEditToken( $salt = '', $request = null ) {
3986 return $this->getEditTokenAtTimestamp(
3987 $salt, $request ?
: $this->getRequest(), wfTimestamp()
3992 * Generate a looking random token for various uses.
3994 * @return string The new random token
3995 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
3996 * wfRandomString for pseudo-randomness.
3998 public static function generateToken() {
3999 return MWCryptRand
::generateHex( 32 );
4003 * Get the embedded timestamp from a token.
4004 * @param string $val Input token
4007 public static function getEditTokenTimestamp( $val ) {
4008 $suffixLen = strlen( self
::EDIT_TOKEN_SUFFIX
);
4009 if ( strlen( $val ) <= 32 +
$suffixLen ) {
4013 return hexdec( substr( $val, 32, -$suffixLen ) );
4017 * Check given value against the token value stored in the session.
4018 * A match should confirm that the form was submitted from the
4019 * user's own login session, not a form submission from a third-party
4022 * @param string $val Input value to compare
4023 * @param string $salt Optional function-specific data for hashing
4024 * @param WebRequest|null $request Object to use or null to use $wgRequest
4025 * @param int $maxage Fail tokens older than this, in seconds
4026 * @return bool Whether the token matches
4028 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4029 if ( $this->isAnon() ) {
4030 return $val === self
::EDIT_TOKEN_SUFFIX
;
4033 $timestamp = self
::getEditTokenTimestamp( $val );
4034 if ( $timestamp === null ) {
4037 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
4042 $sessionToken = $this->getEditTokenAtTimestamp(
4043 $salt, $request ?
: $this->getRequest(), $timestamp
4046 if ( $val != $sessionToken ) {
4047 wfDebug( "User::matchEditToken: broken session data\n" );
4050 return hash_equals( $sessionToken, $val );
4054 * Check given value against the token value stored in the session,
4055 * ignoring the suffix.
4057 * @param string $val Input value to compare
4058 * @param string $salt Optional function-specific data for hashing
4059 * @param WebRequest|null $request Object to use or null to use $wgRequest
4060 * @param int $maxage Fail tokens older than this, in seconds
4061 * @return bool Whether the token matches
4063 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4064 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4065 return $this->matchEditToken( $val, $salt, $request, $maxage );
4069 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4070 * mail to the user's given address.
4072 * @param string $type Message to send, either "created", "changed" or "set"
4075 public function sendConfirmationMail( $type = 'created' ) {
4077 $expiration = null; // gets passed-by-ref and defined in next line.
4078 $token = $this->confirmationToken( $expiration );
4079 $url = $this->confirmationTokenUrl( $token );
4080 $invalidateURL = $this->invalidationTokenUrl( $token );
4081 $this->saveSettings();
4083 if ( $type == 'created' ||
$type === false ) {
4084 $message = 'confirmemail_body';
4085 } elseif ( $type === true ) {
4086 $message = 'confirmemail_body_changed';
4088 // Messages: confirmemail_body_changed, confirmemail_body_set
4089 $message = 'confirmemail_body_' . $type;
4092 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4093 wfMessage( $message,
4094 $this->getRequest()->getIP(),
4097 $wgLang->timeanddate( $expiration, false ),
4099 $wgLang->date( $expiration, false ),
4100 $wgLang->time( $expiration, false ) )->text() );
4104 * Send an e-mail to this user's account. Does not check for
4105 * confirmed status or validity.
4107 * @param string $subject Message subject
4108 * @param string $body Message body
4109 * @param string $from Optional From address; if unspecified, default
4110 * $wgPasswordSender will be used.
4111 * @param string $replyto Reply-To address
4114 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4115 if ( is_null( $from ) ) {
4116 global $wgPasswordSender;
4117 $sender = new MailAddress( $wgPasswordSender,
4118 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4120 $sender = MailAddress
::newFromUser( $from );
4123 $to = MailAddress
::newFromUser( $this );
4124 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
4128 * Generate, store, and return a new e-mail confirmation code.
4129 * A hash (unsalted, since it's used as a key) is stored.
4131 * @note Call saveSettings() after calling this function to commit
4132 * this change to the database.
4134 * @param string &$expiration Accepts the expiration time
4135 * @return string New token
4137 protected function confirmationToken( &$expiration ) {
4138 global $wgUserEmailConfirmationTokenExpiry;
4140 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4141 $expiration = wfTimestamp( TS_MW
, $expires );
4143 $token = MWCryptRand
::generateHex( 32 );
4144 $hash = md5( $token );
4145 $this->mEmailToken
= $hash;
4146 $this->mEmailTokenExpires
= $expiration;
4151 * Return a URL the user can use to confirm their email address.
4152 * @param string $token Accepts the email confirmation token
4153 * @return string New token URL
4155 protected function confirmationTokenUrl( $token ) {
4156 return $this->getTokenUrl( 'ConfirmEmail', $token );
4160 * Return a URL the user can use to invalidate their email address.
4161 * @param string $token Accepts the email confirmation token
4162 * @return string New token URL
4164 protected function invalidationTokenUrl( $token ) {
4165 return $this->getTokenUrl( 'InvalidateEmail', $token );
4169 * Internal function to format the e-mail validation/invalidation URLs.
4170 * This uses a quickie hack to use the
4171 * hardcoded English names of the Special: pages, for ASCII safety.
4173 * @note Since these URLs get dropped directly into emails, using the
4174 * short English names avoids insanely long URL-encoded links, which
4175 * also sometimes can get corrupted in some browsers/mailers
4176 * (bug 6957 with Gmail and Internet Explorer).
4178 * @param string $page Special page
4179 * @param string $token Token
4180 * @return string Formatted URL
4182 protected function getTokenUrl( $page, $token ) {
4183 // Hack to bypass localization of 'Special:'
4184 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4185 return $title->getCanonicalURL();
4189 * Mark the e-mail address confirmed.
4191 * @note Call saveSettings() after calling this function to commit the change.
4195 public function confirmEmail() {
4196 // Check if it's already confirmed, so we don't touch the database
4197 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4198 if ( !$this->isEmailConfirmed() ) {
4199 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4200 Hooks
::run( 'ConfirmEmailComplete', array( $this ) );
4206 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4207 * address if it was already confirmed.
4209 * @note Call saveSettings() after calling this function to commit the change.
4210 * @return bool Returns true
4212 public function invalidateEmail() {
4214 $this->mEmailToken
= null;
4215 $this->mEmailTokenExpires
= null;
4216 $this->setEmailAuthenticationTimestamp( null );
4218 Hooks
::run( 'InvalidateEmailComplete', array( $this ) );
4223 * Set the e-mail authentication timestamp.
4224 * @param string $timestamp TS_MW timestamp
4226 public function setEmailAuthenticationTimestamp( $timestamp ) {
4228 $this->mEmailAuthenticated
= $timestamp;
4229 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4233 * Is this user allowed to send e-mails within limits of current
4234 * site configuration?
4237 public function canSendEmail() {
4238 global $wgEnableEmail, $wgEnableUserEmail;
4239 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4242 $canSend = $this->isEmailConfirmed();
4243 Hooks
::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4248 * Is this user allowed to receive e-mails within limits of current
4249 * site configuration?
4252 public function canReceiveEmail() {
4253 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4257 * Is this user's e-mail address valid-looking and confirmed within
4258 * limits of the current site configuration?
4260 * @note If $wgEmailAuthentication is on, this may require the user to have
4261 * confirmed their address by returning a code or using a password
4262 * sent to the address from the wiki.
4266 public function isEmailConfirmed() {
4267 global $wgEmailAuthentication;
4270 if ( Hooks
::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4271 if ( $this->isAnon() ) {
4274 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4277 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4287 * Check whether there is an outstanding request for e-mail confirmation.
4290 public function isEmailConfirmationPending() {
4291 global $wgEmailAuthentication;
4292 return $wgEmailAuthentication &&
4293 !$this->isEmailConfirmed() &&
4294 $this->mEmailToken
&&
4295 $this->mEmailTokenExpires
> wfTimestamp();
4299 * Get the timestamp of account creation.
4301 * @return string|bool|null Timestamp of account creation, false for
4302 * non-existent/anonymous user accounts, or null if existing account
4303 * but information is not in database.
4305 public function getRegistration() {
4306 if ( $this->isAnon() ) {
4310 return $this->mRegistration
;
4314 * Get the timestamp of the first edit
4316 * @return string|bool Timestamp of first edit, or false for
4317 * non-existent/anonymous user accounts.
4319 public function getFirstEditTimestamp() {
4320 if ( $this->getId() == 0 ) {
4321 return false; // anons
4323 $dbr = wfGetDB( DB_SLAVE
);
4324 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4325 array( 'rev_user' => $this->getId() ),
4327 array( 'ORDER BY' => 'rev_timestamp ASC' )
4330 return false; // no edits
4332 return wfTimestamp( TS_MW
, $time );
4336 * Get the permissions associated with a given list of groups
4338 * @param array $groups Array of Strings List of internal group names
4339 * @return array Array of Strings List of permission key names for given groups combined
4341 public static function getGroupPermissions( $groups ) {
4342 global $wgGroupPermissions, $wgRevokePermissions;
4344 // grant every granted permission first
4345 foreach ( $groups as $group ) {
4346 if ( isset( $wgGroupPermissions[$group] ) ) {
4347 $rights = array_merge( $rights,
4348 // array_filter removes empty items
4349 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4352 // now revoke the revoked permissions
4353 foreach ( $groups as $group ) {
4354 if ( isset( $wgRevokePermissions[$group] ) ) {
4355 $rights = array_diff( $rights,
4356 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4359 return array_unique( $rights );
4363 * Get all the groups who have a given permission
4365 * @param string $role Role to check
4366 * @return array Array of Strings List of internal group names with the given permission
4368 public static function getGroupsWithPermission( $role ) {
4369 global $wgGroupPermissions;
4370 $allowedGroups = array();
4371 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4372 if ( self
::groupHasPermission( $group, $role ) ) {
4373 $allowedGroups[] = $group;
4376 return $allowedGroups;
4380 * Check, if the given group has the given permission
4382 * If you're wanting to check whether all users have a permission, use
4383 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4387 * @param string $group Group to check
4388 * @param string $role Role to check
4391 public static function groupHasPermission( $group, $role ) {
4392 global $wgGroupPermissions, $wgRevokePermissions;
4393 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4394 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4398 * Check if all users have the given permission
4401 * @param string $right Right to check
4404 public static function isEveryoneAllowed( $right ) {
4405 global $wgGroupPermissions, $wgRevokePermissions;
4406 static $cache = array();
4408 // Use the cached results, except in unit tests which rely on
4409 // being able change the permission mid-request
4410 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4411 return $cache[$right];
4414 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4415 $cache[$right] = false;
4419 // If it's revoked anywhere, then everyone doesn't have it
4420 foreach ( $wgRevokePermissions as $rights ) {
4421 if ( isset( $rights[$right] ) && $rights[$right] ) {
4422 $cache[$right] = false;
4427 // Allow extensions (e.g. OAuth) to say false
4428 if ( !Hooks
::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4429 $cache[$right] = false;
4433 $cache[$right] = true;
4438 * Get the localized descriptive name for a group, if it exists
4440 * @param string $group Internal group name
4441 * @return string Localized descriptive group name
4443 public static function getGroupName( $group ) {
4444 $msg = wfMessage( "group-$group" );
4445 return $msg->isBlank() ?
$group : $msg->text();
4449 * Get the localized descriptive name for a member of a group, if it exists
4451 * @param string $group Internal group name
4452 * @param string $username Username for gender (since 1.19)
4453 * @return string Localized name for group member
4455 public static function getGroupMember( $group, $username = '#' ) {
4456 $msg = wfMessage( "group-$group-member", $username );
4457 return $msg->isBlank() ?
$group : $msg->text();
4461 * Return the set of defined explicit groups.
4462 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4463 * are not included, as they are defined automatically, not in the database.
4464 * @return array Array of internal group names
4466 public static function getAllGroups() {
4467 global $wgGroupPermissions, $wgRevokePermissions;
4469 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4470 self
::getImplicitGroups()
4475 * Get a list of all available permissions.
4476 * @return string[] Array of permission names
4478 public static function getAllRights() {
4479 if ( self
::$mAllRights === false ) {
4480 global $wgAvailableRights;
4481 if ( count( $wgAvailableRights ) ) {
4482 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4484 self
::$mAllRights = self
::$mCoreRights;
4486 Hooks
::run( 'UserGetAllRights', array( &self
::$mAllRights ) );
4488 return self
::$mAllRights;
4492 * Get a list of implicit groups
4493 * @return array Array of Strings Array of internal group names
4495 public static function getImplicitGroups() {
4496 global $wgImplicitGroups;
4498 $groups = $wgImplicitGroups;
4499 # Deprecated, use $wgImplicitGroups instead
4500 Hooks
::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4506 * Get the title of a page describing a particular group
4508 * @param string $group Internal group name
4509 * @return Title|bool Title of the page if it exists, false otherwise
4511 public static function getGroupPage( $group ) {
4512 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4513 if ( $msg->exists() ) {
4514 $title = Title
::newFromText( $msg->text() );
4515 if ( is_object( $title ) ) {
4523 * Create a link to the group in HTML, if available;
4524 * else return the group name.
4526 * @param string $group Internal name of the group
4527 * @param string $text The text of the link
4528 * @return string HTML link to the group
4530 public static function makeGroupLinkHTML( $group, $text = '' ) {
4531 if ( $text == '' ) {
4532 $text = self
::getGroupName( $group );
4534 $title = self
::getGroupPage( $group );
4536 return Linker
::link( $title, htmlspecialchars( $text ) );
4538 return htmlspecialchars( $text );
4543 * Create a link to the group in Wikitext, if available;
4544 * else return the group name.
4546 * @param string $group Internal name of the group
4547 * @param string $text The text of the link
4548 * @return string Wikilink to the group
4550 public static function makeGroupLinkWiki( $group, $text = '' ) {
4551 if ( $text == '' ) {
4552 $text = self
::getGroupName( $group );
4554 $title = self
::getGroupPage( $group );
4556 $page = $title->getFullText();
4557 return "[[$page|$text]]";
4564 * Returns an array of the groups that a particular group can add/remove.
4566 * @param string $group The group to check for whether it can add/remove
4567 * @return array Array( 'add' => array( addablegroups ),
4568 * 'remove' => array( removablegroups ),
4569 * 'add-self' => array( addablegroups to self),
4570 * 'remove-self' => array( removable groups from self) )
4572 public static function changeableByGroup( $group ) {
4573 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4577 'remove' => array(),
4578 'add-self' => array(),
4579 'remove-self' => array()
4582 if ( empty( $wgAddGroups[$group] ) ) {
4583 // Don't add anything to $groups
4584 } elseif ( $wgAddGroups[$group] === true ) {
4585 // You get everything
4586 $groups['add'] = self
::getAllGroups();
4587 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4588 $groups['add'] = $wgAddGroups[$group];
4591 // Same thing for remove
4592 if ( empty( $wgRemoveGroups[$group] ) ) {
4594 } elseif ( $wgRemoveGroups[$group] === true ) {
4595 $groups['remove'] = self
::getAllGroups();
4596 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4597 $groups['remove'] = $wgRemoveGroups[$group];
4600 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4601 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4602 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4603 if ( is_int( $key ) ) {
4604 $wgGroupsAddToSelf['user'][] = $value;
4609 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4610 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4611 if ( is_int( $key ) ) {
4612 $wgGroupsRemoveFromSelf['user'][] = $value;
4617 // Now figure out what groups the user can add to him/herself
4618 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4620 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4621 // No idea WHY this would be used, but it's there
4622 $groups['add-self'] = User
::getAllGroups();
4623 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4624 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4627 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4629 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4630 $groups['remove-self'] = User
::getAllGroups();
4631 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4632 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4639 * Returns an array of groups that this user can add and remove
4640 * @return array Array( 'add' => array( addablegroups ),
4641 * 'remove' => array( removablegroups ),
4642 * 'add-self' => array( addablegroups to self),
4643 * 'remove-self' => array( removable groups from self) )
4645 public function changeableGroups() {
4646 if ( $this->isAllowed( 'userrights' ) ) {
4647 // This group gives the right to modify everything (reverse-
4648 // compatibility with old "userrights lets you change
4650 // Using array_merge to make the groups reindexed
4651 $all = array_merge( User
::getAllGroups() );
4655 'add-self' => array(),
4656 'remove-self' => array()
4660 // Okay, it's not so simple, we will have to go through the arrays
4663 'remove' => array(),
4664 'add-self' => array(),
4665 'remove-self' => array()
4667 $addergroups = $this->getEffectiveGroups();
4669 foreach ( $addergroups as $addergroup ) {
4670 $groups = array_merge_recursive(
4671 $groups, $this->changeableByGroup( $addergroup )
4673 $groups['add'] = array_unique( $groups['add'] );
4674 $groups['remove'] = array_unique( $groups['remove'] );
4675 $groups['add-self'] = array_unique( $groups['add-self'] );
4676 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4682 * Increment the user's edit-count field.
4683 * Will have no effect for anonymous users.
4685 public function incEditCount() {
4686 if ( !$this->isAnon() ) {
4687 $dbw = wfGetDB( DB_MASTER
);
4690 array( 'user_editcount=user_editcount+1' ),
4691 array( 'user_id' => $this->getId() ),
4695 // Lazy initialization check...
4696 if ( $dbw->affectedRows() == 0 ) {
4697 // Now here's a goddamn hack...
4698 $dbr = wfGetDB( DB_SLAVE
);
4699 if ( $dbr !== $dbw ) {
4700 // If we actually have a slave server, the count is
4701 // at least one behind because the current transaction
4702 // has not been committed and replicated.
4703 $this->initEditCount( 1 );
4705 // But if DB_SLAVE is selecting the master, then the
4706 // count we just read includes the revision that was
4707 // just added in the working transaction.
4708 $this->initEditCount();
4712 // edit count in user cache too
4713 $this->invalidateCache();
4717 * Initialize user_editcount from data out of the revision table
4719 * @param int $add Edits to add to the count from the revision table
4720 * @return int Number of edits
4722 protected function initEditCount( $add = 0 ) {
4723 // Pull from a slave to be less cruel to servers
4724 // Accuracy isn't the point anyway here
4725 $dbr = wfGetDB( DB_SLAVE
);
4726 $count = (int)$dbr->selectField(
4729 array( 'rev_user' => $this->getId() ),
4732 $count = $count +
$add;
4734 $dbw = wfGetDB( DB_MASTER
);
4737 array( 'user_editcount' => $count ),
4738 array( 'user_id' => $this->getId() ),
4746 * Get the description of a given right
4748 * @param string $right Right to query
4749 * @return string Localized description of the right
4751 public static function getRightDescription( $right ) {
4752 $key = "right-$right";
4753 $msg = wfMessage( $key );
4754 return $msg->isBlank() ?
$right : $msg->text();
4758 * Make a new-style password hash
4760 * @param string $password Plain-text password
4761 * @param bool|string $salt Optional salt, may be random or the user ID.
4762 * If unspecified or false, will generate one automatically
4763 * @return string Password hash
4764 * @deprecated since 1.24, use Password class
4766 public static function crypt( $password, $salt = false ) {
4767 wfDeprecated( __METHOD__
, '1.24' );
4768 $hash = self
::getPasswordFactory()->newFromPlaintext( $password );
4769 return $hash->toString();
4773 * Compare a password hash with a plain-text password. Requires the user
4774 * ID if there's a chance that the hash is an old-style hash.
4776 * @param string $hash Password hash
4777 * @param string $password Plain-text password to compare
4778 * @param string|bool $userId User ID for old-style password salt
4781 * @deprecated since 1.24, use Password class
4783 public static function comparePasswords( $hash, $password, $userId = false ) {
4784 wfDeprecated( __METHOD__
, '1.24' );
4786 // Check for *really* old password hashes that don't even have a type
4787 // The old hash format was just an md5 hex hash, with no type information
4788 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4789 global $wgPasswordSalt;
4790 if ( $wgPasswordSalt ) {
4791 $password = ":B:{$userId}:{$hash}";
4793 $password = ":A:{$hash}";
4797 $hash = self
::getPasswordFactory()->newFromCiphertext( $hash );
4798 return $hash->equals( $password );
4802 * Add a newuser log entry for this user.
4803 * Before 1.19 the return value was always true.
4805 * @param string|bool $action Account creation type.
4806 * - String, one of the following values:
4807 * - 'create' for an anonymous user creating an account for himself.
4808 * This will force the action's performer to be the created user itself,
4809 * no matter the value of $wgUser
4810 * - 'create2' for a logged in user creating an account for someone else
4811 * - 'byemail' when the created user will receive its password by e-mail
4812 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4813 * - Boolean means whether the account was created by e-mail (deprecated):
4814 * - true will be converted to 'byemail'
4815 * - false will be converted to 'create' if this object is the same as
4816 * $wgUser and to 'create2' otherwise
4818 * @param string $reason User supplied reason
4820 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4822 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4823 global $wgUser, $wgNewUserLog;
4824 if ( empty( $wgNewUserLog ) ) {
4825 return true; // disabled
4828 if ( $action === true ) {
4829 $action = 'byemail';
4830 } elseif ( $action === false ) {
4831 if ( $this->equals( $wgUser ) ) {
4834 $action = 'create2';
4838 if ( $action === 'create' ||
$action === 'autocreate' ) {
4841 $performer = $wgUser;
4844 $logEntry = new ManualLogEntry( 'newusers', $action );
4845 $logEntry->setPerformer( $performer );
4846 $logEntry->setTarget( $this->getUserPage() );
4847 $logEntry->setComment( $reason );
4848 $logEntry->setParameters( array(
4849 '4::userid' => $this->getId(),
4851 $logid = $logEntry->insert();
4853 if ( $action !== 'autocreate' ) {
4854 $logEntry->publish( $logid );
4861 * Add an autocreate newuser log entry for this user
4862 * Used by things like CentralAuth and perhaps other authplugins.
4863 * Consider calling addNewUserLogEntry() directly instead.
4867 public function addNewUserLogEntryAutoCreate() {
4868 $this->addNewUserLogEntry( 'autocreate' );
4874 * Load the user options either from cache, the database or an array
4876 * @param array $data Rows for the current user out of the user_properties table
4878 protected function loadOptions( $data = null ) {
4883 if ( $this->mOptionsLoaded
) {
4887 $this->mOptions
= self
::getDefaultOptions();
4889 if ( !$this->getId() ) {
4890 // For unlogged-in users, load language/variant options from request.
4891 // There's no need to do it for logged-in users: they can set preferences,
4892 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4893 // so don't override user's choice (especially when the user chooses site default).
4894 $variant = $wgContLang->getDefaultVariant();
4895 $this->mOptions
['variant'] = $variant;
4896 $this->mOptions
['language'] = $variant;
4897 $this->mOptionsLoaded
= true;
4901 // Maybe load from the object
4902 if ( !is_null( $this->mOptionOverrides
) ) {
4903 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4904 foreach ( $this->mOptionOverrides
as $key => $value ) {
4905 $this->mOptions
[$key] = $value;
4908 if ( !is_array( $data ) ) {
4909 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4910 // Load from database
4911 $dbr = wfGetDB( DB_SLAVE
);
4913 $res = $dbr->select(
4915 array( 'up_property', 'up_value' ),
4916 array( 'up_user' => $this->getId() ),
4920 $this->mOptionOverrides
= array();
4922 foreach ( $res as $row ) {
4923 $data[$row->up_property
] = $row->up_value
;
4926 foreach ( $data as $property => $value ) {
4927 $this->mOptionOverrides
[$property] = $value;
4928 $this->mOptions
[$property] = $value;
4932 $this->mOptionsLoaded
= true;
4934 Hooks
::run( 'UserLoadOptions', array( $this, &$this->mOptions
) );
4938 * Saves the non-default options for this user, as previously set e.g. via
4939 * setOption(), in the database's "user_properties" (preferences) table.
4940 * Usually used via saveSettings().
4942 protected function saveOptions() {
4943 $this->loadOptions();
4945 // Not using getOptions(), to keep hidden preferences in database
4946 $saveOptions = $this->mOptions
;
4948 // Allow hooks to abort, for instance to save to a global profile.
4949 // Reset options to default state before saving.
4950 if ( !Hooks
::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4954 $userId = $this->getId();
4956 $insert_rows = array(); // all the new preference rows
4957 foreach ( $saveOptions as $key => $value ) {
4958 // Don't bother storing default values
4959 $defaultOption = self
::getDefaultOption( $key );
4960 if ( ( $defaultOption === null && $value !== false && $value !== null )
4961 ||
$value != $defaultOption
4963 $insert_rows[] = array(
4964 'up_user' => $userId,
4965 'up_property' => $key,
4966 'up_value' => $value,
4971 $dbw = wfGetDB( DB_MASTER
);
4973 $res = $dbw->select( 'user_properties',
4974 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
4976 // Find prior rows that need to be removed or updated. These rows will
4977 // all be deleted (the later so that INSERT IGNORE applies the new values).
4978 $keysDelete = array();
4979 foreach ( $res as $row ) {
4980 if ( !isset( $saveOptions[$row->up_property
] )
4981 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
4983 $keysDelete[] = $row->up_property
;
4987 if ( count( $keysDelete ) ) {
4988 // Do the DELETE by PRIMARY KEY for prior rows.
4989 // In the past a very large portion of calls to this function are for setting
4990 // 'rememberpassword' for new accounts (a preference that has since been removed).
4991 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4992 // caused gap locks on [max user ID,+infinity) which caused high contention since
4993 // updates would pile up on each other as they are for higher (newer) user IDs.
4994 // It might not be necessary these days, but it shouldn't hurt either.
4995 $dbw->delete( 'user_properties',
4996 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
4998 // Insert the new preference rows
4999 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
5003 * Lazily instantiate and return a factory object for making passwords
5005 * @return PasswordFactory
5007 public static function getPasswordFactory() {
5008 if ( self
::$mPasswordFactory === null ) {
5009 self
::$mPasswordFactory = new PasswordFactory();
5010 self
::$mPasswordFactory->init( RequestContext
::getMain()->getConfig() );
5013 return self
::$mPasswordFactory;
5017 * Provide an array of HTML5 attributes to put on an input element
5018 * intended for the user to enter a new password. This may include
5019 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5021 * Do *not* use this when asking the user to enter his current password!
5022 * Regardless of configuration, users may have invalid passwords for whatever
5023 * reason (e.g., they were set before requirements were tightened up).
5024 * Only use it when asking for a new password, like on account creation or
5027 * Obviously, you still need to do server-side checking.
5029 * NOTE: A combination of bugs in various browsers means that this function
5030 * actually just returns array() unconditionally at the moment. May as
5031 * well keep it around for when the browser bugs get fixed, though.
5033 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5035 * @return array Array of HTML attributes suitable for feeding to
5036 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5037 * That will get confused by the boolean attribute syntax used.)
5039 public static function passwordChangeInputAttribs() {
5040 global $wgMinimalPasswordLength;
5042 if ( $wgMinimalPasswordLength == 0 ) {
5046 # Note that the pattern requirement will always be satisfied if the
5047 # input is empty, so we need required in all cases.
5049 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5050 # if e-mail confirmation is being used. Since HTML5 input validation
5051 # is b0rked anyway in some browsers, just return nothing. When it's
5052 # re-enabled, fix this code to not output required for e-mail
5054 #$ret = array( 'required' );
5057 # We can't actually do this right now, because Opera 9.6 will print out
5058 # the entered password visibly in its error message! When other
5059 # browsers add support for this attribute, or Opera fixes its support,
5060 # we can add support with a version check to avoid doing this on Opera
5061 # versions where it will be a problem. Reported to Opera as
5062 # DSK-262266, but they don't have a public bug tracker for us to follow.
5064 if ( $wgMinimalPasswordLength > 1 ) {
5065 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5066 $ret['title'] = wfMessage( 'passwordtooshort' )
5067 ->numParams( $wgMinimalPasswordLength )->text();
5075 * Return the list of user fields that should be selected to create
5076 * a new user object.
5079 public static function selectFields() {
5087 'user_email_authenticated',
5089 'user_email_token_expires',
5090 'user_registration',
5096 * Factory function for fatal permission-denied errors
5099 * @param string $permission User right required
5102 static function newFatalPermissionDeniedStatus( $permission ) {
5105 $groups = array_map(
5106 array( 'User', 'makeGroupLinkWiki' ),
5107 User
::getGroupsWithPermission( $permission )
5111 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5113 return Status
::newFatal( 'badaccess-group0' );
5118 * Checks if two user objects point to the same user.
5124 public function equals( User
$user ) {
5125 return $this->getName() === $user->getName();