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', 9 );
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 * Array of Strings List of member variables which are saved to the
75 * shared cache (memcached). Any operation which changes the
76 * corresponding database fields must call a cache-clearing function.
79 protected static $mCacheVars = array(
90 'mEmailAuthenticated',
98 // user_properties table
103 * Array of Strings Core rights.
104 * Each of these should have a corresponding message of the form
108 protected static $mCoreRights = array(
134 'editusercssjs', #deprecated
146 'move-categorypages',
147 'move-rootuserpages',
151 'override-export-depth',
175 'userrights-interwiki',
182 * String Cached results of getAllRights()
184 protected static $mAllRights = false;
186 /** @name Cache variables */
196 public $mNewpassword;
198 public $mNewpassTime;
206 public $mEmailAuthenticated;
208 protected $mEmailToken;
210 protected $mEmailTokenExpires;
212 protected $mRegistration;
214 protected $mEditCount;
218 protected $mOptionOverrides;
220 protected $mPasswordExpires;
224 * Bool Whether the cache variables have been loaded.
227 public $mOptionsLoaded;
230 * Array with already loaded items or true if all items have been loaded.
232 protected $mLoadedItems = array();
236 * String Initialization data source if mLoadedItems!==true. May be one of:
237 * - 'defaults' anonymous user initialised from class defaults
238 * - 'name' initialise from mName
239 * - 'id' initialise from mId
240 * - 'session' log in from cookies or session if possible
242 * Use the User::newFrom*() family of functions to set this.
247 * Lazy-initialized variables, invalidated with clearInstanceCache
251 protected $mDatePreference;
259 protected $mBlockreason;
261 protected $mEffectiveGroups;
263 protected $mImplicitGroups;
265 protected $mFormerGroups;
267 protected $mBlockedGlobally;
284 protected $mAllowUsertalk;
287 private $mBlockedFromCreateAccount = false;
290 private $mWatchedItems = array();
292 public static $idCacheByName = array();
295 * Lightweight constructor for an anonymous user.
296 * Use the User::newFrom* factory functions for other kinds of users.
300 * @see newFromConfirmationCode()
301 * @see newFromSession()
304 public function __construct() {
305 $this->clearInstanceCache( 'defaults' );
311 public function __toString() {
312 return $this->getName();
316 * Load the user table data for this object from the source given by mFrom.
318 public function load() {
319 if ( $this->mLoadedItems
=== true ) {
322 wfProfileIn( __METHOD__
);
324 // Set it now to avoid infinite recursion in accessors
325 $this->mLoadedItems
= true;
327 switch ( $this->mFrom
) {
329 $this->loadDefaults();
332 $this->mId
= self
::idFromName( $this->mName
);
334 // Nonexistent user placeholder object
335 $this->loadDefaults( $this->mName
);
344 if ( !$this->loadFromSession() ) {
345 // Loading from session failed. Load defaults.
346 $this->loadDefaults();
348 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
351 wfProfileOut( __METHOD__
);
352 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
354 wfProfileOut( __METHOD__
);
358 * Load user table data, given mId has already been set.
359 * @return bool false if the ID does not exist, true otherwise
361 public function loadFromId() {
363 if ( $this->mId
== 0 ) {
364 $this->loadDefaults();
369 $key = wfMemcKey( 'user', 'id', $this->mId
);
370 $data = $wgMemc->get( $key );
371 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
372 // Object is expired, load from DB
377 wfDebug( "User: cache miss for user {$this->mId}\n" );
379 if ( !$this->loadFromDatabase() ) {
380 // Can't load from ID, user is anonymous
383 $this->saveToCache();
385 wfDebug( "User: got user {$this->mId} from cache\n" );
386 // Restore from cache
387 foreach ( self
::$mCacheVars as $name ) {
388 $this->$name = $data[$name];
392 $this->mLoadedItems
= true;
398 * Save user data to the shared cache
400 public function saveToCache() {
403 $this->loadOptions();
404 if ( $this->isAnon() ) {
405 // Anonymous users are uncached
409 foreach ( self
::$mCacheVars as $name ) {
410 $data[$name] = $this->$name;
412 $data['mVersion'] = MW_USER_VERSION
;
413 $key = wfMemcKey( 'user', 'id', $this->mId
);
415 $wgMemc->set( $key, $data );
418 /** @name newFrom*() static factory methods */
422 * Static factory method for creation from username.
424 * This is slightly less efficient than newFromId(), so use newFromId() if
425 * you have both an ID and a name handy.
427 * @param string $name Username, validated by Title::newFromText()
428 * @param string|bool $validate Validate username. Takes the same parameters as
429 * User::getCanonicalName(), except that true is accepted as an alias
430 * for 'valid', for BC.
432 * @return User|bool User object, or false if the username is invalid
433 * (e.g. if it contains illegal characters or is an IP address). If the
434 * username is not present in the database, the result will be a user object
435 * with a name, zero user ID and default settings.
437 public static function newFromName( $name, $validate = 'valid' ) {
438 if ( $validate === true ) {
441 $name = self
::getCanonicalName( $name, $validate );
442 if ( $name === false ) {
445 // Create unloaded user object
449 $u->setItemLoaded( 'name' );
455 * Static factory method for creation from a given user ID.
457 * @param int $id Valid user ID
458 * @return User The corresponding User object
460 public static function newFromId( $id ) {
464 $u->setItemLoaded( 'id' );
469 * Factory method to fetch whichever user has a given email confirmation code.
470 * This code is generated when an account is created or its e-mail address
473 * If the code is invalid or has expired, returns NULL.
475 * @param string $code Confirmation code
478 public static function newFromConfirmationCode( $code ) {
479 $dbr = wfGetDB( DB_SLAVE
);
480 $id = $dbr->selectField( 'user', 'user_id', array(
481 'user_email_token' => md5( $code ),
482 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
484 if ( $id !== false ) {
485 return User
::newFromId( $id );
492 * Create a new user object using data from session or cookies. If the
493 * login credentials are invalid, the result is an anonymous user.
495 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
498 public static function newFromSession( WebRequest
$request = null ) {
500 $user->mFrom
= 'session';
501 $user->mRequest
= $request;
506 * Create a new user object from a user row.
507 * The row should have the following fields from the user table in it:
508 * - either user_name or user_id to load further data if needed (or both)
510 * - all other fields (email, password, etc.)
511 * It is useless to provide the remaining fields if either user_id,
512 * user_name and user_real_name are not provided because the whole row
513 * will be loaded once more from the database when accessing them.
515 * @param stdClass $row A row from the user table
516 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
519 public static function newFromRow( $row, $data = null ) {
521 $user->loadFromRow( $row, $data );
528 * Get the username corresponding to a given user ID
529 * @param int $id User ID
530 * @return string|bool The corresponding username
532 public static function whoIs( $id ) {
533 return UserCache
::singleton()->getProp( $id, 'name' );
537 * Get the real name of a user given their user ID
539 * @param int $id User ID
540 * @return string|bool The corresponding user's real name
542 public static function whoIsReal( $id ) {
543 return UserCache
::singleton()->getProp( $id, 'real_name' );
547 * Get database id given a user name
548 * @param string $name Username
549 * @return int|null The corresponding user's ID, or null if user is nonexistent
551 public static function idFromName( $name ) {
552 $nt = Title
::makeTitleSafe( NS_USER
, $name );
553 if ( is_null( $nt ) ) {
558 if ( isset( self
::$idCacheByName[$name] ) ) {
559 return self
::$idCacheByName[$name];
562 $dbr = wfGetDB( DB_SLAVE
);
563 $s = $dbr->selectRow(
566 array( 'user_name' => $nt->getText() ),
570 if ( $s === false ) {
573 $result = $s->user_id
;
576 self
::$idCacheByName[$name] = $result;
578 if ( count( self
::$idCacheByName ) > 1000 ) {
579 self
::$idCacheByName = array();
586 * Reset the cache used in idFromName(). For use in tests.
588 public static function resetIdByNameCache() {
589 self
::$idCacheByName = array();
593 * Does the string match an anonymous IPv4 address?
595 * This function exists for username validation, in order to reject
596 * usernames which are similar in form to IP addresses. Strings such
597 * as 300.300.300.300 will return true because it looks like an IP
598 * address, despite not being strictly valid.
600 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
601 * address because the usemod software would "cloak" anonymous IP
602 * addresses like this, if we allowed accounts like this to be created
603 * new users could get the old edits of these anonymous users.
605 * @param string $name Name to match
608 public static function isIP( $name ) {
609 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
610 || IP
::isIPv6( $name );
614 * Is the input a valid username?
616 * Checks if the input is a valid username, we don't want an empty string,
617 * an IP address, anything that contains slashes (would mess up subpages),
618 * is longer than the maximum allowed username size or doesn't begin with
621 * @param string $name Name to match
624 public static function isValidUserName( $name ) {
625 global $wgContLang, $wgMaxNameChars;
628 || User
::isIP( $name )
629 ||
strpos( $name, '/' ) !== false
630 ||
strlen( $name ) > $wgMaxNameChars
631 ||
$name != $wgContLang->ucfirst( $name ) ) {
632 wfDebugLog( 'username', __METHOD__
.
633 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
637 // Ensure that the name can't be misresolved as a different title,
638 // such as with extra namespace keys at the start.
639 $parsed = Title
::newFromText( $name );
640 if ( is_null( $parsed )
641 ||
$parsed->getNamespace()
642 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
643 wfDebugLog( 'username', __METHOD__
.
644 ": '$name' invalid due to ambiguous prefixes" );
648 // Check an additional blacklist of troublemaker characters.
649 // Should these be merged into the title char list?
650 $unicodeBlacklist = '/[' .
651 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
652 '\x{00a0}' . # non-breaking space
653 '\x{2000}-\x{200f}' . # various whitespace
654 '\x{2028}-\x{202f}' . # breaks and control chars
655 '\x{3000}' . # ideographic space
656 '\x{e000}-\x{f8ff}' . # private use
658 if ( preg_match( $unicodeBlacklist, $name ) ) {
659 wfDebugLog( 'username', __METHOD__
.
660 ": '$name' invalid due to blacklisted characters" );
668 * Usernames which fail to pass this function will be blocked
669 * from user login and new account registrations, but may be used
670 * internally by batch processes.
672 * If an account already exists in this form, login will be blocked
673 * by a failure to pass this function.
675 * @param string $name Name to match
678 public static function isUsableName( $name ) {
679 global $wgReservedUsernames;
680 // Must be a valid username, obviously ;)
681 if ( !self
::isValidUserName( $name ) ) {
685 static $reservedUsernames = false;
686 if ( !$reservedUsernames ) {
687 $reservedUsernames = $wgReservedUsernames;
688 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
691 // Certain names may be reserved for batch processes.
692 foreach ( $reservedUsernames as $reserved ) {
693 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
694 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
696 if ( $reserved == $name ) {
704 * Usernames which fail to pass this function will be blocked
705 * from new account registrations, but may be used internally
706 * either by batch processes or by user accounts which have
707 * already been created.
709 * Additional blacklisting may be added here rather than in
710 * isValidUserName() to avoid disrupting existing accounts.
712 * @param string $name String to match
715 public static function isCreatableName( $name ) {
716 global $wgInvalidUsernameCharacters;
718 // Ensure that the username isn't longer than 235 bytes, so that
719 // (at least for the builtin skins) user javascript and css files
720 // will work. (bug 23080)
721 if ( strlen( $name ) > 235 ) {
722 wfDebugLog( 'username', __METHOD__
.
723 ": '$name' invalid due to length" );
727 // Preg yells if you try to give it an empty string
728 if ( $wgInvalidUsernameCharacters !== '' ) {
729 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
730 wfDebugLog( 'username', __METHOD__
.
731 ": '$name' invalid due to wgInvalidUsernameCharacters" );
736 return self
::isUsableName( $name );
740 * Is the input a valid password for this user?
742 * @param string $password Desired password
745 public function isValidPassword( $password ) {
746 //simple boolean wrapper for getPasswordValidity
747 return $this->getPasswordValidity( $password ) === true;
752 * Given unvalidated password input, return error message on failure.
754 * @param string $password Desired password
755 * @return bool|string|array true on success, string or array of error message on failure
757 public function getPasswordValidity( $password ) {
758 $result = $this->checkPasswordValidity( $password );
759 if ( $result->isGood() ) {
763 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
764 $messages[] = $error['message'];
766 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
767 $messages[] = $warning['message'];
769 if ( count( $messages ) === 1 ) {
777 * Check if this is a valid password for this user. Status will be good if
778 * the password is valid, or have an array of error messages if not.
780 * @param string $password Desired password
784 public function checkPasswordValidity( $password ) {
785 global $wgMinimalPasswordLength, $wgContLang;
787 static $blockedLogins = array(
788 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
789 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
792 $status = Status
::newGood();
794 $result = false; //init $result to false for the internal checks
796 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
797 $status->error( $result );
801 if ( $result === false ) {
802 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
803 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
805 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
806 $status->error( 'password-name-match' );
808 } elseif ( isset( $blockedLogins[$this->getName()] )
809 && $password == $blockedLogins[$this->getName()]
811 $status->error( 'password-login-forbidden' );
814 //it seems weird returning a Good status here, but this is because of the
815 //initialization of $result to false above. If the hook is never run or it
816 //doesn't modify $result, then we will likely get down into this if with
820 } elseif ( $result === true ) {
823 $status->error( $result );
824 return $status; //the isValidPassword hook set a string $result and returned true
829 * Expire a user's password
831 * @param int $ts Optional timestamp to convert, default 0 for the current time
833 public function expirePassword( $ts = 0 ) {
835 $timestamp = wfTimestamp( TS_MW
, $ts );
836 $this->mPasswordExpires
= $timestamp;
837 $this->saveSettings();
841 * Clear the password expiration for a user
843 * @param bool $load Ensure user object is loaded first
845 public function resetPasswordExpiration( $load = true ) {
846 global $wgPasswordExpirationDays;
851 if ( $wgPasswordExpirationDays ) {
852 $newExpire = wfTimestamp(
854 time() +
( $wgPasswordExpirationDays * 24 * 3600 )
857 // Give extensions a chance to force an expiration
858 wfRunHooks( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
859 $this->mPasswordExpires
= $newExpire;
863 * Check if the user's password is expired.
864 * TODO: Put this and password length into a PasswordPolicy object
866 * @return string|bool The expiration type, or false if not expired
867 * hard: A password change is required to login
868 * soft: Allow login, but encourage password change
869 * false: Password is not expired
871 public function getPasswordExpired() {
872 global $wgPasswordExpireGrace;
874 $now = wfTimestamp();
875 $expiration = $this->getPasswordExpireDate();
876 $expUnix = wfTimestamp( TS_UNIX
, $expiration );
877 if ( $expiration !== null && $expUnix < $now ) {
878 $expired = ( $expUnix +
$wgPasswordExpireGrace < $now ) ?
'hard' : 'soft';
884 * Get this user's password expiration date. Since this may be using
885 * the cached User object, we assume that whatever mechanism is setting
886 * the expiration date is also expiring the User cache.
888 * @return string|bool The datestamp of the expiration, or null if not set
890 public function getPasswordExpireDate() {
892 return $this->mPasswordExpires
;
896 * Given unvalidated user input, return a canonical username, or false if
897 * the username is invalid.
898 * @param string $name User input
899 * @param string|bool $validate Type of validation to use:
900 * - false No validation
901 * - 'valid' Valid for batch processes
902 * - 'usable' Valid for batch processes and login
903 * - 'creatable' Valid for batch processes, login and account creation
905 * @throws MWException
906 * @return bool|string
908 public static function getCanonicalName( $name, $validate = 'valid' ) {
909 // Force usernames to capital
911 $name = $wgContLang->ucfirst( $name );
913 # Reject names containing '#'; these will be cleaned up
914 # with title normalisation, but then it's too late to
916 if ( strpos( $name, '#' ) !== false ) {
920 // Clean up name according to title rules
921 $t = ( $validate === 'valid' ) ?
922 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
923 // Check for invalid titles
924 if ( is_null( $t ) ) {
928 // Reject various classes of invalid names
930 $name = $wgAuth->getCanonicalName( $t->getText() );
932 switch ( $validate ) {
936 if ( !User
::isValidUserName( $name ) ) {
941 if ( !User
::isUsableName( $name ) ) {
946 if ( !User
::isCreatableName( $name ) ) {
951 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
957 * Count the number of edits of a user
959 * @param int $uid User ID to check
960 * @return int The user's edit count
962 * @deprecated since 1.21 in favour of User::getEditCount
964 public static function edits( $uid ) {
965 wfDeprecated( __METHOD__
, '1.21' );
966 $user = self
::newFromId( $uid );
967 return $user->getEditCount();
971 * Return a random password.
973 * @return string New random password
975 public static function randomPassword() {
976 global $wgMinimalPasswordLength;
977 // Decide the final password length based on our min password length,
978 // stopping at a minimum of 10 chars.
979 $length = max( 10, $wgMinimalPasswordLength );
980 // Multiply by 1.25 to get the number of hex characters we need
981 $length = $length * 1.25;
982 // Generate random hex chars
983 $hex = MWCryptRand
::generateHex( $length );
984 // Convert from base 16 to base 32 to get a proper password like string
985 return wfBaseConvert( $hex, 16, 32 );
989 * Set cached properties to default.
991 * @note This no longer clears uncached lazy-initialised properties;
992 * the constructor does that instead.
994 * @param string|bool $name
996 public function loadDefaults( $name = false ) {
997 wfProfileIn( __METHOD__
);
1000 $this->mName
= $name;
1001 $this->mRealName
= '';
1002 $this->mPassword
= $this->mNewpassword
= '';
1003 $this->mNewpassTime
= null;
1005 $this->mOptionOverrides
= null;
1006 $this->mOptionsLoaded
= false;
1008 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1009 if ( $loggedOut !== null ) {
1010 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1012 $this->mTouched
= '1'; # Allow any pages to be cached
1015 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1016 $this->mEmailAuthenticated
= null;
1017 $this->mEmailToken
= '';
1018 $this->mEmailTokenExpires
= null;
1019 $this->mPasswordExpires
= null;
1020 $this->resetPasswordExpiration( false );
1021 $this->mRegistration
= wfTimestamp( TS_MW
);
1022 $this->mGroups
= array();
1024 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
1026 wfProfileOut( __METHOD__
);
1030 * Return whether an item has been loaded.
1032 * @param string $item Item to check. Current possibilities:
1036 * @param string $all 'all' to check if the whole object has been loaded
1037 * or any other string to check if only the item is available (e.g.
1041 public function isItemLoaded( $item, $all = 'all' ) {
1042 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1043 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1047 * Set that an item has been loaded
1049 * @param string $item
1051 protected function setItemLoaded( $item ) {
1052 if ( is_array( $this->mLoadedItems
) ) {
1053 $this->mLoadedItems
[$item] = true;
1058 * Load user data from the session or login cookie.
1059 * @return bool True if the user is logged in, false otherwise.
1061 private function loadFromSession() {
1063 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
1064 if ( $result !== null ) {
1068 $request = $this->getRequest();
1070 $cookieId = $request->getCookie( 'UserID' );
1071 $sessId = $request->getSessionData( 'wsUserID' );
1073 if ( $cookieId !== null ) {
1074 $sId = intval( $cookieId );
1075 if ( $sessId !== null && $cookieId != $sessId ) {
1076 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1077 cookie user ID ($sId) don't match!" );
1080 $request->setSessionData( 'wsUserID', $sId );
1081 } elseif ( $sessId !== null && $sessId != 0 ) {
1087 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1088 $sName = $request->getSessionData( 'wsUserName' );
1089 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1090 $sName = $request->getCookie( 'UserName' );
1091 $request->setSessionData( 'wsUserName', $sName );
1096 $proposedUser = User
::newFromId( $sId );
1097 if ( !$proposedUser->isLoggedIn() ) {
1102 global $wgBlockDisablesLogin;
1103 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1104 // User blocked and we've disabled blocked user logins
1108 if ( $request->getSessionData( 'wsToken' ) ) {
1110 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1112 } elseif ( $request->getCookie( 'Token' ) ) {
1113 # Get the token from DB/cache and clean it up to remove garbage padding.
1114 # This deals with historical problems with bugs and the default column value.
1115 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1116 // Make comparison in constant time (bug 61346)
1117 $passwordCorrect = strlen( $token )
1118 && hash_equals( $token, $request->getCookie( 'Token' ) );
1121 // No session or persistent login cookie
1125 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1126 $this->loadFromUserObject( $proposedUser );
1127 $request->setSessionData( 'wsToken', $this->mToken
);
1128 wfDebug( "User: logged in from $from\n" );
1131 // Invalid credentials
1132 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1138 * Load user and user_group data from the database.
1139 * $this->mId must be set, this is how the user is identified.
1141 * @param integer $flags Supports User::READ_LOCKING
1142 * @return bool True if the user exists, false if the user is anonymous
1144 public function loadFromDatabase( $flags = 0 ) {
1146 $this->mId
= intval( $this->mId
);
1149 if ( !$this->mId
) {
1150 $this->loadDefaults();
1154 $dbr = wfGetDB( DB_MASTER
);
1155 $s = $dbr->selectRow(
1157 self
::selectFields(),
1158 array( 'user_id' => $this->mId
),
1160 ( $flags & self
::READ_LOCKING
== self
::READ_LOCKING
)
1161 ?
array( 'LOCK IN SHARE MODE' )
1165 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1167 if ( $s !== false ) {
1168 // Initialise user table data
1169 $this->loadFromRow( $s );
1170 $this->mGroups
= null; // deferred
1171 $this->getEditCount(); // revalidation for nulls
1176 $this->loadDefaults();
1182 * Initialize this object from a row from the user table.
1184 * @param stdClass $row Row from the user table to load.
1185 * @param array $data Further user data to load into the object
1187 * user_groups Array with groups out of the user_groups table
1188 * user_properties Array with properties out of the user_properties table
1190 public function loadFromRow( $row, $data = null ) {
1193 $this->mGroups
= null; // deferred
1195 if ( isset( $row->user_name
) ) {
1196 $this->mName
= $row->user_name
;
1197 $this->mFrom
= 'name';
1198 $this->setItemLoaded( 'name' );
1203 if ( isset( $row->user_real_name
) ) {
1204 $this->mRealName
= $row->user_real_name
;
1205 $this->setItemLoaded( 'realname' );
1210 if ( isset( $row->user_id
) ) {
1211 $this->mId
= intval( $row->user_id
);
1212 $this->mFrom
= 'id';
1213 $this->setItemLoaded( 'id' );
1218 if ( isset( $row->user_editcount
) ) {
1219 $this->mEditCount
= $row->user_editcount
;
1224 if ( isset( $row->user_password
) ) {
1225 $this->mPassword
= $row->user_password
;
1226 $this->mNewpassword
= $row->user_newpassword
;
1227 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1228 $this->mEmail
= $row->user_email
;
1229 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1230 $this->mToken
= $row->user_token
;
1231 if ( $this->mToken
== '' ) {
1232 $this->mToken
= null;
1234 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1235 $this->mEmailToken
= $row->user_email_token
;
1236 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1237 $this->mPasswordExpires
= wfTimestampOrNull( TS_MW
, $row->user_password_expires
);
1238 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1244 $this->mLoadedItems
= true;
1247 if ( is_array( $data ) ) {
1248 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1249 $this->mGroups
= $data['user_groups'];
1251 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1252 $this->loadOptions( $data['user_properties'] );
1258 * Load the data for this user object from another user object.
1262 protected function loadFromUserObject( $user ) {
1264 $user->loadGroups();
1265 $user->loadOptions();
1266 foreach ( self
::$mCacheVars as $var ) {
1267 $this->$var = $user->$var;
1272 * Load the groups from the database if they aren't already loaded.
1274 private function loadGroups() {
1275 if ( is_null( $this->mGroups
) ) {
1276 $dbr = wfGetDB( DB_MASTER
);
1277 $res = $dbr->select( 'user_groups',
1278 array( 'ug_group' ),
1279 array( 'ug_user' => $this->mId
),
1281 $this->mGroups
= array();
1282 foreach ( $res as $row ) {
1283 $this->mGroups
[] = $row->ug_group
;
1289 * Add the user to the group if he/she meets given criteria.
1291 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1292 * possible to remove manually via Special:UserRights. In such case it
1293 * will not be re-added automatically. The user will also not lose the
1294 * group if they no longer meet the criteria.
1296 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1298 * @return array Array of groups the user has been promoted to.
1300 * @see $wgAutopromoteOnce
1302 public function addAutopromoteOnceGroups( $event ) {
1303 global $wgAutopromoteOnceLogInRC, $wgAuth;
1305 $toPromote = array();
1306 if ( $this->getId() ) {
1307 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1308 if ( count( $toPromote ) ) {
1309 $oldGroups = $this->getGroups(); // previous groups
1311 foreach ( $toPromote as $group ) {
1312 $this->addGroup( $group );
1314 // update groups in external authentication database
1315 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1317 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1319 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1320 $logEntry->setPerformer( $this );
1321 $logEntry->setTarget( $this->getUserPage() );
1322 $logEntry->setParameters( array(
1323 '4::oldgroups' => $oldGroups,
1324 '5::newgroups' => $newGroups,
1326 $logid = $logEntry->insert();
1327 if ( $wgAutopromoteOnceLogInRC ) {
1328 $logEntry->publish( $logid );
1336 * Clear various cached data stored in this object. The cache of the user table
1337 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1339 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1340 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1342 public function clearInstanceCache( $reloadFrom = false ) {
1343 $this->mNewtalk
= -1;
1344 $this->mDatePreference
= null;
1345 $this->mBlockedby
= -1; # Unset
1346 $this->mHash
= false;
1347 $this->mRights
= null;
1348 $this->mEffectiveGroups
= null;
1349 $this->mImplicitGroups
= null;
1350 $this->mGroups
= null;
1351 $this->mOptions
= null;
1352 $this->mOptionsLoaded
= false;
1353 $this->mEditCount
= null;
1355 if ( $reloadFrom ) {
1356 $this->mLoadedItems
= array();
1357 $this->mFrom
= $reloadFrom;
1362 * Combine the language default options with any site-specific options
1363 * and add the default language variants.
1365 * @return array Array of String options
1367 public static function getDefaultOptions() {
1368 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1370 static $defOpt = null;
1371 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1372 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1373 // mid-request and see that change reflected in the return value of this function.
1374 // Which is insane and would never happen during normal MW operation
1378 $defOpt = $wgDefaultUserOptions;
1379 // Default language setting
1380 $defOpt['language'] = $wgContLang->getCode();
1381 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1382 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1384 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1385 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1387 $defOpt['skin'] = $wgDefaultSkin;
1389 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1395 * Get a given default option value.
1397 * @param string $opt Name of option to retrieve
1398 * @return string Default option value
1400 public static function getDefaultOption( $opt ) {
1401 $defOpts = self
::getDefaultOptions();
1402 if ( isset( $defOpts[$opt] ) ) {
1403 return $defOpts[$opt];
1410 * Get blocking information
1411 * @param bool $bFromSlave Whether to check the slave database first.
1412 * To improve performance, non-critical checks are done against slaves.
1413 * Check when actually saving should be done against master.
1415 private function getBlockedStatus( $bFromSlave = true ) {
1416 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1418 if ( -1 != $this->mBlockedby
) {
1422 wfProfileIn( __METHOD__
);
1423 wfDebug( __METHOD__
. ": checking...\n" );
1425 // Initialize data...
1426 // Otherwise something ends up stomping on $this->mBlockedby when
1427 // things get lazy-loaded later, causing false positive block hits
1428 // due to -1 !== 0. Probably session-related... Nothing should be
1429 // overwriting mBlockedby, surely?
1432 # We only need to worry about passing the IP address to the Block generator if the
1433 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1434 # know which IP address they're actually coming from
1435 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1436 $ip = $this->getRequest()->getIP();
1442 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1445 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1446 && !in_array( $ip, $wgProxyWhitelist )
1449 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1451 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1452 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1453 $block->setTarget( $ip );
1454 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1456 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1457 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1458 $block->setTarget( $ip );
1462 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1463 if ( !$block instanceof Block
1464 && $wgApplyIpBlocksToXff
1466 && !$this->isAllowed( 'proxyunbannable' )
1467 && !in_array( $ip, $wgProxyWhitelist )
1469 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1470 $xff = array_map( 'trim', explode( ',', $xff ) );
1471 $xff = array_diff( $xff, array( $ip ) );
1472 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1473 $block = Block
::chooseBlock( $xffblocks, $xff );
1474 if ( $block instanceof Block
) {
1475 # Mangle the reason to alert the user that the block
1476 # originated from matching the X-Forwarded-For header.
1477 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1481 if ( $block instanceof Block
) {
1482 wfDebug( __METHOD__
. ": Found block.\n" );
1483 $this->mBlock
= $block;
1484 $this->mBlockedby
= $block->getByName();
1485 $this->mBlockreason
= $block->mReason
;
1486 $this->mHideName
= $block->mHideName
;
1487 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1489 $this->mBlockedby
= '';
1490 $this->mHideName
= 0;
1491 $this->mAllowUsertalk
= false;
1495 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1497 wfProfileOut( __METHOD__
);
1501 * Whether the given IP is in a DNS blacklist.
1503 * @param string $ip IP to check
1504 * @param bool $checkWhitelist Whether to check the whitelist first
1505 * @return bool True if blacklisted.
1507 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1508 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1510 if ( !$wgEnableDnsBlacklist ) {
1514 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1518 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1522 * Whether the given IP is in a given DNS blacklist.
1524 * @param string $ip IP to check
1525 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1526 * @return bool True if blacklisted.
1528 public function inDnsBlacklist( $ip, $bases ) {
1529 wfProfileIn( __METHOD__
);
1532 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1533 if ( IP
::isIPv4( $ip ) ) {
1534 // Reverse IP, bug 21255
1535 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1537 foreach ( (array)$bases as $base ) {
1539 // If we have an access key, use that too (ProjectHoneypot, etc.)
1540 if ( is_array( $base ) ) {
1541 if ( count( $base ) >= 2 ) {
1542 // Access key is 1, base URL is 0
1543 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1545 $host = "$ipReversed.{$base[0]}";
1548 $host = "$ipReversed.$base";
1552 $ipList = gethostbynamel( $host );
1555 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1559 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1564 wfProfileOut( __METHOD__
);
1569 * Check if an IP address is in the local proxy list
1575 public static function isLocallyBlockedProxy( $ip ) {
1576 global $wgProxyList;
1578 if ( !$wgProxyList ) {
1581 wfProfileIn( __METHOD__
);
1583 if ( !is_array( $wgProxyList ) ) {
1584 // Load from the specified file
1585 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1588 if ( !is_array( $wgProxyList ) ) {
1590 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1592 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1593 // Old-style flipped proxy list
1598 wfProfileOut( __METHOD__
);
1603 * Is this user subject to rate limiting?
1605 * @return bool True if rate limited
1607 public function isPingLimitable() {
1608 global $wgRateLimitsExcludedIPs;
1609 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1610 // No other good way currently to disable rate limits
1611 // for specific IPs. :P
1612 // But this is a crappy hack and should die.
1615 return !$this->isAllowed( 'noratelimit' );
1619 * Primitive rate limits: enforce maximum actions per time period
1620 * to put a brake on flooding.
1622 * The method generates both a generic profiling point and a per action one
1623 * (suffix being "-$action".
1625 * @note When using a shared cache like memcached, IP-address
1626 * last-hit counters will be shared across wikis.
1628 * @param string $action Action to enforce; 'edit' if unspecified
1629 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1630 * @return bool True if a rate limiter was tripped
1632 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1633 // Call the 'PingLimiter' hook
1635 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1639 global $wgRateLimits;
1640 if ( !isset( $wgRateLimits[$action] ) ) {
1644 // Some groups shouldn't trigger the ping limiter, ever
1645 if ( !$this->isPingLimitable() ) {
1650 wfProfileIn( __METHOD__
);
1651 wfProfileIn( __METHOD__
. '-' . $action );
1653 $limits = $wgRateLimits[$action];
1655 $id = $this->getId();
1658 if ( isset( $limits['anon'] ) && $id == 0 ) {
1659 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1662 if ( isset( $limits['user'] ) && $id != 0 ) {
1663 $userLimit = $limits['user'];
1665 if ( $this->isNewbie() ) {
1666 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1667 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1669 if ( isset( $limits['ip'] ) ) {
1670 $ip = $this->getRequest()->getIP();
1671 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1673 if ( isset( $limits['subnet'] ) ) {
1674 $ip = $this->getRequest()->getIP();
1677 if ( IP
::isIPv6( $ip ) ) {
1678 $parts = IP
::parseRange( "$ip/64" );
1679 $subnet = $parts[0];
1680 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1682 $subnet = $matches[1];
1684 if ( $subnet !== false ) {
1685 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1689 // Check for group-specific permissions
1690 // If more than one group applies, use the group with the highest limit
1691 foreach ( $this->getGroups() as $group ) {
1692 if ( isset( $limits[$group] ) ) {
1693 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1694 $userLimit = $limits[$group];
1698 // Set the user limit key
1699 if ( $userLimit !== false ) {
1700 list( $max, $period ) = $userLimit;
1701 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1702 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1706 foreach ( $keys as $key => $limit ) {
1707 list( $max, $period ) = $limit;
1708 $summary = "(limit $max in {$period}s)";
1709 $count = $wgMemc->get( $key );
1712 if ( $count >= $max ) {
1713 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1714 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1717 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1720 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1721 if ( $incrBy > 0 ) {
1722 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1725 if ( $incrBy > 0 ) {
1726 $wgMemc->incr( $key, $incrBy );
1730 wfProfileOut( __METHOD__
. '-' . $action );
1731 wfProfileOut( __METHOD__
);
1736 * Check if user is blocked
1738 * @param bool $bFromSlave Whether to check the slave database instead of
1739 * the master. Hacked from false due to horrible probs on site.
1740 * @return bool True if blocked, false otherwise
1742 public function isBlocked( $bFromSlave = true ) {
1743 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1747 * Get the block affecting the user, or null if the user is not blocked
1749 * @param bool $bFromSlave Whether to check the slave database instead of the master
1750 * @return Block|null
1752 public function getBlock( $bFromSlave = true ) {
1753 $this->getBlockedStatus( $bFromSlave );
1754 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1758 * Check if user is blocked from editing a particular article
1760 * @param Title $title Title to check
1761 * @param bool $bFromSlave Whether to check the slave database instead of the master
1764 public function isBlockedFrom( $title, $bFromSlave = false ) {
1765 global $wgBlockAllowsUTEdit;
1766 wfProfileIn( __METHOD__
);
1768 $blocked = $this->isBlocked( $bFromSlave );
1769 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1770 // If a user's name is suppressed, they cannot make edits anywhere
1771 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1772 && $title->getNamespace() == NS_USER_TALK
) {
1774 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1777 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1779 wfProfileOut( __METHOD__
);
1784 * If user is blocked, return the name of the user who placed the block
1785 * @return string Name of blocker
1787 public function blockedBy() {
1788 $this->getBlockedStatus();
1789 return $this->mBlockedby
;
1793 * If user is blocked, return the specified reason for the block
1794 * @return string Blocking reason
1796 public function blockedFor() {
1797 $this->getBlockedStatus();
1798 return $this->mBlockreason
;
1802 * If user is blocked, return the ID for the block
1803 * @return int Block ID
1805 public function getBlockId() {
1806 $this->getBlockedStatus();
1807 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1811 * Check if user is blocked on all wikis.
1812 * Do not use for actual edit permission checks!
1813 * This is intended for quick UI checks.
1815 * @param string $ip IP address, uses current client if none given
1816 * @return bool True if blocked, false otherwise
1818 public function isBlockedGlobally( $ip = '' ) {
1819 if ( $this->mBlockedGlobally
!== null ) {
1820 return $this->mBlockedGlobally
;
1822 // User is already an IP?
1823 if ( IP
::isIPAddress( $this->getName() ) ) {
1824 $ip = $this->getName();
1826 $ip = $this->getRequest()->getIP();
1829 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1830 $this->mBlockedGlobally
= (bool)$blocked;
1831 return $this->mBlockedGlobally
;
1835 * Check if user account is locked
1837 * @return bool True if locked, false otherwise
1839 public function isLocked() {
1840 if ( $this->mLocked
!== null ) {
1841 return $this->mLocked
;
1844 StubObject
::unstub( $wgAuth );
1845 $authUser = $wgAuth->getUserInstance( $this );
1846 $this->mLocked
= (bool)$authUser->isLocked();
1847 return $this->mLocked
;
1851 * Check if user account is hidden
1853 * @return bool True if hidden, false otherwise
1855 public function isHidden() {
1856 if ( $this->mHideName
!== null ) {
1857 return $this->mHideName
;
1859 $this->getBlockedStatus();
1860 if ( !$this->mHideName
) {
1862 StubObject
::unstub( $wgAuth );
1863 $authUser = $wgAuth->getUserInstance( $this );
1864 $this->mHideName
= (bool)$authUser->isHidden();
1866 return $this->mHideName
;
1870 * Get the user's ID.
1871 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1873 public function getId() {
1874 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1875 // Special case, we know the user is anonymous
1877 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1878 // Don't load if this was initialized from an ID
1885 * Set the user and reload all fields according to a given ID
1886 * @param int $v User ID to reload
1888 public function setId( $v ) {
1890 $this->clearInstanceCache( 'id' );
1894 * Get the user name, or the IP of an anonymous user
1895 * @return string User's name or IP address
1897 public function getName() {
1898 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1899 // Special case optimisation
1900 return $this->mName
;
1903 if ( $this->mName
=== false ) {
1905 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1907 return $this->mName
;
1912 * Set the user name.
1914 * This does not reload fields from the database according to the given
1915 * name. Rather, it is used to create a temporary "nonexistent user" for
1916 * later addition to the database. It can also be used to set the IP
1917 * address for an anonymous user to something other than the current
1920 * @note User::newFromName() has roughly the same function, when the named user
1922 * @param string $str New user name to set
1924 public function setName( $str ) {
1926 $this->mName
= $str;
1930 * Get the user's name escaped by underscores.
1931 * @return string Username escaped by underscores.
1933 public function getTitleKey() {
1934 return str_replace( ' ', '_', $this->getName() );
1938 * Check if the user has new messages.
1939 * @return bool True if the user has new messages
1941 public function getNewtalk() {
1944 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1945 if ( $this->mNewtalk
=== -1 ) {
1946 $this->mNewtalk
= false; # reset talk page status
1948 // Check memcached separately for anons, who have no
1949 // entire User object stored in there.
1950 if ( !$this->mId
) {
1951 global $wgDisableAnonTalk;
1952 if ( $wgDisableAnonTalk ) {
1953 // Anon newtalk disabled by configuration.
1954 $this->mNewtalk
= false;
1957 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1958 $newtalk = $wgMemc->get( $key );
1959 if ( strval( $newtalk ) !== '' ) {
1960 $this->mNewtalk
= (bool)$newtalk;
1962 // Since we are caching this, make sure it is up to date by getting it
1964 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1965 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1969 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1973 return (bool)$this->mNewtalk
;
1977 * Return the data needed to construct links for new talk page message
1978 * alerts. If there are new messages, this will return an associative array
1979 * with the following data:
1980 * wiki: The database name of the wiki
1981 * link: Root-relative link to the user's talk page
1982 * rev: The last talk page revision that the user has seen or null. This
1983 * is useful for building diff links.
1984 * If there are no new messages, it returns an empty array.
1985 * @note This function was designed to accomodate multiple talk pages, but
1986 * currently only returns a single link and revision.
1989 public function getNewMessageLinks() {
1991 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
1993 } elseif ( !$this->getNewtalk() ) {
1996 $utp = $this->getTalkPage();
1997 $dbr = wfGetDB( DB_SLAVE
);
1998 // Get the "last viewed rev" timestamp from the oldest message notification
1999 $timestamp = $dbr->selectField( 'user_newtalk',
2000 'MIN(user_last_timestamp)',
2001 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2003 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2004 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2008 * Get the revision ID for the last talk page revision viewed by the talk
2010 * @return int|null Revision ID or null
2012 public function getNewMessageRevisionId() {
2013 $newMessageRevisionId = null;
2014 $newMessageLinks = $this->getNewMessageLinks();
2015 if ( $newMessageLinks ) {
2016 // Note: getNewMessageLinks() never returns more than a single link
2017 // and it is always for the same wiki, but we double-check here in
2018 // case that changes some time in the future.
2019 if ( count( $newMessageLinks ) === 1
2020 && $newMessageLinks[0]['wiki'] === wfWikiID()
2021 && $newMessageLinks[0]['rev']
2023 $newMessageRevision = $newMessageLinks[0]['rev'];
2024 $newMessageRevisionId = $newMessageRevision->getId();
2027 return $newMessageRevisionId;
2031 * Internal uncached check for new messages
2034 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2035 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2036 * @param bool $fromMaster true to fetch from the master, false for a slave
2037 * @return bool True if the user has new messages
2039 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2040 if ( $fromMaster ) {
2041 $db = wfGetDB( DB_MASTER
);
2043 $db = wfGetDB( DB_SLAVE
);
2045 $ok = $db->selectField( 'user_newtalk', $field,
2046 array( $field => $id ), __METHOD__
);
2047 return $ok !== false;
2051 * Add or update the new messages flag
2052 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2053 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2054 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2055 * @return bool True if successful, false otherwise
2057 protected function updateNewtalk( $field, $id, $curRev = null ) {
2058 // Get timestamp of the talk page revision prior to the current one
2059 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2060 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2061 // Mark the user as having new messages since this revision
2062 $dbw = wfGetDB( DB_MASTER
);
2063 $dbw->insert( 'user_newtalk',
2064 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2067 if ( $dbw->affectedRows() ) {
2068 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2071 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2077 * Clear the new messages flag for the given user
2078 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2079 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2080 * @return bool True if successful, false otherwise
2082 protected function deleteNewtalk( $field, $id ) {
2083 $dbw = wfGetDB( DB_MASTER
);
2084 $dbw->delete( 'user_newtalk',
2085 array( $field => $id ),
2087 if ( $dbw->affectedRows() ) {
2088 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2091 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2097 * Update the 'You have new messages!' status.
2098 * @param bool $val Whether the user has new messages
2099 * @param Revision $curRev New, as yet unseen revision of the user talk
2100 * page. Ignored if null or !$val.
2102 public function setNewtalk( $val, $curRev = null ) {
2103 if ( wfReadOnly() ) {
2108 $this->mNewtalk
= $val;
2110 if ( $this->isAnon() ) {
2112 $id = $this->getName();
2115 $id = $this->getId();
2120 $changed = $this->updateNewtalk( $field, $id, $curRev );
2122 $changed = $this->deleteNewtalk( $field, $id );
2125 if ( $this->isAnon() ) {
2126 // Anons have a separate memcached space, since
2127 // user records aren't kept for them.
2128 $key = wfMemcKey( 'newtalk', 'ip', $id );
2129 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
2132 $this->invalidateCache();
2137 * Generate a current or new-future timestamp to be stored in the
2138 * user_touched field when we update things.
2139 * @return string Timestamp in TS_MW format
2141 private static function newTouchedTimestamp() {
2142 global $wgClockSkewFudge;
2143 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2147 * Clear user data from memcached.
2148 * Use after applying fun updates to the database; caller's
2149 * responsibility to update user_touched if appropriate.
2151 * Called implicitly from invalidateCache() and saveSettings().
2153 private function clearSharedCache() {
2157 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
2162 * Immediately touch the user data cache for this account.
2163 * Updates user_touched field, and removes account data from memcached
2164 * for reload on the next hit.
2166 public function invalidateCache() {
2167 if ( wfReadOnly() ) {
2172 $this->mTouched
= self
::newTouchedTimestamp();
2174 $dbw = wfGetDB( DB_MASTER
);
2175 $userid = $this->mId
;
2176 $touched = $this->mTouched
;
2177 $method = __METHOD__
;
2178 $dbw->onTransactionIdle( function() use ( $dbw, $userid, $touched, $method ) {
2179 // Prevent contention slams by checking user_touched first
2180 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2181 $needsPurge = $dbw->selectField( 'user', '1',
2182 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2183 if ( $needsPurge ) {
2184 $dbw->update( 'user',
2185 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2186 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2191 $this->clearSharedCache();
2196 * Validate the cache for this account.
2197 * @param string $timestamp A timestamp in TS_MW format
2200 public function validateCache( $timestamp ) {
2202 return ( $timestamp >= $this->mTouched
);
2206 * Get the user touched timestamp
2207 * @return string Timestamp
2209 public function getTouched() {
2211 return $this->mTouched
;
2215 * Set the password and reset the random token.
2216 * Calls through to authentication plugin if necessary;
2217 * will have no effect if the auth plugin refuses to
2218 * pass the change through or if the legal password
2221 * As a special case, setting the password to null
2222 * wipes it, so the account cannot be logged in until
2223 * a new password is set, for instance via e-mail.
2225 * @param string $str New password to set
2226 * @throws PasswordError on failure
2230 public function setPassword( $str ) {
2233 if ( $str !== null ) {
2234 if ( !$wgAuth->allowPasswordChange() ) {
2235 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2238 if ( !$this->isValidPassword( $str ) ) {
2239 global $wgMinimalPasswordLength;
2240 $valid = $this->getPasswordValidity( $str );
2241 if ( is_array( $valid ) ) {
2242 $message = array_shift( $valid );
2246 $params = array( $wgMinimalPasswordLength );
2248 throw new PasswordError( wfMessage( $message, $params )->text() );
2252 if ( !$wgAuth->setPassword( $this, $str ) ) {
2253 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2256 $this->setInternalPassword( $str );
2262 * Set the password and reset the random token unconditionally.
2264 * @param string|null $str New password to set or null to set an invalid
2265 * password hash meaning that the user will not be able to log in
2266 * through the web interface.
2268 public function setInternalPassword( $str ) {
2272 if ( $str === null ) {
2273 // Save an invalid hash...
2274 $this->mPassword
= '';
2276 $this->mPassword
= self
::crypt( $str );
2278 $this->mNewpassword
= '';
2279 $this->mNewpassTime
= null;
2283 * Get the user's current token.
2284 * @param bool $forceCreation Force the generation of a new token if the
2285 * user doesn't have one (default=true for backwards compatibility).
2286 * @return string Token
2288 public function getToken( $forceCreation = true ) {
2290 if ( !$this->mToken
&& $forceCreation ) {
2293 return $this->mToken
;
2297 * Set the random token (used for persistent authentication)
2298 * Called from loadDefaults() among other places.
2300 * @param string|bool $token If specified, set the token to this value
2302 public function setToken( $token = false ) {
2305 $this->mToken
= MWCryptRand
::generateHex( USER_TOKEN_LENGTH
);
2307 $this->mToken
= $token;
2312 * Set the password for a password reminder or new account email
2314 * @param string $str New password to set or null to set an invalid
2315 * password hash meaning that the user will not be able to use it
2316 * @param bool $throttle If true, reset the throttle timestamp to the present
2318 public function setNewpassword( $str, $throttle = true ) {
2321 if ( $str === null ) {
2322 $this->mNewpassword
= '';
2323 $this->mNewpassTime
= null;
2325 $this->mNewpassword
= self
::crypt( $str );
2327 $this->mNewpassTime
= wfTimestampNow();
2333 * Has password reminder email been sent within the last
2334 * $wgPasswordReminderResendTime hours?
2337 public function isPasswordReminderThrottled() {
2338 global $wgPasswordReminderResendTime;
2340 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2343 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2344 return time() < $expiry;
2348 * Get the user's e-mail address
2349 * @return string User's email address
2351 public function getEmail() {
2353 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
2354 return $this->mEmail
;
2358 * Get the timestamp of the user's e-mail authentication
2359 * @return string TS_MW timestamp
2361 public function getEmailAuthenticationTimestamp() {
2363 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2364 return $this->mEmailAuthenticated
;
2368 * Set the user's e-mail address
2369 * @param string $str New e-mail address
2371 public function setEmail( $str ) {
2373 if ( $str == $this->mEmail
) {
2376 $this->mEmail
= $str;
2377 $this->invalidateEmail();
2378 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
2382 * Set the user's e-mail address and a confirmation mail if needed.
2385 * @param string $str New e-mail address
2388 public function setEmailWithConfirmation( $str ) {
2389 global $wgEnableEmail, $wgEmailAuthentication;
2391 if ( !$wgEnableEmail ) {
2392 return Status
::newFatal( 'emaildisabled' );
2395 $oldaddr = $this->getEmail();
2396 if ( $str === $oldaddr ) {
2397 return Status
::newGood( true );
2400 $this->setEmail( $str );
2402 if ( $str !== '' && $wgEmailAuthentication ) {
2403 // Send a confirmation request to the new address if needed
2404 $type = $oldaddr != '' ?
'changed' : 'set';
2405 $result = $this->sendConfirmationMail( $type );
2406 if ( $result->isGood() ) {
2407 // Say the the caller that a confirmation mail has been sent
2408 $result->value
= 'eauth';
2411 $result = Status
::newGood( true );
2418 * Get the user's real name
2419 * @return string User's real name
2421 public function getRealName() {
2422 if ( !$this->isItemLoaded( 'realname' ) ) {
2426 return $this->mRealName
;
2430 * Set the user's real name
2431 * @param string $str New real name
2433 public function setRealName( $str ) {
2435 $this->mRealName
= $str;
2439 * Get the user's current setting for a given option.
2441 * @param string $oname The option to check
2442 * @param string $defaultOverride A default value returned if the option does not exist
2443 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2444 * @return string User's current value for the option
2445 * @see getBoolOption()
2446 * @see getIntOption()
2448 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2449 global $wgHiddenPrefs;
2450 $this->loadOptions();
2452 # We want 'disabled' preferences to always behave as the default value for
2453 # users, even if they have set the option explicitly in their settings (ie they
2454 # set it, and then it was disabled removing their ability to change it). But
2455 # we don't want to erase the preferences in the database in case the preference
2456 # is re-enabled again. So don't touch $mOptions, just override the returned value
2457 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2458 return self
::getDefaultOption( $oname );
2461 if ( array_key_exists( $oname, $this->mOptions
) ) {
2462 return $this->mOptions
[$oname];
2464 return $defaultOverride;
2469 * Get all user's options
2473 public function getOptions() {
2474 global $wgHiddenPrefs;
2475 $this->loadOptions();
2476 $options = $this->mOptions
;
2478 # We want 'disabled' preferences to always behave as the default value for
2479 # users, even if they have set the option explicitly in their settings (ie they
2480 # set it, and then it was disabled removing their ability to change it). But
2481 # we don't want to erase the preferences in the database in case the preference
2482 # is re-enabled again. So don't touch $mOptions, just override the returned value
2483 foreach ( $wgHiddenPrefs as $pref ) {
2484 $default = self
::getDefaultOption( $pref );
2485 if ( $default !== null ) {
2486 $options[$pref] = $default;
2494 * Get the user's current setting for a given option, as a boolean value.
2496 * @param string $oname The option to check
2497 * @return bool User's current value for the option
2500 public function getBoolOption( $oname ) {
2501 return (bool)$this->getOption( $oname );
2505 * Get the user's current setting for a given option, as an integer value.
2507 * @param string $oname The option to check
2508 * @param int $defaultOverride A default value returned if the option does not exist
2509 * @return int User's current value for the option
2512 public function getIntOption( $oname, $defaultOverride = 0 ) {
2513 $val = $this->getOption( $oname );
2515 $val = $defaultOverride;
2517 return intval( $val );
2521 * Set the given option for a user.
2523 * You need to call saveSettings() to actually write to the database.
2525 * @param string $oname The option to set
2526 * @param mixed $val New value to set
2528 public function setOption( $oname, $val ) {
2529 $this->loadOptions();
2531 // Explicitly NULL values should refer to defaults
2532 if ( is_null( $val ) ) {
2533 $val = self
::getDefaultOption( $oname );
2536 $this->mOptions
[$oname] = $val;
2540 * Get a token stored in the preferences (like the watchlist one),
2541 * resetting it if it's empty (and saving changes).
2543 * @param string $oname The option name to retrieve the token from
2544 * @return string|bool User's current value for the option, or false if this option is disabled.
2545 * @see resetTokenFromOption()
2548 public function getTokenFromOption( $oname ) {
2549 global $wgHiddenPrefs;
2550 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2554 $token = $this->getOption( $oname );
2556 $token = $this->resetTokenFromOption( $oname );
2557 $this->saveSettings();
2563 * Reset a token stored in the preferences (like the watchlist one).
2564 * *Does not* save user's preferences (similarly to setOption()).
2566 * @param string $oname The option name to reset the token in
2567 * @return string|bool New token value, or false if this option is disabled.
2568 * @see getTokenFromOption()
2571 public function resetTokenFromOption( $oname ) {
2572 global $wgHiddenPrefs;
2573 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2577 $token = MWCryptRand
::generateHex( 40 );
2578 $this->setOption( $oname, $token );
2583 * Return a list of the types of user options currently returned by
2584 * User::getOptionKinds().
2586 * Currently, the option kinds are:
2587 * - 'registered' - preferences which are registered in core MediaWiki or
2588 * by extensions using the UserGetDefaultOptions hook.
2589 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2590 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2591 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2592 * be used by user scripts.
2593 * - 'special' - "preferences" that are not accessible via User::getOptions
2594 * or User::setOptions.
2595 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2596 * These are usually legacy options, removed in newer versions.
2598 * The API (and possibly others) use this function to determine the possible
2599 * option types for validation purposes, so make sure to update this when a
2600 * new option kind is added.
2602 * @see User::getOptionKinds
2603 * @return array Option kinds
2605 public static function listOptionKinds() {
2608 'registered-multiselect',
2609 'registered-checkmatrix',
2617 * Return an associative array mapping preferences keys to the kind of a preference they're
2618 * used for. Different kinds are handled differently when setting or reading preferences.
2620 * See User::listOptionKinds for the list of valid option types that can be provided.
2622 * @see User::listOptionKinds
2623 * @param IContextSource $context
2624 * @param array $options Assoc. array with options keys to check as keys.
2625 * Defaults to $this->mOptions.
2626 * @return array the key => kind mapping data
2628 public function getOptionKinds( IContextSource
$context, $options = null ) {
2629 $this->loadOptions();
2630 if ( $options === null ) {
2631 $options = $this->mOptions
;
2634 $prefs = Preferences
::getPreferences( $this, $context );
2637 // Pull out the "special" options, so they don't get converted as
2638 // multiselect or checkmatrix.
2639 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2640 foreach ( $specialOptions as $name => $value ) {
2641 unset( $prefs[$name] );
2644 // Multiselect and checkmatrix options are stored in the database with
2645 // one key per option, each having a boolean value. Extract those keys.
2646 $multiselectOptions = array();
2647 foreach ( $prefs as $name => $info ) {
2648 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2649 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2650 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2651 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2653 foreach ( $opts as $value ) {
2654 $multiselectOptions["$prefix$value"] = true;
2657 unset( $prefs[$name] );
2660 $checkmatrixOptions = array();
2661 foreach ( $prefs as $name => $info ) {
2662 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2663 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2664 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2665 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2666 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2668 foreach ( $columns as $column ) {
2669 foreach ( $rows as $row ) {
2670 $checkmatrixOptions["$prefix-$column-$row"] = true;
2674 unset( $prefs[$name] );
2678 // $value is ignored
2679 foreach ( $options as $key => $value ) {
2680 if ( isset( $prefs[$key] ) ) {
2681 $mapping[$key] = 'registered';
2682 } elseif ( isset( $multiselectOptions[$key] ) ) {
2683 $mapping[$key] = 'registered-multiselect';
2684 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2685 $mapping[$key] = 'registered-checkmatrix';
2686 } elseif ( isset( $specialOptions[$key] ) ) {
2687 $mapping[$key] = 'special';
2688 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2689 $mapping[$key] = 'userjs';
2691 $mapping[$key] = 'unused';
2699 * Reset certain (or all) options to the site defaults
2701 * The optional parameter determines which kinds of preferences will be reset.
2702 * Supported values are everything that can be reported by getOptionKinds()
2703 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2705 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2706 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2707 * for backwards-compatibility.
2708 * @param IContextSource|null $context Context source used when $resetKinds
2709 * does not contain 'all', passed to getOptionKinds().
2710 * Defaults to RequestContext::getMain() when null.
2712 public function resetOptions(
2713 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2714 IContextSource
$context = null
2717 $defaultOptions = self
::getDefaultOptions();
2719 if ( !is_array( $resetKinds ) ) {
2720 $resetKinds = array( $resetKinds );
2723 if ( in_array( 'all', $resetKinds ) ) {
2724 $newOptions = $defaultOptions;
2726 if ( $context === null ) {
2727 $context = RequestContext
::getMain();
2730 $optionKinds = $this->getOptionKinds( $context );
2731 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2732 $newOptions = array();
2734 // Use default values for the options that should be deleted, and
2735 // copy old values for the ones that shouldn't.
2736 foreach ( $this->mOptions
as $key => $value ) {
2737 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2738 if ( array_key_exists( $key, $defaultOptions ) ) {
2739 $newOptions[$key] = $defaultOptions[$key];
2742 $newOptions[$key] = $value;
2747 wfRunHooks( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2749 $this->mOptions
= $newOptions;
2750 $this->mOptionsLoaded
= true;
2754 * Get the user's preferred date format.
2755 * @return string User's preferred date format
2757 public function getDatePreference() {
2758 // Important migration for old data rows
2759 if ( is_null( $this->mDatePreference
) ) {
2761 $value = $this->getOption( 'date' );
2762 $map = $wgLang->getDatePreferenceMigrationMap();
2763 if ( isset( $map[$value] ) ) {
2764 $value = $map[$value];
2766 $this->mDatePreference
= $value;
2768 return $this->mDatePreference
;
2772 * Determine based on the wiki configuration and the user's options,
2773 * whether this user must be over HTTPS no matter what.
2777 public function requiresHTTPS() {
2778 global $wgSecureLogin;
2779 if ( !$wgSecureLogin ) {
2782 $https = $this->getBoolOption( 'prefershttps' );
2783 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2785 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2792 * Get the user preferred stub threshold
2796 public function getStubThreshold() {
2797 global $wgMaxArticleSize; # Maximum article size, in Kb
2798 $threshold = $this->getIntOption( 'stubthreshold' );
2799 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2800 // If they have set an impossible value, disable the preference
2801 // so we can use the parser cache again.
2808 * Get the permissions this user has.
2809 * @return array Array of String permission names
2811 public function getRights() {
2812 if ( is_null( $this->mRights
) ) {
2813 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2814 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2815 // Force reindexation of rights when a hook has unset one of them
2816 $this->mRights
= array_values( array_unique( $this->mRights
) );
2818 return $this->mRights
;
2822 * Get the list of explicit group memberships this user has.
2823 * The implicit * and user groups are not included.
2824 * @return array Array of String internal group names
2826 public function getGroups() {
2828 $this->loadGroups();
2829 return $this->mGroups
;
2833 * Get the list of implicit group memberships this user has.
2834 * This includes all explicit groups, plus 'user' if logged in,
2835 * '*' for all accounts, and autopromoted groups
2836 * @param bool $recache Whether to avoid the cache
2837 * @return array Array of String internal group names
2839 public function getEffectiveGroups( $recache = false ) {
2840 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2841 wfProfileIn( __METHOD__
);
2842 $this->mEffectiveGroups
= array_unique( array_merge(
2843 $this->getGroups(), // explicit groups
2844 $this->getAutomaticGroups( $recache ) // implicit groups
2846 // Hook for additional groups
2847 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2848 // Force reindexation of groups when a hook has unset one of them
2849 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
2850 wfProfileOut( __METHOD__
);
2852 return $this->mEffectiveGroups
;
2856 * Get the list of implicit group memberships this user has.
2857 * This includes 'user' if logged in, '*' for all accounts,
2858 * and autopromoted groups
2859 * @param bool $recache Whether to avoid the cache
2860 * @return array Array of String internal group names
2862 public function getAutomaticGroups( $recache = false ) {
2863 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
2864 wfProfileIn( __METHOD__
);
2865 $this->mImplicitGroups
= array( '*' );
2866 if ( $this->getId() ) {
2867 $this->mImplicitGroups
[] = 'user';
2869 $this->mImplicitGroups
= array_unique( array_merge(
2870 $this->mImplicitGroups
,
2871 Autopromote
::getAutopromoteGroups( $this )
2875 // Assure data consistency with rights/groups,
2876 // as getEffectiveGroups() depends on this function
2877 $this->mEffectiveGroups
= null;
2879 wfProfileOut( __METHOD__
);
2881 return $this->mImplicitGroups
;
2885 * Returns the groups the user has belonged to.
2887 * The user may still belong to the returned groups. Compare with getGroups().
2889 * The function will not return groups the user had belonged to before MW 1.17
2891 * @return array Names of the groups the user has belonged to.
2893 public function getFormerGroups() {
2894 if ( is_null( $this->mFormerGroups
) ) {
2895 $dbr = wfGetDB( DB_MASTER
);
2896 $res = $dbr->select( 'user_former_groups',
2897 array( 'ufg_group' ),
2898 array( 'ufg_user' => $this->mId
),
2900 $this->mFormerGroups
= array();
2901 foreach ( $res as $row ) {
2902 $this->mFormerGroups
[] = $row->ufg_group
;
2905 return $this->mFormerGroups
;
2909 * Get the user's edit count.
2910 * @return int|null null for anonymous users
2912 public function getEditCount() {
2913 if ( !$this->getId() ) {
2917 if ( $this->mEditCount
=== null ) {
2918 /* Populate the count, if it has not been populated yet */
2919 wfProfileIn( __METHOD__
);
2920 $dbr = wfGetDB( DB_SLAVE
);
2921 // check if the user_editcount field has been initialized
2922 $count = $dbr->selectField(
2923 'user', 'user_editcount',
2924 array( 'user_id' => $this->mId
),
2928 if ( $count === null ) {
2929 // it has not been initialized. do so.
2930 $count = $this->initEditCount();
2932 $this->mEditCount
= $count;
2933 wfProfileOut( __METHOD__
);
2935 return (int)$this->mEditCount
;
2939 * Add the user to the given group.
2940 * This takes immediate effect.
2941 * @param string $group Name of the group to add
2943 public function addGroup( $group ) {
2944 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2945 $dbw = wfGetDB( DB_MASTER
);
2946 if ( $this->getId() ) {
2947 $dbw->insert( 'user_groups',
2949 'ug_user' => $this->getID(),
2950 'ug_group' => $group,
2953 array( 'IGNORE' ) );
2956 $this->loadGroups();
2957 $this->mGroups
[] = $group;
2958 // In case loadGroups was not called before, we now have the right twice.
2959 // Get rid of the duplicate.
2960 $this->mGroups
= array_unique( $this->mGroups
);
2962 // Refresh the groups caches, and clear the rights cache so it will be
2963 // refreshed on the next call to $this->getRights().
2964 $this->getEffectiveGroups( true );
2965 $this->mRights
= null;
2967 $this->invalidateCache();
2971 * Remove the user from the given group.
2972 * This takes immediate effect.
2973 * @param string $group Name of the group to remove
2975 public function removeGroup( $group ) {
2977 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2978 $dbw = wfGetDB( DB_MASTER
);
2979 $dbw->delete( 'user_groups',
2981 'ug_user' => $this->getID(),
2982 'ug_group' => $group,
2984 // Remember that the user was in this group
2985 $dbw->insert( 'user_former_groups',
2987 'ufg_user' => $this->getID(),
2988 'ufg_group' => $group,
2991 array( 'IGNORE' ) );
2993 $this->loadGroups();
2994 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2996 // Refresh the groups caches, and clear the rights cache so it will be
2997 // refreshed on the next call to $this->getRights().
2998 $this->getEffectiveGroups( true );
2999 $this->mRights
= null;
3001 $this->invalidateCache();
3005 * Get whether the user is logged in
3008 public function isLoggedIn() {
3009 return $this->getID() != 0;
3013 * Get whether the user is anonymous
3016 public function isAnon() {
3017 return !$this->isLoggedIn();
3021 * Check if user is allowed to access a feature / make an action
3023 * @internal param \String $varargs permissions to test
3024 * @return bool True if user is allowed to perform *any* of the given actions
3028 public function isAllowedAny( /*...*/ ) {
3029 $permissions = func_get_args();
3030 foreach ( $permissions as $permission ) {
3031 if ( $this->isAllowed( $permission ) ) {
3040 * @internal param $varargs string
3041 * @return bool True if the user is allowed to perform *all* of the given actions
3043 public function isAllowedAll( /*...*/ ) {
3044 $permissions = func_get_args();
3045 foreach ( $permissions as $permission ) {
3046 if ( !$this->isAllowed( $permission ) ) {
3054 * Internal mechanics of testing a permission
3055 * @param string $action
3058 public function isAllowed( $action = '' ) {
3059 if ( $action === '' ) {
3060 return true; // In the spirit of DWIM
3062 // Patrolling may not be enabled
3063 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3064 global $wgUseRCPatrol, $wgUseNPPatrol;
3065 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3069 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3070 // by misconfiguration: 0 == 'foo'
3071 return in_array( $action, $this->getRights(), true );
3075 * Check whether to enable recent changes patrol features for this user
3076 * @return bool True or false
3078 public function useRCPatrol() {
3079 global $wgUseRCPatrol;
3080 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3084 * Check whether to enable new pages patrol features for this user
3085 * @return bool True or false
3087 public function useNPPatrol() {
3088 global $wgUseRCPatrol, $wgUseNPPatrol;
3090 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3091 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3096 * Get the WebRequest object to use with this object
3098 * @return WebRequest
3100 public function getRequest() {
3101 if ( $this->mRequest
) {
3102 return $this->mRequest
;
3110 * Get the current skin, loading it if required
3111 * @return Skin The current skin
3112 * @todo FIXME: Need to check the old failback system [AV]
3113 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3115 public function getSkin() {
3116 wfDeprecated( __METHOD__
, '1.18' );
3117 return RequestContext
::getMain()->getSkin();
3121 * Get a WatchedItem for this user and $title.
3123 * @since 1.22 $checkRights parameter added
3124 * @param Title $title
3125 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3126 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3127 * @return WatchedItem
3129 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3130 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3132 if ( isset( $this->mWatchedItems
[$key] ) ) {
3133 return $this->mWatchedItems
[$key];
3136 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3137 $this->mWatchedItems
= array();
3140 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3141 return $this->mWatchedItems
[$key];
3145 * Check the watched status of an article.
3146 * @since 1.22 $checkRights parameter added
3147 * @param Title $title Title of the article to look at
3148 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3149 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3152 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3153 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3158 * @since 1.22 $checkRights parameter added
3159 * @param Title $title Title of the article to look at
3160 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3161 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3163 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3164 $this->getWatchedItem( $title, $checkRights )->addWatch();
3165 $this->invalidateCache();
3169 * Stop watching an article.
3170 * @since 1.22 $checkRights parameter added
3171 * @param Title $title Title of the article to look at
3172 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3173 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3175 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3176 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3177 $this->invalidateCache();
3181 * Clear the user's notification timestamp for the given title.
3182 * If e-notif e-mails are on, they will receive notification mails on
3183 * the next change of the page if it's watched etc.
3184 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3185 * @param Title $title Title of the article to look at
3186 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3188 public function clearNotification( &$title, $oldid = 0 ) {
3189 global $wgUseEnotif, $wgShowUpdatedMarker;
3191 // Do nothing if the database is locked to writes
3192 if ( wfReadOnly() ) {
3196 // Do nothing if not allowed to edit the watchlist
3197 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3201 // If we're working on user's talk page, we should update the talk page message indicator
3202 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3203 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3207 $nextid = $oldid ?
$title->getNextRevisionID( $oldid ) : null;
3209 if ( !$oldid ||
!$nextid ) {
3210 // If we're looking at the latest revision, we should definitely clear it
3211 $this->setNewtalk( false );
3213 // Otherwise we should update its revision, if it's present
3214 if ( $this->getNewtalk() ) {
3215 // Naturally the other one won't clear by itself
3216 $this->setNewtalk( false );
3217 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3222 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3226 if ( $this->isAnon() ) {
3227 // Nothing else to do...
3231 // Only update the timestamp if the page is being watched.
3232 // The query to find out if it is watched is cached both in memcached and per-invocation,
3233 // and when it does have to be executed, it can be on a slave
3234 // If this is the user's newtalk page, we always update the timestamp
3236 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3240 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3244 * Resets all of the given user's page-change notification timestamps.
3245 * If e-notif e-mails are on, they will receive notification mails on
3246 * the next change of any watched page.
3247 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3249 public function clearAllNotifications() {
3250 if ( wfReadOnly() ) {
3254 // Do nothing if not allowed to edit the watchlist
3255 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3259 global $wgUseEnotif, $wgShowUpdatedMarker;
3260 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3261 $this->setNewtalk( false );
3264 $id = $this->getId();
3266 $dbw = wfGetDB( DB_MASTER
);
3267 $dbw->update( 'watchlist',
3268 array( /* SET */ 'wl_notificationtimestamp' => null ),
3269 array( /* WHERE */ 'wl_user' => $id ),
3272 // We also need to clear here the "you have new message" notification for the own user_talk page;
3273 // it's cleared one page view later in WikiPage::doViewUpdates().
3278 * Set a cookie on the user's client. Wrapper for
3279 * WebResponse::setCookie
3280 * @param string $name Name of the cookie to set
3281 * @param string $value Value to set
3282 * @param int $exp Expiration time, as a UNIX time value;
3283 * if 0 or not specified, use the default $wgCookieExpiration
3284 * @param bool $secure
3285 * true: Force setting the secure attribute when setting the cookie
3286 * false: Force NOT setting the secure attribute when setting the cookie
3287 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3288 * @param array $params Array of options sent passed to WebResponse::setcookie()
3290 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3291 $params['secure'] = $secure;
3292 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3296 * Clear a cookie on the user's client
3297 * @param string $name Name of the cookie to clear
3298 * @param bool $secure
3299 * true: Force setting the secure attribute when setting the cookie
3300 * false: Force NOT setting the secure attribute when setting the cookie
3301 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3302 * @param array $params Array of options sent passed to WebResponse::setcookie()
3304 protected function clearCookie( $name, $secure = null, $params = array() ) {
3305 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3309 * Set the default cookies for this session on the user's client.
3311 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3313 * @param bool $secure Whether to force secure/insecure cookies or use default
3314 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3316 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3317 if ( $request === null ) {
3318 $request = $this->getRequest();
3322 if ( 0 == $this->mId
) {
3325 if ( !$this->mToken
) {
3326 // When token is empty or NULL generate a new one and then save it to the database
3327 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3328 // Simply by setting every cell in the user_token column to NULL and letting them be
3329 // regenerated as users log back into the wiki.
3331 $this->saveSettings();
3334 'wsUserID' => $this->mId
,
3335 'wsToken' => $this->mToken
,
3336 'wsUserName' => $this->getName()
3339 'UserID' => $this->mId
,
3340 'UserName' => $this->getName(),
3342 if ( $rememberMe ) {
3343 $cookies['Token'] = $this->mToken
;
3345 $cookies['Token'] = false;
3348 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3350 foreach ( $session as $name => $value ) {
3351 $request->setSessionData( $name, $value );
3353 foreach ( $cookies as $name => $value ) {
3354 if ( $value === false ) {
3355 $this->clearCookie( $name );
3357 $this->setCookie( $name, $value, 0, $secure );
3362 * If wpStickHTTPS was selected, also set an insecure cookie that
3363 * will cause the site to redirect the user to HTTPS, if they access
3364 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3365 * as the one set by centralauth (bug 53538). Also set it to session, or
3366 * standard time setting, based on if rememberme was set.
3368 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3372 $rememberMe ?
0 : null,
3374 array( 'prefix' => '' ) // no prefix
3380 * Log this user out.
3382 public function logout() {
3383 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3389 * Clear the user's cookies and session, and reset the instance cache.
3392 public function doLogout() {
3393 $this->clearInstanceCache( 'defaults' );
3395 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3397 $this->clearCookie( 'UserID' );
3398 $this->clearCookie( 'Token' );
3399 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3401 // Remember when user logged out, to prevent seeing cached pages
3402 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3406 * Save this user's settings into the database.
3407 * @todo Only rarely do all these fields need to be set!
3409 public function saveSettings() {
3413 if ( wfReadOnly() ) {
3416 if ( 0 == $this->mId
) {
3420 $this->mTouched
= self
::newTouchedTimestamp();
3421 if ( !$wgAuth->allowSetLocalPassword() ) {
3422 $this->mPassword
= '';
3425 $dbw = wfGetDB( DB_MASTER
);
3426 $dbw->update( 'user',
3428 'user_name' => $this->mName
,
3429 'user_password' => $this->mPassword
,
3430 'user_newpassword' => $this->mNewpassword
,
3431 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3432 'user_real_name' => $this->mRealName
,
3433 'user_email' => $this->mEmail
,
3434 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3435 'user_touched' => $dbw->timestamp( $this->mTouched
),
3436 'user_token' => strval( $this->mToken
),
3437 'user_email_token' => $this->mEmailToken
,
3438 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3439 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires
),
3440 ), array( /* WHERE */
3441 'user_id' => $this->mId
3445 $this->saveOptions();
3447 wfRunHooks( 'UserSaveSettings', array( $this ) );
3448 $this->clearSharedCache();
3449 $this->getUserPage()->invalidateCache();
3453 * If only this user's username is known, and it exists, return the user ID.
3456 public function idForName() {
3457 $s = trim( $this->getName() );
3462 $dbr = wfGetDB( DB_SLAVE
);
3463 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
3464 if ( $id === false ) {
3471 * Add a user to the database, return the user object
3473 * @param string $name Username to add
3474 * @param array $params Array of Strings Non-default parameters to save to
3475 * the database as user_* fields:
3476 * - password: The user's password hash. Password logins will be disabled
3477 * if this is omitted.
3478 * - newpassword: Hash for a temporary password that has been mailed to
3480 * - email: The user's email address.
3481 * - email_authenticated: The email authentication timestamp.
3482 * - real_name: The user's real name.
3483 * - options: An associative array of non-default options.
3484 * - token: Random authentication token. Do not set.
3485 * - registration: Registration timestamp. Do not set.
3487 * @return User|null User object, or null if the username already exists.
3489 public static function createNew( $name, $params = array() ) {
3492 $user->setToken(); // init token
3493 if ( isset( $params['options'] ) ) {
3494 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3495 unset( $params['options'] );
3497 $dbw = wfGetDB( DB_MASTER
);
3498 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3501 'user_id' => $seqVal,
3502 'user_name' => $name,
3503 'user_password' => $user->mPassword
,
3504 'user_newpassword' => $user->mNewpassword
,
3505 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3506 'user_email' => $user->mEmail
,
3507 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3508 'user_real_name' => $user->mRealName
,
3509 'user_token' => strval( $user->mToken
),
3510 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3511 'user_editcount' => 0,
3512 'user_touched' => $dbw->timestamp( self
::newTouchedTimestamp() ),
3514 foreach ( $params as $name => $value ) {
3515 $fields["user_$name"] = $value;
3517 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3518 if ( $dbw->affectedRows() ) {
3519 $newUser = User
::newFromId( $dbw->insertId() );
3527 * Add this existing user object to the database. If the user already
3528 * exists, a fatal status object is returned, and the user object is
3529 * initialised with the data from the database.
3531 * Previously, this function generated a DB error due to a key conflict
3532 * if the user already existed. Many extension callers use this function
3533 * in code along the lines of:
3535 * $user = User::newFromName( $name );
3536 * if ( !$user->isLoggedIn() ) {
3537 * $user->addToDatabase();
3539 * // do something with $user...
3541 * However, this was vulnerable to a race condition (bug 16020). By
3542 * initialising the user object if the user exists, we aim to support this
3543 * calling sequence as far as possible.
3545 * Note that if the user exists, this function will acquire a write lock,
3546 * so it is still advisable to make the call conditional on isLoggedIn(),
3547 * and to commit the transaction after calling.
3549 * @throws MWException
3552 public function addToDatabase() {
3554 if ( !$this->mToken
) {
3555 $this->setToken(); // init token
3558 $this->mTouched
= self
::newTouchedTimestamp();
3560 $dbw = wfGetDB( DB_MASTER
);
3561 $inWrite = $dbw->writesOrCallbacksPending();
3562 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3563 $dbw->insert( 'user',
3565 'user_id' => $seqVal,
3566 'user_name' => $this->mName
,
3567 'user_password' => $this->mPassword
,
3568 'user_newpassword' => $this->mNewpassword
,
3569 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3570 'user_email' => $this->mEmail
,
3571 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3572 'user_real_name' => $this->mRealName
,
3573 'user_token' => strval( $this->mToken
),
3574 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3575 'user_editcount' => 0,
3576 'user_touched' => $dbw->timestamp( $this->mTouched
),
3580 if ( !$dbw->affectedRows() ) {
3581 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3582 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3584 // Can't commit due to pending writes that may need atomicity.
3585 // This may cause some lock contention unlike the case below.
3586 $options = array( 'LOCK IN SHARE MODE' );
3587 $flags = self
::READ_LOCKING
;
3589 // Often, this case happens early in views before any writes when
3590 // using CentralAuth. It's should be OK to commit and break the snapshot.
3591 $dbw->commit( __METHOD__
, 'flush' );
3595 $this->mId
= $dbw->selectField( 'user', 'user_id',
3596 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3599 if ( $this->loadFromDatabase( $flags ) ) {
3604 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3605 "to insert user '{$this->mName}' row, but it was not present in select!" );
3607 return Status
::newFatal( 'userexists' );
3609 $this->mId
= $dbw->insertId();
3611 // Clear instance cache other than user table data, which is already accurate
3612 $this->clearInstanceCache();
3614 $this->saveOptions();
3615 return Status
::newGood();
3619 * If this user is logged-in and blocked,
3620 * block any IP address they've successfully logged in from.
3621 * @return bool A block was spread
3623 public function spreadAnyEditBlock() {
3624 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3625 return $this->spreadBlock();
3631 * If this (non-anonymous) user is blocked,
3632 * block the IP address they've successfully logged in from.
3633 * @return bool A block was spread
3635 protected function spreadBlock() {
3636 wfDebug( __METHOD__
. "()\n" );
3638 if ( $this->mId
== 0 ) {
3642 $userblock = Block
::newFromTarget( $this->getName() );
3643 if ( !$userblock ) {
3647 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3651 * Get whether the user is explicitly blocked from account creation.
3652 * @return bool|Block
3654 public function isBlockedFromCreateAccount() {
3655 $this->getBlockedStatus();
3656 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3657 return $this->mBlock
;
3660 # bug 13611: if the IP address the user is trying to create an account from is
3661 # blocked with createaccount disabled, prevent new account creation there even
3662 # when the user is logged in
3663 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3664 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3666 return $this->mBlockedFromCreateAccount
instanceof Block
3667 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3668 ?
$this->mBlockedFromCreateAccount
3673 * Get whether the user is blocked from using Special:Emailuser.
3676 public function isBlockedFromEmailuser() {
3677 $this->getBlockedStatus();
3678 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3682 * Get whether the user is allowed to create an account.
3685 public function isAllowedToCreateAccount() {
3686 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3690 * Get this user's personal page title.
3692 * @return Title User's personal page title
3694 public function getUserPage() {
3695 return Title
::makeTitle( NS_USER
, $this->getName() );
3699 * Get this user's talk page title.
3701 * @return Title User's talk page title
3703 public function getTalkPage() {
3704 $title = $this->getUserPage();
3705 return $title->getTalkPage();
3709 * Determine whether the user is a newbie. Newbies are either
3710 * anonymous IPs, or the most recently created accounts.
3713 public function isNewbie() {
3714 return !$this->isAllowed( 'autoconfirmed' );
3718 * Check to see if the given clear-text password is one of the accepted passwords
3719 * @param string $password user password.
3720 * @return bool True if the given password is correct, otherwise False.
3722 public function checkPassword( $password ) {
3723 global $wgAuth, $wgLegacyEncoding;
3726 // Certain authentication plugins do NOT want to save
3727 // domain passwords in a mysql database, so we should
3728 // check this (in case $wgAuth->strict() is false).
3730 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3732 } elseif ( $wgAuth->strict() ) {
3733 // Auth plugin doesn't allow local authentication
3735 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3736 // Auth plugin doesn't allow local authentication for this user name
3739 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
3741 } elseif ( $wgLegacyEncoding ) {
3742 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3743 // Check for this with iconv
3744 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3745 if ( $cp1252Password != $password
3746 && self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
)
3755 * Check if the given clear-text password matches the temporary password
3756 * sent by e-mail for password reset operations.
3758 * @param string $plaintext
3760 * @return bool True if matches, false otherwise
3762 public function checkTemporaryPassword( $plaintext ) {
3763 global $wgNewPasswordExpiry;
3766 if ( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
3767 if ( is_null( $this->mNewpassTime
) ) {
3770 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3771 return ( time() < $expiry );
3778 * Alias for getEditToken.
3779 * @deprecated since 1.19, use getEditToken instead.
3781 * @param string|array $salt of Strings Optional function-specific data for hashing
3782 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3783 * @return string The new edit token
3785 public function editToken( $salt = '', $request = null ) {
3786 wfDeprecated( __METHOD__
, '1.19' );
3787 return $this->getEditToken( $salt, $request );
3791 * Initialize (if necessary) and return a session token value
3792 * which can be used in edit forms to show that the user's
3793 * login credentials aren't being hijacked with a foreign form
3798 * @param string|array $salt of Strings Optional function-specific data for hashing
3799 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3800 * @return string The new edit token
3802 public function getEditToken( $salt = '', $request = null ) {
3803 if ( $request == null ) {
3804 $request = $this->getRequest();
3807 if ( $this->isAnon() ) {
3808 return EDIT_TOKEN_SUFFIX
;
3810 $token = $request->getSessionData( 'wsEditToken' );
3811 if ( $token === null ) {
3812 $token = MWCryptRand
::generateHex( 32 );
3813 $request->setSessionData( 'wsEditToken', $token );
3815 if ( is_array( $salt ) ) {
3816 $salt = implode( '|', $salt );
3818 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
3823 * Generate a looking random token for various uses.
3825 * @return string The new random token
3826 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
3827 * wfRandomString for pseudo-randomness.
3829 public static function generateToken() {
3830 return MWCryptRand
::generateHex( 32 );
3834 * Check given value against the token value stored in the session.
3835 * A match should confirm that the form was submitted from the
3836 * user's own login session, not a form submission from a third-party
3839 * @param string $val Input value to compare
3840 * @param string $salt Optional function-specific data for hashing
3841 * @param WebRequest|null $request Object to use or null to use $wgRequest
3842 * @return bool Whether the token matches
3844 public function matchEditToken( $val, $salt = '', $request = null ) {
3845 $sessionToken = $this->getEditToken( $salt, $request );
3846 if ( $val != $sessionToken ) {
3847 wfDebug( "User::matchEditToken: broken session data\n" );
3850 return $val == $sessionToken;
3854 * Check given value against the token value stored in the session,
3855 * ignoring the suffix.
3857 * @param string $val Input value to compare
3858 * @param string $salt Optional function-specific data for hashing
3859 * @param WebRequest|null $request object to use or null to use $wgRequest
3860 * @return bool Whether the token matches
3862 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3863 $sessionToken = $this->getEditToken( $salt, $request );
3864 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3868 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3869 * mail to the user's given address.
3871 * @param string $type Message to send, either "created", "changed" or "set"
3874 public function sendConfirmationMail( $type = 'created' ) {
3876 $expiration = null; // gets passed-by-ref and defined in next line.
3877 $token = $this->confirmationToken( $expiration );
3878 $url = $this->confirmationTokenUrl( $token );
3879 $invalidateURL = $this->invalidationTokenUrl( $token );
3880 $this->saveSettings();
3882 if ( $type == 'created' ||
$type === false ) {
3883 $message = 'confirmemail_body';
3884 } elseif ( $type === true ) {
3885 $message = 'confirmemail_body_changed';
3887 // Messages: confirmemail_body_changed, confirmemail_body_set
3888 $message = 'confirmemail_body_' . $type;
3891 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3892 wfMessage( $message,
3893 $this->getRequest()->getIP(),
3896 $wgLang->timeanddate( $expiration, false ),
3898 $wgLang->date( $expiration, false ),
3899 $wgLang->time( $expiration, false ) )->text() );
3903 * Send an e-mail to this user's account. Does not check for
3904 * confirmed status or validity.
3906 * @param string $subject Message subject
3907 * @param string $body Message body
3908 * @param string $from Optional From address; if unspecified, default
3909 * $wgPasswordSender will be used.
3910 * @param string $replyto Reply-To address
3913 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3914 if ( is_null( $from ) ) {
3915 global $wgPasswordSender;
3916 $sender = new MailAddress( $wgPasswordSender,
3917 wfMessage( 'emailsender' )->inContentLanguage()->text() );
3919 $sender = new MailAddress( $from );
3922 $to = new MailAddress( $this );
3923 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
3927 * Generate, store, and return a new e-mail confirmation code.
3928 * A hash (unsalted, since it's used as a key) is stored.
3930 * @note Call saveSettings() after calling this function to commit
3931 * this change to the database.
3933 * @param string &$expiration Accepts the expiration time
3934 * @return string New token
3936 protected function confirmationToken( &$expiration ) {
3937 global $wgUserEmailConfirmationTokenExpiry;
3939 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
3940 $expiration = wfTimestamp( TS_MW
, $expires );
3942 $token = MWCryptRand
::generateHex( 32 );
3943 $hash = md5( $token );
3944 $this->mEmailToken
= $hash;
3945 $this->mEmailTokenExpires
= $expiration;
3950 * Return a URL the user can use to confirm their email address.
3951 * @param string $token Accepts the email confirmation token
3952 * @return string New token URL
3954 protected function confirmationTokenUrl( $token ) {
3955 return $this->getTokenUrl( 'ConfirmEmail', $token );
3959 * Return a URL the user can use to invalidate their email address.
3960 * @param string $token Accepts the email confirmation token
3961 * @return string New token URL
3963 protected function invalidationTokenUrl( $token ) {
3964 return $this->getTokenUrl( 'InvalidateEmail', $token );
3968 * Internal function to format the e-mail validation/invalidation URLs.
3969 * This uses a quickie hack to use the
3970 * hardcoded English names of the Special: pages, for ASCII safety.
3972 * @note Since these URLs get dropped directly into emails, using the
3973 * short English names avoids insanely long URL-encoded links, which
3974 * also sometimes can get corrupted in some browsers/mailers
3975 * (bug 6957 with Gmail and Internet Explorer).
3977 * @param string $page Special page
3978 * @param string $token Token
3979 * @return string Formatted URL
3981 protected function getTokenUrl( $page, $token ) {
3982 // Hack to bypass localization of 'Special:'
3983 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
3984 return $title->getCanonicalURL();
3988 * Mark the e-mail address confirmed.
3990 * @note Call saveSettings() after calling this function to commit the change.
3994 public function confirmEmail() {
3995 // Check if it's already confirmed, so we don't touch the database
3996 // and fire the ConfirmEmailComplete hook on redundant confirmations.
3997 if ( !$this->isEmailConfirmed() ) {
3998 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3999 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
4005 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4006 * address if it was already confirmed.
4008 * @note Call saveSettings() after calling this function to commit the change.
4009 * @return bool Returns true
4011 public function invalidateEmail() {
4013 $this->mEmailToken
= null;
4014 $this->mEmailTokenExpires
= null;
4015 $this->setEmailAuthenticationTimestamp( null );
4016 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
4021 * Set the e-mail authentication timestamp.
4022 * @param string $timestamp TS_MW timestamp
4024 public function setEmailAuthenticationTimestamp( $timestamp ) {
4026 $this->mEmailAuthenticated
= $timestamp;
4027 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4031 * Is this user allowed to send e-mails within limits of current
4032 * site configuration?
4035 public function canSendEmail() {
4036 global $wgEnableEmail, $wgEnableUserEmail;
4037 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4040 $canSend = $this->isEmailConfirmed();
4041 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4046 * Is this user allowed to receive e-mails within limits of current
4047 * site configuration?
4050 public function canReceiveEmail() {
4051 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4055 * Is this user's e-mail address valid-looking and confirmed within
4056 * limits of the current site configuration?
4058 * @note If $wgEmailAuthentication is on, this may require the user to have
4059 * confirmed their address by returning a code or using a password
4060 * sent to the address from the wiki.
4064 public function isEmailConfirmed() {
4065 global $wgEmailAuthentication;
4068 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4069 if ( $this->isAnon() ) {
4072 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4075 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4085 * Check whether there is an outstanding request for e-mail confirmation.
4088 public function isEmailConfirmationPending() {
4089 global $wgEmailAuthentication;
4090 return $wgEmailAuthentication &&
4091 !$this->isEmailConfirmed() &&
4092 $this->mEmailToken
&&
4093 $this->mEmailTokenExpires
> wfTimestamp();
4097 * Get the timestamp of account creation.
4099 * @return string|bool|null Timestamp of account creation, false for
4100 * non-existent/anonymous user accounts, or null if existing account
4101 * but information is not in database.
4103 public function getRegistration() {
4104 if ( $this->isAnon() ) {
4108 return $this->mRegistration
;
4112 * Get the timestamp of the first edit
4114 * @return string|bool Timestamp of first edit, or false for
4115 * non-existent/anonymous user accounts.
4117 public function getFirstEditTimestamp() {
4118 if ( $this->getId() == 0 ) {
4119 return false; // anons
4121 $dbr = wfGetDB( DB_SLAVE
);
4122 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4123 array( 'rev_user' => $this->getId() ),
4125 array( 'ORDER BY' => 'rev_timestamp ASC' )
4128 return false; // no edits
4130 return wfTimestamp( TS_MW
, $time );
4134 * Get the permissions associated with a given list of groups
4136 * @param array $groups Array of Strings List of internal group names
4137 * @return array Array of Strings List of permission key names for given groups combined
4139 public static function getGroupPermissions( $groups ) {
4140 global $wgGroupPermissions, $wgRevokePermissions;
4142 // grant every granted permission first
4143 foreach ( $groups as $group ) {
4144 if ( isset( $wgGroupPermissions[$group] ) ) {
4145 $rights = array_merge( $rights,
4146 // array_filter removes empty items
4147 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4150 // now revoke the revoked permissions
4151 foreach ( $groups as $group ) {
4152 if ( isset( $wgRevokePermissions[$group] ) ) {
4153 $rights = array_diff( $rights,
4154 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4157 return array_unique( $rights );
4161 * Get all the groups who have a given permission
4163 * @param string $role Role to check
4164 * @return array Array of Strings List of internal group names with the given permission
4166 public static function getGroupsWithPermission( $role ) {
4167 global $wgGroupPermissions;
4168 $allowedGroups = array();
4169 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4170 if ( self
::groupHasPermission( $group, $role ) ) {
4171 $allowedGroups[] = $group;
4174 return $allowedGroups;
4178 * Check, if the given group has the given permission
4180 * If you're wanting to check whether all users have a permission, use
4181 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4185 * @param string $group Group to check
4186 * @param string $role Role to check
4189 public static function groupHasPermission( $group, $role ) {
4190 global $wgGroupPermissions, $wgRevokePermissions;
4191 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4192 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4196 * Check if all users have the given permission
4199 * @param string $right Right to check
4202 public static function isEveryoneAllowed( $right ) {
4203 global $wgGroupPermissions, $wgRevokePermissions;
4204 static $cache = array();
4206 // Use the cached results, except in unit tests which rely on
4207 // being able change the permission mid-request
4208 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4209 return $cache[$right];
4212 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4213 $cache[$right] = false;
4217 // If it's revoked anywhere, then everyone doesn't have it
4218 foreach ( $wgRevokePermissions as $rights ) {
4219 if ( isset( $rights[$right] ) && $rights[$right] ) {
4220 $cache[$right] = false;
4225 // Allow extensions (e.g. OAuth) to say false
4226 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4227 $cache[$right] = false;
4231 $cache[$right] = true;
4236 * Get the localized descriptive name for a group, if it exists
4238 * @param string $group Internal group name
4239 * @return string Localized descriptive group name
4241 public static function getGroupName( $group ) {
4242 $msg = wfMessage( "group-$group" );
4243 return $msg->isBlank() ?
$group : $msg->text();
4247 * Get the localized descriptive name for a member of a group, if it exists
4249 * @param string $group Internal group name
4250 * @param string $username Username for gender (since 1.19)
4251 * @return string Localized name for group member
4253 public static function getGroupMember( $group, $username = '#' ) {
4254 $msg = wfMessage( "group-$group-member", $username );
4255 return $msg->isBlank() ?
$group : $msg->text();
4259 * Return the set of defined explicit groups.
4260 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4261 * are not included, as they are defined automatically, not in the database.
4262 * @return array Array of internal group names
4264 public static function getAllGroups() {
4265 global $wgGroupPermissions, $wgRevokePermissions;
4267 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4268 self
::getImplicitGroups()
4273 * Get a list of all available permissions.
4274 * @return array Array of permission names
4276 public static function getAllRights() {
4277 if ( self
::$mAllRights === false ) {
4278 global $wgAvailableRights;
4279 if ( count( $wgAvailableRights ) ) {
4280 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4282 self
::$mAllRights = self
::$mCoreRights;
4284 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
4286 return self
::$mAllRights;
4290 * Get a list of implicit groups
4291 * @return array Array of Strings Array of internal group names
4293 public static function getImplicitGroups() {
4294 global $wgImplicitGroups;
4296 $groups = $wgImplicitGroups;
4297 # Deprecated, use $wgImplictGroups instead
4298 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) );
4304 * Get the title of a page describing a particular group
4306 * @param string $group Internal group name
4307 * @return Title|bool Title of the page if it exists, false otherwise
4309 public static function getGroupPage( $group ) {
4310 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4311 if ( $msg->exists() ) {
4312 $title = Title
::newFromText( $msg->text() );
4313 if ( is_object( $title ) ) {
4321 * Create a link to the group in HTML, if available;
4322 * else return the group name.
4324 * @param string $group Internal name of the group
4325 * @param string $text The text of the link
4326 * @return string HTML link to the group
4328 public static function makeGroupLinkHTML( $group, $text = '' ) {
4329 if ( $text == '' ) {
4330 $text = self
::getGroupName( $group );
4332 $title = self
::getGroupPage( $group );
4334 return Linker
::link( $title, htmlspecialchars( $text ) );
4341 * Create a link to the group in Wikitext, if available;
4342 * else return the group name.
4344 * @param string $group Internal name of the group
4345 * @param string $text The text of the link
4346 * @return string Wikilink to the group
4348 public static function makeGroupLinkWiki( $group, $text = '' ) {
4349 if ( $text == '' ) {
4350 $text = self
::getGroupName( $group );
4352 $title = self
::getGroupPage( $group );
4354 $page = $title->getPrefixedText();
4355 return "[[$page|$text]]";
4362 * Returns an array of the groups that a particular group can add/remove.
4364 * @param string $group The group to check for whether it can add/remove
4365 * @return array array( 'add' => array( addablegroups ),
4366 * 'remove' => array( removablegroups ),
4367 * 'add-self' => array( addablegroups to self),
4368 * 'remove-self' => array( removable groups from self) )
4370 public static function changeableByGroup( $group ) {
4371 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4375 'remove' => array(),
4376 'add-self' => array(),
4377 'remove-self' => array()
4380 if ( empty( $wgAddGroups[$group] ) ) {
4381 // Don't add anything to $groups
4382 } elseif ( $wgAddGroups[$group] === true ) {
4383 // You get everything
4384 $groups['add'] = self
::getAllGroups();
4385 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4386 $groups['add'] = $wgAddGroups[$group];
4389 // Same thing for remove
4390 if ( empty( $wgRemoveGroups[$group] ) ) {
4391 } elseif ( $wgRemoveGroups[$group] === true ) {
4392 $groups['remove'] = self
::getAllGroups();
4393 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4394 $groups['remove'] = $wgRemoveGroups[$group];
4397 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4398 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4399 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4400 if ( is_int( $key ) ) {
4401 $wgGroupsAddToSelf['user'][] = $value;
4406 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4407 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4408 if ( is_int( $key ) ) {
4409 $wgGroupsRemoveFromSelf['user'][] = $value;
4414 // Now figure out what groups the user can add to him/herself
4415 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4416 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4417 // No idea WHY this would be used, but it's there
4418 $groups['add-self'] = User
::getAllGroups();
4419 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4420 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4423 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4424 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4425 $groups['remove-self'] = User
::getAllGroups();
4426 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4427 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4434 * Returns an array of groups that this user can add and remove
4435 * @return array array( 'add' => array( addablegroups ),
4436 * 'remove' => array( removablegroups ),
4437 * 'add-self' => array( addablegroups to self),
4438 * 'remove-self' => array( removable groups from self) )
4440 public function changeableGroups() {
4441 if ( $this->isAllowed( 'userrights' ) ) {
4442 // This group gives the right to modify everything (reverse-
4443 // compatibility with old "userrights lets you change
4445 // Using array_merge to make the groups reindexed
4446 $all = array_merge( User
::getAllGroups() );
4450 'add-self' => array(),
4451 'remove-self' => array()
4455 // Okay, it's not so simple, we will have to go through the arrays
4458 'remove' => array(),
4459 'add-self' => array(),
4460 'remove-self' => array()
4462 $addergroups = $this->getEffectiveGroups();
4464 foreach ( $addergroups as $addergroup ) {
4465 $groups = array_merge_recursive(
4466 $groups, $this->changeableByGroup( $addergroup )
4468 $groups['add'] = array_unique( $groups['add'] );
4469 $groups['remove'] = array_unique( $groups['remove'] );
4470 $groups['add-self'] = array_unique( $groups['add-self'] );
4471 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4477 * Increment the user's edit-count field.
4478 * Will have no effect for anonymous users.
4480 public function incEditCount() {
4481 if ( !$this->isAnon() ) {
4482 $dbw = wfGetDB( DB_MASTER
);
4485 array( 'user_editcount=user_editcount+1' ),
4486 array( 'user_id' => $this->getId() ),
4490 // Lazy initialization check...
4491 if ( $dbw->affectedRows() == 0 ) {
4492 // Now here's a goddamn hack...
4493 $dbr = wfGetDB( DB_SLAVE
);
4494 if ( $dbr !== $dbw ) {
4495 // If we actually have a slave server, the count is
4496 // at least one behind because the current transaction
4497 // has not been committed and replicated.
4498 $this->initEditCount( 1 );
4500 // But if DB_SLAVE is selecting the master, then the
4501 // count we just read includes the revision that was
4502 // just added in the working transaction.
4503 $this->initEditCount();
4507 // edit count in user cache too
4508 $this->invalidateCache();
4512 * Initialize user_editcount from data out of the revision table
4514 * @param int $add Edits to add to the count from the revision table
4515 * @return int Number of edits
4517 protected function initEditCount( $add = 0 ) {
4518 // Pull from a slave to be less cruel to servers
4519 // Accuracy isn't the point anyway here
4520 $dbr = wfGetDB( DB_SLAVE
);
4521 $count = (int)$dbr->selectField(
4524 array( 'rev_user' => $this->getId() ),
4527 $count = $count +
$add;
4529 $dbw = wfGetDB( DB_MASTER
);
4532 array( 'user_editcount' => $count ),
4533 array( 'user_id' => $this->getId() ),
4541 * Get the description of a given right
4543 * @param string $right Right to query
4544 * @return string Localized description of the right
4546 public static function getRightDescription( $right ) {
4547 $key = "right-$right";
4548 $msg = wfMessage( $key );
4549 return $msg->isBlank() ?
$right : $msg->text();
4553 * Make an old-style password hash
4555 * @param string $password Plain-text password
4556 * @param string $userId User ID
4557 * @return string Password hash
4559 public static function oldCrypt( $password, $userId ) {
4560 global $wgPasswordSalt;
4561 if ( $wgPasswordSalt ) {
4562 return md5( $userId . '-' . md5( $password ) );
4564 return md5( $password );
4569 * Make a new-style password hash
4571 * @param string $password Plain-text password
4572 * @param bool|string $salt Optional salt, may be random or the user ID.
4573 * If unspecified or false, will generate one automatically
4574 * @return string Password hash
4576 public static function crypt( $password, $salt = false ) {
4577 global $wgPasswordSalt;
4580 if ( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4584 if ( $wgPasswordSalt ) {
4585 if ( $salt === false ) {
4586 $salt = MWCryptRand
::generateHex( 8 );
4588 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4590 return ':A:' . md5( $password );
4595 * Compare a password hash with a plain-text password. Requires the user
4596 * ID if there's a chance that the hash is an old-style hash.
4598 * @param string $hash Password hash
4599 * @param string $password Plain-text password to compare
4600 * @param string|bool $userId User ID for old-style password salt
4604 public static function comparePasswords( $hash, $password, $userId = false ) {
4605 $type = substr( $hash, 0, 3 );
4608 if ( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4612 if ( $type == ':A:' ) {
4614 return md5( $password ) === substr( $hash, 3 );
4615 } elseif ( $type == ':B:' ) {
4617 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4618 return md5( $salt . '-' . md5( $password ) ) === $realHash;
4621 return self
::oldCrypt( $password, $userId ) === $hash;
4626 * Add a newuser log entry for this user.
4627 * Before 1.19 the return value was always true.
4629 * @param string|bool $action Account creation type.
4630 * - String, one of the following values:
4631 * - 'create' for an anonymous user creating an account for himself.
4632 * This will force the action's performer to be the created user itself,
4633 * no matter the value of $wgUser
4634 * - 'create2' for a logged in user creating an account for someone else
4635 * - 'byemail' when the created user will receive its password by e-mail
4636 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4637 * - Boolean means whether the account was created by e-mail (deprecated):
4638 * - true will be converted to 'byemail'
4639 * - false will be converted to 'create' if this object is the same as
4640 * $wgUser and to 'create2' otherwise
4642 * @param string $reason User supplied reason
4644 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4646 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4647 global $wgUser, $wgNewUserLog;
4648 if ( empty( $wgNewUserLog ) ) {
4649 return true; // disabled
4652 if ( $action === true ) {
4653 $action = 'byemail';
4654 } elseif ( $action === false ) {
4655 if ( $this->getName() == $wgUser->getName() ) {
4658 $action = 'create2';
4662 if ( $action === 'create' ||
$action === 'autocreate' ) {
4665 $performer = $wgUser;
4668 $logEntry = new ManualLogEntry( 'newusers', $action );
4669 $logEntry->setPerformer( $performer );
4670 $logEntry->setTarget( $this->getUserPage() );
4671 $logEntry->setComment( $reason );
4672 $logEntry->setParameters( array(
4673 '4::userid' => $this->getId(),
4675 $logid = $logEntry->insert();
4677 if ( $action !== 'autocreate' ) {
4678 $logEntry->publish( $logid );
4685 * Add an autocreate newuser log entry for this user
4686 * Used by things like CentralAuth and perhaps other authplugins.
4687 * Consider calling addNewUserLogEntry() directly instead.
4691 public function addNewUserLogEntryAutoCreate() {
4692 $this->addNewUserLogEntry( 'autocreate' );
4698 * Load the user options either from cache, the database or an array
4700 * @param array $data Rows for the current user out of the user_properties table
4702 protected function loadOptions( $data = null ) {
4707 if ( $this->mOptionsLoaded
) {
4711 $this->mOptions
= self
::getDefaultOptions();
4713 if ( !$this->getId() ) {
4714 // For unlogged-in users, load language/variant options from request.
4715 // There's no need to do it for logged-in users: they can set preferences,
4716 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4717 // so don't override user's choice (especially when the user chooses site default).
4718 $variant = $wgContLang->getDefaultVariant();
4719 $this->mOptions
['variant'] = $variant;
4720 $this->mOptions
['language'] = $variant;
4721 $this->mOptionsLoaded
= true;
4725 // Maybe load from the object
4726 if ( !is_null( $this->mOptionOverrides
) ) {
4727 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4728 foreach ( $this->mOptionOverrides
as $key => $value ) {
4729 $this->mOptions
[$key] = $value;
4732 if ( !is_array( $data ) ) {
4733 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4734 // Load from database
4735 $dbr = wfGetDB( DB_SLAVE
);
4737 $res = $dbr->select(
4739 array( 'up_property', 'up_value' ),
4740 array( 'up_user' => $this->getId() ),
4744 $this->mOptionOverrides
= array();
4746 foreach ( $res as $row ) {
4747 $data[$row->up_property
] = $row->up_value
;
4750 foreach ( $data as $property => $value ) {
4751 $this->mOptionOverrides
[$property] = $value;
4752 $this->mOptions
[$property] = $value;
4756 $this->mOptionsLoaded
= true;
4758 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
4762 * Saves the non-default options for this user, as previously set e.g. via
4763 * setOption(), in the database's "user_properties" (preferences) table.
4764 * Usually used via saveSettings().
4766 protected function saveOptions() {
4767 $this->loadOptions();
4769 // Not using getOptions(), to keep hidden preferences in database
4770 $saveOptions = $this->mOptions
;
4772 // Allow hooks to abort, for instance to save to a global profile.
4773 // Reset options to default state before saving.
4774 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4778 $userId = $this->getId();
4780 $insert_rows = array(); // all the new preference rows
4781 foreach ( $saveOptions as $key => $value ) {
4782 // Don't bother storing default values
4783 $defaultOption = self
::getDefaultOption( $key );
4784 if ( ( $defaultOption === null && $value !== false && $value !== null )
4785 ||
$value != $defaultOption
4787 $insert_rows[] = array(
4788 'up_user' => $userId,
4789 'up_property' => $key,
4790 'up_value' => $value,
4795 $dbw = wfGetDB( DB_MASTER
);
4797 $res = $dbw->select( 'user_properties',
4798 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
4800 // Find prior rows that need to be removed or updated. These rows will
4801 // all be deleted (the later so that INSERT IGNORE applies the new values).
4802 $keysDelete = array();
4803 foreach ( $res as $row ) {
4804 if ( !isset( $saveOptions[$row->up_property
] )
4805 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
4807 $keysDelete[] = $row->up_property
;
4811 if ( count( $keysDelete ) ) {
4812 // Do the DELETE by PRIMARY KEY for prior rows.
4813 // In the past a very large portion of calls to this function are for setting
4814 // 'rememberpassword' for new accounts (a preference that has since been removed).
4815 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4816 // caused gap locks on [max user ID,+infinity) which caused high contention since
4817 // updates would pile up on each other as they are for higher (newer) user IDs.
4818 // It might not be necessary these days, but it shouldn't hurt either.
4819 $dbw->delete( 'user_properties',
4820 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
4822 // Insert the new preference rows
4823 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
4827 * Provide an array of HTML5 attributes to put on an input element
4828 * intended for the user to enter a new password. This may include
4829 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4831 * Do *not* use this when asking the user to enter his current password!
4832 * Regardless of configuration, users may have invalid passwords for whatever
4833 * reason (e.g., they were set before requirements were tightened up).
4834 * Only use it when asking for a new password, like on account creation or
4837 * Obviously, you still need to do server-side checking.
4839 * NOTE: A combination of bugs in various browsers means that this function
4840 * actually just returns array() unconditionally at the moment. May as
4841 * well keep it around for when the browser bugs get fixed, though.
4843 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4845 * @return array Array of HTML attributes suitable for feeding to
4846 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4847 * That will get confused by the boolean attribute syntax used.)
4849 public static function passwordChangeInputAttribs() {
4850 global $wgMinimalPasswordLength;
4852 if ( $wgMinimalPasswordLength == 0 ) {
4856 # Note that the pattern requirement will always be satisfied if the
4857 # input is empty, so we need required in all cases.
4859 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4860 # if e-mail confirmation is being used. Since HTML5 input validation
4861 # is b0rked anyway in some browsers, just return nothing. When it's
4862 # re-enabled, fix this code to not output required for e-mail
4864 #$ret = array( 'required' );
4867 # We can't actually do this right now, because Opera 9.6 will print out
4868 # the entered password visibly in its error message! When other
4869 # browsers add support for this attribute, or Opera fixes its support,
4870 # we can add support with a version check to avoid doing this on Opera
4871 # versions where it will be a problem. Reported to Opera as
4872 # DSK-262266, but they don't have a public bug tracker for us to follow.
4874 if ( $wgMinimalPasswordLength > 1 ) {
4875 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4876 $ret['title'] = wfMessage( 'passwordtooshort' )
4877 ->numParams( $wgMinimalPasswordLength )->text();
4885 * Return the list of user fields that should be selected to create
4886 * a new user object.
4889 public static function selectFields() {
4896 'user_newpass_time',
4900 'user_email_authenticated',
4902 'user_email_token_expires',
4903 'user_password_expires',
4904 'user_registration',
4910 * Factory function for fatal permission-denied errors
4913 * @param string $permission User right required
4916 static function newFatalPermissionDeniedStatus( $permission ) {
4919 $groups = array_map(
4920 array( 'User', 'makeGroupLinkWiki' ),
4921 User
::getGroupsWithPermission( $permission )
4925 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4927 return Status
::newFatal( 'badaccess-group0' );