3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Int Number of characters in user_token field.
27 define( 'USER_TOKEN_LENGTH', 32 );
30 * Int Serialized record version.
33 define( 'MW_USER_VERSION', 10 );
36 * String Some punctuation to prevent editing from broken text-mangling proxies.
39 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
42 * The User object encapsulates all of the user-specific settings (user_id,
43 * name, rights, password, email address, options, last login time). Client
44 * classes use the getXXX() functions to access these fields. These functions
45 * do all the work of determining whether the user is logged in,
46 * whether the requested option can be satisfied from cookies or
47 * whether a database query is needed. Most of the settings needed
48 * for rendering normal pages are set in the cookie to minimize use
51 class User
implements IDBAccessObject
{
53 * Global constants made accessible as class constants so that autoloader
56 const USER_TOKEN_LENGTH
= USER_TOKEN_LENGTH
;
57 const MW_USER_VERSION
= MW_USER_VERSION
;
58 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
61 * Maximum items in $mWatchedItems
63 const MAX_WATCHED_ITEMS_CACHE
= 100;
66 * @var PasswordFactory Lazily loaded factory object for passwords
68 private static $mPasswordFactory = null;
71 * Array of Strings List of member variables which are saved to the
72 * shared cache (memcached). Any operation which changes the
73 * corresponding database fields must call a cache-clearing function.
76 protected static $mCacheVars = array(
84 'mEmailAuthenticated',
91 // user_properties table
96 * Array of Strings Core rights.
97 * Each of these should have a corresponding message of the form
101 protected static $mCoreRights = array(
127 'editusercssjs', #deprecated
139 'move-categorypages',
140 'move-rootuserpages',
144 'override-export-depth',
168 'userrights-interwiki',
176 * String Cached results of getAllRights()
178 protected static $mAllRights = false;
180 /** @name Cache variables */
190 public $mNewpassword;
192 public $mNewpassTime;
200 public $mEmailAuthenticated;
202 protected $mEmailToken;
204 protected $mEmailTokenExpires;
206 protected $mRegistration;
208 protected $mEditCount;
212 protected $mOptionOverrides;
214 protected $mPasswordExpires;
218 * Bool Whether the cache variables have been loaded.
221 public $mOptionsLoaded;
224 * Array with already loaded items or true if all items have been loaded.
226 protected $mLoadedItems = array();
230 * String Initialization data source if mLoadedItems!==true. May be one of:
231 * - 'defaults' anonymous user initialised from class defaults
232 * - 'name' initialise from mName
233 * - 'id' initialise from mId
234 * - 'session' log in from cookies or session if possible
236 * Use the User::newFrom*() family of functions to set this.
241 * Lazy-initialized variables, invalidated with clearInstanceCache
245 protected $mDatePreference;
253 protected $mBlockreason;
255 protected $mEffectiveGroups;
257 protected $mImplicitGroups;
259 protected $mFormerGroups;
261 protected $mBlockedGlobally;
278 protected $mAllowUsertalk;
281 private $mBlockedFromCreateAccount = false;
284 private $mWatchedItems = array();
286 public static $idCacheByName = array();
289 * Lightweight constructor for an anonymous user.
290 * Use the User::newFrom* factory functions for other kinds of users.
294 * @see newFromConfirmationCode()
295 * @see newFromSession()
298 public function __construct() {
299 $this->clearInstanceCache( 'defaults' );
305 public function __toString() {
306 return $this->getName();
310 * Load the user table data for this object from the source given by mFrom.
312 public function load() {
313 if ( $this->mLoadedItems
=== true ) {
316 wfProfileIn( __METHOD__
);
318 // Set it now to avoid infinite recursion in accessors
319 $this->mLoadedItems
= true;
321 switch ( $this->mFrom
) {
323 $this->loadDefaults();
326 $this->mId
= self
::idFromName( $this->mName
);
328 // Nonexistent user placeholder object
329 $this->loadDefaults( $this->mName
);
338 if ( !$this->loadFromSession() ) {
339 // Loading from session failed. Load defaults.
340 $this->loadDefaults();
342 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
345 wfProfileOut( __METHOD__
);
346 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
348 wfProfileOut( __METHOD__
);
352 * Load user table data, given mId has already been set.
353 * @return bool False if the ID does not exist, true otherwise
355 public function loadFromId() {
357 if ( $this->mId
== 0 ) {
358 $this->loadDefaults();
363 $key = wfMemcKey( 'user', 'id', $this->mId
);
364 $data = $wgMemc->get( $key );
365 if ( !is_array( $data ) ||
$data['mVersion'] != MW_USER_VERSION
) {
366 // Object is expired, load from DB
371 wfDebug( "User: cache miss for user {$this->mId}\n" );
373 if ( !$this->loadFromDatabase() ) {
374 // Can't load from ID, user is anonymous
377 $this->saveToCache();
379 wfDebug( "User: got user {$this->mId} from cache\n" );
380 // Restore from cache
381 foreach ( self
::$mCacheVars as $name ) {
382 $this->$name = $data[$name];
386 $this->mLoadedItems
= true;
392 * Save user data to the shared cache
394 public function saveToCache() {
397 $this->loadOptions();
398 if ( $this->isAnon() ) {
399 // Anonymous users are uncached
403 foreach ( self
::$mCacheVars as $name ) {
404 $data[$name] = $this->$name;
406 $data['mVersion'] = MW_USER_VERSION
;
407 $key = wfMemcKey( 'user', 'id', $this->mId
);
409 $wgMemc->set( $key, $data );
412 /** @name newFrom*() static factory methods */
416 * Static factory method for creation from username.
418 * This is slightly less efficient than newFromId(), so use newFromId() if
419 * you have both an ID and a name handy.
421 * @param string $name Username, validated by Title::newFromText()
422 * @param string|bool $validate Validate username. Takes the same parameters as
423 * User::getCanonicalName(), except that true is accepted as an alias
424 * for 'valid', for BC.
426 * @return User|bool User object, or false if the username is invalid
427 * (e.g. if it contains illegal characters or is an IP address). If the
428 * username is not present in the database, the result will be a user object
429 * with a name, zero user ID and default settings.
431 public static function newFromName( $name, $validate = 'valid' ) {
432 if ( $validate === true ) {
435 $name = self
::getCanonicalName( $name, $validate );
436 if ( $name === false ) {
439 // Create unloaded user object
443 $u->setItemLoaded( 'name' );
449 * Static factory method for creation from a given user ID.
451 * @param int $id Valid user ID
452 * @return User The corresponding User object
454 public static function newFromId( $id ) {
458 $u->setItemLoaded( 'id' );
463 * Factory method to fetch whichever user has a given email confirmation code.
464 * This code is generated when an account is created or its e-mail address
467 * If the code is invalid or has expired, returns NULL.
469 * @param string $code Confirmation code
472 public static function newFromConfirmationCode( $code ) {
473 $dbr = wfGetDB( DB_SLAVE
);
474 $id = $dbr->selectField( 'user', 'user_id', array(
475 'user_email_token' => md5( $code ),
476 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
478 if ( $id !== false ) {
479 return User
::newFromId( $id );
486 * Create a new user object using data from session or cookies. If the
487 * login credentials are invalid, the result is an anonymous user.
489 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
492 public static function newFromSession( WebRequest
$request = null ) {
494 $user->mFrom
= 'session';
495 $user->mRequest
= $request;
500 * Create a new user object from a user row.
501 * The row should have the following fields from the user table in it:
502 * - either user_name or user_id to load further data if needed (or both)
504 * - all other fields (email, password, etc.)
505 * It is useless to provide the remaining fields if either user_id,
506 * user_name and user_real_name are not provided because the whole row
507 * will be loaded once more from the database when accessing them.
509 * @param stdClass $row A row from the user table
510 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
513 public static function newFromRow( $row, $data = null ) {
515 $user->loadFromRow( $row, $data );
522 * Get the username corresponding to a given user ID
523 * @param int $id User ID
524 * @return string|bool The corresponding username
526 public static function whoIs( $id ) {
527 return UserCache
::singleton()->getProp( $id, 'name' );
531 * Get the real name of a user given their user ID
533 * @param int $id User ID
534 * @return string|bool The corresponding user's real name
536 public static function whoIsReal( $id ) {
537 return UserCache
::singleton()->getProp( $id, 'real_name' );
541 * Get database id given a user name
542 * @param string $name Username
543 * @return int|null The corresponding user's ID, or null if user is nonexistent
545 public static function idFromName( $name ) {
546 $nt = Title
::makeTitleSafe( NS_USER
, $name );
547 if ( is_null( $nt ) ) {
552 if ( isset( self
::$idCacheByName[$name] ) ) {
553 return self
::$idCacheByName[$name];
556 $dbr = wfGetDB( DB_SLAVE
);
557 $s = $dbr->selectRow(
560 array( 'user_name' => $nt->getText() ),
564 if ( $s === false ) {
567 $result = $s->user_id
;
570 self
::$idCacheByName[$name] = $result;
572 if ( count( self
::$idCacheByName ) > 1000 ) {
573 self
::$idCacheByName = array();
580 * Reset the cache used in idFromName(). For use in tests.
582 public static function resetIdByNameCache() {
583 self
::$idCacheByName = array();
587 * Does the string match an anonymous IPv4 address?
589 * This function exists for username validation, in order to reject
590 * usernames which are similar in form to IP addresses. Strings such
591 * as 300.300.300.300 will return true because it looks like an IP
592 * address, despite not being strictly valid.
594 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
595 * address because the usemod software would "cloak" anonymous IP
596 * addresses like this, if we allowed accounts like this to be created
597 * new users could get the old edits of these anonymous users.
599 * @param string $name Name to match
602 public static function isIP( $name ) {
603 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
604 || IP
::isIPv6( $name );
608 * Is the input a valid username?
610 * Checks if the input is a valid username, we don't want an empty string,
611 * an IP address, anything that contains slashes (would mess up subpages),
612 * is longer than the maximum allowed username size or doesn't begin with
615 * @param string $name Name to match
618 public static function isValidUserName( $name ) {
619 global $wgContLang, $wgMaxNameChars;
622 || User
::isIP( $name )
623 ||
strpos( $name, '/' ) !== false
624 ||
strlen( $name ) > $wgMaxNameChars
625 ||
$name != $wgContLang->ucfirst( $name ) ) {
626 wfDebugLog( 'username', __METHOD__
.
627 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
631 // Ensure that the name can't be misresolved as a different title,
632 // such as with extra namespace keys at the start.
633 $parsed = Title
::newFromText( $name );
634 if ( is_null( $parsed )
635 ||
$parsed->getNamespace()
636 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
637 wfDebugLog( 'username', __METHOD__
.
638 ": '$name' invalid due to ambiguous prefixes" );
642 // Check an additional blacklist of troublemaker characters.
643 // Should these be merged into the title char list?
644 $unicodeBlacklist = '/[' .
645 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
646 '\x{00a0}' . # non-breaking space
647 '\x{2000}-\x{200f}' . # various whitespace
648 '\x{2028}-\x{202f}' . # breaks and control chars
649 '\x{3000}' . # ideographic space
650 '\x{e000}-\x{f8ff}' . # private use
652 if ( preg_match( $unicodeBlacklist, $name ) ) {
653 wfDebugLog( 'username', __METHOD__
.
654 ": '$name' invalid due to blacklisted characters" );
662 * Usernames which fail to pass this function will be blocked
663 * from user login and new account registrations, but may be used
664 * internally by batch processes.
666 * If an account already exists in this form, login will be blocked
667 * by a failure to pass this function.
669 * @param string $name Name to match
672 public static function isUsableName( $name ) {
673 global $wgReservedUsernames;
674 // Must be a valid username, obviously ;)
675 if ( !self
::isValidUserName( $name ) ) {
679 static $reservedUsernames = false;
680 if ( !$reservedUsernames ) {
681 $reservedUsernames = $wgReservedUsernames;
682 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
685 // Certain names may be reserved for batch processes.
686 foreach ( $reservedUsernames as $reserved ) {
687 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
688 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
690 if ( $reserved == $name ) {
698 * Usernames which fail to pass this function will be blocked
699 * from new account registrations, but may be used internally
700 * either by batch processes or by user accounts which have
701 * already been created.
703 * Additional blacklisting may be added here rather than in
704 * isValidUserName() to avoid disrupting existing accounts.
706 * @param string $name String to match
709 public static function isCreatableName( $name ) {
710 global $wgInvalidUsernameCharacters;
712 // Ensure that the username isn't longer than 235 bytes, so that
713 // (at least for the builtin skins) user javascript and css files
714 // will work. (bug 23080)
715 if ( strlen( $name ) > 235 ) {
716 wfDebugLog( 'username', __METHOD__
.
717 ": '$name' invalid due to length" );
721 // Preg yells if you try to give it an empty string
722 if ( $wgInvalidUsernameCharacters !== '' ) {
723 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
724 wfDebugLog( 'username', __METHOD__
.
725 ": '$name' invalid due to wgInvalidUsernameCharacters" );
730 return self
::isUsableName( $name );
734 * Is the input a valid password for this user?
736 * @param string $password Desired password
739 public function isValidPassword( $password ) {
740 //simple boolean wrapper for getPasswordValidity
741 return $this->getPasswordValidity( $password ) === true;
746 * Given unvalidated password input, return error message on failure.
748 * @param string $password Desired password
749 * @return bool|string|array True on success, string or array of error message on failure
751 public function getPasswordValidity( $password ) {
752 $result = $this->checkPasswordValidity( $password );
753 if ( $result->isGood() ) {
757 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
758 $messages[] = $error['message'];
760 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
761 $messages[] = $warning['message'];
763 if ( count( $messages ) === 1 ) {
771 * Check if this is a valid password for this user. Status will be good if
772 * the password is valid, or have an array of error messages if not.
774 * @param string $password Desired password
778 public function checkPasswordValidity( $password ) {
779 global $wgMinimalPasswordLength, $wgContLang;
781 static $blockedLogins = array(
782 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
783 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
786 $status = Status
::newGood();
788 $result = false; //init $result to false for the internal checks
790 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
791 $status->error( $result );
795 if ( $result === false ) {
796 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
797 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
799 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
800 $status->error( 'password-name-match' );
802 } elseif ( isset( $blockedLogins[$this->getName()] )
803 && $password == $blockedLogins[$this->getName()]
805 $status->error( 'password-login-forbidden' );
808 //it seems weird returning a Good status here, but this is because of the
809 //initialization of $result to false above. If the hook is never run or it
810 //doesn't modify $result, then we will likely get down into this if with
814 } elseif ( $result === true ) {
817 $status->error( $result );
818 return $status; //the isValidPassword hook set a string $result and returned true
823 * Expire a user's password
825 * @param int $ts Optional timestamp to convert, default 0 for the current time
827 public function expirePassword( $ts = 0 ) {
829 $timestamp = wfTimestamp( TS_MW
, $ts );
830 $this->mPasswordExpires
= $timestamp;
831 $this->saveSettings();
835 * Clear the password expiration for a user
837 * @param bool $load Ensure user object is loaded first
839 public function resetPasswordExpiration( $load = true ) {
840 global $wgPasswordExpirationDays;
845 if ( $wgPasswordExpirationDays ) {
846 $newExpire = wfTimestamp(
848 time() +
( $wgPasswordExpirationDays * 24 * 3600 )
851 // Give extensions a chance to force an expiration
852 wfRunHooks( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
853 $this->mPasswordExpires
= $newExpire;
857 * Check if the user's password is expired.
858 * TODO: Put this and password length into a PasswordPolicy object
860 * @return string|bool The expiration type, or false if not expired
861 * hard: A password change is required to login
862 * soft: Allow login, but encourage password change
863 * false: Password is not expired
865 public function getPasswordExpired() {
866 global $wgPasswordExpireGrace;
868 $now = wfTimestamp();
869 $expiration = $this->getPasswordExpireDate();
870 $expUnix = wfTimestamp( TS_UNIX
, $expiration );
871 if ( $expiration !== null && $expUnix < $now ) {
872 $expired = ( $expUnix +
$wgPasswordExpireGrace < $now ) ?
'hard' : 'soft';
878 * Get this user's password expiration date. Since this may be using
879 * the cached User object, we assume that whatever mechanism is setting
880 * the expiration date is also expiring the User cache.
882 * @return string|bool The datestamp of the expiration, or null if not set
884 public function getPasswordExpireDate() {
886 return $this->mPasswordExpires
;
890 * Given unvalidated user input, return a canonical username, or false if
891 * the username is invalid.
892 * @param string $name User input
893 * @param string|bool $validate Type of validation to use:
894 * - false No validation
895 * - 'valid' Valid for batch processes
896 * - 'usable' Valid for batch processes and login
897 * - 'creatable' Valid for batch processes, login and account creation
899 * @throws MWException
900 * @return bool|string
902 public static function getCanonicalName( $name, $validate = 'valid' ) {
903 // Force usernames to capital
905 $name = $wgContLang->ucfirst( $name );
907 # Reject names containing '#'; these will be cleaned up
908 # with title normalisation, but then it's too late to
910 if ( strpos( $name, '#' ) !== false ) {
914 // Clean up name according to title rules
915 $t = ( $validate === 'valid' ) ?
916 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
917 // Check for invalid titles
918 if ( is_null( $t ) ) {
922 // Reject various classes of invalid names
924 $name = $wgAuth->getCanonicalName( $t->getText() );
926 switch ( $validate ) {
930 if ( !User
::isValidUserName( $name ) ) {
935 if ( !User
::isUsableName( $name ) ) {
940 if ( !User
::isCreatableName( $name ) ) {
945 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
951 * Count the number of edits of a user
953 * @param int $uid User ID to check
954 * @return int The user's edit count
956 * @deprecated since 1.21 in favour of User::getEditCount
958 public static function edits( $uid ) {
959 wfDeprecated( __METHOD__
, '1.21' );
960 $user = self
::newFromId( $uid );
961 return $user->getEditCount();
965 * Return a random password.
967 * @return string New random password
969 public static function randomPassword() {
970 global $wgMinimalPasswordLength;
971 // Decide the final password length based on our min password length,
972 // stopping at a minimum of 10 chars.
973 $length = max( 10, $wgMinimalPasswordLength );
974 // Multiply by 1.25 to get the number of hex characters we need
975 $length = $length * 1.25;
976 // Generate random hex chars
977 $hex = MWCryptRand
::generateHex( $length );
978 // Convert from base 16 to base 32 to get a proper password like string
979 return wfBaseConvert( $hex, 16, 32 );
983 * Set cached properties to default.
985 * @note This no longer clears uncached lazy-initialised properties;
986 * the constructor does that instead.
988 * @param string|bool $name
990 public function loadDefaults( $name = false ) {
991 wfProfileIn( __METHOD__
);
993 $passwordFactory = self
::getPasswordFactory();
996 $this->mName
= $name;
997 $this->mRealName
= '';
998 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
999 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1000 $this->mNewpassTime
= null;
1002 $this->mOptionOverrides
= null;
1003 $this->mOptionsLoaded
= false;
1005 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1006 if ( $loggedOut !== null ) {
1007 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1009 $this->mTouched
= '1'; # Allow any pages to be cached
1012 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1013 $this->mEmailAuthenticated
= null;
1014 $this->mEmailToken
= '';
1015 $this->mEmailTokenExpires
= null;
1016 $this->mPasswordExpires
= null;
1017 $this->resetPasswordExpiration( false );
1018 $this->mRegistration
= wfTimestamp( TS_MW
);
1019 $this->mGroups
= array();
1021 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
1023 wfProfileOut( __METHOD__
);
1027 * Return whether an item has been loaded.
1029 * @param string $item Item to check. Current possibilities:
1033 * @param string $all 'all' to check if the whole object has been loaded
1034 * or any other string to check if only the item is available (e.g.
1038 public function isItemLoaded( $item, $all = 'all' ) {
1039 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1040 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1044 * Set that an item has been loaded
1046 * @param string $item
1048 protected function setItemLoaded( $item ) {
1049 if ( is_array( $this->mLoadedItems
) ) {
1050 $this->mLoadedItems
[$item] = true;
1055 * Load user data from the session or login cookie.
1056 * @return bool True if the user is logged in, false otherwise.
1058 private function loadFromSession() {
1060 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
1061 if ( $result !== null ) {
1065 $request = $this->getRequest();
1067 $cookieId = $request->getCookie( 'UserID' );
1068 $sessId = $request->getSessionData( 'wsUserID' );
1070 if ( $cookieId !== null ) {
1071 $sId = intval( $cookieId );
1072 if ( $sessId !== null && $cookieId != $sessId ) {
1073 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1074 cookie user ID ($sId) don't match!" );
1077 $request->setSessionData( 'wsUserID', $sId );
1078 } elseif ( $sessId !== null && $sessId != 0 ) {
1084 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1085 $sName = $request->getSessionData( 'wsUserName' );
1086 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1087 $sName = $request->getCookie( 'UserName' );
1088 $request->setSessionData( 'wsUserName', $sName );
1093 $proposedUser = User
::newFromId( $sId );
1094 if ( !$proposedUser->isLoggedIn() ) {
1099 global $wgBlockDisablesLogin;
1100 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1101 // User blocked and we've disabled blocked user logins
1105 if ( $request->getSessionData( 'wsToken' ) ) {
1107 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1109 } elseif ( $request->getCookie( 'Token' ) ) {
1110 # Get the token from DB/cache and clean it up to remove garbage padding.
1111 # This deals with historical problems with bugs and the default column value.
1112 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1113 // Make comparison in constant time (bug 61346)
1114 $passwordCorrect = strlen( $token )
1115 && hash_equals( $token, $request->getCookie( 'Token' ) );
1118 // No session or persistent login cookie
1122 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1123 $this->loadFromUserObject( $proposedUser );
1124 $request->setSessionData( 'wsToken', $this->mToken
);
1125 wfDebug( "User: logged in from $from\n" );
1128 // Invalid credentials
1129 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1135 * Load user and user_group data from the database.
1136 * $this->mId must be set, this is how the user is identified.
1138 * @param int $flags Supports User::READ_LOCKING
1139 * @return bool True if the user exists, false if the user is anonymous
1141 public function loadFromDatabase( $flags = 0 ) {
1143 $this->mId
= intval( $this->mId
);
1146 if ( !$this->mId
) {
1147 $this->loadDefaults();
1151 $dbr = wfGetDB( DB_MASTER
);
1152 $s = $dbr->selectRow(
1154 self
::selectFields(),
1155 array( 'user_id' => $this->mId
),
1157 ( $flags & self
::READ_LOCKING
== self
::READ_LOCKING
)
1158 ?
array( 'LOCK IN SHARE MODE' )
1162 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1164 if ( $s !== false ) {
1165 // Initialise user table data
1166 $this->loadFromRow( $s );
1167 $this->mGroups
= null; // deferred
1168 $this->getEditCount(); // revalidation for nulls
1173 $this->loadDefaults();
1179 * Initialize this object from a row from the user table.
1181 * @param stdClass $row Row from the user table to load.
1182 * @param array $data Further user data to load into the object
1184 * user_groups Array with groups out of the user_groups table
1185 * user_properties Array with properties out of the user_properties table
1187 public function loadFromRow( $row, $data = null ) {
1189 $passwordFactory = self
::getPasswordFactory();
1191 $this->mGroups
= null; // deferred
1193 if ( isset( $row->user_name
) ) {
1194 $this->mName
= $row->user_name
;
1195 $this->mFrom
= 'name';
1196 $this->setItemLoaded( 'name' );
1201 if ( isset( $row->user_real_name
) ) {
1202 $this->mRealName
= $row->user_real_name
;
1203 $this->setItemLoaded( 'realname' );
1208 if ( isset( $row->user_id
) ) {
1209 $this->mId
= intval( $row->user_id
);
1210 $this->mFrom
= 'id';
1211 $this->setItemLoaded( 'id' );
1216 if ( isset( $row->user_editcount
) ) {
1217 $this->mEditCount
= $row->user_editcount
;
1222 if ( isset( $row->user_password
) ) {
1223 // Check for *really* old password hashes that don't even have a type
1224 // The old hash format was just an md5 hex hash, with no type information
1225 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password
) ) {
1226 $row->user_password
= ":A:{$this->mId}:{$row->user_password}";
1230 $this->mPassword
= $passwordFactory->newFromCiphertext( $row->user_password
);
1231 } catch ( PasswordError
$e ) {
1232 wfDebug( 'Invalid password hash found in database.' );
1233 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1237 $this->mNewpassword
= $passwordFactory->newFromCiphertext( $row->user_newpassword
);
1238 } catch ( PasswordError
$e ) {
1239 wfDebug( 'Invalid password hash found in database.' );
1240 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1243 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1244 $this->mPasswordExpires
= wfTimestampOrNull( TS_MW
, $row->user_password_expires
);
1247 if ( isset( $row->user_email
) ) {
1248 $this->mEmail
= $row->user_email
;
1249 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1250 $this->mToken
= $row->user_token
;
1251 if ( $this->mToken
== '' ) {
1252 $this->mToken
= null;
1254 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1255 $this->mEmailToken
= $row->user_email_token
;
1256 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1257 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1263 $this->mLoadedItems
= true;
1266 if ( is_array( $data ) ) {
1267 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1268 $this->mGroups
= $data['user_groups'];
1270 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1271 $this->loadOptions( $data['user_properties'] );
1277 * Load the data for this user object from another user object.
1281 protected function loadFromUserObject( $user ) {
1283 $user->loadGroups();
1284 $user->loadOptions();
1285 foreach ( self
::$mCacheVars as $var ) {
1286 $this->$var = $user->$var;
1291 * Load the groups from the database if they aren't already loaded.
1293 private function loadGroups() {
1294 if ( is_null( $this->mGroups
) ) {
1295 $dbr = wfGetDB( DB_MASTER
);
1296 $res = $dbr->select( 'user_groups',
1297 array( 'ug_group' ),
1298 array( 'ug_user' => $this->mId
),
1300 $this->mGroups
= array();
1301 foreach ( $res as $row ) {
1302 $this->mGroups
[] = $row->ug_group
;
1308 * Load the user's password hashes from the database
1310 * This is usually called in a scenario where the actual User object was
1311 * loaded from the cache, and then password comparison needs to be performed.
1312 * Password hashes are not stored in memcached.
1316 private function loadPasswords() {
1317 if ( $this->getId() !== 0 && ( $this->mPassword
=== null ||
$this->mNewpassword
=== null ) ) {
1318 $this->loadFromRow( wfGetDB( DB_MASTER
)->selectRow(
1320 array( 'user_password', 'user_newpassword', 'user_newpass_time', 'user_password_expires' ),
1321 array( 'user_id' => $this->getId() ),
1328 * Add the user to the group if he/she meets given criteria.
1330 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1331 * possible to remove manually via Special:UserRights. In such case it
1332 * will not be re-added automatically. The user will also not lose the
1333 * group if they no longer meet the criteria.
1335 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1337 * @return array Array of groups the user has been promoted to.
1339 * @see $wgAutopromoteOnce
1341 public function addAutopromoteOnceGroups( $event ) {
1342 global $wgAutopromoteOnceLogInRC, $wgAuth;
1344 $toPromote = array();
1345 if ( $this->getId() ) {
1346 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1347 if ( count( $toPromote ) ) {
1348 $oldGroups = $this->getGroups(); // previous groups
1350 foreach ( $toPromote as $group ) {
1351 $this->addGroup( $group );
1353 // update groups in external authentication database
1354 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1356 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1358 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1359 $logEntry->setPerformer( $this );
1360 $logEntry->setTarget( $this->getUserPage() );
1361 $logEntry->setParameters( array(
1362 '4::oldgroups' => $oldGroups,
1363 '5::newgroups' => $newGroups,
1365 $logid = $logEntry->insert();
1366 if ( $wgAutopromoteOnceLogInRC ) {
1367 $logEntry->publish( $logid );
1375 * Clear various cached data stored in this object. The cache of the user table
1376 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1378 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1379 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1381 public function clearInstanceCache( $reloadFrom = false ) {
1382 $this->mNewtalk
= -1;
1383 $this->mDatePreference
= null;
1384 $this->mBlockedby
= -1; # Unset
1385 $this->mHash
= false;
1386 $this->mRights
= null;
1387 $this->mEffectiveGroups
= null;
1388 $this->mImplicitGroups
= null;
1389 $this->mGroups
= null;
1390 $this->mOptions
= null;
1391 $this->mOptionsLoaded
= false;
1392 $this->mEditCount
= null;
1394 if ( $reloadFrom ) {
1395 $this->mLoadedItems
= array();
1396 $this->mFrom
= $reloadFrom;
1401 * Combine the language default options with any site-specific options
1402 * and add the default language variants.
1404 * @return array Array of String options
1406 public static function getDefaultOptions() {
1407 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1409 static $defOpt = null;
1410 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1411 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1412 // mid-request and see that change reflected in the return value of this function.
1413 // Which is insane and would never happen during normal MW operation
1417 $defOpt = $wgDefaultUserOptions;
1418 // Default language setting
1419 $defOpt['language'] = $wgContLang->getCode();
1420 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1421 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1423 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1424 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1426 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1428 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1434 * Get a given default option value.
1436 * @param string $opt Name of option to retrieve
1437 * @return string Default option value
1439 public static function getDefaultOption( $opt ) {
1440 $defOpts = self
::getDefaultOptions();
1441 if ( isset( $defOpts[$opt] ) ) {
1442 return $defOpts[$opt];
1449 * Get blocking information
1450 * @param bool $bFromSlave Whether to check the slave database first.
1451 * To improve performance, non-critical checks are done against slaves.
1452 * Check when actually saving should be done against master.
1454 private function getBlockedStatus( $bFromSlave = true ) {
1455 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1457 if ( -1 != $this->mBlockedby
) {
1461 wfProfileIn( __METHOD__
);
1462 wfDebug( __METHOD__
. ": checking...\n" );
1464 // Initialize data...
1465 // Otherwise something ends up stomping on $this->mBlockedby when
1466 // things get lazy-loaded later, causing false positive block hits
1467 // due to -1 !== 0. Probably session-related... Nothing should be
1468 // overwriting mBlockedby, surely?
1471 # We only need to worry about passing the IP address to the Block generator if the
1472 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1473 # know which IP address they're actually coming from
1474 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1475 $ip = $this->getRequest()->getIP();
1481 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1484 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1485 && !in_array( $ip, $wgProxyWhitelist )
1488 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1490 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1491 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1492 $block->setTarget( $ip );
1493 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1495 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1496 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1497 $block->setTarget( $ip );
1501 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1502 if ( !$block instanceof Block
1503 && $wgApplyIpBlocksToXff
1505 && !$this->isAllowed( 'proxyunbannable' )
1506 && !in_array( $ip, $wgProxyWhitelist )
1508 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1509 $xff = array_map( 'trim', explode( ',', $xff ) );
1510 $xff = array_diff( $xff, array( $ip ) );
1511 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1512 $block = Block
::chooseBlock( $xffblocks, $xff );
1513 if ( $block instanceof Block
) {
1514 # Mangle the reason to alert the user that the block
1515 # originated from matching the X-Forwarded-For header.
1516 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1520 if ( $block instanceof Block
) {
1521 wfDebug( __METHOD__
. ": Found block.\n" );
1522 $this->mBlock
= $block;
1523 $this->mBlockedby
= $block->getByName();
1524 $this->mBlockreason
= $block->mReason
;
1525 $this->mHideName
= $block->mHideName
;
1526 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1528 $this->mBlockedby
= '';
1529 $this->mHideName
= 0;
1530 $this->mAllowUsertalk
= false;
1534 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1536 wfProfileOut( __METHOD__
);
1540 * Whether the given IP is in a DNS blacklist.
1542 * @param string $ip IP to check
1543 * @param bool $checkWhitelist Whether to check the whitelist first
1544 * @return bool True if blacklisted.
1546 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1547 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1549 if ( !$wgEnableDnsBlacklist ) {
1553 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1557 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1561 * Whether the given IP is in a given DNS blacklist.
1563 * @param string $ip IP to check
1564 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1565 * @return bool True if blacklisted.
1567 public function inDnsBlacklist( $ip, $bases ) {
1568 wfProfileIn( __METHOD__
);
1571 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1572 if ( IP
::isIPv4( $ip ) ) {
1573 // Reverse IP, bug 21255
1574 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1576 foreach ( (array)$bases as $base ) {
1578 // If we have an access key, use that too (ProjectHoneypot, etc.)
1579 if ( is_array( $base ) ) {
1580 if ( count( $base ) >= 2 ) {
1581 // Access key is 1, base URL is 0
1582 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1584 $host = "$ipReversed.{$base[0]}";
1587 $host = "$ipReversed.$base";
1591 $ipList = gethostbynamel( $host );
1594 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1598 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1603 wfProfileOut( __METHOD__
);
1608 * Check if an IP address is in the local proxy list
1614 public static function isLocallyBlockedProxy( $ip ) {
1615 global $wgProxyList;
1617 if ( !$wgProxyList ) {
1620 wfProfileIn( __METHOD__
);
1622 if ( !is_array( $wgProxyList ) ) {
1623 // Load from the specified file
1624 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1627 if ( !is_array( $wgProxyList ) ) {
1629 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1631 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1632 // Old-style flipped proxy list
1637 wfProfileOut( __METHOD__
);
1642 * Is this user subject to rate limiting?
1644 * @return bool True if rate limited
1646 public function isPingLimitable() {
1647 global $wgRateLimitsExcludedIPs;
1648 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1649 // No other good way currently to disable rate limits
1650 // for specific IPs. :P
1651 // But this is a crappy hack and should die.
1654 return !$this->isAllowed( 'noratelimit' );
1658 * Primitive rate limits: enforce maximum actions per time period
1659 * to put a brake on flooding.
1661 * The method generates both a generic profiling point and a per action one
1662 * (suffix being "-$action".
1664 * @note When using a shared cache like memcached, IP-address
1665 * last-hit counters will be shared across wikis.
1667 * @param string $action Action to enforce; 'edit' if unspecified
1668 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1669 * @return bool True if a rate limiter was tripped
1671 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1672 // Call the 'PingLimiter' hook
1674 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1678 global $wgRateLimits;
1679 if ( !isset( $wgRateLimits[$action] ) ) {
1683 // Some groups shouldn't trigger the ping limiter, ever
1684 if ( !$this->isPingLimitable() ) {
1689 wfProfileIn( __METHOD__
);
1690 wfProfileIn( __METHOD__
. '-' . $action );
1692 $limits = $wgRateLimits[$action];
1694 $id = $this->getId();
1697 if ( isset( $limits['anon'] ) && $id == 0 ) {
1698 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1701 if ( isset( $limits['user'] ) && $id != 0 ) {
1702 $userLimit = $limits['user'];
1704 if ( $this->isNewbie() ) {
1705 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1706 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1708 if ( isset( $limits['ip'] ) ) {
1709 $ip = $this->getRequest()->getIP();
1710 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1712 if ( isset( $limits['subnet'] ) ) {
1713 $ip = $this->getRequest()->getIP();
1716 if ( IP
::isIPv6( $ip ) ) {
1717 $parts = IP
::parseRange( "$ip/64" );
1718 $subnet = $parts[0];
1719 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1721 $subnet = $matches[1];
1723 if ( $subnet !== false ) {
1724 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1728 // Check for group-specific permissions
1729 // If more than one group applies, use the group with the highest limit
1730 foreach ( $this->getGroups() as $group ) {
1731 if ( isset( $limits[$group] ) ) {
1732 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1733 $userLimit = $limits[$group];
1737 // Set the user limit key
1738 if ( $userLimit !== false ) {
1739 list( $max, $period ) = $userLimit;
1740 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1741 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1745 foreach ( $keys as $key => $limit ) {
1746 list( $max, $period ) = $limit;
1747 $summary = "(limit $max in {$period}s)";
1748 $count = $wgMemc->get( $key );
1751 if ( $count >= $max ) {
1752 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1753 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1756 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1759 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1760 if ( $incrBy > 0 ) {
1761 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1764 if ( $incrBy > 0 ) {
1765 $wgMemc->incr( $key, $incrBy );
1769 wfProfileOut( __METHOD__
. '-' . $action );
1770 wfProfileOut( __METHOD__
);
1775 * Check if user is blocked
1777 * @param bool $bFromSlave Whether to check the slave database instead of
1778 * the master. Hacked from false due to horrible probs on site.
1779 * @return bool True if blocked, false otherwise
1781 public function isBlocked( $bFromSlave = true ) {
1782 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1786 * Get the block affecting the user, or null if the user is not blocked
1788 * @param bool $bFromSlave Whether to check the slave database instead of the master
1789 * @return Block|null
1791 public function getBlock( $bFromSlave = true ) {
1792 $this->getBlockedStatus( $bFromSlave );
1793 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1797 * Check if user is blocked from editing a particular article
1799 * @param Title $title Title to check
1800 * @param bool $bFromSlave Whether to check the slave database instead of the master
1803 public function isBlockedFrom( $title, $bFromSlave = false ) {
1804 global $wgBlockAllowsUTEdit;
1805 wfProfileIn( __METHOD__
);
1807 $blocked = $this->isBlocked( $bFromSlave );
1808 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1809 // If a user's name is suppressed, they cannot make edits anywhere
1810 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1811 && $title->getNamespace() == NS_USER_TALK
) {
1813 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1816 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1818 wfProfileOut( __METHOD__
);
1823 * If user is blocked, return the name of the user who placed the block
1824 * @return string Name of blocker
1826 public function blockedBy() {
1827 $this->getBlockedStatus();
1828 return $this->mBlockedby
;
1832 * If user is blocked, return the specified reason for the block
1833 * @return string Blocking reason
1835 public function blockedFor() {
1836 $this->getBlockedStatus();
1837 return $this->mBlockreason
;
1841 * If user is blocked, return the ID for the block
1842 * @return int Block ID
1844 public function getBlockId() {
1845 $this->getBlockedStatus();
1846 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1850 * Check if user is blocked on all wikis.
1851 * Do not use for actual edit permission checks!
1852 * This is intended for quick UI checks.
1854 * @param string $ip IP address, uses current client if none given
1855 * @return bool True if blocked, false otherwise
1857 public function isBlockedGlobally( $ip = '' ) {
1858 if ( $this->mBlockedGlobally
!== null ) {
1859 return $this->mBlockedGlobally
;
1861 // User is already an IP?
1862 if ( IP
::isIPAddress( $this->getName() ) ) {
1863 $ip = $this->getName();
1865 $ip = $this->getRequest()->getIP();
1868 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1869 $this->mBlockedGlobally
= (bool)$blocked;
1870 return $this->mBlockedGlobally
;
1874 * Check if user account is locked
1876 * @return bool True if locked, false otherwise
1878 public function isLocked() {
1879 if ( $this->mLocked
!== null ) {
1880 return $this->mLocked
;
1883 StubObject
::unstub( $wgAuth );
1884 $authUser = $wgAuth->getUserInstance( $this );
1885 $this->mLocked
= (bool)$authUser->isLocked();
1886 return $this->mLocked
;
1890 * Check if user account is hidden
1892 * @return bool True if hidden, false otherwise
1894 public function isHidden() {
1895 if ( $this->mHideName
!== null ) {
1896 return $this->mHideName
;
1898 $this->getBlockedStatus();
1899 if ( !$this->mHideName
) {
1901 StubObject
::unstub( $wgAuth );
1902 $authUser = $wgAuth->getUserInstance( $this );
1903 $this->mHideName
= (bool)$authUser->isHidden();
1905 return $this->mHideName
;
1909 * Get the user's ID.
1910 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1912 public function getId() {
1913 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1914 // Special case, we know the user is anonymous
1916 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1917 // Don't load if this was initialized from an ID
1924 * Set the user and reload all fields according to a given ID
1925 * @param int $v User ID to reload
1927 public function setId( $v ) {
1929 $this->clearInstanceCache( 'id' );
1933 * Get the user name, or the IP of an anonymous user
1934 * @return string User's name or IP address
1936 public function getName() {
1937 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1938 // Special case optimisation
1939 return $this->mName
;
1942 if ( $this->mName
=== false ) {
1944 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1946 return $this->mName
;
1951 * Set the user name.
1953 * This does not reload fields from the database according to the given
1954 * name. Rather, it is used to create a temporary "nonexistent user" for
1955 * later addition to the database. It can also be used to set the IP
1956 * address for an anonymous user to something other than the current
1959 * @note User::newFromName() has roughly the same function, when the named user
1961 * @param string $str New user name to set
1963 public function setName( $str ) {
1965 $this->mName
= $str;
1969 * Get the user's name escaped by underscores.
1970 * @return string Username escaped by underscores.
1972 public function getTitleKey() {
1973 return str_replace( ' ', '_', $this->getName() );
1977 * Check if the user has new messages.
1978 * @return bool True if the user has new messages
1980 public function getNewtalk() {
1983 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1984 if ( $this->mNewtalk
=== -1 ) {
1985 $this->mNewtalk
= false; # reset talk page status
1987 // Check memcached separately for anons, who have no
1988 // entire User object stored in there.
1989 if ( !$this->mId
) {
1990 global $wgDisableAnonTalk;
1991 if ( $wgDisableAnonTalk ) {
1992 // Anon newtalk disabled by configuration.
1993 $this->mNewtalk
= false;
1996 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1997 $newtalk = $wgMemc->get( $key );
1998 if ( strval( $newtalk ) !== '' ) {
1999 $this->mNewtalk
= (bool)$newtalk;
2001 // Since we are caching this, make sure it is up to date by getting it
2003 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
2004 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
2008 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2012 return (bool)$this->mNewtalk
;
2016 * Return the data needed to construct links for new talk page message
2017 * alerts. If there are new messages, this will return an associative array
2018 * with the following data:
2019 * wiki: The database name of the wiki
2020 * link: Root-relative link to the user's talk page
2021 * rev: The last talk page revision that the user has seen or null. This
2022 * is useful for building diff links.
2023 * If there are no new messages, it returns an empty array.
2024 * @note This function was designed to accomodate multiple talk pages, but
2025 * currently only returns a single link and revision.
2028 public function getNewMessageLinks() {
2030 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2032 } elseif ( !$this->getNewtalk() ) {
2035 $utp = $this->getTalkPage();
2036 $dbr = wfGetDB( DB_SLAVE
);
2037 // Get the "last viewed rev" timestamp from the oldest message notification
2038 $timestamp = $dbr->selectField( 'user_newtalk',
2039 'MIN(user_last_timestamp)',
2040 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2042 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2043 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2047 * Get the revision ID for the last talk page revision viewed by the talk
2049 * @return int|null Revision ID or null
2051 public function getNewMessageRevisionId() {
2052 $newMessageRevisionId = null;
2053 $newMessageLinks = $this->getNewMessageLinks();
2054 if ( $newMessageLinks ) {
2055 // Note: getNewMessageLinks() never returns more than a single link
2056 // and it is always for the same wiki, but we double-check here in
2057 // case that changes some time in the future.
2058 if ( count( $newMessageLinks ) === 1
2059 && $newMessageLinks[0]['wiki'] === wfWikiID()
2060 && $newMessageLinks[0]['rev']
2062 $newMessageRevision = $newMessageLinks[0]['rev'];
2063 $newMessageRevisionId = $newMessageRevision->getId();
2066 return $newMessageRevisionId;
2070 * Internal uncached check for new messages
2073 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2074 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2075 * @param bool $fromMaster True to fetch from the master, false for a slave
2076 * @return bool True if the user has new messages
2078 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2079 if ( $fromMaster ) {
2080 $db = wfGetDB( DB_MASTER
);
2082 $db = wfGetDB( DB_SLAVE
);
2084 $ok = $db->selectField( 'user_newtalk', $field,
2085 array( $field => $id ), __METHOD__
);
2086 return $ok !== false;
2090 * Add or update the new messages flag
2091 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2092 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2093 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2094 * @return bool True if successful, false otherwise
2096 protected function updateNewtalk( $field, $id, $curRev = null ) {
2097 // Get timestamp of the talk page revision prior to the current one
2098 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2099 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2100 // Mark the user as having new messages since this revision
2101 $dbw = wfGetDB( DB_MASTER
);
2102 $dbw->insert( 'user_newtalk',
2103 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2106 if ( $dbw->affectedRows() ) {
2107 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2110 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2116 * Clear the new messages flag for the given user
2117 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2118 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2119 * @return bool True if successful, false otherwise
2121 protected function deleteNewtalk( $field, $id ) {
2122 $dbw = wfGetDB( DB_MASTER
);
2123 $dbw->delete( 'user_newtalk',
2124 array( $field => $id ),
2126 if ( $dbw->affectedRows() ) {
2127 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2130 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2136 * Update the 'You have new messages!' status.
2137 * @param bool $val Whether the user has new messages
2138 * @param Revision $curRev New, as yet unseen revision of the user talk
2139 * page. Ignored if null or !$val.
2141 public function setNewtalk( $val, $curRev = null ) {
2142 if ( wfReadOnly() ) {
2147 $this->mNewtalk
= $val;
2149 if ( $this->isAnon() ) {
2151 $id = $this->getName();
2154 $id = $this->getId();
2159 $changed = $this->updateNewtalk( $field, $id, $curRev );
2161 $changed = $this->deleteNewtalk( $field, $id );
2164 if ( $this->isAnon() ) {
2165 // Anons have a separate memcached space, since
2166 // user records aren't kept for them.
2167 $key = wfMemcKey( 'newtalk', 'ip', $id );
2168 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
2171 $this->invalidateCache();
2176 * Generate a current or new-future timestamp to be stored in the
2177 * user_touched field when we update things.
2178 * @return string Timestamp in TS_MW format
2180 private static function newTouchedTimestamp() {
2181 global $wgClockSkewFudge;
2182 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2186 * Clear user data from memcached.
2187 * Use after applying fun updates to the database; caller's
2188 * responsibility to update user_touched if appropriate.
2190 * Called implicitly from invalidateCache() and saveSettings().
2192 public function clearSharedCache() {
2196 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
2201 * Immediately touch the user data cache for this account.
2202 * Updates user_touched field, and removes account data from memcached
2203 * for reload on the next hit.
2205 public function invalidateCache() {
2206 if ( wfReadOnly() ) {
2211 $this->mTouched
= self
::newTouchedTimestamp();
2213 $dbw = wfGetDB( DB_MASTER
);
2214 $userid = $this->mId
;
2215 $touched = $this->mTouched
;
2216 $method = __METHOD__
;
2217 $dbw->onTransactionIdle( function () use ( $dbw, $userid, $touched, $method ) {
2218 // Prevent contention slams by checking user_touched first
2219 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2220 $needsPurge = $dbw->selectField( 'user', '1',
2221 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2222 if ( $needsPurge ) {
2223 $dbw->update( 'user',
2224 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2225 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2230 $this->clearSharedCache();
2235 * Validate the cache for this account.
2236 * @param string $timestamp A timestamp in TS_MW format
2239 public function validateCache( $timestamp ) {
2241 return ( $timestamp >= $this->mTouched
);
2245 * Get the user touched timestamp
2246 * @return string Timestamp
2248 public function getTouched() {
2250 return $this->mTouched
;
2254 * Set the password and reset the random token.
2255 * Calls through to authentication plugin if necessary;
2256 * will have no effect if the auth plugin refuses to
2257 * pass the change through or if the legal password
2260 * As a special case, setting the password to null
2261 * wipes it, so the account cannot be logged in until
2262 * a new password is set, for instance via e-mail.
2264 * @param string $str New password to set
2265 * @throws PasswordError On failure
2269 public function setPassword( $str ) {
2272 if ( $str !== null ) {
2273 if ( !$wgAuth->allowPasswordChange() ) {
2274 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2277 if ( !$this->isValidPassword( $str ) ) {
2278 global $wgMinimalPasswordLength;
2279 $valid = $this->getPasswordValidity( $str );
2280 if ( is_array( $valid ) ) {
2281 $message = array_shift( $valid );
2285 $params = array( $wgMinimalPasswordLength );
2287 throw new PasswordError( wfMessage( $message, $params )->text() );
2291 if ( !$wgAuth->setPassword( $this, $str ) ) {
2292 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2295 $this->setInternalPassword( $str );
2301 * Set the password and reset the random token unconditionally.
2303 * @param string|null $str New password to set or null to set an invalid
2304 * password hash meaning that the user will not be able to log in
2305 * through the web interface.
2307 public function setInternalPassword( $str ) {
2310 $passwordFactory = self
::getPasswordFactory();
2311 if ( $str === null ) {
2312 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
2314 $this->mPassword
= $passwordFactory->newFromPlaintext( $str );
2317 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
2318 $this->mNewpassTime
= null;
2322 * Get the user's current token.
2323 * @param bool $forceCreation Force the generation of a new token if the
2324 * user doesn't have one (default=true for backwards compatibility).
2325 * @return string Token
2327 public function getToken( $forceCreation = true ) {
2329 if ( !$this->mToken
&& $forceCreation ) {
2332 return $this->mToken
;
2336 * Set the random token (used for persistent authentication)
2337 * Called from loadDefaults() among other places.
2339 * @param string|bool $token If specified, set the token to this value
2341 public function setToken( $token = false ) {
2344 $this->mToken
= MWCryptRand
::generateHex( USER_TOKEN_LENGTH
);
2346 $this->mToken
= $token;
2351 * Set the password for a password reminder or new account email
2353 * @param string $str New password to set or null to set an invalid
2354 * password hash meaning that the user will not be able to use it
2355 * @param bool $throttle If true, reset the throttle timestamp to the present
2357 public function setNewpassword( $str, $throttle = true ) {
2360 if ( $str === null ) {
2361 $this->mNewpassword
= '';
2362 $this->mNewpassTime
= null;
2364 $this->mNewpassword
= self
::getPasswordFactory()->newFromPlaintext( $str );
2366 $this->mNewpassTime
= wfTimestampNow();
2372 * Has password reminder email been sent within the last
2373 * $wgPasswordReminderResendTime hours?
2376 public function isPasswordReminderThrottled() {
2377 global $wgPasswordReminderResendTime;
2379 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2382 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2383 return time() < $expiry;
2387 * Get the user's e-mail address
2388 * @return string User's email address
2390 public function getEmail() {
2392 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
2393 return $this->mEmail
;
2397 * Get the timestamp of the user's e-mail authentication
2398 * @return string TS_MW timestamp
2400 public function getEmailAuthenticationTimestamp() {
2402 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2403 return $this->mEmailAuthenticated
;
2407 * Set the user's e-mail address
2408 * @param string $str New e-mail address
2410 public function setEmail( $str ) {
2412 if ( $str == $this->mEmail
) {
2415 $this->mEmail
= $str;
2416 $this->invalidateEmail();
2417 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
2421 * Set the user's e-mail address and a confirmation mail if needed.
2424 * @param string $str New e-mail address
2427 public function setEmailWithConfirmation( $str ) {
2428 global $wgEnableEmail, $wgEmailAuthentication;
2430 if ( !$wgEnableEmail ) {
2431 return Status
::newFatal( 'emaildisabled' );
2434 $oldaddr = $this->getEmail();
2435 if ( $str === $oldaddr ) {
2436 return Status
::newGood( true );
2439 $this->setEmail( $str );
2441 if ( $str !== '' && $wgEmailAuthentication ) {
2442 // Send a confirmation request to the new address if needed
2443 $type = $oldaddr != '' ?
'changed' : 'set';
2444 $result = $this->sendConfirmationMail( $type );
2445 if ( $result->isGood() ) {
2446 // Say the the caller that a confirmation mail has been sent
2447 $result->value
= 'eauth';
2450 $result = Status
::newGood( true );
2457 * Get the user's real name
2458 * @return string User's real name
2460 public function getRealName() {
2461 if ( !$this->isItemLoaded( 'realname' ) ) {
2465 return $this->mRealName
;
2469 * Set the user's real name
2470 * @param string $str New real name
2472 public function setRealName( $str ) {
2474 $this->mRealName
= $str;
2478 * Get the user's current setting for a given option.
2480 * @param string $oname The option to check
2481 * @param string $defaultOverride A default value returned if the option does not exist
2482 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2483 * @return string User's current value for the option
2484 * @see getBoolOption()
2485 * @see getIntOption()
2487 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2488 global $wgHiddenPrefs;
2489 $this->loadOptions();
2491 # We want 'disabled' preferences to always behave as the default value for
2492 # users, even if they have set the option explicitly in their settings (ie they
2493 # set it, and then it was disabled removing their ability to change it). But
2494 # we don't want to erase the preferences in the database in case the preference
2495 # is re-enabled again. So don't touch $mOptions, just override the returned value
2496 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2497 return self
::getDefaultOption( $oname );
2500 if ( array_key_exists( $oname, $this->mOptions
) ) {
2501 return $this->mOptions
[$oname];
2503 return $defaultOverride;
2508 * Get all user's options
2512 public function getOptions() {
2513 global $wgHiddenPrefs;
2514 $this->loadOptions();
2515 $options = $this->mOptions
;
2517 # We want 'disabled' preferences to always behave as the default value for
2518 # users, even if they have set the option explicitly in their settings (ie they
2519 # set it, and then it was disabled removing their ability to change it). But
2520 # we don't want to erase the preferences in the database in case the preference
2521 # is re-enabled again. So don't touch $mOptions, just override the returned value
2522 foreach ( $wgHiddenPrefs as $pref ) {
2523 $default = self
::getDefaultOption( $pref );
2524 if ( $default !== null ) {
2525 $options[$pref] = $default;
2533 * Get the user's current setting for a given option, as a boolean value.
2535 * @param string $oname The option to check
2536 * @return bool User's current value for the option
2539 public function getBoolOption( $oname ) {
2540 return (bool)$this->getOption( $oname );
2544 * Get the user's current setting for a given option, as an integer value.
2546 * @param string $oname The option to check
2547 * @param int $defaultOverride A default value returned if the option does not exist
2548 * @return int User's current value for the option
2551 public function getIntOption( $oname, $defaultOverride = 0 ) {
2552 $val = $this->getOption( $oname );
2554 $val = $defaultOverride;
2556 return intval( $val );
2560 * Set the given option for a user.
2562 * You need to call saveSettings() to actually write to the database.
2564 * @param string $oname The option to set
2565 * @param mixed $val New value to set
2567 public function setOption( $oname, $val ) {
2568 $this->loadOptions();
2570 // Explicitly NULL values should refer to defaults
2571 if ( is_null( $val ) ) {
2572 $val = self
::getDefaultOption( $oname );
2575 $this->mOptions
[$oname] = $val;
2579 * Get a token stored in the preferences (like the watchlist one),
2580 * resetting it if it's empty (and saving changes).
2582 * @param string $oname The option name to retrieve the token from
2583 * @return string|bool User's current value for the option, or false if this option is disabled.
2584 * @see resetTokenFromOption()
2587 public function getTokenFromOption( $oname ) {
2588 global $wgHiddenPrefs;
2589 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2593 $token = $this->getOption( $oname );
2595 $token = $this->resetTokenFromOption( $oname );
2596 $this->saveSettings();
2602 * Reset a token stored in the preferences (like the watchlist one).
2603 * *Does not* save user's preferences (similarly to setOption()).
2605 * @param string $oname The option name to reset the token in
2606 * @return string|bool New token value, or false if this option is disabled.
2607 * @see getTokenFromOption()
2610 public function resetTokenFromOption( $oname ) {
2611 global $wgHiddenPrefs;
2612 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2616 $token = MWCryptRand
::generateHex( 40 );
2617 $this->setOption( $oname, $token );
2622 * Return a list of the types of user options currently returned by
2623 * User::getOptionKinds().
2625 * Currently, the option kinds are:
2626 * - 'registered' - preferences which are registered in core MediaWiki or
2627 * by extensions using the UserGetDefaultOptions hook.
2628 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2629 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2630 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2631 * be used by user scripts.
2632 * - 'special' - "preferences" that are not accessible via User::getOptions
2633 * or User::setOptions.
2634 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2635 * These are usually legacy options, removed in newer versions.
2637 * The API (and possibly others) use this function to determine the possible
2638 * option types for validation purposes, so make sure to update this when a
2639 * new option kind is added.
2641 * @see User::getOptionKinds
2642 * @return array Option kinds
2644 public static function listOptionKinds() {
2647 'registered-multiselect',
2648 'registered-checkmatrix',
2656 * Return an associative array mapping preferences keys to the kind of a preference they're
2657 * used for. Different kinds are handled differently when setting or reading preferences.
2659 * See User::listOptionKinds for the list of valid option types that can be provided.
2661 * @see User::listOptionKinds
2662 * @param IContextSource $context
2663 * @param array $options Assoc. array with options keys to check as keys.
2664 * Defaults to $this->mOptions.
2665 * @return array The key => kind mapping data
2667 public function getOptionKinds( IContextSource
$context, $options = null ) {
2668 $this->loadOptions();
2669 if ( $options === null ) {
2670 $options = $this->mOptions
;
2673 $prefs = Preferences
::getPreferences( $this, $context );
2676 // Pull out the "special" options, so they don't get converted as
2677 // multiselect or checkmatrix.
2678 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2679 foreach ( $specialOptions as $name => $value ) {
2680 unset( $prefs[$name] );
2683 // Multiselect and checkmatrix options are stored in the database with
2684 // one key per option, each having a boolean value. Extract those keys.
2685 $multiselectOptions = array();
2686 foreach ( $prefs as $name => $info ) {
2687 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2688 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2689 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2690 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2692 foreach ( $opts as $value ) {
2693 $multiselectOptions["$prefix$value"] = true;
2696 unset( $prefs[$name] );
2699 $checkmatrixOptions = array();
2700 foreach ( $prefs as $name => $info ) {
2701 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2702 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2703 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2704 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2705 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2707 foreach ( $columns as $column ) {
2708 foreach ( $rows as $row ) {
2709 $checkmatrixOptions["$prefix-$column-$row"] = true;
2713 unset( $prefs[$name] );
2717 // $value is ignored
2718 foreach ( $options as $key => $value ) {
2719 if ( isset( $prefs[$key] ) ) {
2720 $mapping[$key] = 'registered';
2721 } elseif ( isset( $multiselectOptions[$key] ) ) {
2722 $mapping[$key] = 'registered-multiselect';
2723 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2724 $mapping[$key] = 'registered-checkmatrix';
2725 } elseif ( isset( $specialOptions[$key] ) ) {
2726 $mapping[$key] = 'special';
2727 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2728 $mapping[$key] = 'userjs';
2730 $mapping[$key] = 'unused';
2738 * Reset certain (or all) options to the site defaults
2740 * The optional parameter determines which kinds of preferences will be reset.
2741 * Supported values are everything that can be reported by getOptionKinds()
2742 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2744 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2745 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2746 * for backwards-compatibility.
2747 * @param IContextSource|null $context Context source used when $resetKinds
2748 * does not contain 'all', passed to getOptionKinds().
2749 * Defaults to RequestContext::getMain() when null.
2751 public function resetOptions(
2752 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2753 IContextSource
$context = null
2756 $defaultOptions = self
::getDefaultOptions();
2758 if ( !is_array( $resetKinds ) ) {
2759 $resetKinds = array( $resetKinds );
2762 if ( in_array( 'all', $resetKinds ) ) {
2763 $newOptions = $defaultOptions;
2765 if ( $context === null ) {
2766 $context = RequestContext
::getMain();
2769 $optionKinds = $this->getOptionKinds( $context );
2770 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2771 $newOptions = array();
2773 // Use default values for the options that should be deleted, and
2774 // copy old values for the ones that shouldn't.
2775 foreach ( $this->mOptions
as $key => $value ) {
2776 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2777 if ( array_key_exists( $key, $defaultOptions ) ) {
2778 $newOptions[$key] = $defaultOptions[$key];
2781 $newOptions[$key] = $value;
2786 wfRunHooks( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2788 $this->mOptions
= $newOptions;
2789 $this->mOptionsLoaded
= true;
2793 * Get the user's preferred date format.
2794 * @return string User's preferred date format
2796 public function getDatePreference() {
2797 // Important migration for old data rows
2798 if ( is_null( $this->mDatePreference
) ) {
2800 $value = $this->getOption( 'date' );
2801 $map = $wgLang->getDatePreferenceMigrationMap();
2802 if ( isset( $map[$value] ) ) {
2803 $value = $map[$value];
2805 $this->mDatePreference
= $value;
2807 return $this->mDatePreference
;
2811 * Determine based on the wiki configuration and the user's options,
2812 * whether this user must be over HTTPS no matter what.
2816 public function requiresHTTPS() {
2817 global $wgSecureLogin;
2818 if ( !$wgSecureLogin ) {
2821 $https = $this->getBoolOption( 'prefershttps' );
2822 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2824 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2831 * Get the user preferred stub threshold
2835 public function getStubThreshold() {
2836 global $wgMaxArticleSize; # Maximum article size, in Kb
2837 $threshold = $this->getIntOption( 'stubthreshold' );
2838 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2839 // If they have set an impossible value, disable the preference
2840 // so we can use the parser cache again.
2847 * Get the permissions this user has.
2848 * @return array Array of String permission names
2850 public function getRights() {
2851 if ( is_null( $this->mRights
) ) {
2852 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2853 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2854 // Force reindexation of rights when a hook has unset one of them
2855 $this->mRights
= array_values( array_unique( $this->mRights
) );
2857 return $this->mRights
;
2861 * Get the list of explicit group memberships this user has.
2862 * The implicit * and user groups are not included.
2863 * @return array Array of String internal group names
2865 public function getGroups() {
2867 $this->loadGroups();
2868 return $this->mGroups
;
2872 * Get the list of implicit group memberships this user has.
2873 * This includes all explicit groups, plus 'user' if logged in,
2874 * '*' for all accounts, and autopromoted groups
2875 * @param bool $recache Whether to avoid the cache
2876 * @return array Array of String internal group names
2878 public function getEffectiveGroups( $recache = false ) {
2879 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2880 wfProfileIn( __METHOD__
);
2881 $this->mEffectiveGroups
= array_unique( array_merge(
2882 $this->getGroups(), // explicit groups
2883 $this->getAutomaticGroups( $recache ) // implicit groups
2885 // Hook for additional groups
2886 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2887 // Force reindexation of groups when a hook has unset one of them
2888 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
2889 wfProfileOut( __METHOD__
);
2891 return $this->mEffectiveGroups
;
2895 * Get the list of implicit group memberships this user has.
2896 * This includes 'user' if logged in, '*' for all accounts,
2897 * and autopromoted groups
2898 * @param bool $recache Whether to avoid the cache
2899 * @return array Array of String internal group names
2901 public function getAutomaticGroups( $recache = false ) {
2902 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
2903 wfProfileIn( __METHOD__
);
2904 $this->mImplicitGroups
= array( '*' );
2905 if ( $this->getId() ) {
2906 $this->mImplicitGroups
[] = 'user';
2908 $this->mImplicitGroups
= array_unique( array_merge(
2909 $this->mImplicitGroups
,
2910 Autopromote
::getAutopromoteGroups( $this )
2914 // Assure data consistency with rights/groups,
2915 // as getEffectiveGroups() depends on this function
2916 $this->mEffectiveGroups
= null;
2918 wfProfileOut( __METHOD__
);
2920 return $this->mImplicitGroups
;
2924 * Returns the groups the user has belonged to.
2926 * The user may still belong to the returned groups. Compare with getGroups().
2928 * The function will not return groups the user had belonged to before MW 1.17
2930 * @return array Names of the groups the user has belonged to.
2932 public function getFormerGroups() {
2933 if ( is_null( $this->mFormerGroups
) ) {
2934 $dbr = wfGetDB( DB_MASTER
);
2935 $res = $dbr->select( 'user_former_groups',
2936 array( 'ufg_group' ),
2937 array( 'ufg_user' => $this->mId
),
2939 $this->mFormerGroups
= array();
2940 foreach ( $res as $row ) {
2941 $this->mFormerGroups
[] = $row->ufg_group
;
2944 return $this->mFormerGroups
;
2948 * Get the user's edit count.
2949 * @return int|null Null for anonymous users
2951 public function getEditCount() {
2952 if ( !$this->getId() ) {
2956 if ( $this->mEditCount
=== null ) {
2957 /* Populate the count, if it has not been populated yet */
2958 wfProfileIn( __METHOD__
);
2959 $dbr = wfGetDB( DB_SLAVE
);
2960 // check if the user_editcount field has been initialized
2961 $count = $dbr->selectField(
2962 'user', 'user_editcount',
2963 array( 'user_id' => $this->mId
),
2967 if ( $count === null ) {
2968 // it has not been initialized. do so.
2969 $count = $this->initEditCount();
2971 $this->mEditCount
= $count;
2972 wfProfileOut( __METHOD__
);
2974 return (int)$this->mEditCount
;
2978 * Add the user to the given group.
2979 * This takes immediate effect.
2980 * @param string $group Name of the group to add
2982 public function addGroup( $group ) {
2983 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2984 $dbw = wfGetDB( DB_MASTER
);
2985 if ( $this->getId() ) {
2986 $dbw->insert( 'user_groups',
2988 'ug_user' => $this->getID(),
2989 'ug_group' => $group,
2992 array( 'IGNORE' ) );
2995 $this->loadGroups();
2996 $this->mGroups
[] = $group;
2997 // In case loadGroups was not called before, we now have the right twice.
2998 // Get rid of the duplicate.
2999 $this->mGroups
= array_unique( $this->mGroups
);
3001 // Refresh the groups caches, and clear the rights cache so it will be
3002 // refreshed on the next call to $this->getRights().
3003 $this->getEffectiveGroups( true );
3004 $this->mRights
= null;
3006 $this->invalidateCache();
3010 * Remove the user from the given group.
3011 * This takes immediate effect.
3012 * @param string $group Name of the group to remove
3014 public function removeGroup( $group ) {
3016 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3017 $dbw = wfGetDB( DB_MASTER
);
3018 $dbw->delete( 'user_groups',
3020 'ug_user' => $this->getID(),
3021 'ug_group' => $group,
3023 // Remember that the user was in this group
3024 $dbw->insert( 'user_former_groups',
3026 'ufg_user' => $this->getID(),
3027 'ufg_group' => $group,
3030 array( 'IGNORE' ) );
3032 $this->loadGroups();
3033 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3035 // Refresh the groups caches, and clear the rights cache so it will be
3036 // refreshed on the next call to $this->getRights().
3037 $this->getEffectiveGroups( true );
3038 $this->mRights
= null;
3040 $this->invalidateCache();
3044 * Get whether the user is logged in
3047 public function isLoggedIn() {
3048 return $this->getID() != 0;
3052 * Get whether the user is anonymous
3055 public function isAnon() {
3056 return !$this->isLoggedIn();
3060 * Check if user is allowed to access a feature / make an action
3062 * @internal param \String $varargs permissions to test
3063 * @return bool True if user is allowed to perform *any* of the given actions
3067 public function isAllowedAny( /*...*/ ) {
3068 $permissions = func_get_args();
3069 foreach ( $permissions as $permission ) {
3070 if ( $this->isAllowed( $permission ) ) {
3079 * @internal param $varargs string
3080 * @return bool True if the user is allowed to perform *all* of the given actions
3082 public function isAllowedAll( /*...*/ ) {
3083 $permissions = func_get_args();
3084 foreach ( $permissions as $permission ) {
3085 if ( !$this->isAllowed( $permission ) ) {
3093 * Internal mechanics of testing a permission
3094 * @param string $action
3097 public function isAllowed( $action = '' ) {
3098 if ( $action === '' ) {
3099 return true; // In the spirit of DWIM
3101 // Patrolling may not be enabled
3102 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3103 global $wgUseRCPatrol, $wgUseNPPatrol;
3104 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3108 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3109 // by misconfiguration: 0 == 'foo'
3110 return in_array( $action, $this->getRights(), true );
3114 * Check whether to enable recent changes patrol features for this user
3115 * @return bool True or false
3117 public function useRCPatrol() {
3118 global $wgUseRCPatrol;
3119 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3123 * Check whether to enable new pages patrol features for this user
3124 * @return bool True or false
3126 public function useNPPatrol() {
3127 global $wgUseRCPatrol, $wgUseNPPatrol;
3129 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3130 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3135 * Get the WebRequest object to use with this object
3137 * @return WebRequest
3139 public function getRequest() {
3140 if ( $this->mRequest
) {
3141 return $this->mRequest
;
3149 * Get the current skin, loading it if required
3150 * @return Skin The current skin
3151 * @todo FIXME: Need to check the old failback system [AV]
3152 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3154 public function getSkin() {
3155 wfDeprecated( __METHOD__
, '1.18' );
3156 return RequestContext
::getMain()->getSkin();
3160 * Get a WatchedItem for this user and $title.
3162 * @since 1.22 $checkRights parameter added
3163 * @param Title $title
3164 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3165 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3166 * @return WatchedItem
3168 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3169 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3171 if ( isset( $this->mWatchedItems
[$key] ) ) {
3172 return $this->mWatchedItems
[$key];
3175 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3176 $this->mWatchedItems
= array();
3179 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3180 return $this->mWatchedItems
[$key];
3184 * Check the watched status of an article.
3185 * @since 1.22 $checkRights parameter added
3186 * @param Title $title Title of the article to look at
3187 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3188 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3191 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3192 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3197 * @since 1.22 $checkRights parameter added
3198 * @param Title $title Title of the article to look at
3199 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3200 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3202 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3203 $this->getWatchedItem( $title, $checkRights )->addWatch();
3204 $this->invalidateCache();
3208 * Stop watching an article.
3209 * @since 1.22 $checkRights parameter added
3210 * @param Title $title Title of the article to look at
3211 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3212 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3214 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3215 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3216 $this->invalidateCache();
3220 * Clear the user's notification timestamp for the given title.
3221 * If e-notif e-mails are on, they will receive notification mails on
3222 * the next change of the page if it's watched etc.
3223 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3224 * @param Title $title Title of the article to look at
3225 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3227 public function clearNotification( &$title, $oldid = 0 ) {
3228 global $wgUseEnotif, $wgShowUpdatedMarker;
3230 // Do nothing if the database is locked to writes
3231 if ( wfReadOnly() ) {
3235 // Do nothing if not allowed to edit the watchlist
3236 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3240 // If we're working on user's talk page, we should update the talk page message indicator
3241 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3242 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3246 $nextid = $oldid ?
$title->getNextRevisionID( $oldid ) : null;
3248 if ( !$oldid ||
!$nextid ) {
3249 // If we're looking at the latest revision, we should definitely clear it
3250 $this->setNewtalk( false );
3252 // Otherwise we should update its revision, if it's present
3253 if ( $this->getNewtalk() ) {
3254 // Naturally the other one won't clear by itself
3255 $this->setNewtalk( false );
3256 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3261 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3265 if ( $this->isAnon() ) {
3266 // Nothing else to do...
3270 // Only update the timestamp if the page is being watched.
3271 // The query to find out if it is watched is cached both in memcached and per-invocation,
3272 // and when it does have to be executed, it can be on a slave
3273 // If this is the user's newtalk page, we always update the timestamp
3275 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3279 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3283 * Resets all of the given user's page-change notification timestamps.
3284 * If e-notif e-mails are on, they will receive notification mails on
3285 * the next change of any watched page.
3286 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3288 public function clearAllNotifications() {
3289 if ( wfReadOnly() ) {
3293 // Do nothing if not allowed to edit the watchlist
3294 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3298 global $wgUseEnotif, $wgShowUpdatedMarker;
3299 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3300 $this->setNewtalk( false );
3303 $id = $this->getId();
3305 $dbw = wfGetDB( DB_MASTER
);
3306 $dbw->update( 'watchlist',
3307 array( /* SET */ 'wl_notificationtimestamp' => null ),
3308 array( /* WHERE */ 'wl_user' => $id ),
3311 // We also need to clear here the "you have new message" notification for the own user_talk page;
3312 // it's cleared one page view later in WikiPage::doViewUpdates().
3317 * Set a cookie on the user's client. Wrapper for
3318 * WebResponse::setCookie
3319 * @param string $name Name of the cookie to set
3320 * @param string $value Value to set
3321 * @param int $exp Expiration time, as a UNIX time value;
3322 * if 0 or not specified, use the default $wgCookieExpiration
3323 * @param bool $secure
3324 * true: Force setting the secure attribute when setting the cookie
3325 * false: Force NOT setting the secure attribute when setting the cookie
3326 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3327 * @param array $params Array of options sent passed to WebResponse::setcookie()
3329 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3330 $params['secure'] = $secure;
3331 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3335 * Clear a cookie on the user's client
3336 * @param string $name Name of the cookie to clear
3337 * @param bool $secure
3338 * true: Force setting the secure attribute when setting the cookie
3339 * false: Force NOT setting the secure attribute when setting the cookie
3340 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3341 * @param array $params Array of options sent passed to WebResponse::setcookie()
3343 protected function clearCookie( $name, $secure = null, $params = array() ) {
3344 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3348 * Set the default cookies for this session on the user's client.
3350 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3352 * @param bool $secure Whether to force secure/insecure cookies or use default
3353 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3355 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3356 if ( $request === null ) {
3357 $request = $this->getRequest();
3361 if ( 0 == $this->mId
) {
3364 if ( !$this->mToken
) {
3365 // When token is empty or NULL generate a new one and then save it to the database
3366 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3367 // Simply by setting every cell in the user_token column to NULL and letting them be
3368 // regenerated as users log back into the wiki.
3370 $this->saveSettings();
3373 'wsUserID' => $this->mId
,
3374 'wsToken' => $this->mToken
,
3375 'wsUserName' => $this->getName()
3378 'UserID' => $this->mId
,
3379 'UserName' => $this->getName(),
3381 if ( $rememberMe ) {
3382 $cookies['Token'] = $this->mToken
;
3384 $cookies['Token'] = false;
3387 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3389 foreach ( $session as $name => $value ) {
3390 $request->setSessionData( $name, $value );
3392 foreach ( $cookies as $name => $value ) {
3393 if ( $value === false ) {
3394 $this->clearCookie( $name );
3396 $this->setCookie( $name, $value, 0, $secure );
3401 * If wpStickHTTPS was selected, also set an insecure cookie that
3402 * will cause the site to redirect the user to HTTPS, if they access
3403 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3404 * as the one set by centralauth (bug 53538). Also set it to session, or
3405 * standard time setting, based on if rememberme was set.
3407 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3411 $rememberMe ?
0 : null,
3413 array( 'prefix' => '' ) // no prefix
3419 * Log this user out.
3421 public function logout() {
3422 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3428 * Clear the user's cookies and session, and reset the instance cache.
3431 public function doLogout() {
3432 $this->clearInstanceCache( 'defaults' );
3434 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3436 $this->clearCookie( 'UserID' );
3437 $this->clearCookie( 'Token' );
3438 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3440 // Remember when user logged out, to prevent seeing cached pages
3441 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3445 * Save this user's settings into the database.
3446 * @todo Only rarely do all these fields need to be set!
3448 public function saveSettings() {
3452 $this->loadPasswords();
3453 if ( wfReadOnly() ) {
3456 if ( 0 == $this->mId
) {
3460 $this->mTouched
= self
::newTouchedTimestamp();
3461 if ( !$wgAuth->allowSetLocalPassword() ) {
3462 $this->mPassword
= self
::getPasswordFactory()->newFromCiphertext( null );
3465 $dbw = wfGetDB( DB_MASTER
);
3466 $dbw->update( 'user',
3468 'user_name' => $this->mName
,
3469 'user_password' => $this->mPassword
->toString(),
3470 'user_newpassword' => $this->mNewpassword
->toString(),
3471 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3472 'user_real_name' => $this->mRealName
,
3473 'user_email' => $this->mEmail
,
3474 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3475 'user_touched' => $dbw->timestamp( $this->mTouched
),
3476 'user_token' => strval( $this->mToken
),
3477 'user_email_token' => $this->mEmailToken
,
3478 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3479 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires
),
3480 ), array( /* WHERE */
3481 'user_id' => $this->mId
3485 $this->saveOptions();
3487 wfRunHooks( 'UserSaveSettings', array( $this ) );
3488 $this->clearSharedCache();
3489 $this->getUserPage()->invalidateCache();
3493 * If only this user's username is known, and it exists, return the user ID.
3496 public function idForName() {
3497 $s = trim( $this->getName() );
3502 $dbr = wfGetDB( DB_SLAVE
);
3503 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
3504 if ( $id === false ) {
3511 * Add a user to the database, return the user object
3513 * @param string $name Username to add
3514 * @param array $params Array of Strings Non-default parameters to save to
3515 * the database as user_* fields:
3516 * - password: The user's password hash. Password logins will be disabled
3517 * if this is omitted.
3518 * - newpassword: Hash for a temporary password that has been mailed to
3520 * - email: The user's email address.
3521 * - email_authenticated: The email authentication timestamp.
3522 * - real_name: The user's real name.
3523 * - options: An associative array of non-default options.
3524 * - token: Random authentication token. Do not set.
3525 * - registration: Registration timestamp. Do not set.
3527 * @return User|null User object, or null if the username already exists.
3529 public static function createNew( $name, $params = array() ) {
3532 $user->loadPasswords();
3533 $user->setToken(); // init token
3534 if ( isset( $params['options'] ) ) {
3535 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3536 unset( $params['options'] );
3538 $dbw = wfGetDB( DB_MASTER
);
3539 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3542 'user_id' => $seqVal,
3543 'user_name' => $name,
3544 'user_password' => $user->mPassword
->toString(),
3545 'user_newpassword' => $user->mNewpassword
->toString(),
3546 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3547 'user_email' => $user->mEmail
,
3548 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3549 'user_real_name' => $user->mRealName
,
3550 'user_token' => strval( $user->mToken
),
3551 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3552 'user_editcount' => 0,
3553 'user_touched' => $dbw->timestamp( self
::newTouchedTimestamp() ),
3555 foreach ( $params as $name => $value ) {
3556 $fields["user_$name"] = $value;
3558 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3559 if ( $dbw->affectedRows() ) {
3560 $newUser = User
::newFromId( $dbw->insertId() );
3568 * Add this existing user object to the database. If the user already
3569 * exists, a fatal status object is returned, and the user object is
3570 * initialised with the data from the database.
3572 * Previously, this function generated a DB error due to a key conflict
3573 * if the user already existed. Many extension callers use this function
3574 * in code along the lines of:
3576 * $user = User::newFromName( $name );
3577 * if ( !$user->isLoggedIn() ) {
3578 * $user->addToDatabase();
3580 * // do something with $user...
3582 * However, this was vulnerable to a race condition (bug 16020). By
3583 * initialising the user object if the user exists, we aim to support this
3584 * calling sequence as far as possible.
3586 * Note that if the user exists, this function will acquire a write lock,
3587 * so it is still advisable to make the call conditional on isLoggedIn(),
3588 * and to commit the transaction after calling.
3590 * @throws MWException
3593 public function addToDatabase() {
3595 $this->loadPasswords();
3596 if ( !$this->mToken
) {
3597 $this->setToken(); // init token
3600 $this->mTouched
= self
::newTouchedTimestamp();
3602 $dbw = wfGetDB( DB_MASTER
);
3603 $inWrite = $dbw->writesOrCallbacksPending();
3604 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3605 $dbw->insert( 'user',
3607 'user_id' => $seqVal,
3608 'user_name' => $this->mName
,
3609 'user_password' => $this->mPassword
->toString(),
3610 'user_newpassword' => $this->mNewpassword
->toString(),
3611 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3612 'user_email' => $this->mEmail
,
3613 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3614 'user_real_name' => $this->mRealName
,
3615 'user_token' => strval( $this->mToken
),
3616 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3617 'user_editcount' => 0,
3618 'user_touched' => $dbw->timestamp( $this->mTouched
),
3622 if ( !$dbw->affectedRows() ) {
3623 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3624 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3626 // Can't commit due to pending writes that may need atomicity.
3627 // This may cause some lock contention unlike the case below.
3628 $options = array( 'LOCK IN SHARE MODE' );
3629 $flags = self
::READ_LOCKING
;
3631 // Often, this case happens early in views before any writes when
3632 // using CentralAuth. It's should be OK to commit and break the snapshot.
3633 $dbw->commit( __METHOD__
, 'flush' );
3637 $this->mId
= $dbw->selectField( 'user', 'user_id',
3638 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3641 if ( $this->loadFromDatabase( $flags ) ) {
3646 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3647 "to insert user '{$this->mName}' row, but it was not present in select!" );
3649 return Status
::newFatal( 'userexists' );
3651 $this->mId
= $dbw->insertId();
3653 // Clear instance cache other than user table data, which is already accurate
3654 $this->clearInstanceCache();
3656 $this->saveOptions();
3657 return Status
::newGood();
3661 * If this user is logged-in and blocked,
3662 * block any IP address they've successfully logged in from.
3663 * @return bool A block was spread
3665 public function spreadAnyEditBlock() {
3666 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3667 return $this->spreadBlock();
3673 * If this (non-anonymous) user is blocked,
3674 * block the IP address they've successfully logged in from.
3675 * @return bool A block was spread
3677 protected function spreadBlock() {
3678 wfDebug( __METHOD__
. "()\n" );
3680 if ( $this->mId
== 0 ) {
3684 $userblock = Block
::newFromTarget( $this->getName() );
3685 if ( !$userblock ) {
3689 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3693 * Get whether the user is explicitly blocked from account creation.
3694 * @return bool|Block
3696 public function isBlockedFromCreateAccount() {
3697 $this->getBlockedStatus();
3698 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3699 return $this->mBlock
;
3702 # bug 13611: if the IP address the user is trying to create an account from is
3703 # blocked with createaccount disabled, prevent new account creation there even
3704 # when the user is logged in
3705 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3706 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3708 return $this->mBlockedFromCreateAccount
instanceof Block
3709 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3710 ?
$this->mBlockedFromCreateAccount
3715 * Get whether the user is blocked from using Special:Emailuser.
3718 public function isBlockedFromEmailuser() {
3719 $this->getBlockedStatus();
3720 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3724 * Get whether the user is allowed to create an account.
3727 public function isAllowedToCreateAccount() {
3728 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3732 * Get this user's personal page title.
3734 * @return Title User's personal page title
3736 public function getUserPage() {
3737 return Title
::makeTitle( NS_USER
, $this->getName() );
3741 * Get this user's talk page title.
3743 * @return Title User's talk page title
3745 public function getTalkPage() {
3746 $title = $this->getUserPage();
3747 return $title->getTalkPage();
3751 * Determine whether the user is a newbie. Newbies are either
3752 * anonymous IPs, or the most recently created accounts.
3755 public function isNewbie() {
3756 return !$this->isAllowed( 'autoconfirmed' );
3760 * Check to see if the given clear-text password is one of the accepted passwords
3761 * @param string $password User password
3762 * @return bool True if the given password is correct, otherwise False
3764 public function checkPassword( $password ) {
3765 global $wgAuth, $wgLegacyEncoding;
3766 $this->loadPasswords();
3768 // Certain authentication plugins do NOT want to save
3769 // domain passwords in a mysql database, so we should
3770 // check this (in case $wgAuth->strict() is false).
3772 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3774 } elseif ( $wgAuth->strict() ) {
3775 // Auth plugin doesn't allow local authentication
3777 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3778 // Auth plugin doesn't allow local authentication for this user name
3782 $passwordFactory = self
::getPasswordFactory();
3783 if ( !$this->mPassword
->equals( $password ) ) {
3784 if ( $wgLegacyEncoding ) {
3785 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3786 // Check for this with iconv
3787 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3788 if ( $cp1252Password === $password ||
!$this->mPassword
->equals( $cp1252Password ) ) {
3796 if ( $passwordFactory->needsUpdate( $this->mPassword
) ) {
3797 $this->mPassword
= $passwordFactory->newFromPlaintext( $password );
3798 $this->saveSettings();
3805 * Check if the given clear-text password matches the temporary password
3806 * sent by e-mail for password reset operations.
3808 * @param string $plaintext
3810 * @return bool True if matches, false otherwise
3812 public function checkTemporaryPassword( $plaintext ) {
3813 global $wgNewPasswordExpiry;
3816 if ( $this->mNewpassword
->equals( $plaintext ) ) {
3817 if ( is_null( $this->mNewpassTime
) ) {
3820 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3821 return ( time() < $expiry );
3828 * Alias for getEditToken.
3829 * @deprecated since 1.19, use getEditToken instead.
3831 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3832 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3833 * @return string The new edit token
3835 public function editToken( $salt = '', $request = null ) {
3836 wfDeprecated( __METHOD__
, '1.19' );
3837 return $this->getEditToken( $salt, $request );
3841 * Initialize (if necessary) and return a session token value
3842 * which can be used in edit forms to show that the user's
3843 * login credentials aren't being hijacked with a foreign form
3848 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3849 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3850 * @return string The new edit token
3852 public function getEditToken( $salt = '', $request = null ) {
3853 if ( $request == null ) {
3854 $request = $this->getRequest();
3857 if ( $this->isAnon() ) {
3858 return EDIT_TOKEN_SUFFIX
;
3860 $token = $request->getSessionData( 'wsEditToken' );
3861 if ( $token === null ) {
3862 $token = MWCryptRand
::generateHex( 32 );
3863 $request->setSessionData( 'wsEditToken', $token );
3865 if ( is_array( $salt ) ) {
3866 $salt = implode( '|', $salt );
3868 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
3873 * Generate a looking random token for various uses.
3875 * @return string The new random token
3876 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
3877 * wfRandomString for pseudo-randomness.
3879 public static function generateToken() {
3880 return MWCryptRand
::generateHex( 32 );
3884 * Check given value against the token value stored in the session.
3885 * A match should confirm that the form was submitted from the
3886 * user's own login session, not a form submission from a third-party
3889 * @param string $val Input value to compare
3890 * @param string $salt Optional function-specific data for hashing
3891 * @param WebRequest|null $request Object to use or null to use $wgRequest
3892 * @return bool Whether the token matches
3894 public function matchEditToken( $val, $salt = '', $request = null ) {
3895 $sessionToken = $this->getEditToken( $salt, $request );
3896 if ( $val != $sessionToken ) {
3897 wfDebug( "User::matchEditToken: broken session data\n" );
3900 return $val == $sessionToken;
3904 * Check given value against the token value stored in the session,
3905 * ignoring the suffix.
3907 * @param string $val Input value to compare
3908 * @param string $salt Optional function-specific data for hashing
3909 * @param WebRequest|null $request Object to use or null to use $wgRequest
3910 * @return bool Whether the token matches
3912 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3913 $sessionToken = $this->getEditToken( $salt, $request );
3914 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3918 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3919 * mail to the user's given address.
3921 * @param string $type Message to send, either "created", "changed" or "set"
3924 public function sendConfirmationMail( $type = 'created' ) {
3926 $expiration = null; // gets passed-by-ref and defined in next line.
3927 $token = $this->confirmationToken( $expiration );
3928 $url = $this->confirmationTokenUrl( $token );
3929 $invalidateURL = $this->invalidationTokenUrl( $token );
3930 $this->saveSettings();
3932 if ( $type == 'created' ||
$type === false ) {
3933 $message = 'confirmemail_body';
3934 } elseif ( $type === true ) {
3935 $message = 'confirmemail_body_changed';
3937 // Messages: confirmemail_body_changed, confirmemail_body_set
3938 $message = 'confirmemail_body_' . $type;
3941 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3942 wfMessage( $message,
3943 $this->getRequest()->getIP(),
3946 $wgLang->timeanddate( $expiration, false ),
3948 $wgLang->date( $expiration, false ),
3949 $wgLang->time( $expiration, false ) )->text() );
3953 * Send an e-mail to this user's account. Does not check for
3954 * confirmed status or validity.
3956 * @param string $subject Message subject
3957 * @param string $body Message body
3958 * @param string $from Optional From address; if unspecified, default
3959 * $wgPasswordSender will be used.
3960 * @param string $replyto Reply-To address
3963 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3964 if ( is_null( $from ) ) {
3965 global $wgPasswordSender;
3966 $sender = new MailAddress( $wgPasswordSender,
3967 wfMessage( 'emailsender' )->inContentLanguage()->text() );
3969 $sender = new MailAddress( $from );
3972 $to = new MailAddress( $this );
3973 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
3977 * Generate, store, and return a new e-mail confirmation code.
3978 * A hash (unsalted, since it's used as a key) is stored.
3980 * @note Call saveSettings() after calling this function to commit
3981 * this change to the database.
3983 * @param string &$expiration Accepts the expiration time
3984 * @return string New token
3986 protected function confirmationToken( &$expiration ) {
3987 global $wgUserEmailConfirmationTokenExpiry;
3989 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
3990 $expiration = wfTimestamp( TS_MW
, $expires );
3992 $token = MWCryptRand
::generateHex( 32 );
3993 $hash = md5( $token );
3994 $this->mEmailToken
= $hash;
3995 $this->mEmailTokenExpires
= $expiration;
4000 * Return a URL the user can use to confirm their email address.
4001 * @param string $token Accepts the email confirmation token
4002 * @return string New token URL
4004 protected function confirmationTokenUrl( $token ) {
4005 return $this->getTokenUrl( 'ConfirmEmail', $token );
4009 * Return a URL the user can use to invalidate their email address.
4010 * @param string $token Accepts the email confirmation token
4011 * @return string New token URL
4013 protected function invalidationTokenUrl( $token ) {
4014 return $this->getTokenUrl( 'InvalidateEmail', $token );
4018 * Internal function to format the e-mail validation/invalidation URLs.
4019 * This uses a quickie hack to use the
4020 * hardcoded English names of the Special: pages, for ASCII safety.
4022 * @note Since these URLs get dropped directly into emails, using the
4023 * short English names avoids insanely long URL-encoded links, which
4024 * also sometimes can get corrupted in some browsers/mailers
4025 * (bug 6957 with Gmail and Internet Explorer).
4027 * @param string $page Special page
4028 * @param string $token Token
4029 * @return string Formatted URL
4031 protected function getTokenUrl( $page, $token ) {
4032 // Hack to bypass localization of 'Special:'
4033 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4034 return $title->getCanonicalURL();
4038 * Mark the e-mail address confirmed.
4040 * @note Call saveSettings() after calling this function to commit the change.
4044 public function confirmEmail() {
4045 // Check if it's already confirmed, so we don't touch the database
4046 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4047 if ( !$this->isEmailConfirmed() ) {
4048 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4049 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
4055 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4056 * address if it was already confirmed.
4058 * @note Call saveSettings() after calling this function to commit the change.
4059 * @return bool Returns true
4061 public function invalidateEmail() {
4063 $this->mEmailToken
= null;
4064 $this->mEmailTokenExpires
= null;
4065 $this->setEmailAuthenticationTimestamp( null );
4066 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
4071 * Set the e-mail authentication timestamp.
4072 * @param string $timestamp TS_MW timestamp
4074 public function setEmailAuthenticationTimestamp( $timestamp ) {
4076 $this->mEmailAuthenticated
= $timestamp;
4077 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4081 * Is this user allowed to send e-mails within limits of current
4082 * site configuration?
4085 public function canSendEmail() {
4086 global $wgEnableEmail, $wgEnableUserEmail;
4087 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4090 $canSend = $this->isEmailConfirmed();
4091 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4096 * Is this user allowed to receive e-mails within limits of current
4097 * site configuration?
4100 public function canReceiveEmail() {
4101 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4105 * Is this user's e-mail address valid-looking and confirmed within
4106 * limits of the current site configuration?
4108 * @note If $wgEmailAuthentication is on, this may require the user to have
4109 * confirmed their address by returning a code or using a password
4110 * sent to the address from the wiki.
4114 public function isEmailConfirmed() {
4115 global $wgEmailAuthentication;
4118 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4119 if ( $this->isAnon() ) {
4122 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4125 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4135 * Check whether there is an outstanding request for e-mail confirmation.
4138 public function isEmailConfirmationPending() {
4139 global $wgEmailAuthentication;
4140 return $wgEmailAuthentication &&
4141 !$this->isEmailConfirmed() &&
4142 $this->mEmailToken
&&
4143 $this->mEmailTokenExpires
> wfTimestamp();
4147 * Get the timestamp of account creation.
4149 * @return string|bool|null Timestamp of account creation, false for
4150 * non-existent/anonymous user accounts, or null if existing account
4151 * but information is not in database.
4153 public function getRegistration() {
4154 if ( $this->isAnon() ) {
4158 return $this->mRegistration
;
4162 * Get the timestamp of the first edit
4164 * @return string|bool Timestamp of first edit, or false for
4165 * non-existent/anonymous user accounts.
4167 public function getFirstEditTimestamp() {
4168 if ( $this->getId() == 0 ) {
4169 return false; // anons
4171 $dbr = wfGetDB( DB_SLAVE
);
4172 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4173 array( 'rev_user' => $this->getId() ),
4175 array( 'ORDER BY' => 'rev_timestamp ASC' )
4178 return false; // no edits
4180 return wfTimestamp( TS_MW
, $time );
4184 * Get the permissions associated with a given list of groups
4186 * @param array $groups Array of Strings List of internal group names
4187 * @return array Array of Strings List of permission key names for given groups combined
4189 public static function getGroupPermissions( $groups ) {
4190 global $wgGroupPermissions, $wgRevokePermissions;
4192 // grant every granted permission first
4193 foreach ( $groups as $group ) {
4194 if ( isset( $wgGroupPermissions[$group] ) ) {
4195 $rights = array_merge( $rights,
4196 // array_filter removes empty items
4197 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4200 // now revoke the revoked permissions
4201 foreach ( $groups as $group ) {
4202 if ( isset( $wgRevokePermissions[$group] ) ) {
4203 $rights = array_diff( $rights,
4204 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4207 return array_unique( $rights );
4211 * Get all the groups who have a given permission
4213 * @param string $role Role to check
4214 * @return array Array of Strings List of internal group names with the given permission
4216 public static function getGroupsWithPermission( $role ) {
4217 global $wgGroupPermissions;
4218 $allowedGroups = array();
4219 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4220 if ( self
::groupHasPermission( $group, $role ) ) {
4221 $allowedGroups[] = $group;
4224 return $allowedGroups;
4228 * Check, if the given group has the given permission
4230 * If you're wanting to check whether all users have a permission, use
4231 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4235 * @param string $group Group to check
4236 * @param string $role Role to check
4239 public static function groupHasPermission( $group, $role ) {
4240 global $wgGroupPermissions, $wgRevokePermissions;
4241 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4242 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4246 * Check if all users have the given permission
4249 * @param string $right Right to check
4252 public static function isEveryoneAllowed( $right ) {
4253 global $wgGroupPermissions, $wgRevokePermissions;
4254 static $cache = array();
4256 // Use the cached results, except in unit tests which rely on
4257 // being able change the permission mid-request
4258 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4259 return $cache[$right];
4262 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4263 $cache[$right] = false;
4267 // If it's revoked anywhere, then everyone doesn't have it
4268 foreach ( $wgRevokePermissions as $rights ) {
4269 if ( isset( $rights[$right] ) && $rights[$right] ) {
4270 $cache[$right] = false;
4275 // Allow extensions (e.g. OAuth) to say false
4276 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4277 $cache[$right] = false;
4281 $cache[$right] = true;
4286 * Get the localized descriptive name for a group, if it exists
4288 * @param string $group Internal group name
4289 * @return string Localized descriptive group name
4291 public static function getGroupName( $group ) {
4292 $msg = wfMessage( "group-$group" );
4293 return $msg->isBlank() ?
$group : $msg->text();
4297 * Get the localized descriptive name for a member of a group, if it exists
4299 * @param string $group Internal group name
4300 * @param string $username Username for gender (since 1.19)
4301 * @return string Localized name for group member
4303 public static function getGroupMember( $group, $username = '#' ) {
4304 $msg = wfMessage( "group-$group-member", $username );
4305 return $msg->isBlank() ?
$group : $msg->text();
4309 * Return the set of defined explicit groups.
4310 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4311 * are not included, as they are defined automatically, not in the database.
4312 * @return array Array of internal group names
4314 public static function getAllGroups() {
4315 global $wgGroupPermissions, $wgRevokePermissions;
4317 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4318 self
::getImplicitGroups()
4323 * Get a list of all available permissions.
4324 * @return array Array of permission names
4326 public static function getAllRights() {
4327 if ( self
::$mAllRights === false ) {
4328 global $wgAvailableRights;
4329 if ( count( $wgAvailableRights ) ) {
4330 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4332 self
::$mAllRights = self
::$mCoreRights;
4334 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
4336 return self
::$mAllRights;
4340 * Get a list of implicit groups
4341 * @return array Array of Strings Array of internal group names
4343 public static function getImplicitGroups() {
4344 global $wgImplicitGroups;
4346 $groups = $wgImplicitGroups;
4347 # Deprecated, use $wgImplictGroups instead
4348 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) );
4354 * Get the title of a page describing a particular group
4356 * @param string $group Internal group name
4357 * @return Title|bool Title of the page if it exists, false otherwise
4359 public static function getGroupPage( $group ) {
4360 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4361 if ( $msg->exists() ) {
4362 $title = Title
::newFromText( $msg->text() );
4363 if ( is_object( $title ) ) {
4371 * Create a link to the group in HTML, if available;
4372 * else return the group name.
4374 * @param string $group Internal name of the group
4375 * @param string $text The text of the link
4376 * @return string HTML link to the group
4378 public static function makeGroupLinkHTML( $group, $text = '' ) {
4379 if ( $text == '' ) {
4380 $text = self
::getGroupName( $group );
4382 $title = self
::getGroupPage( $group );
4384 return Linker
::link( $title, htmlspecialchars( $text ) );
4391 * Create a link to the group in Wikitext, if available;
4392 * else return the group name.
4394 * @param string $group Internal name of the group
4395 * @param string $text The text of the link
4396 * @return string Wikilink to the group
4398 public static function makeGroupLinkWiki( $group, $text = '' ) {
4399 if ( $text == '' ) {
4400 $text = self
::getGroupName( $group );
4402 $title = self
::getGroupPage( $group );
4404 $page = $title->getPrefixedText();
4405 return "[[$page|$text]]";
4412 * Returns an array of the groups that a particular group can add/remove.
4414 * @param string $group The group to check for whether it can add/remove
4415 * @return array Array( 'add' => array( addablegroups ),
4416 * 'remove' => array( removablegroups ),
4417 * 'add-self' => array( addablegroups to self),
4418 * 'remove-self' => array( removable groups from self) )
4420 public static function changeableByGroup( $group ) {
4421 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4425 'remove' => array(),
4426 'add-self' => array(),
4427 'remove-self' => array()
4430 if ( empty( $wgAddGroups[$group] ) ) {
4431 // Don't add anything to $groups
4432 } elseif ( $wgAddGroups[$group] === true ) {
4433 // You get everything
4434 $groups['add'] = self
::getAllGroups();
4435 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4436 $groups['add'] = $wgAddGroups[$group];
4439 // Same thing for remove
4440 if ( empty( $wgRemoveGroups[$group] ) ) {
4441 } elseif ( $wgRemoveGroups[$group] === true ) {
4442 $groups['remove'] = self
::getAllGroups();
4443 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4444 $groups['remove'] = $wgRemoveGroups[$group];
4447 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4448 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4449 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4450 if ( is_int( $key ) ) {
4451 $wgGroupsAddToSelf['user'][] = $value;
4456 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4457 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4458 if ( is_int( $key ) ) {
4459 $wgGroupsRemoveFromSelf['user'][] = $value;
4464 // Now figure out what groups the user can add to him/herself
4465 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4466 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4467 // No idea WHY this would be used, but it's there
4468 $groups['add-self'] = User
::getAllGroups();
4469 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4470 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4473 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4474 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4475 $groups['remove-self'] = User
::getAllGroups();
4476 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4477 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4484 * Returns an array of groups that this user can add and remove
4485 * @return array Array( 'add' => array( addablegroups ),
4486 * 'remove' => array( removablegroups ),
4487 * 'add-self' => array( addablegroups to self),
4488 * 'remove-self' => array( removable groups from self) )
4490 public function changeableGroups() {
4491 if ( $this->isAllowed( 'userrights' ) ) {
4492 // This group gives the right to modify everything (reverse-
4493 // compatibility with old "userrights lets you change
4495 // Using array_merge to make the groups reindexed
4496 $all = array_merge( User
::getAllGroups() );
4500 'add-self' => array(),
4501 'remove-self' => array()
4505 // Okay, it's not so simple, we will have to go through the arrays
4508 'remove' => array(),
4509 'add-self' => array(),
4510 'remove-self' => array()
4512 $addergroups = $this->getEffectiveGroups();
4514 foreach ( $addergroups as $addergroup ) {
4515 $groups = array_merge_recursive(
4516 $groups, $this->changeableByGroup( $addergroup )
4518 $groups['add'] = array_unique( $groups['add'] );
4519 $groups['remove'] = array_unique( $groups['remove'] );
4520 $groups['add-self'] = array_unique( $groups['add-self'] );
4521 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4527 * Increment the user's edit-count field.
4528 * Will have no effect for anonymous users.
4530 public function incEditCount() {
4531 if ( !$this->isAnon() ) {
4532 $dbw = wfGetDB( DB_MASTER
);
4535 array( 'user_editcount=user_editcount+1' ),
4536 array( 'user_id' => $this->getId() ),
4540 // Lazy initialization check...
4541 if ( $dbw->affectedRows() == 0 ) {
4542 // Now here's a goddamn hack...
4543 $dbr = wfGetDB( DB_SLAVE
);
4544 if ( $dbr !== $dbw ) {
4545 // If we actually have a slave server, the count is
4546 // at least one behind because the current transaction
4547 // has not been committed and replicated.
4548 $this->initEditCount( 1 );
4550 // But if DB_SLAVE is selecting the master, then the
4551 // count we just read includes the revision that was
4552 // just added in the working transaction.
4553 $this->initEditCount();
4557 // edit count in user cache too
4558 $this->invalidateCache();
4562 * Initialize user_editcount from data out of the revision table
4564 * @param int $add Edits to add to the count from the revision table
4565 * @return int Number of edits
4567 protected function initEditCount( $add = 0 ) {
4568 // Pull from a slave to be less cruel to servers
4569 // Accuracy isn't the point anyway here
4570 $dbr = wfGetDB( DB_SLAVE
);
4571 $count = (int)$dbr->selectField(
4574 array( 'rev_user' => $this->getId() ),
4577 $count = $count +
$add;
4579 $dbw = wfGetDB( DB_MASTER
);
4582 array( 'user_editcount' => $count ),
4583 array( 'user_id' => $this->getId() ),
4591 * Get the description of a given right
4593 * @param string $right Right to query
4594 * @return string Localized description of the right
4596 public static function getRightDescription( $right ) {
4597 $key = "right-$right";
4598 $msg = wfMessage( $key );
4599 return $msg->isBlank() ?
$right : $msg->text();
4603 * Make a new-style password hash
4605 * @param string $password Plain-text password
4606 * @param bool|string $salt Optional salt, may be random or the user ID.
4607 * If unspecified or false, will generate one automatically
4608 * @return string Password hash
4609 * @deprecated since 1.24, use Password class
4611 public static function crypt( $password, $salt = false ) {
4612 wfDeprecated( __METHOD__
, '1.24' );
4613 $hash = self
::getPasswordFactory()->newFromPlaintext( $password );
4614 return $hash->toString();
4618 * Compare a password hash with a plain-text password. Requires the user
4619 * ID if there's a chance that the hash is an old-style hash.
4621 * @param string $hash Password hash
4622 * @param string $password Plain-text password to compare
4623 * @param string|bool $userId User ID for old-style password salt
4626 * @deprecated since 1.24, use Password class
4628 public static function comparePasswords( $hash, $password, $userId = false ) {
4629 wfDeprecated( __METHOD__
, '1.24' );
4631 // Check for *really* old password hashes that don't even have a type
4632 // The old hash format was just an md5 hex hash, with no type information
4633 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4634 global $wgPasswordSalt;
4635 if ( $wgPasswordSalt ) {
4636 $password = ":B:{$userId}:{$hash}";
4638 $password = ":A:{$hash}";
4642 $hash = self
::getPasswordFactory()->newFromCiphertext( $hash );
4643 return $hash->equals( $password );
4647 * Add a newuser log entry for this user.
4648 * Before 1.19 the return value was always true.
4650 * @param string|bool $action Account creation type.
4651 * - String, one of the following values:
4652 * - 'create' for an anonymous user creating an account for himself.
4653 * This will force the action's performer to be the created user itself,
4654 * no matter the value of $wgUser
4655 * - 'create2' for a logged in user creating an account for someone else
4656 * - 'byemail' when the created user will receive its password by e-mail
4657 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4658 * - Boolean means whether the account was created by e-mail (deprecated):
4659 * - true will be converted to 'byemail'
4660 * - false will be converted to 'create' if this object is the same as
4661 * $wgUser and to 'create2' otherwise
4663 * @param string $reason User supplied reason
4665 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4667 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4668 global $wgUser, $wgNewUserLog;
4669 if ( empty( $wgNewUserLog ) ) {
4670 return true; // disabled
4673 if ( $action === true ) {
4674 $action = 'byemail';
4675 } elseif ( $action === false ) {
4676 if ( $this->getName() == $wgUser->getName() ) {
4679 $action = 'create2';
4683 if ( $action === 'create' ||
$action === 'autocreate' ) {
4686 $performer = $wgUser;
4689 $logEntry = new ManualLogEntry( 'newusers', $action );
4690 $logEntry->setPerformer( $performer );
4691 $logEntry->setTarget( $this->getUserPage() );
4692 $logEntry->setComment( $reason );
4693 $logEntry->setParameters( array(
4694 '4::userid' => $this->getId(),
4696 $logid = $logEntry->insert();
4698 if ( $action !== 'autocreate' ) {
4699 $logEntry->publish( $logid );
4706 * Add an autocreate newuser log entry for this user
4707 * Used by things like CentralAuth and perhaps other authplugins.
4708 * Consider calling addNewUserLogEntry() directly instead.
4712 public function addNewUserLogEntryAutoCreate() {
4713 $this->addNewUserLogEntry( 'autocreate' );
4719 * Load the user options either from cache, the database or an array
4721 * @param array $data Rows for the current user out of the user_properties table
4723 protected function loadOptions( $data = null ) {
4728 if ( $this->mOptionsLoaded
) {
4732 $this->mOptions
= self
::getDefaultOptions();
4734 if ( !$this->getId() ) {
4735 // For unlogged-in users, load language/variant options from request.
4736 // There's no need to do it for logged-in users: they can set preferences,
4737 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4738 // so don't override user's choice (especially when the user chooses site default).
4739 $variant = $wgContLang->getDefaultVariant();
4740 $this->mOptions
['variant'] = $variant;
4741 $this->mOptions
['language'] = $variant;
4742 $this->mOptionsLoaded
= true;
4746 // Maybe load from the object
4747 if ( !is_null( $this->mOptionOverrides
) ) {
4748 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4749 foreach ( $this->mOptionOverrides
as $key => $value ) {
4750 $this->mOptions
[$key] = $value;
4753 if ( !is_array( $data ) ) {
4754 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4755 // Load from database
4756 $dbr = wfGetDB( DB_SLAVE
);
4758 $res = $dbr->select(
4760 array( 'up_property', 'up_value' ),
4761 array( 'up_user' => $this->getId() ),
4765 $this->mOptionOverrides
= array();
4767 foreach ( $res as $row ) {
4768 $data[$row->up_property
] = $row->up_value
;
4771 foreach ( $data as $property => $value ) {
4772 $this->mOptionOverrides
[$property] = $value;
4773 $this->mOptions
[$property] = $value;
4777 $this->mOptionsLoaded
= true;
4779 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
4783 * Saves the non-default options for this user, as previously set e.g. via
4784 * setOption(), in the database's "user_properties" (preferences) table.
4785 * Usually used via saveSettings().
4787 protected function saveOptions() {
4788 $this->loadOptions();
4790 // Not using getOptions(), to keep hidden preferences in database
4791 $saveOptions = $this->mOptions
;
4793 // Allow hooks to abort, for instance to save to a global profile.
4794 // Reset options to default state before saving.
4795 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4799 $userId = $this->getId();
4801 $insert_rows = array(); // all the new preference rows
4802 foreach ( $saveOptions as $key => $value ) {
4803 // Don't bother storing default values
4804 $defaultOption = self
::getDefaultOption( $key );
4805 if ( ( $defaultOption === null && $value !== false && $value !== null )
4806 ||
$value != $defaultOption
4808 $insert_rows[] = array(
4809 'up_user' => $userId,
4810 'up_property' => $key,
4811 'up_value' => $value,
4816 $dbw = wfGetDB( DB_MASTER
);
4818 $res = $dbw->select( 'user_properties',
4819 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
4821 // Find prior rows that need to be removed or updated. These rows will
4822 // all be deleted (the later so that INSERT IGNORE applies the new values).
4823 $keysDelete = array();
4824 foreach ( $res as $row ) {
4825 if ( !isset( $saveOptions[$row->up_property
] )
4826 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
4828 $keysDelete[] = $row->up_property
;
4832 if ( count( $keysDelete ) ) {
4833 // Do the DELETE by PRIMARY KEY for prior rows.
4834 // In the past a very large portion of calls to this function are for setting
4835 // 'rememberpassword' for new accounts (a preference that has since been removed).
4836 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4837 // caused gap locks on [max user ID,+infinity) which caused high contention since
4838 // updates would pile up on each other as they are for higher (newer) user IDs.
4839 // It might not be necessary these days, but it shouldn't hurt either.
4840 $dbw->delete( 'user_properties',
4841 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
4843 // Insert the new preference rows
4844 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
4848 * Lazily instantiate and return a factory object for making passwords
4850 * @return PasswordFactory
4852 public static function getPasswordFactory() {
4853 if ( self
::$mPasswordFactory === null ) {
4854 self
::$mPasswordFactory = new PasswordFactory();
4855 self
::$mPasswordFactory->init( RequestContext
::getMain()->getConfig() );
4858 return self
::$mPasswordFactory;
4862 * Provide an array of HTML5 attributes to put on an input element
4863 * intended for the user to enter a new password. This may include
4864 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4866 * Do *not* use this when asking the user to enter his current password!
4867 * Regardless of configuration, users may have invalid passwords for whatever
4868 * reason (e.g., they were set before requirements were tightened up).
4869 * Only use it when asking for a new password, like on account creation or
4872 * Obviously, you still need to do server-side checking.
4874 * NOTE: A combination of bugs in various browsers means that this function
4875 * actually just returns array() unconditionally at the moment. May as
4876 * well keep it around for when the browser bugs get fixed, though.
4878 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4880 * @return array Array of HTML attributes suitable for feeding to
4881 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4882 * That will get confused by the boolean attribute syntax used.)
4884 public static function passwordChangeInputAttribs() {
4885 global $wgMinimalPasswordLength;
4887 if ( $wgMinimalPasswordLength == 0 ) {
4891 # Note that the pattern requirement will always be satisfied if the
4892 # input is empty, so we need required in all cases.
4894 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4895 # if e-mail confirmation is being used. Since HTML5 input validation
4896 # is b0rked anyway in some browsers, just return nothing. When it's
4897 # re-enabled, fix this code to not output required for e-mail
4899 #$ret = array( 'required' );
4902 # We can't actually do this right now, because Opera 9.6 will print out
4903 # the entered password visibly in its error message! When other
4904 # browsers add support for this attribute, or Opera fixes its support,
4905 # we can add support with a version check to avoid doing this on Opera
4906 # versions where it will be a problem. Reported to Opera as
4907 # DSK-262266, but they don't have a public bug tracker for us to follow.
4909 if ( $wgMinimalPasswordLength > 1 ) {
4910 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4911 $ret['title'] = wfMessage( 'passwordtooshort' )
4912 ->numParams( $wgMinimalPasswordLength )->text();
4920 * Return the list of user fields that should be selected to create
4921 * a new user object.
4924 public static function selectFields() {
4932 'user_email_authenticated',
4934 'user_email_token_expires',
4935 'user_registration',
4941 * Factory function for fatal permission-denied errors
4944 * @param string $permission User right required
4947 static function newFatalPermissionDeniedStatus( $permission ) {
4950 $groups = array_map(
4951 array( 'User', 'makeGroupLinkWiki' ),
4952 User
::getGroupsWithPermission( $permission )
4956 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4958 return Status
::newFatal( 'badaccess-group0' );