3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * String Some punctuation to prevent editing from broken text-mangling proxies.
27 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
30 * The User object encapsulates all of the user-specific settings (user_id,
31 * name, rights, password, email address, options, last login time). Client
32 * classes use the getXXX() functions to access these fields. These functions
33 * do all the work of determining whether the user is logged in,
34 * whether the requested option can be satisfied from cookies or
35 * whether a database query is needed. Most of the settings needed
36 * for rendering normal pages are set in the cookie to minimize use
39 class User
implements IDBAccessObject
{
41 * @const int Number of characters in user_token field.
43 const TOKEN_LENGTH
= 32;
46 * Global constant made accessible as class constants so that autoloader
49 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
52 * @const int Serialized record version.
57 * Maximum items in $mWatchedItems
59 const MAX_WATCHED_ITEMS_CACHE
= 100;
62 * @var PasswordFactory Lazily loaded factory object for passwords
64 private static $mPasswordFactory = null;
67 * Array of Strings List of member variables which are saved to the
68 * shared cache (memcached). Any operation which changes the
69 * corresponding database fields must call a cache-clearing function.
72 protected static $mCacheVars = array(
80 'mEmailAuthenticated',
87 // user_properties table
92 * Array of Strings Core rights.
93 * Each of these should have a corresponding message of the form
97 protected static $mCoreRights = array(
123 'editusercssjs', #deprecated
135 'move-categorypages',
136 'move-rootuserpages',
140 'override-export-depth',
164 'userrights-interwiki',
172 * String Cached results of getAllRights()
174 protected static $mAllRights = false;
176 /** @name Cache variables */
185 * @todo Make this actually private
191 * @todo Make this actually private
194 public $mNewpassword;
196 public $mNewpassTime;
204 public $mEmailAuthenticated;
206 protected $mEmailToken;
208 protected $mEmailTokenExpires;
210 protected $mRegistration;
212 protected $mEditCount;
216 protected $mOptionOverrides;
218 protected $mPasswordExpires;
222 * Bool Whether the cache variables have been loaded.
225 public $mOptionsLoaded;
228 * Array with already loaded items or true if all items have been loaded.
230 protected $mLoadedItems = array();
234 * String Initialization data source if mLoadedItems!==true. May be one of:
235 * - 'defaults' anonymous user initialised from class defaults
236 * - 'name' initialise from mName
237 * - 'id' initialise from mId
238 * - 'session' log in from cookies or session if possible
240 * Use the User::newFrom*() family of functions to set this.
245 * Lazy-initialized variables, invalidated with clearInstanceCache
249 protected $mDatePreference;
257 protected $mBlockreason;
259 protected $mEffectiveGroups;
261 protected $mImplicitGroups;
263 protected $mFormerGroups;
265 protected $mBlockedGlobally;
282 protected $mAllowUsertalk;
285 private $mBlockedFromCreateAccount = false;
288 private $mWatchedItems = array();
290 public static $idCacheByName = array();
293 * Lightweight constructor for an anonymous user.
294 * Use the User::newFrom* factory functions for other kinds of users.
298 * @see newFromConfirmationCode()
299 * @see newFromSession()
302 public function __construct() {
303 $this->clearInstanceCache( 'defaults' );
309 public function __toString() {
310 return $this->getName();
314 * Load the user table data for this object from the source given by mFrom.
316 public function load() {
317 if ( $this->mLoadedItems
=== true ) {
320 wfProfileIn( __METHOD__
);
322 // Set it now to avoid infinite recursion in accessors
323 $this->mLoadedItems
= true;
325 switch ( $this->mFrom
) {
327 $this->loadDefaults();
330 $this->mId
= self
::idFromName( $this->mName
);
332 // Nonexistent user placeholder object
333 $this->loadDefaults( $this->mName
);
342 if ( !$this->loadFromSession() ) {
343 // Loading from session failed. Load defaults.
344 $this->loadDefaults();
346 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
349 wfProfileOut( __METHOD__
);
350 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
352 wfProfileOut( __METHOD__
);
356 * Load user table data, given mId has already been set.
357 * @return bool False if the ID does not exist, true otherwise
359 public function loadFromId() {
361 if ( $this->mId
== 0 ) {
362 $this->loadDefaults();
367 $key = wfMemcKey( 'user', 'id', $this->mId
);
368 $data = $wgMemc->get( $key );
369 if ( !is_array( $data ) ||
$data['mVersion'] != self
::VERSION
) {
370 // Object is expired, load from DB
375 wfDebug( "User: cache miss for user {$this->mId}\n" );
377 if ( !$this->loadFromDatabase() ) {
378 // Can't load from ID, user is anonymous
381 $this->saveToCache();
383 wfDebug( "User: got user {$this->mId} from cache\n" );
384 // Restore from cache
385 foreach ( self
::$mCacheVars as $name ) {
386 $this->$name = $data[$name];
390 $this->mLoadedItems
= true;
396 * Save user data to the shared cache
398 public function saveToCache() {
401 $this->loadOptions();
402 if ( $this->isAnon() ) {
403 // Anonymous users are uncached
407 foreach ( self
::$mCacheVars as $name ) {
408 $data[$name] = $this->$name;
410 $data['mVersion'] = self
::VERSION
;
411 $key = wfMemcKey( 'user', 'id', $this->mId
);
413 $wgMemc->set( $key, $data );
416 /** @name newFrom*() static factory methods */
420 * Static factory method for creation from username.
422 * This is slightly less efficient than newFromId(), so use newFromId() if
423 * you have both an ID and a name handy.
425 * @param string $name Username, validated by Title::newFromText()
426 * @param string|bool $validate Validate username. Takes the same parameters as
427 * User::getCanonicalName(), except that true is accepted as an alias
428 * for 'valid', for BC.
430 * @return User|bool User object, or false if the username is invalid
431 * (e.g. if it contains illegal characters or is an IP address). If the
432 * username is not present in the database, the result will be a user object
433 * with a name, zero user ID and default settings.
435 public static function newFromName( $name, $validate = 'valid' ) {
436 if ( $validate === true ) {
439 $name = self
::getCanonicalName( $name, $validate );
440 if ( $name === false ) {
443 // Create unloaded user object
447 $u->setItemLoaded( 'name' );
453 * Static factory method for creation from a given user ID.
455 * @param int $id Valid user ID
456 * @return User The corresponding User object
458 public static function newFromId( $id ) {
462 $u->setItemLoaded( 'id' );
467 * Factory method to fetch whichever user has a given email confirmation code.
468 * This code is generated when an account is created or its e-mail address
471 * If the code is invalid or has expired, returns NULL.
473 * @param string $code Confirmation code
476 public static function newFromConfirmationCode( $code ) {
477 $dbr = wfGetDB( DB_SLAVE
);
478 $id = $dbr->selectField( 'user', 'user_id', array(
479 'user_email_token' => md5( $code ),
480 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
482 if ( $id !== false ) {
483 return User
::newFromId( $id );
490 * Create a new user object using data from session or cookies. If the
491 * login credentials are invalid, the result is an anonymous user.
493 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
496 public static function newFromSession( WebRequest
$request = null ) {
498 $user->mFrom
= 'session';
499 $user->mRequest
= $request;
504 * Create a new user object from a user row.
505 * The row should have the following fields from the user table in it:
506 * - either user_name or user_id to load further data if needed (or both)
508 * - all other fields (email, password, etc.)
509 * It is useless to provide the remaining fields if either user_id,
510 * user_name and user_real_name are not provided because the whole row
511 * will be loaded once more from the database when accessing them.
513 * @param stdClass $row A row from the user table
514 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
517 public static function newFromRow( $row, $data = null ) {
519 $user->loadFromRow( $row, $data );
526 * Get the username corresponding to a given user ID
527 * @param int $id User ID
528 * @return string|bool The corresponding username
530 public static function whoIs( $id ) {
531 return UserCache
::singleton()->getProp( $id, 'name' );
535 * Get the real name of a user given their user ID
537 * @param int $id User ID
538 * @return string|bool The corresponding user's real name
540 public static function whoIsReal( $id ) {
541 return UserCache
::singleton()->getProp( $id, 'real_name' );
545 * Get database id given a user name
546 * @param string $name Username
547 * @return int|null The corresponding user's ID, or null if user is nonexistent
549 public static function idFromName( $name ) {
550 $nt = Title
::makeTitleSafe( NS_USER
, $name );
551 if ( is_null( $nt ) ) {
556 if ( isset( self
::$idCacheByName[$name] ) ) {
557 return self
::$idCacheByName[$name];
560 $dbr = wfGetDB( DB_SLAVE
);
561 $s = $dbr->selectRow(
564 array( 'user_name' => $nt->getText() ),
568 if ( $s === false ) {
571 $result = $s->user_id
;
574 self
::$idCacheByName[$name] = $result;
576 if ( count( self
::$idCacheByName ) > 1000 ) {
577 self
::$idCacheByName = array();
584 * Reset the cache used in idFromName(). For use in tests.
586 public static function resetIdByNameCache() {
587 self
::$idCacheByName = array();
591 * Does the string match an anonymous IPv4 address?
593 * This function exists for username validation, in order to reject
594 * usernames which are similar in form to IP addresses. Strings such
595 * as 300.300.300.300 will return true because it looks like an IP
596 * address, despite not being strictly valid.
598 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
599 * address because the usemod software would "cloak" anonymous IP
600 * addresses like this, if we allowed accounts like this to be created
601 * new users could get the old edits of these anonymous users.
603 * @param string $name Name to match
606 public static function isIP( $name ) {
607 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
608 || IP
::isIPv6( $name );
612 * Is the input a valid username?
614 * Checks if the input is a valid username, we don't want an empty string,
615 * an IP address, anything that contains slashes (would mess up subpages),
616 * is longer than the maximum allowed username size or doesn't begin with
619 * @param string $name Name to match
622 public static function isValidUserName( $name ) {
623 global $wgContLang, $wgMaxNameChars;
626 || User
::isIP( $name )
627 ||
strpos( $name, '/' ) !== false
628 ||
strlen( $name ) > $wgMaxNameChars
629 ||
$name != $wgContLang->ucfirst( $name ) ) {
630 wfDebugLog( 'username', __METHOD__
.
631 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
635 // Ensure that the name can't be misresolved as a different title,
636 // such as with extra namespace keys at the start.
637 $parsed = Title
::newFromText( $name );
638 if ( is_null( $parsed )
639 ||
$parsed->getNamespace()
640 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
641 wfDebugLog( 'username', __METHOD__
.
642 ": '$name' invalid due to ambiguous prefixes" );
646 // Check an additional blacklist of troublemaker characters.
647 // Should these be merged into the title char list?
648 $unicodeBlacklist = '/[' .
649 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
650 '\x{00a0}' . # non-breaking space
651 '\x{2000}-\x{200f}' . # various whitespace
652 '\x{2028}-\x{202f}' . # breaks and control chars
653 '\x{3000}' . # ideographic space
654 '\x{e000}-\x{f8ff}' . # private use
656 if ( preg_match( $unicodeBlacklist, $name ) ) {
657 wfDebugLog( 'username', __METHOD__
.
658 ": '$name' invalid due to blacklisted characters" );
666 * Usernames which fail to pass this function will be blocked
667 * from user login and new account registrations, but may be used
668 * internally by batch processes.
670 * If an account already exists in this form, login will be blocked
671 * by a failure to pass this function.
673 * @param string $name Name to match
676 public static function isUsableName( $name ) {
677 global $wgReservedUsernames;
678 // Must be a valid username, obviously ;)
679 if ( !self
::isValidUserName( $name ) ) {
683 static $reservedUsernames = false;
684 if ( !$reservedUsernames ) {
685 $reservedUsernames = $wgReservedUsernames;
686 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
689 // Certain names may be reserved for batch processes.
690 foreach ( $reservedUsernames as $reserved ) {
691 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
692 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
694 if ( $reserved == $name ) {
702 * Usernames which fail to pass this function will be blocked
703 * from new account registrations, but may be used internally
704 * either by batch processes or by user accounts which have
705 * already been created.
707 * Additional blacklisting may be added here rather than in
708 * isValidUserName() to avoid disrupting existing accounts.
710 * @param string $name String to match
713 public static function isCreatableName( $name ) {
714 global $wgInvalidUsernameCharacters;
716 // Ensure that the username isn't longer than 235 bytes, so that
717 // (at least for the builtin skins) user javascript and css files
718 // will work. (bug 23080)
719 if ( strlen( $name ) > 235 ) {
720 wfDebugLog( 'username', __METHOD__
.
721 ": '$name' invalid due to length" );
725 // Preg yells if you try to give it an empty string
726 if ( $wgInvalidUsernameCharacters !== '' ) {
727 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
728 wfDebugLog( 'username', __METHOD__
.
729 ": '$name' invalid due to wgInvalidUsernameCharacters" );
734 return self
::isUsableName( $name );
738 * Is the input a valid password for this user?
740 * @param string $password Desired password
743 public function isValidPassword( $password ) {
744 //simple boolean wrapper for getPasswordValidity
745 return $this->getPasswordValidity( $password ) === true;
750 * Given unvalidated password input, return error message on failure.
752 * @param string $password Desired password
753 * @return bool|string|array True on success, string or array of error message on failure
755 public function getPasswordValidity( $password ) {
756 $result = $this->checkPasswordValidity( $password );
757 if ( $result->isGood() ) {
761 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
762 $messages[] = $error['message'];
764 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
765 $messages[] = $warning['message'];
767 if ( count( $messages ) === 1 ) {
775 * Check if this is a valid password for this user. Status will be good if
776 * the password is valid, or have an array of error messages if not.
778 * @param string $password Desired password
782 public function checkPasswordValidity( $password ) {
783 global $wgMinimalPasswordLength, $wgContLang;
785 static $blockedLogins = array(
786 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
787 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
790 $status = Status
::newGood();
792 $result = false; //init $result to false for the internal checks
794 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
795 $status->error( $result );
799 if ( $result === false ) {
800 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
801 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
803 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
804 $status->error( 'password-name-match' );
806 } elseif ( isset( $blockedLogins[$this->getName()] )
807 && $password == $blockedLogins[$this->getName()]
809 $status->error( 'password-login-forbidden' );
812 //it seems weird returning a Good status here, but this is because of the
813 //initialization of $result to false above. If the hook is never run or it
814 //doesn't modify $result, then we will likely get down into this if with
818 } elseif ( $result === true ) {
821 $status->error( $result );
822 return $status; //the isValidPassword hook set a string $result and returned true
827 * Expire a user's password
829 * @param int $ts Optional timestamp to convert, default 0 for the current time
831 public function expirePassword( $ts = 0 ) {
833 $timestamp = wfTimestamp( TS_MW
, $ts );
834 $this->mPasswordExpires
= $timestamp;
835 $this->saveSettings();
839 * Clear the password expiration for a user
841 * @param bool $load Ensure user object is loaded first
843 public function resetPasswordExpiration( $load = true ) {
844 global $wgPasswordExpirationDays;
849 if ( $wgPasswordExpirationDays ) {
850 $newExpire = wfTimestamp(
852 time() +
( $wgPasswordExpirationDays * 24 * 3600 )
855 // Give extensions a chance to force an expiration
856 wfRunHooks( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
857 $this->mPasswordExpires
= $newExpire;
861 * Check if the user's password is expired.
862 * TODO: Put this and password length into a PasswordPolicy object
864 * @return string|bool The expiration type, or false if not expired
865 * hard: A password change is required to login
866 * soft: Allow login, but encourage password change
867 * false: Password is not expired
869 public function getPasswordExpired() {
870 global $wgPasswordExpireGrace;
872 $now = wfTimestamp();
873 $expiration = $this->getPasswordExpireDate();
874 $expUnix = wfTimestamp( TS_UNIX
, $expiration );
875 if ( $expiration !== null && $expUnix < $now ) {
876 $expired = ( $expUnix +
$wgPasswordExpireGrace < $now ) ?
'hard' : 'soft';
882 * Get this user's password expiration date. Since this may be using
883 * the cached User object, we assume that whatever mechanism is setting
884 * the expiration date is also expiring the User cache.
886 * @return string|bool The datestamp of the expiration, or null if not set
888 public function getPasswordExpireDate() {
890 return $this->mPasswordExpires
;
894 * Given unvalidated user input, return a canonical username, or false if
895 * the username is invalid.
896 * @param string $name User input
897 * @param string|bool $validate Type of validation to use:
898 * - false No validation
899 * - 'valid' Valid for batch processes
900 * - 'usable' Valid for batch processes and login
901 * - 'creatable' Valid for batch processes, login and account creation
903 * @throws MWException
904 * @return bool|string
906 public static function getCanonicalName( $name, $validate = 'valid' ) {
907 // Force usernames to capital
909 $name = $wgContLang->ucfirst( $name );
911 # Reject names containing '#'; these will be cleaned up
912 # with title normalisation, but then it's too late to
914 if ( strpos( $name, '#' ) !== false ) {
918 // Clean up name according to title rules,
919 // but only when validation is requested (bug 12654)
920 $t = ( $validate !== false ) ?
921 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
922 // Check for invalid titles
923 if ( is_null( $t ) ) {
927 // Reject various classes of invalid names
929 $name = $wgAuth->getCanonicalName( $t->getText() );
931 switch ( $validate ) {
935 if ( !User
::isValidUserName( $name ) ) {
940 if ( !User
::isUsableName( $name ) ) {
945 if ( !User
::isCreatableName( $name ) ) {
950 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
956 * Count the number of edits of a user
958 * @param int $uid User ID to check
959 * @return int The user's edit count
961 * @deprecated since 1.21 in favour of User::getEditCount
963 public static function edits( $uid ) {
964 wfDeprecated( __METHOD__
, '1.21' );
965 $user = self
::newFromId( $uid );
966 return $user->getEditCount();
970 * Return a random password.
972 * @return string New random password
974 public static function randomPassword() {
975 global $wgMinimalPasswordLength;
976 // Decide the final password length based on our min password length,
977 // stopping at a minimum of 10 chars.
978 $length = max( 10, $wgMinimalPasswordLength );
979 // Multiply by 1.25 to get the number of hex characters we need
980 $length = $length * 1.25;
981 // Generate random hex chars
982 $hex = MWCryptRand
::generateHex( $length );
983 // Convert from base 16 to base 32 to get a proper password like string
984 return wfBaseConvert( $hex, 16, 32 );
988 * Set cached properties to default.
990 * @note This no longer clears uncached lazy-initialised properties;
991 * the constructor does that instead.
993 * @param string|bool $name
995 public function loadDefaults( $name = false ) {
996 wfProfileIn( __METHOD__
);
998 $passwordFactory = self
::getPasswordFactory();
1001 $this->mName
= $name;
1002 $this->mRealName
= '';
1003 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1004 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1005 $this->mNewpassTime
= null;
1007 $this->mOptionOverrides
= null;
1008 $this->mOptionsLoaded
= false;
1010 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1011 if ( $loggedOut !== null ) {
1012 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1014 $this->mTouched
= '1'; # Allow any pages to be cached
1017 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1018 $this->mEmailAuthenticated
= null;
1019 $this->mEmailToken
= '';
1020 $this->mEmailTokenExpires
= null;
1021 $this->mPasswordExpires
= null;
1022 $this->resetPasswordExpiration( false );
1023 $this->mRegistration
= wfTimestamp( TS_MW
);
1024 $this->mGroups
= array();
1026 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
1028 wfProfileOut( __METHOD__
);
1032 * Return whether an item has been loaded.
1034 * @param string $item Item to check. Current possibilities:
1038 * @param string $all 'all' to check if the whole object has been loaded
1039 * or any other string to check if only the item is available (e.g.
1043 public function isItemLoaded( $item, $all = 'all' ) {
1044 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1045 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1049 * Set that an item has been loaded
1051 * @param string $item
1053 protected function setItemLoaded( $item ) {
1054 if ( is_array( $this->mLoadedItems
) ) {
1055 $this->mLoadedItems
[$item] = true;
1060 * Load user data from the session or login cookie.
1061 * @return bool True if the user is logged in, false otherwise.
1063 private function loadFromSession() {
1065 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
1066 if ( $result !== null ) {
1070 $request = $this->getRequest();
1072 $cookieId = $request->getCookie( 'UserID' );
1073 $sessId = $request->getSessionData( 'wsUserID' );
1075 if ( $cookieId !== null ) {
1076 $sId = intval( $cookieId );
1077 if ( $sessId !== null && $cookieId != $sessId ) {
1078 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1079 cookie user ID ($sId) don't match!" );
1082 $request->setSessionData( 'wsUserID', $sId );
1083 } elseif ( $sessId !== null && $sessId != 0 ) {
1089 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1090 $sName = $request->getSessionData( 'wsUserName' );
1091 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1092 $sName = $request->getCookie( 'UserName' );
1093 $request->setSessionData( 'wsUserName', $sName );
1098 $proposedUser = User
::newFromId( $sId );
1099 if ( !$proposedUser->isLoggedIn() ) {
1104 global $wgBlockDisablesLogin;
1105 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1106 // User blocked and we've disabled blocked user logins
1110 if ( $request->getSessionData( 'wsToken' ) ) {
1112 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1114 } elseif ( $request->getCookie( 'Token' ) ) {
1115 # Get the token from DB/cache and clean it up to remove garbage padding.
1116 # This deals with historical problems with bugs and the default column value.
1117 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1118 // Make comparison in constant time (bug 61346)
1119 $passwordCorrect = strlen( $token )
1120 && hash_equals( $token, $request->getCookie( 'Token' ) );
1123 // No session or persistent login cookie
1127 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1128 $this->loadFromUserObject( $proposedUser );
1129 $request->setSessionData( 'wsToken', $this->mToken
);
1130 wfDebug( "User: logged in from $from\n" );
1133 // Invalid credentials
1134 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1140 * Load user and user_group data from the database.
1141 * $this->mId must be set, this is how the user is identified.
1143 * @param int $flags Supports User::READ_LOCKING
1144 * @return bool True if the user exists, false if the user is anonymous
1146 public function loadFromDatabase( $flags = 0 ) {
1148 $this->mId
= intval( $this->mId
);
1151 if ( !$this->mId
) {
1152 $this->loadDefaults();
1156 $dbr = wfGetDB( DB_MASTER
);
1157 $s = $dbr->selectRow(
1159 self
::selectFields(),
1160 array( 'user_id' => $this->mId
),
1162 ( $flags & self
::READ_LOCKING
== self
::READ_LOCKING
)
1163 ?
array( 'LOCK IN SHARE MODE' )
1167 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1169 if ( $s !== false ) {
1170 // Initialise user table data
1171 $this->loadFromRow( $s );
1172 $this->mGroups
= null; // deferred
1173 $this->getEditCount(); // revalidation for nulls
1178 $this->loadDefaults();
1184 * Initialize this object from a row from the user table.
1186 * @param stdClass $row Row from the user table to load.
1187 * @param array $data Further user data to load into the object
1189 * user_groups Array with groups out of the user_groups table
1190 * user_properties Array with properties out of the user_properties table
1192 public function loadFromRow( $row, $data = null ) {
1194 $passwordFactory = self
::getPasswordFactory();
1196 $this->mGroups
= null; // deferred
1198 if ( isset( $row->user_name
) ) {
1199 $this->mName
= $row->user_name
;
1200 $this->mFrom
= 'name';
1201 $this->setItemLoaded( 'name' );
1206 if ( isset( $row->user_real_name
) ) {
1207 $this->mRealName
= $row->user_real_name
;
1208 $this->setItemLoaded( 'realname' );
1213 if ( isset( $row->user_id
) ) {
1214 $this->mId
= intval( $row->user_id
);
1215 $this->mFrom
= 'id';
1216 $this->setItemLoaded( 'id' );
1221 if ( isset( $row->user_editcount
) ) {
1222 $this->mEditCount
= $row->user_editcount
;
1227 if ( isset( $row->user_password
) ) {
1228 // Check for *really* old password hashes that don't even have a type
1229 // The old hash format was just an md5 hex hash, with no type information
1230 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password
) ) {
1231 $row->user_password
= ":A:{$this->mId}:{$row->user_password}";
1235 $this->mPassword
= $passwordFactory->newFromCiphertext( $row->user_password
);
1236 } catch ( PasswordError
$e ) {
1237 wfDebug( 'Invalid password hash found in database.' );
1238 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1242 $this->mNewpassword
= $passwordFactory->newFromCiphertext( $row->user_newpassword
);
1243 } catch ( PasswordError
$e ) {
1244 wfDebug( 'Invalid password hash found in database.' );
1245 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1248 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1249 $this->mPasswordExpires
= wfTimestampOrNull( TS_MW
, $row->user_password_expires
);
1252 if ( isset( $row->user_email
) ) {
1253 $this->mEmail
= $row->user_email
;
1254 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1255 $this->mToken
= $row->user_token
;
1256 if ( $this->mToken
== '' ) {
1257 $this->mToken
= null;
1259 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1260 $this->mEmailToken
= $row->user_email_token
;
1261 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1262 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1268 $this->mLoadedItems
= true;
1271 if ( is_array( $data ) ) {
1272 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1273 $this->mGroups
= $data['user_groups'];
1275 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1276 $this->loadOptions( $data['user_properties'] );
1282 * Load the data for this user object from another user object.
1286 protected function loadFromUserObject( $user ) {
1288 $user->loadGroups();
1289 $user->loadOptions();
1290 foreach ( self
::$mCacheVars as $var ) {
1291 $this->$var = $user->$var;
1296 * Load the groups from the database if they aren't already loaded.
1298 private function loadGroups() {
1299 if ( is_null( $this->mGroups
) ) {
1300 $dbr = wfGetDB( DB_MASTER
);
1301 $res = $dbr->select( 'user_groups',
1302 array( 'ug_group' ),
1303 array( 'ug_user' => $this->mId
),
1305 $this->mGroups
= array();
1306 foreach ( $res as $row ) {
1307 $this->mGroups
[] = $row->ug_group
;
1313 * Load the user's password hashes from the database
1315 * This is usually called in a scenario where the actual User object was
1316 * loaded from the cache, and then password comparison needs to be performed.
1317 * Password hashes are not stored in memcached.
1321 private function loadPasswords() {
1322 if ( $this->getId() !== 0 && ( $this->mPassword
=== null ||
$this->mNewpassword
=== null ) ) {
1323 $this->loadFromRow( wfGetDB( DB_MASTER
)->selectRow(
1325 array( 'user_password', 'user_newpassword', 'user_newpass_time', 'user_password_expires' ),
1326 array( 'user_id' => $this->getId() ),
1333 * Add the user to the group if he/she meets given criteria.
1335 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1336 * possible to remove manually via Special:UserRights. In such case it
1337 * will not be re-added automatically. The user will also not lose the
1338 * group if they no longer meet the criteria.
1340 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1342 * @return array Array of groups the user has been promoted to.
1344 * @see $wgAutopromoteOnce
1346 public function addAutopromoteOnceGroups( $event ) {
1347 global $wgAutopromoteOnceLogInRC, $wgAuth;
1349 $toPromote = array();
1350 if ( $this->getId() ) {
1351 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1352 if ( count( $toPromote ) ) {
1353 $oldGroups = $this->getGroups(); // previous groups
1355 foreach ( $toPromote as $group ) {
1356 $this->addGroup( $group );
1358 // update groups in external authentication database
1359 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1361 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1363 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1364 $logEntry->setPerformer( $this );
1365 $logEntry->setTarget( $this->getUserPage() );
1366 $logEntry->setParameters( array(
1367 '4::oldgroups' => $oldGroups,
1368 '5::newgroups' => $newGroups,
1370 $logid = $logEntry->insert();
1371 if ( $wgAutopromoteOnceLogInRC ) {
1372 $logEntry->publish( $logid );
1380 * Clear various cached data stored in this object. The cache of the user table
1381 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1383 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1384 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1386 public function clearInstanceCache( $reloadFrom = false ) {
1387 $this->mNewtalk
= -1;
1388 $this->mDatePreference
= null;
1389 $this->mBlockedby
= -1; # Unset
1390 $this->mHash
= false;
1391 $this->mRights
= null;
1392 $this->mEffectiveGroups
= null;
1393 $this->mImplicitGroups
= null;
1394 $this->mGroups
= null;
1395 $this->mOptions
= null;
1396 $this->mOptionsLoaded
= false;
1397 $this->mEditCount
= null;
1399 if ( $reloadFrom ) {
1400 $this->mLoadedItems
= array();
1401 $this->mFrom
= $reloadFrom;
1406 * Combine the language default options with any site-specific options
1407 * and add the default language variants.
1409 * @return array Array of String options
1411 public static function getDefaultOptions() {
1412 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1414 static $defOpt = null;
1415 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1416 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1417 // mid-request and see that change reflected in the return value of this function.
1418 // Which is insane and would never happen during normal MW operation
1422 $defOpt = $wgDefaultUserOptions;
1423 // Default language setting
1424 $defOpt['language'] = $wgContLang->getCode();
1425 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1426 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1428 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1429 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1431 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1433 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1439 * Get a given default option value.
1441 * @param string $opt Name of option to retrieve
1442 * @return string Default option value
1444 public static function getDefaultOption( $opt ) {
1445 $defOpts = self
::getDefaultOptions();
1446 if ( isset( $defOpts[$opt] ) ) {
1447 return $defOpts[$opt];
1454 * Get blocking information
1455 * @param bool $bFromSlave Whether to check the slave database first.
1456 * To improve performance, non-critical checks are done against slaves.
1457 * Check when actually saving should be done against master.
1459 private function getBlockedStatus( $bFromSlave = true ) {
1460 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1462 if ( -1 != $this->mBlockedby
) {
1466 wfProfileIn( __METHOD__
);
1467 wfDebug( __METHOD__
. ": checking...\n" );
1469 // Initialize data...
1470 // Otherwise something ends up stomping on $this->mBlockedby when
1471 // things get lazy-loaded later, causing false positive block hits
1472 // due to -1 !== 0. Probably session-related... Nothing should be
1473 // overwriting mBlockedby, surely?
1476 # We only need to worry about passing the IP address to the Block generator if the
1477 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1478 # know which IP address they're actually coming from
1479 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1480 $ip = $this->getRequest()->getIP();
1486 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1489 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1490 && !in_array( $ip, $wgProxyWhitelist )
1493 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1495 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1496 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1497 $block->setTarget( $ip );
1498 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1500 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1501 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1502 $block->setTarget( $ip );
1506 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1507 if ( !$block instanceof Block
1508 && $wgApplyIpBlocksToXff
1510 && !$this->isAllowed( 'proxyunbannable' )
1511 && !in_array( $ip, $wgProxyWhitelist )
1513 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1514 $xff = array_map( 'trim', explode( ',', $xff ) );
1515 $xff = array_diff( $xff, array( $ip ) );
1516 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1517 $block = Block
::chooseBlock( $xffblocks, $xff );
1518 if ( $block instanceof Block
) {
1519 # Mangle the reason to alert the user that the block
1520 # originated from matching the X-Forwarded-For header.
1521 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1525 if ( $block instanceof Block
) {
1526 wfDebug( __METHOD__
. ": Found block.\n" );
1527 $this->mBlock
= $block;
1528 $this->mBlockedby
= $block->getByName();
1529 $this->mBlockreason
= $block->mReason
;
1530 $this->mHideName
= $block->mHideName
;
1531 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1533 $this->mBlockedby
= '';
1534 $this->mHideName
= 0;
1535 $this->mAllowUsertalk
= false;
1539 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1541 wfProfileOut( __METHOD__
);
1545 * Whether the given IP is in a DNS blacklist.
1547 * @param string $ip IP to check
1548 * @param bool $checkWhitelist Whether to check the whitelist first
1549 * @return bool True if blacklisted.
1551 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1552 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1554 if ( !$wgEnableDnsBlacklist ) {
1558 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1562 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1566 * Whether the given IP is in a given DNS blacklist.
1568 * @param string $ip IP to check
1569 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1570 * @return bool True if blacklisted.
1572 public function inDnsBlacklist( $ip, $bases ) {
1573 wfProfileIn( __METHOD__
);
1576 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1577 if ( IP
::isIPv4( $ip ) ) {
1578 // Reverse IP, bug 21255
1579 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1581 foreach ( (array)$bases as $base ) {
1583 // If we have an access key, use that too (ProjectHoneypot, etc.)
1584 if ( is_array( $base ) ) {
1585 if ( count( $base ) >= 2 ) {
1586 // Access key is 1, base URL is 0
1587 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1589 $host = "$ipReversed.{$base[0]}";
1592 $host = "$ipReversed.$base";
1596 $ipList = gethostbynamel( $host );
1599 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1603 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1608 wfProfileOut( __METHOD__
);
1613 * Check if an IP address is in the local proxy list
1619 public static function isLocallyBlockedProxy( $ip ) {
1620 global $wgProxyList;
1622 if ( !$wgProxyList ) {
1625 wfProfileIn( __METHOD__
);
1627 if ( !is_array( $wgProxyList ) ) {
1628 // Load from the specified file
1629 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1632 if ( !is_array( $wgProxyList ) ) {
1634 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1636 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1637 // Old-style flipped proxy list
1642 wfProfileOut( __METHOD__
);
1647 * Is this user subject to rate limiting?
1649 * @return bool True if rate limited
1651 public function isPingLimitable() {
1652 global $wgRateLimitsExcludedIPs;
1653 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1654 // No other good way currently to disable rate limits
1655 // for specific IPs. :P
1656 // But this is a crappy hack and should die.
1659 return !$this->isAllowed( 'noratelimit' );
1663 * Primitive rate limits: enforce maximum actions per time period
1664 * to put a brake on flooding.
1666 * The method generates both a generic profiling point and a per action one
1667 * (suffix being "-$action".
1669 * @note When using a shared cache like memcached, IP-address
1670 * last-hit counters will be shared across wikis.
1672 * @param string $action Action to enforce; 'edit' if unspecified
1673 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1674 * @return bool True if a rate limiter was tripped
1676 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1677 // Call the 'PingLimiter' hook
1679 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1683 global $wgRateLimits;
1684 if ( !isset( $wgRateLimits[$action] ) ) {
1688 // Some groups shouldn't trigger the ping limiter, ever
1689 if ( !$this->isPingLimitable() ) {
1694 wfProfileIn( __METHOD__
);
1695 wfProfileIn( __METHOD__
. '-' . $action );
1697 $limits = $wgRateLimits[$action];
1699 $id = $this->getId();
1702 if ( isset( $limits['anon'] ) && $id == 0 ) {
1703 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1706 if ( isset( $limits['user'] ) && $id != 0 ) {
1707 $userLimit = $limits['user'];
1709 if ( $this->isNewbie() ) {
1710 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1711 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1713 if ( isset( $limits['ip'] ) ) {
1714 $ip = $this->getRequest()->getIP();
1715 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1717 if ( isset( $limits['subnet'] ) ) {
1718 $ip = $this->getRequest()->getIP();
1721 if ( IP
::isIPv6( $ip ) ) {
1722 $parts = IP
::parseRange( "$ip/64" );
1723 $subnet = $parts[0];
1724 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1726 $subnet = $matches[1];
1728 if ( $subnet !== false ) {
1729 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1733 // Check for group-specific permissions
1734 // If more than one group applies, use the group with the highest limit
1735 foreach ( $this->getGroups() as $group ) {
1736 if ( isset( $limits[$group] ) ) {
1737 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1738 $userLimit = $limits[$group];
1742 // Set the user limit key
1743 if ( $userLimit !== false ) {
1744 list( $max, $period ) = $userLimit;
1745 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1746 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1750 foreach ( $keys as $key => $limit ) {
1751 list( $max, $period ) = $limit;
1752 $summary = "(limit $max in {$period}s)";
1753 $count = $wgMemc->get( $key );
1756 if ( $count >= $max ) {
1757 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1758 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1761 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1764 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1765 if ( $incrBy > 0 ) {
1766 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1769 if ( $incrBy > 0 ) {
1770 $wgMemc->incr( $key, $incrBy );
1774 wfProfileOut( __METHOD__
. '-' . $action );
1775 wfProfileOut( __METHOD__
);
1780 * Check if user is blocked
1782 * @param bool $bFromSlave Whether to check the slave database instead of
1783 * the master. Hacked from false due to horrible probs on site.
1784 * @return bool True if blocked, false otherwise
1786 public function isBlocked( $bFromSlave = true ) {
1787 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1791 * Get the block affecting the user, or null if the user is not blocked
1793 * @param bool $bFromSlave Whether to check the slave database instead of the master
1794 * @return Block|null
1796 public function getBlock( $bFromSlave = true ) {
1797 $this->getBlockedStatus( $bFromSlave );
1798 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1802 * Check if user is blocked from editing a particular article
1804 * @param Title $title Title to check
1805 * @param bool $bFromSlave Whether to check the slave database instead of the master
1808 public function isBlockedFrom( $title, $bFromSlave = false ) {
1809 global $wgBlockAllowsUTEdit;
1810 wfProfileIn( __METHOD__
);
1812 $blocked = $this->isBlocked( $bFromSlave );
1813 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1814 // If a user's name is suppressed, they cannot make edits anywhere
1815 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1816 && $title->getNamespace() == NS_USER_TALK
) {
1818 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1821 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1823 wfProfileOut( __METHOD__
);
1828 * If user is blocked, return the name of the user who placed the block
1829 * @return string Name of blocker
1831 public function blockedBy() {
1832 $this->getBlockedStatus();
1833 return $this->mBlockedby
;
1837 * If user is blocked, return the specified reason for the block
1838 * @return string Blocking reason
1840 public function blockedFor() {
1841 $this->getBlockedStatus();
1842 return $this->mBlockreason
;
1846 * If user is blocked, return the ID for the block
1847 * @return int Block ID
1849 public function getBlockId() {
1850 $this->getBlockedStatus();
1851 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1855 * Check if user is blocked on all wikis.
1856 * Do not use for actual edit permission checks!
1857 * This is intended for quick UI checks.
1859 * @param string $ip IP address, uses current client if none given
1860 * @return bool True if blocked, false otherwise
1862 public function isBlockedGlobally( $ip = '' ) {
1863 if ( $this->mBlockedGlobally
!== null ) {
1864 return $this->mBlockedGlobally
;
1866 // User is already an IP?
1867 if ( IP
::isIPAddress( $this->getName() ) ) {
1868 $ip = $this->getName();
1870 $ip = $this->getRequest()->getIP();
1873 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1874 $this->mBlockedGlobally
= (bool)$blocked;
1875 return $this->mBlockedGlobally
;
1879 * Check if user account is locked
1881 * @return bool True if locked, false otherwise
1883 public function isLocked() {
1884 if ( $this->mLocked
!== null ) {
1885 return $this->mLocked
;
1888 StubObject
::unstub( $wgAuth );
1889 $authUser = $wgAuth->getUserInstance( $this );
1890 $this->mLocked
= (bool)$authUser->isLocked();
1891 return $this->mLocked
;
1895 * Check if user account is hidden
1897 * @return bool True if hidden, false otherwise
1899 public function isHidden() {
1900 if ( $this->mHideName
!== null ) {
1901 return $this->mHideName
;
1903 $this->getBlockedStatus();
1904 if ( !$this->mHideName
) {
1906 StubObject
::unstub( $wgAuth );
1907 $authUser = $wgAuth->getUserInstance( $this );
1908 $this->mHideName
= (bool)$authUser->isHidden();
1910 return $this->mHideName
;
1914 * Get the user's ID.
1915 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1917 public function getId() {
1918 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1919 // Special case, we know the user is anonymous
1921 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1922 // Don't load if this was initialized from an ID
1929 * Set the user and reload all fields according to a given ID
1930 * @param int $v User ID to reload
1932 public function setId( $v ) {
1934 $this->clearInstanceCache( 'id' );
1938 * Get the user name, or the IP of an anonymous user
1939 * @return string User's name or IP address
1941 public function getName() {
1942 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1943 // Special case optimisation
1944 return $this->mName
;
1947 if ( $this->mName
=== false ) {
1949 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1951 return $this->mName
;
1956 * Set the user name.
1958 * This does not reload fields from the database according to the given
1959 * name. Rather, it is used to create a temporary "nonexistent user" for
1960 * later addition to the database. It can also be used to set the IP
1961 * address for an anonymous user to something other than the current
1964 * @note User::newFromName() has roughly the same function, when the named user
1966 * @param string $str New user name to set
1968 public function setName( $str ) {
1970 $this->mName
= $str;
1974 * Get the user's name escaped by underscores.
1975 * @return string Username escaped by underscores.
1977 public function getTitleKey() {
1978 return str_replace( ' ', '_', $this->getName() );
1982 * Check if the user has new messages.
1983 * @return bool True if the user has new messages
1985 public function getNewtalk() {
1988 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1989 if ( $this->mNewtalk
=== -1 ) {
1990 $this->mNewtalk
= false; # reset talk page status
1992 // Check memcached separately for anons, who have no
1993 // entire User object stored in there.
1994 if ( !$this->mId
) {
1995 global $wgDisableAnonTalk;
1996 if ( $wgDisableAnonTalk ) {
1997 // Anon newtalk disabled by configuration.
1998 $this->mNewtalk
= false;
2001 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
2002 $newtalk = $wgMemc->get( $key );
2003 if ( strval( $newtalk ) !== '' ) {
2004 $this->mNewtalk
= (bool)$newtalk;
2006 // Since we are caching this, make sure it is up to date by getting it
2008 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
2009 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
2013 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2017 return (bool)$this->mNewtalk
;
2021 * Return the data needed to construct links for new talk page message
2022 * alerts. If there are new messages, this will return an associative array
2023 * with the following data:
2024 * wiki: The database name of the wiki
2025 * link: Root-relative link to the user's talk page
2026 * rev: The last talk page revision that the user has seen or null. This
2027 * is useful for building diff links.
2028 * If there are no new messages, it returns an empty array.
2029 * @note This function was designed to accomodate multiple talk pages, but
2030 * currently only returns a single link and revision.
2033 public function getNewMessageLinks() {
2035 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2037 } elseif ( !$this->getNewtalk() ) {
2040 $utp = $this->getTalkPage();
2041 $dbr = wfGetDB( DB_SLAVE
);
2042 // Get the "last viewed rev" timestamp from the oldest message notification
2043 $timestamp = $dbr->selectField( 'user_newtalk',
2044 'MIN(user_last_timestamp)',
2045 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2047 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2048 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2052 * Get the revision ID for the last talk page revision viewed by the talk
2054 * @return int|null Revision ID or null
2056 public function getNewMessageRevisionId() {
2057 $newMessageRevisionId = null;
2058 $newMessageLinks = $this->getNewMessageLinks();
2059 if ( $newMessageLinks ) {
2060 // Note: getNewMessageLinks() never returns more than a single link
2061 // and it is always for the same wiki, but we double-check here in
2062 // case that changes some time in the future.
2063 if ( count( $newMessageLinks ) === 1
2064 && $newMessageLinks[0]['wiki'] === wfWikiID()
2065 && $newMessageLinks[0]['rev']
2067 $newMessageRevision = $newMessageLinks[0]['rev'];
2068 $newMessageRevisionId = $newMessageRevision->getId();
2071 return $newMessageRevisionId;
2075 * Internal uncached check for new messages
2078 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2079 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2080 * @param bool $fromMaster True to fetch from the master, false for a slave
2081 * @return bool True if the user has new messages
2083 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2084 if ( $fromMaster ) {
2085 $db = wfGetDB( DB_MASTER
);
2087 $db = wfGetDB( DB_SLAVE
);
2089 $ok = $db->selectField( 'user_newtalk', $field,
2090 array( $field => $id ), __METHOD__
);
2091 return $ok !== false;
2095 * Add or update the new messages flag
2096 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2097 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2098 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2099 * @return bool True if successful, false otherwise
2101 protected function updateNewtalk( $field, $id, $curRev = null ) {
2102 // Get timestamp of the talk page revision prior to the current one
2103 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2104 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2105 // Mark the user as having new messages since this revision
2106 $dbw = wfGetDB( DB_MASTER
);
2107 $dbw->insert( 'user_newtalk',
2108 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2111 if ( $dbw->affectedRows() ) {
2112 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2115 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2121 * Clear the new messages flag for the given user
2122 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2123 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2124 * @return bool True if successful, false otherwise
2126 protected function deleteNewtalk( $field, $id ) {
2127 $dbw = wfGetDB( DB_MASTER
);
2128 $dbw->delete( 'user_newtalk',
2129 array( $field => $id ),
2131 if ( $dbw->affectedRows() ) {
2132 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2135 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2141 * Update the 'You have new messages!' status.
2142 * @param bool $val Whether the user has new messages
2143 * @param Revision $curRev New, as yet unseen revision of the user talk
2144 * page. Ignored if null or !$val.
2146 public function setNewtalk( $val, $curRev = null ) {
2147 if ( wfReadOnly() ) {
2152 $this->mNewtalk
= $val;
2154 if ( $this->isAnon() ) {
2156 $id = $this->getName();
2159 $id = $this->getId();
2164 $changed = $this->updateNewtalk( $field, $id, $curRev );
2166 $changed = $this->deleteNewtalk( $field, $id );
2169 if ( $this->isAnon() ) {
2170 // Anons have a separate memcached space, since
2171 // user records aren't kept for them.
2172 $key = wfMemcKey( 'newtalk', 'ip', $id );
2173 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
2176 $this->invalidateCache();
2181 * Generate a current or new-future timestamp to be stored in the
2182 * user_touched field when we update things.
2183 * @return string Timestamp in TS_MW format
2185 private static function newTouchedTimestamp() {
2186 global $wgClockSkewFudge;
2187 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2191 * Clear user data from memcached.
2192 * Use after applying fun updates to the database; caller's
2193 * responsibility to update user_touched if appropriate.
2195 * Called implicitly from invalidateCache() and saveSettings().
2197 public function clearSharedCache() {
2201 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
2206 * Immediately touch the user data cache for this account.
2207 * Updates user_touched field, and removes account data from memcached
2208 * for reload on the next hit.
2210 public function invalidateCache() {
2211 if ( wfReadOnly() ) {
2216 $this->mTouched
= self
::newTouchedTimestamp();
2218 $dbw = wfGetDB( DB_MASTER
);
2219 $userid = $this->mId
;
2220 $touched = $this->mTouched
;
2221 $method = __METHOD__
;
2222 $dbw->onTransactionIdle( function () use ( $dbw, $userid, $touched, $method ) {
2223 // Prevent contention slams by checking user_touched first
2224 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2225 $needsPurge = $dbw->selectField( 'user', '1',
2226 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2227 if ( $needsPurge ) {
2228 $dbw->update( 'user',
2229 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2230 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2235 $this->clearSharedCache();
2240 * Validate the cache for this account.
2241 * @param string $timestamp A timestamp in TS_MW format
2244 public function validateCache( $timestamp ) {
2246 return ( $timestamp >= $this->mTouched
);
2250 * Get the user touched timestamp
2251 * @return string Timestamp
2253 public function getTouched() {
2255 return $this->mTouched
;
2262 public function getPassword() {
2263 $this->loadPasswords();
2265 return $this->mPassword
;
2272 public function getTemporaryPassword() {
2273 $this->loadPasswords();
2275 return $this->mNewpassword
;
2279 * Set the password and reset the random token.
2280 * Calls through to authentication plugin if necessary;
2281 * will have no effect if the auth plugin refuses to
2282 * pass the change through or if the legal password
2285 * As a special case, setting the password to null
2286 * wipes it, so the account cannot be logged in until
2287 * a new password is set, for instance via e-mail.
2289 * @param string $str New password to set
2290 * @throws PasswordError On failure
2294 public function setPassword( $str ) {
2297 $this->loadPasswords();
2299 if ( $str !== null ) {
2300 if ( !$wgAuth->allowPasswordChange() ) {
2301 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2304 if ( !$this->isValidPassword( $str ) ) {
2305 global $wgMinimalPasswordLength;
2306 $valid = $this->getPasswordValidity( $str );
2307 if ( is_array( $valid ) ) {
2308 $message = array_shift( $valid );
2312 $params = array( $wgMinimalPasswordLength );
2314 throw new PasswordError( wfMessage( $message, $params )->text() );
2318 if ( !$wgAuth->setPassword( $this, $str ) ) {
2319 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2322 $this->setInternalPassword( $str );
2328 * Set the password and reset the random token unconditionally.
2330 * @param string|null $str New password to set or null to set an invalid
2331 * password hash meaning that the user will not be able to log in
2332 * through the web interface.
2334 public function setInternalPassword( $str ) {
2337 $passwordFactory = self
::getPasswordFactory();
2338 if ( $str === null ) {
2339 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
2341 $this->mPassword
= $passwordFactory->newFromPlaintext( $str );
2344 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
2345 $this->mNewpassTime
= null;
2349 * Get the user's current token.
2350 * @param bool $forceCreation Force the generation of a new token if the
2351 * user doesn't have one (default=true for backwards compatibility).
2352 * @return string Token
2354 public function getToken( $forceCreation = true ) {
2356 if ( !$this->mToken
&& $forceCreation ) {
2359 return $this->mToken
;
2363 * Set the random token (used for persistent authentication)
2364 * Called from loadDefaults() among other places.
2366 * @param string|bool $token If specified, set the token to this value
2368 public function setToken( $token = false ) {
2371 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2373 $this->mToken
= $token;
2378 * Set the password for a password reminder or new account email
2380 * @param string $str New password to set or null to set an invalid
2381 * password hash meaning that the user will not be able to use it
2382 * @param bool $throttle If true, reset the throttle timestamp to the present
2384 public function setNewpassword( $str, $throttle = true ) {
2385 $this->loadPasswords();
2387 if ( $str === null ) {
2388 $this->mNewpassword
= '';
2389 $this->mNewpassTime
= null;
2391 $this->mNewpassword
= self
::getPasswordFactory()->newFromPlaintext( $str );
2393 $this->mNewpassTime
= wfTimestampNow();
2399 * Has password reminder email been sent within the last
2400 * $wgPasswordReminderResendTime hours?
2403 public function isPasswordReminderThrottled() {
2404 global $wgPasswordReminderResendTime;
2406 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2409 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2410 return time() < $expiry;
2414 * Get the user's e-mail address
2415 * @return string User's email address
2417 public function getEmail() {
2419 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
2420 return $this->mEmail
;
2424 * Get the timestamp of the user's e-mail authentication
2425 * @return string TS_MW timestamp
2427 public function getEmailAuthenticationTimestamp() {
2429 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2430 return $this->mEmailAuthenticated
;
2434 * Set the user's e-mail address
2435 * @param string $str New e-mail address
2437 public function setEmail( $str ) {
2439 if ( $str == $this->mEmail
) {
2442 $this->invalidateEmail();
2443 $this->mEmail
= $str;
2444 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
2448 * Set the user's e-mail address and a confirmation mail if needed.
2451 * @param string $str New e-mail address
2454 public function setEmailWithConfirmation( $str ) {
2455 global $wgEnableEmail, $wgEmailAuthentication;
2457 if ( !$wgEnableEmail ) {
2458 return Status
::newFatal( 'emaildisabled' );
2461 $oldaddr = $this->getEmail();
2462 if ( $str === $oldaddr ) {
2463 return Status
::newGood( true );
2466 $this->setEmail( $str );
2468 if ( $str !== '' && $wgEmailAuthentication ) {
2469 // Send a confirmation request to the new address if needed
2470 $type = $oldaddr != '' ?
'changed' : 'set';
2471 $result = $this->sendConfirmationMail( $type );
2472 if ( $result->isGood() ) {
2473 // Say the the caller that a confirmation mail has been sent
2474 $result->value
= 'eauth';
2477 $result = Status
::newGood( true );
2484 * Get the user's real name
2485 * @return string User's real name
2487 public function getRealName() {
2488 if ( !$this->isItemLoaded( 'realname' ) ) {
2492 return $this->mRealName
;
2496 * Set the user's real name
2497 * @param string $str New real name
2499 public function setRealName( $str ) {
2501 $this->mRealName
= $str;
2505 * Get the user's current setting for a given option.
2507 * @param string $oname The option to check
2508 * @param string $defaultOverride A default value returned if the option does not exist
2509 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2510 * @return string User's current value for the option
2511 * @see getBoolOption()
2512 * @see getIntOption()
2514 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2515 global $wgHiddenPrefs;
2516 $this->loadOptions();
2518 # We want 'disabled' preferences to always behave as the default value for
2519 # users, even if they have set the option explicitly in their settings (ie they
2520 # set it, and then it was disabled removing their ability to change it). But
2521 # we don't want to erase the preferences in the database in case the preference
2522 # is re-enabled again. So don't touch $mOptions, just override the returned value
2523 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2524 return self
::getDefaultOption( $oname );
2527 if ( array_key_exists( $oname, $this->mOptions
) ) {
2528 return $this->mOptions
[$oname];
2530 return $defaultOverride;
2535 * Get all user's options
2539 public function getOptions() {
2540 global $wgHiddenPrefs;
2541 $this->loadOptions();
2542 $options = $this->mOptions
;
2544 # We want 'disabled' preferences to always behave as the default value for
2545 # users, even if they have set the option explicitly in their settings (ie they
2546 # set it, and then it was disabled removing their ability to change it). But
2547 # we don't want to erase the preferences in the database in case the preference
2548 # is re-enabled again. So don't touch $mOptions, just override the returned value
2549 foreach ( $wgHiddenPrefs as $pref ) {
2550 $default = self
::getDefaultOption( $pref );
2551 if ( $default !== null ) {
2552 $options[$pref] = $default;
2560 * Get the user's current setting for a given option, as a boolean value.
2562 * @param string $oname The option to check
2563 * @return bool User's current value for the option
2566 public function getBoolOption( $oname ) {
2567 return (bool)$this->getOption( $oname );
2571 * Get the user's current setting for a given option, as an integer value.
2573 * @param string $oname The option to check
2574 * @param int $defaultOverride A default value returned if the option does not exist
2575 * @return int User's current value for the option
2578 public function getIntOption( $oname, $defaultOverride = 0 ) {
2579 $val = $this->getOption( $oname );
2581 $val = $defaultOverride;
2583 return intval( $val );
2587 * Set the given option for a user.
2589 * You need to call saveSettings() to actually write to the database.
2591 * @param string $oname The option to set
2592 * @param mixed $val New value to set
2594 public function setOption( $oname, $val ) {
2595 $this->loadOptions();
2597 // Explicitly NULL values should refer to defaults
2598 if ( is_null( $val ) ) {
2599 $val = self
::getDefaultOption( $oname );
2602 $this->mOptions
[$oname] = $val;
2606 * Get a token stored in the preferences (like the watchlist one),
2607 * resetting it if it's empty (and saving changes).
2609 * @param string $oname The option name to retrieve the token from
2610 * @return string|bool User's current value for the option, or false if this option is disabled.
2611 * @see resetTokenFromOption()
2614 public function getTokenFromOption( $oname ) {
2615 global $wgHiddenPrefs;
2616 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2620 $token = $this->getOption( $oname );
2622 $token = $this->resetTokenFromOption( $oname );
2623 $this->saveSettings();
2629 * Reset a token stored in the preferences (like the watchlist one).
2630 * *Does not* save user's preferences (similarly to setOption()).
2632 * @param string $oname The option name to reset the token in
2633 * @return string|bool New token value, or false if this option is disabled.
2634 * @see getTokenFromOption()
2637 public function resetTokenFromOption( $oname ) {
2638 global $wgHiddenPrefs;
2639 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2643 $token = MWCryptRand
::generateHex( 40 );
2644 $this->setOption( $oname, $token );
2649 * Return a list of the types of user options currently returned by
2650 * User::getOptionKinds().
2652 * Currently, the option kinds are:
2653 * - 'registered' - preferences which are registered in core MediaWiki or
2654 * by extensions using the UserGetDefaultOptions hook.
2655 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2656 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2657 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2658 * be used by user scripts.
2659 * - 'special' - "preferences" that are not accessible via User::getOptions
2660 * or User::setOptions.
2661 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2662 * These are usually legacy options, removed in newer versions.
2664 * The API (and possibly others) use this function to determine the possible
2665 * option types for validation purposes, so make sure to update this when a
2666 * new option kind is added.
2668 * @see User::getOptionKinds
2669 * @return array Option kinds
2671 public static function listOptionKinds() {
2674 'registered-multiselect',
2675 'registered-checkmatrix',
2683 * Return an associative array mapping preferences keys to the kind of a preference they're
2684 * used for. Different kinds are handled differently when setting or reading preferences.
2686 * See User::listOptionKinds for the list of valid option types that can be provided.
2688 * @see User::listOptionKinds
2689 * @param IContextSource $context
2690 * @param array $options Assoc. array with options keys to check as keys.
2691 * Defaults to $this->mOptions.
2692 * @return array The key => kind mapping data
2694 public function getOptionKinds( IContextSource
$context, $options = null ) {
2695 $this->loadOptions();
2696 if ( $options === null ) {
2697 $options = $this->mOptions
;
2700 $prefs = Preferences
::getPreferences( $this, $context );
2703 // Pull out the "special" options, so they don't get converted as
2704 // multiselect or checkmatrix.
2705 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2706 foreach ( $specialOptions as $name => $value ) {
2707 unset( $prefs[$name] );
2710 // Multiselect and checkmatrix options are stored in the database with
2711 // one key per option, each having a boolean value. Extract those keys.
2712 $multiselectOptions = array();
2713 foreach ( $prefs as $name => $info ) {
2714 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2715 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2716 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2717 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2719 foreach ( $opts as $value ) {
2720 $multiselectOptions["$prefix$value"] = true;
2723 unset( $prefs[$name] );
2726 $checkmatrixOptions = array();
2727 foreach ( $prefs as $name => $info ) {
2728 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2729 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2730 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2731 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2732 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2734 foreach ( $columns as $column ) {
2735 foreach ( $rows as $row ) {
2736 $checkmatrixOptions["$prefix-$column-$row"] = true;
2740 unset( $prefs[$name] );
2744 // $value is ignored
2745 foreach ( $options as $key => $value ) {
2746 if ( isset( $prefs[$key] ) ) {
2747 $mapping[$key] = 'registered';
2748 } elseif ( isset( $multiselectOptions[$key] ) ) {
2749 $mapping[$key] = 'registered-multiselect';
2750 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2751 $mapping[$key] = 'registered-checkmatrix';
2752 } elseif ( isset( $specialOptions[$key] ) ) {
2753 $mapping[$key] = 'special';
2754 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2755 $mapping[$key] = 'userjs';
2757 $mapping[$key] = 'unused';
2765 * Reset certain (or all) options to the site defaults
2767 * The optional parameter determines which kinds of preferences will be reset.
2768 * Supported values are everything that can be reported by getOptionKinds()
2769 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2771 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2772 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2773 * for backwards-compatibility.
2774 * @param IContextSource|null $context Context source used when $resetKinds
2775 * does not contain 'all', passed to getOptionKinds().
2776 * Defaults to RequestContext::getMain() when null.
2778 public function resetOptions(
2779 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2780 IContextSource
$context = null
2783 $defaultOptions = self
::getDefaultOptions();
2785 if ( !is_array( $resetKinds ) ) {
2786 $resetKinds = array( $resetKinds );
2789 if ( in_array( 'all', $resetKinds ) ) {
2790 $newOptions = $defaultOptions;
2792 if ( $context === null ) {
2793 $context = RequestContext
::getMain();
2796 $optionKinds = $this->getOptionKinds( $context );
2797 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2798 $newOptions = array();
2800 // Use default values for the options that should be deleted, and
2801 // copy old values for the ones that shouldn't.
2802 foreach ( $this->mOptions
as $key => $value ) {
2803 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2804 if ( array_key_exists( $key, $defaultOptions ) ) {
2805 $newOptions[$key] = $defaultOptions[$key];
2808 $newOptions[$key] = $value;
2813 wfRunHooks( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2815 $this->mOptions
= $newOptions;
2816 $this->mOptionsLoaded
= true;
2820 * Get the user's preferred date format.
2821 * @return string User's preferred date format
2823 public function getDatePreference() {
2824 // Important migration for old data rows
2825 if ( is_null( $this->mDatePreference
) ) {
2827 $value = $this->getOption( 'date' );
2828 $map = $wgLang->getDatePreferenceMigrationMap();
2829 if ( isset( $map[$value] ) ) {
2830 $value = $map[$value];
2832 $this->mDatePreference
= $value;
2834 return $this->mDatePreference
;
2838 * Determine based on the wiki configuration and the user's options,
2839 * whether this user must be over HTTPS no matter what.
2843 public function requiresHTTPS() {
2844 global $wgSecureLogin;
2845 if ( !$wgSecureLogin ) {
2848 $https = $this->getBoolOption( 'prefershttps' );
2849 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2851 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2858 * Get the user preferred stub threshold
2862 public function getStubThreshold() {
2863 global $wgMaxArticleSize; # Maximum article size, in Kb
2864 $threshold = $this->getIntOption( 'stubthreshold' );
2865 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2866 // If they have set an impossible value, disable the preference
2867 // so we can use the parser cache again.
2874 * Get the permissions this user has.
2875 * @return array Array of String permission names
2877 public function getRights() {
2878 if ( is_null( $this->mRights
) ) {
2879 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2880 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2881 // Force reindexation of rights when a hook has unset one of them
2882 $this->mRights
= array_values( array_unique( $this->mRights
) );
2884 return $this->mRights
;
2888 * Get the list of explicit group memberships this user has.
2889 * The implicit * and user groups are not included.
2890 * @return array Array of String internal group names
2892 public function getGroups() {
2894 $this->loadGroups();
2895 return $this->mGroups
;
2899 * Get the list of implicit group memberships this user has.
2900 * This includes all explicit groups, plus 'user' if logged in,
2901 * '*' for all accounts, and autopromoted groups
2902 * @param bool $recache Whether to avoid the cache
2903 * @return array Array of String internal group names
2905 public function getEffectiveGroups( $recache = false ) {
2906 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2907 wfProfileIn( __METHOD__
);
2908 $this->mEffectiveGroups
= array_unique( array_merge(
2909 $this->getGroups(), // explicit groups
2910 $this->getAutomaticGroups( $recache ) // implicit groups
2912 // Hook for additional groups
2913 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2914 // Force reindexation of groups when a hook has unset one of them
2915 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
2916 wfProfileOut( __METHOD__
);
2918 return $this->mEffectiveGroups
;
2922 * Get the list of implicit group memberships this user has.
2923 * This includes 'user' if logged in, '*' for all accounts,
2924 * and autopromoted groups
2925 * @param bool $recache Whether to avoid the cache
2926 * @return array Array of String internal group names
2928 public function getAutomaticGroups( $recache = false ) {
2929 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
2930 wfProfileIn( __METHOD__
);
2931 $this->mImplicitGroups
= array( '*' );
2932 if ( $this->getId() ) {
2933 $this->mImplicitGroups
[] = 'user';
2935 $this->mImplicitGroups
= array_unique( array_merge(
2936 $this->mImplicitGroups
,
2937 Autopromote
::getAutopromoteGroups( $this )
2941 // Assure data consistency with rights/groups,
2942 // as getEffectiveGroups() depends on this function
2943 $this->mEffectiveGroups
= null;
2945 wfProfileOut( __METHOD__
);
2947 return $this->mImplicitGroups
;
2951 * Returns the groups the user has belonged to.
2953 * The user may still belong to the returned groups. Compare with getGroups().
2955 * The function will not return groups the user had belonged to before MW 1.17
2957 * @return array Names of the groups the user has belonged to.
2959 public function getFormerGroups() {
2960 if ( is_null( $this->mFormerGroups
) ) {
2961 $dbr = wfGetDB( DB_MASTER
);
2962 $res = $dbr->select( 'user_former_groups',
2963 array( 'ufg_group' ),
2964 array( 'ufg_user' => $this->mId
),
2966 $this->mFormerGroups
= array();
2967 foreach ( $res as $row ) {
2968 $this->mFormerGroups
[] = $row->ufg_group
;
2971 return $this->mFormerGroups
;
2975 * Get the user's edit count.
2976 * @return int|null Null for anonymous users
2978 public function getEditCount() {
2979 if ( !$this->getId() ) {
2983 if ( $this->mEditCount
=== null ) {
2984 /* Populate the count, if it has not been populated yet */
2985 wfProfileIn( __METHOD__
);
2986 $dbr = wfGetDB( DB_SLAVE
);
2987 // check if the user_editcount field has been initialized
2988 $count = $dbr->selectField(
2989 'user', 'user_editcount',
2990 array( 'user_id' => $this->mId
),
2994 if ( $count === null ) {
2995 // it has not been initialized. do so.
2996 $count = $this->initEditCount();
2998 $this->mEditCount
= $count;
2999 wfProfileOut( __METHOD__
);
3001 return (int)$this->mEditCount
;
3005 * Add the user to the given group.
3006 * This takes immediate effect.
3007 * @param string $group Name of the group to add
3009 public function addGroup( $group ) {
3010 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
3011 $dbw = wfGetDB( DB_MASTER
);
3012 if ( $this->getId() ) {
3013 $dbw->insert( 'user_groups',
3015 'ug_user' => $this->getID(),
3016 'ug_group' => $group,
3019 array( 'IGNORE' ) );
3022 $this->loadGroups();
3023 $this->mGroups
[] = $group;
3024 // In case loadGroups was not called before, we now have the right twice.
3025 // Get rid of the duplicate.
3026 $this->mGroups
= array_unique( $this->mGroups
);
3028 // Refresh the groups caches, and clear the rights cache so it will be
3029 // refreshed on the next call to $this->getRights().
3030 $this->getEffectiveGroups( true );
3031 $this->mRights
= null;
3033 $this->invalidateCache();
3037 * Remove the user from the given group.
3038 * This takes immediate effect.
3039 * @param string $group Name of the group to remove
3041 public function removeGroup( $group ) {
3043 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3044 $dbw = wfGetDB( DB_MASTER
);
3045 $dbw->delete( 'user_groups',
3047 'ug_user' => $this->getID(),
3048 'ug_group' => $group,
3050 // Remember that the user was in this group
3051 $dbw->insert( 'user_former_groups',
3053 'ufg_user' => $this->getID(),
3054 'ufg_group' => $group,
3057 array( 'IGNORE' ) );
3059 $this->loadGroups();
3060 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3062 // Refresh the groups caches, and clear the rights cache so it will be
3063 // refreshed on the next call to $this->getRights().
3064 $this->getEffectiveGroups( true );
3065 $this->mRights
= null;
3067 $this->invalidateCache();
3071 * Get whether the user is logged in
3074 public function isLoggedIn() {
3075 return $this->getID() != 0;
3079 * Get whether the user is anonymous
3082 public function isAnon() {
3083 return !$this->isLoggedIn();
3087 * Check if user is allowed to access a feature / make an action
3089 * @internal param \String $varargs permissions to test
3090 * @return bool True if user is allowed to perform *any* of the given actions
3094 public function isAllowedAny( /*...*/ ) {
3095 $permissions = func_get_args();
3096 foreach ( $permissions as $permission ) {
3097 if ( $this->isAllowed( $permission ) ) {
3106 * @internal param $varargs string
3107 * @return bool True if the user is allowed to perform *all* of the given actions
3109 public function isAllowedAll( /*...*/ ) {
3110 $permissions = func_get_args();
3111 foreach ( $permissions as $permission ) {
3112 if ( !$this->isAllowed( $permission ) ) {
3120 * Internal mechanics of testing a permission
3121 * @param string $action
3124 public function isAllowed( $action = '' ) {
3125 if ( $action === '' ) {
3126 return true; // In the spirit of DWIM
3128 // Patrolling may not be enabled
3129 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3130 global $wgUseRCPatrol, $wgUseNPPatrol;
3131 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3135 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3136 // by misconfiguration: 0 == 'foo'
3137 return in_array( $action, $this->getRights(), true );
3141 * Check whether to enable recent changes patrol features for this user
3142 * @return bool True or false
3144 public function useRCPatrol() {
3145 global $wgUseRCPatrol;
3146 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3150 * Check whether to enable new pages patrol features for this user
3151 * @return bool True or false
3153 public function useNPPatrol() {
3154 global $wgUseRCPatrol, $wgUseNPPatrol;
3156 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3157 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3162 * Get the WebRequest object to use with this object
3164 * @return WebRequest
3166 public function getRequest() {
3167 if ( $this->mRequest
) {
3168 return $this->mRequest
;
3176 * Get the current skin, loading it if required
3177 * @return Skin The current skin
3178 * @todo FIXME: Need to check the old failback system [AV]
3179 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3181 public function getSkin() {
3182 wfDeprecated( __METHOD__
, '1.18' );
3183 return RequestContext
::getMain()->getSkin();
3187 * Get a WatchedItem for this user and $title.
3189 * @since 1.22 $checkRights parameter added
3190 * @param Title $title
3191 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3192 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3193 * @return WatchedItem
3195 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3196 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3198 if ( isset( $this->mWatchedItems
[$key] ) ) {
3199 return $this->mWatchedItems
[$key];
3202 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3203 $this->mWatchedItems
= array();
3206 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3207 return $this->mWatchedItems
[$key];
3211 * Check the watched status of an article.
3212 * @since 1.22 $checkRights parameter added
3213 * @param Title $title Title of the article to look at
3214 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3215 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3218 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3219 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3224 * @since 1.22 $checkRights parameter added
3225 * @param Title $title Title of the article to look at
3226 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3227 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3229 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3230 $this->getWatchedItem( $title, $checkRights )->addWatch();
3231 $this->invalidateCache();
3235 * Stop watching an article.
3236 * @since 1.22 $checkRights parameter added
3237 * @param Title $title Title of the article to look at
3238 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3239 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3241 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3242 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3243 $this->invalidateCache();
3247 * Clear the user's notification timestamp for the given title.
3248 * If e-notif e-mails are on, they will receive notification mails on
3249 * the next change of the page if it's watched etc.
3250 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3251 * @param Title $title Title of the article to look at
3252 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3254 public function clearNotification( &$title, $oldid = 0 ) {
3255 global $wgUseEnotif, $wgShowUpdatedMarker;
3257 // Do nothing if the database is locked to writes
3258 if ( wfReadOnly() ) {
3262 // Do nothing if not allowed to edit the watchlist
3263 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3267 // If we're working on user's talk page, we should update the talk page message indicator
3268 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3269 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3273 $nextid = $oldid ?
$title->getNextRevisionID( $oldid ) : null;
3275 if ( !$oldid ||
!$nextid ) {
3276 // If we're looking at the latest revision, we should definitely clear it
3277 $this->setNewtalk( false );
3279 // Otherwise we should update its revision, if it's present
3280 if ( $this->getNewtalk() ) {
3281 // Naturally the other one won't clear by itself
3282 $this->setNewtalk( false );
3283 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3288 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3292 if ( $this->isAnon() ) {
3293 // Nothing else to do...
3297 // Only update the timestamp if the page is being watched.
3298 // The query to find out if it is watched is cached both in memcached and per-invocation,
3299 // and when it does have to be executed, it can be on a slave
3300 // If this is the user's newtalk page, we always update the timestamp
3302 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3306 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3310 * Resets all of the given user's page-change notification timestamps.
3311 * If e-notif e-mails are on, they will receive notification mails on
3312 * the next change of any watched page.
3313 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3315 public function clearAllNotifications() {
3316 if ( wfReadOnly() ) {
3320 // Do nothing if not allowed to edit the watchlist
3321 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3325 global $wgUseEnotif, $wgShowUpdatedMarker;
3326 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3327 $this->setNewtalk( false );
3330 $id = $this->getId();
3332 $dbw = wfGetDB( DB_MASTER
);
3333 $dbw->update( 'watchlist',
3334 array( /* SET */ 'wl_notificationtimestamp' => null ),
3335 array( /* WHERE */ 'wl_user' => $id ),
3338 // We also need to clear here the "you have new message" notification for the own user_talk page;
3339 // it's cleared one page view later in WikiPage::doViewUpdates().
3344 * Set a cookie on the user's client. Wrapper for
3345 * WebResponse::setCookie
3346 * @param string $name Name of the cookie to set
3347 * @param string $value Value to set
3348 * @param int $exp Expiration time, as a UNIX time value;
3349 * if 0 or not specified, use the default $wgCookieExpiration
3350 * @param bool $secure
3351 * true: Force setting the secure attribute when setting the cookie
3352 * false: Force NOT setting the secure attribute when setting the cookie
3353 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3354 * @param array $params Array of options sent passed to WebResponse::setcookie()
3356 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3357 $params['secure'] = $secure;
3358 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3362 * Clear a cookie on the user's client
3363 * @param string $name Name of the cookie to clear
3364 * @param bool $secure
3365 * true: Force setting the secure attribute when setting the cookie
3366 * false: Force NOT setting the secure attribute when setting the cookie
3367 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3368 * @param array $params Array of options sent passed to WebResponse::setcookie()
3370 protected function clearCookie( $name, $secure = null, $params = array() ) {
3371 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3375 * Set the default cookies for this session on the user's client.
3377 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3379 * @param bool $secure Whether to force secure/insecure cookies or use default
3380 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3382 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3383 if ( $request === null ) {
3384 $request = $this->getRequest();
3388 if ( 0 == $this->mId
) {
3391 if ( !$this->mToken
) {
3392 // When token is empty or NULL generate a new one and then save it to the database
3393 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3394 // Simply by setting every cell in the user_token column to NULL and letting them be
3395 // regenerated as users log back into the wiki.
3397 $this->saveSettings();
3400 'wsUserID' => $this->mId
,
3401 'wsToken' => $this->mToken
,
3402 'wsUserName' => $this->getName()
3405 'UserID' => $this->mId
,
3406 'UserName' => $this->getName(),
3408 if ( $rememberMe ) {
3409 $cookies['Token'] = $this->mToken
;
3411 $cookies['Token'] = false;
3414 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3416 foreach ( $session as $name => $value ) {
3417 $request->setSessionData( $name, $value );
3419 foreach ( $cookies as $name => $value ) {
3420 if ( $value === false ) {
3421 $this->clearCookie( $name );
3423 $this->setCookie( $name, $value, 0, $secure );
3428 * If wpStickHTTPS was selected, also set an insecure cookie that
3429 * will cause the site to redirect the user to HTTPS, if they access
3430 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3431 * as the one set by centralauth (bug 53538). Also set it to session, or
3432 * standard time setting, based on if rememberme was set.
3434 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3438 $rememberMe ?
0 : null,
3440 array( 'prefix' => '' ) // no prefix
3446 * Log this user out.
3448 public function logout() {
3449 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3455 * Clear the user's cookies and session, and reset the instance cache.
3458 public function doLogout() {
3459 $this->clearInstanceCache( 'defaults' );
3461 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3463 $this->clearCookie( 'UserID' );
3464 $this->clearCookie( 'Token' );
3465 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3467 // Remember when user logged out, to prevent seeing cached pages
3468 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3472 * Save this user's settings into the database.
3473 * @todo Only rarely do all these fields need to be set!
3475 public function saveSettings() {
3479 $this->loadPasswords();
3480 if ( wfReadOnly() ) {
3483 if ( 0 == $this->mId
) {
3487 $this->mTouched
= self
::newTouchedTimestamp();
3488 if ( !$wgAuth->allowSetLocalPassword() ) {
3489 $this->mPassword
= self
::getPasswordFactory()->newFromCiphertext( null );
3492 $dbw = wfGetDB( DB_MASTER
);
3493 $dbw->update( 'user',
3495 'user_name' => $this->mName
,
3496 'user_password' => $this->mPassword
->toString(),
3497 'user_newpassword' => $this->mNewpassword
->toString(),
3498 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3499 'user_real_name' => $this->mRealName
,
3500 'user_email' => $this->mEmail
,
3501 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3502 'user_touched' => $dbw->timestamp( $this->mTouched
),
3503 'user_token' => strval( $this->mToken
),
3504 'user_email_token' => $this->mEmailToken
,
3505 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3506 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires
),
3507 ), array( /* WHERE */
3508 'user_id' => $this->mId
3512 $this->saveOptions();
3514 wfRunHooks( 'UserSaveSettings', array( $this ) );
3515 $this->clearSharedCache();
3516 $this->getUserPage()->invalidateCache();
3520 * If only this user's username is known, and it exists, return the user ID.
3523 public function idForName() {
3524 $s = trim( $this->getName() );
3529 $dbr = wfGetDB( DB_SLAVE
);
3530 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
3531 if ( $id === false ) {
3538 * Add a user to the database, return the user object
3540 * @param string $name Username to add
3541 * @param array $params Array of Strings Non-default parameters to save to
3542 * the database as user_* fields:
3543 * - password: The user's password hash. Password logins will be disabled
3544 * if this is omitted.
3545 * - newpassword: Hash for a temporary password that has been mailed to
3547 * - email: The user's email address.
3548 * - email_authenticated: The email authentication timestamp.
3549 * - real_name: The user's real name.
3550 * - options: An associative array of non-default options.
3551 * - token: Random authentication token. Do not set.
3552 * - registration: Registration timestamp. Do not set.
3554 * @return User|null User object, or null if the username already exists.
3556 public static function createNew( $name, $params = array() ) {
3559 $user->loadPasswords();
3560 $user->setToken(); // init token
3561 if ( isset( $params['options'] ) ) {
3562 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3563 unset( $params['options'] );
3565 $dbw = wfGetDB( DB_MASTER
);
3566 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3569 'user_id' => $seqVal,
3570 'user_name' => $name,
3571 'user_password' => $user->mPassword
->toString(),
3572 'user_newpassword' => $user->mNewpassword
->toString(),
3573 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3574 'user_email' => $user->mEmail
,
3575 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3576 'user_real_name' => $user->mRealName
,
3577 'user_token' => strval( $user->mToken
),
3578 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3579 'user_editcount' => 0,
3580 'user_touched' => $dbw->timestamp( self
::newTouchedTimestamp() ),
3582 foreach ( $params as $name => $value ) {
3583 $fields["user_$name"] = $value;
3585 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3586 if ( $dbw->affectedRows() ) {
3587 $newUser = User
::newFromId( $dbw->insertId() );
3595 * Add this existing user object to the database. If the user already
3596 * exists, a fatal status object is returned, and the user object is
3597 * initialised with the data from the database.
3599 * Previously, this function generated a DB error due to a key conflict
3600 * if the user already existed. Many extension callers use this function
3601 * in code along the lines of:
3603 * $user = User::newFromName( $name );
3604 * if ( !$user->isLoggedIn() ) {
3605 * $user->addToDatabase();
3607 * // do something with $user...
3609 * However, this was vulnerable to a race condition (bug 16020). By
3610 * initialising the user object if the user exists, we aim to support this
3611 * calling sequence as far as possible.
3613 * Note that if the user exists, this function will acquire a write lock,
3614 * so it is still advisable to make the call conditional on isLoggedIn(),
3615 * and to commit the transaction after calling.
3617 * @throws MWException
3620 public function addToDatabase() {
3622 $this->loadPasswords();
3623 if ( !$this->mToken
) {
3624 $this->setToken(); // init token
3627 $this->mTouched
= self
::newTouchedTimestamp();
3629 $dbw = wfGetDB( DB_MASTER
);
3630 $inWrite = $dbw->writesOrCallbacksPending();
3631 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3632 $dbw->insert( 'user',
3634 'user_id' => $seqVal,
3635 'user_name' => $this->mName
,
3636 'user_password' => $this->mPassword
->toString(),
3637 'user_newpassword' => $this->mNewpassword
->toString(),
3638 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3639 'user_email' => $this->mEmail
,
3640 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3641 'user_real_name' => $this->mRealName
,
3642 'user_token' => strval( $this->mToken
),
3643 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3644 'user_editcount' => 0,
3645 'user_touched' => $dbw->timestamp( $this->mTouched
),
3649 if ( !$dbw->affectedRows() ) {
3650 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3651 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3653 // Can't commit due to pending writes that may need atomicity.
3654 // This may cause some lock contention unlike the case below.
3655 $options = array( 'LOCK IN SHARE MODE' );
3656 $flags = self
::READ_LOCKING
;
3658 // Often, this case happens early in views before any writes when
3659 // using CentralAuth. It's should be OK to commit and break the snapshot.
3660 $dbw->commit( __METHOD__
, 'flush' );
3664 $this->mId
= $dbw->selectField( 'user', 'user_id',
3665 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3668 if ( $this->loadFromDatabase( $flags ) ) {
3673 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3674 "to insert user '{$this->mName}' row, but it was not present in select!" );
3676 return Status
::newFatal( 'userexists' );
3678 $this->mId
= $dbw->insertId();
3680 // Clear instance cache other than user table data, which is already accurate
3681 $this->clearInstanceCache();
3683 $this->saveOptions();
3684 return Status
::newGood();
3688 * If this user is logged-in and blocked,
3689 * block any IP address they've successfully logged in from.
3690 * @return bool A block was spread
3692 public function spreadAnyEditBlock() {
3693 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3694 return $this->spreadBlock();
3700 * If this (non-anonymous) user is blocked,
3701 * block the IP address they've successfully logged in from.
3702 * @return bool A block was spread
3704 protected function spreadBlock() {
3705 wfDebug( __METHOD__
. "()\n" );
3707 if ( $this->mId
== 0 ) {
3711 $userblock = Block
::newFromTarget( $this->getName() );
3712 if ( !$userblock ) {
3716 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3720 * Get whether the user is explicitly blocked from account creation.
3721 * @return bool|Block
3723 public function isBlockedFromCreateAccount() {
3724 $this->getBlockedStatus();
3725 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3726 return $this->mBlock
;
3729 # bug 13611: if the IP address the user is trying to create an account from is
3730 # blocked with createaccount disabled, prevent new account creation there even
3731 # when the user is logged in
3732 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3733 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3735 return $this->mBlockedFromCreateAccount
instanceof Block
3736 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3737 ?
$this->mBlockedFromCreateAccount
3742 * Get whether the user is blocked from using Special:Emailuser.
3745 public function isBlockedFromEmailuser() {
3746 $this->getBlockedStatus();
3747 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3751 * Get whether the user is allowed to create an account.
3754 public function isAllowedToCreateAccount() {
3755 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3759 * Get this user's personal page title.
3761 * @return Title User's personal page title
3763 public function getUserPage() {
3764 return Title
::makeTitle( NS_USER
, $this->getName() );
3768 * Get this user's talk page title.
3770 * @return Title User's talk page title
3772 public function getTalkPage() {
3773 $title = $this->getUserPage();
3774 return $title->getTalkPage();
3778 * Determine whether the user is a newbie. Newbies are either
3779 * anonymous IPs, or the most recently created accounts.
3782 public function isNewbie() {
3783 return !$this->isAllowed( 'autoconfirmed' );
3787 * Check to see if the given clear-text password is one of the accepted passwords
3788 * @param string $password User password
3789 * @return bool True if the given password is correct, otherwise False
3791 public function checkPassword( $password ) {
3792 global $wgAuth, $wgLegacyEncoding;
3793 $this->loadPasswords();
3795 // Certain authentication plugins do NOT want to save
3796 // domain passwords in a mysql database, so we should
3797 // check this (in case $wgAuth->strict() is false).
3799 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3801 } elseif ( $wgAuth->strict() ) {
3802 // Auth plugin doesn't allow local authentication
3804 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3805 // Auth plugin doesn't allow local authentication for this user name
3809 $passwordFactory = self
::getPasswordFactory();
3810 if ( !$this->mPassword
->equals( $password ) ) {
3811 if ( $wgLegacyEncoding ) {
3812 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3813 // Check for this with iconv
3814 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3815 if ( $cp1252Password === $password ||
!$this->mPassword
->equals( $cp1252Password ) ) {
3823 if ( $passwordFactory->needsUpdate( $this->mPassword
) ) {
3824 $this->mPassword
= $passwordFactory->newFromPlaintext( $password );
3825 $this->saveSettings();
3832 * Check if the given clear-text password matches the temporary password
3833 * sent by e-mail for password reset operations.
3835 * @param string $plaintext
3837 * @return bool True if matches, false otherwise
3839 public function checkTemporaryPassword( $plaintext ) {
3840 global $wgNewPasswordExpiry;
3843 $this->loadPasswords();
3844 if ( $this->mNewpassword
->equals( $plaintext ) ) {
3845 if ( is_null( $this->mNewpassTime
) ) {
3848 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3849 return ( time() < $expiry );
3856 * Alias for getEditToken.
3857 * @deprecated since 1.19, use getEditToken instead.
3859 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3860 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3861 * @return string The new edit token
3863 public function editToken( $salt = '', $request = null ) {
3864 wfDeprecated( __METHOD__
, '1.19' );
3865 return $this->getEditToken( $salt, $request );
3869 * Initialize (if necessary) and return a session token value
3870 * which can be used in edit forms to show that the user's
3871 * login credentials aren't being hijacked with a foreign form
3876 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3877 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3878 * @return string The new edit token
3880 public function getEditToken( $salt = '', $request = null ) {
3881 if ( $request == null ) {
3882 $request = $this->getRequest();
3885 if ( $this->isAnon() ) {
3886 return self
::EDIT_TOKEN_SUFFIX
;
3888 $token = $request->getSessionData( 'wsEditToken' );
3889 if ( $token === null ) {
3890 $token = MWCryptRand
::generateHex( 32 );
3891 $request->setSessionData( 'wsEditToken', $token );
3893 if ( is_array( $salt ) ) {
3894 $salt = implode( '|', $salt );
3896 return md5( $token . $salt ) . self
::EDIT_TOKEN_SUFFIX
;
3901 * Generate a looking random token for various uses.
3903 * @return string The new random token
3904 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
3905 * wfRandomString for pseudo-randomness.
3907 public static function generateToken() {
3908 return MWCryptRand
::generateHex( 32 );
3912 * Check given value against the token value stored in the session.
3913 * A match should confirm that the form was submitted from the
3914 * user's own login session, not a form submission from a third-party
3917 * @param string $val Input value to compare
3918 * @param string $salt Optional function-specific data for hashing
3919 * @param WebRequest|null $request Object to use or null to use $wgRequest
3920 * @return bool Whether the token matches
3922 public function matchEditToken( $val, $salt = '', $request = null ) {
3923 $sessionToken = $this->getEditToken( $salt, $request );
3924 if ( $val != $sessionToken ) {
3925 wfDebug( "User::matchEditToken: broken session data\n" );
3928 return $val == $sessionToken;
3932 * Check given value against the token value stored in the session,
3933 * ignoring the suffix.
3935 * @param string $val Input value to compare
3936 * @param string $salt Optional function-specific data for hashing
3937 * @param WebRequest|null $request Object to use or null to use $wgRequest
3938 * @return bool Whether the token matches
3940 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3941 $sessionToken = $this->getEditToken( $salt, $request );
3942 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3946 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3947 * mail to the user's given address.
3949 * @param string $type Message to send, either "created", "changed" or "set"
3952 public function sendConfirmationMail( $type = 'created' ) {
3954 $expiration = null; // gets passed-by-ref and defined in next line.
3955 $token = $this->confirmationToken( $expiration );
3956 $url = $this->confirmationTokenUrl( $token );
3957 $invalidateURL = $this->invalidationTokenUrl( $token );
3958 $this->saveSettings();
3960 if ( $type == 'created' ||
$type === false ) {
3961 $message = 'confirmemail_body';
3962 } elseif ( $type === true ) {
3963 $message = 'confirmemail_body_changed';
3965 // Messages: confirmemail_body_changed, confirmemail_body_set
3966 $message = 'confirmemail_body_' . $type;
3969 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3970 wfMessage( $message,
3971 $this->getRequest()->getIP(),
3974 $wgLang->timeanddate( $expiration, false ),
3976 $wgLang->date( $expiration, false ),
3977 $wgLang->time( $expiration, false ) )->text() );
3981 * Send an e-mail to this user's account. Does not check for
3982 * confirmed status or validity.
3984 * @param string $subject Message subject
3985 * @param string $body Message body
3986 * @param string $from Optional From address; if unspecified, default
3987 * $wgPasswordSender will be used.
3988 * @param string $replyto Reply-To address
3991 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3992 if ( is_null( $from ) ) {
3993 global $wgPasswordSender;
3994 $sender = new MailAddress( $wgPasswordSender,
3995 wfMessage( 'emailsender' )->inContentLanguage()->text() );
3997 $sender = new MailAddress( $from );
4000 $to = new MailAddress( $this );
4001 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
4005 * Generate, store, and return a new e-mail confirmation code.
4006 * A hash (unsalted, since it's used as a key) is stored.
4008 * @note Call saveSettings() after calling this function to commit
4009 * this change to the database.
4011 * @param string &$expiration Accepts the expiration time
4012 * @return string New token
4014 protected function confirmationToken( &$expiration ) {
4015 global $wgUserEmailConfirmationTokenExpiry;
4017 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4018 $expiration = wfTimestamp( TS_MW
, $expires );
4020 $token = MWCryptRand
::generateHex( 32 );
4021 $hash = md5( $token );
4022 $this->mEmailToken
= $hash;
4023 $this->mEmailTokenExpires
= $expiration;
4028 * Return a URL the user can use to confirm their email address.
4029 * @param string $token Accepts the email confirmation token
4030 * @return string New token URL
4032 protected function confirmationTokenUrl( $token ) {
4033 return $this->getTokenUrl( 'ConfirmEmail', $token );
4037 * Return a URL the user can use to invalidate their email address.
4038 * @param string $token Accepts the email confirmation token
4039 * @return string New token URL
4041 protected function invalidationTokenUrl( $token ) {
4042 return $this->getTokenUrl( 'InvalidateEmail', $token );
4046 * Internal function to format the e-mail validation/invalidation URLs.
4047 * This uses a quickie hack to use the
4048 * hardcoded English names of the Special: pages, for ASCII safety.
4050 * @note Since these URLs get dropped directly into emails, using the
4051 * short English names avoids insanely long URL-encoded links, which
4052 * also sometimes can get corrupted in some browsers/mailers
4053 * (bug 6957 with Gmail and Internet Explorer).
4055 * @param string $page Special page
4056 * @param string $token Token
4057 * @return string Formatted URL
4059 protected function getTokenUrl( $page, $token ) {
4060 // Hack to bypass localization of 'Special:'
4061 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4062 return $title->getCanonicalURL();
4066 * Mark the e-mail address confirmed.
4068 * @note Call saveSettings() after calling this function to commit the change.
4072 public function confirmEmail() {
4073 // Check if it's already confirmed, so we don't touch the database
4074 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4075 if ( !$this->isEmailConfirmed() ) {
4076 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4077 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
4083 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4084 * address if it was already confirmed.
4086 * @note Call saveSettings() after calling this function to commit the change.
4087 * @return bool Returns true
4089 public function invalidateEmail() {
4091 $this->mEmailToken
= null;
4092 $this->mEmailTokenExpires
= null;
4093 $this->setEmailAuthenticationTimestamp( null );
4095 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
4100 * Set the e-mail authentication timestamp.
4101 * @param string $timestamp TS_MW timestamp
4103 public function setEmailAuthenticationTimestamp( $timestamp ) {
4105 $this->mEmailAuthenticated
= $timestamp;
4106 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4110 * Is this user allowed to send e-mails within limits of current
4111 * site configuration?
4114 public function canSendEmail() {
4115 global $wgEnableEmail, $wgEnableUserEmail;
4116 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4119 $canSend = $this->isEmailConfirmed();
4120 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4125 * Is this user allowed to receive e-mails within limits of current
4126 * site configuration?
4129 public function canReceiveEmail() {
4130 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4134 * Is this user's e-mail address valid-looking and confirmed within
4135 * limits of the current site configuration?
4137 * @note If $wgEmailAuthentication is on, this may require the user to have
4138 * confirmed their address by returning a code or using a password
4139 * sent to the address from the wiki.
4143 public function isEmailConfirmed() {
4144 global $wgEmailAuthentication;
4147 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4148 if ( $this->isAnon() ) {
4151 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4154 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4164 * Check whether there is an outstanding request for e-mail confirmation.
4167 public function isEmailConfirmationPending() {
4168 global $wgEmailAuthentication;
4169 return $wgEmailAuthentication &&
4170 !$this->isEmailConfirmed() &&
4171 $this->mEmailToken
&&
4172 $this->mEmailTokenExpires
> wfTimestamp();
4176 * Get the timestamp of account creation.
4178 * @return string|bool|null Timestamp of account creation, false for
4179 * non-existent/anonymous user accounts, or null if existing account
4180 * but information is not in database.
4182 public function getRegistration() {
4183 if ( $this->isAnon() ) {
4187 return $this->mRegistration
;
4191 * Get the timestamp of the first edit
4193 * @return string|bool Timestamp of first edit, or false for
4194 * non-existent/anonymous user accounts.
4196 public function getFirstEditTimestamp() {
4197 if ( $this->getId() == 0 ) {
4198 return false; // anons
4200 $dbr = wfGetDB( DB_SLAVE
);
4201 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4202 array( 'rev_user' => $this->getId() ),
4204 array( 'ORDER BY' => 'rev_timestamp ASC' )
4207 return false; // no edits
4209 return wfTimestamp( TS_MW
, $time );
4213 * Get the permissions associated with a given list of groups
4215 * @param array $groups Array of Strings List of internal group names
4216 * @return array Array of Strings List of permission key names for given groups combined
4218 public static function getGroupPermissions( $groups ) {
4219 global $wgGroupPermissions, $wgRevokePermissions;
4221 // grant every granted permission first
4222 foreach ( $groups as $group ) {
4223 if ( isset( $wgGroupPermissions[$group] ) ) {
4224 $rights = array_merge( $rights,
4225 // array_filter removes empty items
4226 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4229 // now revoke the revoked permissions
4230 foreach ( $groups as $group ) {
4231 if ( isset( $wgRevokePermissions[$group] ) ) {
4232 $rights = array_diff( $rights,
4233 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4236 return array_unique( $rights );
4240 * Get all the groups who have a given permission
4242 * @param string $role Role to check
4243 * @return array Array of Strings List of internal group names with the given permission
4245 public static function getGroupsWithPermission( $role ) {
4246 global $wgGroupPermissions;
4247 $allowedGroups = array();
4248 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4249 if ( self
::groupHasPermission( $group, $role ) ) {
4250 $allowedGroups[] = $group;
4253 return $allowedGroups;
4257 * Check, if the given group has the given permission
4259 * If you're wanting to check whether all users have a permission, use
4260 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4264 * @param string $group Group to check
4265 * @param string $role Role to check
4268 public static function groupHasPermission( $group, $role ) {
4269 global $wgGroupPermissions, $wgRevokePermissions;
4270 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4271 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4275 * Check if all users have the given permission
4278 * @param string $right Right to check
4281 public static function isEveryoneAllowed( $right ) {
4282 global $wgGroupPermissions, $wgRevokePermissions;
4283 static $cache = array();
4285 // Use the cached results, except in unit tests which rely on
4286 // being able change the permission mid-request
4287 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4288 return $cache[$right];
4291 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4292 $cache[$right] = false;
4296 // If it's revoked anywhere, then everyone doesn't have it
4297 foreach ( $wgRevokePermissions as $rights ) {
4298 if ( isset( $rights[$right] ) && $rights[$right] ) {
4299 $cache[$right] = false;
4304 // Allow extensions (e.g. OAuth) to say false
4305 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4306 $cache[$right] = false;
4310 $cache[$right] = true;
4315 * Get the localized descriptive name for a group, if it exists
4317 * @param string $group Internal group name
4318 * @return string Localized descriptive group name
4320 public static function getGroupName( $group ) {
4321 $msg = wfMessage( "group-$group" );
4322 return $msg->isBlank() ?
$group : $msg->text();
4326 * Get the localized descriptive name for a member of a group, if it exists
4328 * @param string $group Internal group name
4329 * @param string $username Username for gender (since 1.19)
4330 * @return string Localized name for group member
4332 public static function getGroupMember( $group, $username = '#' ) {
4333 $msg = wfMessage( "group-$group-member", $username );
4334 return $msg->isBlank() ?
$group : $msg->text();
4338 * Return the set of defined explicit groups.
4339 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4340 * are not included, as they are defined automatically, not in the database.
4341 * @return array Array of internal group names
4343 public static function getAllGroups() {
4344 global $wgGroupPermissions, $wgRevokePermissions;
4346 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4347 self
::getImplicitGroups()
4352 * Get a list of all available permissions.
4353 * @return array Array of permission names
4355 public static function getAllRights() {
4356 if ( self
::$mAllRights === false ) {
4357 global $wgAvailableRights;
4358 if ( count( $wgAvailableRights ) ) {
4359 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4361 self
::$mAllRights = self
::$mCoreRights;
4363 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
4365 return self
::$mAllRights;
4369 * Get a list of implicit groups
4370 * @return array Array of Strings Array of internal group names
4372 public static function getImplicitGroups() {
4373 global $wgImplicitGroups;
4375 $groups = $wgImplicitGroups;
4376 # Deprecated, use $wgImplictGroups instead
4377 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) );
4383 * Get the title of a page describing a particular group
4385 * @param string $group Internal group name
4386 * @return Title|bool Title of the page if it exists, false otherwise
4388 public static function getGroupPage( $group ) {
4389 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4390 if ( $msg->exists() ) {
4391 $title = Title
::newFromText( $msg->text() );
4392 if ( is_object( $title ) ) {
4400 * Create a link to the group in HTML, if available;
4401 * else return the group name.
4403 * @param string $group Internal name of the group
4404 * @param string $text The text of the link
4405 * @return string HTML link to the group
4407 public static function makeGroupLinkHTML( $group, $text = '' ) {
4408 if ( $text == '' ) {
4409 $text = self
::getGroupName( $group );
4411 $title = self
::getGroupPage( $group );
4413 return Linker
::link( $title, htmlspecialchars( $text ) );
4420 * Create a link to the group in Wikitext, if available;
4421 * else return the group name.
4423 * @param string $group Internal name of the group
4424 * @param string $text The text of the link
4425 * @return string Wikilink to the group
4427 public static function makeGroupLinkWiki( $group, $text = '' ) {
4428 if ( $text == '' ) {
4429 $text = self
::getGroupName( $group );
4431 $title = self
::getGroupPage( $group );
4433 $page = $title->getPrefixedText();
4434 return "[[$page|$text]]";
4441 * Returns an array of the groups that a particular group can add/remove.
4443 * @param string $group The group to check for whether it can add/remove
4444 * @return array Array( 'add' => array( addablegroups ),
4445 * 'remove' => array( removablegroups ),
4446 * 'add-self' => array( addablegroups to self),
4447 * 'remove-self' => array( removable groups from self) )
4449 public static function changeableByGroup( $group ) {
4450 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4454 'remove' => array(),
4455 'add-self' => array(),
4456 'remove-self' => array()
4459 if ( empty( $wgAddGroups[$group] ) ) {
4460 // Don't add anything to $groups
4461 } elseif ( $wgAddGroups[$group] === true ) {
4462 // You get everything
4463 $groups['add'] = self
::getAllGroups();
4464 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4465 $groups['add'] = $wgAddGroups[$group];
4468 // Same thing for remove
4469 if ( empty( $wgRemoveGroups[$group] ) ) {
4470 } elseif ( $wgRemoveGroups[$group] === true ) {
4471 $groups['remove'] = self
::getAllGroups();
4472 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4473 $groups['remove'] = $wgRemoveGroups[$group];
4476 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4477 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4478 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4479 if ( is_int( $key ) ) {
4480 $wgGroupsAddToSelf['user'][] = $value;
4485 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4486 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4487 if ( is_int( $key ) ) {
4488 $wgGroupsRemoveFromSelf['user'][] = $value;
4493 // Now figure out what groups the user can add to him/herself
4494 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4495 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4496 // No idea WHY this would be used, but it's there
4497 $groups['add-self'] = User
::getAllGroups();
4498 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4499 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4502 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4503 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4504 $groups['remove-self'] = User
::getAllGroups();
4505 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4506 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4513 * Returns an array of groups that this user can add and remove
4514 * @return array Array( 'add' => array( addablegroups ),
4515 * 'remove' => array( removablegroups ),
4516 * 'add-self' => array( addablegroups to self),
4517 * 'remove-self' => array( removable groups from self) )
4519 public function changeableGroups() {
4520 if ( $this->isAllowed( 'userrights' ) ) {
4521 // This group gives the right to modify everything (reverse-
4522 // compatibility with old "userrights lets you change
4524 // Using array_merge to make the groups reindexed
4525 $all = array_merge( User
::getAllGroups() );
4529 'add-self' => array(),
4530 'remove-self' => array()
4534 // Okay, it's not so simple, we will have to go through the arrays
4537 'remove' => array(),
4538 'add-self' => array(),
4539 'remove-self' => array()
4541 $addergroups = $this->getEffectiveGroups();
4543 foreach ( $addergroups as $addergroup ) {
4544 $groups = array_merge_recursive(
4545 $groups, $this->changeableByGroup( $addergroup )
4547 $groups['add'] = array_unique( $groups['add'] );
4548 $groups['remove'] = array_unique( $groups['remove'] );
4549 $groups['add-self'] = array_unique( $groups['add-self'] );
4550 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4556 * Increment the user's edit-count field.
4557 * Will have no effect for anonymous users.
4559 public function incEditCount() {
4560 if ( !$this->isAnon() ) {
4561 $dbw = wfGetDB( DB_MASTER
);
4564 array( 'user_editcount=user_editcount+1' ),
4565 array( 'user_id' => $this->getId() ),
4569 // Lazy initialization check...
4570 if ( $dbw->affectedRows() == 0 ) {
4571 // Now here's a goddamn hack...
4572 $dbr = wfGetDB( DB_SLAVE
);
4573 if ( $dbr !== $dbw ) {
4574 // If we actually have a slave server, the count is
4575 // at least one behind because the current transaction
4576 // has not been committed and replicated.
4577 $this->initEditCount( 1 );
4579 // But if DB_SLAVE is selecting the master, then the
4580 // count we just read includes the revision that was
4581 // just added in the working transaction.
4582 $this->initEditCount();
4586 // edit count in user cache too
4587 $this->invalidateCache();
4591 * Initialize user_editcount from data out of the revision table
4593 * @param int $add Edits to add to the count from the revision table
4594 * @return int Number of edits
4596 protected function initEditCount( $add = 0 ) {
4597 // Pull from a slave to be less cruel to servers
4598 // Accuracy isn't the point anyway here
4599 $dbr = wfGetDB( DB_SLAVE
);
4600 $count = (int)$dbr->selectField(
4603 array( 'rev_user' => $this->getId() ),
4606 $count = $count +
$add;
4608 $dbw = wfGetDB( DB_MASTER
);
4611 array( 'user_editcount' => $count ),
4612 array( 'user_id' => $this->getId() ),
4620 * Get the description of a given right
4622 * @param string $right Right to query
4623 * @return string Localized description of the right
4625 public static function getRightDescription( $right ) {
4626 $key = "right-$right";
4627 $msg = wfMessage( $key );
4628 return $msg->isBlank() ?
$right : $msg->text();
4632 * Make a new-style password hash
4634 * @param string $password Plain-text password
4635 * @param bool|string $salt Optional salt, may be random or the user ID.
4636 * If unspecified or false, will generate one automatically
4637 * @return string Password hash
4638 * @deprecated since 1.24, use Password class
4640 public static function crypt( $password, $salt = false ) {
4641 wfDeprecated( __METHOD__
, '1.24' );
4642 $hash = self
::getPasswordFactory()->newFromPlaintext( $password );
4643 return $hash->toString();
4647 * Compare a password hash with a plain-text password. Requires the user
4648 * ID if there's a chance that the hash is an old-style hash.
4650 * @param string $hash Password hash
4651 * @param string $password Plain-text password to compare
4652 * @param string|bool $userId User ID for old-style password salt
4655 * @deprecated since 1.24, use Password class
4657 public static function comparePasswords( $hash, $password, $userId = false ) {
4658 wfDeprecated( __METHOD__
, '1.24' );
4660 // Check for *really* old password hashes that don't even have a type
4661 // The old hash format was just an md5 hex hash, with no type information
4662 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4663 global $wgPasswordSalt;
4664 if ( $wgPasswordSalt ) {
4665 $password = ":B:{$userId}:{$hash}";
4667 $password = ":A:{$hash}";
4671 $hash = self
::getPasswordFactory()->newFromCiphertext( $hash );
4672 return $hash->equals( $password );
4676 * Add a newuser log entry for this user.
4677 * Before 1.19 the return value was always true.
4679 * @param string|bool $action Account creation type.
4680 * - String, one of the following values:
4681 * - 'create' for an anonymous user creating an account for himself.
4682 * This will force the action's performer to be the created user itself,
4683 * no matter the value of $wgUser
4684 * - 'create2' for a logged in user creating an account for someone else
4685 * - 'byemail' when the created user will receive its password by e-mail
4686 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4687 * - Boolean means whether the account was created by e-mail (deprecated):
4688 * - true will be converted to 'byemail'
4689 * - false will be converted to 'create' if this object is the same as
4690 * $wgUser and to 'create2' otherwise
4692 * @param string $reason User supplied reason
4694 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4696 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4697 global $wgUser, $wgNewUserLog;
4698 if ( empty( $wgNewUserLog ) ) {
4699 return true; // disabled
4702 if ( $action === true ) {
4703 $action = 'byemail';
4704 } elseif ( $action === false ) {
4705 if ( $this->getName() == $wgUser->getName() ) {
4708 $action = 'create2';
4712 if ( $action === 'create' ||
$action === 'autocreate' ) {
4715 $performer = $wgUser;
4718 $logEntry = new ManualLogEntry( 'newusers', $action );
4719 $logEntry->setPerformer( $performer );
4720 $logEntry->setTarget( $this->getUserPage() );
4721 $logEntry->setComment( $reason );
4722 $logEntry->setParameters( array(
4723 '4::userid' => $this->getId(),
4725 $logid = $logEntry->insert();
4727 if ( $action !== 'autocreate' ) {
4728 $logEntry->publish( $logid );
4735 * Add an autocreate newuser log entry for this user
4736 * Used by things like CentralAuth and perhaps other authplugins.
4737 * Consider calling addNewUserLogEntry() directly instead.
4741 public function addNewUserLogEntryAutoCreate() {
4742 $this->addNewUserLogEntry( 'autocreate' );
4748 * Load the user options either from cache, the database or an array
4750 * @param array $data Rows for the current user out of the user_properties table
4752 protected function loadOptions( $data = null ) {
4757 if ( $this->mOptionsLoaded
) {
4761 $this->mOptions
= self
::getDefaultOptions();
4763 if ( !$this->getId() ) {
4764 // For unlogged-in users, load language/variant options from request.
4765 // There's no need to do it for logged-in users: they can set preferences,
4766 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4767 // so don't override user's choice (especially when the user chooses site default).
4768 $variant = $wgContLang->getDefaultVariant();
4769 $this->mOptions
['variant'] = $variant;
4770 $this->mOptions
['language'] = $variant;
4771 $this->mOptionsLoaded
= true;
4775 // Maybe load from the object
4776 if ( !is_null( $this->mOptionOverrides
) ) {
4777 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4778 foreach ( $this->mOptionOverrides
as $key => $value ) {
4779 $this->mOptions
[$key] = $value;
4782 if ( !is_array( $data ) ) {
4783 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4784 // Load from database
4785 $dbr = wfGetDB( DB_SLAVE
);
4787 $res = $dbr->select(
4789 array( 'up_property', 'up_value' ),
4790 array( 'up_user' => $this->getId() ),
4794 $this->mOptionOverrides
= array();
4796 foreach ( $res as $row ) {
4797 $data[$row->up_property
] = $row->up_value
;
4800 foreach ( $data as $property => $value ) {
4801 $this->mOptionOverrides
[$property] = $value;
4802 $this->mOptions
[$property] = $value;
4806 $this->mOptionsLoaded
= true;
4808 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
4812 * Saves the non-default options for this user, as previously set e.g. via
4813 * setOption(), in the database's "user_properties" (preferences) table.
4814 * Usually used via saveSettings().
4816 protected function saveOptions() {
4817 $this->loadOptions();
4819 // Not using getOptions(), to keep hidden preferences in database
4820 $saveOptions = $this->mOptions
;
4822 // Allow hooks to abort, for instance to save to a global profile.
4823 // Reset options to default state before saving.
4824 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4828 $userId = $this->getId();
4830 $insert_rows = array(); // all the new preference rows
4831 foreach ( $saveOptions as $key => $value ) {
4832 // Don't bother storing default values
4833 $defaultOption = self
::getDefaultOption( $key );
4834 if ( ( $defaultOption === null && $value !== false && $value !== null )
4835 ||
$value != $defaultOption
4837 $insert_rows[] = array(
4838 'up_user' => $userId,
4839 'up_property' => $key,
4840 'up_value' => $value,
4845 $dbw = wfGetDB( DB_MASTER
);
4847 $res = $dbw->select( 'user_properties',
4848 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
4850 // Find prior rows that need to be removed or updated. These rows will
4851 // all be deleted (the later so that INSERT IGNORE applies the new values).
4852 $keysDelete = array();
4853 foreach ( $res as $row ) {
4854 if ( !isset( $saveOptions[$row->up_property
] )
4855 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
4857 $keysDelete[] = $row->up_property
;
4861 if ( count( $keysDelete ) ) {
4862 // Do the DELETE by PRIMARY KEY for prior rows.
4863 // In the past a very large portion of calls to this function are for setting
4864 // 'rememberpassword' for new accounts (a preference that has since been removed).
4865 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4866 // caused gap locks on [max user ID,+infinity) which caused high contention since
4867 // updates would pile up on each other as they are for higher (newer) user IDs.
4868 // It might not be necessary these days, but it shouldn't hurt either.
4869 $dbw->delete( 'user_properties',
4870 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
4872 // Insert the new preference rows
4873 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
4877 * Lazily instantiate and return a factory object for making passwords
4879 * @return PasswordFactory
4881 public static function getPasswordFactory() {
4882 if ( self
::$mPasswordFactory === null ) {
4883 self
::$mPasswordFactory = new PasswordFactory();
4884 self
::$mPasswordFactory->init( RequestContext
::getMain()->getConfig() );
4887 return self
::$mPasswordFactory;
4891 * Provide an array of HTML5 attributes to put on an input element
4892 * intended for the user to enter a new password. This may include
4893 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4895 * Do *not* use this when asking the user to enter his current password!
4896 * Regardless of configuration, users may have invalid passwords for whatever
4897 * reason (e.g., they were set before requirements were tightened up).
4898 * Only use it when asking for a new password, like on account creation or
4901 * Obviously, you still need to do server-side checking.
4903 * NOTE: A combination of bugs in various browsers means that this function
4904 * actually just returns array() unconditionally at the moment. May as
4905 * well keep it around for when the browser bugs get fixed, though.
4907 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4909 * @return array Array of HTML attributes suitable for feeding to
4910 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4911 * That will get confused by the boolean attribute syntax used.)
4913 public static function passwordChangeInputAttribs() {
4914 global $wgMinimalPasswordLength;
4916 if ( $wgMinimalPasswordLength == 0 ) {
4920 # Note that the pattern requirement will always be satisfied if the
4921 # input is empty, so we need required in all cases.
4923 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4924 # if e-mail confirmation is being used. Since HTML5 input validation
4925 # is b0rked anyway in some browsers, just return nothing. When it's
4926 # re-enabled, fix this code to not output required for e-mail
4928 #$ret = array( 'required' );
4931 # We can't actually do this right now, because Opera 9.6 will print out
4932 # the entered password visibly in its error message! When other
4933 # browsers add support for this attribute, or Opera fixes its support,
4934 # we can add support with a version check to avoid doing this on Opera
4935 # versions where it will be a problem. Reported to Opera as
4936 # DSK-262266, but they don't have a public bug tracker for us to follow.
4938 if ( $wgMinimalPasswordLength > 1 ) {
4939 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4940 $ret['title'] = wfMessage( 'passwordtooshort' )
4941 ->numParams( $wgMinimalPasswordLength )->text();
4949 * Return the list of user fields that should be selected to create
4950 * a new user object.
4953 public static function selectFields() {
4961 'user_email_authenticated',
4963 'user_email_token_expires',
4964 'user_registration',
4970 * Factory function for fatal permission-denied errors
4973 * @param string $permission User right required
4976 static function newFatalPermissionDeniedStatus( $permission ) {
4979 $groups = array_map(
4980 array( 'User', 'makeGroupLinkWiki' ),
4981 User
::getGroupsWithPermission( $permission )
4985 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4987 return Status
::newFatal( 'badaccess-group0' );