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(
132 'editusercssjs', #deprecated
145 'move-categorypages',
146 'move-rootuserpages',
150 'override-export-depth',
174 'userrights-interwiki',
182 * String Cached results of getAllRights()
184 protected static $mAllRights = false;
186 /** @name Cache variables */
195 * @todo Make this actually private
201 * @todo Make this actually private
204 public $mNewpassword;
206 public $mNewpassTime;
209 /** @var string TS_MW timestamp from the DB */
211 /** @var string TS_MW timestamp from cache */
212 protected $mQuickTouched;
216 public $mEmailAuthenticated;
218 protected $mEmailToken;
220 protected $mEmailTokenExpires;
222 protected $mRegistration;
224 protected $mEditCount;
228 protected $mOptionOverrides;
230 protected $mPasswordExpires;
234 * Bool Whether the cache variables have been loaded.
237 public $mOptionsLoaded;
240 * Array with already loaded items or true if all items have been loaded.
242 protected $mLoadedItems = array();
246 * String Initialization data source if mLoadedItems!==true. May be one of:
247 * - 'defaults' anonymous user initialised from class defaults
248 * - 'name' initialise from mName
249 * - 'id' initialise from mId
250 * - 'session' log in from cookies or session if possible
252 * Use the User::newFrom*() family of functions to set this.
257 * Lazy-initialized variables, invalidated with clearInstanceCache
261 protected $mDatePreference;
269 protected $mBlockreason;
271 protected $mEffectiveGroups;
273 protected $mImplicitGroups;
275 protected $mFormerGroups;
277 protected $mBlockedGlobally;
294 protected $mAllowUsertalk;
297 private $mBlockedFromCreateAccount = false;
300 private $mWatchedItems = array();
302 /** @var integer User::READ_* constant bitfield used to load data */
303 protected $queryFlagsUsed = self
::READ_NORMAL
;
305 public static $idCacheByName = array();
308 * Lightweight constructor for an anonymous user.
309 * Use the User::newFrom* factory functions for other kinds of users.
313 * @see newFromConfirmationCode()
314 * @see newFromSession()
317 public function __construct() {
318 $this->clearInstanceCache( 'defaults' );
324 public function __toString() {
325 return $this->getName();
329 * Load the user table data for this object from the source given by mFrom.
331 * @param integer $flags User::READ_* constant bitfield
333 public function load( $flags = self
::READ_LATEST
) {
334 if ( $this->mLoadedItems
=== true ) {
338 // Set it now to avoid infinite recursion in accessors
339 $this->mLoadedItems
= true;
340 $this->queryFlagsUsed
= $flags;
342 switch ( $this->mFrom
) {
344 $this->loadDefaults();
347 // @TODO: this gets the ID from a slave, assuming renames
348 // are rare. This should be controllable and more consistent.
349 $this->mId
= self
::idFromName( $this->mName
);
351 // Nonexistent user placeholder object
352 $this->loadDefaults( $this->mName
);
354 $this->loadFromId( $flags );
358 $this->loadFromId( $flags );
361 if ( !$this->loadFromSession() ) {
362 // Loading from session failed. Load defaults.
363 $this->loadDefaults();
365 Hooks
::run( 'UserLoadAfterLoadFromSession', array( $this ) );
368 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
373 * Load user table data, given mId has already been set.
374 * @param integer $flags User::READ_* constant bitfield
375 * @return bool False if the ID does not exist, true otherwise
377 public function loadFromId( $flags = self
::READ_LATEST
) {
378 if ( $this->mId
== 0 ) {
379 $this->loadDefaults();
384 $cache = $this->loadFromCache();
386 wfDebug( "User: cache miss for user {$this->mId}\n" );
388 if ( !$this->loadFromDatabase( $flags ) ) {
389 // Can't load from ID, user is anonymous
392 if ( $flags & self
::READ_LATEST
) {
393 // Only save master data back to the cache to keep it consistent.
394 // @TODO: save it anyway and have callers specifiy $flags and have
395 // load() called as needed. That requires updating MANY callers...
396 $this->saveToCache();
400 $this->mLoadedItems
= true;
401 $this->queryFlagsUsed
= $flags;
407 * Load user data from shared cache, given mId has already been set.
409 * @return bool false if the ID does not exist or data is invalid, true otherwise
412 protected function loadFromCache() {
415 if ( $this->mId
== 0 ) {
416 $this->loadDefaults();
420 $key = wfMemcKey( 'user', 'id', $this->mId
);
421 $data = $wgMemc->get( $key );
422 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
427 wfDebug( "User: got user {$this->mId} from cache\n" );
429 // Restore from cache
430 foreach ( self
::$mCacheVars as $name ) {
431 $this->$name = $data[$name];
438 * Save user data to the shared cache
440 * This method should not be called outside the User class
442 public function saveToCache() {
447 $this->loadOptions();
449 if ( $this->isAnon() ) {
450 // Anonymous users are uncached
454 // The cache needs good consistency due to its high TTL, so the user
455 // should have been loaded from the master to avoid lag amplification.
456 if ( !( $this->queryFlagsUsed
& self
::READ_LATEST
) ) {
457 wfWarn( "Cannot cache slave-loaded User object with ID '{$this->mId}'." );
462 foreach ( self
::$mCacheVars as $name ) {
463 $data[$name] = $this->$name;
465 $data['mVersion'] = self
::VERSION
;
466 $key = wfMemcKey( 'user', 'id', $this->mId
);
468 $wgMemc->set( $key, $data );
471 /** @name newFrom*() static factory methods */
475 * Static factory method for creation from username.
477 * This is slightly less efficient than newFromId(), so use newFromId() if
478 * you have both an ID and a name handy.
480 * @param string $name Username, validated by Title::newFromText()
481 * @param string|bool $validate Validate username. Takes the same parameters as
482 * User::getCanonicalName(), except that true is accepted as an alias
483 * for 'valid', for BC.
485 * @return User|bool User object, or false if the username is invalid
486 * (e.g. if it contains illegal characters or is an IP address). If the
487 * username is not present in the database, the result will be a user object
488 * with a name, zero user ID and default settings.
490 public static function newFromName( $name, $validate = 'valid' ) {
491 if ( $validate === true ) {
494 $name = self
::getCanonicalName( $name, $validate );
495 if ( $name === false ) {
498 // Create unloaded user object
502 $u->setItemLoaded( 'name' );
508 * Static factory method for creation from a given user ID.
510 * @param int $id Valid user ID
511 * @return User The corresponding User object
513 public static function newFromId( $id ) {
517 $u->setItemLoaded( 'id' );
522 * Factory method to fetch whichever user has a given email confirmation code.
523 * This code is generated when an account is created or its e-mail address
526 * If the code is invalid or has expired, returns NULL.
528 * @param string $code Confirmation code
531 public static function newFromConfirmationCode( $code ) {
532 $dbr = wfGetDB( DB_SLAVE
);
533 $id = $dbr->selectField( 'user', 'user_id', array(
534 'user_email_token' => md5( $code ),
535 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
537 if ( $id !== false ) {
538 return User
::newFromId( $id );
545 * Create a new user object using data from session or cookies. If the
546 * login credentials are invalid, the result is an anonymous user.
548 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
551 public static function newFromSession( WebRequest
$request = null ) {
553 $user->mFrom
= 'session';
554 $user->mRequest
= $request;
559 * Create a new user object from a user row.
560 * The row should have the following fields from the user table in it:
561 * - either user_name or user_id to load further data if needed (or both)
563 * - all other fields (email, password, etc.)
564 * It is useless to provide the remaining fields if either user_id,
565 * user_name and user_real_name are not provided because the whole row
566 * will be loaded once more from the database when accessing them.
568 * @param stdClass $row A row from the user table
569 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
572 public static function newFromRow( $row, $data = null ) {
574 $user->loadFromRow( $row, $data );
581 * Get the username corresponding to a given user ID
582 * @param int $id User ID
583 * @return string|bool The corresponding username
585 public static function whoIs( $id ) {
586 return UserCache
::singleton()->getProp( $id, 'name' );
590 * Get the real name of a user given their user ID
592 * @param int $id User ID
593 * @return string|bool The corresponding user's real name
595 public static function whoIsReal( $id ) {
596 return UserCache
::singleton()->getProp( $id, 'real_name' );
600 * Get database id given a user name
601 * @param string $name Username
602 * @return int|null The corresponding user's ID, or null if user is nonexistent
604 public static function idFromName( $name ) {
605 $nt = Title
::makeTitleSafe( NS_USER
, $name );
606 if ( is_null( $nt ) ) {
611 if ( isset( self
::$idCacheByName[$name] ) ) {
612 return self
::$idCacheByName[$name];
615 $dbr = wfGetDB( DB_SLAVE
);
616 $s = $dbr->selectRow(
619 array( 'user_name' => $nt->getText() ),
623 if ( $s === false ) {
626 $result = $s->user_id
;
629 self
::$idCacheByName[$name] = $result;
631 if ( count( self
::$idCacheByName ) > 1000 ) {
632 self
::$idCacheByName = array();
639 * Reset the cache used in idFromName(). For use in tests.
641 public static function resetIdByNameCache() {
642 self
::$idCacheByName = array();
646 * Does the string match an anonymous IPv4 address?
648 * This function exists for username validation, in order to reject
649 * usernames which are similar in form to IP addresses. Strings such
650 * as 300.300.300.300 will return true because it looks like an IP
651 * address, despite not being strictly valid.
653 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
654 * address because the usemod software would "cloak" anonymous IP
655 * addresses like this, if we allowed accounts like this to be created
656 * new users could get the old edits of these anonymous users.
658 * @param string $name Name to match
661 public static function isIP( $name ) {
662 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
663 || IP
::isIPv6( $name );
667 * Is the input a valid username?
669 * Checks if the input is a valid username, we don't want an empty string,
670 * an IP address, anything that contains slashes (would mess up subpages),
671 * is longer than the maximum allowed username size or doesn't begin with
674 * @param string $name Name to match
677 public static function isValidUserName( $name ) {
678 global $wgContLang, $wgMaxNameChars;
681 || User
::isIP( $name )
682 ||
strpos( $name, '/' ) !== false
683 ||
strlen( $name ) > $wgMaxNameChars
684 ||
$name != $wgContLang->ucfirst( $name )
686 wfDebugLog( 'username', __METHOD__
.
687 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
691 // Ensure that the name can't be misresolved as a different title,
692 // such as with extra namespace keys at the start.
693 $parsed = Title
::newFromText( $name );
694 if ( is_null( $parsed )
695 ||
$parsed->getNamespace()
696 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
697 wfDebugLog( 'username', __METHOD__
.
698 ": '$name' invalid due to ambiguous prefixes" );
702 // Check an additional blacklist of troublemaker characters.
703 // Should these be merged into the title char list?
704 $unicodeBlacklist = '/[' .
705 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
706 '\x{00a0}' . # non-breaking space
707 '\x{2000}-\x{200f}' . # various whitespace
708 '\x{2028}-\x{202f}' . # breaks and control chars
709 '\x{3000}' . # ideographic space
710 '\x{e000}-\x{f8ff}' . # private use
712 if ( preg_match( $unicodeBlacklist, $name ) ) {
713 wfDebugLog( 'username', __METHOD__
.
714 ": '$name' invalid due to blacklisted characters" );
722 * Usernames which fail to pass this function will be blocked
723 * from user login and new account registrations, but may be used
724 * internally by batch processes.
726 * If an account already exists in this form, login will be blocked
727 * by a failure to pass this function.
729 * @param string $name Name to match
732 public static function isUsableName( $name ) {
733 global $wgReservedUsernames;
734 // Must be a valid username, obviously ;)
735 if ( !self
::isValidUserName( $name ) ) {
739 static $reservedUsernames = false;
740 if ( !$reservedUsernames ) {
741 $reservedUsernames = $wgReservedUsernames;
742 Hooks
::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
745 // Certain names may be reserved for batch processes.
746 foreach ( $reservedUsernames as $reserved ) {
747 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
748 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
750 if ( $reserved == $name ) {
758 * Usernames which fail to pass this function will be blocked
759 * from new account registrations, but may be used internally
760 * either by batch processes or by user accounts which have
761 * already been created.
763 * Additional blacklisting may be added here rather than in
764 * isValidUserName() to avoid disrupting existing accounts.
766 * @param string $name String to match
769 public static function isCreatableName( $name ) {
770 global $wgInvalidUsernameCharacters;
772 // Ensure that the username isn't longer than 235 bytes, so that
773 // (at least for the builtin skins) user javascript and css files
774 // will work. (bug 23080)
775 if ( strlen( $name ) > 235 ) {
776 wfDebugLog( 'username', __METHOD__
.
777 ": '$name' invalid due to length" );
781 // Preg yells if you try to give it an empty string
782 if ( $wgInvalidUsernameCharacters !== '' ) {
783 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
784 wfDebugLog( 'username', __METHOD__
.
785 ": '$name' invalid due to wgInvalidUsernameCharacters" );
790 return self
::isUsableName( $name );
794 * Is the input a valid password for this user?
796 * @param string $password Desired password
799 public function isValidPassword( $password ) {
800 //simple boolean wrapper for getPasswordValidity
801 return $this->getPasswordValidity( $password ) === true;
806 * Given unvalidated password input, return error message on failure.
808 * @param string $password Desired password
809 * @return bool|string|array True on success, string or array of error message on failure
811 public function getPasswordValidity( $password ) {
812 $result = $this->checkPasswordValidity( $password );
813 if ( $result->isGood() ) {
817 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
818 $messages[] = $error['message'];
820 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
821 $messages[] = $warning['message'];
823 if ( count( $messages ) === 1 ) {
831 * Check if this is a valid password for this user
833 * Create a Status object based on the password's validity.
834 * The Status should be set to fatal if the user should not
835 * be allowed to log in, and should have any errors that
836 * would block changing the password.
838 * If the return value of this is not OK, the password
839 * should not be checked. If the return value is not Good,
840 * the password can be checked, but the user should not be
841 * able to set their password to this.
843 * @param string $password Desired password
847 public function checkPasswordValidity( $password ) {
848 global $wgMinimalPasswordLength, $wgMaximalPasswordLength, $wgContLang;
850 static $blockedLogins = array(
851 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
852 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
855 $status = Status
::newGood();
857 $result = false; //init $result to false for the internal checks
859 if ( !Hooks
::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
860 $status->error( $result );
864 if ( $result === false ) {
865 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
866 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
868 } elseif ( strlen( $password ) > $wgMaximalPasswordLength ) {
869 // T64685: Password too long, might cause DoS attack
870 $status->fatal( 'passwordtoolong', $wgMaximalPasswordLength );
872 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
873 $status->error( 'password-name-match' );
875 } elseif ( isset( $blockedLogins[$this->getName()] )
876 && $password == $blockedLogins[$this->getName()]
878 $status->error( 'password-login-forbidden' );
881 //it seems weird returning a Good status here, but this is because of the
882 //initialization of $result to false above. If the hook is never run or it
883 //doesn't modify $result, then we will likely get down into this if with
887 } elseif ( $result === true ) {
890 $status->error( $result );
891 return $status; //the isValidPassword hook set a string $result and returned true
896 * Expire a user's password
898 * @param int $ts Optional timestamp to convert, default 0 for the current time
900 public function expirePassword( $ts = 0 ) {
901 $this->loadPasswords();
902 $timestamp = wfTimestamp( TS_MW
, $ts );
903 $this->mPasswordExpires
= $timestamp;
904 $this->saveSettings();
908 * Clear the password expiration for a user
910 * @param bool $load Ensure user object is loaded first
912 public function resetPasswordExpiration( $load = true ) {
913 global $wgPasswordExpirationDays;
918 if ( $wgPasswordExpirationDays ) {
919 $newExpire = wfTimestamp(
921 time() +
( $wgPasswordExpirationDays * 24 * 3600 )
924 // Give extensions a chance to force an expiration
925 Hooks
::run( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
926 $this->mPasswordExpires
= $newExpire;
930 * Check if the user's password is expired.
931 * TODO: Put this and password length into a PasswordPolicy object
933 * @return string|bool The expiration type, or false if not expired
934 * hard: A password change is required to login
935 * soft: Allow login, but encourage password change
936 * false: Password is not expired
938 public function getPasswordExpired() {
939 global $wgPasswordExpireGrace;
941 $now = wfTimestamp();
942 $expiration = $this->getPasswordExpireDate();
943 $expUnix = wfTimestamp( TS_UNIX
, $expiration );
944 if ( $expiration !== null && $expUnix < $now ) {
945 $expired = ( $expUnix +
$wgPasswordExpireGrace < $now ) ?
'hard' : 'soft';
951 * Get this user's password expiration date. Since this may be using
952 * the cached User object, we assume that whatever mechanism is setting
953 * the expiration date is also expiring the User cache.
955 * @return string|bool The datestamp of the expiration, or null if not set
957 public function getPasswordExpireDate() {
959 return $this->mPasswordExpires
;
963 * Given unvalidated user input, return a canonical username, or false if
964 * the username is invalid.
965 * @param string $name User input
966 * @param string|bool $validate Type of validation to use:
967 * - false No validation
968 * - 'valid' Valid for batch processes
969 * - 'usable' Valid for batch processes and login
970 * - 'creatable' Valid for batch processes, login and account creation
972 * @throws MWException
973 * @return bool|string
975 public static function getCanonicalName( $name, $validate = 'valid' ) {
976 // Force usernames to capital
978 $name = $wgContLang->ucfirst( $name );
980 # Reject names containing '#'; these will be cleaned up
981 # with title normalisation, but then it's too late to
983 if ( strpos( $name, '#' ) !== false ) {
987 // Clean up name according to title rules,
988 // but only when validation is requested (bug 12654)
989 $t = ( $validate !== false ) ?
990 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
991 // Check for invalid titles
992 if ( is_null( $t ) ) {
996 // Reject various classes of invalid names
998 $name = $wgAuth->getCanonicalName( $t->getText() );
1000 switch ( $validate ) {
1004 if ( !User
::isValidUserName( $name ) ) {
1009 if ( !User
::isUsableName( $name ) ) {
1014 if ( !User
::isCreatableName( $name ) ) {
1019 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
1025 * Count the number of edits of a user
1027 * @param int $uid User ID to check
1028 * @return int The user's edit count
1030 * @deprecated since 1.21 in favour of User::getEditCount
1032 public static function edits( $uid ) {
1033 wfDeprecated( __METHOD__
, '1.21' );
1034 $user = self
::newFromId( $uid );
1035 return $user->getEditCount();
1039 * Return a random password.
1041 * @return string New random password
1043 public static function randomPassword() {
1044 global $wgMinimalPasswordLength;
1045 // Decide the final password length based on our min password length,
1046 // stopping at a minimum of 10 chars.
1047 $length = max( 10, $wgMinimalPasswordLength );
1048 // Multiply by 1.25 to get the number of hex characters we need
1049 $length = $length * 1.25;
1050 // Generate random hex chars
1051 $hex = MWCryptRand
::generateHex( $length );
1052 // Convert from base 16 to base 32 to get a proper password like string
1053 return wfBaseConvert( $hex, 16, 32 );
1057 * Set cached properties to default.
1059 * @note This no longer clears uncached lazy-initialised properties;
1060 * the constructor does that instead.
1062 * @param string|bool $name
1064 public function loadDefaults( $name = false ) {
1066 $passwordFactory = self
::getPasswordFactory();
1069 $this->mName
= $name;
1070 $this->mRealName
= '';
1071 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1072 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1073 $this->mNewpassTime
= null;
1075 $this->mOptionOverrides
= null;
1076 $this->mOptionsLoaded
= false;
1078 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1079 if ( $loggedOut !== null ) {
1080 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1082 $this->mTouched
= '1'; # Allow any pages to be cached
1085 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1086 $this->mEmailAuthenticated
= null;
1087 $this->mEmailToken
= '';
1088 $this->mEmailTokenExpires
= null;
1089 $this->mPasswordExpires
= null;
1090 $this->resetPasswordExpiration( false );
1091 $this->mRegistration
= wfTimestamp( TS_MW
);
1092 $this->mGroups
= array();
1094 Hooks
::run( 'UserLoadDefaults', array( $this, $name ) );
1098 * Return whether an item has been loaded.
1100 * @param string $item Item to check. Current possibilities:
1104 * @param string $all 'all' to check if the whole object has been loaded
1105 * or any other string to check if only the item is available (e.g.
1109 public function isItemLoaded( $item, $all = 'all' ) {
1110 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1111 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1115 * Set that an item has been loaded
1117 * @param string $item
1119 protected function setItemLoaded( $item ) {
1120 if ( is_array( $this->mLoadedItems
) ) {
1121 $this->mLoadedItems
[$item] = true;
1126 * Load user data from the session or login cookie.
1128 * @return bool True if the user is logged in, false otherwise.
1130 private function loadFromSession() {
1132 Hooks
::run( 'UserLoadFromSession', array( $this, &$result ) );
1133 if ( $result !== null ) {
1137 $request = $this->getRequest();
1139 $cookieId = $request->getCookie( 'UserID' );
1140 $sessId = $request->getSessionData( 'wsUserID' );
1142 if ( $cookieId !== null ) {
1143 $sId = intval( $cookieId );
1144 if ( $sessId !== null && $cookieId != $sessId ) {
1145 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1146 cookie user ID ($sId) don't match!" );
1149 $request->setSessionData( 'wsUserID', $sId );
1150 } elseif ( $sessId !== null && $sessId != 0 ) {
1156 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1157 $sName = $request->getSessionData( 'wsUserName' );
1158 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1159 $sName = $request->getCookie( 'UserName' );
1160 $request->setSessionData( 'wsUserName', $sName );
1165 $proposedUser = User
::newFromId( $sId );
1166 $proposedUser->load( self
::READ_LATEST
);
1167 if ( !$proposedUser->isLoggedIn() ) {
1172 global $wgBlockDisablesLogin;
1173 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1174 // User blocked and we've disabled blocked user logins
1178 if ( $request->getSessionData( 'wsToken' ) ) {
1180 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1182 } elseif ( $request->getCookie( 'Token' ) ) {
1183 # Get the token from DB/cache and clean it up to remove garbage padding.
1184 # This deals with historical problems with bugs and the default column value.
1185 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1186 // Make comparison in constant time (bug 61346)
1187 $passwordCorrect = strlen( $token )
1188 && hash_equals( $token, $request->getCookie( 'Token' ) );
1191 // No session or persistent login cookie
1195 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1196 $this->loadFromUserObject( $proposedUser );
1197 $request->setSessionData( 'wsToken', $this->mToken
);
1198 wfDebug( "User: logged in from $from\n" );
1201 // Invalid credentials
1202 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1208 * Load user and user_group data from the database.
1209 * $this->mId must be set, this is how the user is identified.
1211 * @param integer $flags User::READ_* constant bitfield
1212 * @return bool True if the user exists, false if the user is anonymous
1214 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1216 $this->mId
= intval( $this->mId
);
1219 if ( !$this->mId
) {
1220 $this->loadDefaults();
1224 $db = ( $flags & self
::READ_LATEST
)
1225 ?
wfGetDB( DB_MASTER
)
1226 : wfGetDB( DB_SLAVE
);
1228 $s = $db->selectRow(
1230 self
::selectFields(),
1231 array( 'user_id' => $this->mId
),
1233 ( $flags & self
::READ_LOCKING
== self
::READ_LOCKING
)
1234 ?
array( 'LOCK IN SHARE MODE' )
1238 $this->queryFlagsUsed
= $flags;
1239 Hooks
::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1241 if ( $s !== false ) {
1242 // Initialise user table data
1243 $this->loadFromRow( $s );
1244 $this->mGroups
= null; // deferred
1245 $this->getEditCount(); // revalidation for nulls
1250 $this->loadDefaults();
1256 * Initialize this object from a row from the user table.
1258 * @param stdClass $row Row from the user table to load.
1259 * @param array $data Further user data to load into the object
1261 * user_groups Array with groups out of the user_groups table
1262 * user_properties Array with properties out of the user_properties table
1264 protected function loadFromRow( $row, $data = null ) {
1266 $passwordFactory = self
::getPasswordFactory();
1268 $this->mGroups
= null; // deferred
1270 if ( isset( $row->user_name
) ) {
1271 $this->mName
= $row->user_name
;
1272 $this->mFrom
= 'name';
1273 $this->setItemLoaded( 'name' );
1278 if ( isset( $row->user_real_name
) ) {
1279 $this->mRealName
= $row->user_real_name
;
1280 $this->setItemLoaded( 'realname' );
1285 if ( isset( $row->user_id
) ) {
1286 $this->mId
= intval( $row->user_id
);
1287 $this->mFrom
= 'id';
1288 $this->setItemLoaded( 'id' );
1293 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1294 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1297 if ( isset( $row->user_editcount
) ) {
1298 $this->mEditCount
= $row->user_editcount
;
1303 if ( isset( $row->user_password
) ) {
1304 // Check for *really* old password hashes that don't even have a type
1305 // The old hash format was just an md5 hex hash, with no type information
1306 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password
) ) {
1307 $row->user_password
= ":A:{$this->mId}:{$row->user_password}";
1311 $this->mPassword
= $passwordFactory->newFromCiphertext( $row->user_password
);
1312 } catch ( PasswordError
$e ) {
1313 wfDebug( 'Invalid password hash found in database.' );
1314 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1318 $this->mNewpassword
= $passwordFactory->newFromCiphertext( $row->user_newpassword
);
1319 } catch ( PasswordError
$e ) {
1320 wfDebug( 'Invalid password hash found in database.' );
1321 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1324 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1325 $this->mPasswordExpires
= wfTimestampOrNull( TS_MW
, $row->user_password_expires
);
1328 if ( isset( $row->user_email
) ) {
1329 $this->mEmail
= $row->user_email
;
1330 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1331 $this->mToken
= $row->user_token
;
1332 if ( $this->mToken
== '' ) {
1333 $this->mToken
= null;
1335 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1336 $this->mEmailToken
= $row->user_email_token
;
1337 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1338 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1344 $this->mLoadedItems
= true;
1347 if ( is_array( $data ) ) {
1348 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1349 $this->mGroups
= $data['user_groups'];
1351 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1352 $this->loadOptions( $data['user_properties'] );
1358 * Load the data for this user object from another user object.
1362 protected function loadFromUserObject( $user ) {
1364 $user->loadGroups();
1365 $user->loadOptions();
1366 foreach ( self
::$mCacheVars as $var ) {
1367 $this->$var = $user->$var;
1372 * Load the groups from the database if they aren't already loaded.
1374 private function loadGroups() {
1375 if ( is_null( $this->mGroups
) ) {
1376 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1377 ?
wfGetDB( DB_MASTER
)
1378 : wfGetDB( DB_SLAVE
);
1379 $res = $db->select( 'user_groups',
1380 array( 'ug_group' ),
1381 array( 'ug_user' => $this->mId
),
1383 $this->mGroups
= array();
1384 foreach ( $res as $row ) {
1385 $this->mGroups
[] = $row->ug_group
;
1391 * Load the user's password hashes from the database
1393 * This is usually called in a scenario where the actual User object was
1394 * loaded from the cache, and then password comparison needs to be performed.
1395 * Password hashes are not stored in memcached.
1399 private function loadPasswords() {
1400 if ( $this->getId() !== 0 &&
1401 ( $this->mPassword
=== null ||
$this->mNewpassword
=== null )
1403 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1404 ?
wfGetDB( DB_MASTER
)
1405 : wfGetDB( DB_SLAVE
);
1407 $this->loadFromRow( $db->selectRow(
1409 array( 'user_password', 'user_newpassword',
1410 'user_newpass_time', 'user_password_expires' ),
1411 array( 'user_id' => $this->getId() ),
1418 * Add the user to the group if he/she meets given criteria.
1420 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1421 * possible to remove manually via Special:UserRights. In such case it
1422 * will not be re-added automatically. The user will also not lose the
1423 * group if they no longer meet the criteria.
1425 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1427 * @return array Array of groups the user has been promoted to.
1429 * @see $wgAutopromoteOnce
1431 public function addAutopromoteOnceGroups( $event ) {
1432 global $wgAutopromoteOnceLogInRC, $wgAuth;
1434 $toPromote = array();
1435 if ( !wfReadOnly() && $this->getId() ) {
1436 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1437 if ( count( $toPromote ) ) {
1438 $oldGroups = $this->getGroups(); // previous groups
1440 foreach ( $toPromote as $group ) {
1441 $this->addGroup( $group );
1443 // update groups in external authentication database
1444 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1446 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1448 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1449 $logEntry->setPerformer( $this );
1450 $logEntry->setTarget( $this->getUserPage() );
1451 $logEntry->setParameters( array(
1452 '4::oldgroups' => $oldGroups,
1453 '5::newgroups' => $newGroups,
1455 $logid = $logEntry->insert();
1456 if ( $wgAutopromoteOnceLogInRC ) {
1457 $logEntry->publish( $logid );
1466 * Clear various cached data stored in this object. The cache of the user table
1467 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1469 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1470 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1472 public function clearInstanceCache( $reloadFrom = false ) {
1473 $this->mNewtalk
= -1;
1474 $this->mDatePreference
= null;
1475 $this->mBlockedby
= -1; # Unset
1476 $this->mHash
= false;
1477 $this->mRights
= null;
1478 $this->mEffectiveGroups
= null;
1479 $this->mImplicitGroups
= null;
1480 $this->mGroups
= null;
1481 $this->mOptions
= null;
1482 $this->mOptionsLoaded
= false;
1483 $this->mEditCount
= null;
1485 if ( $reloadFrom ) {
1486 $this->mLoadedItems
= array();
1487 $this->mFrom
= $reloadFrom;
1492 * Combine the language default options with any site-specific options
1493 * and add the default language variants.
1495 * @return array Array of String options
1497 public static function getDefaultOptions() {
1498 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1500 static $defOpt = null;
1501 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1502 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1503 // mid-request and see that change reflected in the return value of this function.
1504 // Which is insane and would never happen during normal MW operation
1508 $defOpt = $wgDefaultUserOptions;
1509 // Default language setting
1510 $defOpt['language'] = $wgContLang->getCode();
1511 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1512 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1514 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1515 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1517 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1519 Hooks
::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1525 * Get a given default option value.
1527 * @param string $opt Name of option to retrieve
1528 * @return string Default option value
1530 public static function getDefaultOption( $opt ) {
1531 $defOpts = self
::getDefaultOptions();
1532 if ( isset( $defOpts[$opt] ) ) {
1533 return $defOpts[$opt];
1540 * Get blocking information
1541 * @param bool $bFromSlave Whether to check the slave database first.
1542 * To improve performance, non-critical checks are done against slaves.
1543 * Check when actually saving should be done against master.
1545 private function getBlockedStatus( $bFromSlave = true ) {
1546 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1548 if ( -1 != $this->mBlockedby
) {
1552 wfDebug( __METHOD__
. ": checking...\n" );
1554 // Initialize data...
1555 // Otherwise something ends up stomping on $this->mBlockedby when
1556 // things get lazy-loaded later, causing false positive block hits
1557 // due to -1 !== 0. Probably session-related... Nothing should be
1558 // overwriting mBlockedby, surely?
1561 # We only need to worry about passing the IP address to the Block generator if the
1562 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1563 # know which IP address they're actually coming from
1564 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1565 $ip = $this->getRequest()->getIP();
1571 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1574 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1575 && !in_array( $ip, $wgProxyWhitelist )
1578 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1580 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1581 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1582 $block->setTarget( $ip );
1583 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1585 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1586 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1587 $block->setTarget( $ip );
1591 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1592 if ( !$block instanceof Block
1593 && $wgApplyIpBlocksToXff
1595 && !$this->isAllowed( 'proxyunbannable' )
1596 && !in_array( $ip, $wgProxyWhitelist )
1598 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1599 $xff = array_map( 'trim', explode( ',', $xff ) );
1600 $xff = array_diff( $xff, array( $ip ) );
1601 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1602 $block = Block
::chooseBlock( $xffblocks, $xff );
1603 if ( $block instanceof Block
) {
1604 # Mangle the reason to alert the user that the block
1605 # originated from matching the X-Forwarded-For header.
1606 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1610 if ( $block instanceof Block
) {
1611 wfDebug( __METHOD__
. ": Found block.\n" );
1612 $this->mBlock
= $block;
1613 $this->mBlockedby
= $block->getByName();
1614 $this->mBlockreason
= $block->mReason
;
1615 $this->mHideName
= $block->mHideName
;
1616 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1618 $this->mBlockedby
= '';
1619 $this->mHideName
= 0;
1620 $this->mAllowUsertalk
= false;
1624 Hooks
::run( 'GetBlockedStatus', array( &$this ) );
1629 * Whether the given IP is in a DNS blacklist.
1631 * @param string $ip IP to check
1632 * @param bool $checkWhitelist Whether to check the whitelist first
1633 * @return bool True if blacklisted.
1635 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1636 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1638 if ( !$wgEnableDnsBlacklist ) {
1642 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1646 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1650 * Whether the given IP is in a given DNS blacklist.
1652 * @param string $ip IP to check
1653 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1654 * @return bool True if blacklisted.
1656 public function inDnsBlacklist( $ip, $bases ) {
1659 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1660 if ( IP
::isIPv4( $ip ) ) {
1661 // Reverse IP, bug 21255
1662 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1664 foreach ( (array)$bases as $base ) {
1666 // If we have an access key, use that too (ProjectHoneypot, etc.)
1667 if ( is_array( $base ) ) {
1668 if ( count( $base ) >= 2 ) {
1669 // Access key is 1, base URL is 0
1670 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1672 $host = "$ipReversed.{$base[0]}";
1675 $host = "$ipReversed.$base";
1679 $ipList = gethostbynamel( $host );
1682 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1686 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1695 * Check if an IP address is in the local proxy list
1701 public static function isLocallyBlockedProxy( $ip ) {
1702 global $wgProxyList;
1704 if ( !$wgProxyList ) {
1708 if ( !is_array( $wgProxyList ) ) {
1709 // Load from the specified file
1710 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1713 if ( !is_array( $wgProxyList ) ) {
1715 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1717 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1718 // Old-style flipped proxy list
1727 * Is this user subject to rate limiting?
1729 * @return bool True if rate limited
1731 public function isPingLimitable() {
1732 global $wgRateLimitsExcludedIPs;
1733 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1734 // No other good way currently to disable rate limits
1735 // for specific IPs. :P
1736 // But this is a crappy hack and should die.
1739 return !$this->isAllowed( 'noratelimit' );
1743 * Primitive rate limits: enforce maximum actions per time period
1744 * to put a brake on flooding.
1746 * The method generates both a generic profiling point and a per action one
1747 * (suffix being "-$action".
1749 * @note When using a shared cache like memcached, IP-address
1750 * last-hit counters will be shared across wikis.
1752 * @param string $action Action to enforce; 'edit' if unspecified
1753 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1754 * @return bool True if a rate limiter was tripped
1756 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1757 // Call the 'PingLimiter' hook
1759 if ( !Hooks
::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1763 global $wgRateLimits;
1764 if ( !isset( $wgRateLimits[$action] ) ) {
1768 // Some groups shouldn't trigger the ping limiter, ever
1769 if ( !$this->isPingLimitable() ) {
1775 $limits = $wgRateLimits[$action];
1777 $id = $this->getId();
1780 if ( isset( $limits['anon'] ) && $id == 0 ) {
1781 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1784 if ( isset( $limits['user'] ) && $id != 0 ) {
1785 $userLimit = $limits['user'];
1787 if ( $this->isNewbie() ) {
1788 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1789 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1791 if ( isset( $limits['ip'] ) ) {
1792 $ip = $this->getRequest()->getIP();
1793 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1795 if ( isset( $limits['subnet'] ) ) {
1796 $ip = $this->getRequest()->getIP();
1799 if ( IP
::isIPv6( $ip ) ) {
1800 $parts = IP
::parseRange( "$ip/64" );
1801 $subnet = $parts[0];
1802 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1804 $subnet = $matches[1];
1806 if ( $subnet !== false ) {
1807 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1811 // Check for group-specific permissions
1812 // If more than one group applies, use the group with the highest limit
1813 foreach ( $this->getGroups() as $group ) {
1814 if ( isset( $limits[$group] ) ) {
1815 if ( $userLimit === false
1816 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1818 $userLimit = $limits[$group];
1822 // Set the user limit key
1823 if ( $userLimit !== false ) {
1824 list( $max, $period ) = $userLimit;
1825 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1826 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1830 foreach ( $keys as $key => $limit ) {
1831 list( $max, $period ) = $limit;
1832 $summary = "(limit $max in {$period}s)";
1833 $count = $wgMemc->get( $key );
1836 if ( $count >= $max ) {
1837 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1838 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1841 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1844 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1845 if ( $incrBy > 0 ) {
1846 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1849 if ( $incrBy > 0 ) {
1850 $wgMemc->incr( $key, $incrBy );
1858 * Check if user is blocked
1860 * @param bool $bFromSlave Whether to check the slave database instead of
1861 * the master. Hacked from false due to horrible probs on site.
1862 * @return bool True if blocked, false otherwise
1864 public function isBlocked( $bFromSlave = true ) {
1865 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1869 * Get the block affecting the user, or null if the user is not blocked
1871 * @param bool $bFromSlave Whether to check the slave database instead of the master
1872 * @return Block|null
1874 public function getBlock( $bFromSlave = true ) {
1875 $this->getBlockedStatus( $bFromSlave );
1876 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1880 * Check if user is blocked from editing a particular article
1882 * @param Title $title Title to check
1883 * @param bool $bFromSlave Whether to check the slave database instead of the master
1886 public function isBlockedFrom( $title, $bFromSlave = false ) {
1887 global $wgBlockAllowsUTEdit;
1889 $blocked = $this->isBlocked( $bFromSlave );
1890 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1891 // If a user's name is suppressed, they cannot make edits anywhere
1892 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1893 && $title->getNamespace() == NS_USER_TALK
) {
1895 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1898 Hooks
::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1904 * If user is blocked, return the name of the user who placed the block
1905 * @return string Name of blocker
1907 public function blockedBy() {
1908 $this->getBlockedStatus();
1909 return $this->mBlockedby
;
1913 * If user is blocked, return the specified reason for the block
1914 * @return string Blocking reason
1916 public function blockedFor() {
1917 $this->getBlockedStatus();
1918 return $this->mBlockreason
;
1922 * If user is blocked, return the ID for the block
1923 * @return int Block ID
1925 public function getBlockId() {
1926 $this->getBlockedStatus();
1927 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1931 * Check if user is blocked on all wikis.
1932 * Do not use for actual edit permission checks!
1933 * This is intended for quick UI checks.
1935 * @param string $ip IP address, uses current client if none given
1936 * @return bool True if blocked, false otherwise
1938 public function isBlockedGlobally( $ip = '' ) {
1939 if ( $this->mBlockedGlobally
!== null ) {
1940 return $this->mBlockedGlobally
;
1942 // User is already an IP?
1943 if ( IP
::isIPAddress( $this->getName() ) ) {
1944 $ip = $this->getName();
1946 $ip = $this->getRequest()->getIP();
1949 Hooks
::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1950 $this->mBlockedGlobally
= (bool)$blocked;
1951 return $this->mBlockedGlobally
;
1955 * Check if user account is locked
1957 * @return bool True if locked, false otherwise
1959 public function isLocked() {
1960 if ( $this->mLocked
!== null ) {
1961 return $this->mLocked
;
1964 $authUser = $wgAuth->getUserInstance( $this );
1965 $this->mLocked
= (bool)$authUser->isLocked();
1966 return $this->mLocked
;
1970 * Check if user account is hidden
1972 * @return bool True if hidden, false otherwise
1974 public function isHidden() {
1975 if ( $this->mHideName
!== null ) {
1976 return $this->mHideName
;
1978 $this->getBlockedStatus();
1979 if ( !$this->mHideName
) {
1981 $authUser = $wgAuth->getUserInstance( $this );
1982 $this->mHideName
= (bool)$authUser->isHidden();
1984 return $this->mHideName
;
1988 * Get the user's ID.
1989 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1991 public function getId() {
1992 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1993 // Special case, we know the user is anonymous
1995 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1996 // Don't load if this was initialized from an ID
2003 * Set the user and reload all fields according to a given ID
2004 * @param int $v User ID to reload
2006 public function setId( $v ) {
2008 $this->clearInstanceCache( 'id' );
2012 * Get the user name, or the IP of an anonymous user
2013 * @return string User's name or IP address
2015 public function getName() {
2016 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2017 // Special case optimisation
2018 return $this->mName
;
2021 if ( $this->mName
=== false ) {
2023 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2025 return $this->mName
;
2030 * Set the user name.
2032 * This does not reload fields from the database according to the given
2033 * name. Rather, it is used to create a temporary "nonexistent user" for
2034 * later addition to the database. It can also be used to set the IP
2035 * address for an anonymous user to something other than the current
2038 * @note User::newFromName() has roughly the same function, when the named user
2040 * @param string $str New user name to set
2042 public function setName( $str ) {
2044 $this->mName
= $str;
2048 * Get the user's name escaped by underscores.
2049 * @return string Username escaped by underscores.
2051 public function getTitleKey() {
2052 return str_replace( ' ', '_', $this->getName() );
2056 * Check if the user has new messages.
2057 * @return bool True if the user has new messages
2059 public function getNewtalk() {
2062 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2063 if ( $this->mNewtalk
=== -1 ) {
2064 $this->mNewtalk
= false; # reset talk page status
2066 // Check memcached separately for anons, who have no
2067 // entire User object stored in there.
2068 if ( !$this->mId
) {
2069 global $wgDisableAnonTalk;
2070 if ( $wgDisableAnonTalk ) {
2071 // Anon newtalk disabled by configuration.
2072 $this->mNewtalk
= false;
2074 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2077 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2081 return (bool)$this->mNewtalk
;
2085 * Return the data needed to construct links for new talk page message
2086 * alerts. If there are new messages, this will return an associative array
2087 * with the following data:
2088 * wiki: The database name of the wiki
2089 * link: Root-relative link to the user's talk page
2090 * rev: The last talk page revision that the user has seen or null. This
2091 * is useful for building diff links.
2092 * If there are no new messages, it returns an empty array.
2093 * @note This function was designed to accomodate multiple talk pages, but
2094 * currently only returns a single link and revision.
2097 public function getNewMessageLinks() {
2099 if ( !Hooks
::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2101 } elseif ( !$this->getNewtalk() ) {
2104 $utp = $this->getTalkPage();
2105 $dbr = wfGetDB( DB_SLAVE
);
2106 // Get the "last viewed rev" timestamp from the oldest message notification
2107 $timestamp = $dbr->selectField( 'user_newtalk',
2108 'MIN(user_last_timestamp)',
2109 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2111 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2112 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2116 * Get the revision ID for the last talk page revision viewed by the talk
2118 * @return int|null Revision ID or null
2120 public function getNewMessageRevisionId() {
2121 $newMessageRevisionId = null;
2122 $newMessageLinks = $this->getNewMessageLinks();
2123 if ( $newMessageLinks ) {
2124 // Note: getNewMessageLinks() never returns more than a single link
2125 // and it is always for the same wiki, but we double-check here in
2126 // case that changes some time in the future.
2127 if ( count( $newMessageLinks ) === 1
2128 && $newMessageLinks[0]['wiki'] === wfWikiID()
2129 && $newMessageLinks[0]['rev']
2131 $newMessageRevision = $newMessageLinks[0]['rev'];
2132 $newMessageRevisionId = $newMessageRevision->getId();
2135 return $newMessageRevisionId;
2139 * Internal uncached check for new messages
2142 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2143 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2144 * @return bool True if the user has new messages
2146 protected function checkNewtalk( $field, $id ) {
2147 $dbr = wfGetDB( DB_SLAVE
);
2149 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__
);
2151 return $ok !== false;
2155 * Add or update the new messages flag
2156 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2157 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2158 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2159 * @return bool True if successful, false otherwise
2161 protected function updateNewtalk( $field, $id, $curRev = null ) {
2162 // Get timestamp of the talk page revision prior to the current one
2163 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2164 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2165 // Mark the user as having new messages since this revision
2166 $dbw = wfGetDB( DB_MASTER
);
2167 $dbw->insert( 'user_newtalk',
2168 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2171 if ( $dbw->affectedRows() ) {
2172 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2175 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2181 * Clear the new messages flag for the given user
2182 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2183 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2184 * @return bool True if successful, false otherwise
2186 protected function deleteNewtalk( $field, $id ) {
2187 $dbw = wfGetDB( DB_MASTER
);
2188 $dbw->delete( 'user_newtalk',
2189 array( $field => $id ),
2191 if ( $dbw->affectedRows() ) {
2192 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2195 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2201 * Update the 'You have new messages!' status.
2202 * @param bool $val Whether the user has new messages
2203 * @param Revision $curRev New, as yet unseen revision of the user talk
2204 * page. Ignored if null or !$val.
2206 public function setNewtalk( $val, $curRev = null ) {
2209 if ( wfReadOnly() ) {
2214 $this->mNewtalk
= $val;
2216 if ( $this->isAnon() ) {
2218 $id = $this->getName();
2221 $id = $this->getId();
2225 $changed = $this->updateNewtalk( $field, $id, $curRev );
2227 $changed = $this->deleteNewtalk( $field, $id );
2230 if ( $this->isAnon() ) {
2231 // Anons have a separate memcached space, since
2232 // user records aren't kept for them.
2233 $key = wfMemcKey( 'newtalk', 'ip', $id );
2234 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
2237 $this->invalidateCache();
2242 * Generate a current or new-future timestamp to be stored in the
2243 * user_touched field when we update things.
2244 * @return string Timestamp in TS_MW format
2246 private function newTouchedTimestamp() {
2247 global $wgClockSkewFudge;
2249 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2250 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2251 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2258 * Clear user data from memcached.
2259 * Use after applying fun updates to the database; caller's
2260 * responsibility to update user_touched if appropriate.
2262 * Called implicitly from invalidateCache() and saveSettings().
2264 public function clearSharedCache() {
2269 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
2274 * Immediately touch the user data cache for this account
2276 * Calls touch() and removes account data from memcached
2278 public function invalidateCache() {
2280 $this->clearSharedCache();
2284 * Update the "touched" timestamp for the user
2286 * This is useful on various login/logout events when making sure that
2287 * a browser or proxy that has multiple tenants does not suffer cache
2288 * pollution where the new user sees the old users content. The value
2289 * of getTouched() is checked when determining 304 vs 200 responses.
2290 * Unlike invalidateCache(), this preserves the User object cache and
2291 * avoids database writes.
2295 public function touch() {
2301 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2302 $timestamp = $this->newTouchedTimestamp();
2303 $wgMemc->set( $key, $timestamp );
2304 $this->mQuickTouched
= $timestamp;
2309 * Validate the cache for this account.
2310 * @param string $timestamp A timestamp in TS_MW format
2313 public function validateCache( $timestamp ) {
2314 return ( $timestamp >= $this->getTouched() );
2318 * Get the user touched timestamp
2319 * @return string TS_MW Timestamp
2321 public function getTouched() {
2327 if ( $this->mQuickTouched
=== null ) {
2328 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2329 $timestamp = $wgMemc->get( $key );
2331 $this->mQuickTouched
= $timestamp;
2333 # Set the timestamp to get HTTP 304 cache hits
2338 return max( $this->mTouched
, $this->mQuickTouched
);
2341 return $this->mTouched
;
2348 public function getPassword() {
2349 $this->loadPasswords();
2351 return $this->mPassword
;
2358 public function getTemporaryPassword() {
2359 $this->loadPasswords();
2361 return $this->mNewpassword
;
2365 * Set the password and reset the random token.
2366 * Calls through to authentication plugin if necessary;
2367 * will have no effect if the auth plugin refuses to
2368 * pass the change through or if the legal password
2371 * As a special case, setting the password to null
2372 * wipes it, so the account cannot be logged in until
2373 * a new password is set, for instance via e-mail.
2375 * @param string $str New password to set
2376 * @throws PasswordError On failure
2380 public function setPassword( $str ) {
2383 $this->loadPasswords();
2385 if ( $str !== null ) {
2386 if ( !$wgAuth->allowPasswordChange() ) {
2387 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2390 $status = $this->checkPasswordValidity( $str );
2391 if ( !$status->isGood() ) {
2392 throw new PasswordError( $status->getMessage()->text() );
2396 if ( !$wgAuth->setPassword( $this, $str ) ) {
2397 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2400 $this->setInternalPassword( $str );
2406 * Set the password and reset the random token unconditionally.
2408 * @param string|null $str New password to set or null to set an invalid
2409 * password hash meaning that the user will not be able to log in
2410 * through the web interface.
2412 public function setInternalPassword( $str ) {
2415 $passwordFactory = self
::getPasswordFactory();
2416 $this->mPassword
= $passwordFactory->newFromPlaintext( $str );
2418 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
2419 $this->mNewpassTime
= null;
2423 * Get the user's current token.
2424 * @param bool $forceCreation Force the generation of a new token if the
2425 * user doesn't have one (default=true for backwards compatibility).
2426 * @return string Token
2428 public function getToken( $forceCreation = true ) {
2430 if ( !$this->mToken
&& $forceCreation ) {
2433 return $this->mToken
;
2437 * Set the random token (used for persistent authentication)
2438 * Called from loadDefaults() among other places.
2440 * @param string|bool $token If specified, set the token to this value
2442 public function setToken( $token = false ) {
2445 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2447 $this->mToken
= $token;
2452 * Set the password for a password reminder or new account email
2454 * @param string $str New password to set or null to set an invalid
2455 * password hash meaning that the user will not be able to use it
2456 * @param bool $throttle If true, reset the throttle timestamp to the present
2458 public function setNewpassword( $str, $throttle = true ) {
2459 $this->loadPasswords();
2461 $this->mNewpassword
= self
::getPasswordFactory()->newFromPlaintext( $str );
2462 if ( $str === null ) {
2463 $this->mNewpassTime
= null;
2464 } elseif ( $throttle ) {
2465 $this->mNewpassTime
= wfTimestampNow();
2470 * Has password reminder email been sent within the last
2471 * $wgPasswordReminderResendTime hours?
2474 public function isPasswordReminderThrottled() {
2475 global $wgPasswordReminderResendTime;
2477 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2480 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2481 return time() < $expiry;
2485 * Get the user's e-mail address
2486 * @return string User's email address
2488 public function getEmail() {
2490 Hooks
::run( 'UserGetEmail', array( $this, &$this->mEmail
) );
2491 return $this->mEmail
;
2495 * Get the timestamp of the user's e-mail authentication
2496 * @return string TS_MW timestamp
2498 public function getEmailAuthenticationTimestamp() {
2500 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2501 return $this->mEmailAuthenticated
;
2505 * Set the user's e-mail address
2506 * @param string $str New e-mail address
2508 public function setEmail( $str ) {
2510 if ( $str == $this->mEmail
) {
2513 $this->invalidateEmail();
2514 $this->mEmail
= $str;
2515 Hooks
::run( 'UserSetEmail', array( $this, &$this->mEmail
) );
2519 * Set the user's e-mail address and a confirmation mail if needed.
2522 * @param string $str New e-mail address
2525 public function setEmailWithConfirmation( $str ) {
2526 global $wgEnableEmail, $wgEmailAuthentication;
2528 if ( !$wgEnableEmail ) {
2529 return Status
::newFatal( 'emaildisabled' );
2532 $oldaddr = $this->getEmail();
2533 if ( $str === $oldaddr ) {
2534 return Status
::newGood( true );
2537 $this->setEmail( $str );
2539 if ( $str !== '' && $wgEmailAuthentication ) {
2540 // Send a confirmation request to the new address if needed
2541 $type = $oldaddr != '' ?
'changed' : 'set';
2542 $result = $this->sendConfirmationMail( $type );
2543 if ( $result->isGood() ) {
2544 // Say to the caller that a confirmation mail has been sent
2545 $result->value
= 'eauth';
2548 $result = Status
::newGood( true );
2555 * Get the user's real name
2556 * @return string User's real name
2558 public function getRealName() {
2559 if ( !$this->isItemLoaded( 'realname' ) ) {
2563 return $this->mRealName
;
2567 * Set the user's real name
2568 * @param string $str New real name
2570 public function setRealName( $str ) {
2572 $this->mRealName
= $str;
2576 * Get the user's current setting for a given option.
2578 * @param string $oname The option to check
2579 * @param string $defaultOverride A default value returned if the option does not exist
2580 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2581 * @return string User's current value for the option
2582 * @see getBoolOption()
2583 * @see getIntOption()
2585 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2586 global $wgHiddenPrefs;
2587 $this->loadOptions();
2589 # We want 'disabled' preferences to always behave as the default value for
2590 # users, even if they have set the option explicitly in their settings (ie they
2591 # set it, and then it was disabled removing their ability to change it). But
2592 # we don't want to erase the preferences in the database in case the preference
2593 # is re-enabled again. So don't touch $mOptions, just override the returned value
2594 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2595 return self
::getDefaultOption( $oname );
2598 if ( array_key_exists( $oname, $this->mOptions
) ) {
2599 return $this->mOptions
[$oname];
2601 return $defaultOverride;
2606 * Get all user's options
2608 * @param int $flags Bitwise combination of:
2609 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2610 * to the default value. (Since 1.25)
2613 public function getOptions( $flags = 0 ) {
2614 global $wgHiddenPrefs;
2615 $this->loadOptions();
2616 $options = $this->mOptions
;
2618 # We want 'disabled' preferences to always behave as the default value for
2619 # users, even if they have set the option explicitly in their settings (ie they
2620 # set it, and then it was disabled removing their ability to change it). But
2621 # we don't want to erase the preferences in the database in case the preference
2622 # is re-enabled again. So don't touch $mOptions, just override the returned value
2623 foreach ( $wgHiddenPrefs as $pref ) {
2624 $default = self
::getDefaultOption( $pref );
2625 if ( $default !== null ) {
2626 $options[$pref] = $default;
2630 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2631 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2638 * Get the user's current setting for a given option, as a boolean value.
2640 * @param string $oname The option to check
2641 * @return bool User's current value for the option
2644 public function getBoolOption( $oname ) {
2645 return (bool)$this->getOption( $oname );
2649 * Get the user's current setting for a given option, as an integer value.
2651 * @param string $oname The option to check
2652 * @param int $defaultOverride A default value returned if the option does not exist
2653 * @return int User's current value for the option
2656 public function getIntOption( $oname, $defaultOverride = 0 ) {
2657 $val = $this->getOption( $oname );
2659 $val = $defaultOverride;
2661 return intval( $val );
2665 * Set the given option for a user.
2667 * You need to call saveSettings() to actually write to the database.
2669 * @param string $oname The option to set
2670 * @param mixed $val New value to set
2672 public function setOption( $oname, $val ) {
2673 $this->loadOptions();
2675 // Explicitly NULL values should refer to defaults
2676 if ( is_null( $val ) ) {
2677 $val = self
::getDefaultOption( $oname );
2680 $this->mOptions
[$oname] = $val;
2684 * Get a token stored in the preferences (like the watchlist one),
2685 * resetting it if it's empty (and saving changes).
2687 * @param string $oname The option name to retrieve the token from
2688 * @return string|bool User's current value for the option, or false if this option is disabled.
2689 * @see resetTokenFromOption()
2692 public function getTokenFromOption( $oname ) {
2693 global $wgHiddenPrefs;
2694 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2698 $token = $this->getOption( $oname );
2700 $token = $this->resetTokenFromOption( $oname );
2701 if ( !wfReadOnly() ) {
2702 $this->saveSettings();
2709 * Reset a token stored in the preferences (like the watchlist one).
2710 * *Does not* save user's preferences (similarly to setOption()).
2712 * @param string $oname The option name to reset the token in
2713 * @return string|bool New token value, or false if this option is disabled.
2714 * @see getTokenFromOption()
2717 public function resetTokenFromOption( $oname ) {
2718 global $wgHiddenPrefs;
2719 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2723 $token = MWCryptRand
::generateHex( 40 );
2724 $this->setOption( $oname, $token );
2729 * Return a list of the types of user options currently returned by
2730 * User::getOptionKinds().
2732 * Currently, the option kinds are:
2733 * - 'registered' - preferences which are registered in core MediaWiki or
2734 * by extensions using the UserGetDefaultOptions hook.
2735 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2736 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2737 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2738 * be used by user scripts.
2739 * - 'special' - "preferences" that are not accessible via User::getOptions
2740 * or User::setOptions.
2741 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2742 * These are usually legacy options, removed in newer versions.
2744 * The API (and possibly others) use this function to determine the possible
2745 * option types for validation purposes, so make sure to update this when a
2746 * new option kind is added.
2748 * @see User::getOptionKinds
2749 * @return array Option kinds
2751 public static function listOptionKinds() {
2754 'registered-multiselect',
2755 'registered-checkmatrix',
2763 * Return an associative array mapping preferences keys to the kind of a preference they're
2764 * used for. Different kinds are handled differently when setting or reading preferences.
2766 * See User::listOptionKinds for the list of valid option types that can be provided.
2768 * @see User::listOptionKinds
2769 * @param IContextSource $context
2770 * @param array $options Assoc. array with options keys to check as keys.
2771 * Defaults to $this->mOptions.
2772 * @return array The key => kind mapping data
2774 public function getOptionKinds( IContextSource
$context, $options = null ) {
2775 $this->loadOptions();
2776 if ( $options === null ) {
2777 $options = $this->mOptions
;
2780 $prefs = Preferences
::getPreferences( $this, $context );
2783 // Pull out the "special" options, so they don't get converted as
2784 // multiselect or checkmatrix.
2785 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2786 foreach ( $specialOptions as $name => $value ) {
2787 unset( $prefs[$name] );
2790 // Multiselect and checkmatrix options are stored in the database with
2791 // one key per option, each having a boolean value. Extract those keys.
2792 $multiselectOptions = array();
2793 foreach ( $prefs as $name => $info ) {
2794 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2795 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2796 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2797 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2799 foreach ( $opts as $value ) {
2800 $multiselectOptions["$prefix$value"] = true;
2803 unset( $prefs[$name] );
2806 $checkmatrixOptions = array();
2807 foreach ( $prefs as $name => $info ) {
2808 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2809 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2810 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2811 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2812 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2814 foreach ( $columns as $column ) {
2815 foreach ( $rows as $row ) {
2816 $checkmatrixOptions["$prefix$column-$row"] = true;
2820 unset( $prefs[$name] );
2824 // $value is ignored
2825 foreach ( $options as $key => $value ) {
2826 if ( isset( $prefs[$key] ) ) {
2827 $mapping[$key] = 'registered';
2828 } elseif ( isset( $multiselectOptions[$key] ) ) {
2829 $mapping[$key] = 'registered-multiselect';
2830 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2831 $mapping[$key] = 'registered-checkmatrix';
2832 } elseif ( isset( $specialOptions[$key] ) ) {
2833 $mapping[$key] = 'special';
2834 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2835 $mapping[$key] = 'userjs';
2837 $mapping[$key] = 'unused';
2845 * Reset certain (or all) options to the site defaults
2847 * The optional parameter determines which kinds of preferences will be reset.
2848 * Supported values are everything that can be reported by getOptionKinds()
2849 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2851 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2852 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2853 * for backwards-compatibility.
2854 * @param IContextSource|null $context Context source used when $resetKinds
2855 * does not contain 'all', passed to getOptionKinds().
2856 * Defaults to RequestContext::getMain() when null.
2858 public function resetOptions(
2859 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2860 IContextSource
$context = null
2863 $defaultOptions = self
::getDefaultOptions();
2865 if ( !is_array( $resetKinds ) ) {
2866 $resetKinds = array( $resetKinds );
2869 if ( in_array( 'all', $resetKinds ) ) {
2870 $newOptions = $defaultOptions;
2872 if ( $context === null ) {
2873 $context = RequestContext
::getMain();
2876 $optionKinds = $this->getOptionKinds( $context );
2877 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2878 $newOptions = array();
2880 // Use default values for the options that should be deleted, and
2881 // copy old values for the ones that shouldn't.
2882 foreach ( $this->mOptions
as $key => $value ) {
2883 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2884 if ( array_key_exists( $key, $defaultOptions ) ) {
2885 $newOptions[$key] = $defaultOptions[$key];
2888 $newOptions[$key] = $value;
2893 Hooks
::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2895 $this->mOptions
= $newOptions;
2896 $this->mOptionsLoaded
= true;
2900 * Get the user's preferred date format.
2901 * @return string User's preferred date format
2903 public function getDatePreference() {
2904 // Important migration for old data rows
2905 if ( is_null( $this->mDatePreference
) ) {
2907 $value = $this->getOption( 'date' );
2908 $map = $wgLang->getDatePreferenceMigrationMap();
2909 if ( isset( $map[$value] ) ) {
2910 $value = $map[$value];
2912 $this->mDatePreference
= $value;
2914 return $this->mDatePreference
;
2918 * Determine based on the wiki configuration and the user's options,
2919 * whether this user must be over HTTPS no matter what.
2923 public function requiresHTTPS() {
2924 global $wgSecureLogin;
2925 if ( !$wgSecureLogin ) {
2928 $https = $this->getBoolOption( 'prefershttps' );
2929 Hooks
::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2931 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2938 * Get the user preferred stub threshold
2942 public function getStubThreshold() {
2943 global $wgMaxArticleSize; # Maximum article size, in Kb
2944 $threshold = $this->getIntOption( 'stubthreshold' );
2945 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2946 // If they have set an impossible value, disable the preference
2947 // so we can use the parser cache again.
2954 * Get the permissions this user has.
2955 * @return array Array of String permission names
2957 public function getRights() {
2958 if ( is_null( $this->mRights
) ) {
2959 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2960 Hooks
::run( 'UserGetRights', array( $this, &$this->mRights
) );
2961 // Force reindexation of rights when a hook has unset one of them
2962 $this->mRights
= array_values( array_unique( $this->mRights
) );
2964 return $this->mRights
;
2968 * Get the list of explicit group memberships this user has.
2969 * The implicit * and user groups are not included.
2970 * @return array Array of String internal group names
2972 public function getGroups() {
2974 $this->loadGroups();
2975 return $this->mGroups
;
2979 * Get the list of implicit group memberships this user has.
2980 * This includes all explicit groups, plus 'user' if logged in,
2981 * '*' for all accounts, and autopromoted groups
2982 * @param bool $recache Whether to avoid the cache
2983 * @return array Array of String internal group names
2985 public function getEffectiveGroups( $recache = false ) {
2986 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2987 $this->mEffectiveGroups
= array_unique( array_merge(
2988 $this->getGroups(), // explicit groups
2989 $this->getAutomaticGroups( $recache ) // implicit groups
2991 // Hook for additional groups
2992 Hooks
::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2993 // Force reindexation of groups when a hook has unset one of them
2994 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
2996 return $this->mEffectiveGroups
;
3000 * Get the list of implicit group memberships this user has.
3001 * This includes 'user' if logged in, '*' for all accounts,
3002 * and autopromoted groups
3003 * @param bool $recache Whether to avoid the cache
3004 * @return array Array of String internal group names
3006 public function getAutomaticGroups( $recache = false ) {
3007 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3008 $this->mImplicitGroups
= array( '*' );
3009 if ( $this->getId() ) {
3010 $this->mImplicitGroups
[] = 'user';
3012 $this->mImplicitGroups
= array_unique( array_merge(
3013 $this->mImplicitGroups
,
3014 Autopromote
::getAutopromoteGroups( $this )
3018 // Assure data consistency with rights/groups,
3019 // as getEffectiveGroups() depends on this function
3020 $this->mEffectiveGroups
= null;
3023 return $this->mImplicitGroups
;
3027 * Returns the groups the user has belonged to.
3029 * The user may still belong to the returned groups. Compare with getGroups().
3031 * The function will not return groups the user had belonged to before MW 1.17
3033 * @return array Names of the groups the user has belonged to.
3035 public function getFormerGroups() {
3038 if ( is_null( $this->mFormerGroups
) ) {
3039 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3040 ?
wfGetDB( DB_MASTER
)
3041 : wfGetDB( DB_SLAVE
);
3042 $res = $db->select( 'user_former_groups',
3043 array( 'ufg_group' ),
3044 array( 'ufg_user' => $this->mId
),
3046 $this->mFormerGroups
= array();
3047 foreach ( $res as $row ) {
3048 $this->mFormerGroups
[] = $row->ufg_group
;
3052 return $this->mFormerGroups
;
3056 * Get the user's edit count.
3057 * @return int|null Null for anonymous users
3059 public function getEditCount() {
3060 if ( !$this->getId() ) {
3064 if ( $this->mEditCount
=== null ) {
3065 /* Populate the count, if it has not been populated yet */
3066 $dbr = wfGetDB( DB_SLAVE
);
3067 // check if the user_editcount field has been initialized
3068 $count = $dbr->selectField(
3069 'user', 'user_editcount',
3070 array( 'user_id' => $this->mId
),
3074 if ( $count === null ) {
3075 // it has not been initialized. do so.
3076 $count = $this->initEditCount();
3078 $this->mEditCount
= $count;
3080 return (int)$this->mEditCount
;
3084 * Add the user to the given group.
3085 * This takes immediate effect.
3086 * @param string $group Name of the group to add
3089 public function addGroup( $group ) {
3092 if ( !Hooks
::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3096 $dbw = wfGetDB( DB_MASTER
);
3097 if ( $this->getId() ) {
3098 $dbw->insert( 'user_groups',
3100 'ug_user' => $this->getID(),
3101 'ug_group' => $group,
3104 array( 'IGNORE' ) );
3107 $this->loadGroups();
3108 $this->mGroups
[] = $group;
3109 // In case loadGroups was not called before, we now have the right twice.
3110 // Get rid of the duplicate.
3111 $this->mGroups
= array_unique( $this->mGroups
);
3113 // Refresh the groups caches, and clear the rights cache so it will be
3114 // refreshed on the next call to $this->getRights().
3115 $this->getEffectiveGroups( true );
3116 $this->mRights
= null;
3118 $this->invalidateCache();
3124 * Remove the user from the given group.
3125 * This takes immediate effect.
3126 * @param string $group Name of the group to remove
3129 public function removeGroup( $group ) {
3131 if ( !Hooks
::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3135 $dbw = wfGetDB( DB_MASTER
);
3136 $dbw->delete( 'user_groups',
3138 'ug_user' => $this->getID(),
3139 'ug_group' => $group,
3142 // Remember that the user was in this group
3143 $dbw->insert( 'user_former_groups',
3145 'ufg_user' => $this->getID(),
3146 'ufg_group' => $group,
3152 $this->loadGroups();
3153 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3155 // Refresh the groups caches, and clear the rights cache so it will be
3156 // refreshed on the next call to $this->getRights().
3157 $this->getEffectiveGroups( true );
3158 $this->mRights
= null;
3160 $this->invalidateCache();
3166 * Get whether the user is logged in
3169 public function isLoggedIn() {
3170 return $this->getID() != 0;
3174 * Get whether the user is anonymous
3177 public function isAnon() {
3178 return !$this->isLoggedIn();
3182 * Check if user is allowed to access a feature / make an action
3184 * @param string $permissions,... Permissions to test
3185 * @return bool True if user is allowed to perform *any* of the given actions
3187 public function isAllowedAny( /*...*/ ) {
3188 $permissions = func_get_args();
3189 foreach ( $permissions as $permission ) {
3190 if ( $this->isAllowed( $permission ) ) {
3199 * @param string $permissions,... Permissions to test
3200 * @return bool True if the user is allowed to perform *all* of the given actions
3202 public function isAllowedAll( /*...*/ ) {
3203 $permissions = func_get_args();
3204 foreach ( $permissions as $permission ) {
3205 if ( !$this->isAllowed( $permission ) ) {
3213 * Internal mechanics of testing a permission
3214 * @param string $action
3217 public function isAllowed( $action = '' ) {
3218 if ( $action === '' ) {
3219 return true; // In the spirit of DWIM
3221 // Patrolling may not be enabled
3222 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3223 global $wgUseRCPatrol, $wgUseNPPatrol;
3224 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3228 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3229 // by misconfiguration: 0 == 'foo'
3230 return in_array( $action, $this->getRights(), true );
3234 * Check whether to enable recent changes patrol features for this user
3235 * @return bool True or false
3237 public function useRCPatrol() {
3238 global $wgUseRCPatrol;
3239 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3243 * Check whether to enable new pages patrol features for this user
3244 * @return bool True or false
3246 public function useNPPatrol() {
3247 global $wgUseRCPatrol, $wgUseNPPatrol;
3249 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3250 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3255 * Get the WebRequest object to use with this object
3257 * @return WebRequest
3259 public function getRequest() {
3260 if ( $this->mRequest
) {
3261 return $this->mRequest
;
3269 * Get the current skin, loading it if required
3270 * @return Skin The current skin
3271 * @todo FIXME: Need to check the old failback system [AV]
3272 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3274 public function getSkin() {
3275 wfDeprecated( __METHOD__
, '1.18' );
3276 return RequestContext
::getMain()->getSkin();
3280 * Get a WatchedItem for this user and $title.
3282 * @since 1.22 $checkRights parameter added
3283 * @param Title $title
3284 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3285 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3286 * @return WatchedItem
3288 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3289 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3291 if ( isset( $this->mWatchedItems
[$key] ) ) {
3292 return $this->mWatchedItems
[$key];
3295 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3296 $this->mWatchedItems
= array();
3299 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3300 return $this->mWatchedItems
[$key];
3304 * Check the watched status of an article.
3305 * @since 1.22 $checkRights parameter added
3306 * @param Title $title Title of the article to look at
3307 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3308 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3311 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3312 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3317 * @since 1.22 $checkRights parameter added
3318 * @param Title $title Title of the article to look at
3319 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3320 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3322 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3323 $this->getWatchedItem( $title, $checkRights )->addWatch();
3324 $this->invalidateCache();
3328 * Stop watching an article.
3329 * @since 1.22 $checkRights parameter added
3330 * @param Title $title Title of the article to look at
3331 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3332 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3334 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3335 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3336 $this->invalidateCache();
3340 * Clear the user's notification timestamp for the given title.
3341 * If e-notif e-mails are on, they will receive notification mails on
3342 * the next change of the page if it's watched etc.
3343 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3344 * @param Title $title Title of the article to look at
3345 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3347 public function clearNotification( &$title, $oldid = 0 ) {
3348 global $wgUseEnotif, $wgShowUpdatedMarker;
3350 // Do nothing if the database is locked to writes
3351 if ( wfReadOnly() ) {
3355 // Do nothing if not allowed to edit the watchlist
3356 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3360 // If we're working on user's talk page, we should update the talk page message indicator
3361 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3362 if ( !Hooks
::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3366 $nextid = $oldid ?
$title->getNextRevisionID( $oldid ) : null;
3368 if ( !$oldid ||
!$nextid ) {
3369 // If we're looking at the latest revision, we should definitely clear it
3370 $this->setNewtalk( false );
3372 // Otherwise we should update its revision, if it's present
3373 if ( $this->getNewtalk() ) {
3374 // Naturally the other one won't clear by itself
3375 $this->setNewtalk( false );
3376 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3381 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3385 if ( $this->isAnon() ) {
3386 // Nothing else to do...
3390 // Only update the timestamp if the page is being watched.
3391 // The query to find out if it is watched is cached both in memcached and per-invocation,
3392 // and when it does have to be executed, it can be on a slave
3393 // If this is the user's newtalk page, we always update the timestamp
3395 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3399 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3403 * Resets all of the given user's page-change notification timestamps.
3404 * If e-notif e-mails are on, they will receive notification mails on
3405 * the next change of any watched page.
3406 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3408 public function clearAllNotifications() {
3409 if ( wfReadOnly() ) {
3413 // Do nothing if not allowed to edit the watchlist
3414 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3418 global $wgUseEnotif, $wgShowUpdatedMarker;
3419 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3420 $this->setNewtalk( false );
3423 $id = $this->getId();
3425 $dbw = wfGetDB( DB_MASTER
);
3426 $dbw->update( 'watchlist',
3427 array( /* SET */ 'wl_notificationtimestamp' => null ),
3428 array( /* WHERE */ 'wl_user' => $id ),
3431 // We also need to clear here the "you have new message" notification for the own user_talk page;
3432 // it's cleared one page view later in WikiPage::doViewUpdates().
3437 * Set a cookie on the user's client. Wrapper for
3438 * WebResponse::setCookie
3439 * @param string $name Name of the cookie to set
3440 * @param string $value Value to set
3441 * @param int $exp Expiration time, as a UNIX time value;
3442 * if 0 or not specified, use the default $wgCookieExpiration
3443 * @param bool $secure
3444 * true: Force setting the secure attribute when setting the cookie
3445 * false: Force NOT setting the secure attribute when setting the cookie
3446 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3447 * @param array $params Array of options sent passed to WebResponse::setcookie()
3448 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3451 protected function setCookie(
3452 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3454 if ( $request === null ) {
3455 $request = $this->getRequest();
3457 $params['secure'] = $secure;
3458 $request->response()->setcookie( $name, $value, $exp, $params );
3462 * Clear a cookie on the user's client
3463 * @param string $name Name of the cookie to clear
3464 * @param bool $secure
3465 * true: Force setting the secure attribute when setting the cookie
3466 * false: Force NOT setting the secure attribute when setting the cookie
3467 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3468 * @param array $params Array of options sent passed to WebResponse::setcookie()
3470 protected function clearCookie( $name, $secure = null, $params = array() ) {
3471 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3475 * Set the default cookies for this session on the user's client.
3477 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3479 * @param bool $secure Whether to force secure/insecure cookies or use default
3480 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3482 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3483 if ( $request === null ) {
3484 $request = $this->getRequest();
3488 if ( 0 == $this->mId
) {
3491 if ( !$this->mToken
) {
3492 // When token is empty or NULL generate a new one and then save it to the database
3493 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3494 // Simply by setting every cell in the user_token column to NULL and letting them be
3495 // regenerated as users log back into the wiki.
3497 if ( !wfReadOnly() ) {
3498 $this->saveSettings();
3502 'wsUserID' => $this->mId
,
3503 'wsToken' => $this->mToken
,
3504 'wsUserName' => $this->getName()
3507 'UserID' => $this->mId
,
3508 'UserName' => $this->getName(),
3510 if ( $rememberMe ) {
3511 $cookies['Token'] = $this->mToken
;
3513 $cookies['Token'] = false;
3516 Hooks
::run( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3518 foreach ( $session as $name => $value ) {
3519 $request->setSessionData( $name, $value );
3521 foreach ( $cookies as $name => $value ) {
3522 if ( $value === false ) {
3523 $this->clearCookie( $name );
3525 $this->setCookie( $name, $value, 0, $secure, array(), $request );
3530 * If wpStickHTTPS was selected, also set an insecure cookie that
3531 * will cause the site to redirect the user to HTTPS, if they access
3532 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3533 * as the one set by centralauth (bug 53538). Also set it to session, or
3534 * standard time setting, based on if rememberme was set.
3536 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3540 $rememberMe ?
0 : null,
3542 array( 'prefix' => '' ) // no prefix
3548 * Log this user out.
3550 public function logout() {
3551 if ( Hooks
::run( 'UserLogout', array( &$this ) ) ) {
3557 * Clear the user's cookies and session, and reset the instance cache.
3560 public function doLogout() {
3561 $this->clearInstanceCache( 'defaults' );
3563 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3565 $this->clearCookie( 'UserID' );
3566 $this->clearCookie( 'Token' );
3567 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3569 // Remember when user logged out, to prevent seeing cached pages
3570 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3574 * Save this user's settings into the database.
3575 * @todo Only rarely do all these fields need to be set!
3577 public function saveSettings() {
3580 if ( wfReadOnly() ) {
3581 // @TODO: caller should deal with this instead!
3582 // This should really just be an exception.
3583 MWExceptionHandler
::logException( new DBExpectedError(
3585 "Could not update user with ID '{$this->mId}'; DB is read-only."
3591 $this->loadPasswords();
3592 if ( 0 == $this->mId
) {
3596 // This method is for updating existing users, so the user should
3597 // have been loaded from the master to begin with to avoid problems.
3598 if ( !( $this->queryFlagsUsed
& self
::READ_LATEST
) ) {
3599 wfWarn( "Attempting to save slave-loaded User object with ID '{$this->mId}'." );
3602 // Get a new user_touched that is higher than the old one.
3603 // This will be used for a CAS check as a last-resort safety
3604 // check against race conditions and slave lag.
3605 $oldTouched = $this->mTouched
;
3606 $this->mTouched
= $this->newTouchedTimestamp();
3608 if ( !$wgAuth->allowSetLocalPassword() ) {
3609 $this->mPassword
= self
::getPasswordFactory()->newFromCiphertext( null );
3612 $dbw = wfGetDB( DB_MASTER
);
3613 $dbw->update( 'user',
3615 'user_name' => $this->mName
,
3616 'user_password' => $this->mPassword
->toString(),
3617 'user_newpassword' => $this->mNewpassword
->toString(),
3618 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3619 'user_real_name' => $this->mRealName
,
3620 'user_email' => $this->mEmail
,
3621 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3622 'user_touched' => $dbw->timestamp( $this->mTouched
),
3623 'user_token' => strval( $this->mToken
),
3624 'user_email_token' => $this->mEmailToken
,
3625 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3626 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires
),
3627 ), array( /* WHERE */
3628 'user_id' => $this->mId
,
3629 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3633 if ( !$dbw->affectedRows() ) {
3634 // User was changed in the meantime or loaded with stale data
3635 MWExceptionHandler
::logException( new MWException(
3636 "CAS update failed on user_touched for user ID '{$this->mId}';" .
3637 "the version of the user to be saved is older than the current version."
3639 // Maybe the problem was a missed cache update; clear it to be safe
3640 $this->clearSharedCache();
3645 $this->saveOptions();
3647 Hooks
::run( 'UserSaveSettings', array( $this ) );
3648 $this->clearSharedCache();
3649 $this->getUserPage()->invalidateCache();
3651 // T95839: clear the cache again post-commit to reduce race conditions
3652 // where stale values are written back to the cache by other threads.
3653 // Note: this *still* doesn't deal with REPEATABLE-READ snapshot lag...
3655 $dbw->onTransactionIdle( function() use ( $that ) {
3656 $that->clearSharedCache();
3661 * If only this user's username is known, and it exists, return the user ID.
3664 public function idForName() {
3665 $s = trim( $this->getName() );
3670 $dbr = wfGetDB( DB_SLAVE
);
3671 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
3672 if ( $id === false ) {
3679 * Add a user to the database, return the user object
3681 * @param string $name Username to add
3682 * @param array $params Array of Strings Non-default parameters to save to
3683 * the database as user_* fields:
3684 * - password: The user's password hash. Password logins will be disabled
3685 * if this is omitted.
3686 * - newpassword: Hash for a temporary password that has been mailed to
3688 * - email: The user's email address.
3689 * - email_authenticated: The email authentication timestamp.
3690 * - real_name: The user's real name.
3691 * - options: An associative array of non-default options.
3692 * - token: Random authentication token. Do not set.
3693 * - registration: Registration timestamp. Do not set.
3695 * @return User|null User object, or null if the username already exists.
3697 public static function createNew( $name, $params = array() ) {
3700 $user->loadPasswords();
3701 $user->setToken(); // init token
3702 if ( isset( $params['options'] ) ) {
3703 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3704 unset( $params['options'] );
3706 $dbw = wfGetDB( DB_MASTER
);
3707 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3710 'user_id' => $seqVal,
3711 'user_name' => $name,
3712 'user_password' => $user->mPassword
->toString(),
3713 'user_newpassword' => $user->mNewpassword
->toString(),
3714 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3715 'user_email' => $user->mEmail
,
3716 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3717 'user_real_name' => $user->mRealName
,
3718 'user_token' => strval( $user->mToken
),
3719 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3720 'user_editcount' => 0,
3721 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3723 foreach ( $params as $name => $value ) {
3724 $fields["user_$name"] = $value;
3726 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3727 if ( $dbw->affectedRows() ) {
3728 $newUser = User
::newFromId( $dbw->insertId() );
3736 * Add this existing user object to the database. If the user already
3737 * exists, a fatal status object is returned, and the user object is
3738 * initialised with the data from the database.
3740 * Previously, this function generated a DB error due to a key conflict
3741 * if the user already existed. Many extension callers use this function
3742 * in code along the lines of:
3744 * $user = User::newFromName( $name );
3745 * if ( !$user->isLoggedIn() ) {
3746 * $user->addToDatabase();
3748 * // do something with $user...
3750 * However, this was vulnerable to a race condition (bug 16020). By
3751 * initialising the user object if the user exists, we aim to support this
3752 * calling sequence as far as possible.
3754 * Note that if the user exists, this function will acquire a write lock,
3755 * so it is still advisable to make the call conditional on isLoggedIn(),
3756 * and to commit the transaction after calling.
3758 * @throws MWException
3761 public function addToDatabase() {
3763 $this->loadPasswords();
3764 if ( !$this->mToken
) {
3765 $this->setToken(); // init token
3768 $this->mTouched
= $this->newTouchedTimestamp();
3770 $dbw = wfGetDB( DB_MASTER
);
3771 $inWrite = $dbw->writesOrCallbacksPending();
3772 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3773 $dbw->insert( 'user',
3775 'user_id' => $seqVal,
3776 'user_name' => $this->mName
,
3777 'user_password' => $this->mPassword
->toString(),
3778 'user_newpassword' => $this->mNewpassword
->toString(),
3779 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3780 'user_email' => $this->mEmail
,
3781 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3782 'user_real_name' => $this->mRealName
,
3783 'user_token' => strval( $this->mToken
),
3784 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3785 'user_editcount' => 0,
3786 'user_touched' => $dbw->timestamp( $this->mTouched
),
3790 if ( !$dbw->affectedRows() ) {
3791 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3792 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3794 // Can't commit due to pending writes that may need atomicity.
3795 // This may cause some lock contention unlike the case below.
3796 $options = array( 'LOCK IN SHARE MODE' );
3797 $flags = self
::READ_LOCKING
;
3799 // Often, this case happens early in views before any writes when
3800 // using CentralAuth. It's should be OK to commit and break the snapshot.
3801 $dbw->commit( __METHOD__
, 'flush' );
3803 $flags = self
::READ_LATEST
;
3805 $this->mId
= $dbw->selectField( 'user', 'user_id',
3806 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3809 if ( $this->loadFromDatabase( $flags ) ) {
3814 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3815 "to insert user '{$this->mName}' row, but it was not present in select!" );
3817 return Status
::newFatal( 'userexists' );
3819 $this->mId
= $dbw->insertId();
3821 // Clear instance cache other than user table data, which is already accurate
3822 $this->clearInstanceCache();
3824 $this->saveOptions();
3825 return Status
::newGood();
3829 * If this user is logged-in and blocked,
3830 * block any IP address they've successfully logged in from.
3831 * @return bool A block was spread
3833 public function spreadAnyEditBlock() {
3834 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3835 return $this->spreadBlock();
3841 * If this (non-anonymous) user is blocked,
3842 * block the IP address they've successfully logged in from.
3843 * @return bool A block was spread
3845 protected function spreadBlock() {
3846 wfDebug( __METHOD__
. "()\n" );
3848 if ( $this->mId
== 0 ) {
3852 $userblock = Block
::newFromTarget( $this->getName() );
3853 if ( !$userblock ) {
3857 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3861 * Get whether the user is explicitly blocked from account creation.
3862 * @return bool|Block
3864 public function isBlockedFromCreateAccount() {
3865 $this->getBlockedStatus();
3866 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3867 return $this->mBlock
;
3870 # bug 13611: if the IP address the user is trying to create an account from is
3871 # blocked with createaccount disabled, prevent new account creation there even
3872 # when the user is logged in
3873 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3874 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3876 return $this->mBlockedFromCreateAccount
instanceof Block
3877 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3878 ?
$this->mBlockedFromCreateAccount
3883 * Get whether the user is blocked from using Special:Emailuser.
3886 public function isBlockedFromEmailuser() {
3887 $this->getBlockedStatus();
3888 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3892 * Get whether the user is allowed to create an account.
3895 public function isAllowedToCreateAccount() {
3896 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3900 * Get this user's personal page title.
3902 * @return Title User's personal page title
3904 public function getUserPage() {
3905 return Title
::makeTitle( NS_USER
, $this->getName() );
3909 * Get this user's talk page title.
3911 * @return Title User's talk page title
3913 public function getTalkPage() {
3914 $title = $this->getUserPage();
3915 return $title->getTalkPage();
3919 * Determine whether the user is a newbie. Newbies are either
3920 * anonymous IPs, or the most recently created accounts.
3923 public function isNewbie() {
3924 return !$this->isAllowed( 'autoconfirmed' );
3928 * Check to see if the given clear-text password is one of the accepted passwords
3929 * @param string $password User password
3930 * @return bool True if the given password is correct, otherwise False
3932 public function checkPassword( $password ) {
3933 global $wgAuth, $wgLegacyEncoding;
3935 $this->loadPasswords();
3937 // Some passwords will give a fatal Status, which means there is
3938 // some sort of technical or security reason for this password to
3939 // be completely invalid and should never be checked (e.g., T64685)
3940 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
3944 // Certain authentication plugins do NOT want to save
3945 // domain passwords in a mysql database, so we should
3946 // check this (in case $wgAuth->strict() is false).
3947 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3949 } elseif ( $wgAuth->strict() ) {
3950 // Auth plugin doesn't allow local authentication
3952 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3953 // Auth plugin doesn't allow local authentication for this user name
3957 if ( !$this->mPassword
->equals( $password ) ) {
3958 if ( $wgLegacyEncoding ) {
3959 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3960 // Check for this with iconv
3961 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3962 if ( $cp1252Password === $password ||
!$this->mPassword
->equals( $cp1252Password ) ) {
3970 $passwordFactory = self
::getPasswordFactory();
3971 if ( $passwordFactory->needsUpdate( $this->mPassword
) && !wfReadOnly() ) {
3972 $this->mPassword
= $passwordFactory->newFromPlaintext( $password );
3973 $this->saveSettings();
3980 * Check if the given clear-text password matches the temporary password
3981 * sent by e-mail for password reset operations.
3983 * @param string $plaintext
3985 * @return bool True if matches, false otherwise
3987 public function checkTemporaryPassword( $plaintext ) {
3988 global $wgNewPasswordExpiry;
3991 $this->loadPasswords();
3992 if ( $this->mNewpassword
->equals( $plaintext ) ) {
3993 if ( is_null( $this->mNewpassTime
) ) {
3996 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3997 return ( time() < $expiry );
4004 * Alias for getEditToken.
4005 * @deprecated since 1.19, use getEditToken instead.
4007 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4008 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4009 * @return string The new edit token
4011 public function editToken( $salt = '', $request = null ) {
4012 wfDeprecated( __METHOD__
, '1.19' );
4013 return $this->getEditToken( $salt, $request );
4017 * Internal implementation for self::getEditToken() and
4018 * self::matchEditToken().
4020 * @param string|array $salt
4021 * @param WebRequest $request
4022 * @param string|int $timestamp
4025 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
4026 if ( $this->isAnon() ) {
4027 return self
::EDIT_TOKEN_SUFFIX
;
4029 $token = $request->getSessionData( 'wsEditToken' );
4030 if ( $token === null ) {
4031 $token = MWCryptRand
::generateHex( 32 );
4032 $request->setSessionData( 'wsEditToken', $token );
4034 if ( is_array( $salt ) ) {
4035 $salt = implode( '|', $salt );
4037 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
4038 dechex( $timestamp ) .
4039 self
::EDIT_TOKEN_SUFFIX
;
4044 * Initialize (if necessary) and return a session token value
4045 * which can be used in edit forms to show that the user's
4046 * login credentials aren't being hijacked with a foreign form
4051 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4052 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4053 * @return string The new edit token
4055 public function getEditToken( $salt = '', $request = null ) {
4056 return $this->getEditTokenAtTimestamp(
4057 $salt, $request ?
: $this->getRequest(), wfTimestamp()
4062 * Generate a looking random token for various uses.
4064 * @return string The new random token
4065 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
4066 * wfRandomString for pseudo-randomness.
4068 public static function generateToken() {
4069 return MWCryptRand
::generateHex( 32 );
4073 * Get the embedded timestamp from a token.
4074 * @param string $val Input token
4077 public static function getEditTokenTimestamp( $val ) {
4078 $suffixLen = strlen( self
::EDIT_TOKEN_SUFFIX
);
4079 if ( strlen( $val ) <= 32 +
$suffixLen ) {
4083 return hexdec( substr( $val, 32, -$suffixLen ) );
4087 * Check given value against the token value stored in the session.
4088 * A match should confirm that the form was submitted from the
4089 * user's own login session, not a form submission from a third-party
4092 * @param string $val Input value to compare
4093 * @param string $salt Optional function-specific data for hashing
4094 * @param WebRequest|null $request Object to use or null to use $wgRequest
4095 * @param int $maxage Fail tokens older than this, in seconds
4096 * @return bool Whether the token matches
4098 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4099 if ( $this->isAnon() ) {
4100 return $val === self
::EDIT_TOKEN_SUFFIX
;
4103 $timestamp = self
::getEditTokenTimestamp( $val );
4104 if ( $timestamp === null ) {
4107 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
4112 $sessionToken = $this->getEditTokenAtTimestamp(
4113 $salt, $request ?
: $this->getRequest(), $timestamp
4116 if ( $val != $sessionToken ) {
4117 wfDebug( "User::matchEditToken: broken session data\n" );
4120 return hash_equals( $sessionToken, $val );
4124 * Check given value against the token value stored in the session,
4125 * ignoring the suffix.
4127 * @param string $val Input value to compare
4128 * @param string $salt Optional function-specific data for hashing
4129 * @param WebRequest|null $request Object to use or null to use $wgRequest
4130 * @param int $maxage Fail tokens older than this, in seconds
4131 * @return bool Whether the token matches
4133 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4134 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4135 return $this->matchEditToken( $val, $salt, $request, $maxage );
4139 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4140 * mail to the user's given address.
4142 * @param string $type Message to send, either "created", "changed" or "set"
4145 public function sendConfirmationMail( $type = 'created' ) {
4147 $expiration = null; // gets passed-by-ref and defined in next line.
4148 $token = $this->confirmationToken( $expiration );
4149 $url = $this->confirmationTokenUrl( $token );
4150 $invalidateURL = $this->invalidationTokenUrl( $token );
4151 $this->saveSettings();
4153 if ( $type == 'created' ||
$type === false ) {
4154 $message = 'confirmemail_body';
4155 } elseif ( $type === true ) {
4156 $message = 'confirmemail_body_changed';
4158 // Messages: confirmemail_body_changed, confirmemail_body_set
4159 $message = 'confirmemail_body_' . $type;
4162 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4163 wfMessage( $message,
4164 $this->getRequest()->getIP(),
4167 $wgLang->timeanddate( $expiration, false ),
4169 $wgLang->date( $expiration, false ),
4170 $wgLang->time( $expiration, false ) )->text() );
4174 * Send an e-mail to this user's account. Does not check for
4175 * confirmed status or validity.
4177 * @param string $subject Message subject
4178 * @param string $body Message body
4179 * @param string $from Optional From address; if unspecified, default
4180 * $wgPasswordSender will be used.
4181 * @param string $replyto Reply-To address
4184 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4185 if ( is_null( $from ) ) {
4186 global $wgPasswordSender;
4187 $sender = new MailAddress( $wgPasswordSender,
4188 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4190 $sender = MailAddress
::newFromUser( $from );
4193 $to = MailAddress
::newFromUser( $this );
4194 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
4198 * Generate, store, and return a new e-mail confirmation code.
4199 * A hash (unsalted, since it's used as a key) is stored.
4201 * @note Call saveSettings() after calling this function to commit
4202 * this change to the database.
4204 * @param string &$expiration Accepts the expiration time
4205 * @return string New token
4207 protected function confirmationToken( &$expiration ) {
4208 global $wgUserEmailConfirmationTokenExpiry;
4210 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4211 $expiration = wfTimestamp( TS_MW
, $expires );
4213 $token = MWCryptRand
::generateHex( 32 );
4214 $hash = md5( $token );
4215 $this->mEmailToken
= $hash;
4216 $this->mEmailTokenExpires
= $expiration;
4221 * Return a URL the user can use to confirm their email address.
4222 * @param string $token Accepts the email confirmation token
4223 * @return string New token URL
4225 protected function confirmationTokenUrl( $token ) {
4226 return $this->getTokenUrl( 'ConfirmEmail', $token );
4230 * Return a URL the user can use to invalidate their email address.
4231 * @param string $token Accepts the email confirmation token
4232 * @return string New token URL
4234 protected function invalidationTokenUrl( $token ) {
4235 return $this->getTokenUrl( 'InvalidateEmail', $token );
4239 * Internal function to format the e-mail validation/invalidation URLs.
4240 * This uses a quickie hack to use the
4241 * hardcoded English names of the Special: pages, for ASCII safety.
4243 * @note Since these URLs get dropped directly into emails, using the
4244 * short English names avoids insanely long URL-encoded links, which
4245 * also sometimes can get corrupted in some browsers/mailers
4246 * (bug 6957 with Gmail and Internet Explorer).
4248 * @param string $page Special page
4249 * @param string $token Token
4250 * @return string Formatted URL
4252 protected function getTokenUrl( $page, $token ) {
4253 // Hack to bypass localization of 'Special:'
4254 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4255 return $title->getCanonicalURL();
4259 * Mark the e-mail address confirmed.
4261 * @note Call saveSettings() after calling this function to commit the change.
4265 public function confirmEmail() {
4266 // Check if it's already confirmed, so we don't touch the database
4267 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4268 if ( !$this->isEmailConfirmed() ) {
4269 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4270 Hooks
::run( 'ConfirmEmailComplete', array( $this ) );
4276 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4277 * address if it was already confirmed.
4279 * @note Call saveSettings() after calling this function to commit the change.
4280 * @return bool Returns true
4282 public function invalidateEmail() {
4284 $this->mEmailToken
= null;
4285 $this->mEmailTokenExpires
= null;
4286 $this->setEmailAuthenticationTimestamp( null );
4288 Hooks
::run( 'InvalidateEmailComplete', array( $this ) );
4293 * Set the e-mail authentication timestamp.
4294 * @param string $timestamp TS_MW timestamp
4296 public function setEmailAuthenticationTimestamp( $timestamp ) {
4298 $this->mEmailAuthenticated
= $timestamp;
4299 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4303 * Is this user allowed to send e-mails within limits of current
4304 * site configuration?
4307 public function canSendEmail() {
4308 global $wgEnableEmail, $wgEnableUserEmail;
4309 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4312 $canSend = $this->isEmailConfirmed();
4313 Hooks
::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4318 * Is this user allowed to receive e-mails within limits of current
4319 * site configuration?
4322 public function canReceiveEmail() {
4323 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4327 * Is this user's e-mail address valid-looking and confirmed within
4328 * limits of the current site configuration?
4330 * @note If $wgEmailAuthentication is on, this may require the user to have
4331 * confirmed their address by returning a code or using a password
4332 * sent to the address from the wiki.
4336 public function isEmailConfirmed() {
4337 global $wgEmailAuthentication;
4340 if ( Hooks
::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4341 if ( $this->isAnon() ) {
4344 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4347 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4357 * Check whether there is an outstanding request for e-mail confirmation.
4360 public function isEmailConfirmationPending() {
4361 global $wgEmailAuthentication;
4362 return $wgEmailAuthentication &&
4363 !$this->isEmailConfirmed() &&
4364 $this->mEmailToken
&&
4365 $this->mEmailTokenExpires
> wfTimestamp();
4369 * Get the timestamp of account creation.
4371 * @return string|bool|null Timestamp of account creation, false for
4372 * non-existent/anonymous user accounts, or null if existing account
4373 * but information is not in database.
4375 public function getRegistration() {
4376 if ( $this->isAnon() ) {
4380 return $this->mRegistration
;
4384 * Get the timestamp of the first edit
4386 * @return string|bool Timestamp of first edit, or false for
4387 * non-existent/anonymous user accounts.
4389 public function getFirstEditTimestamp() {
4390 if ( $this->getId() == 0 ) {
4391 return false; // anons
4393 $dbr = wfGetDB( DB_SLAVE
);
4394 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4395 array( 'rev_user' => $this->getId() ),
4397 array( 'ORDER BY' => 'rev_timestamp ASC' )
4400 return false; // no edits
4402 return wfTimestamp( TS_MW
, $time );
4406 * Get the permissions associated with a given list of groups
4408 * @param array $groups Array of Strings List of internal group names
4409 * @return array Array of Strings List of permission key names for given groups combined
4411 public static function getGroupPermissions( $groups ) {
4412 global $wgGroupPermissions, $wgRevokePermissions;
4414 // grant every granted permission first
4415 foreach ( $groups as $group ) {
4416 if ( isset( $wgGroupPermissions[$group] ) ) {
4417 $rights = array_merge( $rights,
4418 // array_filter removes empty items
4419 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4422 // now revoke the revoked permissions
4423 foreach ( $groups as $group ) {
4424 if ( isset( $wgRevokePermissions[$group] ) ) {
4425 $rights = array_diff( $rights,
4426 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4429 return array_unique( $rights );
4433 * Get all the groups who have a given permission
4435 * @param string $role Role to check
4436 * @return array Array of Strings List of internal group names with the given permission
4438 public static function getGroupsWithPermission( $role ) {
4439 global $wgGroupPermissions;
4440 $allowedGroups = array();
4441 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4442 if ( self
::groupHasPermission( $group, $role ) ) {
4443 $allowedGroups[] = $group;
4446 return $allowedGroups;
4450 * Check, if the given group has the given permission
4452 * If you're wanting to check whether all users have a permission, use
4453 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4457 * @param string $group Group to check
4458 * @param string $role Role to check
4461 public static function groupHasPermission( $group, $role ) {
4462 global $wgGroupPermissions, $wgRevokePermissions;
4463 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4464 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4468 * Check if all users have the given permission
4471 * @param string $right Right to check
4474 public static function isEveryoneAllowed( $right ) {
4475 global $wgGroupPermissions, $wgRevokePermissions;
4476 static $cache = array();
4478 // Use the cached results, except in unit tests which rely on
4479 // being able change the permission mid-request
4480 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4481 return $cache[$right];
4484 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4485 $cache[$right] = false;
4489 // If it's revoked anywhere, then everyone doesn't have it
4490 foreach ( $wgRevokePermissions as $rights ) {
4491 if ( isset( $rights[$right] ) && $rights[$right] ) {
4492 $cache[$right] = false;
4497 // Allow extensions (e.g. OAuth) to say false
4498 if ( !Hooks
::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4499 $cache[$right] = false;
4503 $cache[$right] = true;
4508 * Get the localized descriptive name for a group, if it exists
4510 * @param string $group Internal group name
4511 * @return string Localized descriptive group name
4513 public static function getGroupName( $group ) {
4514 $msg = wfMessage( "group-$group" );
4515 return $msg->isBlank() ?
$group : $msg->text();
4519 * Get the localized descriptive name for a member of a group, if it exists
4521 * @param string $group Internal group name
4522 * @param string $username Username for gender (since 1.19)
4523 * @return string Localized name for group member
4525 public static function getGroupMember( $group, $username = '#' ) {
4526 $msg = wfMessage( "group-$group-member", $username );
4527 return $msg->isBlank() ?
$group : $msg->text();
4531 * Return the set of defined explicit groups.
4532 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4533 * are not included, as they are defined automatically, not in the database.
4534 * @return array Array of internal group names
4536 public static function getAllGroups() {
4537 global $wgGroupPermissions, $wgRevokePermissions;
4539 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4540 self
::getImplicitGroups()
4545 * Get a list of all available permissions.
4546 * @return string[] Array of permission names
4548 public static function getAllRights() {
4549 if ( self
::$mAllRights === false ) {
4550 global $wgAvailableRights;
4551 if ( count( $wgAvailableRights ) ) {
4552 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4554 self
::$mAllRights = self
::$mCoreRights;
4556 Hooks
::run( 'UserGetAllRights', array( &self
::$mAllRights ) );
4558 return self
::$mAllRights;
4562 * Get a list of implicit groups
4563 * @return array Array of Strings Array of internal group names
4565 public static function getImplicitGroups() {
4566 global $wgImplicitGroups;
4568 $groups = $wgImplicitGroups;
4569 # Deprecated, use $wgImplicitGroups instead
4570 Hooks
::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4576 * Get the title of a page describing a particular group
4578 * @param string $group Internal group name
4579 * @return Title|bool Title of the page if it exists, false otherwise
4581 public static function getGroupPage( $group ) {
4582 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4583 if ( $msg->exists() ) {
4584 $title = Title
::newFromText( $msg->text() );
4585 if ( is_object( $title ) ) {
4593 * Create a link to the group in HTML, if available;
4594 * else return the group name.
4596 * @param string $group Internal name of the group
4597 * @param string $text The text of the link
4598 * @return string HTML link to the group
4600 public static function makeGroupLinkHTML( $group, $text = '' ) {
4601 if ( $text == '' ) {
4602 $text = self
::getGroupName( $group );
4604 $title = self
::getGroupPage( $group );
4606 return Linker
::link( $title, htmlspecialchars( $text ) );
4608 return htmlspecialchars( $text );
4613 * Create a link to the group in Wikitext, if available;
4614 * else return the group name.
4616 * @param string $group Internal name of the group
4617 * @param string $text The text of the link
4618 * @return string Wikilink to the group
4620 public static function makeGroupLinkWiki( $group, $text = '' ) {
4621 if ( $text == '' ) {
4622 $text = self
::getGroupName( $group );
4624 $title = self
::getGroupPage( $group );
4626 $page = $title->getFullText();
4627 return "[[$page|$text]]";
4634 * Returns an array of the groups that a particular group can add/remove.
4636 * @param string $group The group to check for whether it can add/remove
4637 * @return array Array( 'add' => array( addablegroups ),
4638 * 'remove' => array( removablegroups ),
4639 * 'add-self' => array( addablegroups to self),
4640 * 'remove-self' => array( removable groups from self) )
4642 public static function changeableByGroup( $group ) {
4643 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4647 'remove' => array(),
4648 'add-self' => array(),
4649 'remove-self' => array()
4652 if ( empty( $wgAddGroups[$group] ) ) {
4653 // Don't add anything to $groups
4654 } elseif ( $wgAddGroups[$group] === true ) {
4655 // You get everything
4656 $groups['add'] = self
::getAllGroups();
4657 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4658 $groups['add'] = $wgAddGroups[$group];
4661 // Same thing for remove
4662 if ( empty( $wgRemoveGroups[$group] ) ) {
4664 } elseif ( $wgRemoveGroups[$group] === true ) {
4665 $groups['remove'] = self
::getAllGroups();
4666 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4667 $groups['remove'] = $wgRemoveGroups[$group];
4670 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4671 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4672 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4673 if ( is_int( $key ) ) {
4674 $wgGroupsAddToSelf['user'][] = $value;
4679 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4680 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4681 if ( is_int( $key ) ) {
4682 $wgGroupsRemoveFromSelf['user'][] = $value;
4687 // Now figure out what groups the user can add to him/herself
4688 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4690 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4691 // No idea WHY this would be used, but it's there
4692 $groups['add-self'] = User
::getAllGroups();
4693 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4694 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4697 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4699 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4700 $groups['remove-self'] = User
::getAllGroups();
4701 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4702 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4709 * Returns an array of groups that this user can add and remove
4710 * @return array Array( 'add' => array( addablegroups ),
4711 * 'remove' => array( removablegroups ),
4712 * 'add-self' => array( addablegroups to self),
4713 * 'remove-self' => array( removable groups from self) )
4715 public function changeableGroups() {
4716 if ( $this->isAllowed( 'userrights' ) ) {
4717 // This group gives the right to modify everything (reverse-
4718 // compatibility with old "userrights lets you change
4720 // Using array_merge to make the groups reindexed
4721 $all = array_merge( User
::getAllGroups() );
4725 'add-self' => array(),
4726 'remove-self' => array()
4730 // Okay, it's not so simple, we will have to go through the arrays
4733 'remove' => array(),
4734 'add-self' => array(),
4735 'remove-self' => array()
4737 $addergroups = $this->getEffectiveGroups();
4739 foreach ( $addergroups as $addergroup ) {
4740 $groups = array_merge_recursive(
4741 $groups, $this->changeableByGroup( $addergroup )
4743 $groups['add'] = array_unique( $groups['add'] );
4744 $groups['remove'] = array_unique( $groups['remove'] );
4745 $groups['add-self'] = array_unique( $groups['add-self'] );
4746 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4752 * Deferred version of incEditCountImmediate()
4754 public function incEditCount() {
4756 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $that ) {
4757 $that->incEditCountImmediate();
4762 * Increment the user's edit-count field.
4763 * Will have no effect for anonymous users.
4766 public function incEditCountImmediate() {
4767 if ( $this->isAnon() ) {
4771 $dbw = wfGetDB( DB_MASTER
);
4772 // No rows will be "affected" if user_editcount is NULL
4775 array( 'user_editcount=user_editcount+1' ),
4776 array( 'user_id' => $this->getId() ),
4779 // Lazy initialization check...
4780 if ( $dbw->affectedRows() == 0 ) {
4781 // Now here's a goddamn hack...
4782 $dbr = wfGetDB( DB_SLAVE
);
4783 if ( $dbr !== $dbw ) {
4784 // If we actually have a slave server, the count is
4785 // at least one behind because the current transaction
4786 // has not been committed and replicated.
4787 $this->initEditCount( 1 );
4789 // But if DB_SLAVE is selecting the master, then the
4790 // count we just read includes the revision that was
4791 // just added in the working transaction.
4792 $this->initEditCount();
4795 // Edit count in user cache too
4796 $this->invalidateCache();
4800 * Initialize user_editcount from data out of the revision table
4802 * @param int $add Edits to add to the count from the revision table
4803 * @return int Number of edits
4805 protected function initEditCount( $add = 0 ) {
4806 // Pull from a slave to be less cruel to servers
4807 // Accuracy isn't the point anyway here
4808 $dbr = wfGetDB( DB_SLAVE
);
4809 $count = (int)$dbr->selectField(
4812 array( 'rev_user' => $this->getId() ),
4815 $count = $count +
$add;
4817 $dbw = wfGetDB( DB_MASTER
);
4820 array( 'user_editcount' => $count ),
4821 array( 'user_id' => $this->getId() ),
4829 * Get the description of a given right
4831 * @param string $right Right to query
4832 * @return string Localized description of the right
4834 public static function getRightDescription( $right ) {
4835 $key = "right-$right";
4836 $msg = wfMessage( $key );
4837 return $msg->isBlank() ?
$right : $msg->text();
4841 * Make a new-style password hash
4843 * @param string $password Plain-text password
4844 * @param bool|string $salt Optional salt, may be random or the user ID.
4845 * If unspecified or false, will generate one automatically
4846 * @return string Password hash
4847 * @deprecated since 1.24, use Password class
4849 public static function crypt( $password, $salt = false ) {
4850 wfDeprecated( __METHOD__
, '1.24' );
4851 $hash = self
::getPasswordFactory()->newFromPlaintext( $password );
4852 return $hash->toString();
4856 * Compare a password hash with a plain-text password. Requires the user
4857 * ID if there's a chance that the hash is an old-style hash.
4859 * @param string $hash Password hash
4860 * @param string $password Plain-text password to compare
4861 * @param string|bool $userId User ID for old-style password salt
4864 * @deprecated since 1.24, use Password class
4866 public static function comparePasswords( $hash, $password, $userId = false ) {
4867 wfDeprecated( __METHOD__
, '1.24' );
4869 // Check for *really* old password hashes that don't even have a type
4870 // The old hash format was just an md5 hex hash, with no type information
4871 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4872 global $wgPasswordSalt;
4873 if ( $wgPasswordSalt ) {
4874 $password = ":B:{$userId}:{$hash}";
4876 $password = ":A:{$hash}";
4880 $hash = self
::getPasswordFactory()->newFromCiphertext( $hash );
4881 return $hash->equals( $password );
4885 * Add a newuser log entry for this user.
4886 * Before 1.19 the return value was always true.
4888 * @param string|bool $action Account creation type.
4889 * - String, one of the following values:
4890 * - 'create' for an anonymous user creating an account for himself.
4891 * This will force the action's performer to be the created user itself,
4892 * no matter the value of $wgUser
4893 * - 'create2' for a logged in user creating an account for someone else
4894 * - 'byemail' when the created user will receive its password by e-mail
4895 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4896 * - Boolean means whether the account was created by e-mail (deprecated):
4897 * - true will be converted to 'byemail'
4898 * - false will be converted to 'create' if this object is the same as
4899 * $wgUser and to 'create2' otherwise
4901 * @param string $reason User supplied reason
4903 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4905 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4906 global $wgUser, $wgNewUserLog;
4907 if ( empty( $wgNewUserLog ) ) {
4908 return true; // disabled
4911 if ( $action === true ) {
4912 $action = 'byemail';
4913 } elseif ( $action === false ) {
4914 if ( $this->equals( $wgUser ) ) {
4917 $action = 'create2';
4921 if ( $action === 'create' ||
$action === 'autocreate' ) {
4924 $performer = $wgUser;
4927 $logEntry = new ManualLogEntry( 'newusers', $action );
4928 $logEntry->setPerformer( $performer );
4929 $logEntry->setTarget( $this->getUserPage() );
4930 $logEntry->setComment( $reason );
4931 $logEntry->setParameters( array(
4932 '4::userid' => $this->getId(),
4934 $logid = $logEntry->insert();
4936 if ( $action !== 'autocreate' ) {
4937 $logEntry->publish( $logid );
4944 * Add an autocreate newuser log entry for this user
4945 * Used by things like CentralAuth and perhaps other authplugins.
4946 * Consider calling addNewUserLogEntry() directly instead.
4950 public function addNewUserLogEntryAutoCreate() {
4951 $this->addNewUserLogEntry( 'autocreate' );
4957 * Load the user options either from cache, the database or an array
4959 * @param array $data Rows for the current user out of the user_properties table
4961 protected function loadOptions( $data = null ) {
4966 if ( $this->mOptionsLoaded
) {
4970 $this->mOptions
= self
::getDefaultOptions();
4972 if ( !$this->getId() ) {
4973 // For unlogged-in users, load language/variant options from request.
4974 // There's no need to do it for logged-in users: they can set preferences,
4975 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4976 // so don't override user's choice (especially when the user chooses site default).
4977 $variant = $wgContLang->getDefaultVariant();
4978 $this->mOptions
['variant'] = $variant;
4979 $this->mOptions
['language'] = $variant;
4980 $this->mOptionsLoaded
= true;
4984 // Maybe load from the object
4985 if ( !is_null( $this->mOptionOverrides
) ) {
4986 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4987 foreach ( $this->mOptionOverrides
as $key => $value ) {
4988 $this->mOptions
[$key] = $value;
4991 if ( !is_array( $data ) ) {
4992 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4993 // Load from database
4994 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4995 ?
wfGetDB( DB_MASTER
)
4996 : wfGetDB( DB_SLAVE
);
4998 $res = $dbr->select(
5000 array( 'up_property', 'up_value' ),
5001 array( 'up_user' => $this->getId() ),
5005 $this->mOptionOverrides
= array();
5007 foreach ( $res as $row ) {
5008 $data[$row->up_property
] = $row->up_value
;
5011 foreach ( $data as $property => $value ) {
5012 $this->mOptionOverrides
[$property] = $value;
5013 $this->mOptions
[$property] = $value;
5017 $this->mOptionsLoaded
= true;
5019 Hooks
::run( 'UserLoadOptions', array( $this, &$this->mOptions
) );
5023 * Saves the non-default options for this user, as previously set e.g. via
5024 * setOption(), in the database's "user_properties" (preferences) table.
5025 * Usually used via saveSettings().
5027 protected function saveOptions() {
5028 $this->loadOptions();
5030 // Not using getOptions(), to keep hidden preferences in database
5031 $saveOptions = $this->mOptions
;
5033 // Allow hooks to abort, for instance to save to a global profile.
5034 // Reset options to default state before saving.
5035 if ( !Hooks
::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5039 $userId = $this->getId();
5041 $insert_rows = array(); // all the new preference rows
5042 foreach ( $saveOptions as $key => $value ) {
5043 // Don't bother storing default values
5044 $defaultOption = self
::getDefaultOption( $key );
5045 if ( ( $defaultOption === null && $value !== false && $value !== null )
5046 ||
$value != $defaultOption
5048 $insert_rows[] = array(
5049 'up_user' => $userId,
5050 'up_property' => $key,
5051 'up_value' => $value,
5056 $dbw = wfGetDB( DB_MASTER
);
5058 $res = $dbw->select( 'user_properties',
5059 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
5061 // Find prior rows that need to be removed or updated. These rows will
5062 // all be deleted (the later so that INSERT IGNORE applies the new values).
5063 $keysDelete = array();
5064 foreach ( $res as $row ) {
5065 if ( !isset( $saveOptions[$row->up_property
] )
5066 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5068 $keysDelete[] = $row->up_property
;
5072 if ( count( $keysDelete ) ) {
5073 // Do the DELETE by PRIMARY KEY for prior rows.
5074 // In the past a very large portion of calls to this function are for setting
5075 // 'rememberpassword' for new accounts (a preference that has since been removed).
5076 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5077 // caused gap locks on [max user ID,+infinity) which caused high contention since
5078 // updates would pile up on each other as they are for higher (newer) user IDs.
5079 // It might not be necessary these days, but it shouldn't hurt either.
5080 $dbw->delete( 'user_properties',
5081 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
5083 // Insert the new preference rows
5084 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
5088 * Lazily instantiate and return a factory object for making passwords
5090 * @return PasswordFactory
5092 public static function getPasswordFactory() {
5093 if ( self
::$mPasswordFactory === null ) {
5094 self
::$mPasswordFactory = new PasswordFactory();
5095 self
::$mPasswordFactory->init( RequestContext
::getMain()->getConfig() );
5098 return self
::$mPasswordFactory;
5102 * Provide an array of HTML5 attributes to put on an input element
5103 * intended for the user to enter a new password. This may include
5104 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5106 * Do *not* use this when asking the user to enter his current password!
5107 * Regardless of configuration, users may have invalid passwords for whatever
5108 * reason (e.g., they were set before requirements were tightened up).
5109 * Only use it when asking for a new password, like on account creation or
5112 * Obviously, you still need to do server-side checking.
5114 * NOTE: A combination of bugs in various browsers means that this function
5115 * actually just returns array() unconditionally at the moment. May as
5116 * well keep it around for when the browser bugs get fixed, though.
5118 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5120 * @return array Array of HTML attributes suitable for feeding to
5121 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5122 * That will get confused by the boolean attribute syntax used.)
5124 public static function passwordChangeInputAttribs() {
5125 global $wgMinimalPasswordLength;
5127 if ( $wgMinimalPasswordLength == 0 ) {
5131 # Note that the pattern requirement will always be satisfied if the
5132 # input is empty, so we need required in all cases.
5134 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5135 # if e-mail confirmation is being used. Since HTML5 input validation
5136 # is b0rked anyway in some browsers, just return nothing. When it's
5137 # re-enabled, fix this code to not output required for e-mail
5139 #$ret = array( 'required' );
5142 # We can't actually do this right now, because Opera 9.6 will print out
5143 # the entered password visibly in its error message! When other
5144 # browsers add support for this attribute, or Opera fixes its support,
5145 # we can add support with a version check to avoid doing this on Opera
5146 # versions where it will be a problem. Reported to Opera as
5147 # DSK-262266, but they don't have a public bug tracker for us to follow.
5149 if ( $wgMinimalPasswordLength > 1 ) {
5150 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5151 $ret['title'] = wfMessage( 'passwordtooshort' )
5152 ->numParams( $wgMinimalPasswordLength )->text();
5160 * Return the list of user fields that should be selected to create
5161 * a new user object.
5164 public static function selectFields() {
5172 'user_email_authenticated',
5174 'user_email_token_expires',
5175 'user_registration',
5181 * Factory function for fatal permission-denied errors
5184 * @param string $permission User right required
5187 static function newFatalPermissionDeniedStatus( $permission ) {
5190 $groups = array_map(
5191 array( 'User', 'makeGroupLinkWiki' ),
5192 User
::getGroupsWithPermission( $permission )
5196 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5198 return Status
::newFatal( 'badaccess-group0' );
5203 * Checks if two user objects point to the same user.
5209 public function equals( User
$user ) {
5210 return $this->getName() === $user->getName();