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 * Int Number of characters in user_token field.
27 define( 'USER_TOKEN_LENGTH', 32 );
30 * Int Serialized record version.
33 define( 'MW_USER_VERSION', 10 );
36 * String Some punctuation to prevent editing from broken text-mangling proxies.
39 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
42 * Thrown by User::setPassword() on error.
45 class PasswordError
extends MWException
{
50 * The User object encapsulates all of the user-specific settings (user_id,
51 * name, rights, password, email address, options, last login time). Client
52 * classes use the getXXX() functions to access these fields. These functions
53 * do all the work of determining whether the user is logged in,
54 * whether the requested option can be satisfied from cookies or
55 * whether a database query is needed. Most of the settings needed
56 * for rendering normal pages are set in the cookie to minimize use
59 class User
implements IDBAccessObject
{
61 * Global constants made accessible as class constants so that autoloader
64 const USER_TOKEN_LENGTH
= USER_TOKEN_LENGTH
;
65 const MW_USER_VERSION
= MW_USER_VERSION
;
66 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
69 * Maximum items in $mWatchedItems
71 const MAX_WATCHED_ITEMS_CACHE
= 100;
74 * @var PasswordFactory Lazily loaded factory object for passwords
76 private static $mPasswordFactory = null;
79 * Array of Strings List of member variables which are saved to the
80 * shared cache (memcached). Any operation which changes the
81 * corresponding database fields must call a cache-clearing function.
84 protected static $mCacheVars = array(
92 'mEmailAuthenticated',
99 // user_properties table
104 * Array of Strings Core rights.
105 * Each of these should have a corresponding message of the form
109 protected static $mCoreRights = array(
135 'editusercssjs', #deprecated
147 'move-categorypages',
148 'move-rootuserpages',
152 'override-export-depth',
176 'userrights-interwiki',
184 * String Cached results of getAllRights()
186 protected static $mAllRights = false;
188 /** @name Cache variables */
198 public $mNewpassword;
200 public $mNewpassTime;
208 public $mEmailAuthenticated;
210 protected $mEmailToken;
212 protected $mEmailTokenExpires;
214 protected $mRegistration;
216 protected $mEditCount;
220 protected $mOptionOverrides;
222 protected $mPasswordExpires;
226 * Bool Whether the cache variables have been loaded.
229 public $mOptionsLoaded;
232 * Array with already loaded items or true if all items have been loaded.
234 protected $mLoadedItems = array();
238 * String Initialization data source if mLoadedItems!==true. May be one of:
239 * - 'defaults' anonymous user initialised from class defaults
240 * - 'name' initialise from mName
241 * - 'id' initialise from mId
242 * - 'session' log in from cookies or session if possible
244 * Use the User::newFrom*() family of functions to set this.
249 * Lazy-initialized variables, invalidated with clearInstanceCache
253 protected $mDatePreference;
261 protected $mBlockreason;
263 protected $mEffectiveGroups;
265 protected $mImplicitGroups;
267 protected $mFormerGroups;
269 protected $mBlockedGlobally;
286 protected $mAllowUsertalk;
289 private $mBlockedFromCreateAccount = false;
292 private $mWatchedItems = array();
294 public static $idCacheByName = array();
297 * Lightweight constructor for an anonymous user.
298 * Use the User::newFrom* factory functions for other kinds of users.
302 * @see newFromConfirmationCode()
303 * @see newFromSession()
306 public function __construct() {
307 $this->clearInstanceCache( 'defaults' );
313 public function __toString() {
314 return $this->getName();
318 * Load the user table data for this object from the source given by mFrom.
320 public function load() {
321 if ( $this->mLoadedItems
=== true ) {
324 wfProfileIn( __METHOD__
);
326 // Set it now to avoid infinite recursion in accessors
327 $this->mLoadedItems
= true;
329 switch ( $this->mFrom
) {
331 $this->loadDefaults();
334 $this->mId
= self
::idFromName( $this->mName
);
336 // Nonexistent user placeholder object
337 $this->loadDefaults( $this->mName
);
346 if ( !$this->loadFromSession() ) {
347 // Loading from session failed. Load defaults.
348 $this->loadDefaults();
350 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
353 wfProfileOut( __METHOD__
);
354 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
356 wfProfileOut( __METHOD__
);
360 * Load user table data, given mId has already been set.
361 * @return bool False if the ID does not exist, true otherwise
363 public function loadFromId() {
365 if ( $this->mId
== 0 ) {
366 $this->loadDefaults();
371 $key = wfMemcKey( 'user', 'id', $this->mId
);
372 $data = $wgMemc->get( $key );
373 if ( !is_array( $data ) ||
$data['mVersion'] != MW_USER_VERSION
) {
374 // Object is expired, load from DB
379 wfDebug( "User: cache miss for user {$this->mId}\n" );
381 if ( !$this->loadFromDatabase() ) {
382 // Can't load from ID, user is anonymous
385 $this->saveToCache();
387 wfDebug( "User: got user {$this->mId} from cache\n" );
388 // Restore from cache
389 foreach ( self
::$mCacheVars as $name ) {
390 $this->$name = $data[$name];
394 $this->mLoadedItems
= true;
400 * Save user data to the shared cache
402 public function saveToCache() {
405 $this->loadOptions();
406 if ( $this->isAnon() ) {
407 // Anonymous users are uncached
411 foreach ( self
::$mCacheVars as $name ) {
412 $data[$name] = $this->$name;
414 $data['mVersion'] = MW_USER_VERSION
;
415 $key = wfMemcKey( 'user', 'id', $this->mId
);
417 $wgMemc->set( $key, $data );
420 /** @name newFrom*() static factory methods */
424 * Static factory method for creation from username.
426 * This is slightly less efficient than newFromId(), so use newFromId() if
427 * you have both an ID and a name handy.
429 * @param string $name Username, validated by Title::newFromText()
430 * @param string|bool $validate Validate username. Takes the same parameters as
431 * User::getCanonicalName(), except that true is accepted as an alias
432 * for 'valid', for BC.
434 * @return User|bool User object, or false if the username is invalid
435 * (e.g. if it contains illegal characters or is an IP address). If the
436 * username is not present in the database, the result will be a user object
437 * with a name, zero user ID and default settings.
439 public static function newFromName( $name, $validate = 'valid' ) {
440 if ( $validate === true ) {
443 $name = self
::getCanonicalName( $name, $validate );
444 if ( $name === false ) {
447 // Create unloaded user object
451 $u->setItemLoaded( 'name' );
457 * Static factory method for creation from a given user ID.
459 * @param int $id Valid user ID
460 * @return User The corresponding User object
462 public static function newFromId( $id ) {
466 $u->setItemLoaded( 'id' );
471 * Factory method to fetch whichever user has a given email confirmation code.
472 * This code is generated when an account is created or its e-mail address
475 * If the code is invalid or has expired, returns NULL.
477 * @param string $code Confirmation code
480 public static function newFromConfirmationCode( $code ) {
481 $dbr = wfGetDB( DB_SLAVE
);
482 $id = $dbr->selectField( 'user', 'user_id', array(
483 'user_email_token' => md5( $code ),
484 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
486 if ( $id !== false ) {
487 return User
::newFromId( $id );
494 * Create a new user object using data from session or cookies. If the
495 * login credentials are invalid, the result is an anonymous user.
497 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
500 public static function newFromSession( WebRequest
$request = null ) {
502 $user->mFrom
= 'session';
503 $user->mRequest
= $request;
508 * Create a new user object from a user row.
509 * The row should have the following fields from the user table in it:
510 * - either user_name or user_id to load further data if needed (or both)
512 * - all other fields (email, password, etc.)
513 * It is useless to provide the remaining fields if either user_id,
514 * user_name and user_real_name are not provided because the whole row
515 * will be loaded once more from the database when accessing them.
517 * @param stdClass $row A row from the user table
518 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
521 public static function newFromRow( $row, $data = null ) {
523 $user->loadFromRow( $row, $data );
530 * Get the username corresponding to a given user ID
531 * @param int $id User ID
532 * @return string|bool The corresponding username
534 public static function whoIs( $id ) {
535 return UserCache
::singleton()->getProp( $id, 'name' );
539 * Get the real name of a user given their user ID
541 * @param int $id User ID
542 * @return string|bool The corresponding user's real name
544 public static function whoIsReal( $id ) {
545 return UserCache
::singleton()->getProp( $id, 'real_name' );
549 * Get database id given a user name
550 * @param string $name Username
551 * @return int|null The corresponding user's ID, or null if user is nonexistent
553 public static function idFromName( $name ) {
554 $nt = Title
::makeTitleSafe( NS_USER
, $name );
555 if ( is_null( $nt ) ) {
560 if ( isset( self
::$idCacheByName[$name] ) ) {
561 return self
::$idCacheByName[$name];
564 $dbr = wfGetDB( DB_SLAVE
);
565 $s = $dbr->selectRow(
568 array( 'user_name' => $nt->getText() ),
572 if ( $s === false ) {
575 $result = $s->user_id
;
578 self
::$idCacheByName[$name] = $result;
580 if ( count( self
::$idCacheByName ) > 1000 ) {
581 self
::$idCacheByName = array();
588 * Reset the cache used in idFromName(). For use in tests.
590 public static function resetIdByNameCache() {
591 self
::$idCacheByName = array();
595 * Does the string match an anonymous IPv4 address?
597 * This function exists for username validation, in order to reject
598 * usernames which are similar in form to IP addresses. Strings such
599 * as 300.300.300.300 will return true because it looks like an IP
600 * address, despite not being strictly valid.
602 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
603 * address because the usemod software would "cloak" anonymous IP
604 * addresses like this, if we allowed accounts like this to be created
605 * new users could get the old edits of these anonymous users.
607 * @param string $name Name to match
610 public static function isIP( $name ) {
611 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
612 || IP
::isIPv6( $name );
616 * Is the input a valid username?
618 * Checks if the input is a valid username, we don't want an empty string,
619 * an IP address, anything that contains slashes (would mess up subpages),
620 * is longer than the maximum allowed username size or doesn't begin with
623 * @param string $name Name to match
626 public static function isValidUserName( $name ) {
627 global $wgContLang, $wgMaxNameChars;
630 || User
::isIP( $name )
631 ||
strpos( $name, '/' ) !== false
632 ||
strlen( $name ) > $wgMaxNameChars
633 ||
$name != $wgContLang->ucfirst( $name ) ) {
634 wfDebugLog( 'username', __METHOD__
.
635 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
639 // Ensure that the name can't be misresolved as a different title,
640 // such as with extra namespace keys at the start.
641 $parsed = Title
::newFromText( $name );
642 if ( is_null( $parsed )
643 ||
$parsed->getNamespace()
644 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
645 wfDebugLog( 'username', __METHOD__
.
646 ": '$name' invalid due to ambiguous prefixes" );
650 // Check an additional blacklist of troublemaker characters.
651 // Should these be merged into the title char list?
652 $unicodeBlacklist = '/[' .
653 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
654 '\x{00a0}' . # non-breaking space
655 '\x{2000}-\x{200f}' . # various whitespace
656 '\x{2028}-\x{202f}' . # breaks and control chars
657 '\x{3000}' . # ideographic space
658 '\x{e000}-\x{f8ff}' . # private use
660 if ( preg_match( $unicodeBlacklist, $name ) ) {
661 wfDebugLog( 'username', __METHOD__
.
662 ": '$name' invalid due to blacklisted characters" );
670 * Usernames which fail to pass this function will be blocked
671 * from user login and new account registrations, but may be used
672 * internally by batch processes.
674 * If an account already exists in this form, login will be blocked
675 * by a failure to pass this function.
677 * @param string $name Name to match
680 public static function isUsableName( $name ) {
681 global $wgReservedUsernames;
682 // Must be a valid username, obviously ;)
683 if ( !self
::isValidUserName( $name ) ) {
687 static $reservedUsernames = false;
688 if ( !$reservedUsernames ) {
689 $reservedUsernames = $wgReservedUsernames;
690 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
693 // Certain names may be reserved for batch processes.
694 foreach ( $reservedUsernames as $reserved ) {
695 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
696 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
698 if ( $reserved == $name ) {
706 * Usernames which fail to pass this function will be blocked
707 * from new account registrations, but may be used internally
708 * either by batch processes or by user accounts which have
709 * already been created.
711 * Additional blacklisting may be added here rather than in
712 * isValidUserName() to avoid disrupting existing accounts.
714 * @param string $name String to match
717 public static function isCreatableName( $name ) {
718 global $wgInvalidUsernameCharacters;
720 // Ensure that the username isn't longer than 235 bytes, so that
721 // (at least for the builtin skins) user javascript and css files
722 // will work. (bug 23080)
723 if ( strlen( $name ) > 235 ) {
724 wfDebugLog( 'username', __METHOD__
.
725 ": '$name' invalid due to length" );
729 // Preg yells if you try to give it an empty string
730 if ( $wgInvalidUsernameCharacters !== '' ) {
731 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
732 wfDebugLog( 'username', __METHOD__
.
733 ": '$name' invalid due to wgInvalidUsernameCharacters" );
738 return self
::isUsableName( $name );
742 * Is the input a valid password for this user?
744 * @param string $password Desired password
747 public function isValidPassword( $password ) {
748 //simple boolean wrapper for getPasswordValidity
749 return $this->getPasswordValidity( $password ) === true;
754 * Given unvalidated password input, return error message on failure.
756 * @param string $password Desired password
757 * @return bool|string|array True on success, string or array of error message on failure
759 public function getPasswordValidity( $password ) {
760 $result = $this->checkPasswordValidity( $password );
761 if ( $result->isGood() ) {
765 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
766 $messages[] = $error['message'];
768 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
769 $messages[] = $warning['message'];
771 if ( count( $messages ) === 1 ) {
779 * Check if this is a valid password for this user. Status will be good if
780 * the password is valid, or have an array of error messages if not.
782 * @param string $password Desired password
786 public function checkPasswordValidity( $password ) {
787 global $wgMinimalPasswordLength, $wgContLang;
789 static $blockedLogins = array(
790 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
791 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
794 $status = Status
::newGood();
796 $result = false; //init $result to false for the internal checks
798 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
799 $status->error( $result );
803 if ( $result === false ) {
804 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
805 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
807 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
808 $status->error( 'password-name-match' );
810 } elseif ( isset( $blockedLogins[$this->getName()] )
811 && $password == $blockedLogins[$this->getName()]
813 $status->error( 'password-login-forbidden' );
816 //it seems weird returning a Good status here, but this is because of the
817 //initialization of $result to false above. If the hook is never run or it
818 //doesn't modify $result, then we will likely get down into this if with
822 } elseif ( $result === true ) {
825 $status->error( $result );
826 return $status; //the isValidPassword hook set a string $result and returned true
831 * Expire a user's password
833 * @param int $ts Optional timestamp to convert, default 0 for the current time
835 public function expirePassword( $ts = 0 ) {
837 $timestamp = wfTimestamp( TS_MW
, $ts );
838 $this->mPasswordExpires
= $timestamp;
839 $this->saveSettings();
843 * Clear the password expiration for a user
845 * @param bool $load Ensure user object is loaded first
847 public function resetPasswordExpiration( $load = true ) {
848 global $wgPasswordExpirationDays;
853 if ( $wgPasswordExpirationDays ) {
854 $newExpire = wfTimestamp(
856 time() +
( $wgPasswordExpirationDays * 24 * 3600 )
859 // Give extensions a chance to force an expiration
860 wfRunHooks( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
861 $this->mPasswordExpires
= $newExpire;
865 * Check if the user's password is expired.
866 * TODO: Put this and password length into a PasswordPolicy object
868 * @return string|bool The expiration type, or false if not expired
869 * hard: A password change is required to login
870 * soft: Allow login, but encourage password change
871 * false: Password is not expired
873 public function getPasswordExpired() {
874 global $wgPasswordExpireGrace;
876 $now = wfTimestamp();
877 $expiration = $this->getPasswordExpireDate();
878 $expUnix = wfTimestamp( TS_UNIX
, $expiration );
879 if ( $expiration !== null && $expUnix < $now ) {
880 $expired = ( $expUnix +
$wgPasswordExpireGrace < $now ) ?
'hard' : 'soft';
886 * Get this user's password expiration date. Since this may be using
887 * the cached User object, we assume that whatever mechanism is setting
888 * the expiration date is also expiring the User cache.
890 * @return string|bool The datestamp of the expiration, or null if not set
892 public function getPasswordExpireDate() {
894 return $this->mPasswordExpires
;
898 * Given unvalidated user input, return a canonical username, or false if
899 * the username is invalid.
900 * @param string $name User input
901 * @param string|bool $validate Type of validation to use:
902 * - false No validation
903 * - 'valid' Valid for batch processes
904 * - 'usable' Valid for batch processes and login
905 * - 'creatable' Valid for batch processes, login and account creation
907 * @throws MWException
908 * @return bool|string
910 public static function getCanonicalName( $name, $validate = 'valid' ) {
911 // Force usernames to capital
913 $name = $wgContLang->ucfirst( $name );
915 # Reject names containing '#'; these will be cleaned up
916 # with title normalisation, but then it's too late to
918 if ( strpos( $name, '#' ) !== false ) {
922 // Clean up name according to title rules
923 $t = ( $validate === 'valid' ) ?
924 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
925 // Check for invalid titles
926 if ( is_null( $t ) ) {
930 // Reject various classes of invalid names
932 $name = $wgAuth->getCanonicalName( $t->getText() );
934 switch ( $validate ) {
938 if ( !User
::isValidUserName( $name ) ) {
943 if ( !User
::isUsableName( $name ) ) {
948 if ( !User
::isCreatableName( $name ) ) {
953 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
959 * Count the number of edits of a user
961 * @param int $uid User ID to check
962 * @return int The user's edit count
964 * @deprecated since 1.21 in favour of User::getEditCount
966 public static function edits( $uid ) {
967 wfDeprecated( __METHOD__
, '1.21' );
968 $user = self
::newFromId( $uid );
969 return $user->getEditCount();
973 * Return a random password.
975 * @return string New random password
977 public static function randomPassword() {
978 global $wgMinimalPasswordLength;
979 // Decide the final password length based on our min password length,
980 // stopping at a minimum of 10 chars.
981 $length = max( 10, $wgMinimalPasswordLength );
982 // Multiply by 1.25 to get the number of hex characters we need
983 $length = $length * 1.25;
984 // Generate random hex chars
985 $hex = MWCryptRand
::generateHex( $length );
986 // Convert from base 16 to base 32 to get a proper password like string
987 return wfBaseConvert( $hex, 16, 32 );
991 * Set cached properties to default.
993 * @note This no longer clears uncached lazy-initialised properties;
994 * the constructor does that instead.
996 * @param string|bool $name
998 public function loadDefaults( $name = false ) {
999 wfProfileIn( __METHOD__
);
1001 $passwordFactory = self
::getPasswordFactory();
1004 $this->mName
= $name;
1005 $this->mRealName
= '';
1006 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1007 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1008 $this->mNewpassTime
= null;
1010 $this->mOptionOverrides
= null;
1011 $this->mOptionsLoaded
= false;
1013 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1014 if ( $loggedOut !== null ) {
1015 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1017 $this->mTouched
= '1'; # Allow any pages to be cached
1020 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1021 $this->mEmailAuthenticated
= null;
1022 $this->mEmailToken
= '';
1023 $this->mEmailTokenExpires
= null;
1024 $this->mPasswordExpires
= null;
1025 $this->resetPasswordExpiration( false );
1026 $this->mRegistration
= wfTimestamp( TS_MW
);
1027 $this->mGroups
= array();
1029 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
1031 wfProfileOut( __METHOD__
);
1035 * Return whether an item has been loaded.
1037 * @param string $item Item to check. Current possibilities:
1041 * @param string $all 'all' to check if the whole object has been loaded
1042 * or any other string to check if only the item is available (e.g.
1046 public function isItemLoaded( $item, $all = 'all' ) {
1047 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1048 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1052 * Set that an item has been loaded
1054 * @param string $item
1056 protected function setItemLoaded( $item ) {
1057 if ( is_array( $this->mLoadedItems
) ) {
1058 $this->mLoadedItems
[$item] = true;
1063 * Load user data from the session or login cookie.
1064 * @return bool True if the user is logged in, false otherwise.
1066 private function loadFromSession() {
1068 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
1069 if ( $result !== null ) {
1073 $request = $this->getRequest();
1075 $cookieId = $request->getCookie( 'UserID' );
1076 $sessId = $request->getSessionData( 'wsUserID' );
1078 if ( $cookieId !== null ) {
1079 $sId = intval( $cookieId );
1080 if ( $sessId !== null && $cookieId != $sessId ) {
1081 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1082 cookie user ID ($sId) don't match!" );
1085 $request->setSessionData( 'wsUserID', $sId );
1086 } elseif ( $sessId !== null && $sessId != 0 ) {
1092 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1093 $sName = $request->getSessionData( 'wsUserName' );
1094 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1095 $sName = $request->getCookie( 'UserName' );
1096 $request->setSessionData( 'wsUserName', $sName );
1101 $proposedUser = User
::newFromId( $sId );
1102 if ( !$proposedUser->isLoggedIn() ) {
1107 global $wgBlockDisablesLogin;
1108 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1109 // User blocked and we've disabled blocked user logins
1113 if ( $request->getSessionData( 'wsToken' ) ) {
1115 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1117 } elseif ( $request->getCookie( 'Token' ) ) {
1118 # Get the token from DB/cache and clean it up to remove garbage padding.
1119 # This deals with historical problems with bugs and the default column value.
1120 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1121 // Make comparison in constant time (bug 61346)
1122 $passwordCorrect = strlen( $token )
1123 && hash_equals( $token, $request->getCookie( 'Token' ) );
1126 // No session or persistent login cookie
1130 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1131 $this->loadFromUserObject( $proposedUser );
1132 $request->setSessionData( 'wsToken', $this->mToken
);
1133 wfDebug( "User: logged in from $from\n" );
1136 // Invalid credentials
1137 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1143 * Load user and user_group data from the database.
1144 * $this->mId must be set, this is how the user is identified.
1146 * @param int $flags Supports User::READ_LOCKING
1147 * @return bool True if the user exists, false if the user is anonymous
1149 public function loadFromDatabase( $flags = 0 ) {
1151 $this->mId
= intval( $this->mId
);
1154 if ( !$this->mId
) {
1155 $this->loadDefaults();
1159 $dbr = wfGetDB( DB_MASTER
);
1160 $s = $dbr->selectRow(
1162 self
::selectFields(),
1163 array( 'user_id' => $this->mId
),
1165 ( $flags & self
::READ_LOCKING
== self
::READ_LOCKING
)
1166 ?
array( 'LOCK IN SHARE MODE' )
1170 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1172 if ( $s !== false ) {
1173 // Initialise user table data
1174 $this->loadFromRow( $s );
1175 $this->mGroups
= null; // deferred
1176 $this->getEditCount(); // revalidation for nulls
1181 $this->loadDefaults();
1187 * Initialize this object from a row from the user table.
1189 * @param stdClass $row Row from the user table to load.
1190 * @param array $data Further user data to load into the object
1192 * user_groups Array with groups out of the user_groups table
1193 * user_properties Array with properties out of the user_properties table
1195 public function loadFromRow( $row, $data = null ) {
1197 $passwordFactory = self
::getPasswordFactory();
1199 $this->mGroups
= null; // deferred
1201 if ( isset( $row->user_name
) ) {
1202 $this->mName
= $row->user_name
;
1203 $this->mFrom
= 'name';
1204 $this->setItemLoaded( 'name' );
1209 if ( isset( $row->user_real_name
) ) {
1210 $this->mRealName
= $row->user_real_name
;
1211 $this->setItemLoaded( 'realname' );
1216 if ( isset( $row->user_id
) ) {
1217 $this->mId
= intval( $row->user_id
);
1218 $this->mFrom
= 'id';
1219 $this->setItemLoaded( 'id' );
1224 if ( isset( $row->user_editcount
) ) {
1225 $this->mEditCount
= $row->user_editcount
;
1230 if ( isset( $row->user_password
) ) {
1231 // Check for *really* old password hashes that don't even have a type
1232 // The old hash format was just an md5 hex hash, with no type information
1233 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password
) ) {
1234 $row->user_password
= ":A:{$this->mId}:{$row->user_password}";
1238 $this->mPassword
= $passwordFactory->newFromCiphertext( $row->user_password
);
1239 } catch ( PasswordError
$e ) {
1240 wfDebug( 'Invalid password hash found in database.' );
1241 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1245 $this->mNewpassword
= $passwordFactory->newFromCiphertext( $row->user_newpassword
);
1246 } catch ( PasswordError
$e ) {
1247 wfDebug( 'Invalid password hash found in database.' );
1248 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1251 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1252 $this->mPasswordExpires
= wfTimestampOrNull( TS_MW
, $row->user_password_expires
);
1255 if ( isset( $row->user_email
) ) {
1256 $this->mEmail
= $row->user_email
;
1257 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1258 $this->mToken
= $row->user_token
;
1259 if ( $this->mToken
== '' ) {
1260 $this->mToken
= null;
1262 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1263 $this->mEmailToken
= $row->user_email_token
;
1264 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1265 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1271 $this->mLoadedItems
= true;
1274 if ( is_array( $data ) ) {
1275 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1276 $this->mGroups
= $data['user_groups'];
1278 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1279 $this->loadOptions( $data['user_properties'] );
1285 * Load the data for this user object from another user object.
1289 protected function loadFromUserObject( $user ) {
1291 $user->loadGroups();
1292 $user->loadOptions();
1293 foreach ( self
::$mCacheVars as $var ) {
1294 $this->$var = $user->$var;
1299 * Load the groups from the database if they aren't already loaded.
1301 private function loadGroups() {
1302 if ( is_null( $this->mGroups
) ) {
1303 $dbr = wfGetDB( DB_MASTER
);
1304 $res = $dbr->select( 'user_groups',
1305 array( 'ug_group' ),
1306 array( 'ug_user' => $this->mId
),
1308 $this->mGroups
= array();
1309 foreach ( $res as $row ) {
1310 $this->mGroups
[] = $row->ug_group
;
1316 * Load the user's password hashes from the database
1318 * This is usually called in a scenario where the actual User object was
1319 * loaded from the cache, and then password comparison needs to be performed.
1320 * Password hashes are not stored in memcached.
1324 private function loadPasswords() {
1325 if ( $this->getId() !== 0 && ( $this->mPassword
=== null ||
$this->mNewpassword
=== null ) ) {
1326 $this->loadFromRow( wfGetDB( DB_MASTER
)->selectRow(
1328 array( 'user_password', 'user_newpassword', 'user_newpass_time', 'user_password_expires' ),
1329 array( 'user_id' => $this->getId() ),
1336 * Add the user to the group if he/she meets given criteria.
1338 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1339 * possible to remove manually via Special:UserRights. In such case it
1340 * will not be re-added automatically. The user will also not lose the
1341 * group if they no longer meet the criteria.
1343 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1345 * @return array Array of groups the user has been promoted to.
1347 * @see $wgAutopromoteOnce
1349 public function addAutopromoteOnceGroups( $event ) {
1350 global $wgAutopromoteOnceLogInRC, $wgAuth;
1352 $toPromote = array();
1353 if ( $this->getId() ) {
1354 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1355 if ( count( $toPromote ) ) {
1356 $oldGroups = $this->getGroups(); // previous groups
1358 foreach ( $toPromote as $group ) {
1359 $this->addGroup( $group );
1361 // update groups in external authentication database
1362 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1364 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1366 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1367 $logEntry->setPerformer( $this );
1368 $logEntry->setTarget( $this->getUserPage() );
1369 $logEntry->setParameters( array(
1370 '4::oldgroups' => $oldGroups,
1371 '5::newgroups' => $newGroups,
1373 $logid = $logEntry->insert();
1374 if ( $wgAutopromoteOnceLogInRC ) {
1375 $logEntry->publish( $logid );
1383 * Clear various cached data stored in this object. The cache of the user table
1384 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1386 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1387 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1389 public function clearInstanceCache( $reloadFrom = false ) {
1390 $this->mNewtalk
= -1;
1391 $this->mDatePreference
= null;
1392 $this->mBlockedby
= -1; # Unset
1393 $this->mHash
= false;
1394 $this->mRights
= null;
1395 $this->mEffectiveGroups
= null;
1396 $this->mImplicitGroups
= null;
1397 $this->mGroups
= null;
1398 $this->mOptions
= null;
1399 $this->mOptionsLoaded
= false;
1400 $this->mEditCount
= null;
1402 if ( $reloadFrom ) {
1403 $this->mLoadedItems
= array();
1404 $this->mFrom
= $reloadFrom;
1409 * Combine the language default options with any site-specific options
1410 * and add the default language variants.
1412 * @return array Array of String options
1414 public static function getDefaultOptions() {
1415 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1417 static $defOpt = null;
1418 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1419 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1420 // mid-request and see that change reflected in the return value of this function.
1421 // Which is insane and would never happen during normal MW operation
1425 $defOpt = $wgDefaultUserOptions;
1426 // Default language setting
1427 $defOpt['language'] = $wgContLang->getCode();
1428 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1429 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1431 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1432 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1434 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1436 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1442 * Get a given default option value.
1444 * @param string $opt Name of option to retrieve
1445 * @return string Default option value
1447 public static function getDefaultOption( $opt ) {
1448 $defOpts = self
::getDefaultOptions();
1449 if ( isset( $defOpts[$opt] ) ) {
1450 return $defOpts[$opt];
1457 * Get blocking information
1458 * @param bool $bFromSlave Whether to check the slave database first.
1459 * To improve performance, non-critical checks are done against slaves.
1460 * Check when actually saving should be done against master.
1462 private function getBlockedStatus( $bFromSlave = true ) {
1463 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1465 if ( -1 != $this->mBlockedby
) {
1469 wfProfileIn( __METHOD__
);
1470 wfDebug( __METHOD__
. ": checking...\n" );
1472 // Initialize data...
1473 // Otherwise something ends up stomping on $this->mBlockedby when
1474 // things get lazy-loaded later, causing false positive block hits
1475 // due to -1 !== 0. Probably session-related... Nothing should be
1476 // overwriting mBlockedby, surely?
1479 # We only need to worry about passing the IP address to the Block generator if the
1480 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1481 # know which IP address they're actually coming from
1482 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1483 $ip = $this->getRequest()->getIP();
1489 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1492 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1493 && !in_array( $ip, $wgProxyWhitelist )
1496 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1498 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1499 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1500 $block->setTarget( $ip );
1501 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1503 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1504 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1505 $block->setTarget( $ip );
1509 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1510 if ( !$block instanceof Block
1511 && $wgApplyIpBlocksToXff
1513 && !$this->isAllowed( 'proxyunbannable' )
1514 && !in_array( $ip, $wgProxyWhitelist )
1516 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1517 $xff = array_map( 'trim', explode( ',', $xff ) );
1518 $xff = array_diff( $xff, array( $ip ) );
1519 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1520 $block = Block
::chooseBlock( $xffblocks, $xff );
1521 if ( $block instanceof Block
) {
1522 # Mangle the reason to alert the user that the block
1523 # originated from matching the X-Forwarded-For header.
1524 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1528 if ( $block instanceof Block
) {
1529 wfDebug( __METHOD__
. ": Found block.\n" );
1530 $this->mBlock
= $block;
1531 $this->mBlockedby
= $block->getByName();
1532 $this->mBlockreason
= $block->mReason
;
1533 $this->mHideName
= $block->mHideName
;
1534 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1536 $this->mBlockedby
= '';
1537 $this->mHideName
= 0;
1538 $this->mAllowUsertalk
= false;
1542 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1544 wfProfileOut( __METHOD__
);
1548 * Whether the given IP is in a DNS blacklist.
1550 * @param string $ip IP to check
1551 * @param bool $checkWhitelist Whether to check the whitelist first
1552 * @return bool True if blacklisted.
1554 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1555 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1557 if ( !$wgEnableDnsBlacklist ) {
1561 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1565 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1569 * Whether the given IP is in a given DNS blacklist.
1571 * @param string $ip IP to check
1572 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1573 * @return bool True if blacklisted.
1575 public function inDnsBlacklist( $ip, $bases ) {
1576 wfProfileIn( __METHOD__
);
1579 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1580 if ( IP
::isIPv4( $ip ) ) {
1581 // Reverse IP, bug 21255
1582 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1584 foreach ( (array)$bases as $base ) {
1586 // If we have an access key, use that too (ProjectHoneypot, etc.)
1587 if ( is_array( $base ) ) {
1588 if ( count( $base ) >= 2 ) {
1589 // Access key is 1, base URL is 0
1590 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1592 $host = "$ipReversed.{$base[0]}";
1595 $host = "$ipReversed.$base";
1599 $ipList = gethostbynamel( $host );
1602 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1606 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1611 wfProfileOut( __METHOD__
);
1616 * Check if an IP address is in the local proxy list
1622 public static function isLocallyBlockedProxy( $ip ) {
1623 global $wgProxyList;
1625 if ( !$wgProxyList ) {
1628 wfProfileIn( __METHOD__
);
1630 if ( !is_array( $wgProxyList ) ) {
1631 // Load from the specified file
1632 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1635 if ( !is_array( $wgProxyList ) ) {
1637 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1639 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1640 // Old-style flipped proxy list
1645 wfProfileOut( __METHOD__
);
1650 * Is this user subject to rate limiting?
1652 * @return bool True if rate limited
1654 public function isPingLimitable() {
1655 global $wgRateLimitsExcludedIPs;
1656 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1657 // No other good way currently to disable rate limits
1658 // for specific IPs. :P
1659 // But this is a crappy hack and should die.
1662 return !$this->isAllowed( 'noratelimit' );
1666 * Primitive rate limits: enforce maximum actions per time period
1667 * to put a brake on flooding.
1669 * The method generates both a generic profiling point and a per action one
1670 * (suffix being "-$action".
1672 * @note When using a shared cache like memcached, IP-address
1673 * last-hit counters will be shared across wikis.
1675 * @param string $action Action to enforce; 'edit' if unspecified
1676 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1677 * @return bool True if a rate limiter was tripped
1679 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1680 // Call the 'PingLimiter' hook
1682 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1686 global $wgRateLimits;
1687 if ( !isset( $wgRateLimits[$action] ) ) {
1691 // Some groups shouldn't trigger the ping limiter, ever
1692 if ( !$this->isPingLimitable() ) {
1697 wfProfileIn( __METHOD__
);
1698 wfProfileIn( __METHOD__
. '-' . $action );
1700 $limits = $wgRateLimits[$action];
1702 $id = $this->getId();
1705 if ( isset( $limits['anon'] ) && $id == 0 ) {
1706 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1709 if ( isset( $limits['user'] ) && $id != 0 ) {
1710 $userLimit = $limits['user'];
1712 if ( $this->isNewbie() ) {
1713 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1714 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1716 if ( isset( $limits['ip'] ) ) {
1717 $ip = $this->getRequest()->getIP();
1718 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1720 if ( isset( $limits['subnet'] ) ) {
1721 $ip = $this->getRequest()->getIP();
1724 if ( IP
::isIPv6( $ip ) ) {
1725 $parts = IP
::parseRange( "$ip/64" );
1726 $subnet = $parts[0];
1727 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1729 $subnet = $matches[1];
1731 if ( $subnet !== false ) {
1732 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1736 // Check for group-specific permissions
1737 // If more than one group applies, use the group with the highest limit
1738 foreach ( $this->getGroups() as $group ) {
1739 if ( isset( $limits[$group] ) ) {
1740 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1741 $userLimit = $limits[$group];
1745 // Set the user limit key
1746 if ( $userLimit !== false ) {
1747 list( $max, $period ) = $userLimit;
1748 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1749 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1753 foreach ( $keys as $key => $limit ) {
1754 list( $max, $period ) = $limit;
1755 $summary = "(limit $max in {$period}s)";
1756 $count = $wgMemc->get( $key );
1759 if ( $count >= $max ) {
1760 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1761 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1764 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1767 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1768 if ( $incrBy > 0 ) {
1769 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1772 if ( $incrBy > 0 ) {
1773 $wgMemc->incr( $key, $incrBy );
1777 wfProfileOut( __METHOD__
. '-' . $action );
1778 wfProfileOut( __METHOD__
);
1783 * Check if user is blocked
1785 * @param bool $bFromSlave Whether to check the slave database instead of
1786 * the master. Hacked from false due to horrible probs on site.
1787 * @return bool True if blocked, false otherwise
1789 public function isBlocked( $bFromSlave = true ) {
1790 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1794 * Get the block affecting the user, or null if the user is not blocked
1796 * @param bool $bFromSlave Whether to check the slave database instead of the master
1797 * @return Block|null
1799 public function getBlock( $bFromSlave = true ) {
1800 $this->getBlockedStatus( $bFromSlave );
1801 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1805 * Check if user is blocked from editing a particular article
1807 * @param Title $title Title to check
1808 * @param bool $bFromSlave Whether to check the slave database instead of the master
1811 public function isBlockedFrom( $title, $bFromSlave = false ) {
1812 global $wgBlockAllowsUTEdit;
1813 wfProfileIn( __METHOD__
);
1815 $blocked = $this->isBlocked( $bFromSlave );
1816 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1817 // If a user's name is suppressed, they cannot make edits anywhere
1818 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1819 && $title->getNamespace() == NS_USER_TALK
) {
1821 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1824 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1826 wfProfileOut( __METHOD__
);
1831 * If user is blocked, return the name of the user who placed the block
1832 * @return string Name of blocker
1834 public function blockedBy() {
1835 $this->getBlockedStatus();
1836 return $this->mBlockedby
;
1840 * If user is blocked, return the specified reason for the block
1841 * @return string Blocking reason
1843 public function blockedFor() {
1844 $this->getBlockedStatus();
1845 return $this->mBlockreason
;
1849 * If user is blocked, return the ID for the block
1850 * @return int Block ID
1852 public function getBlockId() {
1853 $this->getBlockedStatus();
1854 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1858 * Check if user is blocked on all wikis.
1859 * Do not use for actual edit permission checks!
1860 * This is intended for quick UI checks.
1862 * @param string $ip IP address, uses current client if none given
1863 * @return bool True if blocked, false otherwise
1865 public function isBlockedGlobally( $ip = '' ) {
1866 if ( $this->mBlockedGlobally
!== null ) {
1867 return $this->mBlockedGlobally
;
1869 // User is already an IP?
1870 if ( IP
::isIPAddress( $this->getName() ) ) {
1871 $ip = $this->getName();
1873 $ip = $this->getRequest()->getIP();
1876 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1877 $this->mBlockedGlobally
= (bool)$blocked;
1878 return $this->mBlockedGlobally
;
1882 * Check if user account is locked
1884 * @return bool True if locked, false otherwise
1886 public function isLocked() {
1887 if ( $this->mLocked
!== null ) {
1888 return $this->mLocked
;
1891 StubObject
::unstub( $wgAuth );
1892 $authUser = $wgAuth->getUserInstance( $this );
1893 $this->mLocked
= (bool)$authUser->isLocked();
1894 return $this->mLocked
;
1898 * Check if user account is hidden
1900 * @return bool True if hidden, false otherwise
1902 public function isHidden() {
1903 if ( $this->mHideName
!== null ) {
1904 return $this->mHideName
;
1906 $this->getBlockedStatus();
1907 if ( !$this->mHideName
) {
1909 StubObject
::unstub( $wgAuth );
1910 $authUser = $wgAuth->getUserInstance( $this );
1911 $this->mHideName
= (bool)$authUser->isHidden();
1913 return $this->mHideName
;
1917 * Get the user's ID.
1918 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1920 public function getId() {
1921 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1922 // Special case, we know the user is anonymous
1924 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1925 // Don't load if this was initialized from an ID
1932 * Set the user and reload all fields according to a given ID
1933 * @param int $v User ID to reload
1935 public function setId( $v ) {
1937 $this->clearInstanceCache( 'id' );
1941 * Get the user name, or the IP of an anonymous user
1942 * @return string User's name or IP address
1944 public function getName() {
1945 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1946 // Special case optimisation
1947 return $this->mName
;
1950 if ( $this->mName
=== false ) {
1952 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1954 return $this->mName
;
1959 * Set the user name.
1961 * This does not reload fields from the database according to the given
1962 * name. Rather, it is used to create a temporary "nonexistent user" for
1963 * later addition to the database. It can also be used to set the IP
1964 * address for an anonymous user to something other than the current
1967 * @note User::newFromName() has roughly the same function, when the named user
1969 * @param string $str New user name to set
1971 public function setName( $str ) {
1973 $this->mName
= $str;
1977 * Get the user's name escaped by underscores.
1978 * @return string Username escaped by underscores.
1980 public function getTitleKey() {
1981 return str_replace( ' ', '_', $this->getName() );
1985 * Check if the user has new messages.
1986 * @return bool True if the user has new messages
1988 public function getNewtalk() {
1991 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1992 if ( $this->mNewtalk
=== -1 ) {
1993 $this->mNewtalk
= false; # reset talk page status
1995 // Check memcached separately for anons, who have no
1996 // entire User object stored in there.
1997 if ( !$this->mId
) {
1998 global $wgDisableAnonTalk;
1999 if ( $wgDisableAnonTalk ) {
2000 // Anon newtalk disabled by configuration.
2001 $this->mNewtalk
= false;
2004 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
2005 $newtalk = $wgMemc->get( $key );
2006 if ( strval( $newtalk ) !== '' ) {
2007 $this->mNewtalk
= (bool)$newtalk;
2009 // Since we are caching this, make sure it is up to date by getting it
2011 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
2012 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
2016 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2020 return (bool)$this->mNewtalk
;
2024 * Return the data needed to construct links for new talk page message
2025 * alerts. If there are new messages, this will return an associative array
2026 * with the following data:
2027 * wiki: The database name of the wiki
2028 * link: Root-relative link to the user's talk page
2029 * rev: The last talk page revision that the user has seen or null. This
2030 * is useful for building diff links.
2031 * If there are no new messages, it returns an empty array.
2032 * @note This function was designed to accomodate multiple talk pages, but
2033 * currently only returns a single link and revision.
2036 public function getNewMessageLinks() {
2038 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2040 } elseif ( !$this->getNewtalk() ) {
2043 $utp = $this->getTalkPage();
2044 $dbr = wfGetDB( DB_SLAVE
);
2045 // Get the "last viewed rev" timestamp from the oldest message notification
2046 $timestamp = $dbr->selectField( 'user_newtalk',
2047 'MIN(user_last_timestamp)',
2048 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2050 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2051 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2055 * Get the revision ID for the last talk page revision viewed by the talk
2057 * @return int|null Revision ID or null
2059 public function getNewMessageRevisionId() {
2060 $newMessageRevisionId = null;
2061 $newMessageLinks = $this->getNewMessageLinks();
2062 if ( $newMessageLinks ) {
2063 // Note: getNewMessageLinks() never returns more than a single link
2064 // and it is always for the same wiki, but we double-check here in
2065 // case that changes some time in the future.
2066 if ( count( $newMessageLinks ) === 1
2067 && $newMessageLinks[0]['wiki'] === wfWikiID()
2068 && $newMessageLinks[0]['rev']
2070 $newMessageRevision = $newMessageLinks[0]['rev'];
2071 $newMessageRevisionId = $newMessageRevision->getId();
2074 return $newMessageRevisionId;
2078 * Internal uncached check for new messages
2081 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2082 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2083 * @param bool $fromMaster True to fetch from the master, false for a slave
2084 * @return bool True if the user has new messages
2086 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2087 if ( $fromMaster ) {
2088 $db = wfGetDB( DB_MASTER
);
2090 $db = wfGetDB( DB_SLAVE
);
2092 $ok = $db->selectField( 'user_newtalk', $field,
2093 array( $field => $id ), __METHOD__
);
2094 return $ok !== false;
2098 * Add or update the new messages flag
2099 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2100 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2101 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2102 * @return bool True if successful, false otherwise
2104 protected function updateNewtalk( $field, $id, $curRev = null ) {
2105 // Get timestamp of the talk page revision prior to the current one
2106 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2107 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2108 // Mark the user as having new messages since this revision
2109 $dbw = wfGetDB( DB_MASTER
);
2110 $dbw->insert( 'user_newtalk',
2111 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2114 if ( $dbw->affectedRows() ) {
2115 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2118 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2124 * Clear the new messages flag for the given user
2125 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2126 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2127 * @return bool True if successful, false otherwise
2129 protected function deleteNewtalk( $field, $id ) {
2130 $dbw = wfGetDB( DB_MASTER
);
2131 $dbw->delete( 'user_newtalk',
2132 array( $field => $id ),
2134 if ( $dbw->affectedRows() ) {
2135 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2138 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2144 * Update the 'You have new messages!' status.
2145 * @param bool $val Whether the user has new messages
2146 * @param Revision $curRev New, as yet unseen revision of the user talk
2147 * page. Ignored if null or !$val.
2149 public function setNewtalk( $val, $curRev = null ) {
2150 if ( wfReadOnly() ) {
2155 $this->mNewtalk
= $val;
2157 if ( $this->isAnon() ) {
2159 $id = $this->getName();
2162 $id = $this->getId();
2167 $changed = $this->updateNewtalk( $field, $id, $curRev );
2169 $changed = $this->deleteNewtalk( $field, $id );
2172 if ( $this->isAnon() ) {
2173 // Anons have a separate memcached space, since
2174 // user records aren't kept for them.
2175 $key = wfMemcKey( 'newtalk', 'ip', $id );
2176 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
2179 $this->invalidateCache();
2184 * Generate a current or new-future timestamp to be stored in the
2185 * user_touched field when we update things.
2186 * @return string Timestamp in TS_MW format
2188 private static function newTouchedTimestamp() {
2189 global $wgClockSkewFudge;
2190 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2194 * Clear user data from memcached.
2195 * Use after applying fun updates to the database; caller's
2196 * responsibility to update user_touched if appropriate.
2198 * Called implicitly from invalidateCache() and saveSettings().
2200 public function clearSharedCache() {
2204 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
2209 * Immediately touch the user data cache for this account.
2210 * Updates user_touched field, and removes account data from memcached
2211 * for reload on the next hit.
2213 public function invalidateCache() {
2214 if ( wfReadOnly() ) {
2219 $this->mTouched
= self
::newTouchedTimestamp();
2221 $dbw = wfGetDB( DB_MASTER
);
2222 $userid = $this->mId
;
2223 $touched = $this->mTouched
;
2224 $method = __METHOD__
;
2225 $dbw->onTransactionIdle( function () use ( $dbw, $userid, $touched, $method ) {
2226 // Prevent contention slams by checking user_touched first
2227 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2228 $needsPurge = $dbw->selectField( 'user', '1',
2229 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2230 if ( $needsPurge ) {
2231 $dbw->update( 'user',
2232 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2233 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2238 $this->clearSharedCache();
2243 * Validate the cache for this account.
2244 * @param string $timestamp A timestamp in TS_MW format
2247 public function validateCache( $timestamp ) {
2249 return ( $timestamp >= $this->mTouched
);
2253 * Get the user touched timestamp
2254 * @return string Timestamp
2256 public function getTouched() {
2258 return $this->mTouched
;
2262 * Set the password and reset the random token.
2263 * Calls through to authentication plugin if necessary;
2264 * will have no effect if the auth plugin refuses to
2265 * pass the change through or if the legal password
2268 * As a special case, setting the password to null
2269 * wipes it, so the account cannot be logged in until
2270 * a new password is set, for instance via e-mail.
2272 * @param string $str New password to set
2273 * @throws PasswordError On failure
2277 public function setPassword( $str ) {
2280 if ( $str !== null ) {
2281 if ( !$wgAuth->allowPasswordChange() ) {
2282 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2285 if ( !$this->isValidPassword( $str ) ) {
2286 global $wgMinimalPasswordLength;
2287 $valid = $this->getPasswordValidity( $str );
2288 if ( is_array( $valid ) ) {
2289 $message = array_shift( $valid );
2293 $params = array( $wgMinimalPasswordLength );
2295 throw new PasswordError( wfMessage( $message, $params )->text() );
2299 if ( !$wgAuth->setPassword( $this, $str ) ) {
2300 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2303 $this->setInternalPassword( $str );
2309 * Set the password and reset the random token unconditionally.
2311 * @param string|null $str New password to set or null to set an invalid
2312 * password hash meaning that the user will not be able to log in
2313 * through the web interface.
2315 public function setInternalPassword( $str ) {
2318 $passwordFactory = self
::getPasswordFactory();
2319 if ( $str === null ) {
2320 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
2322 $this->mPassword
= $passwordFactory->newFromPlaintext( $str );
2325 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
2326 $this->mNewpassTime
= null;
2330 * Get the user's current token.
2331 * @param bool $forceCreation Force the generation of a new token if the
2332 * user doesn't have one (default=true for backwards compatibility).
2333 * @return string Token
2335 public function getToken( $forceCreation = true ) {
2337 if ( !$this->mToken
&& $forceCreation ) {
2340 return $this->mToken
;
2344 * Set the random token (used for persistent authentication)
2345 * Called from loadDefaults() among other places.
2347 * @param string|bool $token If specified, set the token to this value
2349 public function setToken( $token = false ) {
2352 $this->mToken
= MWCryptRand
::generateHex( USER_TOKEN_LENGTH
);
2354 $this->mToken
= $token;
2359 * Set the password for a password reminder or new account email
2361 * @param string $str New password to set or null to set an invalid
2362 * password hash meaning that the user will not be able to use it
2363 * @param bool $throttle If true, reset the throttle timestamp to the present
2365 public function setNewpassword( $str, $throttle = true ) {
2368 if ( $str === null ) {
2369 $this->mNewpassword
= '';
2370 $this->mNewpassTime
= null;
2372 $this->mNewpassword
= self
::getPasswordFactory()->newFromPlaintext( $str );
2374 $this->mNewpassTime
= wfTimestampNow();
2380 * Has password reminder email been sent within the last
2381 * $wgPasswordReminderResendTime hours?
2384 public function isPasswordReminderThrottled() {
2385 global $wgPasswordReminderResendTime;
2387 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2390 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2391 return time() < $expiry;
2395 * Get the user's e-mail address
2396 * @return string User's email address
2398 public function getEmail() {
2400 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
2401 return $this->mEmail
;
2405 * Get the timestamp of the user's e-mail authentication
2406 * @return string TS_MW timestamp
2408 public function getEmailAuthenticationTimestamp() {
2410 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2411 return $this->mEmailAuthenticated
;
2415 * Set the user's e-mail address
2416 * @param string $str New e-mail address
2418 public function setEmail( $str ) {
2420 if ( $str == $this->mEmail
) {
2423 $this->mEmail
= $str;
2424 $this->invalidateEmail();
2425 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
2429 * Set the user's e-mail address and a confirmation mail if needed.
2432 * @param string $str New e-mail address
2435 public function setEmailWithConfirmation( $str ) {
2436 global $wgEnableEmail, $wgEmailAuthentication;
2438 if ( !$wgEnableEmail ) {
2439 return Status
::newFatal( 'emaildisabled' );
2442 $oldaddr = $this->getEmail();
2443 if ( $str === $oldaddr ) {
2444 return Status
::newGood( true );
2447 $this->setEmail( $str );
2449 if ( $str !== '' && $wgEmailAuthentication ) {
2450 // Send a confirmation request to the new address if needed
2451 $type = $oldaddr != '' ?
'changed' : 'set';
2452 $result = $this->sendConfirmationMail( $type );
2453 if ( $result->isGood() ) {
2454 // Say the the caller that a confirmation mail has been sent
2455 $result->value
= 'eauth';
2458 $result = Status
::newGood( true );
2465 * Get the user's real name
2466 * @return string User's real name
2468 public function getRealName() {
2469 if ( !$this->isItemLoaded( 'realname' ) ) {
2473 return $this->mRealName
;
2477 * Set the user's real name
2478 * @param string $str New real name
2480 public function setRealName( $str ) {
2482 $this->mRealName
= $str;
2486 * Get the user's current setting for a given option.
2488 * @param string $oname The option to check
2489 * @param string $defaultOverride A default value returned if the option does not exist
2490 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2491 * @return string User's current value for the option
2492 * @see getBoolOption()
2493 * @see getIntOption()
2495 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2496 global $wgHiddenPrefs;
2497 $this->loadOptions();
2499 # We want 'disabled' preferences to always behave as the default value for
2500 # users, even if they have set the option explicitly in their settings (ie they
2501 # set it, and then it was disabled removing their ability to change it). But
2502 # we don't want to erase the preferences in the database in case the preference
2503 # is re-enabled again. So don't touch $mOptions, just override the returned value
2504 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2505 return self
::getDefaultOption( $oname );
2508 if ( array_key_exists( $oname, $this->mOptions
) ) {
2509 return $this->mOptions
[$oname];
2511 return $defaultOverride;
2516 * Get all user's options
2520 public function getOptions() {
2521 global $wgHiddenPrefs;
2522 $this->loadOptions();
2523 $options = $this->mOptions
;
2525 # We want 'disabled' preferences to always behave as the default value for
2526 # users, even if they have set the option explicitly in their settings (ie they
2527 # set it, and then it was disabled removing their ability to change it). But
2528 # we don't want to erase the preferences in the database in case the preference
2529 # is re-enabled again. So don't touch $mOptions, just override the returned value
2530 foreach ( $wgHiddenPrefs as $pref ) {
2531 $default = self
::getDefaultOption( $pref );
2532 if ( $default !== null ) {
2533 $options[$pref] = $default;
2541 * Get the user's current setting for a given option, as a boolean value.
2543 * @param string $oname The option to check
2544 * @return bool User's current value for the option
2547 public function getBoolOption( $oname ) {
2548 return (bool)$this->getOption( $oname );
2552 * Get the user's current setting for a given option, as an integer value.
2554 * @param string $oname The option to check
2555 * @param int $defaultOverride A default value returned if the option does not exist
2556 * @return int User's current value for the option
2559 public function getIntOption( $oname, $defaultOverride = 0 ) {
2560 $val = $this->getOption( $oname );
2562 $val = $defaultOverride;
2564 return intval( $val );
2568 * Set the given option for a user.
2570 * You need to call saveSettings() to actually write to the database.
2572 * @param string $oname The option to set
2573 * @param mixed $val New value to set
2575 public function setOption( $oname, $val ) {
2576 $this->loadOptions();
2578 // Explicitly NULL values should refer to defaults
2579 if ( is_null( $val ) ) {
2580 $val = self
::getDefaultOption( $oname );
2583 $this->mOptions
[$oname] = $val;
2587 * Get a token stored in the preferences (like the watchlist one),
2588 * resetting it if it's empty (and saving changes).
2590 * @param string $oname The option name to retrieve the token from
2591 * @return string|bool User's current value for the option, or false if this option is disabled.
2592 * @see resetTokenFromOption()
2595 public function getTokenFromOption( $oname ) {
2596 global $wgHiddenPrefs;
2597 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2601 $token = $this->getOption( $oname );
2603 $token = $this->resetTokenFromOption( $oname );
2604 $this->saveSettings();
2610 * Reset a token stored in the preferences (like the watchlist one).
2611 * *Does not* save user's preferences (similarly to setOption()).
2613 * @param string $oname The option name to reset the token in
2614 * @return string|bool New token value, or false if this option is disabled.
2615 * @see getTokenFromOption()
2618 public function resetTokenFromOption( $oname ) {
2619 global $wgHiddenPrefs;
2620 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2624 $token = MWCryptRand
::generateHex( 40 );
2625 $this->setOption( $oname, $token );
2630 * Return a list of the types of user options currently returned by
2631 * User::getOptionKinds().
2633 * Currently, the option kinds are:
2634 * - 'registered' - preferences which are registered in core MediaWiki or
2635 * by extensions using the UserGetDefaultOptions hook.
2636 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2637 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2638 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2639 * be used by user scripts.
2640 * - 'special' - "preferences" that are not accessible via User::getOptions
2641 * or User::setOptions.
2642 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2643 * These are usually legacy options, removed in newer versions.
2645 * The API (and possibly others) use this function to determine the possible
2646 * option types for validation purposes, so make sure to update this when a
2647 * new option kind is added.
2649 * @see User::getOptionKinds
2650 * @return array Option kinds
2652 public static function listOptionKinds() {
2655 'registered-multiselect',
2656 'registered-checkmatrix',
2664 * Return an associative array mapping preferences keys to the kind of a preference they're
2665 * used for. Different kinds are handled differently when setting or reading preferences.
2667 * See User::listOptionKinds for the list of valid option types that can be provided.
2669 * @see User::listOptionKinds
2670 * @param IContextSource $context
2671 * @param array $options Assoc. array with options keys to check as keys.
2672 * Defaults to $this->mOptions.
2673 * @return array The key => kind mapping data
2675 public function getOptionKinds( IContextSource
$context, $options = null ) {
2676 $this->loadOptions();
2677 if ( $options === null ) {
2678 $options = $this->mOptions
;
2681 $prefs = Preferences
::getPreferences( $this, $context );
2684 // Pull out the "special" options, so they don't get converted as
2685 // multiselect or checkmatrix.
2686 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2687 foreach ( $specialOptions as $name => $value ) {
2688 unset( $prefs[$name] );
2691 // Multiselect and checkmatrix options are stored in the database with
2692 // one key per option, each having a boolean value. Extract those keys.
2693 $multiselectOptions = array();
2694 foreach ( $prefs as $name => $info ) {
2695 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2696 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2697 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2698 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2700 foreach ( $opts as $value ) {
2701 $multiselectOptions["$prefix$value"] = true;
2704 unset( $prefs[$name] );
2707 $checkmatrixOptions = array();
2708 foreach ( $prefs as $name => $info ) {
2709 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2710 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2711 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2712 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2713 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2715 foreach ( $columns as $column ) {
2716 foreach ( $rows as $row ) {
2717 $checkmatrixOptions["$prefix-$column-$row"] = true;
2721 unset( $prefs[$name] );
2725 // $value is ignored
2726 foreach ( $options as $key => $value ) {
2727 if ( isset( $prefs[$key] ) ) {
2728 $mapping[$key] = 'registered';
2729 } elseif ( isset( $multiselectOptions[$key] ) ) {
2730 $mapping[$key] = 'registered-multiselect';
2731 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2732 $mapping[$key] = 'registered-checkmatrix';
2733 } elseif ( isset( $specialOptions[$key] ) ) {
2734 $mapping[$key] = 'special';
2735 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2736 $mapping[$key] = 'userjs';
2738 $mapping[$key] = 'unused';
2746 * Reset certain (or all) options to the site defaults
2748 * The optional parameter determines which kinds of preferences will be reset.
2749 * Supported values are everything that can be reported by getOptionKinds()
2750 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2752 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2753 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2754 * for backwards-compatibility.
2755 * @param IContextSource|null $context Context source used when $resetKinds
2756 * does not contain 'all', passed to getOptionKinds().
2757 * Defaults to RequestContext::getMain() when null.
2759 public function resetOptions(
2760 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2761 IContextSource
$context = null
2764 $defaultOptions = self
::getDefaultOptions();
2766 if ( !is_array( $resetKinds ) ) {
2767 $resetKinds = array( $resetKinds );
2770 if ( in_array( 'all', $resetKinds ) ) {
2771 $newOptions = $defaultOptions;
2773 if ( $context === null ) {
2774 $context = RequestContext
::getMain();
2777 $optionKinds = $this->getOptionKinds( $context );
2778 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2779 $newOptions = array();
2781 // Use default values for the options that should be deleted, and
2782 // copy old values for the ones that shouldn't.
2783 foreach ( $this->mOptions
as $key => $value ) {
2784 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2785 if ( array_key_exists( $key, $defaultOptions ) ) {
2786 $newOptions[$key] = $defaultOptions[$key];
2789 $newOptions[$key] = $value;
2794 wfRunHooks( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2796 $this->mOptions
= $newOptions;
2797 $this->mOptionsLoaded
= true;
2801 * Get the user's preferred date format.
2802 * @return string User's preferred date format
2804 public function getDatePreference() {
2805 // Important migration for old data rows
2806 if ( is_null( $this->mDatePreference
) ) {
2808 $value = $this->getOption( 'date' );
2809 $map = $wgLang->getDatePreferenceMigrationMap();
2810 if ( isset( $map[$value] ) ) {
2811 $value = $map[$value];
2813 $this->mDatePreference
= $value;
2815 return $this->mDatePreference
;
2819 * Determine based on the wiki configuration and the user's options,
2820 * whether this user must be over HTTPS no matter what.
2824 public function requiresHTTPS() {
2825 global $wgSecureLogin;
2826 if ( !$wgSecureLogin ) {
2829 $https = $this->getBoolOption( 'prefershttps' );
2830 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2832 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2839 * Get the user preferred stub threshold
2843 public function getStubThreshold() {
2844 global $wgMaxArticleSize; # Maximum article size, in Kb
2845 $threshold = $this->getIntOption( 'stubthreshold' );
2846 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2847 // If they have set an impossible value, disable the preference
2848 // so we can use the parser cache again.
2855 * Get the permissions this user has.
2856 * @return array Array of String permission names
2858 public function getRights() {
2859 if ( is_null( $this->mRights
) ) {
2860 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2861 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2862 // Force reindexation of rights when a hook has unset one of them
2863 $this->mRights
= array_values( array_unique( $this->mRights
) );
2865 return $this->mRights
;
2869 * Get the list of explicit group memberships this user has.
2870 * The implicit * and user groups are not included.
2871 * @return array Array of String internal group names
2873 public function getGroups() {
2875 $this->loadGroups();
2876 return $this->mGroups
;
2880 * Get the list of implicit group memberships this user has.
2881 * This includes all explicit groups, plus 'user' if logged in,
2882 * '*' for all accounts, and autopromoted groups
2883 * @param bool $recache Whether to avoid the cache
2884 * @return array Array of String internal group names
2886 public function getEffectiveGroups( $recache = false ) {
2887 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2888 wfProfileIn( __METHOD__
);
2889 $this->mEffectiveGroups
= array_unique( array_merge(
2890 $this->getGroups(), // explicit groups
2891 $this->getAutomaticGroups( $recache ) // implicit groups
2893 // Hook for additional groups
2894 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2895 // Force reindexation of groups when a hook has unset one of them
2896 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
2897 wfProfileOut( __METHOD__
);
2899 return $this->mEffectiveGroups
;
2903 * Get the list of implicit group memberships this user has.
2904 * This includes 'user' if logged in, '*' for all accounts,
2905 * and autopromoted groups
2906 * @param bool $recache Whether to avoid the cache
2907 * @return array Array of String internal group names
2909 public function getAutomaticGroups( $recache = false ) {
2910 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
2911 wfProfileIn( __METHOD__
);
2912 $this->mImplicitGroups
= array( '*' );
2913 if ( $this->getId() ) {
2914 $this->mImplicitGroups
[] = 'user';
2916 $this->mImplicitGroups
= array_unique( array_merge(
2917 $this->mImplicitGroups
,
2918 Autopromote
::getAutopromoteGroups( $this )
2922 // Assure data consistency with rights/groups,
2923 // as getEffectiveGroups() depends on this function
2924 $this->mEffectiveGroups
= null;
2926 wfProfileOut( __METHOD__
);
2928 return $this->mImplicitGroups
;
2932 * Returns the groups the user has belonged to.
2934 * The user may still belong to the returned groups. Compare with getGroups().
2936 * The function will not return groups the user had belonged to before MW 1.17
2938 * @return array Names of the groups the user has belonged to.
2940 public function getFormerGroups() {
2941 if ( is_null( $this->mFormerGroups
) ) {
2942 $dbr = wfGetDB( DB_MASTER
);
2943 $res = $dbr->select( 'user_former_groups',
2944 array( 'ufg_group' ),
2945 array( 'ufg_user' => $this->mId
),
2947 $this->mFormerGroups
= array();
2948 foreach ( $res as $row ) {
2949 $this->mFormerGroups
[] = $row->ufg_group
;
2952 return $this->mFormerGroups
;
2956 * Get the user's edit count.
2957 * @return int|null Null for anonymous users
2959 public function getEditCount() {
2960 if ( !$this->getId() ) {
2964 if ( $this->mEditCount
=== null ) {
2965 /* Populate the count, if it has not been populated yet */
2966 wfProfileIn( __METHOD__
);
2967 $dbr = wfGetDB( DB_SLAVE
);
2968 // check if the user_editcount field has been initialized
2969 $count = $dbr->selectField(
2970 'user', 'user_editcount',
2971 array( 'user_id' => $this->mId
),
2975 if ( $count === null ) {
2976 // it has not been initialized. do so.
2977 $count = $this->initEditCount();
2979 $this->mEditCount
= $count;
2980 wfProfileOut( __METHOD__
);
2982 return (int)$this->mEditCount
;
2986 * Add the user to the given group.
2987 * This takes immediate effect.
2988 * @param string $group Name of the group to add
2990 public function addGroup( $group ) {
2991 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2992 $dbw = wfGetDB( DB_MASTER
);
2993 if ( $this->getId() ) {
2994 $dbw->insert( 'user_groups',
2996 'ug_user' => $this->getID(),
2997 'ug_group' => $group,
3000 array( 'IGNORE' ) );
3003 $this->loadGroups();
3004 $this->mGroups
[] = $group;
3005 // In case loadGroups was not called before, we now have the right twice.
3006 // Get rid of the duplicate.
3007 $this->mGroups
= array_unique( $this->mGroups
);
3009 // Refresh the groups caches, and clear the rights cache so it will be
3010 // refreshed on the next call to $this->getRights().
3011 $this->getEffectiveGroups( true );
3012 $this->mRights
= null;
3014 $this->invalidateCache();
3018 * Remove the user from the given group.
3019 * This takes immediate effect.
3020 * @param string $group Name of the group to remove
3022 public function removeGroup( $group ) {
3024 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3025 $dbw = wfGetDB( DB_MASTER
);
3026 $dbw->delete( 'user_groups',
3028 'ug_user' => $this->getID(),
3029 'ug_group' => $group,
3031 // Remember that the user was in this group
3032 $dbw->insert( 'user_former_groups',
3034 'ufg_user' => $this->getID(),
3035 'ufg_group' => $group,
3038 array( 'IGNORE' ) );
3040 $this->loadGroups();
3041 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3043 // Refresh the groups caches, and clear the rights cache so it will be
3044 // refreshed on the next call to $this->getRights().
3045 $this->getEffectiveGroups( true );
3046 $this->mRights
= null;
3048 $this->invalidateCache();
3052 * Get whether the user is logged in
3055 public function isLoggedIn() {
3056 return $this->getID() != 0;
3060 * Get whether the user is anonymous
3063 public function isAnon() {
3064 return !$this->isLoggedIn();
3068 * Check if user is allowed to access a feature / make an action
3070 * @internal param \String $varargs permissions to test
3071 * @return bool True if user is allowed to perform *any* of the given actions
3075 public function isAllowedAny( /*...*/ ) {
3076 $permissions = func_get_args();
3077 foreach ( $permissions as $permission ) {
3078 if ( $this->isAllowed( $permission ) ) {
3087 * @internal param $varargs string
3088 * @return bool True if the user is allowed to perform *all* of the given actions
3090 public function isAllowedAll( /*...*/ ) {
3091 $permissions = func_get_args();
3092 foreach ( $permissions as $permission ) {
3093 if ( !$this->isAllowed( $permission ) ) {
3101 * Internal mechanics of testing a permission
3102 * @param string $action
3105 public function isAllowed( $action = '' ) {
3106 if ( $action === '' ) {
3107 return true; // In the spirit of DWIM
3109 // Patrolling may not be enabled
3110 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3111 global $wgUseRCPatrol, $wgUseNPPatrol;
3112 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3116 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3117 // by misconfiguration: 0 == 'foo'
3118 return in_array( $action, $this->getRights(), true );
3122 * Check whether to enable recent changes patrol features for this user
3123 * @return bool True or false
3125 public function useRCPatrol() {
3126 global $wgUseRCPatrol;
3127 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3131 * Check whether to enable new pages patrol features for this user
3132 * @return bool True or false
3134 public function useNPPatrol() {
3135 global $wgUseRCPatrol, $wgUseNPPatrol;
3137 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3138 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3143 * Get the WebRequest object to use with this object
3145 * @return WebRequest
3147 public function getRequest() {
3148 if ( $this->mRequest
) {
3149 return $this->mRequest
;
3157 * Get the current skin, loading it if required
3158 * @return Skin The current skin
3159 * @todo FIXME: Need to check the old failback system [AV]
3160 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3162 public function getSkin() {
3163 wfDeprecated( __METHOD__
, '1.18' );
3164 return RequestContext
::getMain()->getSkin();
3168 * Get a WatchedItem for this user and $title.
3170 * @since 1.22 $checkRights parameter added
3171 * @param Title $title
3172 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3173 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3174 * @return WatchedItem
3176 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3177 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3179 if ( isset( $this->mWatchedItems
[$key] ) ) {
3180 return $this->mWatchedItems
[$key];
3183 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3184 $this->mWatchedItems
= array();
3187 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3188 return $this->mWatchedItems
[$key];
3192 * Check the watched status of an article.
3193 * @since 1.22 $checkRights parameter added
3194 * @param Title $title Title of the article to look at
3195 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3196 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3199 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3200 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3205 * @since 1.22 $checkRights parameter added
3206 * @param Title $title Title of the article to look at
3207 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3208 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3210 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3211 $this->getWatchedItem( $title, $checkRights )->addWatch();
3212 $this->invalidateCache();
3216 * Stop watching an article.
3217 * @since 1.22 $checkRights parameter added
3218 * @param Title $title Title of the article to look at
3219 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3220 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3222 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3223 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3224 $this->invalidateCache();
3228 * Clear the user's notification timestamp for the given title.
3229 * If e-notif e-mails are on, they will receive notification mails on
3230 * the next change of the page if it's watched etc.
3231 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3232 * @param Title $title Title of the article to look at
3233 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3235 public function clearNotification( &$title, $oldid = 0 ) {
3236 global $wgUseEnotif, $wgShowUpdatedMarker;
3238 // Do nothing if the database is locked to writes
3239 if ( wfReadOnly() ) {
3243 // Do nothing if not allowed to edit the watchlist
3244 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3248 // If we're working on user's talk page, we should update the talk page message indicator
3249 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3250 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3254 $nextid = $oldid ?
$title->getNextRevisionID( $oldid ) : null;
3256 if ( !$oldid ||
!$nextid ) {
3257 // If we're looking at the latest revision, we should definitely clear it
3258 $this->setNewtalk( false );
3260 // Otherwise we should update its revision, if it's present
3261 if ( $this->getNewtalk() ) {
3262 // Naturally the other one won't clear by itself
3263 $this->setNewtalk( false );
3264 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3269 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3273 if ( $this->isAnon() ) {
3274 // Nothing else to do...
3278 // Only update the timestamp if the page is being watched.
3279 // The query to find out if it is watched is cached both in memcached and per-invocation,
3280 // and when it does have to be executed, it can be on a slave
3281 // If this is the user's newtalk page, we always update the timestamp
3283 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3287 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3291 * Resets all of the given user's page-change notification timestamps.
3292 * If e-notif e-mails are on, they will receive notification mails on
3293 * the next change of any watched page.
3294 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3296 public function clearAllNotifications() {
3297 if ( wfReadOnly() ) {
3301 // Do nothing if not allowed to edit the watchlist
3302 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3306 global $wgUseEnotif, $wgShowUpdatedMarker;
3307 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3308 $this->setNewtalk( false );
3311 $id = $this->getId();
3313 $dbw = wfGetDB( DB_MASTER
);
3314 $dbw->update( 'watchlist',
3315 array( /* SET */ 'wl_notificationtimestamp' => null ),
3316 array( /* WHERE */ 'wl_user' => $id ),
3319 // We also need to clear here the "you have new message" notification for the own user_talk page;
3320 // it's cleared one page view later in WikiPage::doViewUpdates().
3325 * Set a cookie on the user's client. Wrapper for
3326 * WebResponse::setCookie
3327 * @param string $name Name of the cookie to set
3328 * @param string $value Value to set
3329 * @param int $exp Expiration time, as a UNIX time value;
3330 * if 0 or not specified, use the default $wgCookieExpiration
3331 * @param bool $secure
3332 * true: Force setting the secure attribute when setting the cookie
3333 * false: Force NOT setting the secure attribute when setting the cookie
3334 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3335 * @param array $params Array of options sent passed to WebResponse::setcookie()
3337 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3338 $params['secure'] = $secure;
3339 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3343 * Clear a cookie on the user's client
3344 * @param string $name Name of the cookie to clear
3345 * @param bool $secure
3346 * true: Force setting the secure attribute when setting the cookie
3347 * false: Force NOT setting the secure attribute when setting the cookie
3348 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3349 * @param array $params Array of options sent passed to WebResponse::setcookie()
3351 protected function clearCookie( $name, $secure = null, $params = array() ) {
3352 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3356 * Set the default cookies for this session on the user's client.
3358 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3360 * @param bool $secure Whether to force secure/insecure cookies or use default
3361 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3363 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3364 if ( $request === null ) {
3365 $request = $this->getRequest();
3369 if ( 0 == $this->mId
) {
3372 if ( !$this->mToken
) {
3373 // When token is empty or NULL generate a new one and then save it to the database
3374 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3375 // Simply by setting every cell in the user_token column to NULL and letting them be
3376 // regenerated as users log back into the wiki.
3378 $this->saveSettings();
3381 'wsUserID' => $this->mId
,
3382 'wsToken' => $this->mToken
,
3383 'wsUserName' => $this->getName()
3386 'UserID' => $this->mId
,
3387 'UserName' => $this->getName(),
3389 if ( $rememberMe ) {
3390 $cookies['Token'] = $this->mToken
;
3392 $cookies['Token'] = false;
3395 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3397 foreach ( $session as $name => $value ) {
3398 $request->setSessionData( $name, $value );
3400 foreach ( $cookies as $name => $value ) {
3401 if ( $value === false ) {
3402 $this->clearCookie( $name );
3404 $this->setCookie( $name, $value, 0, $secure );
3409 * If wpStickHTTPS was selected, also set an insecure cookie that
3410 * will cause the site to redirect the user to HTTPS, if they access
3411 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3412 * as the one set by centralauth (bug 53538). Also set it to session, or
3413 * standard time setting, based on if rememberme was set.
3415 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3419 $rememberMe ?
0 : null,
3421 array( 'prefix' => '' ) // no prefix
3427 * Log this user out.
3429 public function logout() {
3430 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3436 * Clear the user's cookies and session, and reset the instance cache.
3439 public function doLogout() {
3440 $this->clearInstanceCache( 'defaults' );
3442 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3444 $this->clearCookie( 'UserID' );
3445 $this->clearCookie( 'Token' );
3446 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3448 // Remember when user logged out, to prevent seeing cached pages
3449 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3453 * Save this user's settings into the database.
3454 * @todo Only rarely do all these fields need to be set!
3456 public function saveSettings() {
3460 $this->loadPasswords();
3461 if ( wfReadOnly() ) {
3464 if ( 0 == $this->mId
) {
3468 $this->mTouched
= self
::newTouchedTimestamp();
3469 if ( !$wgAuth->allowSetLocalPassword() ) {
3470 $this->mPassword
= self
::getPasswordFactory()->newFromCiphertext( null );
3473 $dbw = wfGetDB( DB_MASTER
);
3474 $dbw->update( 'user',
3476 'user_name' => $this->mName
,
3477 'user_password' => $this->mPassword
->toString(),
3478 'user_newpassword' => $this->mNewpassword
->toString(),
3479 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3480 'user_real_name' => $this->mRealName
,
3481 'user_email' => $this->mEmail
,
3482 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3483 'user_touched' => $dbw->timestamp( $this->mTouched
),
3484 'user_token' => strval( $this->mToken
),
3485 'user_email_token' => $this->mEmailToken
,
3486 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3487 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires
),
3488 ), array( /* WHERE */
3489 'user_id' => $this->mId
3493 $this->saveOptions();
3495 wfRunHooks( 'UserSaveSettings', array( $this ) );
3496 $this->clearSharedCache();
3497 $this->getUserPage()->invalidateCache();
3501 * If only this user's username is known, and it exists, return the user ID.
3504 public function idForName() {
3505 $s = trim( $this->getName() );
3510 $dbr = wfGetDB( DB_SLAVE
);
3511 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
3512 if ( $id === false ) {
3519 * Add a user to the database, return the user object
3521 * @param string $name Username to add
3522 * @param array $params Array of Strings Non-default parameters to save to
3523 * the database as user_* fields:
3524 * - password: The user's password hash. Password logins will be disabled
3525 * if this is omitted.
3526 * - newpassword: Hash for a temporary password that has been mailed to
3528 * - email: The user's email address.
3529 * - email_authenticated: The email authentication timestamp.
3530 * - real_name: The user's real name.
3531 * - options: An associative array of non-default options.
3532 * - token: Random authentication token. Do not set.
3533 * - registration: Registration timestamp. Do not set.
3535 * @return User|null User object, or null if the username already exists.
3537 public static function createNew( $name, $params = array() ) {
3540 $user->loadPasswords();
3541 $user->setToken(); // init token
3542 if ( isset( $params['options'] ) ) {
3543 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3544 unset( $params['options'] );
3546 $dbw = wfGetDB( DB_MASTER
);
3547 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3550 'user_id' => $seqVal,
3551 'user_name' => $name,
3552 'user_password' => $user->mPassword
->toString(),
3553 'user_newpassword' => $user->mNewpassword
->toString(),
3554 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3555 'user_email' => $user->mEmail
,
3556 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3557 'user_real_name' => $user->mRealName
,
3558 'user_token' => strval( $user->mToken
),
3559 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3560 'user_editcount' => 0,
3561 'user_touched' => $dbw->timestamp( self
::newTouchedTimestamp() ),
3563 foreach ( $params as $name => $value ) {
3564 $fields["user_$name"] = $value;
3566 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3567 if ( $dbw->affectedRows() ) {
3568 $newUser = User
::newFromId( $dbw->insertId() );
3576 * Add this existing user object to the database. If the user already
3577 * exists, a fatal status object is returned, and the user object is
3578 * initialised with the data from the database.
3580 * Previously, this function generated a DB error due to a key conflict
3581 * if the user already existed. Many extension callers use this function
3582 * in code along the lines of:
3584 * $user = User::newFromName( $name );
3585 * if ( !$user->isLoggedIn() ) {
3586 * $user->addToDatabase();
3588 * // do something with $user...
3590 * However, this was vulnerable to a race condition (bug 16020). By
3591 * initialising the user object if the user exists, we aim to support this
3592 * calling sequence as far as possible.
3594 * Note that if the user exists, this function will acquire a write lock,
3595 * so it is still advisable to make the call conditional on isLoggedIn(),
3596 * and to commit the transaction after calling.
3598 * @throws MWException
3601 public function addToDatabase() {
3603 $this->loadPasswords();
3604 if ( !$this->mToken
) {
3605 $this->setToken(); // init token
3608 $this->mTouched
= self
::newTouchedTimestamp();
3610 $dbw = wfGetDB( DB_MASTER
);
3611 $inWrite = $dbw->writesOrCallbacksPending();
3612 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3613 $dbw->insert( 'user',
3615 'user_id' => $seqVal,
3616 'user_name' => $this->mName
,
3617 'user_password' => $this->mPassword
->toString(),
3618 'user_newpassword' => $this->mNewpassword
->toString(),
3619 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3620 'user_email' => $this->mEmail
,
3621 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3622 'user_real_name' => $this->mRealName
,
3623 'user_token' => strval( $this->mToken
),
3624 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3625 'user_editcount' => 0,
3626 'user_touched' => $dbw->timestamp( $this->mTouched
),
3630 if ( !$dbw->affectedRows() ) {
3631 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3632 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3634 // Can't commit due to pending writes that may need atomicity.
3635 // This may cause some lock contention unlike the case below.
3636 $options = array( 'LOCK IN SHARE MODE' );
3637 $flags = self
::READ_LOCKING
;
3639 // Often, this case happens early in views before any writes when
3640 // using CentralAuth. It's should be OK to commit and break the snapshot.
3641 $dbw->commit( __METHOD__
, 'flush' );
3645 $this->mId
= $dbw->selectField( 'user', 'user_id',
3646 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3649 if ( $this->loadFromDatabase( $flags ) ) {
3654 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3655 "to insert user '{$this->mName}' row, but it was not present in select!" );
3657 return Status
::newFatal( 'userexists' );
3659 $this->mId
= $dbw->insertId();
3661 // Clear instance cache other than user table data, which is already accurate
3662 $this->clearInstanceCache();
3664 $this->saveOptions();
3665 return Status
::newGood();
3669 * If this user is logged-in and blocked,
3670 * block any IP address they've successfully logged in from.
3671 * @return bool A block was spread
3673 public function spreadAnyEditBlock() {
3674 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3675 return $this->spreadBlock();
3681 * If this (non-anonymous) user is blocked,
3682 * block the IP address they've successfully logged in from.
3683 * @return bool A block was spread
3685 protected function spreadBlock() {
3686 wfDebug( __METHOD__
. "()\n" );
3688 if ( $this->mId
== 0 ) {
3692 $userblock = Block
::newFromTarget( $this->getName() );
3693 if ( !$userblock ) {
3697 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3701 * Get whether the user is explicitly blocked from account creation.
3702 * @return bool|Block
3704 public function isBlockedFromCreateAccount() {
3705 $this->getBlockedStatus();
3706 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3707 return $this->mBlock
;
3710 # bug 13611: if the IP address the user is trying to create an account from is
3711 # blocked with createaccount disabled, prevent new account creation there even
3712 # when the user is logged in
3713 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3714 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3716 return $this->mBlockedFromCreateAccount
instanceof Block
3717 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3718 ?
$this->mBlockedFromCreateAccount
3723 * Get whether the user is blocked from using Special:Emailuser.
3726 public function isBlockedFromEmailuser() {
3727 $this->getBlockedStatus();
3728 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3732 * Get whether the user is allowed to create an account.
3735 public function isAllowedToCreateAccount() {
3736 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3740 * Get this user's personal page title.
3742 * @return Title User's personal page title
3744 public function getUserPage() {
3745 return Title
::makeTitle( NS_USER
, $this->getName() );
3749 * Get this user's talk page title.
3751 * @return Title User's talk page title
3753 public function getTalkPage() {
3754 $title = $this->getUserPage();
3755 return $title->getTalkPage();
3759 * Determine whether the user is a newbie. Newbies are either
3760 * anonymous IPs, or the most recently created accounts.
3763 public function isNewbie() {
3764 return !$this->isAllowed( 'autoconfirmed' );
3768 * Check to see if the given clear-text password is one of the accepted passwords
3769 * @param string $password User password
3770 * @return bool True if the given password is correct, otherwise False
3772 public function checkPassword( $password ) {
3773 global $wgAuth, $wgLegacyEncoding;
3774 $this->loadPasswords();
3776 // Certain authentication plugins do NOT want to save
3777 // domain passwords in a mysql database, so we should
3778 // check this (in case $wgAuth->strict() is false).
3780 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3782 } elseif ( $wgAuth->strict() ) {
3783 // Auth plugin doesn't allow local authentication
3785 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3786 // Auth plugin doesn't allow local authentication for this user name
3790 $passwordFactory = self
::getPasswordFactory();
3791 if ( !$this->mPassword
->equals( $password ) ) {
3792 if ( $wgLegacyEncoding ) {
3793 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3794 // Check for this with iconv
3795 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3796 if ( $cp1252Password === $password ||
!$this->mPassword
->equals( $cp1252Password ) ) {
3804 if ( $passwordFactory->needsUpdate( $this->mPassword
) ) {
3805 $this->mPassword
= $passwordFactory->newFromPlaintext( $password );
3806 $this->saveSettings();
3813 * Check if the given clear-text password matches the temporary password
3814 * sent by e-mail for password reset operations.
3816 * @param string $plaintext
3818 * @return bool True if matches, false otherwise
3820 public function checkTemporaryPassword( $plaintext ) {
3821 global $wgNewPasswordExpiry;
3824 if ( $this->mNewpassword
->equals( $plaintext ) ) {
3825 if ( is_null( $this->mNewpassTime
) ) {
3828 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3829 return ( time() < $expiry );
3836 * Alias for getEditToken.
3837 * @deprecated since 1.19, use getEditToken instead.
3839 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3840 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3841 * @return string The new edit token
3843 public function editToken( $salt = '', $request = null ) {
3844 wfDeprecated( __METHOD__
, '1.19' );
3845 return $this->getEditToken( $salt, $request );
3849 * Initialize (if necessary) and return a session token value
3850 * which can be used in edit forms to show that the user's
3851 * login credentials aren't being hijacked with a foreign form
3856 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3857 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3858 * @return string The new edit token
3860 public function getEditToken( $salt = '', $request = null ) {
3861 if ( $request == null ) {
3862 $request = $this->getRequest();
3865 if ( $this->isAnon() ) {
3866 return EDIT_TOKEN_SUFFIX
;
3868 $token = $request->getSessionData( 'wsEditToken' );
3869 if ( $token === null ) {
3870 $token = MWCryptRand
::generateHex( 32 );
3871 $request->setSessionData( 'wsEditToken', $token );
3873 if ( is_array( $salt ) ) {
3874 $salt = implode( '|', $salt );
3876 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
3881 * Generate a looking random token for various uses.
3883 * @return string The new random token
3884 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
3885 * wfRandomString for pseudo-randomness.
3887 public static function generateToken() {
3888 return MWCryptRand
::generateHex( 32 );
3892 * Check given value against the token value stored in the session.
3893 * A match should confirm that the form was submitted from the
3894 * user's own login session, not a form submission from a third-party
3897 * @param string $val Input value to compare
3898 * @param string $salt Optional function-specific data for hashing
3899 * @param WebRequest|null $request Object to use or null to use $wgRequest
3900 * @return bool Whether the token matches
3902 public function matchEditToken( $val, $salt = '', $request = null ) {
3903 $sessionToken = $this->getEditToken( $salt, $request );
3904 if ( $val != $sessionToken ) {
3905 wfDebug( "User::matchEditToken: broken session data\n" );
3908 return $val == $sessionToken;
3912 * Check given value against the token value stored in the session,
3913 * ignoring the suffix.
3915 * @param string $val Input value to compare
3916 * @param string $salt Optional function-specific data for hashing
3917 * @param WebRequest|null $request Object to use or null to use $wgRequest
3918 * @return bool Whether the token matches
3920 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3921 $sessionToken = $this->getEditToken( $salt, $request );
3922 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3926 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3927 * mail to the user's given address.
3929 * @param string $type Message to send, either "created", "changed" or "set"
3932 public function sendConfirmationMail( $type = 'created' ) {
3934 $expiration = null; // gets passed-by-ref and defined in next line.
3935 $token = $this->confirmationToken( $expiration );
3936 $url = $this->confirmationTokenUrl( $token );
3937 $invalidateURL = $this->invalidationTokenUrl( $token );
3938 $this->saveSettings();
3940 if ( $type == 'created' ||
$type === false ) {
3941 $message = 'confirmemail_body';
3942 } elseif ( $type === true ) {
3943 $message = 'confirmemail_body_changed';
3945 // Messages: confirmemail_body_changed, confirmemail_body_set
3946 $message = 'confirmemail_body_' . $type;
3949 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3950 wfMessage( $message,
3951 $this->getRequest()->getIP(),
3954 $wgLang->timeanddate( $expiration, false ),
3956 $wgLang->date( $expiration, false ),
3957 $wgLang->time( $expiration, false ) )->text() );
3961 * Send an e-mail to this user's account. Does not check for
3962 * confirmed status or validity.
3964 * @param string $subject Message subject
3965 * @param string $body Message body
3966 * @param string $from Optional From address; if unspecified, default
3967 * $wgPasswordSender will be used.
3968 * @param string $replyto Reply-To address
3971 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3972 if ( is_null( $from ) ) {
3973 global $wgPasswordSender;
3974 $sender = new MailAddress( $wgPasswordSender,
3975 wfMessage( 'emailsender' )->inContentLanguage()->text() );
3977 $sender = new MailAddress( $from );
3980 $to = new MailAddress( $this );
3981 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
3985 * Generate, store, and return a new e-mail confirmation code.
3986 * A hash (unsalted, since it's used as a key) is stored.
3988 * @note Call saveSettings() after calling this function to commit
3989 * this change to the database.
3991 * @param string &$expiration Accepts the expiration time
3992 * @return string New token
3994 protected function confirmationToken( &$expiration ) {
3995 global $wgUserEmailConfirmationTokenExpiry;
3997 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
3998 $expiration = wfTimestamp( TS_MW
, $expires );
4000 $token = MWCryptRand
::generateHex( 32 );
4001 $hash = md5( $token );
4002 $this->mEmailToken
= $hash;
4003 $this->mEmailTokenExpires
= $expiration;
4008 * Return a URL the user can use to confirm their email address.
4009 * @param string $token Accepts the email confirmation token
4010 * @return string New token URL
4012 protected function confirmationTokenUrl( $token ) {
4013 return $this->getTokenUrl( 'ConfirmEmail', $token );
4017 * Return a URL the user can use to invalidate their email address.
4018 * @param string $token Accepts the email confirmation token
4019 * @return string New token URL
4021 protected function invalidationTokenUrl( $token ) {
4022 return $this->getTokenUrl( 'InvalidateEmail', $token );
4026 * Internal function to format the e-mail validation/invalidation URLs.
4027 * This uses a quickie hack to use the
4028 * hardcoded English names of the Special: pages, for ASCII safety.
4030 * @note Since these URLs get dropped directly into emails, using the
4031 * short English names avoids insanely long URL-encoded links, which
4032 * also sometimes can get corrupted in some browsers/mailers
4033 * (bug 6957 with Gmail and Internet Explorer).
4035 * @param string $page Special page
4036 * @param string $token Token
4037 * @return string Formatted URL
4039 protected function getTokenUrl( $page, $token ) {
4040 // Hack to bypass localization of 'Special:'
4041 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4042 return $title->getCanonicalURL();
4046 * Mark the e-mail address confirmed.
4048 * @note Call saveSettings() after calling this function to commit the change.
4052 public function confirmEmail() {
4053 // Check if it's already confirmed, so we don't touch the database
4054 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4055 if ( !$this->isEmailConfirmed() ) {
4056 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4057 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
4063 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4064 * address if it was already confirmed.
4066 * @note Call saveSettings() after calling this function to commit the change.
4067 * @return bool Returns true
4069 public function invalidateEmail() {
4071 $this->mEmailToken
= null;
4072 $this->mEmailTokenExpires
= null;
4073 $this->setEmailAuthenticationTimestamp( null );
4074 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
4079 * Set the e-mail authentication timestamp.
4080 * @param string $timestamp TS_MW timestamp
4082 public function setEmailAuthenticationTimestamp( $timestamp ) {
4084 $this->mEmailAuthenticated
= $timestamp;
4085 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4089 * Is this user allowed to send e-mails within limits of current
4090 * site configuration?
4093 public function canSendEmail() {
4094 global $wgEnableEmail, $wgEnableUserEmail;
4095 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4098 $canSend = $this->isEmailConfirmed();
4099 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4104 * Is this user allowed to receive e-mails within limits of current
4105 * site configuration?
4108 public function canReceiveEmail() {
4109 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4113 * Is this user's e-mail address valid-looking and confirmed within
4114 * limits of the current site configuration?
4116 * @note If $wgEmailAuthentication is on, this may require the user to have
4117 * confirmed their address by returning a code or using a password
4118 * sent to the address from the wiki.
4122 public function isEmailConfirmed() {
4123 global $wgEmailAuthentication;
4126 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4127 if ( $this->isAnon() ) {
4130 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4133 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4143 * Check whether there is an outstanding request for e-mail confirmation.
4146 public function isEmailConfirmationPending() {
4147 global $wgEmailAuthentication;
4148 return $wgEmailAuthentication &&
4149 !$this->isEmailConfirmed() &&
4150 $this->mEmailToken
&&
4151 $this->mEmailTokenExpires
> wfTimestamp();
4155 * Get the timestamp of account creation.
4157 * @return string|bool|null Timestamp of account creation, false for
4158 * non-existent/anonymous user accounts, or null if existing account
4159 * but information is not in database.
4161 public function getRegistration() {
4162 if ( $this->isAnon() ) {
4166 return $this->mRegistration
;
4170 * Get the timestamp of the first edit
4172 * @return string|bool Timestamp of first edit, or false for
4173 * non-existent/anonymous user accounts.
4175 public function getFirstEditTimestamp() {
4176 if ( $this->getId() == 0 ) {
4177 return false; // anons
4179 $dbr = wfGetDB( DB_SLAVE
);
4180 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4181 array( 'rev_user' => $this->getId() ),
4183 array( 'ORDER BY' => 'rev_timestamp ASC' )
4186 return false; // no edits
4188 return wfTimestamp( TS_MW
, $time );
4192 * Get the permissions associated with a given list of groups
4194 * @param array $groups Array of Strings List of internal group names
4195 * @return array Array of Strings List of permission key names for given groups combined
4197 public static function getGroupPermissions( $groups ) {
4198 global $wgGroupPermissions, $wgRevokePermissions;
4200 // grant every granted permission first
4201 foreach ( $groups as $group ) {
4202 if ( isset( $wgGroupPermissions[$group] ) ) {
4203 $rights = array_merge( $rights,
4204 // array_filter removes empty items
4205 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4208 // now revoke the revoked permissions
4209 foreach ( $groups as $group ) {
4210 if ( isset( $wgRevokePermissions[$group] ) ) {
4211 $rights = array_diff( $rights,
4212 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4215 return array_unique( $rights );
4219 * Get all the groups who have a given permission
4221 * @param string $role Role to check
4222 * @return array Array of Strings List of internal group names with the given permission
4224 public static function getGroupsWithPermission( $role ) {
4225 global $wgGroupPermissions;
4226 $allowedGroups = array();
4227 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4228 if ( self
::groupHasPermission( $group, $role ) ) {
4229 $allowedGroups[] = $group;
4232 return $allowedGroups;
4236 * Check, if the given group has the given permission
4238 * If you're wanting to check whether all users have a permission, use
4239 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4243 * @param string $group Group to check
4244 * @param string $role Role to check
4247 public static function groupHasPermission( $group, $role ) {
4248 global $wgGroupPermissions, $wgRevokePermissions;
4249 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4250 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4254 * Check if all users have the given permission
4257 * @param string $right Right to check
4260 public static function isEveryoneAllowed( $right ) {
4261 global $wgGroupPermissions, $wgRevokePermissions;
4262 static $cache = array();
4264 // Use the cached results, except in unit tests which rely on
4265 // being able change the permission mid-request
4266 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4267 return $cache[$right];
4270 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4271 $cache[$right] = false;
4275 // If it's revoked anywhere, then everyone doesn't have it
4276 foreach ( $wgRevokePermissions as $rights ) {
4277 if ( isset( $rights[$right] ) && $rights[$right] ) {
4278 $cache[$right] = false;
4283 // Allow extensions (e.g. OAuth) to say false
4284 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4285 $cache[$right] = false;
4289 $cache[$right] = true;
4294 * Get the localized descriptive name for a group, if it exists
4296 * @param string $group Internal group name
4297 * @return string Localized descriptive group name
4299 public static function getGroupName( $group ) {
4300 $msg = wfMessage( "group-$group" );
4301 return $msg->isBlank() ?
$group : $msg->text();
4305 * Get the localized descriptive name for a member of a group, if it exists
4307 * @param string $group Internal group name
4308 * @param string $username Username for gender (since 1.19)
4309 * @return string Localized name for group member
4311 public static function getGroupMember( $group, $username = '#' ) {
4312 $msg = wfMessage( "group-$group-member", $username );
4313 return $msg->isBlank() ?
$group : $msg->text();
4317 * Return the set of defined explicit groups.
4318 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4319 * are not included, as they are defined automatically, not in the database.
4320 * @return array Array of internal group names
4322 public static function getAllGroups() {
4323 global $wgGroupPermissions, $wgRevokePermissions;
4325 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4326 self
::getImplicitGroups()
4331 * Get a list of all available permissions.
4332 * @return array Array of permission names
4334 public static function getAllRights() {
4335 if ( self
::$mAllRights === false ) {
4336 global $wgAvailableRights;
4337 if ( count( $wgAvailableRights ) ) {
4338 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4340 self
::$mAllRights = self
::$mCoreRights;
4342 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
4344 return self
::$mAllRights;
4348 * Get a list of implicit groups
4349 * @return array Array of Strings Array of internal group names
4351 public static function getImplicitGroups() {
4352 global $wgImplicitGroups;
4354 $groups = $wgImplicitGroups;
4355 # Deprecated, use $wgImplictGroups instead
4356 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) );
4362 * Get the title of a page describing a particular group
4364 * @param string $group Internal group name
4365 * @return Title|bool Title of the page if it exists, false otherwise
4367 public static function getGroupPage( $group ) {
4368 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4369 if ( $msg->exists() ) {
4370 $title = Title
::newFromText( $msg->text() );
4371 if ( is_object( $title ) ) {
4379 * Create a link to the group in HTML, if available;
4380 * else return the group name.
4382 * @param string $group Internal name of the group
4383 * @param string $text The text of the link
4384 * @return string HTML link to the group
4386 public static function makeGroupLinkHTML( $group, $text = '' ) {
4387 if ( $text == '' ) {
4388 $text = self
::getGroupName( $group );
4390 $title = self
::getGroupPage( $group );
4392 return Linker
::link( $title, htmlspecialchars( $text ) );
4399 * Create a link to the group in Wikitext, if available;
4400 * else return the group name.
4402 * @param string $group Internal name of the group
4403 * @param string $text The text of the link
4404 * @return string Wikilink to the group
4406 public static function makeGroupLinkWiki( $group, $text = '' ) {
4407 if ( $text == '' ) {
4408 $text = self
::getGroupName( $group );
4410 $title = self
::getGroupPage( $group );
4412 $page = $title->getPrefixedText();
4413 return "[[$page|$text]]";
4420 * Returns an array of the groups that a particular group can add/remove.
4422 * @param string $group The group to check for whether it can add/remove
4423 * @return array Array( 'add' => array( addablegroups ),
4424 * 'remove' => array( removablegroups ),
4425 * 'add-self' => array( addablegroups to self),
4426 * 'remove-self' => array( removable groups from self) )
4428 public static function changeableByGroup( $group ) {
4429 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4433 'remove' => array(),
4434 'add-self' => array(),
4435 'remove-self' => array()
4438 if ( empty( $wgAddGroups[$group] ) ) {
4439 // Don't add anything to $groups
4440 } elseif ( $wgAddGroups[$group] === true ) {
4441 // You get everything
4442 $groups['add'] = self
::getAllGroups();
4443 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4444 $groups['add'] = $wgAddGroups[$group];
4447 // Same thing for remove
4448 if ( empty( $wgRemoveGroups[$group] ) ) {
4449 } elseif ( $wgRemoveGroups[$group] === true ) {
4450 $groups['remove'] = self
::getAllGroups();
4451 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4452 $groups['remove'] = $wgRemoveGroups[$group];
4455 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4456 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4457 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4458 if ( is_int( $key ) ) {
4459 $wgGroupsAddToSelf['user'][] = $value;
4464 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4465 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4466 if ( is_int( $key ) ) {
4467 $wgGroupsRemoveFromSelf['user'][] = $value;
4472 // Now figure out what groups the user can add to him/herself
4473 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4474 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4475 // No idea WHY this would be used, but it's there
4476 $groups['add-self'] = User
::getAllGroups();
4477 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4478 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4481 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4482 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4483 $groups['remove-self'] = User
::getAllGroups();
4484 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4485 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4492 * Returns an array of groups that this user can add and remove
4493 * @return array Array( 'add' => array( addablegroups ),
4494 * 'remove' => array( removablegroups ),
4495 * 'add-self' => array( addablegroups to self),
4496 * 'remove-self' => array( removable groups from self) )
4498 public function changeableGroups() {
4499 if ( $this->isAllowed( 'userrights' ) ) {
4500 // This group gives the right to modify everything (reverse-
4501 // compatibility with old "userrights lets you change
4503 // Using array_merge to make the groups reindexed
4504 $all = array_merge( User
::getAllGroups() );
4508 'add-self' => array(),
4509 'remove-self' => array()
4513 // Okay, it's not so simple, we will have to go through the arrays
4516 'remove' => array(),
4517 'add-self' => array(),
4518 'remove-self' => array()
4520 $addergroups = $this->getEffectiveGroups();
4522 foreach ( $addergroups as $addergroup ) {
4523 $groups = array_merge_recursive(
4524 $groups, $this->changeableByGroup( $addergroup )
4526 $groups['add'] = array_unique( $groups['add'] );
4527 $groups['remove'] = array_unique( $groups['remove'] );
4528 $groups['add-self'] = array_unique( $groups['add-self'] );
4529 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4535 * Increment the user's edit-count field.
4536 * Will have no effect for anonymous users.
4538 public function incEditCount() {
4539 if ( !$this->isAnon() ) {
4540 $dbw = wfGetDB( DB_MASTER
);
4543 array( 'user_editcount=user_editcount+1' ),
4544 array( 'user_id' => $this->getId() ),
4548 // Lazy initialization check...
4549 if ( $dbw->affectedRows() == 0 ) {
4550 // Now here's a goddamn hack...
4551 $dbr = wfGetDB( DB_SLAVE
);
4552 if ( $dbr !== $dbw ) {
4553 // If we actually have a slave server, the count is
4554 // at least one behind because the current transaction
4555 // has not been committed and replicated.
4556 $this->initEditCount( 1 );
4558 // But if DB_SLAVE is selecting the master, then the
4559 // count we just read includes the revision that was
4560 // just added in the working transaction.
4561 $this->initEditCount();
4565 // edit count in user cache too
4566 $this->invalidateCache();
4570 * Initialize user_editcount from data out of the revision table
4572 * @param int $add Edits to add to the count from the revision table
4573 * @return int Number of edits
4575 protected function initEditCount( $add = 0 ) {
4576 // Pull from a slave to be less cruel to servers
4577 // Accuracy isn't the point anyway here
4578 $dbr = wfGetDB( DB_SLAVE
);
4579 $count = (int)$dbr->selectField(
4582 array( 'rev_user' => $this->getId() ),
4585 $count = $count +
$add;
4587 $dbw = wfGetDB( DB_MASTER
);
4590 array( 'user_editcount' => $count ),
4591 array( 'user_id' => $this->getId() ),
4599 * Get the description of a given right
4601 * @param string $right Right to query
4602 * @return string Localized description of the right
4604 public static function getRightDescription( $right ) {
4605 $key = "right-$right";
4606 $msg = wfMessage( $key );
4607 return $msg->isBlank() ?
$right : $msg->text();
4611 * Make a new-style password hash
4613 * @param string $password Plain-text password
4614 * @param bool|string $salt Optional salt, may be random or the user ID.
4615 * If unspecified or false, will generate one automatically
4616 * @return string Password hash
4617 * @deprecated since 1.23, use Password class
4619 public static function crypt( $password, $salt = false ) {
4620 wfDeprecated( __METHOD__
, '1.23' );
4621 $hash = self
::getPasswordFactory()->newFromPlaintext( $password );
4622 return $hash->toString();
4626 * Compare a password hash with a plain-text password. Requires the user
4627 * ID if there's a chance that the hash is an old-style hash.
4629 * @param string $hash Password hash
4630 * @param string $password Plain-text password to compare
4631 * @param string|bool $userId User ID for old-style password salt
4634 * @deprecated since 1.23, use Password class
4636 public static function comparePasswords( $hash, $password, $userId = false ) {
4637 wfDeprecated( __METHOD__
, '1.23' );
4639 // Check for *really* old password hashes that don't even have a type
4640 // The old hash format was just an md5 hex hash, with no type information
4641 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4642 global $wgPasswordSalt;
4643 if ( $wgPasswordSalt ) {
4644 $password = ":B:{$userId}:{$hash}";
4646 $password = ":A:{$hash}";
4650 $hash = self
::getPasswordFactory()->newFromCiphertext( $hash );
4651 return $hash->equals( $password );
4655 * Add a newuser log entry for this user.
4656 * Before 1.19 the return value was always true.
4658 * @param string|bool $action Account creation type.
4659 * - String, one of the following values:
4660 * - 'create' for an anonymous user creating an account for himself.
4661 * This will force the action's performer to be the created user itself,
4662 * no matter the value of $wgUser
4663 * - 'create2' for a logged in user creating an account for someone else
4664 * - 'byemail' when the created user will receive its password by e-mail
4665 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4666 * - Boolean means whether the account was created by e-mail (deprecated):
4667 * - true will be converted to 'byemail'
4668 * - false will be converted to 'create' if this object is the same as
4669 * $wgUser and to 'create2' otherwise
4671 * @param string $reason User supplied reason
4673 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4675 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4676 global $wgUser, $wgNewUserLog;
4677 if ( empty( $wgNewUserLog ) ) {
4678 return true; // disabled
4681 if ( $action === true ) {
4682 $action = 'byemail';
4683 } elseif ( $action === false ) {
4684 if ( $this->getName() == $wgUser->getName() ) {
4687 $action = 'create2';
4691 if ( $action === 'create' ||
$action === 'autocreate' ) {
4694 $performer = $wgUser;
4697 $logEntry = new ManualLogEntry( 'newusers', $action );
4698 $logEntry->setPerformer( $performer );
4699 $logEntry->setTarget( $this->getUserPage() );
4700 $logEntry->setComment( $reason );
4701 $logEntry->setParameters( array(
4702 '4::userid' => $this->getId(),
4704 $logid = $logEntry->insert();
4706 if ( $action !== 'autocreate' ) {
4707 $logEntry->publish( $logid );
4714 * Add an autocreate newuser log entry for this user
4715 * Used by things like CentralAuth and perhaps other authplugins.
4716 * Consider calling addNewUserLogEntry() directly instead.
4720 public function addNewUserLogEntryAutoCreate() {
4721 $this->addNewUserLogEntry( 'autocreate' );
4727 * Load the user options either from cache, the database or an array
4729 * @param array $data Rows for the current user out of the user_properties table
4731 protected function loadOptions( $data = null ) {
4736 if ( $this->mOptionsLoaded
) {
4740 $this->mOptions
= self
::getDefaultOptions();
4742 if ( !$this->getId() ) {
4743 // For unlogged-in users, load language/variant options from request.
4744 // There's no need to do it for logged-in users: they can set preferences,
4745 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4746 // so don't override user's choice (especially when the user chooses site default).
4747 $variant = $wgContLang->getDefaultVariant();
4748 $this->mOptions
['variant'] = $variant;
4749 $this->mOptions
['language'] = $variant;
4750 $this->mOptionsLoaded
= true;
4754 // Maybe load from the object
4755 if ( !is_null( $this->mOptionOverrides
) ) {
4756 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4757 foreach ( $this->mOptionOverrides
as $key => $value ) {
4758 $this->mOptions
[$key] = $value;
4761 if ( !is_array( $data ) ) {
4762 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4763 // Load from database
4764 $dbr = wfGetDB( DB_SLAVE
);
4766 $res = $dbr->select(
4768 array( 'up_property', 'up_value' ),
4769 array( 'up_user' => $this->getId() ),
4773 $this->mOptionOverrides
= array();
4775 foreach ( $res as $row ) {
4776 $data[$row->up_property
] = $row->up_value
;
4779 foreach ( $data as $property => $value ) {
4780 $this->mOptionOverrides
[$property] = $value;
4781 $this->mOptions
[$property] = $value;
4785 $this->mOptionsLoaded
= true;
4787 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
4791 * Saves the non-default options for this user, as previously set e.g. via
4792 * setOption(), in the database's "user_properties" (preferences) table.
4793 * Usually used via saveSettings().
4795 protected function saveOptions() {
4796 $this->loadOptions();
4798 // Not using getOptions(), to keep hidden preferences in database
4799 $saveOptions = $this->mOptions
;
4801 // Allow hooks to abort, for instance to save to a global profile.
4802 // Reset options to default state before saving.
4803 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4807 $userId = $this->getId();
4809 $insert_rows = array(); // all the new preference rows
4810 foreach ( $saveOptions as $key => $value ) {
4811 // Don't bother storing default values
4812 $defaultOption = self
::getDefaultOption( $key );
4813 if ( ( $defaultOption === null && $value !== false && $value !== null )
4814 ||
$value != $defaultOption
4816 $insert_rows[] = array(
4817 'up_user' => $userId,
4818 'up_property' => $key,
4819 'up_value' => $value,
4824 $dbw = wfGetDB( DB_MASTER
);
4826 $res = $dbw->select( 'user_properties',
4827 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
4829 // Find prior rows that need to be removed or updated. These rows will
4830 // all be deleted (the later so that INSERT IGNORE applies the new values).
4831 $keysDelete = array();
4832 foreach ( $res as $row ) {
4833 if ( !isset( $saveOptions[$row->up_property
] )
4834 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
4836 $keysDelete[] = $row->up_property
;
4840 if ( count( $keysDelete ) ) {
4841 // Do the DELETE by PRIMARY KEY for prior rows.
4842 // In the past a very large portion of calls to this function are for setting
4843 // 'rememberpassword' for new accounts (a preference that has since been removed).
4844 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4845 // caused gap locks on [max user ID,+infinity) which caused high contention since
4846 // updates would pile up on each other as they are for higher (newer) user IDs.
4847 // It might not be necessary these days, but it shouldn't hurt either.
4848 $dbw->delete( 'user_properties',
4849 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
4851 // Insert the new preference rows
4852 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
4856 * Lazily instantiate and return a factory object for making passwords
4858 * @return PasswordFactory
4860 public static function getPasswordFactory() {
4861 if ( self
::$mPasswordFactory === null ) {
4862 self
::$mPasswordFactory = new PasswordFactory();
4863 self
::$mPasswordFactory->init( RequestContext
::getMain()->getConfig() );
4866 return self
::$mPasswordFactory;
4870 * Provide an array of HTML5 attributes to put on an input element
4871 * intended for the user to enter a new password. This may include
4872 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4874 * Do *not* use this when asking the user to enter his current password!
4875 * Regardless of configuration, users may have invalid passwords for whatever
4876 * reason (e.g., they were set before requirements were tightened up).
4877 * Only use it when asking for a new password, like on account creation or
4880 * Obviously, you still need to do server-side checking.
4882 * NOTE: A combination of bugs in various browsers means that this function
4883 * actually just returns array() unconditionally at the moment. May as
4884 * well keep it around for when the browser bugs get fixed, though.
4886 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4888 * @return array Array of HTML attributes suitable for feeding to
4889 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4890 * That will get confused by the boolean attribute syntax used.)
4892 public static function passwordChangeInputAttribs() {
4893 global $wgMinimalPasswordLength;
4895 if ( $wgMinimalPasswordLength == 0 ) {
4899 # Note that the pattern requirement will always be satisfied if the
4900 # input is empty, so we need required in all cases.
4902 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4903 # if e-mail confirmation is being used. Since HTML5 input validation
4904 # is b0rked anyway in some browsers, just return nothing. When it's
4905 # re-enabled, fix this code to not output required for e-mail
4907 #$ret = array( 'required' );
4910 # We can't actually do this right now, because Opera 9.6 will print out
4911 # the entered password visibly in its error message! When other
4912 # browsers add support for this attribute, or Opera fixes its support,
4913 # we can add support with a version check to avoid doing this on Opera
4914 # versions where it will be a problem. Reported to Opera as
4915 # DSK-262266, but they don't have a public bug tracker for us to follow.
4917 if ( $wgMinimalPasswordLength > 1 ) {
4918 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4919 $ret['title'] = wfMessage( 'passwordtooshort' )
4920 ->numParams( $wgMinimalPasswordLength )->text();
4928 * Return the list of user fields that should be selected to create
4929 * a new user object.
4932 public static function selectFields() {
4940 'user_email_authenticated',
4942 'user_email_token_expires',
4943 'user_registration',
4949 * Factory function for fatal permission-denied errors
4952 * @param string $permission User right required
4955 static function newFatalPermissionDeniedStatus( $permission ) {
4958 $groups = array_map(
4959 array( 'User', 'makeGroupLinkWiki' ),
4960 User
::getGroupsWithPermission( $permission )
4964 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4966 return Status
::newFatal( 'badaccess-group0' );