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',
183 * String Cached results of getAllRights()
185 protected static $mAllRights = false;
187 /** @name Cache variables */
197 public $mNewpassword;
199 public $mNewpassTime;
207 public $mEmailAuthenticated;
209 protected $mEmailToken;
211 protected $mEmailTokenExpires;
213 protected $mRegistration;
215 protected $mEditCount;
219 protected $mOptionOverrides;
221 protected $mPasswordExpires;
225 * Bool Whether the cache variables have been loaded.
228 public $mOptionsLoaded;
231 * Array with already loaded items or true if all items have been loaded.
233 protected $mLoadedItems = array();
237 * String Initialization data source if mLoadedItems!==true. May be one of:
238 * - 'defaults' anonymous user initialised from class defaults
239 * - 'name' initialise from mName
240 * - 'id' initialise from mId
241 * - 'session' log in from cookies or session if possible
243 * Use the User::newFrom*() family of functions to set this.
248 * Lazy-initialized variables, invalidated with clearInstanceCache
252 protected $mDatePreference;
260 protected $mBlockreason;
262 protected $mEffectiveGroups;
264 protected $mImplicitGroups;
266 protected $mFormerGroups;
268 protected $mBlockedGlobally;
285 protected $mAllowUsertalk;
288 private $mBlockedFromCreateAccount = false;
291 private $mWatchedItems = array();
293 public static $idCacheByName = array();
296 * Lightweight constructor for an anonymous user.
297 * Use the User::newFrom* factory functions for other kinds of users.
301 * @see newFromConfirmationCode()
302 * @see newFromSession()
305 public function __construct() {
306 $this->clearInstanceCache( 'defaults' );
312 public function __toString() {
313 return $this->getName();
317 * Load the user table data for this object from the source given by mFrom.
319 public function load() {
320 if ( $this->mLoadedItems
=== true ) {
323 wfProfileIn( __METHOD__
);
325 // Set it now to avoid infinite recursion in accessors
326 $this->mLoadedItems
= true;
328 switch ( $this->mFrom
) {
330 $this->loadDefaults();
333 $this->mId
= self
::idFromName( $this->mName
);
335 // Nonexistent user placeholder object
336 $this->loadDefaults( $this->mName
);
345 if ( !$this->loadFromSession() ) {
346 // Loading from session failed. Load defaults.
347 $this->loadDefaults();
349 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
352 wfProfileOut( __METHOD__
);
353 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
355 wfProfileOut( __METHOD__
);
359 * Load user table data, given mId has already been set.
360 * @return bool false if the ID does not exist, true otherwise
362 public function loadFromId() {
364 if ( $this->mId
== 0 ) {
365 $this->loadDefaults();
370 $key = wfMemcKey( 'user', 'id', $this->mId
);
371 $data = $wgMemc->get( $key );
372 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
373 // Object is expired, load from DB
378 wfDebug( "User: cache miss for user {$this->mId}\n" );
380 if ( !$this->loadFromDatabase() ) {
381 // Can't load from ID, user is anonymous
384 $this->saveToCache();
386 wfDebug( "User: got user {$this->mId} from cache\n" );
387 // Restore from cache
388 foreach ( self
::$mCacheVars as $name ) {
389 $this->$name = $data[$name];
393 $this->mLoadedItems
= true;
399 * Save user data to the shared cache
401 public function saveToCache() {
404 $this->loadOptions();
405 if ( $this->isAnon() ) {
406 // Anonymous users are uncached
410 foreach ( self
::$mCacheVars as $name ) {
411 $data[$name] = $this->$name;
413 $data['mVersion'] = MW_USER_VERSION
;
414 $key = wfMemcKey( 'user', 'id', $this->mId
);
416 $wgMemc->set( $key, $data );
419 /** @name newFrom*() static factory methods */
423 * Static factory method for creation from username.
425 * This is slightly less efficient than newFromId(), so use newFromId() if
426 * you have both an ID and a name handy.
428 * @param string $name Username, validated by Title::newFromText()
429 * @param string|bool $validate Validate username. Takes the same parameters as
430 * User::getCanonicalName(), except that true is accepted as an alias
431 * for 'valid', for BC.
433 * @return User|bool User object, or false if the username is invalid
434 * (e.g. if it contains illegal characters or is an IP address). If the
435 * username is not present in the database, the result will be a user object
436 * with a name, zero user ID and default settings.
438 public static function newFromName( $name, $validate = 'valid' ) {
439 if ( $validate === true ) {
442 $name = self
::getCanonicalName( $name, $validate );
443 if ( $name === false ) {
446 // Create unloaded user object
450 $u->setItemLoaded( 'name' );
456 * Static factory method for creation from a given user ID.
458 * @param int $id Valid user ID
459 * @return User The corresponding User object
461 public static function newFromId( $id ) {
465 $u->setItemLoaded( 'id' );
470 * Factory method to fetch whichever user has a given email confirmation code.
471 * This code is generated when an account is created or its e-mail address
474 * If the code is invalid or has expired, returns NULL.
476 * @param string $code Confirmation code
479 public static function newFromConfirmationCode( $code ) {
480 $dbr = wfGetDB( DB_SLAVE
);
481 $id = $dbr->selectField( 'user', 'user_id', array(
482 'user_email_token' => md5( $code ),
483 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
485 if ( $id !== false ) {
486 return User
::newFromId( $id );
493 * Create a new user object using data from session or cookies. If the
494 * login credentials are invalid, the result is an anonymous user.
496 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
499 public static function newFromSession( WebRequest
$request = null ) {
501 $user->mFrom
= 'session';
502 $user->mRequest
= $request;
507 * Create a new user object from a user row.
508 * The row should have the following fields from the user table in it:
509 * - either user_name or user_id to load further data if needed (or both)
511 * - all other fields (email, password, etc.)
512 * It is useless to provide the remaining fields if either user_id,
513 * user_name and user_real_name are not provided because the whole row
514 * will be loaded once more from the database when accessing them.
516 * @param stdClass $row A row from the user table
517 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
520 public static function newFromRow( $row, $data = null ) {
522 $user->loadFromRow( $row, $data );
529 * Get the username corresponding to a given user ID
530 * @param int $id User ID
531 * @return string|bool The corresponding username
533 public static function whoIs( $id ) {
534 return UserCache
::singleton()->getProp( $id, 'name' );
538 * Get the real name of a user given their user ID
540 * @param int $id User ID
541 * @return string|bool The corresponding user's real name
543 public static function whoIsReal( $id ) {
544 return UserCache
::singleton()->getProp( $id, 'real_name' );
548 * Get database id given a user name
549 * @param string $name Username
550 * @return int|null The corresponding user's ID, or null if user is nonexistent
552 public static function idFromName( $name ) {
553 $nt = Title
::makeTitleSafe( NS_USER
, $name );
554 if ( is_null( $nt ) ) {
559 if ( isset( self
::$idCacheByName[$name] ) ) {
560 return self
::$idCacheByName[$name];
563 $dbr = wfGetDB( DB_SLAVE
);
564 $s = $dbr->selectRow(
567 array( 'user_name' => $nt->getText() ),
571 if ( $s === false ) {
574 $result = $s->user_id
;
577 self
::$idCacheByName[$name] = $result;
579 if ( count( self
::$idCacheByName ) > 1000 ) {
580 self
::$idCacheByName = array();
587 * Reset the cache used in idFromName(). For use in tests.
589 public static function resetIdByNameCache() {
590 self
::$idCacheByName = array();
594 * Does the string match an anonymous IPv4 address?
596 * This function exists for username validation, in order to reject
597 * usernames which are similar in form to IP addresses. Strings such
598 * as 300.300.300.300 will return true because it looks like an IP
599 * address, despite not being strictly valid.
601 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
602 * address because the usemod software would "cloak" anonymous IP
603 * addresses like this, if we allowed accounts like this to be created
604 * new users could get the old edits of these anonymous users.
606 * @param string $name Name to match
609 public static function isIP( $name ) {
610 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
611 || IP
::isIPv6( $name );
615 * Is the input a valid username?
617 * Checks if the input is a valid username, we don't want an empty string,
618 * an IP address, anything that contains slashes (would mess up subpages),
619 * is longer than the maximum allowed username size or doesn't begin with
622 * @param string $name Name to match
625 public static function isValidUserName( $name ) {
626 global $wgContLang, $wgMaxNameChars;
629 || User
::isIP( $name )
630 ||
strpos( $name, '/' ) !== false
631 ||
strlen( $name ) > $wgMaxNameChars
632 ||
$name != $wgContLang->ucfirst( $name ) ) {
633 wfDebugLog( 'username', __METHOD__
.
634 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
638 // Ensure that the name can't be misresolved as a different title,
639 // such as with extra namespace keys at the start.
640 $parsed = Title
::newFromText( $name );
641 if ( is_null( $parsed )
642 ||
$parsed->getNamespace()
643 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
644 wfDebugLog( 'username', __METHOD__
.
645 ": '$name' invalid due to ambiguous prefixes" );
649 // Check an additional blacklist of troublemaker characters.
650 // Should these be merged into the title char list?
651 $unicodeBlacklist = '/[' .
652 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
653 '\x{00a0}' . # non-breaking space
654 '\x{2000}-\x{200f}' . # various whitespace
655 '\x{2028}-\x{202f}' . # breaks and control chars
656 '\x{3000}' . # ideographic space
657 '\x{e000}-\x{f8ff}' . # private use
659 if ( preg_match( $unicodeBlacklist, $name ) ) {
660 wfDebugLog( 'username', __METHOD__
.
661 ": '$name' invalid due to blacklisted characters" );
669 * Usernames which fail to pass this function will be blocked
670 * from user login and new account registrations, but may be used
671 * internally by batch processes.
673 * If an account already exists in this form, login will be blocked
674 * by a failure to pass this function.
676 * @param string $name Name to match
679 public static function isUsableName( $name ) {
680 global $wgReservedUsernames;
681 // Must be a valid username, obviously ;)
682 if ( !self
::isValidUserName( $name ) ) {
686 static $reservedUsernames = false;
687 if ( !$reservedUsernames ) {
688 $reservedUsernames = $wgReservedUsernames;
689 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
692 // Certain names may be reserved for batch processes.
693 foreach ( $reservedUsernames as $reserved ) {
694 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
695 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
697 if ( $reserved == $name ) {
705 * Usernames which fail to pass this function will be blocked
706 * from new account registrations, but may be used internally
707 * either by batch processes or by user accounts which have
708 * already been created.
710 * Additional blacklisting may be added here rather than in
711 * isValidUserName() to avoid disrupting existing accounts.
713 * @param string $name String to match
716 public static function isCreatableName( $name ) {
717 global $wgInvalidUsernameCharacters;
719 // Ensure that the username isn't longer than 235 bytes, so that
720 // (at least for the builtin skins) user javascript and css files
721 // will work. (bug 23080)
722 if ( strlen( $name ) > 235 ) {
723 wfDebugLog( 'username', __METHOD__
.
724 ": '$name' invalid due to length" );
728 // Preg yells if you try to give it an empty string
729 if ( $wgInvalidUsernameCharacters !== '' ) {
730 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
731 wfDebugLog( 'username', __METHOD__
.
732 ": '$name' invalid due to wgInvalidUsernameCharacters" );
737 return self
::isUsableName( $name );
741 * Is the input a valid password for this user?
743 * @param string $password Desired password
746 public function isValidPassword( $password ) {
747 //simple boolean wrapper for getPasswordValidity
748 return $this->getPasswordValidity( $password ) === true;
753 * Given unvalidated password input, return error message on failure.
755 * @param string $password Desired password
756 * @return bool|string|array true on success, string or array of error message on failure
758 public function getPasswordValidity( $password ) {
759 $result = $this->checkPasswordValidity( $password );
760 if ( $result->isGood() ) {
764 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
765 $messages[] = $error['message'];
767 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
768 $messages[] = $warning['message'];
770 if ( count( $messages ) === 1 ) {
778 * Check if this is a valid password for this user. Status will be good if
779 * the password is valid, or have an array of error messages if not.
781 * @param string $password Desired password
785 public function checkPasswordValidity( $password ) {
786 global $wgMinimalPasswordLength, $wgContLang;
788 static $blockedLogins = array(
789 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
790 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
793 $status = Status
::newGood();
795 $result = false; //init $result to false for the internal checks
797 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
798 $status->error( $result );
802 if ( $result === false ) {
803 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
804 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
806 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
807 $status->error( 'password-name-match' );
809 } elseif ( isset( $blockedLogins[$this->getName()] )
810 && $password == $blockedLogins[$this->getName()]
812 $status->error( 'password-login-forbidden' );
815 //it seems weird returning a Good status here, but this is because of the
816 //initialization of $result to false above. If the hook is never run or it
817 //doesn't modify $result, then we will likely get down into this if with
821 } elseif ( $result === true ) {
824 $status->error( $result );
825 return $status; //the isValidPassword hook set a string $result and returned true
830 * Expire a user's password
832 * @param int $ts Optional timestamp to convert, default 0 for the current time
834 public function expirePassword( $ts = 0 ) {
836 $timestamp = wfTimestamp( TS_MW
, $ts );
837 $this->mPasswordExpires
= $timestamp;
838 $this->saveSettings();
842 * Clear the password expiration for a user
844 * @param bool $load Ensure user object is loaded first
846 public function resetPasswordExpiration( $load = true ) {
847 global $wgPasswordExpirationDays;
852 if ( $wgPasswordExpirationDays ) {
853 $newExpire = wfTimestamp(
855 time() +
( $wgPasswordExpirationDays * 24 * 3600 )
858 // Give extensions a chance to force an expiration
859 wfRunHooks( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
860 $this->mPasswordExpires
= $newExpire;
864 * Check if the user's password is expired.
865 * TODO: Put this and password length into a PasswordPolicy object
867 * @return string|bool The expiration type, or false if not expired
868 * hard: A password change is required to login
869 * soft: Allow login, but encourage password change
870 * false: Password is not expired
872 public function getPasswordExpired() {
873 global $wgPasswordExpireGrace;
875 $now = wfTimestamp();
876 $expiration = $this->getPasswordExpireDate();
877 $expUnix = wfTimestamp( TS_UNIX
, $expiration );
878 if ( $expiration !== null && $expUnix < $now ) {
879 $expired = ( $expUnix +
$wgPasswordExpireGrace < $now ) ?
'hard' : 'soft';
885 * Get this user's password expiration date. Since this may be using
886 * the cached User object, we assume that whatever mechanism is setting
887 * the expiration date is also expiring the User cache.
889 * @return string|bool The datestamp of the expiration, or null if not set
891 public function getPasswordExpireDate() {
893 return $this->mPasswordExpires
;
897 * Given unvalidated user input, return a canonical username, or false if
898 * the username is invalid.
899 * @param string $name User input
900 * @param string|bool $validate Type of validation to use:
901 * - false No validation
902 * - 'valid' Valid for batch processes
903 * - 'usable' Valid for batch processes and login
904 * - 'creatable' Valid for batch processes, login and account creation
906 * @throws MWException
907 * @return bool|string
909 public static function getCanonicalName( $name, $validate = 'valid' ) {
910 // Force usernames to capital
912 $name = $wgContLang->ucfirst( $name );
914 # Reject names containing '#'; these will be cleaned up
915 # with title normalisation, but then it's too late to
917 if ( strpos( $name, '#' ) !== false ) {
921 // Clean up name according to title rules
922 $t = ( $validate === 'valid' ) ?
923 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
924 // Check for invalid titles
925 if ( is_null( $t ) ) {
929 // Reject various classes of invalid names
931 $name = $wgAuth->getCanonicalName( $t->getText() );
933 switch ( $validate ) {
937 if ( !User
::isValidUserName( $name ) ) {
942 if ( !User
::isUsableName( $name ) ) {
947 if ( !User
::isCreatableName( $name ) ) {
952 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
958 * Count the number of edits of a user
960 * @param int $uid User ID to check
961 * @return int The user's edit count
963 * @deprecated since 1.21 in favour of User::getEditCount
965 public static function edits( $uid ) {
966 wfDeprecated( __METHOD__
, '1.21' );
967 $user = self
::newFromId( $uid );
968 return $user->getEditCount();
972 * Return a random password.
974 * @return string New random password
976 public static function randomPassword() {
977 global $wgMinimalPasswordLength;
978 // Decide the final password length based on our min password length,
979 // stopping at a minimum of 10 chars.
980 $length = max( 10, $wgMinimalPasswordLength );
981 // Multiply by 1.25 to get the number of hex characters we need
982 $length = $length * 1.25;
983 // Generate random hex chars
984 $hex = MWCryptRand
::generateHex( $length );
985 // Convert from base 16 to base 32 to get a proper password like string
986 return wfBaseConvert( $hex, 16, 32 );
990 * Set cached properties to default.
992 * @note This no longer clears uncached lazy-initialised properties;
993 * the constructor does that instead.
995 * @param string|bool $name
997 public function loadDefaults( $name = false ) {
998 wfProfileIn( __METHOD__
);
1001 $this->mName
= $name;
1002 $this->mRealName
= '';
1003 $this->mPassword
= $this->mNewpassword
= '';
1004 $this->mNewpassTime
= null;
1006 $this->mOptionOverrides
= null;
1007 $this->mOptionsLoaded
= false;
1009 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1010 if ( $loggedOut !== null ) {
1011 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1013 $this->mTouched
= '1'; # Allow any pages to be cached
1016 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1017 $this->mEmailAuthenticated
= null;
1018 $this->mEmailToken
= '';
1019 $this->mEmailTokenExpires
= null;
1020 $this->mPasswordExpires
= null;
1021 $this->resetPasswordExpiration( false );
1022 $this->mRegistration
= wfTimestamp( TS_MW
);
1023 $this->mGroups
= array();
1025 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
1027 wfProfileOut( __METHOD__
);
1031 * Return whether an item has been loaded.
1033 * @param string $item Item to check. Current possibilities:
1037 * @param string $all 'all' to check if the whole object has been loaded
1038 * or any other string to check if only the item is available (e.g.
1042 public function isItemLoaded( $item, $all = 'all' ) {
1043 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1044 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1048 * Set that an item has been loaded
1050 * @param string $item
1052 protected function setItemLoaded( $item ) {
1053 if ( is_array( $this->mLoadedItems
) ) {
1054 $this->mLoadedItems
[$item] = true;
1059 * Load user data from the session or login cookie.
1060 * @return bool True if the user is logged in, false otherwise.
1062 private function loadFromSession() {
1064 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
1065 if ( $result !== null ) {
1069 $request = $this->getRequest();
1071 $cookieId = $request->getCookie( 'UserID' );
1072 $sessId = $request->getSessionData( 'wsUserID' );
1074 if ( $cookieId !== null ) {
1075 $sId = intval( $cookieId );
1076 if ( $sessId !== null && $cookieId != $sessId ) {
1077 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1078 cookie user ID ($sId) don't match!" );
1081 $request->setSessionData( 'wsUserID', $sId );
1082 } elseif ( $sessId !== null && $sessId != 0 ) {
1088 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1089 $sName = $request->getSessionData( 'wsUserName' );
1090 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1091 $sName = $request->getCookie( 'UserName' );
1092 $request->setSessionData( 'wsUserName', $sName );
1097 $proposedUser = User
::newFromId( $sId );
1098 if ( !$proposedUser->isLoggedIn() ) {
1103 global $wgBlockDisablesLogin;
1104 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1105 // User blocked and we've disabled blocked user logins
1109 if ( $request->getSessionData( 'wsToken' ) ) {
1111 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1113 } elseif ( $request->getCookie( 'Token' ) ) {
1114 # Get the token from DB/cache and clean it up to remove garbage padding.
1115 # This deals with historical problems with bugs and the default column value.
1116 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1117 // Make comparison in constant time (bug 61346)
1118 $passwordCorrect = strlen( $token )
1119 && hash_equals( $token, $request->getCookie( 'Token' ) );
1122 // No session or persistent login cookie
1126 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1127 $this->loadFromUserObject( $proposedUser );
1128 $request->setSessionData( 'wsToken', $this->mToken
);
1129 wfDebug( "User: logged in from $from\n" );
1132 // Invalid credentials
1133 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1139 * Load user and user_group data from the database.
1140 * $this->mId must be set, this is how the user is identified.
1142 * @param integer $flags Supports User::READ_LOCKING
1143 * @return bool True if the user exists, false if the user is anonymous
1145 public function loadFromDatabase( $flags = 0 ) {
1147 $this->mId
= intval( $this->mId
);
1150 if ( !$this->mId
) {
1151 $this->loadDefaults();
1155 $dbr = wfGetDB( DB_MASTER
);
1156 $s = $dbr->selectRow(
1158 self
::selectFields(),
1159 array( 'user_id' => $this->mId
),
1161 ( $flags & self
::READ_LOCKING
== self
::READ_LOCKING
)
1162 ?
array( 'LOCK IN SHARE MODE' )
1166 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1168 if ( $s !== false ) {
1169 // Initialise user table data
1170 $this->loadFromRow( $s );
1171 $this->mGroups
= null; // deferred
1172 $this->getEditCount(); // revalidation for nulls
1177 $this->loadDefaults();
1183 * Initialize this object from a row from the user table.
1185 * @param stdClass $row Row from the user table to load.
1186 * @param array $data Further user data to load into the object
1188 * user_groups Array with groups out of the user_groups table
1189 * user_properties Array with properties out of the user_properties table
1191 public function loadFromRow( $row, $data = null ) {
1194 $this->mGroups
= null; // deferred
1196 if ( isset( $row->user_name
) ) {
1197 $this->mName
= $row->user_name
;
1198 $this->mFrom
= 'name';
1199 $this->setItemLoaded( 'name' );
1204 if ( isset( $row->user_real_name
) ) {
1205 $this->mRealName
= $row->user_real_name
;
1206 $this->setItemLoaded( 'realname' );
1211 if ( isset( $row->user_id
) ) {
1212 $this->mId
= intval( $row->user_id
);
1213 $this->mFrom
= 'id';
1214 $this->setItemLoaded( 'id' );
1219 if ( isset( $row->user_editcount
) ) {
1220 $this->mEditCount
= $row->user_editcount
;
1225 if ( isset( $row->user_password
) ) {
1226 $this->mPassword
= $row->user_password
;
1227 $this->mNewpassword
= $row->user_newpassword
;
1228 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1229 $this->mEmail
= $row->user_email
;
1230 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1231 $this->mToken
= $row->user_token
;
1232 if ( $this->mToken
== '' ) {
1233 $this->mToken
= null;
1235 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1236 $this->mEmailToken
= $row->user_email_token
;
1237 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1238 $this->mPasswordExpires
= wfTimestampOrNull( TS_MW
, $row->user_password_expires
);
1239 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1245 $this->mLoadedItems
= true;
1248 if ( is_array( $data ) ) {
1249 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1250 $this->mGroups
= $data['user_groups'];
1252 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1253 $this->loadOptions( $data['user_properties'] );
1259 * Load the data for this user object from another user object.
1263 protected function loadFromUserObject( $user ) {
1265 $user->loadGroups();
1266 $user->loadOptions();
1267 foreach ( self
::$mCacheVars as $var ) {
1268 $this->$var = $user->$var;
1273 * Load the groups from the database if they aren't already loaded.
1275 private function loadGroups() {
1276 if ( is_null( $this->mGroups
) ) {
1277 $dbr = wfGetDB( DB_MASTER
);
1278 $res = $dbr->select( 'user_groups',
1279 array( 'ug_group' ),
1280 array( 'ug_user' => $this->mId
),
1282 $this->mGroups
= array();
1283 foreach ( $res as $row ) {
1284 $this->mGroups
[] = $row->ug_group
;
1290 * Add the user to the group if he/she meets given criteria.
1292 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1293 * possible to remove manually via Special:UserRights. In such case it
1294 * will not be re-added automatically. The user will also not lose the
1295 * group if they no longer meet the criteria.
1297 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1299 * @return array Array of groups the user has been promoted to.
1301 * @see $wgAutopromoteOnce
1303 public function addAutopromoteOnceGroups( $event ) {
1304 global $wgAutopromoteOnceLogInRC, $wgAuth;
1306 $toPromote = array();
1307 if ( $this->getId() ) {
1308 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1309 if ( count( $toPromote ) ) {
1310 $oldGroups = $this->getGroups(); // previous groups
1312 foreach ( $toPromote as $group ) {
1313 $this->addGroup( $group );
1315 // update groups in external authentication database
1316 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1318 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1320 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1321 $logEntry->setPerformer( $this );
1322 $logEntry->setTarget( $this->getUserPage() );
1323 $logEntry->setParameters( array(
1324 '4::oldgroups' => $oldGroups,
1325 '5::newgroups' => $newGroups,
1327 $logid = $logEntry->insert();
1328 if ( $wgAutopromoteOnceLogInRC ) {
1329 $logEntry->publish( $logid );
1337 * Clear various cached data stored in this object. The cache of the user table
1338 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1340 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1341 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1343 public function clearInstanceCache( $reloadFrom = false ) {
1344 $this->mNewtalk
= -1;
1345 $this->mDatePreference
= null;
1346 $this->mBlockedby
= -1; # Unset
1347 $this->mHash
= false;
1348 $this->mRights
= null;
1349 $this->mEffectiveGroups
= null;
1350 $this->mImplicitGroups
= null;
1351 $this->mGroups
= null;
1352 $this->mOptions
= null;
1353 $this->mOptionsLoaded
= false;
1354 $this->mEditCount
= null;
1356 if ( $reloadFrom ) {
1357 $this->mLoadedItems
= array();
1358 $this->mFrom
= $reloadFrom;
1363 * Combine the language default options with any site-specific options
1364 * and add the default language variants.
1366 * @return array Array of String options
1368 public static function getDefaultOptions() {
1369 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1371 static $defOpt = null;
1372 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1373 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1374 // mid-request and see that change reflected in the return value of this function.
1375 // Which is insane and would never happen during normal MW operation
1379 $defOpt = $wgDefaultUserOptions;
1380 // Default language setting
1381 $defOpt['language'] = $wgContLang->getCode();
1382 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1383 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1385 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1386 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1388 $defOpt['skin'] = $wgDefaultSkin;
1390 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1396 * Get a given default option value.
1398 * @param string $opt Name of option to retrieve
1399 * @return string Default option value
1401 public static function getDefaultOption( $opt ) {
1402 $defOpts = self
::getDefaultOptions();
1403 if ( isset( $defOpts[$opt] ) ) {
1404 return $defOpts[$opt];
1411 * Get blocking information
1412 * @param bool $bFromSlave Whether to check the slave database first.
1413 * To improve performance, non-critical checks are done against slaves.
1414 * Check when actually saving should be done against master.
1416 private function getBlockedStatus( $bFromSlave = true ) {
1417 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1419 if ( -1 != $this->mBlockedby
) {
1423 wfProfileIn( __METHOD__
);
1424 wfDebug( __METHOD__
. ": checking...\n" );
1426 // Initialize data...
1427 // Otherwise something ends up stomping on $this->mBlockedby when
1428 // things get lazy-loaded later, causing false positive block hits
1429 // due to -1 !== 0. Probably session-related... Nothing should be
1430 // overwriting mBlockedby, surely?
1433 # We only need to worry about passing the IP address to the Block generator if the
1434 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1435 # know which IP address they're actually coming from
1436 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1437 $ip = $this->getRequest()->getIP();
1443 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1446 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1447 && !in_array( $ip, $wgProxyWhitelist )
1450 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1452 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1453 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1454 $block->setTarget( $ip );
1455 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1457 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1458 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1459 $block->setTarget( $ip );
1463 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1464 if ( !$block instanceof Block
1465 && $wgApplyIpBlocksToXff
1467 && !$this->isAllowed( 'proxyunbannable' )
1468 && !in_array( $ip, $wgProxyWhitelist )
1470 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1471 $xff = array_map( 'trim', explode( ',', $xff ) );
1472 $xff = array_diff( $xff, array( $ip ) );
1473 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1474 $block = Block
::chooseBlock( $xffblocks, $xff );
1475 if ( $block instanceof Block
) {
1476 # Mangle the reason to alert the user that the block
1477 # originated from matching the X-Forwarded-For header.
1478 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1482 if ( $block instanceof Block
) {
1483 wfDebug( __METHOD__
. ": Found block.\n" );
1484 $this->mBlock
= $block;
1485 $this->mBlockedby
= $block->getByName();
1486 $this->mBlockreason
= $block->mReason
;
1487 $this->mHideName
= $block->mHideName
;
1488 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1490 $this->mBlockedby
= '';
1491 $this->mHideName
= 0;
1492 $this->mAllowUsertalk
= false;
1496 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1498 wfProfileOut( __METHOD__
);
1502 * Whether the given IP is in a DNS blacklist.
1504 * @param string $ip IP to check
1505 * @param bool $checkWhitelist Whether to check the whitelist first
1506 * @return bool True if blacklisted.
1508 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1509 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1511 if ( !$wgEnableDnsBlacklist ) {
1515 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1519 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1523 * Whether the given IP is in a given DNS blacklist.
1525 * @param string $ip IP to check
1526 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1527 * @return bool True if blacklisted.
1529 public function inDnsBlacklist( $ip, $bases ) {
1530 wfProfileIn( __METHOD__
);
1533 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1534 if ( IP
::isIPv4( $ip ) ) {
1535 // Reverse IP, bug 21255
1536 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1538 foreach ( (array)$bases as $base ) {
1540 // If we have an access key, use that too (ProjectHoneypot, etc.)
1541 if ( is_array( $base ) ) {
1542 if ( count( $base ) >= 2 ) {
1543 // Access key is 1, base URL is 0
1544 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1546 $host = "$ipReversed.{$base[0]}";
1549 $host = "$ipReversed.$base";
1553 $ipList = gethostbynamel( $host );
1556 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1560 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1565 wfProfileOut( __METHOD__
);
1570 * Check if an IP address is in the local proxy list
1576 public static function isLocallyBlockedProxy( $ip ) {
1577 global $wgProxyList;
1579 if ( !$wgProxyList ) {
1582 wfProfileIn( __METHOD__
);
1584 if ( !is_array( $wgProxyList ) ) {
1585 // Load from the specified file
1586 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1589 if ( !is_array( $wgProxyList ) ) {
1591 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1593 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1594 // Old-style flipped proxy list
1599 wfProfileOut( __METHOD__
);
1604 * Is this user subject to rate limiting?
1606 * @return bool True if rate limited
1608 public function isPingLimitable() {
1609 global $wgRateLimitsExcludedIPs;
1610 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1611 // No other good way currently to disable rate limits
1612 // for specific IPs. :P
1613 // But this is a crappy hack and should die.
1616 return !$this->isAllowed( 'noratelimit' );
1620 * Primitive rate limits: enforce maximum actions per time period
1621 * to put a brake on flooding.
1623 * The method generates both a generic profiling point and a per action one
1624 * (suffix being "-$action".
1626 * @note When using a shared cache like memcached, IP-address
1627 * last-hit counters will be shared across wikis.
1629 * @param string $action Action to enforce; 'edit' if unspecified
1630 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1631 * @return bool True if a rate limiter was tripped
1633 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1634 // Call the 'PingLimiter' hook
1636 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1640 global $wgRateLimits;
1641 if ( !isset( $wgRateLimits[$action] ) ) {
1645 // Some groups shouldn't trigger the ping limiter, ever
1646 if ( !$this->isPingLimitable() ) {
1651 wfProfileIn( __METHOD__
);
1652 wfProfileIn( __METHOD__
. '-' . $action );
1654 $limits = $wgRateLimits[$action];
1656 $id = $this->getId();
1659 if ( isset( $limits['anon'] ) && $id == 0 ) {
1660 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1663 if ( isset( $limits['user'] ) && $id != 0 ) {
1664 $userLimit = $limits['user'];
1666 if ( $this->isNewbie() ) {
1667 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1668 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1670 if ( isset( $limits['ip'] ) ) {
1671 $ip = $this->getRequest()->getIP();
1672 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1674 if ( isset( $limits['subnet'] ) ) {
1675 $ip = $this->getRequest()->getIP();
1678 if ( IP
::isIPv6( $ip ) ) {
1679 $parts = IP
::parseRange( "$ip/64" );
1680 $subnet = $parts[0];
1681 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1683 $subnet = $matches[1];
1685 if ( $subnet !== false ) {
1686 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1690 // Check for group-specific permissions
1691 // If more than one group applies, use the group with the highest limit
1692 foreach ( $this->getGroups() as $group ) {
1693 if ( isset( $limits[$group] ) ) {
1694 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1695 $userLimit = $limits[$group];
1699 // Set the user limit key
1700 if ( $userLimit !== false ) {
1701 list( $max, $period ) = $userLimit;
1702 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1703 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1707 foreach ( $keys as $key => $limit ) {
1708 list( $max, $period ) = $limit;
1709 $summary = "(limit $max in {$period}s)";
1710 $count = $wgMemc->get( $key );
1713 if ( $count >= $max ) {
1714 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1715 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1718 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1721 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1722 if ( $incrBy > 0 ) {
1723 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1726 if ( $incrBy > 0 ) {
1727 $wgMemc->incr( $key, $incrBy );
1731 wfProfileOut( __METHOD__
. '-' . $action );
1732 wfProfileOut( __METHOD__
);
1737 * Check if user is blocked
1739 * @param bool $bFromSlave Whether to check the slave database instead of
1740 * the master. Hacked from false due to horrible probs on site.
1741 * @return bool True if blocked, false otherwise
1743 public function isBlocked( $bFromSlave = true ) {
1744 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1748 * Get the block affecting the user, or null if the user is not blocked
1750 * @param bool $bFromSlave Whether to check the slave database instead of the master
1751 * @return Block|null
1753 public function getBlock( $bFromSlave = true ) {
1754 $this->getBlockedStatus( $bFromSlave );
1755 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1759 * Check if user is blocked from editing a particular article
1761 * @param Title $title Title to check
1762 * @param bool $bFromSlave Whether to check the slave database instead of the master
1765 public function isBlockedFrom( $title, $bFromSlave = false ) {
1766 global $wgBlockAllowsUTEdit;
1767 wfProfileIn( __METHOD__
);
1769 $blocked = $this->isBlocked( $bFromSlave );
1770 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1771 // If a user's name is suppressed, they cannot make edits anywhere
1772 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1773 && $title->getNamespace() == NS_USER_TALK
) {
1775 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1778 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1780 wfProfileOut( __METHOD__
);
1785 * If user is blocked, return the name of the user who placed the block
1786 * @return string Name of blocker
1788 public function blockedBy() {
1789 $this->getBlockedStatus();
1790 return $this->mBlockedby
;
1794 * If user is blocked, return the specified reason for the block
1795 * @return string Blocking reason
1797 public function blockedFor() {
1798 $this->getBlockedStatus();
1799 return $this->mBlockreason
;
1803 * If user is blocked, return the ID for the block
1804 * @return int Block ID
1806 public function getBlockId() {
1807 $this->getBlockedStatus();
1808 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1812 * Check if user is blocked on all wikis.
1813 * Do not use for actual edit permission checks!
1814 * This is intended for quick UI checks.
1816 * @param string $ip IP address, uses current client if none given
1817 * @return bool True if blocked, false otherwise
1819 public function isBlockedGlobally( $ip = '' ) {
1820 if ( $this->mBlockedGlobally
!== null ) {
1821 return $this->mBlockedGlobally
;
1823 // User is already an IP?
1824 if ( IP
::isIPAddress( $this->getName() ) ) {
1825 $ip = $this->getName();
1827 $ip = $this->getRequest()->getIP();
1830 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1831 $this->mBlockedGlobally
= (bool)$blocked;
1832 return $this->mBlockedGlobally
;
1836 * Check if user account is locked
1838 * @return bool True if locked, false otherwise
1840 public function isLocked() {
1841 if ( $this->mLocked
!== null ) {
1842 return $this->mLocked
;
1845 StubObject
::unstub( $wgAuth );
1846 $authUser = $wgAuth->getUserInstance( $this );
1847 $this->mLocked
= (bool)$authUser->isLocked();
1848 return $this->mLocked
;
1852 * Check if user account is hidden
1854 * @return bool True if hidden, false otherwise
1856 public function isHidden() {
1857 if ( $this->mHideName
!== null ) {
1858 return $this->mHideName
;
1860 $this->getBlockedStatus();
1861 if ( !$this->mHideName
) {
1863 StubObject
::unstub( $wgAuth );
1864 $authUser = $wgAuth->getUserInstance( $this );
1865 $this->mHideName
= (bool)$authUser->isHidden();
1867 return $this->mHideName
;
1871 * Get the user's ID.
1872 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1874 public function getId() {
1875 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1876 // Special case, we know the user is anonymous
1878 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1879 // Don't load if this was initialized from an ID
1886 * Set the user and reload all fields according to a given ID
1887 * @param int $v User ID to reload
1889 public function setId( $v ) {
1891 $this->clearInstanceCache( 'id' );
1895 * Get the user name, or the IP of an anonymous user
1896 * @return string User's name or IP address
1898 public function getName() {
1899 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1900 // Special case optimisation
1901 return $this->mName
;
1904 if ( $this->mName
=== false ) {
1906 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1908 return $this->mName
;
1913 * Set the user name.
1915 * This does not reload fields from the database according to the given
1916 * name. Rather, it is used to create a temporary "nonexistent user" for
1917 * later addition to the database. It can also be used to set the IP
1918 * address for an anonymous user to something other than the current
1921 * @note User::newFromName() has roughly the same function, when the named user
1923 * @param string $str New user name to set
1925 public function setName( $str ) {
1927 $this->mName
= $str;
1931 * Get the user's name escaped by underscores.
1932 * @return string Username escaped by underscores.
1934 public function getTitleKey() {
1935 return str_replace( ' ', '_', $this->getName() );
1939 * Check if the user has new messages.
1940 * @return bool True if the user has new messages
1942 public function getNewtalk() {
1945 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1946 if ( $this->mNewtalk
=== -1 ) {
1947 $this->mNewtalk
= false; # reset talk page status
1949 // Check memcached separately for anons, who have no
1950 // entire User object stored in there.
1951 if ( !$this->mId
) {
1952 global $wgDisableAnonTalk;
1953 if ( $wgDisableAnonTalk ) {
1954 // Anon newtalk disabled by configuration.
1955 $this->mNewtalk
= false;
1958 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1959 $newtalk = $wgMemc->get( $key );
1960 if ( strval( $newtalk ) !== '' ) {
1961 $this->mNewtalk
= (bool)$newtalk;
1963 // Since we are caching this, make sure it is up to date by getting it
1965 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1966 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1970 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1974 return (bool)$this->mNewtalk
;
1978 * Return the data needed to construct links for new talk page message
1979 * alerts. If there are new messages, this will return an associative array
1980 * with the following data:
1981 * wiki: The database name of the wiki
1982 * link: Root-relative link to the user's talk page
1983 * rev: The last talk page revision that the user has seen or null. This
1984 * is useful for building diff links.
1985 * If there are no new messages, it returns an empty array.
1986 * @note This function was designed to accomodate multiple talk pages, but
1987 * currently only returns a single link and revision.
1990 public function getNewMessageLinks() {
1992 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
1994 } elseif ( !$this->getNewtalk() ) {
1997 $utp = $this->getTalkPage();
1998 $dbr = wfGetDB( DB_SLAVE
);
1999 // Get the "last viewed rev" timestamp from the oldest message notification
2000 $timestamp = $dbr->selectField( 'user_newtalk',
2001 'MIN(user_last_timestamp)',
2002 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2004 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2005 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2009 * Get the revision ID for the last talk page revision viewed by the talk
2011 * @return int|null Revision ID or null
2013 public function getNewMessageRevisionId() {
2014 $newMessageRevisionId = null;
2015 $newMessageLinks = $this->getNewMessageLinks();
2016 if ( $newMessageLinks ) {
2017 // Note: getNewMessageLinks() never returns more than a single link
2018 // and it is always for the same wiki, but we double-check here in
2019 // case that changes some time in the future.
2020 if ( count( $newMessageLinks ) === 1
2021 && $newMessageLinks[0]['wiki'] === wfWikiID()
2022 && $newMessageLinks[0]['rev']
2024 $newMessageRevision = $newMessageLinks[0]['rev'];
2025 $newMessageRevisionId = $newMessageRevision->getId();
2028 return $newMessageRevisionId;
2032 * Internal uncached check for new messages
2035 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2036 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2037 * @param bool $fromMaster true to fetch from the master, false for a slave
2038 * @return bool True if the user has new messages
2040 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2041 if ( $fromMaster ) {
2042 $db = wfGetDB( DB_MASTER
);
2044 $db = wfGetDB( DB_SLAVE
);
2046 $ok = $db->selectField( 'user_newtalk', $field,
2047 array( $field => $id ), __METHOD__
);
2048 return $ok !== false;
2052 * Add or update the new messages flag
2053 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2054 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2055 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2056 * @return bool True if successful, false otherwise
2058 protected function updateNewtalk( $field, $id, $curRev = null ) {
2059 // Get timestamp of the talk page revision prior to the current one
2060 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2061 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2062 // Mark the user as having new messages since this revision
2063 $dbw = wfGetDB( DB_MASTER
);
2064 $dbw->insert( 'user_newtalk',
2065 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2068 if ( $dbw->affectedRows() ) {
2069 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2072 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2078 * Clear the new messages flag for the given user
2079 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2080 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2081 * @return bool True if successful, false otherwise
2083 protected function deleteNewtalk( $field, $id ) {
2084 $dbw = wfGetDB( DB_MASTER
);
2085 $dbw->delete( 'user_newtalk',
2086 array( $field => $id ),
2088 if ( $dbw->affectedRows() ) {
2089 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2092 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2098 * Update the 'You have new messages!' status.
2099 * @param bool $val Whether the user has new messages
2100 * @param Revision $curRev New, as yet unseen revision of the user talk
2101 * page. Ignored if null or !$val.
2103 public function setNewtalk( $val, $curRev = null ) {
2104 if ( wfReadOnly() ) {
2109 $this->mNewtalk
= $val;
2111 if ( $this->isAnon() ) {
2113 $id = $this->getName();
2116 $id = $this->getId();
2121 $changed = $this->updateNewtalk( $field, $id, $curRev );
2123 $changed = $this->deleteNewtalk( $field, $id );
2126 if ( $this->isAnon() ) {
2127 // Anons have a separate memcached space, since
2128 // user records aren't kept for them.
2129 $key = wfMemcKey( 'newtalk', 'ip', $id );
2130 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
2133 $this->invalidateCache();
2138 * Generate a current or new-future timestamp to be stored in the
2139 * user_touched field when we update things.
2140 * @return string Timestamp in TS_MW format
2142 private static function newTouchedTimestamp() {
2143 global $wgClockSkewFudge;
2144 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2148 * Clear user data from memcached.
2149 * Use after applying fun updates to the database; caller's
2150 * responsibility to update user_touched if appropriate.
2152 * Called implicitly from invalidateCache() and saveSettings().
2154 private function clearSharedCache() {
2158 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
2163 * Immediately touch the user data cache for this account.
2164 * Updates user_touched field, and removes account data from memcached
2165 * for reload on the next hit.
2167 public function invalidateCache() {
2168 if ( wfReadOnly() ) {
2173 $this->mTouched
= self
::newTouchedTimestamp();
2175 $dbw = wfGetDB( DB_MASTER
);
2176 $userid = $this->mId
;
2177 $touched = $this->mTouched
;
2178 $method = __METHOD__
;
2179 $dbw->onTransactionIdle( function () use ( $dbw, $userid, $touched, $method ) {
2180 // Prevent contention slams by checking user_touched first
2181 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2182 $needsPurge = $dbw->selectField( 'user', '1',
2183 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2184 if ( $needsPurge ) {
2185 $dbw->update( 'user',
2186 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2187 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2192 $this->clearSharedCache();
2197 * Validate the cache for this account.
2198 * @param string $timestamp A timestamp in TS_MW format
2201 public function validateCache( $timestamp ) {
2203 return ( $timestamp >= $this->mTouched
);
2207 * Get the user touched timestamp
2208 * @return string Timestamp
2210 public function getTouched() {
2212 return $this->mTouched
;
2216 * Set the password and reset the random token.
2217 * Calls through to authentication plugin if necessary;
2218 * will have no effect if the auth plugin refuses to
2219 * pass the change through or if the legal password
2222 * As a special case, setting the password to null
2223 * wipes it, so the account cannot be logged in until
2224 * a new password is set, for instance via e-mail.
2226 * @param string $str New password to set
2227 * @throws PasswordError on failure
2231 public function setPassword( $str ) {
2234 if ( $str !== null ) {
2235 if ( !$wgAuth->allowPasswordChange() ) {
2236 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2239 if ( !$this->isValidPassword( $str ) ) {
2240 global $wgMinimalPasswordLength;
2241 $valid = $this->getPasswordValidity( $str );
2242 if ( is_array( $valid ) ) {
2243 $message = array_shift( $valid );
2247 $params = array( $wgMinimalPasswordLength );
2249 throw new PasswordError( wfMessage( $message, $params )->text() );
2253 if ( !$wgAuth->setPassword( $this, $str ) ) {
2254 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2257 $this->setInternalPassword( $str );
2263 * Set the password and reset the random token unconditionally.
2265 * @param string|null $str New password to set or null to set an invalid
2266 * password hash meaning that the user will not be able to log in
2267 * through the web interface.
2269 public function setInternalPassword( $str ) {
2273 if ( $str === null ) {
2274 // Save an invalid hash...
2275 $this->mPassword
= '';
2277 $this->mPassword
= self
::crypt( $str );
2279 $this->mNewpassword
= '';
2280 $this->mNewpassTime
= null;
2284 * Get the user's current token.
2285 * @param bool $forceCreation Force the generation of a new token if the
2286 * user doesn't have one (default=true for backwards compatibility).
2287 * @return string Token
2289 public function getToken( $forceCreation = true ) {
2291 if ( !$this->mToken
&& $forceCreation ) {
2294 return $this->mToken
;
2298 * Set the random token (used for persistent authentication)
2299 * Called from loadDefaults() among other places.
2301 * @param string|bool $token If specified, set the token to this value
2303 public function setToken( $token = false ) {
2306 $this->mToken
= MWCryptRand
::generateHex( USER_TOKEN_LENGTH
);
2308 $this->mToken
= $token;
2313 * Set the password for a password reminder or new account email
2315 * @param string $str New password to set or null to set an invalid
2316 * password hash meaning that the user will not be able to use it
2317 * @param bool $throttle If true, reset the throttle timestamp to the present
2319 public function setNewpassword( $str, $throttle = true ) {
2322 if ( $str === null ) {
2323 $this->mNewpassword
= '';
2324 $this->mNewpassTime
= null;
2326 $this->mNewpassword
= self
::crypt( $str );
2328 $this->mNewpassTime
= wfTimestampNow();
2334 * Has password reminder email been sent within the last
2335 * $wgPasswordReminderResendTime hours?
2338 public function isPasswordReminderThrottled() {
2339 global $wgPasswordReminderResendTime;
2341 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2344 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2345 return time() < $expiry;
2349 * Get the user's e-mail address
2350 * @return string User's email address
2352 public function getEmail() {
2354 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
2355 return $this->mEmail
;
2359 * Get the timestamp of the user's e-mail authentication
2360 * @return string TS_MW timestamp
2362 public function getEmailAuthenticationTimestamp() {
2364 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2365 return $this->mEmailAuthenticated
;
2369 * Set the user's e-mail address
2370 * @param string $str New e-mail address
2372 public function setEmail( $str ) {
2374 if ( $str == $this->mEmail
) {
2377 $this->mEmail
= $str;
2378 $this->invalidateEmail();
2379 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
2383 * Set the user's e-mail address and a confirmation mail if needed.
2386 * @param string $str New e-mail address
2389 public function setEmailWithConfirmation( $str ) {
2390 global $wgEnableEmail, $wgEmailAuthentication;
2392 if ( !$wgEnableEmail ) {
2393 return Status
::newFatal( 'emaildisabled' );
2396 $oldaddr = $this->getEmail();
2397 if ( $str === $oldaddr ) {
2398 return Status
::newGood( true );
2401 $this->setEmail( $str );
2403 if ( $str !== '' && $wgEmailAuthentication ) {
2404 // Send a confirmation request to the new address if needed
2405 $type = $oldaddr != '' ?
'changed' : 'set';
2406 $result = $this->sendConfirmationMail( $type );
2407 if ( $result->isGood() ) {
2408 // Say the the caller that a confirmation mail has been sent
2409 $result->value
= 'eauth';
2412 $result = Status
::newGood( true );
2419 * Get the user's real name
2420 * @return string User's real name
2422 public function getRealName() {
2423 if ( !$this->isItemLoaded( 'realname' ) ) {
2427 return $this->mRealName
;
2431 * Set the user's real name
2432 * @param string $str New real name
2434 public function setRealName( $str ) {
2436 $this->mRealName
= $str;
2440 * Get the user's current setting for a given option.
2442 * @param string $oname The option to check
2443 * @param string $defaultOverride A default value returned if the option does not exist
2444 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2445 * @return string User's current value for the option
2446 * @see getBoolOption()
2447 * @see getIntOption()
2449 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2450 global $wgHiddenPrefs;
2451 $this->loadOptions();
2453 # We want 'disabled' preferences to always behave as the default value for
2454 # users, even if they have set the option explicitly in their settings (ie they
2455 # set it, and then it was disabled removing their ability to change it). But
2456 # we don't want to erase the preferences in the database in case the preference
2457 # is re-enabled again. So don't touch $mOptions, just override the returned value
2458 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2459 return self
::getDefaultOption( $oname );
2462 if ( array_key_exists( $oname, $this->mOptions
) ) {
2463 return $this->mOptions
[$oname];
2465 return $defaultOverride;
2470 * Get all user's options
2474 public function getOptions() {
2475 global $wgHiddenPrefs;
2476 $this->loadOptions();
2477 $options = $this->mOptions
;
2479 # We want 'disabled' preferences to always behave as the default value for
2480 # users, even if they have set the option explicitly in their settings (ie they
2481 # set it, and then it was disabled removing their ability to change it). But
2482 # we don't want to erase the preferences in the database in case the preference
2483 # is re-enabled again. So don't touch $mOptions, just override the returned value
2484 foreach ( $wgHiddenPrefs as $pref ) {
2485 $default = self
::getDefaultOption( $pref );
2486 if ( $default !== null ) {
2487 $options[$pref] = $default;
2495 * Get the user's current setting for a given option, as a boolean value.
2497 * @param string $oname The option to check
2498 * @return bool User's current value for the option
2501 public function getBoolOption( $oname ) {
2502 return (bool)$this->getOption( $oname );
2506 * Get the user's current setting for a given option, as an integer value.
2508 * @param string $oname The option to check
2509 * @param int $defaultOverride A default value returned if the option does not exist
2510 * @return int User's current value for the option
2513 public function getIntOption( $oname, $defaultOverride = 0 ) {
2514 $val = $this->getOption( $oname );
2516 $val = $defaultOverride;
2518 return intval( $val );
2522 * Set the given option for a user.
2524 * You need to call saveSettings() to actually write to the database.
2526 * @param string $oname The option to set
2527 * @param mixed $val New value to set
2529 public function setOption( $oname, $val ) {
2530 $this->loadOptions();
2532 // Explicitly NULL values should refer to defaults
2533 if ( is_null( $val ) ) {
2534 $val = self
::getDefaultOption( $oname );
2537 $this->mOptions
[$oname] = $val;
2541 * Get a token stored in the preferences (like the watchlist one),
2542 * resetting it if it's empty (and saving changes).
2544 * @param string $oname The option name to retrieve the token from
2545 * @return string|bool User's current value for the option, or false if this option is disabled.
2546 * @see resetTokenFromOption()
2549 public function getTokenFromOption( $oname ) {
2550 global $wgHiddenPrefs;
2551 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2555 $token = $this->getOption( $oname );
2557 $token = $this->resetTokenFromOption( $oname );
2558 $this->saveSettings();
2564 * Reset a token stored in the preferences (like the watchlist one).
2565 * *Does not* save user's preferences (similarly to setOption()).
2567 * @param string $oname The option name to reset the token in
2568 * @return string|bool New token value, or false if this option is disabled.
2569 * @see getTokenFromOption()
2572 public function resetTokenFromOption( $oname ) {
2573 global $wgHiddenPrefs;
2574 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2578 $token = MWCryptRand
::generateHex( 40 );
2579 $this->setOption( $oname, $token );
2584 * Return a list of the types of user options currently returned by
2585 * User::getOptionKinds().
2587 * Currently, the option kinds are:
2588 * - 'registered' - preferences which are registered in core MediaWiki or
2589 * by extensions using the UserGetDefaultOptions hook.
2590 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2591 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2592 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2593 * be used by user scripts.
2594 * - 'special' - "preferences" that are not accessible via User::getOptions
2595 * or User::setOptions.
2596 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2597 * These are usually legacy options, removed in newer versions.
2599 * The API (and possibly others) use this function to determine the possible
2600 * option types for validation purposes, so make sure to update this when a
2601 * new option kind is added.
2603 * @see User::getOptionKinds
2604 * @return array Option kinds
2606 public static function listOptionKinds() {
2609 'registered-multiselect',
2610 'registered-checkmatrix',
2618 * Return an associative array mapping preferences keys to the kind of a preference they're
2619 * used for. Different kinds are handled differently when setting or reading preferences.
2621 * See User::listOptionKinds for the list of valid option types that can be provided.
2623 * @see User::listOptionKinds
2624 * @param IContextSource $context
2625 * @param array $options Assoc. array with options keys to check as keys.
2626 * Defaults to $this->mOptions.
2627 * @return array the key => kind mapping data
2629 public function getOptionKinds( IContextSource
$context, $options = null ) {
2630 $this->loadOptions();
2631 if ( $options === null ) {
2632 $options = $this->mOptions
;
2635 $prefs = Preferences
::getPreferences( $this, $context );
2638 // Pull out the "special" options, so they don't get converted as
2639 // multiselect or checkmatrix.
2640 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2641 foreach ( $specialOptions as $name => $value ) {
2642 unset( $prefs[$name] );
2645 // Multiselect and checkmatrix options are stored in the database with
2646 // one key per option, each having a boolean value. Extract those keys.
2647 $multiselectOptions = array();
2648 foreach ( $prefs as $name => $info ) {
2649 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2650 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2651 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2652 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2654 foreach ( $opts as $value ) {
2655 $multiselectOptions["$prefix$value"] = true;
2658 unset( $prefs[$name] );
2661 $checkmatrixOptions = array();
2662 foreach ( $prefs as $name => $info ) {
2663 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2664 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2665 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2666 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2667 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2669 foreach ( $columns as $column ) {
2670 foreach ( $rows as $row ) {
2671 $checkmatrixOptions["$prefix-$column-$row"] = true;
2675 unset( $prefs[$name] );
2679 // $value is ignored
2680 foreach ( $options as $key => $value ) {
2681 if ( isset( $prefs[$key] ) ) {
2682 $mapping[$key] = 'registered';
2683 } elseif ( isset( $multiselectOptions[$key] ) ) {
2684 $mapping[$key] = 'registered-multiselect';
2685 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2686 $mapping[$key] = 'registered-checkmatrix';
2687 } elseif ( isset( $specialOptions[$key] ) ) {
2688 $mapping[$key] = 'special';
2689 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2690 $mapping[$key] = 'userjs';
2692 $mapping[$key] = 'unused';
2700 * Reset certain (or all) options to the site defaults
2702 * The optional parameter determines which kinds of preferences will be reset.
2703 * Supported values are everything that can be reported by getOptionKinds()
2704 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2706 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2707 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2708 * for backwards-compatibility.
2709 * @param IContextSource|null $context Context source used when $resetKinds
2710 * does not contain 'all', passed to getOptionKinds().
2711 * Defaults to RequestContext::getMain() when null.
2713 public function resetOptions(
2714 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2715 IContextSource
$context = null
2718 $defaultOptions = self
::getDefaultOptions();
2720 if ( !is_array( $resetKinds ) ) {
2721 $resetKinds = array( $resetKinds );
2724 if ( in_array( 'all', $resetKinds ) ) {
2725 $newOptions = $defaultOptions;
2727 if ( $context === null ) {
2728 $context = RequestContext
::getMain();
2731 $optionKinds = $this->getOptionKinds( $context );
2732 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2733 $newOptions = array();
2735 // Use default values for the options that should be deleted, and
2736 // copy old values for the ones that shouldn't.
2737 foreach ( $this->mOptions
as $key => $value ) {
2738 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2739 if ( array_key_exists( $key, $defaultOptions ) ) {
2740 $newOptions[$key] = $defaultOptions[$key];
2743 $newOptions[$key] = $value;
2748 wfRunHooks( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2750 $this->mOptions
= $newOptions;
2751 $this->mOptionsLoaded
= true;
2755 * Get the user's preferred date format.
2756 * @return string User's preferred date format
2758 public function getDatePreference() {
2759 // Important migration for old data rows
2760 if ( is_null( $this->mDatePreference
) ) {
2762 $value = $this->getOption( 'date' );
2763 $map = $wgLang->getDatePreferenceMigrationMap();
2764 if ( isset( $map[$value] ) ) {
2765 $value = $map[$value];
2767 $this->mDatePreference
= $value;
2769 return $this->mDatePreference
;
2773 * Determine based on the wiki configuration and the user's options,
2774 * whether this user must be over HTTPS no matter what.
2778 public function requiresHTTPS() {
2779 global $wgSecureLogin;
2780 if ( !$wgSecureLogin ) {
2783 $https = $this->getBoolOption( 'prefershttps' );
2784 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2786 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2793 * Get the user preferred stub threshold
2797 public function getStubThreshold() {
2798 global $wgMaxArticleSize; # Maximum article size, in Kb
2799 $threshold = $this->getIntOption( 'stubthreshold' );
2800 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2801 // If they have set an impossible value, disable the preference
2802 // so we can use the parser cache again.
2809 * Get the permissions this user has.
2810 * @return array Array of String permission names
2812 public function getRights() {
2813 if ( is_null( $this->mRights
) ) {
2814 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2815 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2816 // Force reindexation of rights when a hook has unset one of them
2817 $this->mRights
= array_values( array_unique( $this->mRights
) );
2819 return $this->mRights
;
2823 * Get the list of explicit group memberships this user has.
2824 * The implicit * and user groups are not included.
2825 * @return array Array of String internal group names
2827 public function getGroups() {
2829 $this->loadGroups();
2830 return $this->mGroups
;
2834 * Get the list of implicit group memberships this user has.
2835 * This includes all explicit groups, plus 'user' if logged in,
2836 * '*' for all accounts, and autopromoted groups
2837 * @param bool $recache Whether to avoid the cache
2838 * @return array Array of String internal group names
2840 public function getEffectiveGroups( $recache = false ) {
2841 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2842 wfProfileIn( __METHOD__
);
2843 $this->mEffectiveGroups
= array_unique( array_merge(
2844 $this->getGroups(), // explicit groups
2845 $this->getAutomaticGroups( $recache ) // implicit groups
2847 // Hook for additional groups
2848 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2849 // Force reindexation of groups when a hook has unset one of them
2850 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
2851 wfProfileOut( __METHOD__
);
2853 return $this->mEffectiveGroups
;
2857 * Get the list of implicit group memberships this user has.
2858 * This includes 'user' if logged in, '*' for all accounts,
2859 * and autopromoted groups
2860 * @param bool $recache Whether to avoid the cache
2861 * @return array Array of String internal group names
2863 public function getAutomaticGroups( $recache = false ) {
2864 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
2865 wfProfileIn( __METHOD__
);
2866 $this->mImplicitGroups
= array( '*' );
2867 if ( $this->getId() ) {
2868 $this->mImplicitGroups
[] = 'user';
2870 $this->mImplicitGroups
= array_unique( array_merge(
2871 $this->mImplicitGroups
,
2872 Autopromote
::getAutopromoteGroups( $this )
2876 // Assure data consistency with rights/groups,
2877 // as getEffectiveGroups() depends on this function
2878 $this->mEffectiveGroups
= null;
2880 wfProfileOut( __METHOD__
);
2882 return $this->mImplicitGroups
;
2886 * Returns the groups the user has belonged to.
2888 * The user may still belong to the returned groups. Compare with getGroups().
2890 * The function will not return groups the user had belonged to before MW 1.17
2892 * @return array Names of the groups the user has belonged to.
2894 public function getFormerGroups() {
2895 if ( is_null( $this->mFormerGroups
) ) {
2896 $dbr = wfGetDB( DB_MASTER
);
2897 $res = $dbr->select( 'user_former_groups',
2898 array( 'ufg_group' ),
2899 array( 'ufg_user' => $this->mId
),
2901 $this->mFormerGroups
= array();
2902 foreach ( $res as $row ) {
2903 $this->mFormerGroups
[] = $row->ufg_group
;
2906 return $this->mFormerGroups
;
2910 * Get the user's edit count.
2911 * @return int|null null for anonymous users
2913 public function getEditCount() {
2914 if ( !$this->getId() ) {
2918 if ( $this->mEditCount
=== null ) {
2919 /* Populate the count, if it has not been populated yet */
2920 wfProfileIn( __METHOD__
);
2921 $dbr = wfGetDB( DB_SLAVE
);
2922 // check if the user_editcount field has been initialized
2923 $count = $dbr->selectField(
2924 'user', 'user_editcount',
2925 array( 'user_id' => $this->mId
),
2929 if ( $count === null ) {
2930 // it has not been initialized. do so.
2931 $count = $this->initEditCount();
2933 $this->mEditCount
= $count;
2934 wfProfileOut( __METHOD__
);
2936 return (int)$this->mEditCount
;
2940 * Add the user to the given group.
2941 * This takes immediate effect.
2942 * @param string $group Name of the group to add
2944 public function addGroup( $group ) {
2945 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2946 $dbw = wfGetDB( DB_MASTER
);
2947 if ( $this->getId() ) {
2948 $dbw->insert( 'user_groups',
2950 'ug_user' => $this->getID(),
2951 'ug_group' => $group,
2954 array( 'IGNORE' ) );
2957 $this->loadGroups();
2958 $this->mGroups
[] = $group;
2959 // In case loadGroups was not called before, we now have the right twice.
2960 // Get rid of the duplicate.
2961 $this->mGroups
= array_unique( $this->mGroups
);
2963 // Refresh the groups caches, and clear the rights cache so it will be
2964 // refreshed on the next call to $this->getRights().
2965 $this->getEffectiveGroups( true );
2966 $this->mRights
= null;
2968 $this->invalidateCache();
2972 * Remove the user from the given group.
2973 * This takes immediate effect.
2974 * @param string $group Name of the group to remove
2976 public function removeGroup( $group ) {
2978 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2979 $dbw = wfGetDB( DB_MASTER
);
2980 $dbw->delete( 'user_groups',
2982 'ug_user' => $this->getID(),
2983 'ug_group' => $group,
2985 // Remember that the user was in this group
2986 $dbw->insert( 'user_former_groups',
2988 'ufg_user' => $this->getID(),
2989 'ufg_group' => $group,
2992 array( 'IGNORE' ) );
2994 $this->loadGroups();
2995 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2997 // Refresh the groups caches, and clear the rights cache so it will be
2998 // refreshed on the next call to $this->getRights().
2999 $this->getEffectiveGroups( true );
3000 $this->mRights
= null;
3002 $this->invalidateCache();
3006 * Get whether the user is logged in
3009 public function isLoggedIn() {
3010 return $this->getID() != 0;
3014 * Get whether the user is anonymous
3017 public function isAnon() {
3018 return !$this->isLoggedIn();
3022 * Check if user is allowed to access a feature / make an action
3024 * @internal param \String $varargs permissions to test
3025 * @return bool True if user is allowed to perform *any* of the given actions
3029 public function isAllowedAny( /*...*/ ) {
3030 $permissions = func_get_args();
3031 foreach ( $permissions as $permission ) {
3032 if ( $this->isAllowed( $permission ) ) {
3041 * @internal param $varargs string
3042 * @return bool True if the user is allowed to perform *all* of the given actions
3044 public function isAllowedAll( /*...*/ ) {
3045 $permissions = func_get_args();
3046 foreach ( $permissions as $permission ) {
3047 if ( !$this->isAllowed( $permission ) ) {
3055 * Internal mechanics of testing a permission
3056 * @param string $action
3059 public function isAllowed( $action = '' ) {
3060 if ( $action === '' ) {
3061 return true; // In the spirit of DWIM
3063 // Patrolling may not be enabled
3064 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3065 global $wgUseRCPatrol, $wgUseNPPatrol;
3066 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3070 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3071 // by misconfiguration: 0 == 'foo'
3072 return in_array( $action, $this->getRights(), true );
3076 * Check whether to enable recent changes patrol features for this user
3077 * @return bool True or false
3079 public function useRCPatrol() {
3080 global $wgUseRCPatrol;
3081 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3085 * Check whether to enable new pages patrol features for this user
3086 * @return bool True or false
3088 public function useNPPatrol() {
3089 global $wgUseRCPatrol, $wgUseNPPatrol;
3091 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3092 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3097 * Get the WebRequest object to use with this object
3099 * @return WebRequest
3101 public function getRequest() {
3102 if ( $this->mRequest
) {
3103 return $this->mRequest
;
3111 * Get the current skin, loading it if required
3112 * @return Skin The current skin
3113 * @todo FIXME: Need to check the old failback system [AV]
3114 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3116 public function getSkin() {
3117 wfDeprecated( __METHOD__
, '1.18' );
3118 return RequestContext
::getMain()->getSkin();
3122 * Get a WatchedItem for this user and $title.
3124 * @since 1.22 $checkRights parameter added
3125 * @param Title $title
3126 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3127 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3128 * @return WatchedItem
3130 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3131 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3133 if ( isset( $this->mWatchedItems
[$key] ) ) {
3134 return $this->mWatchedItems
[$key];
3137 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3138 $this->mWatchedItems
= array();
3141 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3142 return $this->mWatchedItems
[$key];
3146 * Check the watched status of an article.
3147 * @since 1.22 $checkRights parameter added
3148 * @param Title $title Title of the article to look at
3149 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3150 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3153 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3154 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3159 * @since 1.22 $checkRights parameter added
3160 * @param Title $title Title of the article to look at
3161 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3162 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3164 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3165 $this->getWatchedItem( $title, $checkRights )->addWatch();
3166 $this->invalidateCache();
3170 * Stop watching an article.
3171 * @since 1.22 $checkRights parameter added
3172 * @param Title $title Title of the article to look at
3173 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3174 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3176 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3177 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3178 $this->invalidateCache();
3182 * Clear the user's notification timestamp for the given title.
3183 * If e-notif e-mails are on, they will receive notification mails on
3184 * the next change of the page if it's watched etc.
3185 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3186 * @param Title $title Title of the article to look at
3187 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3189 public function clearNotification( &$title, $oldid = 0 ) {
3190 global $wgUseEnotif, $wgShowUpdatedMarker;
3192 // Do nothing if the database is locked to writes
3193 if ( wfReadOnly() ) {
3197 // Do nothing if not allowed to edit the watchlist
3198 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3202 // If we're working on user's talk page, we should update the talk page message indicator
3203 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3204 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3208 $nextid = $oldid ?
$title->getNextRevisionID( $oldid ) : null;
3210 if ( !$oldid ||
!$nextid ) {
3211 // If we're looking at the latest revision, we should definitely clear it
3212 $this->setNewtalk( false );
3214 // Otherwise we should update its revision, if it's present
3215 if ( $this->getNewtalk() ) {
3216 // Naturally the other one won't clear by itself
3217 $this->setNewtalk( false );
3218 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3223 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3227 if ( $this->isAnon() ) {
3228 // Nothing else to do...
3232 // Only update the timestamp if the page is being watched.
3233 // The query to find out if it is watched is cached both in memcached and per-invocation,
3234 // and when it does have to be executed, it can be on a slave
3235 // If this is the user's newtalk page, we always update the timestamp
3237 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3241 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3245 * Resets all of the given user's page-change notification timestamps.
3246 * If e-notif e-mails are on, they will receive notification mails on
3247 * the next change of any watched page.
3248 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3250 public function clearAllNotifications() {
3251 if ( wfReadOnly() ) {
3255 // Do nothing if not allowed to edit the watchlist
3256 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3260 global $wgUseEnotif, $wgShowUpdatedMarker;
3261 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3262 $this->setNewtalk( false );
3265 $id = $this->getId();
3267 $dbw = wfGetDB( DB_MASTER
);
3268 $dbw->update( 'watchlist',
3269 array( /* SET */ 'wl_notificationtimestamp' => null ),
3270 array( /* WHERE */ 'wl_user' => $id ),
3273 // We also need to clear here the "you have new message" notification for the own user_talk page;
3274 // it's cleared one page view later in WikiPage::doViewUpdates().
3279 * Set a cookie on the user's client. Wrapper for
3280 * WebResponse::setCookie
3281 * @param string $name Name of the cookie to set
3282 * @param string $value Value to set
3283 * @param int $exp Expiration time, as a UNIX time value;
3284 * if 0 or not specified, use the default $wgCookieExpiration
3285 * @param bool $secure
3286 * true: Force setting the secure attribute when setting the cookie
3287 * false: Force NOT setting the secure attribute when setting the cookie
3288 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3289 * @param array $params Array of options sent passed to WebResponse::setcookie()
3291 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3292 $params['secure'] = $secure;
3293 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3297 * Clear a cookie on the user's client
3298 * @param string $name Name of the cookie to clear
3299 * @param bool $secure
3300 * true: Force setting the secure attribute when setting the cookie
3301 * false: Force NOT setting the secure attribute when setting the cookie
3302 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3303 * @param array $params Array of options sent passed to WebResponse::setcookie()
3305 protected function clearCookie( $name, $secure = null, $params = array() ) {
3306 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3310 * Set the default cookies for this session on the user's client.
3312 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3314 * @param bool $secure Whether to force secure/insecure cookies or use default
3315 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3317 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3318 if ( $request === null ) {
3319 $request = $this->getRequest();
3323 if ( 0 == $this->mId
) {
3326 if ( !$this->mToken
) {
3327 // When token is empty or NULL generate a new one and then save it to the database
3328 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3329 // Simply by setting every cell in the user_token column to NULL and letting them be
3330 // regenerated as users log back into the wiki.
3332 $this->saveSettings();
3335 'wsUserID' => $this->mId
,
3336 'wsToken' => $this->mToken
,
3337 'wsUserName' => $this->getName()
3340 'UserID' => $this->mId
,
3341 'UserName' => $this->getName(),
3343 if ( $rememberMe ) {
3344 $cookies['Token'] = $this->mToken
;
3346 $cookies['Token'] = false;
3349 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3351 foreach ( $session as $name => $value ) {
3352 $request->setSessionData( $name, $value );
3354 foreach ( $cookies as $name => $value ) {
3355 if ( $value === false ) {
3356 $this->clearCookie( $name );
3358 $this->setCookie( $name, $value, 0, $secure );
3363 * If wpStickHTTPS was selected, also set an insecure cookie that
3364 * will cause the site to redirect the user to HTTPS, if they access
3365 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3366 * as the one set by centralauth (bug 53538). Also set it to session, or
3367 * standard time setting, based on if rememberme was set.
3369 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3373 $rememberMe ?
0 : null,
3375 array( 'prefix' => '' ) // no prefix
3381 * Log this user out.
3383 public function logout() {
3384 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3390 * Clear the user's cookies and session, and reset the instance cache.
3393 public function doLogout() {
3394 $this->clearInstanceCache( 'defaults' );
3396 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3398 $this->clearCookie( 'UserID' );
3399 $this->clearCookie( 'Token' );
3400 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3402 // Remember when user logged out, to prevent seeing cached pages
3403 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3407 * Save this user's settings into the database.
3408 * @todo Only rarely do all these fields need to be set!
3410 public function saveSettings() {
3414 if ( wfReadOnly() ) {
3417 if ( 0 == $this->mId
) {
3421 $this->mTouched
= self
::newTouchedTimestamp();
3422 if ( !$wgAuth->allowSetLocalPassword() ) {
3423 $this->mPassword
= '';
3426 $dbw = wfGetDB( DB_MASTER
);
3427 $dbw->update( 'user',
3429 'user_name' => $this->mName
,
3430 'user_password' => $this->mPassword
,
3431 'user_newpassword' => $this->mNewpassword
,
3432 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3433 'user_real_name' => $this->mRealName
,
3434 'user_email' => $this->mEmail
,
3435 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3436 'user_touched' => $dbw->timestamp( $this->mTouched
),
3437 'user_token' => strval( $this->mToken
),
3438 'user_email_token' => $this->mEmailToken
,
3439 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3440 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires
),
3441 ), array( /* WHERE */
3442 'user_id' => $this->mId
3446 $this->saveOptions();
3448 wfRunHooks( 'UserSaveSettings', array( $this ) );
3449 $this->clearSharedCache();
3450 $this->getUserPage()->invalidateCache();
3454 * If only this user's username is known, and it exists, return the user ID.
3457 public function idForName() {
3458 $s = trim( $this->getName() );
3463 $dbr = wfGetDB( DB_SLAVE
);
3464 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
3465 if ( $id === false ) {
3472 * Add a user to the database, return the user object
3474 * @param string $name Username to add
3475 * @param array $params Array of Strings Non-default parameters to save to
3476 * the database as user_* fields:
3477 * - password: The user's password hash. Password logins will be disabled
3478 * if this is omitted.
3479 * - newpassword: Hash for a temporary password that has been mailed to
3481 * - email: The user's email address.
3482 * - email_authenticated: The email authentication timestamp.
3483 * - real_name: The user's real name.
3484 * - options: An associative array of non-default options.
3485 * - token: Random authentication token. Do not set.
3486 * - registration: Registration timestamp. Do not set.
3488 * @return User|null User object, or null if the username already exists.
3490 public static function createNew( $name, $params = array() ) {
3493 $user->setToken(); // init token
3494 if ( isset( $params['options'] ) ) {
3495 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3496 unset( $params['options'] );
3498 $dbw = wfGetDB( DB_MASTER
);
3499 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3502 'user_id' => $seqVal,
3503 'user_name' => $name,
3504 'user_password' => $user->mPassword
,
3505 'user_newpassword' => $user->mNewpassword
,
3506 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3507 'user_email' => $user->mEmail
,
3508 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3509 'user_real_name' => $user->mRealName
,
3510 'user_token' => strval( $user->mToken
),
3511 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3512 'user_editcount' => 0,
3513 'user_touched' => $dbw->timestamp( self
::newTouchedTimestamp() ),
3515 foreach ( $params as $name => $value ) {
3516 $fields["user_$name"] = $value;
3518 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3519 if ( $dbw->affectedRows() ) {
3520 $newUser = User
::newFromId( $dbw->insertId() );
3528 * Add this existing user object to the database. If the user already
3529 * exists, a fatal status object is returned, and the user object is
3530 * initialised with the data from the database.
3532 * Previously, this function generated a DB error due to a key conflict
3533 * if the user already existed. Many extension callers use this function
3534 * in code along the lines of:
3536 * $user = User::newFromName( $name );
3537 * if ( !$user->isLoggedIn() ) {
3538 * $user->addToDatabase();
3540 * // do something with $user...
3542 * However, this was vulnerable to a race condition (bug 16020). By
3543 * initialising the user object if the user exists, we aim to support this
3544 * calling sequence as far as possible.
3546 * Note that if the user exists, this function will acquire a write lock,
3547 * so it is still advisable to make the call conditional on isLoggedIn(),
3548 * and to commit the transaction after calling.
3550 * @throws MWException
3553 public function addToDatabase() {
3555 if ( !$this->mToken
) {
3556 $this->setToken(); // init token
3559 $this->mTouched
= self
::newTouchedTimestamp();
3561 $dbw = wfGetDB( DB_MASTER
);
3562 $inWrite = $dbw->writesOrCallbacksPending();
3563 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3564 $dbw->insert( 'user',
3566 'user_id' => $seqVal,
3567 'user_name' => $this->mName
,
3568 'user_password' => $this->mPassword
,
3569 'user_newpassword' => $this->mNewpassword
,
3570 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3571 'user_email' => $this->mEmail
,
3572 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3573 'user_real_name' => $this->mRealName
,
3574 'user_token' => strval( $this->mToken
),
3575 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3576 'user_editcount' => 0,
3577 'user_touched' => $dbw->timestamp( $this->mTouched
),
3581 if ( !$dbw->affectedRows() ) {
3582 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3583 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3585 // Can't commit due to pending writes that may need atomicity.
3586 // This may cause some lock contention unlike the case below.
3587 $options = array( 'LOCK IN SHARE MODE' );
3588 $flags = self
::READ_LOCKING
;
3590 // Often, this case happens early in views before any writes when
3591 // using CentralAuth. It's should be OK to commit and break the snapshot.
3592 $dbw->commit( __METHOD__
, 'flush' );
3596 $this->mId
= $dbw->selectField( 'user', 'user_id',
3597 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3600 if ( $this->loadFromDatabase( $flags ) ) {
3605 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3606 "to insert user '{$this->mName}' row, but it was not present in select!" );
3608 return Status
::newFatal( 'userexists' );
3610 $this->mId
= $dbw->insertId();
3612 // Clear instance cache other than user table data, which is already accurate
3613 $this->clearInstanceCache();
3615 $this->saveOptions();
3616 return Status
::newGood();
3620 * If this user is logged-in and blocked,
3621 * block any IP address they've successfully logged in from.
3622 * @return bool A block was spread
3624 public function spreadAnyEditBlock() {
3625 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3626 return $this->spreadBlock();
3632 * If this (non-anonymous) user is blocked,
3633 * block the IP address they've successfully logged in from.
3634 * @return bool A block was spread
3636 protected function spreadBlock() {
3637 wfDebug( __METHOD__
. "()\n" );
3639 if ( $this->mId
== 0 ) {
3643 $userblock = Block
::newFromTarget( $this->getName() );
3644 if ( !$userblock ) {
3648 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3652 * Get whether the user is explicitly blocked from account creation.
3653 * @return bool|Block
3655 public function isBlockedFromCreateAccount() {
3656 $this->getBlockedStatus();
3657 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3658 return $this->mBlock
;
3661 # bug 13611: if the IP address the user is trying to create an account from is
3662 # blocked with createaccount disabled, prevent new account creation there even
3663 # when the user is logged in
3664 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3665 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3667 return $this->mBlockedFromCreateAccount
instanceof Block
3668 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3669 ?
$this->mBlockedFromCreateAccount
3674 * Get whether the user is blocked from using Special:Emailuser.
3677 public function isBlockedFromEmailuser() {
3678 $this->getBlockedStatus();
3679 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3683 * Get whether the user is allowed to create an account.
3686 public function isAllowedToCreateAccount() {
3687 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3691 * Get this user's personal page title.
3693 * @return Title User's personal page title
3695 public function getUserPage() {
3696 return Title
::makeTitle( NS_USER
, $this->getName() );
3700 * Get this user's talk page title.
3702 * @return Title User's talk page title
3704 public function getTalkPage() {
3705 $title = $this->getUserPage();
3706 return $title->getTalkPage();
3710 * Determine whether the user is a newbie. Newbies are either
3711 * anonymous IPs, or the most recently created accounts.
3714 public function isNewbie() {
3715 return !$this->isAllowed( 'autoconfirmed' );
3719 * Check to see if the given clear-text password is one of the accepted passwords
3720 * @param string $password user password.
3721 * @return bool True if the given password is correct, otherwise False.
3723 public function checkPassword( $password ) {
3724 global $wgAuth, $wgLegacyEncoding;
3727 // Certain authentication plugins do NOT want to save
3728 // domain passwords in a mysql database, so we should
3729 // check this (in case $wgAuth->strict() is false).
3731 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3733 } elseif ( $wgAuth->strict() ) {
3734 // Auth plugin doesn't allow local authentication
3736 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3737 // Auth plugin doesn't allow local authentication for this user name
3740 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
3742 } elseif ( $wgLegacyEncoding ) {
3743 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3744 // Check for this with iconv
3745 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3746 if ( $cp1252Password != $password
3747 && self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
)
3756 * Check if the given clear-text password matches the temporary password
3757 * sent by e-mail for password reset operations.
3759 * @param string $plaintext
3761 * @return bool True if matches, false otherwise
3763 public function checkTemporaryPassword( $plaintext ) {
3764 global $wgNewPasswordExpiry;
3767 if ( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
3768 if ( is_null( $this->mNewpassTime
) ) {
3771 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3772 return ( time() < $expiry );
3779 * Alias for getEditToken.
3780 * @deprecated since 1.19, use getEditToken instead.
3782 * @param string|array $salt of Strings Optional function-specific data for hashing
3783 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3784 * @return string The new edit token
3786 public function editToken( $salt = '', $request = null ) {
3787 wfDeprecated( __METHOD__
, '1.19' );
3788 return $this->getEditToken( $salt, $request );
3792 * Initialize (if necessary) and return a session token value
3793 * which can be used in edit forms to show that the user's
3794 * login credentials aren't being hijacked with a foreign form
3799 * @param string|array $salt of Strings Optional function-specific data for hashing
3800 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3801 * @return string The new edit token
3803 public function getEditToken( $salt = '', $request = null ) {
3804 if ( $request == null ) {
3805 $request = $this->getRequest();
3808 if ( $this->isAnon() ) {
3809 return EDIT_TOKEN_SUFFIX
;
3811 $token = $request->getSessionData( 'wsEditToken' );
3812 if ( $token === null ) {
3813 $token = MWCryptRand
::generateHex( 32 );
3814 $request->setSessionData( 'wsEditToken', $token );
3816 if ( is_array( $salt ) ) {
3817 $salt = implode( '|', $salt );
3819 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
3824 * Generate a looking random token for various uses.
3826 * @return string The new random token
3827 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
3828 * wfRandomString for pseudo-randomness.
3830 public static function generateToken() {
3831 return MWCryptRand
::generateHex( 32 );
3835 * Check given value against the token value stored in the session.
3836 * A match should confirm that the form was submitted from the
3837 * user's own login session, not a form submission from a third-party
3840 * @param string $val Input value to compare
3841 * @param string $salt Optional function-specific data for hashing
3842 * @param WebRequest|null $request Object to use or null to use $wgRequest
3843 * @return bool Whether the token matches
3845 public function matchEditToken( $val, $salt = '', $request = null ) {
3846 $sessionToken = $this->getEditToken( $salt, $request );
3847 if ( $val != $sessionToken ) {
3848 wfDebug( "User::matchEditToken: broken session data\n" );
3851 return $val == $sessionToken;
3855 * Check given value against the token value stored in the session,
3856 * ignoring the suffix.
3858 * @param string $val Input value to compare
3859 * @param string $salt Optional function-specific data for hashing
3860 * @param WebRequest|null $request object to use or null to use $wgRequest
3861 * @return bool Whether the token matches
3863 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3864 $sessionToken = $this->getEditToken( $salt, $request );
3865 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3869 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3870 * mail to the user's given address.
3872 * @param string $type Message to send, either "created", "changed" or "set"
3875 public function sendConfirmationMail( $type = 'created' ) {
3877 $expiration = null; // gets passed-by-ref and defined in next line.
3878 $token = $this->confirmationToken( $expiration );
3879 $url = $this->confirmationTokenUrl( $token );
3880 $invalidateURL = $this->invalidationTokenUrl( $token );
3881 $this->saveSettings();
3883 if ( $type == 'created' ||
$type === false ) {
3884 $message = 'confirmemail_body';
3885 } elseif ( $type === true ) {
3886 $message = 'confirmemail_body_changed';
3888 // Messages: confirmemail_body_changed, confirmemail_body_set
3889 $message = 'confirmemail_body_' . $type;
3892 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3893 wfMessage( $message,
3894 $this->getRequest()->getIP(),
3897 $wgLang->timeanddate( $expiration, false ),
3899 $wgLang->date( $expiration, false ),
3900 $wgLang->time( $expiration, false ) )->text() );
3904 * Send an e-mail to this user's account. Does not check for
3905 * confirmed status or validity.
3907 * @param string $subject Message subject
3908 * @param string $body Message body
3909 * @param string $from Optional From address; if unspecified, default
3910 * $wgPasswordSender will be used.
3911 * @param string $replyto Reply-To address
3914 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3915 if ( is_null( $from ) ) {
3916 global $wgPasswordSender;
3917 $sender = new MailAddress( $wgPasswordSender,
3918 wfMessage( 'emailsender' )->inContentLanguage()->text() );
3920 $sender = new MailAddress( $from );
3923 $to = new MailAddress( $this );
3924 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
3928 * Generate, store, and return a new e-mail confirmation code.
3929 * A hash (unsalted, since it's used as a key) is stored.
3931 * @note Call saveSettings() after calling this function to commit
3932 * this change to the database.
3934 * @param string &$expiration Accepts the expiration time
3935 * @return string New token
3937 protected function confirmationToken( &$expiration ) {
3938 global $wgUserEmailConfirmationTokenExpiry;
3940 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
3941 $expiration = wfTimestamp( TS_MW
, $expires );
3943 $token = MWCryptRand
::generateHex( 32 );
3944 $hash = md5( $token );
3945 $this->mEmailToken
= $hash;
3946 $this->mEmailTokenExpires
= $expiration;
3951 * Return a URL the user can use to confirm their email address.
3952 * @param string $token Accepts the email confirmation token
3953 * @return string New token URL
3955 protected function confirmationTokenUrl( $token ) {
3956 return $this->getTokenUrl( 'ConfirmEmail', $token );
3960 * Return a URL the user can use to invalidate their email address.
3961 * @param string $token Accepts the email confirmation token
3962 * @return string New token URL
3964 protected function invalidationTokenUrl( $token ) {
3965 return $this->getTokenUrl( 'InvalidateEmail', $token );
3969 * Internal function to format the e-mail validation/invalidation URLs.
3970 * This uses a quickie hack to use the
3971 * hardcoded English names of the Special: pages, for ASCII safety.
3973 * @note Since these URLs get dropped directly into emails, using the
3974 * short English names avoids insanely long URL-encoded links, which
3975 * also sometimes can get corrupted in some browsers/mailers
3976 * (bug 6957 with Gmail and Internet Explorer).
3978 * @param string $page Special page
3979 * @param string $token Token
3980 * @return string Formatted URL
3982 protected function getTokenUrl( $page, $token ) {
3983 // Hack to bypass localization of 'Special:'
3984 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
3985 return $title->getCanonicalURL();
3989 * Mark the e-mail address confirmed.
3991 * @note Call saveSettings() after calling this function to commit the change.
3995 public function confirmEmail() {
3996 // Check if it's already confirmed, so we don't touch the database
3997 // and fire the ConfirmEmailComplete hook on redundant confirmations.
3998 if ( !$this->isEmailConfirmed() ) {
3999 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4000 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
4006 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4007 * address if it was already confirmed.
4009 * @note Call saveSettings() after calling this function to commit the change.
4010 * @return bool Returns true
4012 public function invalidateEmail() {
4014 $this->mEmailToken
= null;
4015 $this->mEmailTokenExpires
= null;
4016 $this->setEmailAuthenticationTimestamp( null );
4017 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
4022 * Set the e-mail authentication timestamp.
4023 * @param string $timestamp TS_MW timestamp
4025 public function setEmailAuthenticationTimestamp( $timestamp ) {
4027 $this->mEmailAuthenticated
= $timestamp;
4028 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4032 * Is this user allowed to send e-mails within limits of current
4033 * site configuration?
4036 public function canSendEmail() {
4037 global $wgEnableEmail, $wgEnableUserEmail;
4038 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4041 $canSend = $this->isEmailConfirmed();
4042 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4047 * Is this user allowed to receive e-mails within limits of current
4048 * site configuration?
4051 public function canReceiveEmail() {
4052 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4056 * Is this user's e-mail address valid-looking and confirmed within
4057 * limits of the current site configuration?
4059 * @note If $wgEmailAuthentication is on, this may require the user to have
4060 * confirmed their address by returning a code or using a password
4061 * sent to the address from the wiki.
4065 public function isEmailConfirmed() {
4066 global $wgEmailAuthentication;
4069 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4070 if ( $this->isAnon() ) {
4073 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4076 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4086 * Check whether there is an outstanding request for e-mail confirmation.
4089 public function isEmailConfirmationPending() {
4090 global $wgEmailAuthentication;
4091 return $wgEmailAuthentication &&
4092 !$this->isEmailConfirmed() &&
4093 $this->mEmailToken
&&
4094 $this->mEmailTokenExpires
> wfTimestamp();
4098 * Get the timestamp of account creation.
4100 * @return string|bool|null Timestamp of account creation, false for
4101 * non-existent/anonymous user accounts, or null if existing account
4102 * but information is not in database.
4104 public function getRegistration() {
4105 if ( $this->isAnon() ) {
4109 return $this->mRegistration
;
4113 * Get the timestamp of the first edit
4115 * @return string|bool Timestamp of first edit, or false for
4116 * non-existent/anonymous user accounts.
4118 public function getFirstEditTimestamp() {
4119 if ( $this->getId() == 0 ) {
4120 return false; // anons
4122 $dbr = wfGetDB( DB_SLAVE
);
4123 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4124 array( 'rev_user' => $this->getId() ),
4126 array( 'ORDER BY' => 'rev_timestamp ASC' )
4129 return false; // no edits
4131 return wfTimestamp( TS_MW
, $time );
4135 * Get the permissions associated with a given list of groups
4137 * @param array $groups Array of Strings List of internal group names
4138 * @return array Array of Strings List of permission key names for given groups combined
4140 public static function getGroupPermissions( $groups ) {
4141 global $wgGroupPermissions, $wgRevokePermissions;
4143 // grant every granted permission first
4144 foreach ( $groups as $group ) {
4145 if ( isset( $wgGroupPermissions[$group] ) ) {
4146 $rights = array_merge( $rights,
4147 // array_filter removes empty items
4148 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4151 // now revoke the revoked permissions
4152 foreach ( $groups as $group ) {
4153 if ( isset( $wgRevokePermissions[$group] ) ) {
4154 $rights = array_diff( $rights,
4155 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4158 return array_unique( $rights );
4162 * Get all the groups who have a given permission
4164 * @param string $role Role to check
4165 * @return array Array of Strings List of internal group names with the given permission
4167 public static function getGroupsWithPermission( $role ) {
4168 global $wgGroupPermissions;
4169 $allowedGroups = array();
4170 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4171 if ( self
::groupHasPermission( $group, $role ) ) {
4172 $allowedGroups[] = $group;
4175 return $allowedGroups;
4179 * Check, if the given group has the given permission
4181 * If you're wanting to check whether all users have a permission, use
4182 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4186 * @param string $group Group to check
4187 * @param string $role Role to check
4190 public static function groupHasPermission( $group, $role ) {
4191 global $wgGroupPermissions, $wgRevokePermissions;
4192 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4193 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4197 * Check if all users have the given permission
4200 * @param string $right Right to check
4203 public static function isEveryoneAllowed( $right ) {
4204 global $wgGroupPermissions, $wgRevokePermissions;
4205 static $cache = array();
4207 // Use the cached results, except in unit tests which rely on
4208 // being able change the permission mid-request
4209 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4210 return $cache[$right];
4213 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4214 $cache[$right] = false;
4218 // If it's revoked anywhere, then everyone doesn't have it
4219 foreach ( $wgRevokePermissions as $rights ) {
4220 if ( isset( $rights[$right] ) && $rights[$right] ) {
4221 $cache[$right] = false;
4226 // Allow extensions (e.g. OAuth) to say false
4227 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4228 $cache[$right] = false;
4232 $cache[$right] = true;
4237 * Get the localized descriptive name for a group, if it exists
4239 * @param string $group Internal group name
4240 * @return string Localized descriptive group name
4242 public static function getGroupName( $group ) {
4243 $msg = wfMessage( "group-$group" );
4244 return $msg->isBlank() ?
$group : $msg->text();
4248 * Get the localized descriptive name for a member of a group, if it exists
4250 * @param string $group Internal group name
4251 * @param string $username Username for gender (since 1.19)
4252 * @return string Localized name for group member
4254 public static function getGroupMember( $group, $username = '#' ) {
4255 $msg = wfMessage( "group-$group-member", $username );
4256 return $msg->isBlank() ?
$group : $msg->text();
4260 * Return the set of defined explicit groups.
4261 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4262 * are not included, as they are defined automatically, not in the database.
4263 * @return array Array of internal group names
4265 public static function getAllGroups() {
4266 global $wgGroupPermissions, $wgRevokePermissions;
4268 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4269 self
::getImplicitGroups()
4274 * Get a list of all available permissions.
4275 * @return array Array of permission names
4277 public static function getAllRights() {
4278 if ( self
::$mAllRights === false ) {
4279 global $wgAvailableRights;
4280 if ( count( $wgAvailableRights ) ) {
4281 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4283 self
::$mAllRights = self
::$mCoreRights;
4285 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
4287 return self
::$mAllRights;
4291 * Get a list of implicit groups
4292 * @return array Array of Strings Array of internal group names
4294 public static function getImplicitGroups() {
4295 global $wgImplicitGroups;
4297 $groups = $wgImplicitGroups;
4298 # Deprecated, use $wgImplictGroups instead
4299 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) );
4305 * Get the title of a page describing a particular group
4307 * @param string $group Internal group name
4308 * @return Title|bool Title of the page if it exists, false otherwise
4310 public static function getGroupPage( $group ) {
4311 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4312 if ( $msg->exists() ) {
4313 $title = Title
::newFromText( $msg->text() );
4314 if ( is_object( $title ) ) {
4322 * Create a link to the group in HTML, if available;
4323 * else return the group name.
4325 * @param string $group Internal name of the group
4326 * @param string $text The text of the link
4327 * @return string HTML link to the group
4329 public static function makeGroupLinkHTML( $group, $text = '' ) {
4330 if ( $text == '' ) {
4331 $text = self
::getGroupName( $group );
4333 $title = self
::getGroupPage( $group );
4335 return Linker
::link( $title, htmlspecialchars( $text ) );
4342 * Create a link to the group in Wikitext, if available;
4343 * else return the group name.
4345 * @param string $group Internal name of the group
4346 * @param string $text The text of the link
4347 * @return string Wikilink to the group
4349 public static function makeGroupLinkWiki( $group, $text = '' ) {
4350 if ( $text == '' ) {
4351 $text = self
::getGroupName( $group );
4353 $title = self
::getGroupPage( $group );
4355 $page = $title->getPrefixedText();
4356 return "[[$page|$text]]";
4363 * Returns an array of the groups that a particular group can add/remove.
4365 * @param string $group The group to check for whether it can add/remove
4366 * @return array array( 'add' => array( addablegroups ),
4367 * 'remove' => array( removablegroups ),
4368 * 'add-self' => array( addablegroups to self),
4369 * 'remove-self' => array( removable groups from self) )
4371 public static function changeableByGroup( $group ) {
4372 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4376 'remove' => array(),
4377 'add-self' => array(),
4378 'remove-self' => array()
4381 if ( empty( $wgAddGroups[$group] ) ) {
4382 // Don't add anything to $groups
4383 } elseif ( $wgAddGroups[$group] === true ) {
4384 // You get everything
4385 $groups['add'] = self
::getAllGroups();
4386 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4387 $groups['add'] = $wgAddGroups[$group];
4390 // Same thing for remove
4391 if ( empty( $wgRemoveGroups[$group] ) ) {
4392 } elseif ( $wgRemoveGroups[$group] === true ) {
4393 $groups['remove'] = self
::getAllGroups();
4394 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4395 $groups['remove'] = $wgRemoveGroups[$group];
4398 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4399 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4400 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4401 if ( is_int( $key ) ) {
4402 $wgGroupsAddToSelf['user'][] = $value;
4407 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4408 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4409 if ( is_int( $key ) ) {
4410 $wgGroupsRemoveFromSelf['user'][] = $value;
4415 // Now figure out what groups the user can add to him/herself
4416 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4417 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4418 // No idea WHY this would be used, but it's there
4419 $groups['add-self'] = User
::getAllGroups();
4420 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4421 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4424 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4425 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4426 $groups['remove-self'] = User
::getAllGroups();
4427 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4428 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4435 * Returns an array of groups that this user can add and remove
4436 * @return array array( 'add' => array( addablegroups ),
4437 * 'remove' => array( removablegroups ),
4438 * 'add-self' => array( addablegroups to self),
4439 * 'remove-self' => array( removable groups from self) )
4441 public function changeableGroups() {
4442 if ( $this->isAllowed( 'userrights' ) ) {
4443 // This group gives the right to modify everything (reverse-
4444 // compatibility with old "userrights lets you change
4446 // Using array_merge to make the groups reindexed
4447 $all = array_merge( User
::getAllGroups() );
4451 'add-self' => array(),
4452 'remove-self' => array()
4456 // Okay, it's not so simple, we will have to go through the arrays
4459 'remove' => array(),
4460 'add-self' => array(),
4461 'remove-self' => array()
4463 $addergroups = $this->getEffectiveGroups();
4465 foreach ( $addergroups as $addergroup ) {
4466 $groups = array_merge_recursive(
4467 $groups, $this->changeableByGroup( $addergroup )
4469 $groups['add'] = array_unique( $groups['add'] );
4470 $groups['remove'] = array_unique( $groups['remove'] );
4471 $groups['add-self'] = array_unique( $groups['add-self'] );
4472 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4478 * Increment the user's edit-count field.
4479 * Will have no effect for anonymous users.
4481 public function incEditCount() {
4482 if ( !$this->isAnon() ) {
4483 $dbw = wfGetDB( DB_MASTER
);
4486 array( 'user_editcount=user_editcount+1' ),
4487 array( 'user_id' => $this->getId() ),
4491 // Lazy initialization check...
4492 if ( $dbw->affectedRows() == 0 ) {
4493 // Now here's a goddamn hack...
4494 $dbr = wfGetDB( DB_SLAVE
);
4495 if ( $dbr !== $dbw ) {
4496 // If we actually have a slave server, the count is
4497 // at least one behind because the current transaction
4498 // has not been committed and replicated.
4499 $this->initEditCount( 1 );
4501 // But if DB_SLAVE is selecting the master, then the
4502 // count we just read includes the revision that was
4503 // just added in the working transaction.
4504 $this->initEditCount();
4508 // edit count in user cache too
4509 $this->invalidateCache();
4513 * Initialize user_editcount from data out of the revision table
4515 * @param int $add Edits to add to the count from the revision table
4516 * @return int Number of edits
4518 protected function initEditCount( $add = 0 ) {
4519 // Pull from a slave to be less cruel to servers
4520 // Accuracy isn't the point anyway here
4521 $dbr = wfGetDB( DB_SLAVE
);
4522 $count = (int)$dbr->selectField(
4525 array( 'rev_user' => $this->getId() ),
4528 $count = $count +
$add;
4530 $dbw = wfGetDB( DB_MASTER
);
4533 array( 'user_editcount' => $count ),
4534 array( 'user_id' => $this->getId() ),
4542 * Get the description of a given right
4544 * @param string $right Right to query
4545 * @return string Localized description of the right
4547 public static function getRightDescription( $right ) {
4548 $key = "right-$right";
4549 $msg = wfMessage( $key );
4550 return $msg->isBlank() ?
$right : $msg->text();
4554 * Make an old-style password hash
4556 * @param string $password Plain-text password
4557 * @param string $userId User ID
4558 * @return string Password hash
4560 public static function oldCrypt( $password, $userId ) {
4561 global $wgPasswordSalt;
4562 if ( $wgPasswordSalt ) {
4563 return md5( $userId . '-' . md5( $password ) );
4565 return md5( $password );
4570 * Make a new-style password hash
4572 * @param string $password Plain-text password
4573 * @param bool|string $salt Optional salt, may be random or the user ID.
4574 * If unspecified or false, will generate one automatically
4575 * @return string Password hash
4577 public static function crypt( $password, $salt = false ) {
4578 global $wgPasswordSalt;
4581 if ( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4585 if ( $wgPasswordSalt ) {
4586 if ( $salt === false ) {
4587 $salt = MWCryptRand
::generateHex( 8 );
4589 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4591 return ':A:' . md5( $password );
4596 * Compare a password hash with a plain-text password. Requires the user
4597 * ID if there's a chance that the hash is an old-style hash.
4599 * @param string $hash Password hash
4600 * @param string $password Plain-text password to compare
4601 * @param string|bool $userId User ID for old-style password salt
4605 public static function comparePasswords( $hash, $password, $userId = false ) {
4606 $type = substr( $hash, 0, 3 );
4609 if ( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4613 if ( $type == ':A:' ) {
4615 return md5( $password ) === substr( $hash, 3 );
4616 } elseif ( $type == ':B:' ) {
4618 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4619 return md5( $salt . '-' . md5( $password ) ) === $realHash;
4622 return self
::oldCrypt( $password, $userId ) === $hash;
4627 * Add a newuser log entry for this user.
4628 * Before 1.19 the return value was always true.
4630 * @param string|bool $action Account creation type.
4631 * - String, one of the following values:
4632 * - 'create' for an anonymous user creating an account for himself.
4633 * This will force the action's performer to be the created user itself,
4634 * no matter the value of $wgUser
4635 * - 'create2' for a logged in user creating an account for someone else
4636 * - 'byemail' when the created user will receive its password by e-mail
4637 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4638 * - Boolean means whether the account was created by e-mail (deprecated):
4639 * - true will be converted to 'byemail'
4640 * - false will be converted to 'create' if this object is the same as
4641 * $wgUser and to 'create2' otherwise
4643 * @param string $reason User supplied reason
4645 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4647 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4648 global $wgUser, $wgNewUserLog;
4649 if ( empty( $wgNewUserLog ) ) {
4650 return true; // disabled
4653 if ( $action === true ) {
4654 $action = 'byemail';
4655 } elseif ( $action === false ) {
4656 if ( $this->getName() == $wgUser->getName() ) {
4659 $action = 'create2';
4663 if ( $action === 'create' ||
$action === 'autocreate' ) {
4666 $performer = $wgUser;
4669 $logEntry = new ManualLogEntry( 'newusers', $action );
4670 $logEntry->setPerformer( $performer );
4671 $logEntry->setTarget( $this->getUserPage() );
4672 $logEntry->setComment( $reason );
4673 $logEntry->setParameters( array(
4674 '4::userid' => $this->getId(),
4676 $logid = $logEntry->insert();
4678 if ( $action !== 'autocreate' ) {
4679 $logEntry->publish( $logid );
4686 * Add an autocreate newuser log entry for this user
4687 * Used by things like CentralAuth and perhaps other authplugins.
4688 * Consider calling addNewUserLogEntry() directly instead.
4692 public function addNewUserLogEntryAutoCreate() {
4693 $this->addNewUserLogEntry( 'autocreate' );
4699 * Load the user options either from cache, the database or an array
4701 * @param array $data Rows for the current user out of the user_properties table
4703 protected function loadOptions( $data = null ) {
4708 if ( $this->mOptionsLoaded
) {
4712 $this->mOptions
= self
::getDefaultOptions();
4714 if ( !$this->getId() ) {
4715 // For unlogged-in users, load language/variant options from request.
4716 // There's no need to do it for logged-in users: they can set preferences,
4717 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4718 // so don't override user's choice (especially when the user chooses site default).
4719 $variant = $wgContLang->getDefaultVariant();
4720 $this->mOptions
['variant'] = $variant;
4721 $this->mOptions
['language'] = $variant;
4722 $this->mOptionsLoaded
= true;
4726 // Maybe load from the object
4727 if ( !is_null( $this->mOptionOverrides
) ) {
4728 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4729 foreach ( $this->mOptionOverrides
as $key => $value ) {
4730 $this->mOptions
[$key] = $value;
4733 if ( !is_array( $data ) ) {
4734 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4735 // Load from database
4736 $dbr = wfGetDB( DB_SLAVE
);
4738 $res = $dbr->select(
4740 array( 'up_property', 'up_value' ),
4741 array( 'up_user' => $this->getId() ),
4745 $this->mOptionOverrides
= array();
4747 foreach ( $res as $row ) {
4748 $data[$row->up_property
] = $row->up_value
;
4751 foreach ( $data as $property => $value ) {
4752 $this->mOptionOverrides
[$property] = $value;
4753 $this->mOptions
[$property] = $value;
4757 $this->mOptionsLoaded
= true;
4759 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
4763 * Saves the non-default options for this user, as previously set e.g. via
4764 * setOption(), in the database's "user_properties" (preferences) table.
4765 * Usually used via saveSettings().
4767 protected function saveOptions() {
4768 $this->loadOptions();
4770 // Not using getOptions(), to keep hidden preferences in database
4771 $saveOptions = $this->mOptions
;
4773 // Allow hooks to abort, for instance to save to a global profile.
4774 // Reset options to default state before saving.
4775 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4779 $userId = $this->getId();
4781 $insert_rows = array(); // all the new preference rows
4782 foreach ( $saveOptions as $key => $value ) {
4783 // Don't bother storing default values
4784 $defaultOption = self
::getDefaultOption( $key );
4785 if ( ( $defaultOption === null && $value !== false && $value !== null )
4786 ||
$value != $defaultOption
4788 $insert_rows[] = array(
4789 'up_user' => $userId,
4790 'up_property' => $key,
4791 'up_value' => $value,
4796 $dbw = wfGetDB( DB_MASTER
);
4798 $res = $dbw->select( 'user_properties',
4799 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
4801 // Find prior rows that need to be removed or updated. These rows will
4802 // all be deleted (the later so that INSERT IGNORE applies the new values).
4803 $keysDelete = array();
4804 foreach ( $res as $row ) {
4805 if ( !isset( $saveOptions[$row->up_property
] )
4806 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
4808 $keysDelete[] = $row->up_property
;
4812 if ( count( $keysDelete ) ) {
4813 // Do the DELETE by PRIMARY KEY for prior rows.
4814 // In the past a very large portion of calls to this function are for setting
4815 // 'rememberpassword' for new accounts (a preference that has since been removed).
4816 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4817 // caused gap locks on [max user ID,+infinity) which caused high contention since
4818 // updates would pile up on each other as they are for higher (newer) user IDs.
4819 // It might not be necessary these days, but it shouldn't hurt either.
4820 $dbw->delete( 'user_properties',
4821 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
4823 // Insert the new preference rows
4824 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
4828 * Provide an array of HTML5 attributes to put on an input element
4829 * intended for the user to enter a new password. This may include
4830 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4832 * Do *not* use this when asking the user to enter his current password!
4833 * Regardless of configuration, users may have invalid passwords for whatever
4834 * reason (e.g., they were set before requirements were tightened up).
4835 * Only use it when asking for a new password, like on account creation or
4838 * Obviously, you still need to do server-side checking.
4840 * NOTE: A combination of bugs in various browsers means that this function
4841 * actually just returns array() unconditionally at the moment. May as
4842 * well keep it around for when the browser bugs get fixed, though.
4844 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4846 * @return array Array of HTML attributes suitable for feeding to
4847 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4848 * That will get confused by the boolean attribute syntax used.)
4850 public static function passwordChangeInputAttribs() {
4851 global $wgMinimalPasswordLength;
4853 if ( $wgMinimalPasswordLength == 0 ) {
4857 # Note that the pattern requirement will always be satisfied if the
4858 # input is empty, so we need required in all cases.
4860 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4861 # if e-mail confirmation is being used. Since HTML5 input validation
4862 # is b0rked anyway in some browsers, just return nothing. When it's
4863 # re-enabled, fix this code to not output required for e-mail
4865 #$ret = array( 'required' );
4868 # We can't actually do this right now, because Opera 9.6 will print out
4869 # the entered password visibly in its error message! When other
4870 # browsers add support for this attribute, or Opera fixes its support,
4871 # we can add support with a version check to avoid doing this on Opera
4872 # versions where it will be a problem. Reported to Opera as
4873 # DSK-262266, but they don't have a public bug tracker for us to follow.
4875 if ( $wgMinimalPasswordLength > 1 ) {
4876 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4877 $ret['title'] = wfMessage( 'passwordtooshort' )
4878 ->numParams( $wgMinimalPasswordLength )->text();
4886 * Return the list of user fields that should be selected to create
4887 * a new user object.
4890 public static function selectFields() {
4897 'user_newpass_time',
4901 'user_email_authenticated',
4903 'user_email_token_expires',
4904 'user_password_expires',
4905 'user_registration',
4911 * Factory function for fatal permission-denied errors
4914 * @param string $permission User right required
4917 static function newFatalPermissionDeniedStatus( $permission ) {
4920 $groups = array_map(
4921 array( 'User', 'makeGroupLinkWiki' ),
4922 User
::getGroupsWithPermission( $permission )
4926 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4928 return Status
::newFatal( 'badaccess-group0' );