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 * Exclude user options that are set to their default value.
65 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
68 * @var PasswordFactory Lazily loaded factory object for passwords
70 private static $mPasswordFactory = null;
73 * Array of Strings List of member variables which are saved to the
74 * shared cache (memcached). Any operation which changes the
75 * corresponding database fields must call a cache-clearing function.
78 protected static $mCacheVars = array(
86 'mEmailAuthenticated',
93 // user_properties table
98 * Array of Strings Core rights.
99 * Each of these should have a corresponding message of the form
103 protected static $mCoreRights = array(
130 'editusercssjs', #deprecated
143 'move-categorypages',
144 'move-rootuserpages',
148 'override-export-depth',
172 'userrights-interwiki',
180 * String Cached results of getAllRights()
182 protected static $mAllRights = false;
184 /** @name Cache variables */
193 * @todo Make this actually private
199 * @todo Make this actually private
202 public $mNewpassword;
204 public $mNewpassTime;
212 public $mEmailAuthenticated;
214 protected $mEmailToken;
216 protected $mEmailTokenExpires;
218 protected $mRegistration;
220 protected $mEditCount;
224 protected $mOptionOverrides;
226 protected $mPasswordExpires;
230 * Bool Whether the cache variables have been loaded.
233 public $mOptionsLoaded;
236 * Array with already loaded items or true if all items have been loaded.
238 protected $mLoadedItems = array();
242 * String Initialization data source if mLoadedItems!==true. May be one of:
243 * - 'defaults' anonymous user initialised from class defaults
244 * - 'name' initialise from mName
245 * - 'id' initialise from mId
246 * - 'session' log in from cookies or session if possible
248 * Use the User::newFrom*() family of functions to set this.
253 * Lazy-initialized variables, invalidated with clearInstanceCache
257 protected $mDatePreference;
265 protected $mBlockreason;
267 protected $mEffectiveGroups;
269 protected $mImplicitGroups;
271 protected $mFormerGroups;
273 protected $mBlockedGlobally;
290 protected $mAllowUsertalk;
293 private $mBlockedFromCreateAccount = false;
296 private $mWatchedItems = array();
298 public static $idCacheByName = array();
301 * Lightweight constructor for an anonymous user.
302 * Use the User::newFrom* factory functions for other kinds of users.
306 * @see newFromConfirmationCode()
307 * @see newFromSession()
310 public function __construct() {
311 $this->clearInstanceCache( 'defaults' );
317 public function __toString() {
318 return $this->getName();
322 * Load the user table data for this object from the source given by mFrom.
324 * @param integer $flags User::READ_* constant bitfield
326 public function load( $flags = self
::READ_LATEST
) {
327 if ( $this->mLoadedItems
=== true ) {
331 // Set it now to avoid infinite recursion in accessors
332 $this->mLoadedItems
= true;
334 switch ( $this->mFrom
) {
336 $this->loadDefaults();
339 // @TODO: this gets the ID from a slave, assuming renames
340 // are rare. This should be controllable and more consistent.
341 $this->mId
= self
::idFromName( $this->mName
);
343 // Nonexistent user placeholder object
344 $this->loadDefaults( $this->mName
);
346 $this->loadFromId( $flags );
350 $this->loadFromId( $flags );
353 if ( !$this->loadFromSession() ) {
354 // Loading from session failed. Load defaults.
355 $this->loadDefaults();
357 Hooks
::run( 'UserLoadAfterLoadFromSession', array( $this ) );
360 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
365 * Load user table data, given mId has already been set.
366 * @param integer $flags User::READ_* constant bitfield
367 * @return bool False if the ID does not exist, true otherwise
369 public function loadFromId( $flags = self
::READ_LATEST
) {
370 if ( $this->mId
== 0 ) {
371 $this->loadDefaults();
376 $cache = $this->loadFromCache();
378 wfDebug( "User: cache miss for user {$this->mId}\n" );
380 if ( !$this->loadFromDatabase( $flags ) ) {
381 // Can't load from ID, user is anonymous
384 if ( $flags & self
::READ_LATEST
) {
385 // Only save master data back to the cache to keep it consistent.
386 // @TODO: save it anyway and have callers specifiy $flags and have
387 // load() called as needed. That requires updating MANY callers...
388 $this->saveToCache();
392 $this->mLoadedItems
= true;
398 * Load user data from shared cache, given mId has already been set.
400 * @return bool false if the ID does not exist or data is invalid, true otherwise
403 public function loadFromCache() {
406 if ( $this->mId
== 0 ) {
407 $this->loadDefaults();
411 $key = wfMemcKey( 'user', 'id', $this->mId
);
412 $data = $wgMemc->get( $key );
413 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
418 wfDebug( "User: got user {$this->mId} from cache\n" );
420 // Restore from cache
421 foreach ( self
::$mCacheVars as $name ) {
422 $this->$name = $data[$name];
429 * Save user data to the shared cache
431 public function saveToCache() {
434 $this->loadOptions();
435 if ( $this->isAnon() ) {
436 // Anonymous users are uncached
440 foreach ( self
::$mCacheVars as $name ) {
441 $data[$name] = $this->$name;
443 $data['mVersion'] = self
::VERSION
;
444 $key = wfMemcKey( 'user', 'id', $this->mId
);
446 $wgMemc->set( $key, $data );
449 /** @name newFrom*() static factory methods */
453 * Static factory method for creation from username.
455 * This is slightly less efficient than newFromId(), so use newFromId() if
456 * you have both an ID and a name handy.
458 * @param string $name Username, validated by Title::newFromText()
459 * @param string|bool $validate Validate username. Takes the same parameters as
460 * User::getCanonicalName(), except that true is accepted as an alias
461 * for 'valid', for BC.
463 * @return User|bool User object, or false if the username is invalid
464 * (e.g. if it contains illegal characters or is an IP address). If the
465 * username is not present in the database, the result will be a user object
466 * with a name, zero user ID and default settings.
468 public static function newFromName( $name, $validate = 'valid' ) {
469 if ( $validate === true ) {
472 $name = self
::getCanonicalName( $name, $validate );
473 if ( $name === false ) {
476 // Create unloaded user object
480 $u->setItemLoaded( 'name' );
486 * Static factory method for creation from a given user ID.
488 * @param int $id Valid user ID
489 * @return User The corresponding User object
491 public static function newFromId( $id ) {
495 $u->setItemLoaded( 'id' );
500 * Factory method to fetch whichever user has a given email confirmation code.
501 * This code is generated when an account is created or its e-mail address
504 * If the code is invalid or has expired, returns NULL.
506 * @param string $code Confirmation code
509 public static function newFromConfirmationCode( $code ) {
510 $dbr = wfGetDB( DB_SLAVE
);
511 $id = $dbr->selectField( 'user', 'user_id', array(
512 'user_email_token' => md5( $code ),
513 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
515 if ( $id !== false ) {
516 return User
::newFromId( $id );
523 * Create a new user object using data from session or cookies. If the
524 * login credentials are invalid, the result is an anonymous user.
526 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
529 public static function newFromSession( WebRequest
$request = null ) {
531 $user->mFrom
= 'session';
532 $user->mRequest
= $request;
537 * Create a new user object from a user row.
538 * The row should have the following fields from the user table in it:
539 * - either user_name or user_id to load further data if needed (or both)
541 * - all other fields (email, password, etc.)
542 * It is useless to provide the remaining fields if either user_id,
543 * user_name and user_real_name are not provided because the whole row
544 * will be loaded once more from the database when accessing them.
546 * @param stdClass $row A row from the user table
547 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
550 public static function newFromRow( $row, $data = null ) {
552 $user->loadFromRow( $row, $data );
559 * Get the username corresponding to a given user ID
560 * @param int $id User ID
561 * @return string|bool The corresponding username
563 public static function whoIs( $id ) {
564 return UserCache
::singleton()->getProp( $id, 'name' );
568 * Get the real name of a user given their user ID
570 * @param int $id User ID
571 * @return string|bool The corresponding user's real name
573 public static function whoIsReal( $id ) {
574 return UserCache
::singleton()->getProp( $id, 'real_name' );
578 * Get database id given a user name
579 * @param string $name Username
580 * @return int|null The corresponding user's ID, or null if user is nonexistent
582 public static function idFromName( $name ) {
583 $nt = Title
::makeTitleSafe( NS_USER
, $name );
584 if ( is_null( $nt ) ) {
589 if ( isset( self
::$idCacheByName[$name] ) ) {
590 return self
::$idCacheByName[$name];
593 $dbr = wfGetDB( DB_SLAVE
);
594 $s = $dbr->selectRow(
597 array( 'user_name' => $nt->getText() ),
601 if ( $s === false ) {
604 $result = $s->user_id
;
607 self
::$idCacheByName[$name] = $result;
609 if ( count( self
::$idCacheByName ) > 1000 ) {
610 self
::$idCacheByName = array();
617 * Reset the cache used in idFromName(). For use in tests.
619 public static function resetIdByNameCache() {
620 self
::$idCacheByName = array();
624 * Does the string match an anonymous IPv4 address?
626 * This function exists for username validation, in order to reject
627 * usernames which are similar in form to IP addresses. Strings such
628 * as 300.300.300.300 will return true because it looks like an IP
629 * address, despite not being strictly valid.
631 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
632 * address because the usemod software would "cloak" anonymous IP
633 * addresses like this, if we allowed accounts like this to be created
634 * new users could get the old edits of these anonymous users.
636 * @param string $name Name to match
639 public static function isIP( $name ) {
640 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
641 || IP
::isIPv6( $name );
645 * Is the input a valid username?
647 * Checks if the input is a valid username, we don't want an empty string,
648 * an IP address, anything that contains slashes (would mess up subpages),
649 * is longer than the maximum allowed username size or doesn't begin with
652 * @param string $name Name to match
655 public static function isValidUserName( $name ) {
656 global $wgContLang, $wgMaxNameChars;
659 || User
::isIP( $name )
660 ||
strpos( $name, '/' ) !== false
661 ||
strlen( $name ) > $wgMaxNameChars
662 ||
$name != $wgContLang->ucfirst( $name )
664 wfDebugLog( 'username', __METHOD__
.
665 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
669 // Ensure that the name can't be misresolved as a different title,
670 // such as with extra namespace keys at the start.
671 $parsed = Title
::newFromText( $name );
672 if ( is_null( $parsed )
673 ||
$parsed->getNamespace()
674 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
675 wfDebugLog( 'username', __METHOD__
.
676 ": '$name' invalid due to ambiguous prefixes" );
680 // Check an additional blacklist of troublemaker characters.
681 // Should these be merged into the title char list?
682 $unicodeBlacklist = '/[' .
683 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
684 '\x{00a0}' . # non-breaking space
685 '\x{2000}-\x{200f}' . # various whitespace
686 '\x{2028}-\x{202f}' . # breaks and control chars
687 '\x{3000}' . # ideographic space
688 '\x{e000}-\x{f8ff}' . # private use
690 if ( preg_match( $unicodeBlacklist, $name ) ) {
691 wfDebugLog( 'username', __METHOD__
.
692 ": '$name' invalid due to blacklisted characters" );
700 * Usernames which fail to pass this function will be blocked
701 * from user login and new account registrations, but may be used
702 * internally by batch processes.
704 * If an account already exists in this form, login will be blocked
705 * by a failure to pass this function.
707 * @param string $name Name to match
710 public static function isUsableName( $name ) {
711 global $wgReservedUsernames;
712 // Must be a valid username, obviously ;)
713 if ( !self
::isValidUserName( $name ) ) {
717 static $reservedUsernames = false;
718 if ( !$reservedUsernames ) {
719 $reservedUsernames = $wgReservedUsernames;
720 Hooks
::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
723 // Certain names may be reserved for batch processes.
724 foreach ( $reservedUsernames as $reserved ) {
725 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
726 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
728 if ( $reserved == $name ) {
736 * Usernames which fail to pass this function will be blocked
737 * from new account registrations, but may be used internally
738 * either by batch processes or by user accounts which have
739 * already been created.
741 * Additional blacklisting may be added here rather than in
742 * isValidUserName() to avoid disrupting existing accounts.
744 * @param string $name String to match
747 public static function isCreatableName( $name ) {
748 global $wgInvalidUsernameCharacters;
750 // Ensure that the username isn't longer than 235 bytes, so that
751 // (at least for the builtin skins) user javascript and css files
752 // will work. (bug 23080)
753 if ( strlen( $name ) > 235 ) {
754 wfDebugLog( 'username', __METHOD__
.
755 ": '$name' invalid due to length" );
759 // Preg yells if you try to give it an empty string
760 if ( $wgInvalidUsernameCharacters !== '' ) {
761 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
762 wfDebugLog( 'username', __METHOD__
.
763 ": '$name' invalid due to wgInvalidUsernameCharacters" );
768 return self
::isUsableName( $name );
772 * Is the input a valid password for this user?
774 * @param string $password Desired password
777 public function isValidPassword( $password ) {
778 //simple boolean wrapper for getPasswordValidity
779 return $this->getPasswordValidity( $password ) === true;
784 * Given unvalidated password input, return error message on failure.
786 * @param string $password Desired password
787 * @return bool|string|array True on success, string or array of error message on failure
789 public function getPasswordValidity( $password ) {
790 $result = $this->checkPasswordValidity( $password );
791 if ( $result->isGood() ) {
795 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
796 $messages[] = $error['message'];
798 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
799 $messages[] = $warning['message'];
801 if ( count( $messages ) === 1 ) {
809 * Check if this is a valid password for this user. Status will be good if
810 * the password is valid, or have an array of error messages if not.
812 * @param string $password Desired password
816 public function checkPasswordValidity( $password ) {
817 global $wgMinimalPasswordLength, $wgContLang;
819 static $blockedLogins = array(
820 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
821 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
824 $status = Status
::newGood();
826 $result = false; //init $result to false for the internal checks
828 if ( !Hooks
::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
829 $status->error( $result );
833 if ( $result === false ) {
834 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
835 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
837 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
838 $status->error( 'password-name-match' );
840 } elseif ( isset( $blockedLogins[$this->getName()] )
841 && $password == $blockedLogins[$this->getName()]
843 $status->error( 'password-login-forbidden' );
846 //it seems weird returning a Good status here, but this is because of the
847 //initialization of $result to false above. If the hook is never run or it
848 //doesn't modify $result, then we will likely get down into this if with
852 } elseif ( $result === true ) {
855 $status->error( $result );
856 return $status; //the isValidPassword hook set a string $result and returned true
861 * Expire a user's password
863 * @param int $ts Optional timestamp to convert, default 0 for the current time
865 public function expirePassword( $ts = 0 ) {
866 $this->loadPasswords();
867 $timestamp = wfTimestamp( TS_MW
, $ts );
868 $this->mPasswordExpires
= $timestamp;
869 $this->saveSettings();
873 * Clear the password expiration for a user
875 * @param bool $load Ensure user object is loaded first
877 public function resetPasswordExpiration( $load = true ) {
878 global $wgPasswordExpirationDays;
883 if ( $wgPasswordExpirationDays ) {
884 $newExpire = wfTimestamp(
886 time() +
( $wgPasswordExpirationDays * 24 * 3600 )
889 // Give extensions a chance to force an expiration
890 Hooks
::run( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
891 $this->mPasswordExpires
= $newExpire;
895 * Check if the user's password is expired.
896 * TODO: Put this and password length into a PasswordPolicy object
898 * @return string|bool The expiration type, or false if not expired
899 * hard: A password change is required to login
900 * soft: Allow login, but encourage password change
901 * false: Password is not expired
903 public function getPasswordExpired() {
904 global $wgPasswordExpireGrace;
906 $now = wfTimestamp();
907 $expiration = $this->getPasswordExpireDate();
908 $expUnix = wfTimestamp( TS_UNIX
, $expiration );
909 if ( $expiration !== null && $expUnix < $now ) {
910 $expired = ( $expUnix +
$wgPasswordExpireGrace < $now ) ?
'hard' : 'soft';
916 * Get this user's password expiration date. Since this may be using
917 * the cached User object, we assume that whatever mechanism is setting
918 * the expiration date is also expiring the User cache.
920 * @return string|bool The datestamp of the expiration, or null if not set
922 public function getPasswordExpireDate() {
924 return $this->mPasswordExpires
;
928 * Given unvalidated user input, return a canonical username, or false if
929 * the username is invalid.
930 * @param string $name User input
931 * @param string|bool $validate Type of validation to use:
932 * - false No validation
933 * - 'valid' Valid for batch processes
934 * - 'usable' Valid for batch processes and login
935 * - 'creatable' Valid for batch processes, login and account creation
937 * @throws MWException
938 * @return bool|string
940 public static function getCanonicalName( $name, $validate = 'valid' ) {
941 // Force usernames to capital
943 $name = $wgContLang->ucfirst( $name );
945 # Reject names containing '#'; these will be cleaned up
946 # with title normalisation, but then it's too late to
948 if ( strpos( $name, '#' ) !== false ) {
952 // Clean up name according to title rules,
953 // but only when validation is requested (bug 12654)
954 $t = ( $validate !== false ) ?
955 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
956 // Check for invalid titles
957 if ( is_null( $t ) ) {
961 // Reject various classes of invalid names
963 $name = $wgAuth->getCanonicalName( $t->getText() );
965 switch ( $validate ) {
969 if ( !User
::isValidUserName( $name ) ) {
974 if ( !User
::isUsableName( $name ) ) {
979 if ( !User
::isCreatableName( $name ) ) {
984 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
990 * Count the number of edits of a user
992 * @param int $uid User ID to check
993 * @return int The user's edit count
995 * @deprecated since 1.21 in favour of User::getEditCount
997 public static function edits( $uid ) {
998 wfDeprecated( __METHOD__
, '1.21' );
999 $user = self
::newFromId( $uid );
1000 return $user->getEditCount();
1004 * Return a random password.
1006 * @return string New random password
1008 public static function randomPassword() {
1009 global $wgMinimalPasswordLength;
1010 // Decide the final password length based on our min password length,
1011 // stopping at a minimum of 10 chars.
1012 $length = max( 10, $wgMinimalPasswordLength );
1013 // Multiply by 1.25 to get the number of hex characters we need
1014 $length = $length * 1.25;
1015 // Generate random hex chars
1016 $hex = MWCryptRand
::generateHex( $length );
1017 // Convert from base 16 to base 32 to get a proper password like string
1018 return wfBaseConvert( $hex, 16, 32 );
1022 * Set cached properties to default.
1024 * @note This no longer clears uncached lazy-initialised properties;
1025 * the constructor does that instead.
1027 * @param string|bool $name
1029 public function loadDefaults( $name = false ) {
1031 $passwordFactory = self
::getPasswordFactory();
1034 $this->mName
= $name;
1035 $this->mRealName
= '';
1036 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1037 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1038 $this->mNewpassTime
= null;
1040 $this->mOptionOverrides
= null;
1041 $this->mOptionsLoaded
= false;
1043 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1044 if ( $loggedOut !== null ) {
1045 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1047 $this->mTouched
= '1'; # Allow any pages to be cached
1050 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1051 $this->mEmailAuthenticated
= null;
1052 $this->mEmailToken
= '';
1053 $this->mEmailTokenExpires
= null;
1054 $this->mPasswordExpires
= null;
1055 $this->resetPasswordExpiration( false );
1056 $this->mRegistration
= wfTimestamp( TS_MW
);
1057 $this->mGroups
= array();
1059 Hooks
::run( 'UserLoadDefaults', array( $this, $name ) );
1064 * Return whether an item has been loaded.
1066 * @param string $item Item to check. Current possibilities:
1070 * @param string $all 'all' to check if the whole object has been loaded
1071 * or any other string to check if only the item is available (e.g.
1075 public function isItemLoaded( $item, $all = 'all' ) {
1076 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1077 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1081 * Set that an item has been loaded
1083 * @param string $item
1085 protected function setItemLoaded( $item ) {
1086 if ( is_array( $this->mLoadedItems
) ) {
1087 $this->mLoadedItems
[$item] = true;
1092 * Load user data from the session or login cookie.
1094 * @return bool True if the user is logged in, false otherwise.
1096 private function loadFromSession() {
1098 Hooks
::run( 'UserLoadFromSession', array( $this, &$result ) );
1099 if ( $result !== null ) {
1103 $request = $this->getRequest();
1105 $cookieId = $request->getCookie( 'UserID' );
1106 $sessId = $request->getSessionData( 'wsUserID' );
1108 if ( $cookieId !== null ) {
1109 $sId = intval( $cookieId );
1110 if ( $sessId !== null && $cookieId != $sessId ) {
1111 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1112 cookie user ID ($sId) don't match!" );
1115 $request->setSessionData( 'wsUserID', $sId );
1116 } elseif ( $sessId !== null && $sessId != 0 ) {
1122 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1123 $sName = $request->getSessionData( 'wsUserName' );
1124 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1125 $sName = $request->getCookie( 'UserName' );
1126 $request->setSessionData( 'wsUserName', $sName );
1131 $proposedUser = User
::newFromId( $sId );
1132 $proposedUser->load( self
::READ_LATEST
);
1133 if ( !$proposedUser->isLoggedIn() ) {
1138 global $wgBlockDisablesLogin;
1139 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1140 // User blocked and we've disabled blocked user logins
1144 if ( $request->getSessionData( 'wsToken' ) ) {
1146 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1148 } elseif ( $request->getCookie( 'Token' ) ) {
1149 # Get the token from DB/cache and clean it up to remove garbage padding.
1150 # This deals with historical problems with bugs and the default column value.
1151 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1152 // Make comparison in constant time (bug 61346)
1153 $passwordCorrect = strlen( $token )
1154 && hash_equals( $token, $request->getCookie( 'Token' ) );
1157 // No session or persistent login cookie
1161 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1162 $this->loadFromUserObject( $proposedUser );
1163 $request->setSessionData( 'wsToken', $this->mToken
);
1164 wfDebug( "User: logged in from $from\n" );
1167 // Invalid credentials
1168 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1174 * Load user and user_group data from the database.
1175 * $this->mId must be set, this is how the user is identified.
1177 * @param integer $flags User::READ_* constant bitfield
1178 * @return bool True if the user exists, false if the user is anonymous
1180 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1182 $this->mId
= intval( $this->mId
);
1185 if ( !$this->mId
) {
1186 $this->loadDefaults();
1190 $db = ( $flags & self
::READ_LATEST
)
1191 ?
wfGetDB( DB_MASTER
)
1192 : wfGetDB( DB_SLAVE
);
1194 $s = $db->selectRow(
1196 self
::selectFields(),
1197 array( 'user_id' => $this->mId
),
1199 ( $flags & self
::READ_LOCKING
== self
::READ_LOCKING
)
1200 ?
array( 'LOCK IN SHARE MODE' )
1204 Hooks
::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1206 if ( $s !== false ) {
1207 // Initialise user table data
1208 $this->loadFromRow( $s );
1209 $this->mGroups
= null; // deferred
1210 $this->getEditCount(); // revalidation for nulls
1215 $this->loadDefaults();
1221 * Initialize this object from a row from the user table.
1223 * @param stdClass $row Row from the user table to load.
1224 * @param array $data Further user data to load into the object
1226 * user_groups Array with groups out of the user_groups table
1227 * user_properties Array with properties out of the user_properties table
1229 public function loadFromRow( $row, $data = null ) {
1231 $passwordFactory = self
::getPasswordFactory();
1233 $this->mGroups
= null; // deferred
1235 if ( isset( $row->user_name
) ) {
1236 $this->mName
= $row->user_name
;
1237 $this->mFrom
= 'name';
1238 $this->setItemLoaded( 'name' );
1243 if ( isset( $row->user_real_name
) ) {
1244 $this->mRealName
= $row->user_real_name
;
1245 $this->setItemLoaded( 'realname' );
1250 if ( isset( $row->user_id
) ) {
1251 $this->mId
= intval( $row->user_id
);
1252 $this->mFrom
= 'id';
1253 $this->setItemLoaded( 'id' );
1258 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1259 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1262 if ( isset( $row->user_editcount
) ) {
1263 $this->mEditCount
= $row->user_editcount
;
1268 if ( isset( $row->user_password
) ) {
1269 // Check for *really* old password hashes that don't even have a type
1270 // The old hash format was just an md5 hex hash, with no type information
1271 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password
) ) {
1272 $row->user_password
= ":A:{$this->mId}:{$row->user_password}";
1276 $this->mPassword
= $passwordFactory->newFromCiphertext( $row->user_password
);
1277 } catch ( PasswordError
$e ) {
1278 wfDebug( 'Invalid password hash found in database.' );
1279 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1283 $this->mNewpassword
= $passwordFactory->newFromCiphertext( $row->user_newpassword
);
1284 } catch ( PasswordError
$e ) {
1285 wfDebug( 'Invalid password hash found in database.' );
1286 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1289 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1290 $this->mPasswordExpires
= wfTimestampOrNull( TS_MW
, $row->user_password_expires
);
1293 if ( isset( $row->user_email
) ) {
1294 $this->mEmail
= $row->user_email
;
1295 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1296 $this->mToken
= $row->user_token
;
1297 if ( $this->mToken
== '' ) {
1298 $this->mToken
= null;
1300 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1301 $this->mEmailToken
= $row->user_email_token
;
1302 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1303 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1309 $this->mLoadedItems
= true;
1312 if ( is_array( $data ) ) {
1313 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1314 $this->mGroups
= $data['user_groups'];
1316 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1317 $this->loadOptions( $data['user_properties'] );
1323 * Load the data for this user object from another user object.
1327 protected function loadFromUserObject( $user ) {
1329 $user->loadGroups();
1330 $user->loadOptions();
1331 foreach ( self
::$mCacheVars as $var ) {
1332 $this->$var = $user->$var;
1337 * Load the groups from the database if they aren't already loaded.
1339 private function loadGroups() {
1340 if ( is_null( $this->mGroups
) ) {
1341 $dbr = wfGetDB( DB_MASTER
);
1342 $res = $dbr->select( 'user_groups',
1343 array( 'ug_group' ),
1344 array( 'ug_user' => $this->mId
),
1346 $this->mGroups
= array();
1347 foreach ( $res as $row ) {
1348 $this->mGroups
[] = $row->ug_group
;
1354 * Load the user's password hashes from the database
1356 * This is usually called in a scenario where the actual User object was
1357 * loaded from the cache, and then password comparison needs to be performed.
1358 * Password hashes are not stored in memcached.
1362 private function loadPasswords() {
1363 if ( $this->getId() !== 0 && ( $this->mPassword
=== null ||
$this->mNewpassword
=== null ) ) {
1364 $this->loadFromRow( wfGetDB( DB_MASTER
)->selectRow(
1366 array( 'user_password', 'user_newpassword', 'user_newpass_time', 'user_password_expires' ),
1367 array( 'user_id' => $this->getId() ),
1374 * Add the user to the group if he/she meets given criteria.
1376 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1377 * possible to remove manually via Special:UserRights. In such case it
1378 * will not be re-added automatically. The user will also not lose the
1379 * group if they no longer meet the criteria.
1381 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1383 * @return array Array of groups the user has been promoted to.
1385 * @see $wgAutopromoteOnce
1387 public function addAutopromoteOnceGroups( $event ) {
1388 global $wgAutopromoteOnceLogInRC, $wgAuth;
1390 $toPromote = array();
1391 if ( $this->getId() ) {
1392 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1393 if ( count( $toPromote ) ) {
1394 $oldGroups = $this->getGroups(); // previous groups
1396 foreach ( $toPromote as $group ) {
1397 $this->addGroup( $group );
1399 // update groups in external authentication database
1400 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1402 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1404 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1405 $logEntry->setPerformer( $this );
1406 $logEntry->setTarget( $this->getUserPage() );
1407 $logEntry->setParameters( array(
1408 '4::oldgroups' => $oldGroups,
1409 '5::newgroups' => $newGroups,
1411 $logid = $logEntry->insert();
1412 if ( $wgAutopromoteOnceLogInRC ) {
1413 $logEntry->publish( $logid );
1421 * Clear various cached data stored in this object. The cache of the user table
1422 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1424 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1425 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1427 public function clearInstanceCache( $reloadFrom = false ) {
1428 $this->mNewtalk
= -1;
1429 $this->mDatePreference
= null;
1430 $this->mBlockedby
= -1; # Unset
1431 $this->mHash
= false;
1432 $this->mRights
= null;
1433 $this->mEffectiveGroups
= null;
1434 $this->mImplicitGroups
= null;
1435 $this->mGroups
= null;
1436 $this->mOptions
= null;
1437 $this->mOptionsLoaded
= false;
1438 $this->mEditCount
= null;
1440 if ( $reloadFrom ) {
1441 $this->mLoadedItems
= array();
1442 $this->mFrom
= $reloadFrom;
1447 * Combine the language default options with any site-specific options
1448 * and add the default language variants.
1450 * @return array Array of String options
1452 public static function getDefaultOptions() {
1453 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1455 static $defOpt = null;
1456 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1457 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1458 // mid-request and see that change reflected in the return value of this function.
1459 // Which is insane and would never happen during normal MW operation
1463 $defOpt = $wgDefaultUserOptions;
1464 // Default language setting
1465 $defOpt['language'] = $wgContLang->getCode();
1466 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1467 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1469 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1470 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1472 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1474 Hooks
::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1480 * Get a given default option value.
1482 * @param string $opt Name of option to retrieve
1483 * @return string Default option value
1485 public static function getDefaultOption( $opt ) {
1486 $defOpts = self
::getDefaultOptions();
1487 if ( isset( $defOpts[$opt] ) ) {
1488 return $defOpts[$opt];
1495 * Get blocking information
1496 * @param bool $bFromSlave Whether to check the slave database first.
1497 * To improve performance, non-critical checks are done against slaves.
1498 * Check when actually saving should be done against master.
1500 private function getBlockedStatus( $bFromSlave = true ) {
1501 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1503 if ( -1 != $this->mBlockedby
) {
1507 wfDebug( __METHOD__
. ": checking...\n" );
1509 // Initialize data...
1510 // Otherwise something ends up stomping on $this->mBlockedby when
1511 // things get lazy-loaded later, causing false positive block hits
1512 // due to -1 !== 0. Probably session-related... Nothing should be
1513 // overwriting mBlockedby, surely?
1516 # We only need to worry about passing the IP address to the Block generator if the
1517 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1518 # know which IP address they're actually coming from
1519 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1520 $ip = $this->getRequest()->getIP();
1526 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1529 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1530 && !in_array( $ip, $wgProxyWhitelist )
1533 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1535 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1536 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1537 $block->setTarget( $ip );
1538 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1540 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1541 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1542 $block->setTarget( $ip );
1546 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1547 if ( !$block instanceof Block
1548 && $wgApplyIpBlocksToXff
1550 && !$this->isAllowed( 'proxyunbannable' )
1551 && !in_array( $ip, $wgProxyWhitelist )
1553 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1554 $xff = array_map( 'trim', explode( ',', $xff ) );
1555 $xff = array_diff( $xff, array( $ip ) );
1556 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1557 $block = Block
::chooseBlock( $xffblocks, $xff );
1558 if ( $block instanceof Block
) {
1559 # Mangle the reason to alert the user that the block
1560 # originated from matching the X-Forwarded-For header.
1561 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1565 if ( $block instanceof Block
) {
1566 wfDebug( __METHOD__
. ": Found block.\n" );
1567 $this->mBlock
= $block;
1568 $this->mBlockedby
= $block->getByName();
1569 $this->mBlockreason
= $block->mReason
;
1570 $this->mHideName
= $block->mHideName
;
1571 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1573 $this->mBlockedby
= '';
1574 $this->mHideName
= 0;
1575 $this->mAllowUsertalk
= false;
1579 Hooks
::run( 'GetBlockedStatus', array( &$this ) );
1584 * Whether the given IP is in a DNS blacklist.
1586 * @param string $ip IP to check
1587 * @param bool $checkWhitelist Whether to check the whitelist first
1588 * @return bool True if blacklisted.
1590 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1591 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1593 if ( !$wgEnableDnsBlacklist ) {
1597 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1601 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1605 * Whether the given IP is in a given DNS blacklist.
1607 * @param string $ip IP to check
1608 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1609 * @return bool True if blacklisted.
1611 public function inDnsBlacklist( $ip, $bases ) {
1614 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1615 if ( IP
::isIPv4( $ip ) ) {
1616 // Reverse IP, bug 21255
1617 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1619 foreach ( (array)$bases as $base ) {
1621 // If we have an access key, use that too (ProjectHoneypot, etc.)
1622 if ( is_array( $base ) ) {
1623 if ( count( $base ) >= 2 ) {
1624 // Access key is 1, base URL is 0
1625 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1627 $host = "$ipReversed.{$base[0]}";
1630 $host = "$ipReversed.$base";
1634 $ipList = gethostbynamel( $host );
1637 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1641 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1650 * Check if an IP address is in the local proxy list
1656 public static function isLocallyBlockedProxy( $ip ) {
1657 global $wgProxyList;
1659 if ( !$wgProxyList ) {
1663 if ( !is_array( $wgProxyList ) ) {
1664 // Load from the specified file
1665 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1668 if ( !is_array( $wgProxyList ) ) {
1670 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1672 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1673 // Old-style flipped proxy list
1682 * Is this user subject to rate limiting?
1684 * @return bool True if rate limited
1686 public function isPingLimitable() {
1687 global $wgRateLimitsExcludedIPs;
1688 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1689 // No other good way currently to disable rate limits
1690 // for specific IPs. :P
1691 // But this is a crappy hack and should die.
1694 return !$this->isAllowed( 'noratelimit' );
1698 * Primitive rate limits: enforce maximum actions per time period
1699 * to put a brake on flooding.
1701 * The method generates both a generic profiling point and a per action one
1702 * (suffix being "-$action".
1704 * @note When using a shared cache like memcached, IP-address
1705 * last-hit counters will be shared across wikis.
1707 * @param string $action Action to enforce; 'edit' if unspecified
1708 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1709 * @return bool True if a rate limiter was tripped
1711 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1712 // Call the 'PingLimiter' hook
1714 if ( !Hooks
::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1718 global $wgRateLimits;
1719 if ( !isset( $wgRateLimits[$action] ) ) {
1723 // Some groups shouldn't trigger the ping limiter, ever
1724 if ( !$this->isPingLimitable() ) {
1730 $limits = $wgRateLimits[$action];
1732 $id = $this->getId();
1735 if ( isset( $limits['anon'] ) && $id == 0 ) {
1736 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1739 if ( isset( $limits['user'] ) && $id != 0 ) {
1740 $userLimit = $limits['user'];
1742 if ( $this->isNewbie() ) {
1743 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1744 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1746 if ( isset( $limits['ip'] ) ) {
1747 $ip = $this->getRequest()->getIP();
1748 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1750 if ( isset( $limits['subnet'] ) ) {
1751 $ip = $this->getRequest()->getIP();
1754 if ( IP
::isIPv6( $ip ) ) {
1755 $parts = IP
::parseRange( "$ip/64" );
1756 $subnet = $parts[0];
1757 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1759 $subnet = $matches[1];
1761 if ( $subnet !== false ) {
1762 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1766 // Check for group-specific permissions
1767 // If more than one group applies, use the group with the highest limit
1768 foreach ( $this->getGroups() as $group ) {
1769 if ( isset( $limits[$group] ) ) {
1770 if ( $userLimit === false
1771 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1773 $userLimit = $limits[$group];
1777 // Set the user limit key
1778 if ( $userLimit !== false ) {
1779 list( $max, $period ) = $userLimit;
1780 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1781 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1785 foreach ( $keys as $key => $limit ) {
1786 list( $max, $period ) = $limit;
1787 $summary = "(limit $max in {$period}s)";
1788 $count = $wgMemc->get( $key );
1791 if ( $count >= $max ) {
1792 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1793 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1796 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1799 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1800 if ( $incrBy > 0 ) {
1801 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1804 if ( $incrBy > 0 ) {
1805 $wgMemc->incr( $key, $incrBy );
1813 * Check if user is blocked
1815 * @param bool $bFromSlave Whether to check the slave database instead of
1816 * the master. Hacked from false due to horrible probs on site.
1817 * @return bool True if blocked, false otherwise
1819 public function isBlocked( $bFromSlave = true ) {
1820 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1824 * Get the block affecting the user, or null if the user is not blocked
1826 * @param bool $bFromSlave Whether to check the slave database instead of the master
1827 * @return Block|null
1829 public function getBlock( $bFromSlave = true ) {
1830 $this->getBlockedStatus( $bFromSlave );
1831 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1835 * Check if user is blocked from editing a particular article
1837 * @param Title $title Title to check
1838 * @param bool $bFromSlave Whether to check the slave database instead of the master
1841 public function isBlockedFrom( $title, $bFromSlave = false ) {
1842 global $wgBlockAllowsUTEdit;
1844 $blocked = $this->isBlocked( $bFromSlave );
1845 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1846 // If a user's name is suppressed, they cannot make edits anywhere
1847 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1848 && $title->getNamespace() == NS_USER_TALK
) {
1850 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1853 Hooks
::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1859 * If user is blocked, return the name of the user who placed the block
1860 * @return string Name of blocker
1862 public function blockedBy() {
1863 $this->getBlockedStatus();
1864 return $this->mBlockedby
;
1868 * If user is blocked, return the specified reason for the block
1869 * @return string Blocking reason
1871 public function blockedFor() {
1872 $this->getBlockedStatus();
1873 return $this->mBlockreason
;
1877 * If user is blocked, return the ID for the block
1878 * @return int Block ID
1880 public function getBlockId() {
1881 $this->getBlockedStatus();
1882 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1886 * Check if user is blocked on all wikis.
1887 * Do not use for actual edit permission checks!
1888 * This is intended for quick UI checks.
1890 * @param string $ip IP address, uses current client if none given
1891 * @return bool True if blocked, false otherwise
1893 public function isBlockedGlobally( $ip = '' ) {
1894 if ( $this->mBlockedGlobally
!== null ) {
1895 return $this->mBlockedGlobally
;
1897 // User is already an IP?
1898 if ( IP
::isIPAddress( $this->getName() ) ) {
1899 $ip = $this->getName();
1901 $ip = $this->getRequest()->getIP();
1904 Hooks
::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1905 $this->mBlockedGlobally
= (bool)$blocked;
1906 return $this->mBlockedGlobally
;
1910 * Check if user account is locked
1912 * @return bool True if locked, false otherwise
1914 public function isLocked() {
1915 if ( $this->mLocked
!== null ) {
1916 return $this->mLocked
;
1919 $authUser = $wgAuth->getUserInstance( $this );
1920 $this->mLocked
= (bool)$authUser->isLocked();
1921 return $this->mLocked
;
1925 * Check if user account is hidden
1927 * @return bool True if hidden, false otherwise
1929 public function isHidden() {
1930 if ( $this->mHideName
!== null ) {
1931 return $this->mHideName
;
1933 $this->getBlockedStatus();
1934 if ( !$this->mHideName
) {
1936 $authUser = $wgAuth->getUserInstance( $this );
1937 $this->mHideName
= (bool)$authUser->isHidden();
1939 return $this->mHideName
;
1943 * Get the user's ID.
1944 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1946 public function getId() {
1947 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1948 // Special case, we know the user is anonymous
1950 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1951 // Don't load if this was initialized from an ID
1958 * Set the user and reload all fields according to a given ID
1959 * @param int $v User ID to reload
1961 public function setId( $v ) {
1963 $this->clearInstanceCache( 'id' );
1967 * Get the user name, or the IP of an anonymous user
1968 * @return string User's name or IP address
1970 public function getName() {
1971 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1972 // Special case optimisation
1973 return $this->mName
;
1976 if ( $this->mName
=== false ) {
1978 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1980 return $this->mName
;
1985 * Set the user name.
1987 * This does not reload fields from the database according to the given
1988 * name. Rather, it is used to create a temporary "nonexistent user" for
1989 * later addition to the database. It can also be used to set the IP
1990 * address for an anonymous user to something other than the current
1993 * @note User::newFromName() has roughly the same function, when the named user
1995 * @param string $str New user name to set
1997 public function setName( $str ) {
1999 $this->mName
= $str;
2003 * Get the user's name escaped by underscores.
2004 * @return string Username escaped by underscores.
2006 public function getTitleKey() {
2007 return str_replace( ' ', '_', $this->getName() );
2011 * Check if the user has new messages.
2012 * @return bool True if the user has new messages
2014 public function getNewtalk() {
2017 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2018 if ( $this->mNewtalk
=== -1 ) {
2019 $this->mNewtalk
= false; # reset talk page status
2021 // Check memcached separately for anons, who have no
2022 // entire User object stored in there.
2023 if ( !$this->mId
) {
2024 global $wgDisableAnonTalk;
2025 if ( $wgDisableAnonTalk ) {
2026 // Anon newtalk disabled by configuration.
2027 $this->mNewtalk
= false;
2029 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2032 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2036 return (bool)$this->mNewtalk
;
2040 * Return the data needed to construct links for new talk page message
2041 * alerts. If there are new messages, this will return an associative array
2042 * with the following data:
2043 * wiki: The database name of the wiki
2044 * link: Root-relative link to the user's talk page
2045 * rev: The last talk page revision that the user has seen or null. This
2046 * is useful for building diff links.
2047 * If there are no new messages, it returns an empty array.
2048 * @note This function was designed to accomodate multiple talk pages, but
2049 * currently only returns a single link and revision.
2052 public function getNewMessageLinks() {
2054 if ( !Hooks
::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2056 } elseif ( !$this->getNewtalk() ) {
2059 $utp = $this->getTalkPage();
2060 $dbr = wfGetDB( DB_SLAVE
);
2061 // Get the "last viewed rev" timestamp from the oldest message notification
2062 $timestamp = $dbr->selectField( 'user_newtalk',
2063 'MIN(user_last_timestamp)',
2064 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2066 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2067 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2071 * Get the revision ID for the last talk page revision viewed by the talk
2073 * @return int|null Revision ID or null
2075 public function getNewMessageRevisionId() {
2076 $newMessageRevisionId = null;
2077 $newMessageLinks = $this->getNewMessageLinks();
2078 if ( $newMessageLinks ) {
2079 // Note: getNewMessageLinks() never returns more than a single link
2080 // and it is always for the same wiki, but we double-check here in
2081 // case that changes some time in the future.
2082 if ( count( $newMessageLinks ) === 1
2083 && $newMessageLinks[0]['wiki'] === wfWikiID()
2084 && $newMessageLinks[0]['rev']
2086 $newMessageRevision = $newMessageLinks[0]['rev'];
2087 $newMessageRevisionId = $newMessageRevision->getId();
2090 return $newMessageRevisionId;
2094 * Internal uncached check for new messages
2097 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2098 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2099 * @param bool $fromMaster True to fetch from the master, false for a slave
2100 * @return bool True if the user has new messages
2102 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2103 if ( $fromMaster ) {
2104 $db = wfGetDB( DB_MASTER
);
2106 $db = wfGetDB( DB_SLAVE
);
2108 $ok = $db->selectField( 'user_newtalk', $field,
2109 array( $field => $id ), __METHOD__
);
2110 return $ok !== false;
2114 * Add or update the new messages flag
2115 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2116 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2117 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2118 * @return bool True if successful, false otherwise
2120 protected function updateNewtalk( $field, $id, $curRev = null ) {
2121 // Get timestamp of the talk page revision prior to the current one
2122 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2123 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2124 // Mark the user as having new messages since this revision
2125 $dbw = wfGetDB( DB_MASTER
);
2126 $dbw->insert( 'user_newtalk',
2127 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2130 if ( $dbw->affectedRows() ) {
2131 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2134 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2140 * Clear the new messages flag for the given user
2141 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2142 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2143 * @return bool True if successful, false otherwise
2145 protected function deleteNewtalk( $field, $id ) {
2146 $dbw = wfGetDB( DB_MASTER
);
2147 $dbw->delete( 'user_newtalk',
2148 array( $field => $id ),
2150 if ( $dbw->affectedRows() ) {
2151 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2154 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2160 * Update the 'You have new messages!' status.
2161 * @param bool $val Whether the user has new messages
2162 * @param Revision $curRev New, as yet unseen revision of the user talk
2163 * page. Ignored if null or !$val.
2165 public function setNewtalk( $val, $curRev = null ) {
2166 if ( wfReadOnly() ) {
2171 $this->mNewtalk
= $val;
2173 if ( $this->isAnon() ) {
2175 $id = $this->getName();
2178 $id = $this->getId();
2183 $changed = $this->updateNewtalk( $field, $id, $curRev );
2185 $changed = $this->deleteNewtalk( $field, $id );
2188 if ( $this->isAnon() ) {
2189 // Anons have a separate memcached space, since
2190 // user records aren't kept for them.
2191 $key = wfMemcKey( 'newtalk', 'ip', $id );
2192 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
2195 $this->invalidateCache();
2200 * Generate a current or new-future timestamp to be stored in the
2201 * user_touched field when we update things.
2202 * @return string Timestamp in TS_MW format
2204 private static function newTouchedTimestamp() {
2205 global $wgClockSkewFudge;
2206 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2210 * Clear user data from memcached.
2211 * Use after applying fun updates to the database; caller's
2212 * responsibility to update user_touched if appropriate.
2214 * Called implicitly from invalidateCache() and saveSettings().
2216 public function clearSharedCache() {
2220 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
2225 * Immediately touch the user data cache for this account.
2226 * Updates user_touched field, and removes account data from memcached
2227 * for reload on the next hit.
2229 public function invalidateCache() {
2230 if ( wfReadOnly() ) {
2235 $this->mTouched
= self
::newTouchedTimestamp();
2237 $dbw = wfGetDB( DB_MASTER
);
2238 $userid = $this->mId
;
2239 $touched = $this->mTouched
;
2240 $method = __METHOD__
;
2241 $dbw->onTransactionIdle( function () use ( $dbw, $userid, $touched, $method ) {
2242 // Prevent contention slams by checking user_touched first
2243 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2244 $needsPurge = $dbw->selectField( 'user', '1',
2245 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2246 if ( $needsPurge ) {
2247 $dbw->update( 'user',
2248 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2249 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2254 $this->clearSharedCache();
2259 * Validate the cache for this account.
2260 * @param string $timestamp A timestamp in TS_MW format
2263 public function validateCache( $timestamp ) {
2265 return ( $timestamp >= $this->mTouched
);
2269 * Get the user touched timestamp
2270 * @return string Timestamp
2272 public function getTouched() {
2274 return $this->mTouched
;
2281 public function getPassword() {
2282 $this->loadPasswords();
2284 return $this->mPassword
;
2291 public function getTemporaryPassword() {
2292 $this->loadPasswords();
2294 return $this->mNewpassword
;
2298 * Set the password and reset the random token.
2299 * Calls through to authentication plugin if necessary;
2300 * will have no effect if the auth plugin refuses to
2301 * pass the change through or if the legal password
2304 * As a special case, setting the password to null
2305 * wipes it, so the account cannot be logged in until
2306 * a new password is set, for instance via e-mail.
2308 * @param string $str New password to set
2309 * @throws PasswordError On failure
2313 public function setPassword( $str ) {
2316 $this->loadPasswords();
2318 if ( $str !== null ) {
2319 if ( !$wgAuth->allowPasswordChange() ) {
2320 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2323 if ( !$this->isValidPassword( $str ) ) {
2324 global $wgMinimalPasswordLength;
2325 $valid = $this->getPasswordValidity( $str );
2326 if ( is_array( $valid ) ) {
2327 $message = array_shift( $valid );
2331 $params = array( $wgMinimalPasswordLength );
2333 throw new PasswordError( wfMessage( $message, $params )->text() );
2337 if ( !$wgAuth->setPassword( $this, $str ) ) {
2338 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2341 $this->setInternalPassword( $str );
2347 * Set the password and reset the random token unconditionally.
2349 * @param string|null $str New password to set or null to set an invalid
2350 * password hash meaning that the user will not be able to log in
2351 * through the web interface.
2353 public function setInternalPassword( $str ) {
2356 $passwordFactory = self
::getPasswordFactory();
2357 $this->mPassword
= $passwordFactory->newFromPlaintext( $str );
2359 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
2360 $this->mNewpassTime
= null;
2364 * Get the user's current token.
2365 * @param bool $forceCreation Force the generation of a new token if the
2366 * user doesn't have one (default=true for backwards compatibility).
2367 * @return string Token
2369 public function getToken( $forceCreation = true ) {
2371 if ( !$this->mToken
&& $forceCreation ) {
2374 return $this->mToken
;
2378 * Set the random token (used for persistent authentication)
2379 * Called from loadDefaults() among other places.
2381 * @param string|bool $token If specified, set the token to this value
2383 public function setToken( $token = false ) {
2386 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2388 $this->mToken
= $token;
2393 * Set the password for a password reminder or new account email
2395 * @param string $str New password to set or null to set an invalid
2396 * password hash meaning that the user will not be able to use it
2397 * @param bool $throttle If true, reset the throttle timestamp to the present
2399 public function setNewpassword( $str, $throttle = true ) {
2400 $this->loadPasswords();
2402 $this->mNewpassword
= self
::getPasswordFactory()->newFromPlaintext( $str );
2403 if ( $str === null ) {
2404 $this->mNewpassTime
= null;
2405 } elseif ( $throttle ) {
2406 $this->mNewpassTime
= wfTimestampNow();
2411 * Has password reminder email been sent within the last
2412 * $wgPasswordReminderResendTime hours?
2415 public function isPasswordReminderThrottled() {
2416 global $wgPasswordReminderResendTime;
2418 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2421 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2422 return time() < $expiry;
2426 * Get the user's e-mail address
2427 * @return string User's email address
2429 public function getEmail() {
2431 Hooks
::run( 'UserGetEmail', array( $this, &$this->mEmail
) );
2432 return $this->mEmail
;
2436 * Get the timestamp of the user's e-mail authentication
2437 * @return string TS_MW timestamp
2439 public function getEmailAuthenticationTimestamp() {
2441 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2442 return $this->mEmailAuthenticated
;
2446 * Set the user's e-mail address
2447 * @param string $str New e-mail address
2449 public function setEmail( $str ) {
2451 if ( $str == $this->mEmail
) {
2454 $this->invalidateEmail();
2455 $this->mEmail
= $str;
2456 Hooks
::run( 'UserSetEmail', array( $this, &$this->mEmail
) );
2460 * Set the user's e-mail address and a confirmation mail if needed.
2463 * @param string $str New e-mail address
2466 public function setEmailWithConfirmation( $str ) {
2467 global $wgEnableEmail, $wgEmailAuthentication;
2469 if ( !$wgEnableEmail ) {
2470 return Status
::newFatal( 'emaildisabled' );
2473 $oldaddr = $this->getEmail();
2474 if ( $str === $oldaddr ) {
2475 return Status
::newGood( true );
2478 $this->setEmail( $str );
2480 if ( $str !== '' && $wgEmailAuthentication ) {
2481 // Send a confirmation request to the new address if needed
2482 $type = $oldaddr != '' ?
'changed' : 'set';
2483 $result = $this->sendConfirmationMail( $type );
2484 if ( $result->isGood() ) {
2485 // Say to the caller that a confirmation mail has been sent
2486 $result->value
= 'eauth';
2489 $result = Status
::newGood( true );
2496 * Get the user's real name
2497 * @return string User's real name
2499 public function getRealName() {
2500 if ( !$this->isItemLoaded( 'realname' ) ) {
2504 return $this->mRealName
;
2508 * Set the user's real name
2509 * @param string $str New real name
2511 public function setRealName( $str ) {
2513 $this->mRealName
= $str;
2517 * Get the user's current setting for a given option.
2519 * @param string $oname The option to check
2520 * @param string $defaultOverride A default value returned if the option does not exist
2521 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2522 * @return string User's current value for the option
2523 * @see getBoolOption()
2524 * @see getIntOption()
2526 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2527 global $wgHiddenPrefs;
2528 $this->loadOptions();
2530 # We want 'disabled' preferences to always behave as the default value for
2531 # users, even if they have set the option explicitly in their settings (ie they
2532 # set it, and then it was disabled removing their ability to change it). But
2533 # we don't want to erase the preferences in the database in case the preference
2534 # is re-enabled again. So don't touch $mOptions, just override the returned value
2535 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2536 return self
::getDefaultOption( $oname );
2539 if ( array_key_exists( $oname, $this->mOptions
) ) {
2540 return $this->mOptions
[$oname];
2542 return $defaultOverride;
2547 * Get all user's options
2549 * @param int $flags Bitwise combination of:
2550 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2551 * to the default value. (Since 1.25)
2554 public function getOptions( $flags = 0 ) {
2555 global $wgHiddenPrefs;
2556 $this->loadOptions();
2557 $options = $this->mOptions
;
2559 # We want 'disabled' preferences to always behave as the default value for
2560 # users, even if they have set the option explicitly in their settings (ie they
2561 # set it, and then it was disabled removing their ability to change it). But
2562 # we don't want to erase the preferences in the database in case the preference
2563 # is re-enabled again. So don't touch $mOptions, just override the returned value
2564 foreach ( $wgHiddenPrefs as $pref ) {
2565 $default = self
::getDefaultOption( $pref );
2566 if ( $default !== null ) {
2567 $options[$pref] = $default;
2571 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2572 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2579 * Get the user's current setting for a given option, as a boolean value.
2581 * @param string $oname The option to check
2582 * @return bool User's current value for the option
2585 public function getBoolOption( $oname ) {
2586 return (bool)$this->getOption( $oname );
2590 * Get the user's current setting for a given option, as an integer value.
2592 * @param string $oname The option to check
2593 * @param int $defaultOverride A default value returned if the option does not exist
2594 * @return int User's current value for the option
2597 public function getIntOption( $oname, $defaultOverride = 0 ) {
2598 $val = $this->getOption( $oname );
2600 $val = $defaultOverride;
2602 return intval( $val );
2606 * Set the given option for a user.
2608 * You need to call saveSettings() to actually write to the database.
2610 * @param string $oname The option to set
2611 * @param mixed $val New value to set
2613 public function setOption( $oname, $val ) {
2614 $this->loadOptions();
2616 // Explicitly NULL values should refer to defaults
2617 if ( is_null( $val ) ) {
2618 $val = self
::getDefaultOption( $oname );
2621 $this->mOptions
[$oname] = $val;
2625 * Get a token stored in the preferences (like the watchlist one),
2626 * resetting it if it's empty (and saving changes).
2628 * @param string $oname The option name to retrieve the token from
2629 * @return string|bool User's current value for the option, or false if this option is disabled.
2630 * @see resetTokenFromOption()
2633 public function getTokenFromOption( $oname ) {
2634 global $wgHiddenPrefs;
2635 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2639 $token = $this->getOption( $oname );
2641 $token = $this->resetTokenFromOption( $oname );
2642 $this->saveSettings();
2648 * Reset a token stored in the preferences (like the watchlist one).
2649 * *Does not* save user's preferences (similarly to setOption()).
2651 * @param string $oname The option name to reset the token in
2652 * @return string|bool New token value, or false if this option is disabled.
2653 * @see getTokenFromOption()
2656 public function resetTokenFromOption( $oname ) {
2657 global $wgHiddenPrefs;
2658 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2662 $token = MWCryptRand
::generateHex( 40 );
2663 $this->setOption( $oname, $token );
2668 * Return a list of the types of user options currently returned by
2669 * User::getOptionKinds().
2671 * Currently, the option kinds are:
2672 * - 'registered' - preferences which are registered in core MediaWiki or
2673 * by extensions using the UserGetDefaultOptions hook.
2674 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2675 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2676 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2677 * be used by user scripts.
2678 * - 'special' - "preferences" that are not accessible via User::getOptions
2679 * or User::setOptions.
2680 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2681 * These are usually legacy options, removed in newer versions.
2683 * The API (and possibly others) use this function to determine the possible
2684 * option types for validation purposes, so make sure to update this when a
2685 * new option kind is added.
2687 * @see User::getOptionKinds
2688 * @return array Option kinds
2690 public static function listOptionKinds() {
2693 'registered-multiselect',
2694 'registered-checkmatrix',
2702 * Return an associative array mapping preferences keys to the kind of a preference they're
2703 * used for. Different kinds are handled differently when setting or reading preferences.
2705 * See User::listOptionKinds for the list of valid option types that can be provided.
2707 * @see User::listOptionKinds
2708 * @param IContextSource $context
2709 * @param array $options Assoc. array with options keys to check as keys.
2710 * Defaults to $this->mOptions.
2711 * @return array The key => kind mapping data
2713 public function getOptionKinds( IContextSource
$context, $options = null ) {
2714 $this->loadOptions();
2715 if ( $options === null ) {
2716 $options = $this->mOptions
;
2719 $prefs = Preferences
::getPreferences( $this, $context );
2722 // Pull out the "special" options, so they don't get converted as
2723 // multiselect or checkmatrix.
2724 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2725 foreach ( $specialOptions as $name => $value ) {
2726 unset( $prefs[$name] );
2729 // Multiselect and checkmatrix options are stored in the database with
2730 // one key per option, each having a boolean value. Extract those keys.
2731 $multiselectOptions = array();
2732 foreach ( $prefs as $name => $info ) {
2733 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2734 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2735 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2736 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2738 foreach ( $opts as $value ) {
2739 $multiselectOptions["$prefix$value"] = true;
2742 unset( $prefs[$name] );
2745 $checkmatrixOptions = array();
2746 foreach ( $prefs as $name => $info ) {
2747 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2748 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2749 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2750 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2751 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2753 foreach ( $columns as $column ) {
2754 foreach ( $rows as $row ) {
2755 $checkmatrixOptions["$prefix$column-$row"] = true;
2759 unset( $prefs[$name] );
2763 // $value is ignored
2764 foreach ( $options as $key => $value ) {
2765 if ( isset( $prefs[$key] ) ) {
2766 $mapping[$key] = 'registered';
2767 } elseif ( isset( $multiselectOptions[$key] ) ) {
2768 $mapping[$key] = 'registered-multiselect';
2769 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2770 $mapping[$key] = 'registered-checkmatrix';
2771 } elseif ( isset( $specialOptions[$key] ) ) {
2772 $mapping[$key] = 'special';
2773 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2774 $mapping[$key] = 'userjs';
2776 $mapping[$key] = 'unused';
2784 * Reset certain (or all) options to the site defaults
2786 * The optional parameter determines which kinds of preferences will be reset.
2787 * Supported values are everything that can be reported by getOptionKinds()
2788 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2790 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2791 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2792 * for backwards-compatibility.
2793 * @param IContextSource|null $context Context source used when $resetKinds
2794 * does not contain 'all', passed to getOptionKinds().
2795 * Defaults to RequestContext::getMain() when null.
2797 public function resetOptions(
2798 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2799 IContextSource
$context = null
2802 $defaultOptions = self
::getDefaultOptions();
2804 if ( !is_array( $resetKinds ) ) {
2805 $resetKinds = array( $resetKinds );
2808 if ( in_array( 'all', $resetKinds ) ) {
2809 $newOptions = $defaultOptions;
2811 if ( $context === null ) {
2812 $context = RequestContext
::getMain();
2815 $optionKinds = $this->getOptionKinds( $context );
2816 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2817 $newOptions = array();
2819 // Use default values for the options that should be deleted, and
2820 // copy old values for the ones that shouldn't.
2821 foreach ( $this->mOptions
as $key => $value ) {
2822 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2823 if ( array_key_exists( $key, $defaultOptions ) ) {
2824 $newOptions[$key] = $defaultOptions[$key];
2827 $newOptions[$key] = $value;
2832 Hooks
::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2834 $this->mOptions
= $newOptions;
2835 $this->mOptionsLoaded
= true;
2839 * Get the user's preferred date format.
2840 * @return string User's preferred date format
2842 public function getDatePreference() {
2843 // Important migration for old data rows
2844 if ( is_null( $this->mDatePreference
) ) {
2846 $value = $this->getOption( 'date' );
2847 $map = $wgLang->getDatePreferenceMigrationMap();
2848 if ( isset( $map[$value] ) ) {
2849 $value = $map[$value];
2851 $this->mDatePreference
= $value;
2853 return $this->mDatePreference
;
2857 * Determine based on the wiki configuration and the user's options,
2858 * whether this user must be over HTTPS no matter what.
2862 public function requiresHTTPS() {
2863 global $wgSecureLogin;
2864 if ( !$wgSecureLogin ) {
2867 $https = $this->getBoolOption( 'prefershttps' );
2868 Hooks
::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2870 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2877 * Get the user preferred stub threshold
2881 public function getStubThreshold() {
2882 global $wgMaxArticleSize; # Maximum article size, in Kb
2883 $threshold = $this->getIntOption( 'stubthreshold' );
2884 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2885 // If they have set an impossible value, disable the preference
2886 // so we can use the parser cache again.
2893 * Get the permissions this user has.
2894 * @return array Array of String permission names
2896 public function getRights() {
2897 if ( is_null( $this->mRights
) ) {
2898 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2899 Hooks
::run( 'UserGetRights', array( $this, &$this->mRights
) );
2900 // Force reindexation of rights when a hook has unset one of them
2901 $this->mRights
= array_values( array_unique( $this->mRights
) );
2903 return $this->mRights
;
2907 * Get the list of explicit group memberships this user has.
2908 * The implicit * and user groups are not included.
2909 * @return array Array of String internal group names
2911 public function getGroups() {
2913 $this->loadGroups();
2914 return $this->mGroups
;
2918 * Get the list of implicit group memberships this user has.
2919 * This includes all explicit groups, plus 'user' if logged in,
2920 * '*' for all accounts, and autopromoted groups
2921 * @param bool $recache Whether to avoid the cache
2922 * @return array Array of String internal group names
2924 public function getEffectiveGroups( $recache = false ) {
2925 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2926 $this->mEffectiveGroups
= array_unique( array_merge(
2927 $this->getGroups(), // explicit groups
2928 $this->getAutomaticGroups( $recache ) // implicit groups
2930 // Hook for additional groups
2931 Hooks
::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2932 // Force reindexation of groups when a hook has unset one of them
2933 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
2935 return $this->mEffectiveGroups
;
2939 * Get the list of implicit group memberships this user has.
2940 * This includes 'user' if logged in, '*' for all accounts,
2941 * and autopromoted groups
2942 * @param bool $recache Whether to avoid the cache
2943 * @return array Array of String internal group names
2945 public function getAutomaticGroups( $recache = false ) {
2946 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
2947 $this->mImplicitGroups
= array( '*' );
2948 if ( $this->getId() ) {
2949 $this->mImplicitGroups
[] = 'user';
2951 $this->mImplicitGroups
= array_unique( array_merge(
2952 $this->mImplicitGroups
,
2953 Autopromote
::getAutopromoteGroups( $this )
2957 // Assure data consistency with rights/groups,
2958 // as getEffectiveGroups() depends on this function
2959 $this->mEffectiveGroups
= null;
2962 return $this->mImplicitGroups
;
2966 * Returns the groups the user has belonged to.
2968 * The user may still belong to the returned groups. Compare with getGroups().
2970 * The function will not return groups the user had belonged to before MW 1.17
2972 * @return array Names of the groups the user has belonged to.
2974 public function getFormerGroups() {
2975 if ( is_null( $this->mFormerGroups
) ) {
2976 $dbr = wfGetDB( DB_MASTER
);
2977 $res = $dbr->select( 'user_former_groups',
2978 array( 'ufg_group' ),
2979 array( 'ufg_user' => $this->mId
),
2981 $this->mFormerGroups
= array();
2982 foreach ( $res as $row ) {
2983 $this->mFormerGroups
[] = $row->ufg_group
;
2986 return $this->mFormerGroups
;
2990 * Get the user's edit count.
2991 * @return int|null Null for anonymous users
2993 public function getEditCount() {
2994 if ( !$this->getId() ) {
2998 if ( $this->mEditCount
=== null ) {
2999 /* Populate the count, if it has not been populated yet */
3000 $dbr = wfGetDB( DB_SLAVE
);
3001 // check if the user_editcount field has been initialized
3002 $count = $dbr->selectField(
3003 'user', 'user_editcount',
3004 array( 'user_id' => $this->mId
),
3008 if ( $count === null ) {
3009 // it has not been initialized. do so.
3010 $count = $this->initEditCount();
3012 $this->mEditCount
= $count;
3014 return (int)$this->mEditCount
;
3018 * Add the user to the given group.
3019 * This takes immediate effect.
3020 * @param string $group Name of the group to add
3023 public function addGroup( $group ) {
3024 if ( !Hooks
::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3028 $dbw = wfGetDB( DB_MASTER
);
3029 if ( $this->getId() ) {
3030 $dbw->insert( 'user_groups',
3032 'ug_user' => $this->getID(),
3033 'ug_group' => $group,
3036 array( 'IGNORE' ) );
3039 $this->loadGroups();
3040 $this->mGroups
[] = $group;
3041 // In case loadGroups was not called before, we now have the right twice.
3042 // Get rid of the duplicate.
3043 $this->mGroups
= array_unique( $this->mGroups
);
3045 // Refresh the groups caches, and clear the rights cache so it will be
3046 // refreshed on the next call to $this->getRights().
3047 $this->getEffectiveGroups( true );
3048 $this->mRights
= null;
3050 $this->invalidateCache();
3056 * Remove the user from the given group.
3057 * This takes immediate effect.
3058 * @param string $group Name of the group to remove
3061 public function removeGroup( $group ) {
3063 if ( !Hooks
::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3067 $dbw = wfGetDB( DB_MASTER
);
3068 $dbw->delete( 'user_groups',
3070 'ug_user' => $this->getID(),
3071 'ug_group' => $group,
3074 // Remember that the user was in this group
3075 $dbw->insert( 'user_former_groups',
3077 'ufg_user' => $this->getID(),
3078 'ufg_group' => $group,
3084 $this->loadGroups();
3085 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3087 // Refresh the groups caches, and clear the rights cache so it will be
3088 // refreshed on the next call to $this->getRights().
3089 $this->getEffectiveGroups( true );
3090 $this->mRights
= null;
3092 $this->invalidateCache();
3098 * Get whether the user is logged in
3101 public function isLoggedIn() {
3102 return $this->getID() != 0;
3106 * Get whether the user is anonymous
3109 public function isAnon() {
3110 return !$this->isLoggedIn();
3114 * Check if user is allowed to access a feature / make an action
3116 * @param string $permissions,... Permissions to test
3117 * @return bool True if user is allowed to perform *any* of the given actions
3119 public function isAllowedAny( /*...*/ ) {
3120 $permissions = func_get_args();
3121 foreach ( $permissions as $permission ) {
3122 if ( $this->isAllowed( $permission ) ) {
3131 * @param string $permissions,... Permissions to test
3132 * @return bool True if the user is allowed to perform *all* of the given actions
3134 public function isAllowedAll( /*...*/ ) {
3135 $permissions = func_get_args();
3136 foreach ( $permissions as $permission ) {
3137 if ( !$this->isAllowed( $permission ) ) {
3145 * Internal mechanics of testing a permission
3146 * @param string $action
3149 public function isAllowed( $action = '' ) {
3150 if ( $action === '' ) {
3151 return true; // In the spirit of DWIM
3153 // Patrolling may not be enabled
3154 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3155 global $wgUseRCPatrol, $wgUseNPPatrol;
3156 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3160 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3161 // by misconfiguration: 0 == 'foo'
3162 return in_array( $action, $this->getRights(), true );
3166 * Check whether to enable recent changes patrol features for this user
3167 * @return bool True or false
3169 public function useRCPatrol() {
3170 global $wgUseRCPatrol;
3171 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3175 * Check whether to enable new pages patrol features for this user
3176 * @return bool True or false
3178 public function useNPPatrol() {
3179 global $wgUseRCPatrol, $wgUseNPPatrol;
3181 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3182 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3187 * Get the WebRequest object to use with this object
3189 * @return WebRequest
3191 public function getRequest() {
3192 if ( $this->mRequest
) {
3193 return $this->mRequest
;
3201 * Get the current skin, loading it if required
3202 * @return Skin The current skin
3203 * @todo FIXME: Need to check the old failback system [AV]
3204 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3206 public function getSkin() {
3207 wfDeprecated( __METHOD__
, '1.18' );
3208 return RequestContext
::getMain()->getSkin();
3212 * Get a WatchedItem for this user and $title.
3214 * @since 1.22 $checkRights parameter added
3215 * @param Title $title
3216 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3217 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3218 * @return WatchedItem
3220 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3221 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3223 if ( isset( $this->mWatchedItems
[$key] ) ) {
3224 return $this->mWatchedItems
[$key];
3227 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3228 $this->mWatchedItems
= array();
3231 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3232 return $this->mWatchedItems
[$key];
3236 * Check the watched status of an article.
3237 * @since 1.22 $checkRights parameter added
3238 * @param Title $title Title of the article to look at
3239 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3240 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3243 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3244 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3249 * @since 1.22 $checkRights parameter added
3250 * @param Title $title Title of the article to look at
3251 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3252 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3254 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3255 $this->getWatchedItem( $title, $checkRights )->addWatch();
3256 $this->invalidateCache();
3260 * Stop watching an article.
3261 * @since 1.22 $checkRights parameter added
3262 * @param Title $title Title of the article to look at
3263 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3264 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3266 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3267 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3268 $this->invalidateCache();
3272 * Clear the user's notification timestamp for the given title.
3273 * If e-notif e-mails are on, they will receive notification mails on
3274 * the next change of the page if it's watched etc.
3275 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3276 * @param Title $title Title of the article to look at
3277 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3279 public function clearNotification( &$title, $oldid = 0 ) {
3280 global $wgUseEnotif, $wgShowUpdatedMarker;
3282 // Do nothing if the database is locked to writes
3283 if ( wfReadOnly() ) {
3287 // Do nothing if not allowed to edit the watchlist
3288 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3292 // If we're working on user's talk page, we should update the talk page message indicator
3293 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3294 if ( !Hooks
::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3298 $nextid = $oldid ?
$title->getNextRevisionID( $oldid ) : null;
3300 if ( !$oldid ||
!$nextid ) {
3301 // If we're looking at the latest revision, we should definitely clear it
3302 $this->setNewtalk( false );
3304 // Otherwise we should update its revision, if it's present
3305 if ( $this->getNewtalk() ) {
3306 // Naturally the other one won't clear by itself
3307 $this->setNewtalk( false );
3308 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3313 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3317 if ( $this->isAnon() ) {
3318 // Nothing else to do...
3322 // Only update the timestamp if the page is being watched.
3323 // The query to find out if it is watched is cached both in memcached and per-invocation,
3324 // and when it does have to be executed, it can be on a slave
3325 // If this is the user's newtalk page, we always update the timestamp
3327 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3331 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3335 * Resets all of the given user's page-change notification timestamps.
3336 * If e-notif e-mails are on, they will receive notification mails on
3337 * the next change of any watched page.
3338 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3340 public function clearAllNotifications() {
3341 if ( wfReadOnly() ) {
3345 // Do nothing if not allowed to edit the watchlist
3346 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3350 global $wgUseEnotif, $wgShowUpdatedMarker;
3351 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3352 $this->setNewtalk( false );
3355 $id = $this->getId();
3357 $dbw = wfGetDB( DB_MASTER
);
3358 $dbw->update( 'watchlist',
3359 array( /* SET */ 'wl_notificationtimestamp' => null ),
3360 array( /* WHERE */ 'wl_user' => $id ),
3363 // We also need to clear here the "you have new message" notification for the own user_talk page;
3364 // it's cleared one page view later in WikiPage::doViewUpdates().
3369 * Set a cookie on the user's client. Wrapper for
3370 * WebResponse::setCookie
3371 * @param string $name Name of the cookie to set
3372 * @param string $value Value to set
3373 * @param int $exp Expiration time, as a UNIX time value;
3374 * if 0 or not specified, use the default $wgCookieExpiration
3375 * @param bool $secure
3376 * true: Force setting the secure attribute when setting the cookie
3377 * false: Force NOT setting the secure attribute when setting the cookie
3378 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3379 * @param array $params Array of options sent passed to WebResponse::setcookie()
3380 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3383 protected function setCookie(
3384 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3386 if ( $request === null ) {
3387 $request = $this->getRequest();
3389 $params['secure'] = $secure;
3390 $request->response()->setcookie( $name, $value, $exp, $params );
3394 * Clear a cookie on the user's client
3395 * @param string $name Name of the cookie to clear
3396 * @param bool $secure
3397 * true: Force setting the secure attribute when setting the cookie
3398 * false: Force NOT setting the secure attribute when setting the cookie
3399 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3400 * @param array $params Array of options sent passed to WebResponse::setcookie()
3402 protected function clearCookie( $name, $secure = null, $params = array() ) {
3403 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3407 * Set the default cookies for this session on the user's client.
3409 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3411 * @param bool $secure Whether to force secure/insecure cookies or use default
3412 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3414 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3415 if ( $request === null ) {
3416 $request = $this->getRequest();
3420 if ( 0 == $this->mId
) {
3423 if ( !$this->mToken
) {
3424 // When token is empty or NULL generate a new one and then save it to the database
3425 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3426 // Simply by setting every cell in the user_token column to NULL and letting them be
3427 // regenerated as users log back into the wiki.
3429 $this->saveSettings();
3432 'wsUserID' => $this->mId
,
3433 'wsToken' => $this->mToken
,
3434 'wsUserName' => $this->getName()
3437 'UserID' => $this->mId
,
3438 'UserName' => $this->getName(),
3440 if ( $rememberMe ) {
3441 $cookies['Token'] = $this->mToken
;
3443 $cookies['Token'] = false;
3446 Hooks
::run( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3448 foreach ( $session as $name => $value ) {
3449 $request->setSessionData( $name, $value );
3451 foreach ( $cookies as $name => $value ) {
3452 if ( $value === false ) {
3453 $this->clearCookie( $name );
3455 $this->setCookie( $name, $value, 0, $secure, array(), $request );
3460 * If wpStickHTTPS was selected, also set an insecure cookie that
3461 * will cause the site to redirect the user to HTTPS, if they access
3462 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3463 * as the one set by centralauth (bug 53538). Also set it to session, or
3464 * standard time setting, based on if rememberme was set.
3466 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3470 $rememberMe ?
0 : null,
3472 array( 'prefix' => '' ) // no prefix
3478 * Log this user out.
3480 public function logout() {
3481 if ( Hooks
::run( 'UserLogout', array( &$this ) ) ) {
3487 * Clear the user's cookies and session, and reset the instance cache.
3490 public function doLogout() {
3491 $this->clearInstanceCache( 'defaults' );
3493 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3495 $this->clearCookie( 'UserID' );
3496 $this->clearCookie( 'Token' );
3497 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3499 // Remember when user logged out, to prevent seeing cached pages
3500 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3504 * Save this user's settings into the database.
3505 * @todo Only rarely do all these fields need to be set!
3507 public function saveSettings() {
3511 $this->loadPasswords();
3512 if ( wfReadOnly() ) {
3515 if ( 0 == $this->mId
) {
3519 $this->mTouched
= self
::newTouchedTimestamp();
3520 if ( !$wgAuth->allowSetLocalPassword() ) {
3521 $this->mPassword
= self
::getPasswordFactory()->newFromCiphertext( null );
3524 $dbw = wfGetDB( DB_MASTER
);
3525 $dbw->update( 'user',
3527 'user_name' => $this->mName
,
3528 'user_password' => $this->mPassword
->toString(),
3529 'user_newpassword' => $this->mNewpassword
->toString(),
3530 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3531 'user_real_name' => $this->mRealName
,
3532 'user_email' => $this->mEmail
,
3533 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3534 'user_touched' => $dbw->timestamp( $this->mTouched
),
3535 'user_token' => strval( $this->mToken
),
3536 'user_email_token' => $this->mEmailToken
,
3537 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3538 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires
),
3539 ), array( /* WHERE */
3540 'user_id' => $this->mId
3544 $this->saveOptions();
3546 Hooks
::run( 'UserSaveSettings', array( $this ) );
3547 $this->clearSharedCache();
3548 $this->getUserPage()->invalidateCache();
3552 * If only this user's username is known, and it exists, return the user ID.
3555 public function idForName() {
3556 $s = trim( $this->getName() );
3561 $dbr = wfGetDB( DB_SLAVE
);
3562 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
3563 if ( $id === false ) {
3570 * Add a user to the database, return the user object
3572 * @param string $name Username to add
3573 * @param array $params Array of Strings Non-default parameters to save to
3574 * the database as user_* fields:
3575 * - password: The user's password hash. Password logins will be disabled
3576 * if this is omitted.
3577 * - newpassword: Hash for a temporary password that has been mailed to
3579 * - email: The user's email address.
3580 * - email_authenticated: The email authentication timestamp.
3581 * - real_name: The user's real name.
3582 * - options: An associative array of non-default options.
3583 * - token: Random authentication token. Do not set.
3584 * - registration: Registration timestamp. Do not set.
3586 * @return User|null User object, or null if the username already exists.
3588 public static function createNew( $name, $params = array() ) {
3591 $user->loadPasswords();
3592 $user->setToken(); // init token
3593 if ( isset( $params['options'] ) ) {
3594 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3595 unset( $params['options'] );
3597 $dbw = wfGetDB( DB_MASTER
);
3598 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3601 'user_id' => $seqVal,
3602 'user_name' => $name,
3603 'user_password' => $user->mPassword
->toString(),
3604 'user_newpassword' => $user->mNewpassword
->toString(),
3605 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3606 'user_email' => $user->mEmail
,
3607 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3608 'user_real_name' => $user->mRealName
,
3609 'user_token' => strval( $user->mToken
),
3610 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3611 'user_editcount' => 0,
3612 'user_touched' => $dbw->timestamp( self
::newTouchedTimestamp() ),
3614 foreach ( $params as $name => $value ) {
3615 $fields["user_$name"] = $value;
3617 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3618 if ( $dbw->affectedRows() ) {
3619 $newUser = User
::newFromId( $dbw->insertId() );
3627 * Add this existing user object to the database. If the user already
3628 * exists, a fatal status object is returned, and the user object is
3629 * initialised with the data from the database.
3631 * Previously, this function generated a DB error due to a key conflict
3632 * if the user already existed. Many extension callers use this function
3633 * in code along the lines of:
3635 * $user = User::newFromName( $name );
3636 * if ( !$user->isLoggedIn() ) {
3637 * $user->addToDatabase();
3639 * // do something with $user...
3641 * However, this was vulnerable to a race condition (bug 16020). By
3642 * initialising the user object if the user exists, we aim to support this
3643 * calling sequence as far as possible.
3645 * Note that if the user exists, this function will acquire a write lock,
3646 * so it is still advisable to make the call conditional on isLoggedIn(),
3647 * and to commit the transaction after calling.
3649 * @throws MWException
3652 public function addToDatabase() {
3654 $this->loadPasswords();
3655 if ( !$this->mToken
) {
3656 $this->setToken(); // init token
3659 $this->mTouched
= self
::newTouchedTimestamp();
3661 $dbw = wfGetDB( DB_MASTER
);
3662 $inWrite = $dbw->writesOrCallbacksPending();
3663 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3664 $dbw->insert( 'user',
3666 'user_id' => $seqVal,
3667 'user_name' => $this->mName
,
3668 'user_password' => $this->mPassword
->toString(),
3669 'user_newpassword' => $this->mNewpassword
->toString(),
3670 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3671 'user_email' => $this->mEmail
,
3672 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3673 'user_real_name' => $this->mRealName
,
3674 'user_token' => strval( $this->mToken
),
3675 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3676 'user_editcount' => 0,
3677 'user_touched' => $dbw->timestamp( $this->mTouched
),
3681 if ( !$dbw->affectedRows() ) {
3682 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3683 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3685 // Can't commit due to pending writes that may need atomicity.
3686 // This may cause some lock contention unlike the case below.
3687 $options = array( 'LOCK IN SHARE MODE' );
3688 $flags = self
::READ_LOCKING
;
3690 // Often, this case happens early in views before any writes when
3691 // using CentralAuth. It's should be OK to commit and break the snapshot.
3692 $dbw->commit( __METHOD__
, 'flush' );
3696 $this->mId
= $dbw->selectField( 'user', 'user_id',
3697 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3700 if ( $this->loadFromDatabase( $flags ) ) {
3705 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3706 "to insert user '{$this->mName}' row, but it was not present in select!" );
3708 return Status
::newFatal( 'userexists' );
3710 $this->mId
= $dbw->insertId();
3712 // Clear instance cache other than user table data, which is already accurate
3713 $this->clearInstanceCache();
3715 $this->saveOptions();
3716 return Status
::newGood();
3720 * If this user is logged-in and blocked,
3721 * block any IP address they've successfully logged in from.
3722 * @return bool A block was spread
3724 public function spreadAnyEditBlock() {
3725 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3726 return $this->spreadBlock();
3732 * If this (non-anonymous) user is blocked,
3733 * block the IP address they've successfully logged in from.
3734 * @return bool A block was spread
3736 protected function spreadBlock() {
3737 wfDebug( __METHOD__
. "()\n" );
3739 if ( $this->mId
== 0 ) {
3743 $userblock = Block
::newFromTarget( $this->getName() );
3744 if ( !$userblock ) {
3748 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3752 * Get whether the user is explicitly blocked from account creation.
3753 * @return bool|Block
3755 public function isBlockedFromCreateAccount() {
3756 $this->getBlockedStatus();
3757 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3758 return $this->mBlock
;
3761 # bug 13611: if the IP address the user is trying to create an account from is
3762 # blocked with createaccount disabled, prevent new account creation there even
3763 # when the user is logged in
3764 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3765 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3767 return $this->mBlockedFromCreateAccount
instanceof Block
3768 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3769 ?
$this->mBlockedFromCreateAccount
3774 * Get whether the user is blocked from using Special:Emailuser.
3777 public function isBlockedFromEmailuser() {
3778 $this->getBlockedStatus();
3779 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3783 * Get whether the user is allowed to create an account.
3786 public function isAllowedToCreateAccount() {
3787 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3791 * Get this user's personal page title.
3793 * @return Title User's personal page title
3795 public function getUserPage() {
3796 return Title
::makeTitle( NS_USER
, $this->getName() );
3800 * Get this user's talk page title.
3802 * @return Title User's talk page title
3804 public function getTalkPage() {
3805 $title = $this->getUserPage();
3806 return $title->getTalkPage();
3810 * Determine whether the user is a newbie. Newbies are either
3811 * anonymous IPs, or the most recently created accounts.
3814 public function isNewbie() {
3815 return !$this->isAllowed( 'autoconfirmed' );
3819 * Check to see if the given clear-text password is one of the accepted passwords
3820 * @param string $password User password
3821 * @return bool True if the given password is correct, otherwise False
3823 public function checkPassword( $password ) {
3824 global $wgAuth, $wgLegacyEncoding;
3826 $this->loadPasswords();
3828 // Certain authentication plugins do NOT want to save
3829 // domain passwords in a mysql database, so we should
3830 // check this (in case $wgAuth->strict() is false).
3831 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3833 } elseif ( $wgAuth->strict() ) {
3834 // Auth plugin doesn't allow local authentication
3836 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3837 // Auth plugin doesn't allow local authentication for this user name
3841 if ( !$this->mPassword
->equals( $password ) ) {
3842 if ( $wgLegacyEncoding ) {
3843 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3844 // Check for this with iconv
3845 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3846 if ( $cp1252Password === $password ||
!$this->mPassword
->equals( $cp1252Password ) ) {
3854 $passwordFactory = self
::getPasswordFactory();
3855 if ( $passwordFactory->needsUpdate( $this->mPassword
) ) {
3856 $this->mPassword
= $passwordFactory->newFromPlaintext( $password );
3857 $this->saveSettings();
3864 * Check if the given clear-text password matches the temporary password
3865 * sent by e-mail for password reset operations.
3867 * @param string $plaintext
3869 * @return bool True if matches, false otherwise
3871 public function checkTemporaryPassword( $plaintext ) {
3872 global $wgNewPasswordExpiry;
3875 $this->loadPasswords();
3876 if ( $this->mNewpassword
->equals( $plaintext ) ) {
3877 if ( is_null( $this->mNewpassTime
) ) {
3880 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3881 return ( time() < $expiry );
3888 * Alias for getEditToken.
3889 * @deprecated since 1.19, use getEditToken instead.
3891 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3892 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3893 * @return string The new edit token
3895 public function editToken( $salt = '', $request = null ) {
3896 wfDeprecated( __METHOD__
, '1.19' );
3897 return $this->getEditToken( $salt, $request );
3901 * Internal implementation for self::getEditToken() and
3902 * self::matchEditToken().
3904 * @param string|array $salt
3905 * @param WebRequest $request
3906 * @param string|int $timestamp
3909 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
3910 if ( $this->isAnon() ) {
3911 return self
::EDIT_TOKEN_SUFFIX
;
3913 $token = $request->getSessionData( 'wsEditToken' );
3914 if ( $token === null ) {
3915 $token = MWCryptRand
::generateHex( 32 );
3916 $request->setSessionData( 'wsEditToken', $token );
3918 if ( is_array( $salt ) ) {
3919 $salt = implode( '|', $salt );
3921 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
3922 dechex( $timestamp ) .
3923 self
::EDIT_TOKEN_SUFFIX
;
3928 * Initialize (if necessary) and return a session token value
3929 * which can be used in edit forms to show that the user's
3930 * login credentials aren't being hijacked with a foreign form
3935 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3936 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3937 * @return string The new edit token
3939 public function getEditToken( $salt = '', $request = null ) {
3940 return $this->getEditTokenAtTimestamp(
3941 $salt, $request ?
: $this->getRequest(), wfTimestamp()
3946 * Generate a looking random token for various uses.
3948 * @return string The new random token
3949 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
3950 * wfRandomString for pseudo-randomness.
3952 public static function generateToken() {
3953 return MWCryptRand
::generateHex( 32 );
3957 * Get the embedded timestamp from a token.
3958 * @param string $val Input token
3961 public static function getEditTokenTimestamp( $val ) {
3962 $suffixLen = strlen( self
::EDIT_TOKEN_SUFFIX
);
3963 if ( strlen( $val ) <= 32 +
$suffixLen ) {
3967 return hexdec( substr( $val, 32, -$suffixLen ) );
3971 * Check given value against the token value stored in the session.
3972 * A match should confirm that the form was submitted from the
3973 * user's own login session, not a form submission from a third-party
3976 * @param string $val Input value to compare
3977 * @param string $salt Optional function-specific data for hashing
3978 * @param WebRequest|null $request Object to use or null to use $wgRequest
3979 * @param int $maxage Fail tokens older than this, in seconds
3980 * @return bool Whether the token matches
3982 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
3983 if ( $this->isAnon() ) {
3984 return $val === self
::EDIT_TOKEN_SUFFIX
;
3987 $timestamp = self
::getEditTokenTimestamp( $val );
3988 if ( $timestamp === null ) {
3991 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
3996 $sessionToken = $this->getEditTokenAtTimestamp(
3997 $salt, $request ?
: $this->getRequest(), $timestamp
4000 if ( $val != $sessionToken ) {
4001 wfDebug( "User::matchEditToken: broken session data\n" );
4004 return hash_equals( $sessionToken, $val );
4008 * Check given value against the token value stored in the session,
4009 * ignoring the suffix.
4011 * @param string $val Input value to compare
4012 * @param string $salt Optional function-specific data for hashing
4013 * @param WebRequest|null $request Object to use or null to use $wgRequest
4014 * @param int $maxage Fail tokens older than this, in seconds
4015 * @return bool Whether the token matches
4017 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4018 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4019 return $this->matchEditToken( $val, $salt, $request, $maxage );
4023 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4024 * mail to the user's given address.
4026 * @param string $type Message to send, either "created", "changed" or "set"
4029 public function sendConfirmationMail( $type = 'created' ) {
4031 $expiration = null; // gets passed-by-ref and defined in next line.
4032 $token = $this->confirmationToken( $expiration );
4033 $url = $this->confirmationTokenUrl( $token );
4034 $invalidateURL = $this->invalidationTokenUrl( $token );
4035 $this->saveSettings();
4037 if ( $type == 'created' ||
$type === false ) {
4038 $message = 'confirmemail_body';
4039 } elseif ( $type === true ) {
4040 $message = 'confirmemail_body_changed';
4042 // Messages: confirmemail_body_changed, confirmemail_body_set
4043 $message = 'confirmemail_body_' . $type;
4046 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4047 wfMessage( $message,
4048 $this->getRequest()->getIP(),
4051 $wgLang->timeanddate( $expiration, false ),
4053 $wgLang->date( $expiration, false ),
4054 $wgLang->time( $expiration, false ) )->text() );
4058 * Send an e-mail to this user's account. Does not check for
4059 * confirmed status or validity.
4061 * @param string $subject Message subject
4062 * @param string $body Message body
4063 * @param string $from Optional From address; if unspecified, default
4064 * $wgPasswordSender will be used.
4065 * @param string $replyto Reply-To address
4068 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4069 if ( is_null( $from ) ) {
4070 global $wgPasswordSender;
4071 $sender = new MailAddress( $wgPasswordSender,
4072 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4074 $sender = MailAddress
::newFromUser( $from );
4077 $to = MailAddress
::newFromUser( $this );
4078 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
4082 * Generate, store, and return a new e-mail confirmation code.
4083 * A hash (unsalted, since it's used as a key) is stored.
4085 * @note Call saveSettings() after calling this function to commit
4086 * this change to the database.
4088 * @param string &$expiration Accepts the expiration time
4089 * @return string New token
4091 protected function confirmationToken( &$expiration ) {
4092 global $wgUserEmailConfirmationTokenExpiry;
4094 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4095 $expiration = wfTimestamp( TS_MW
, $expires );
4097 $token = MWCryptRand
::generateHex( 32 );
4098 $hash = md5( $token );
4099 $this->mEmailToken
= $hash;
4100 $this->mEmailTokenExpires
= $expiration;
4105 * Return a URL the user can use to confirm their email address.
4106 * @param string $token Accepts the email confirmation token
4107 * @return string New token URL
4109 protected function confirmationTokenUrl( $token ) {
4110 return $this->getTokenUrl( 'ConfirmEmail', $token );
4114 * Return a URL the user can use to invalidate their email address.
4115 * @param string $token Accepts the email confirmation token
4116 * @return string New token URL
4118 protected function invalidationTokenUrl( $token ) {
4119 return $this->getTokenUrl( 'InvalidateEmail', $token );
4123 * Internal function to format the e-mail validation/invalidation URLs.
4124 * This uses a quickie hack to use the
4125 * hardcoded English names of the Special: pages, for ASCII safety.
4127 * @note Since these URLs get dropped directly into emails, using the
4128 * short English names avoids insanely long URL-encoded links, which
4129 * also sometimes can get corrupted in some browsers/mailers
4130 * (bug 6957 with Gmail and Internet Explorer).
4132 * @param string $page Special page
4133 * @param string $token Token
4134 * @return string Formatted URL
4136 protected function getTokenUrl( $page, $token ) {
4137 // Hack to bypass localization of 'Special:'
4138 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4139 return $title->getCanonicalURL();
4143 * Mark the e-mail address confirmed.
4145 * @note Call saveSettings() after calling this function to commit the change.
4149 public function confirmEmail() {
4150 // Check if it's already confirmed, so we don't touch the database
4151 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4152 if ( !$this->isEmailConfirmed() ) {
4153 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4154 Hooks
::run( 'ConfirmEmailComplete', array( $this ) );
4160 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4161 * address if it was already confirmed.
4163 * @note Call saveSettings() after calling this function to commit the change.
4164 * @return bool Returns true
4166 public function invalidateEmail() {
4168 $this->mEmailToken
= null;
4169 $this->mEmailTokenExpires
= null;
4170 $this->setEmailAuthenticationTimestamp( null );
4172 Hooks
::run( 'InvalidateEmailComplete', array( $this ) );
4177 * Set the e-mail authentication timestamp.
4178 * @param string $timestamp TS_MW timestamp
4180 public function setEmailAuthenticationTimestamp( $timestamp ) {
4182 $this->mEmailAuthenticated
= $timestamp;
4183 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4187 * Is this user allowed to send e-mails within limits of current
4188 * site configuration?
4191 public function canSendEmail() {
4192 global $wgEnableEmail, $wgEnableUserEmail;
4193 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4196 $canSend = $this->isEmailConfirmed();
4197 Hooks
::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4202 * Is this user allowed to receive e-mails within limits of current
4203 * site configuration?
4206 public function canReceiveEmail() {
4207 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4211 * Is this user's e-mail address valid-looking and confirmed within
4212 * limits of the current site configuration?
4214 * @note If $wgEmailAuthentication is on, this may require the user to have
4215 * confirmed their address by returning a code or using a password
4216 * sent to the address from the wiki.
4220 public function isEmailConfirmed() {
4221 global $wgEmailAuthentication;
4224 if ( Hooks
::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4225 if ( $this->isAnon() ) {
4228 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4231 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4241 * Check whether there is an outstanding request for e-mail confirmation.
4244 public function isEmailConfirmationPending() {
4245 global $wgEmailAuthentication;
4246 return $wgEmailAuthentication &&
4247 !$this->isEmailConfirmed() &&
4248 $this->mEmailToken
&&
4249 $this->mEmailTokenExpires
> wfTimestamp();
4253 * Get the timestamp of account creation.
4255 * @return string|bool|null Timestamp of account creation, false for
4256 * non-existent/anonymous user accounts, or null if existing account
4257 * but information is not in database.
4259 public function getRegistration() {
4260 if ( $this->isAnon() ) {
4264 return $this->mRegistration
;
4268 * Get the timestamp of the first edit
4270 * @return string|bool Timestamp of first edit, or false for
4271 * non-existent/anonymous user accounts.
4273 public function getFirstEditTimestamp() {
4274 if ( $this->getId() == 0 ) {
4275 return false; // anons
4277 $dbr = wfGetDB( DB_SLAVE
);
4278 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4279 array( 'rev_user' => $this->getId() ),
4281 array( 'ORDER BY' => 'rev_timestamp ASC' )
4284 return false; // no edits
4286 return wfTimestamp( TS_MW
, $time );
4290 * Get the permissions associated with a given list of groups
4292 * @param array $groups Array of Strings List of internal group names
4293 * @return array Array of Strings List of permission key names for given groups combined
4295 public static function getGroupPermissions( $groups ) {
4296 global $wgGroupPermissions, $wgRevokePermissions;
4298 // grant every granted permission first
4299 foreach ( $groups as $group ) {
4300 if ( isset( $wgGroupPermissions[$group] ) ) {
4301 $rights = array_merge( $rights,
4302 // array_filter removes empty items
4303 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4306 // now revoke the revoked permissions
4307 foreach ( $groups as $group ) {
4308 if ( isset( $wgRevokePermissions[$group] ) ) {
4309 $rights = array_diff( $rights,
4310 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4313 return array_unique( $rights );
4317 * Get all the groups who have a given permission
4319 * @param string $role Role to check
4320 * @return array Array of Strings List of internal group names with the given permission
4322 public static function getGroupsWithPermission( $role ) {
4323 global $wgGroupPermissions;
4324 $allowedGroups = array();
4325 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4326 if ( self
::groupHasPermission( $group, $role ) ) {
4327 $allowedGroups[] = $group;
4330 return $allowedGroups;
4334 * Check, if the given group has the given permission
4336 * If you're wanting to check whether all users have a permission, use
4337 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4341 * @param string $group Group to check
4342 * @param string $role Role to check
4345 public static function groupHasPermission( $group, $role ) {
4346 global $wgGroupPermissions, $wgRevokePermissions;
4347 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4348 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4352 * Check if all users have the given permission
4355 * @param string $right Right to check
4358 public static function isEveryoneAllowed( $right ) {
4359 global $wgGroupPermissions, $wgRevokePermissions;
4360 static $cache = array();
4362 // Use the cached results, except in unit tests which rely on
4363 // being able change the permission mid-request
4364 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4365 return $cache[$right];
4368 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4369 $cache[$right] = false;
4373 // If it's revoked anywhere, then everyone doesn't have it
4374 foreach ( $wgRevokePermissions as $rights ) {
4375 if ( isset( $rights[$right] ) && $rights[$right] ) {
4376 $cache[$right] = false;
4381 // Allow extensions (e.g. OAuth) to say false
4382 if ( !Hooks
::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4383 $cache[$right] = false;
4387 $cache[$right] = true;
4392 * Get the localized descriptive name for a group, if it exists
4394 * @param string $group Internal group name
4395 * @return string Localized descriptive group name
4397 public static function getGroupName( $group ) {
4398 $msg = wfMessage( "group-$group" );
4399 return $msg->isBlank() ?
$group : $msg->text();
4403 * Get the localized descriptive name for a member of a group, if it exists
4405 * @param string $group Internal group name
4406 * @param string $username Username for gender (since 1.19)
4407 * @return string Localized name for group member
4409 public static function getGroupMember( $group, $username = '#' ) {
4410 $msg = wfMessage( "group-$group-member", $username );
4411 return $msg->isBlank() ?
$group : $msg->text();
4415 * Return the set of defined explicit groups.
4416 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4417 * are not included, as they are defined automatically, not in the database.
4418 * @return array Array of internal group names
4420 public static function getAllGroups() {
4421 global $wgGroupPermissions, $wgRevokePermissions;
4423 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4424 self
::getImplicitGroups()
4429 * Get a list of all available permissions.
4430 * @return string[] Array of permission names
4432 public static function getAllRights() {
4433 if ( self
::$mAllRights === false ) {
4434 global $wgAvailableRights;
4435 if ( count( $wgAvailableRights ) ) {
4436 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4438 self
::$mAllRights = self
::$mCoreRights;
4440 Hooks
::run( 'UserGetAllRights', array( &self
::$mAllRights ) );
4442 return self
::$mAllRights;
4446 * Get a list of implicit groups
4447 * @return array Array of Strings Array of internal group names
4449 public static function getImplicitGroups() {
4450 global $wgImplicitGroups;
4452 $groups = $wgImplicitGroups;
4453 # Deprecated, use $wgImplicitGroups instead
4454 Hooks
::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4460 * Get the title of a page describing a particular group
4462 * @param string $group Internal group name
4463 * @return Title|bool Title of the page if it exists, false otherwise
4465 public static function getGroupPage( $group ) {
4466 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4467 if ( $msg->exists() ) {
4468 $title = Title
::newFromText( $msg->text() );
4469 if ( is_object( $title ) ) {
4477 * Create a link to the group in HTML, if available;
4478 * else return the group name.
4480 * @param string $group Internal name of the group
4481 * @param string $text The text of the link
4482 * @return string HTML link to the group
4484 public static function makeGroupLinkHTML( $group, $text = '' ) {
4485 if ( $text == '' ) {
4486 $text = self
::getGroupName( $group );
4488 $title = self
::getGroupPage( $group );
4490 return Linker
::link( $title, htmlspecialchars( $text ) );
4492 return htmlspecialchars( $text );
4497 * Create a link to the group in Wikitext, if available;
4498 * else return the group name.
4500 * @param string $group Internal name of the group
4501 * @param string $text The text of the link
4502 * @return string Wikilink to the group
4504 public static function makeGroupLinkWiki( $group, $text = '' ) {
4505 if ( $text == '' ) {
4506 $text = self
::getGroupName( $group );
4508 $title = self
::getGroupPage( $group );
4510 $page = $title->getFullText();
4511 return "[[$page|$text]]";
4518 * Returns an array of the groups that a particular group can add/remove.
4520 * @param string $group The group to check for whether it can add/remove
4521 * @return array Array( 'add' => array( addablegroups ),
4522 * 'remove' => array( removablegroups ),
4523 * 'add-self' => array( addablegroups to self),
4524 * 'remove-self' => array( removable groups from self) )
4526 public static function changeableByGroup( $group ) {
4527 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4531 'remove' => array(),
4532 'add-self' => array(),
4533 'remove-self' => array()
4536 if ( empty( $wgAddGroups[$group] ) ) {
4537 // Don't add anything to $groups
4538 } elseif ( $wgAddGroups[$group] === true ) {
4539 // You get everything
4540 $groups['add'] = self
::getAllGroups();
4541 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4542 $groups['add'] = $wgAddGroups[$group];
4545 // Same thing for remove
4546 if ( empty( $wgRemoveGroups[$group] ) ) {
4548 } elseif ( $wgRemoveGroups[$group] === true ) {
4549 $groups['remove'] = self
::getAllGroups();
4550 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4551 $groups['remove'] = $wgRemoveGroups[$group];
4554 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4555 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4556 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4557 if ( is_int( $key ) ) {
4558 $wgGroupsAddToSelf['user'][] = $value;
4563 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4564 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4565 if ( is_int( $key ) ) {
4566 $wgGroupsRemoveFromSelf['user'][] = $value;
4571 // Now figure out what groups the user can add to him/herself
4572 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4574 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4575 // No idea WHY this would be used, but it's there
4576 $groups['add-self'] = User
::getAllGroups();
4577 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4578 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4581 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4583 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4584 $groups['remove-self'] = User
::getAllGroups();
4585 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4586 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4593 * Returns an array of groups that this user can add and remove
4594 * @return array Array( 'add' => array( addablegroups ),
4595 * 'remove' => array( removablegroups ),
4596 * 'add-self' => array( addablegroups to self),
4597 * 'remove-self' => array( removable groups from self) )
4599 public function changeableGroups() {
4600 if ( $this->isAllowed( 'userrights' ) ) {
4601 // This group gives the right to modify everything (reverse-
4602 // compatibility with old "userrights lets you change
4604 // Using array_merge to make the groups reindexed
4605 $all = array_merge( User
::getAllGroups() );
4609 'add-self' => array(),
4610 'remove-self' => array()
4614 // Okay, it's not so simple, we will have to go through the arrays
4617 'remove' => array(),
4618 'add-self' => array(),
4619 'remove-self' => array()
4621 $addergroups = $this->getEffectiveGroups();
4623 foreach ( $addergroups as $addergroup ) {
4624 $groups = array_merge_recursive(
4625 $groups, $this->changeableByGroup( $addergroup )
4627 $groups['add'] = array_unique( $groups['add'] );
4628 $groups['remove'] = array_unique( $groups['remove'] );
4629 $groups['add-self'] = array_unique( $groups['add-self'] );
4630 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4636 * Increment the user's edit-count field.
4637 * Will have no effect for anonymous users.
4639 public function incEditCount() {
4640 if ( !$this->isAnon() ) {
4641 $dbw = wfGetDB( DB_MASTER
);
4644 array( 'user_editcount=user_editcount+1' ),
4645 array( 'user_id' => $this->getId() ),
4649 // Lazy initialization check...
4650 if ( $dbw->affectedRows() == 0 ) {
4651 // Now here's a goddamn hack...
4652 $dbr = wfGetDB( DB_SLAVE
);
4653 if ( $dbr !== $dbw ) {
4654 // If we actually have a slave server, the count is
4655 // at least one behind because the current transaction
4656 // has not been committed and replicated.
4657 $this->initEditCount( 1 );
4659 // But if DB_SLAVE is selecting the master, then the
4660 // count we just read includes the revision that was
4661 // just added in the working transaction.
4662 $this->initEditCount();
4666 // edit count in user cache too
4667 $this->invalidateCache();
4671 * Initialize user_editcount from data out of the revision table
4673 * @param int $add Edits to add to the count from the revision table
4674 * @return int Number of edits
4676 protected function initEditCount( $add = 0 ) {
4677 // Pull from a slave to be less cruel to servers
4678 // Accuracy isn't the point anyway here
4679 $dbr = wfGetDB( DB_SLAVE
);
4680 $count = (int)$dbr->selectField(
4683 array( 'rev_user' => $this->getId() ),
4686 $count = $count +
$add;
4688 $dbw = wfGetDB( DB_MASTER
);
4691 array( 'user_editcount' => $count ),
4692 array( 'user_id' => $this->getId() ),
4700 * Get the description of a given right
4702 * @param string $right Right to query
4703 * @return string Localized description of the right
4705 public static function getRightDescription( $right ) {
4706 $key = "right-$right";
4707 $msg = wfMessage( $key );
4708 return $msg->isBlank() ?
$right : $msg->text();
4712 * Make a new-style password hash
4714 * @param string $password Plain-text password
4715 * @param bool|string $salt Optional salt, may be random or the user ID.
4716 * If unspecified or false, will generate one automatically
4717 * @return string Password hash
4718 * @deprecated since 1.24, use Password class
4720 public static function crypt( $password, $salt = false ) {
4721 wfDeprecated( __METHOD__
, '1.24' );
4722 $hash = self
::getPasswordFactory()->newFromPlaintext( $password );
4723 return $hash->toString();
4727 * Compare a password hash with a plain-text password. Requires the user
4728 * ID if there's a chance that the hash is an old-style hash.
4730 * @param string $hash Password hash
4731 * @param string $password Plain-text password to compare
4732 * @param string|bool $userId User ID for old-style password salt
4735 * @deprecated since 1.24, use Password class
4737 public static function comparePasswords( $hash, $password, $userId = false ) {
4738 wfDeprecated( __METHOD__
, '1.24' );
4740 // Check for *really* old password hashes that don't even have a type
4741 // The old hash format was just an md5 hex hash, with no type information
4742 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4743 global $wgPasswordSalt;
4744 if ( $wgPasswordSalt ) {
4745 $password = ":B:{$userId}:{$hash}";
4747 $password = ":A:{$hash}";
4751 $hash = self
::getPasswordFactory()->newFromCiphertext( $hash );
4752 return $hash->equals( $password );
4756 * Add a newuser log entry for this user.
4757 * Before 1.19 the return value was always true.
4759 * @param string|bool $action Account creation type.
4760 * - String, one of the following values:
4761 * - 'create' for an anonymous user creating an account for himself.
4762 * This will force the action's performer to be the created user itself,
4763 * no matter the value of $wgUser
4764 * - 'create2' for a logged in user creating an account for someone else
4765 * - 'byemail' when the created user will receive its password by e-mail
4766 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4767 * - Boolean means whether the account was created by e-mail (deprecated):
4768 * - true will be converted to 'byemail'
4769 * - false will be converted to 'create' if this object is the same as
4770 * $wgUser and to 'create2' otherwise
4772 * @param string $reason User supplied reason
4774 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4776 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4777 global $wgUser, $wgNewUserLog;
4778 if ( empty( $wgNewUserLog ) ) {
4779 return true; // disabled
4782 if ( $action === true ) {
4783 $action = 'byemail';
4784 } elseif ( $action === false ) {
4785 if ( $this->equals( $wgUser ) ) {
4788 $action = 'create2';
4792 if ( $action === 'create' ||
$action === 'autocreate' ) {
4795 $performer = $wgUser;
4798 $logEntry = new ManualLogEntry( 'newusers', $action );
4799 $logEntry->setPerformer( $performer );
4800 $logEntry->setTarget( $this->getUserPage() );
4801 $logEntry->setComment( $reason );
4802 $logEntry->setParameters( array(
4803 '4::userid' => $this->getId(),
4805 $logid = $logEntry->insert();
4807 if ( $action !== 'autocreate' ) {
4808 $logEntry->publish( $logid );
4815 * Add an autocreate newuser log entry for this user
4816 * Used by things like CentralAuth and perhaps other authplugins.
4817 * Consider calling addNewUserLogEntry() directly instead.
4821 public function addNewUserLogEntryAutoCreate() {
4822 $this->addNewUserLogEntry( 'autocreate' );
4828 * Load the user options either from cache, the database or an array
4830 * @param array $data Rows for the current user out of the user_properties table
4832 protected function loadOptions( $data = null ) {
4837 if ( $this->mOptionsLoaded
) {
4841 $this->mOptions
= self
::getDefaultOptions();
4843 if ( !$this->getId() ) {
4844 // For unlogged-in users, load language/variant options from request.
4845 // There's no need to do it for logged-in users: they can set preferences,
4846 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4847 // so don't override user's choice (especially when the user chooses site default).
4848 $variant = $wgContLang->getDefaultVariant();
4849 $this->mOptions
['variant'] = $variant;
4850 $this->mOptions
['language'] = $variant;
4851 $this->mOptionsLoaded
= true;
4855 // Maybe load from the object
4856 if ( !is_null( $this->mOptionOverrides
) ) {
4857 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4858 foreach ( $this->mOptionOverrides
as $key => $value ) {
4859 $this->mOptions
[$key] = $value;
4862 if ( !is_array( $data ) ) {
4863 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4864 // Load from database
4865 $dbr = wfGetDB( DB_SLAVE
);
4867 $res = $dbr->select(
4869 array( 'up_property', 'up_value' ),
4870 array( 'up_user' => $this->getId() ),
4874 $this->mOptionOverrides
= array();
4876 foreach ( $res as $row ) {
4877 $data[$row->up_property
] = $row->up_value
;
4880 foreach ( $data as $property => $value ) {
4881 $this->mOptionOverrides
[$property] = $value;
4882 $this->mOptions
[$property] = $value;
4886 $this->mOptionsLoaded
= true;
4888 Hooks
::run( 'UserLoadOptions', array( $this, &$this->mOptions
) );
4892 * Saves the non-default options for this user, as previously set e.g. via
4893 * setOption(), in the database's "user_properties" (preferences) table.
4894 * Usually used via saveSettings().
4896 protected function saveOptions() {
4897 $this->loadOptions();
4899 // Not using getOptions(), to keep hidden preferences in database
4900 $saveOptions = $this->mOptions
;
4902 // Allow hooks to abort, for instance to save to a global profile.
4903 // Reset options to default state before saving.
4904 if ( !Hooks
::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4908 $userId = $this->getId();
4910 $insert_rows = array(); // all the new preference rows
4911 foreach ( $saveOptions as $key => $value ) {
4912 // Don't bother storing default values
4913 $defaultOption = self
::getDefaultOption( $key );
4914 if ( ( $defaultOption === null && $value !== false && $value !== null )
4915 ||
$value != $defaultOption
4917 $insert_rows[] = array(
4918 'up_user' => $userId,
4919 'up_property' => $key,
4920 'up_value' => $value,
4925 $dbw = wfGetDB( DB_MASTER
);
4927 $res = $dbw->select( 'user_properties',
4928 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
4930 // Find prior rows that need to be removed or updated. These rows will
4931 // all be deleted (the later so that INSERT IGNORE applies the new values).
4932 $keysDelete = array();
4933 foreach ( $res as $row ) {
4934 if ( !isset( $saveOptions[$row->up_property
] )
4935 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
4937 $keysDelete[] = $row->up_property
;
4941 if ( count( $keysDelete ) ) {
4942 // Do the DELETE by PRIMARY KEY for prior rows.
4943 // In the past a very large portion of calls to this function are for setting
4944 // 'rememberpassword' for new accounts (a preference that has since been removed).
4945 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4946 // caused gap locks on [max user ID,+infinity) which caused high contention since
4947 // updates would pile up on each other as they are for higher (newer) user IDs.
4948 // It might not be necessary these days, but it shouldn't hurt either.
4949 $dbw->delete( 'user_properties',
4950 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
4952 // Insert the new preference rows
4953 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
4957 * Lazily instantiate and return a factory object for making passwords
4959 * @return PasswordFactory
4961 public static function getPasswordFactory() {
4962 if ( self
::$mPasswordFactory === null ) {
4963 self
::$mPasswordFactory = new PasswordFactory();
4964 self
::$mPasswordFactory->init( RequestContext
::getMain()->getConfig() );
4967 return self
::$mPasswordFactory;
4971 * Provide an array of HTML5 attributes to put on an input element
4972 * intended for the user to enter a new password. This may include
4973 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4975 * Do *not* use this when asking the user to enter his current password!
4976 * Regardless of configuration, users may have invalid passwords for whatever
4977 * reason (e.g., they were set before requirements were tightened up).
4978 * Only use it when asking for a new password, like on account creation or
4981 * Obviously, you still need to do server-side checking.
4983 * NOTE: A combination of bugs in various browsers means that this function
4984 * actually just returns array() unconditionally at the moment. May as
4985 * well keep it around for when the browser bugs get fixed, though.
4987 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4989 * @return array Array of HTML attributes suitable for feeding to
4990 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4991 * That will get confused by the boolean attribute syntax used.)
4993 public static function passwordChangeInputAttribs() {
4994 global $wgMinimalPasswordLength;
4996 if ( $wgMinimalPasswordLength == 0 ) {
5000 # Note that the pattern requirement will always be satisfied if the
5001 # input is empty, so we need required in all cases.
5003 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5004 # if e-mail confirmation is being used. Since HTML5 input validation
5005 # is b0rked anyway in some browsers, just return nothing. When it's
5006 # re-enabled, fix this code to not output required for e-mail
5008 #$ret = array( 'required' );
5011 # We can't actually do this right now, because Opera 9.6 will print out
5012 # the entered password visibly in its error message! When other
5013 # browsers add support for this attribute, or Opera fixes its support,
5014 # we can add support with a version check to avoid doing this on Opera
5015 # versions where it will be a problem. Reported to Opera as
5016 # DSK-262266, but they don't have a public bug tracker for us to follow.
5018 if ( $wgMinimalPasswordLength > 1 ) {
5019 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5020 $ret['title'] = wfMessage( 'passwordtooshort' )
5021 ->numParams( $wgMinimalPasswordLength )->text();
5029 * Return the list of user fields that should be selected to create
5030 * a new user object.
5033 public static function selectFields() {
5041 'user_email_authenticated',
5043 'user_email_token_expires',
5044 'user_registration',
5050 * Factory function for fatal permission-denied errors
5053 * @param string $permission User right required
5056 static function newFatalPermissionDeniedStatus( $permission ) {
5059 $groups = array_map(
5060 array( 'User', 'makeGroupLinkWiki' ),
5061 User
::getGroupsWithPermission( $permission )
5065 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5067 return Status
::newFatal( 'badaccess-group0' );
5072 * Checks if two user objects point to the same user.
5078 public function equals( User
$user ) {
5079 return $this->getName() === $user->getName();