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_NORMAL
) {
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 // Make sure this thread sees its own changes
348 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
349 $flags |
= self
::READ_LATEST
;
350 $this->queryFlagsUsed
= $flags;
353 $this->mId
= self
::idFromName( $this->mName
, $flags );
355 // Nonexistent user placeholder object
356 $this->loadDefaults( $this->mName
);
358 $this->loadFromId( $flags );
362 $this->loadFromId( $flags );
365 if ( !$this->loadFromSession() ) {
366 // Loading from session failed. Load defaults.
367 $this->loadDefaults();
369 Hooks
::run( 'UserLoadAfterLoadFromSession', array( $this ) );
372 throw new UnexpectedValueException(
373 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
378 * Load user table data, given mId has already been set.
379 * @param integer $flags User::READ_* constant bitfield
380 * @return bool False if the ID does not exist, true otherwise
382 public function loadFromId( $flags = self
::READ_NORMAL
) {
383 if ( $this->mId
== 0 ) {
384 $this->loadDefaults();
388 // Try cache (unless this needs to lock the DB).
389 // NOTE: if this thread called saveSettings(), the cache was cleared.
390 $locking = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
);
391 if ( $locking ||
!$this->loadFromCache() ) {
392 wfDebug( "User: cache miss for user {$this->mId}\n" );
393 // Load from DB (make sure this thread sees its own changes)
394 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
395 $flags |
= self
::READ_LATEST
;
397 if ( !$this->loadFromDatabase( $flags ) ) {
398 // Can't load from ID, user is anonymous
401 $this->saveToCache();
404 $this->mLoadedItems
= true;
405 $this->queryFlagsUsed
= $flags;
411 * Load user data from shared cache, given mId has already been set.
413 * @return bool false if the ID does not exist or data is invalid, true otherwise
416 protected function loadFromCache() {
417 if ( $this->mId
== 0 ) {
418 $this->loadDefaults();
422 $key = wfMemcKey( 'user', 'id', $this->mId
);
423 $data = ObjectCache
::getMainWANInstance()->get( $key );
424 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
429 wfDebug( "User: got user {$this->mId} from cache\n" );
431 // Restore from cache
432 foreach ( self
::$mCacheVars as $name ) {
433 $this->$name = $data[$name];
440 * Save user data to the shared cache
442 * This method should not be called outside the User class
444 public function saveToCache() {
447 $this->loadOptions();
449 if ( $this->isAnon() ) {
450 // Anonymous users are uncached
455 foreach ( self
::$mCacheVars as $name ) {
456 $data[$name] = $this->$name;
458 $data['mVersion'] = self
::VERSION
;
459 $key = wfMemcKey( 'user', 'id', $this->mId
);
461 ObjectCache
::getMainWANInstance()->set( $key, $data, 3600 );
464 /** @name newFrom*() static factory methods */
468 * Static factory method for creation from username.
470 * This is slightly less efficient than newFromId(), so use newFromId() if
471 * you have both an ID and a name handy.
473 * @param string $name Username, validated by Title::newFromText()
474 * @param string|bool $validate Validate username. Takes the same parameters as
475 * User::getCanonicalName(), except that true is accepted as an alias
476 * for 'valid', for BC.
478 * @return User|bool User object, or false if the username is invalid
479 * (e.g. if it contains illegal characters or is an IP address). If the
480 * username is not present in the database, the result will be a user object
481 * with a name, zero user ID and default settings.
483 public static function newFromName( $name, $validate = 'valid' ) {
484 if ( $validate === true ) {
487 $name = self
::getCanonicalName( $name, $validate );
488 if ( $name === false ) {
491 // Create unloaded user object
495 $u->setItemLoaded( 'name' );
501 * Static factory method for creation from a given user ID.
503 * @param int $id Valid user ID
504 * @return User The corresponding User object
506 public static function newFromId( $id ) {
510 $u->setItemLoaded( 'id' );
515 * Factory method to fetch whichever user has a given email confirmation code.
516 * This code is generated when an account is created or its e-mail address
519 * If the code is invalid or has expired, returns NULL.
521 * @param string $code Confirmation code
524 public static function newFromConfirmationCode( $code ) {
525 $dbr = wfGetDB( DB_SLAVE
);
526 $id = $dbr->selectField( 'user', 'user_id', array(
527 'user_email_token' => md5( $code ),
528 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
530 if ( $id !== false ) {
531 return User
::newFromId( $id );
538 * Create a new user object using data from session or cookies. If the
539 * login credentials are invalid, the result is an anonymous user.
541 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
544 public static function newFromSession( WebRequest
$request = null ) {
546 $user->mFrom
= 'session';
547 $user->mRequest
= $request;
552 * Create a new user object from a user row.
553 * The row should have the following fields from the user table in it:
554 * - either user_name or user_id to load further data if needed (or both)
556 * - all other fields (email, password, etc.)
557 * It is useless to provide the remaining fields if either user_id,
558 * user_name and user_real_name are not provided because the whole row
559 * will be loaded once more from the database when accessing them.
561 * @param stdClass $row A row from the user table
562 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
565 public static function newFromRow( $row, $data = null ) {
567 $user->loadFromRow( $row, $data );
574 * Get the username corresponding to a given user ID
575 * @param int $id User ID
576 * @return string|bool The corresponding username
578 public static function whoIs( $id ) {
579 return UserCache
::singleton()->getProp( $id, 'name' );
583 * Get the real name of a user given their user ID
585 * @param int $id User ID
586 * @return string|bool The corresponding user's real name
588 public static function whoIsReal( $id ) {
589 return UserCache
::singleton()->getProp( $id, 'real_name' );
593 * Get database id given a user name
594 * @param string $name Username
595 * @param integer $flags User::READ_* constant bitfield
596 * @return int|null The corresponding user's ID, or null if user is nonexistent
598 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
599 $nt = Title
::makeTitleSafe( NS_USER
, $name );
600 if ( is_null( $nt ) ) {
605 if ( isset( self
::$idCacheByName[$name] ) ) {
606 return self
::$idCacheByName[$name];
609 $db = ( $flags & self
::READ_LATEST
)
610 ?
wfGetDB( DB_MASTER
)
611 : wfGetDB( DB_SLAVE
);
616 array( 'user_name' => $nt->getText() ),
620 if ( $s === false ) {
623 $result = $s->user_id
;
626 self
::$idCacheByName[$name] = $result;
628 if ( count( self
::$idCacheByName ) > 1000 ) {
629 self
::$idCacheByName = array();
636 * Reset the cache used in idFromName(). For use in tests.
638 public static function resetIdByNameCache() {
639 self
::$idCacheByName = array();
643 * Does the string match an anonymous IPv4 address?
645 * This function exists for username validation, in order to reject
646 * usernames which are similar in form to IP addresses. Strings such
647 * as 300.300.300.300 will return true because it looks like an IP
648 * address, despite not being strictly valid.
650 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
651 * address because the usemod software would "cloak" anonymous IP
652 * addresses like this, if we allowed accounts like this to be created
653 * new users could get the old edits of these anonymous users.
655 * @param string $name Name to match
658 public static function isIP( $name ) {
659 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
660 || IP
::isIPv6( $name );
664 * Is the input a valid username?
666 * Checks if the input is a valid username, we don't want an empty string,
667 * an IP address, anything that contains slashes (would mess up subpages),
668 * is longer than the maximum allowed username size or doesn't begin with
671 * @param string $name Name to match
674 public static function isValidUserName( $name ) {
675 global $wgContLang, $wgMaxNameChars;
678 || User
::isIP( $name )
679 ||
strpos( $name, '/' ) !== false
680 ||
strlen( $name ) > $wgMaxNameChars
681 ||
$name != $wgContLang->ucfirst( $name )
683 wfDebugLog( 'username', __METHOD__
.
684 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
688 // Ensure that the name can't be misresolved as a different title,
689 // such as with extra namespace keys at the start.
690 $parsed = Title
::newFromText( $name );
691 if ( is_null( $parsed )
692 ||
$parsed->getNamespace()
693 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
694 wfDebugLog( 'username', __METHOD__
.
695 ": '$name' invalid due to ambiguous prefixes" );
699 // Check an additional blacklist of troublemaker characters.
700 // Should these be merged into the title char list?
701 $unicodeBlacklist = '/[' .
702 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
703 '\x{00a0}' . # non-breaking space
704 '\x{2000}-\x{200f}' . # various whitespace
705 '\x{2028}-\x{202f}' . # breaks and control chars
706 '\x{3000}' . # ideographic space
707 '\x{e000}-\x{f8ff}' . # private use
709 if ( preg_match( $unicodeBlacklist, $name ) ) {
710 wfDebugLog( 'username', __METHOD__
.
711 ": '$name' invalid due to blacklisted characters" );
719 * Usernames which fail to pass this function will be blocked
720 * from user login and new account registrations, but may be used
721 * internally by batch processes.
723 * If an account already exists in this form, login will be blocked
724 * by a failure to pass this function.
726 * @param string $name Name to match
729 public static function isUsableName( $name ) {
730 global $wgReservedUsernames;
731 // Must be a valid username, obviously ;)
732 if ( !self
::isValidUserName( $name ) ) {
736 static $reservedUsernames = false;
737 if ( !$reservedUsernames ) {
738 $reservedUsernames = $wgReservedUsernames;
739 Hooks
::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
742 // Certain names may be reserved for batch processes.
743 foreach ( $reservedUsernames as $reserved ) {
744 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
745 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
747 if ( $reserved == $name ) {
755 * Usernames which fail to pass this function will be blocked
756 * from new account registrations, but may be used internally
757 * either by batch processes or by user accounts which have
758 * already been created.
760 * Additional blacklisting may be added here rather than in
761 * isValidUserName() to avoid disrupting existing accounts.
763 * @param string $name String to match
766 public static function isCreatableName( $name ) {
767 global $wgInvalidUsernameCharacters;
769 // Ensure that the username isn't longer than 235 bytes, so that
770 // (at least for the builtin skins) user javascript and css files
771 // will work. (bug 23080)
772 if ( strlen( $name ) > 235 ) {
773 wfDebugLog( 'username', __METHOD__
.
774 ": '$name' invalid due to length" );
778 // Preg yells if you try to give it an empty string
779 if ( $wgInvalidUsernameCharacters !== '' ) {
780 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
781 wfDebugLog( 'username', __METHOD__
.
782 ": '$name' invalid due to wgInvalidUsernameCharacters" );
787 return self
::isUsableName( $name );
791 * Is the input a valid password for this user?
793 * @param string $password Desired password
796 public function isValidPassword( $password ) {
797 //simple boolean wrapper for getPasswordValidity
798 return $this->getPasswordValidity( $password ) === true;
803 * Given unvalidated password input, return error message on failure.
805 * @param string $password Desired password
806 * @return bool|string|array True on success, string or array of error message on failure
808 public function getPasswordValidity( $password ) {
809 $result = $this->checkPasswordValidity( $password );
810 if ( $result->isGood() ) {
814 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
815 $messages[] = $error['message'];
817 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
818 $messages[] = $warning['message'];
820 if ( count( $messages ) === 1 ) {
828 * Check if this is a valid password for this user
830 * Create a Status object based on the password's validity.
831 * The Status should be set to fatal if the user should not
832 * be allowed to log in, and should have any errors that
833 * would block changing the password.
835 * If the return value of this is not OK, the password
836 * should not be checked. If the return value is not Good,
837 * the password can be checked, but the user should not be
838 * able to set their password to this.
840 * @param string $password Desired password
841 * @param string $purpose one of 'login', 'create', 'reset'
845 public function checkPasswordValidity( $password, $purpose = 'login' ) {
846 global $wgPasswordPolicy;
848 $upp = new UserPasswordPolicy(
849 $wgPasswordPolicy['policies'],
850 $wgPasswordPolicy['checks']
853 $status = Status
::newGood();
854 $result = false; //init $result to false for the internal checks
856 if ( !Hooks
::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
857 $status->error( $result );
861 if ( $result === false ) {
862 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
864 } elseif ( $result === true ) {
867 $status->error( $result );
868 return $status; //the isValidPassword hook set a string $result and returned true
873 * Expire a user's password
875 * @param int $ts Optional timestamp to convert, default 0 for the current time
877 public function expirePassword( $ts = 0 ) {
878 $this->loadPasswords();
879 $timestamp = wfTimestamp( TS_MW
, $ts );
880 $this->mPasswordExpires
= $timestamp;
881 $this->saveSettings();
885 * Clear the password expiration for a user
887 * @param bool $load Ensure user object is loaded first
889 public function resetPasswordExpiration( $load = true ) {
890 global $wgPasswordExpirationDays;
895 if ( $wgPasswordExpirationDays ) {
896 $newExpire = wfTimestamp(
898 time() +
( $wgPasswordExpirationDays * 24 * 3600 )
901 // Give extensions a chance to force an expiration
902 Hooks
::run( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
903 $this->mPasswordExpires
= $newExpire;
907 * Check if the user's password is expired.
908 * TODO: Put this and password length into a PasswordPolicy object
910 * @return string|bool The expiration type, or false if not expired
911 * hard: A password change is required to login
912 * soft: Allow login, but encourage password change
913 * false: Password is not expired
915 public function getPasswordExpired() {
916 global $wgPasswordExpireGrace;
918 $now = wfTimestamp();
919 $expiration = $this->getPasswordExpireDate();
920 $expUnix = wfTimestamp( TS_UNIX
, $expiration );
921 if ( $expiration !== null && $expUnix < $now ) {
922 $expired = ( $expUnix +
$wgPasswordExpireGrace < $now ) ?
'hard' : 'soft';
928 * Get this user's password expiration date. Since this may be using
929 * the cached User object, we assume that whatever mechanism is setting
930 * the expiration date is also expiring the User cache.
932 * @return string|bool The datestamp of the expiration, or null if not set
934 public function getPasswordExpireDate() {
936 return $this->mPasswordExpires
;
940 * Given unvalidated user input, return a canonical username, or false if
941 * the username is invalid.
942 * @param string $name User input
943 * @param string|bool $validate Type of validation to use:
944 * - false No validation
945 * - 'valid' Valid for batch processes
946 * - 'usable' Valid for batch processes and login
947 * - 'creatable' Valid for batch processes, login and account creation
949 * @throws InvalidArgumentException
950 * @return bool|string
952 public static function getCanonicalName( $name, $validate = 'valid' ) {
953 // Force usernames to capital
955 $name = $wgContLang->ucfirst( $name );
957 # Reject names containing '#'; these will be cleaned up
958 # with title normalisation, but then it's too late to
960 if ( strpos( $name, '#' ) !== false ) {
964 // Clean up name according to title rules,
965 // but only when validation is requested (bug 12654)
966 $t = ( $validate !== false ) ?
967 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
968 // Check for invalid titles
969 if ( is_null( $t ) ) {
973 // Reject various classes of invalid names
975 $name = $wgAuth->getCanonicalName( $t->getText() );
977 switch ( $validate ) {
981 if ( !User
::isValidUserName( $name ) ) {
986 if ( !User
::isUsableName( $name ) ) {
991 if ( !User
::isCreatableName( $name ) ) {
996 throw new InvalidArgumentException(
997 'Invalid parameter value for $validate in ' . __METHOD__
);
1003 * Count the number of edits of a user
1005 * @param int $uid User ID to check
1006 * @return int The user's edit count
1008 * @deprecated since 1.21 in favour of User::getEditCount
1010 public static function edits( $uid ) {
1011 wfDeprecated( __METHOD__
, '1.21' );
1012 $user = self
::newFromId( $uid );
1013 return $user->getEditCount();
1017 * Return a random password.
1019 * @return string New random password
1021 public static function randomPassword() {
1022 global $wgMinimalPasswordLength;
1023 // Decide the final password length based on our min password length,
1024 // stopping at a minimum of 10 chars.
1025 $length = max( 10, $wgMinimalPasswordLength );
1026 // Multiply by 1.25 to get the number of hex characters we need
1027 $length = $length * 1.25;
1028 // Generate random hex chars
1029 $hex = MWCryptRand
::generateHex( $length );
1030 // Convert from base 16 to base 32 to get a proper password like string
1031 return wfBaseConvert( $hex, 16, 32 );
1035 * Set cached properties to default.
1037 * @note This no longer clears uncached lazy-initialised properties;
1038 * the constructor does that instead.
1040 * @param string|bool $name
1042 public function loadDefaults( $name = false ) {
1044 $passwordFactory = self
::getPasswordFactory();
1047 $this->mName
= $name;
1048 $this->mRealName
= '';
1049 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1050 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1051 $this->mNewpassTime
= null;
1053 $this->mOptionOverrides
= null;
1054 $this->mOptionsLoaded
= false;
1056 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1057 if ( $loggedOut !== null ) {
1058 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1060 $this->mTouched
= '1'; # Allow any pages to be cached
1063 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1064 $this->mEmailAuthenticated
= null;
1065 $this->mEmailToken
= '';
1066 $this->mEmailTokenExpires
= null;
1067 $this->mPasswordExpires
= null;
1068 $this->resetPasswordExpiration( false );
1069 $this->mRegistration
= wfTimestamp( TS_MW
);
1070 $this->mGroups
= array();
1072 Hooks
::run( 'UserLoadDefaults', array( $this, $name ) );
1076 * Return whether an item has been loaded.
1078 * @param string $item Item to check. Current possibilities:
1082 * @param string $all 'all' to check if the whole object has been loaded
1083 * or any other string to check if only the item is available (e.g.
1087 public function isItemLoaded( $item, $all = 'all' ) {
1088 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1089 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1093 * Set that an item has been loaded
1095 * @param string $item
1097 protected function setItemLoaded( $item ) {
1098 if ( is_array( $this->mLoadedItems
) ) {
1099 $this->mLoadedItems
[$item] = true;
1104 * Load user data from the session or login cookie.
1106 * @return bool True if the user is logged in, false otherwise.
1108 private function loadFromSession() {
1110 Hooks
::run( 'UserLoadFromSession', array( $this, &$result ) );
1111 if ( $result !== null ) {
1115 $request = $this->getRequest();
1117 $cookieId = $request->getCookie( 'UserID' );
1118 $sessId = $request->getSessionData( 'wsUserID' );
1120 if ( $cookieId !== null ) {
1121 $sId = intval( $cookieId );
1122 if ( $sessId !== null && $cookieId != $sessId ) {
1123 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1124 cookie user ID ($sId) don't match!" );
1127 $request->setSessionData( 'wsUserID', $sId );
1128 } elseif ( $sessId !== null && $sessId != 0 ) {
1134 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1135 $sName = $request->getSessionData( 'wsUserName' );
1136 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1137 $sName = $request->getCookie( 'UserName' );
1138 $request->setSessionData( 'wsUserName', $sName );
1143 $proposedUser = User
::newFromId( $sId );
1144 if ( !$proposedUser->isLoggedIn() ) {
1149 global $wgBlockDisablesLogin;
1150 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1151 // User blocked and we've disabled blocked user logins
1155 if ( $request->getSessionData( 'wsToken' ) ) {
1157 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1159 } elseif ( $request->getCookie( 'Token' ) ) {
1160 # Get the token from DB/cache and clean it up to remove garbage padding.
1161 # This deals with historical problems with bugs and the default column value.
1162 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1163 // Make comparison in constant time (bug 61346)
1164 $passwordCorrect = strlen( $token )
1165 && hash_equals( $token, $request->getCookie( 'Token' ) );
1168 // No session or persistent login cookie
1172 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1173 $this->loadFromUserObject( $proposedUser );
1174 $request->setSessionData( 'wsToken', $this->mToken
);
1175 wfDebug( "User: logged in from $from\n" );
1178 // Invalid credentials
1179 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1185 * Load user and user_group data from the database.
1186 * $this->mId must be set, this is how the user is identified.
1188 * @param integer $flags User::READ_* constant bitfield
1189 * @return bool True if the user exists, false if the user is anonymous
1191 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1193 $this->mId
= intval( $this->mId
);
1196 if ( !$this->mId
) {
1197 $this->loadDefaults();
1201 $db = ( $flags & self
::READ_LATEST
)
1202 ?
wfGetDB( DB_MASTER
)
1203 : wfGetDB( DB_SLAVE
);
1205 $s = $db->selectRow(
1207 self
::selectFields(),
1208 array( 'user_id' => $this->mId
),
1210 ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
1211 ?
array( 'LOCK IN SHARE MODE' )
1215 $this->queryFlagsUsed
= $flags;
1216 Hooks
::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1218 if ( $s !== false ) {
1219 // Initialise user table data
1220 $this->loadFromRow( $s );
1221 $this->mGroups
= null; // deferred
1222 $this->getEditCount(); // revalidation for nulls
1227 $this->loadDefaults();
1233 * Initialize this object from a row from the user table.
1235 * @param stdClass $row Row from the user table to load.
1236 * @param array $data Further user data to load into the object
1238 * user_groups Array with groups out of the user_groups table
1239 * user_properties Array with properties out of the user_properties table
1241 protected function loadFromRow( $row, $data = null ) {
1243 $passwordFactory = self
::getPasswordFactory();
1245 $this->mGroups
= null; // deferred
1247 if ( isset( $row->user_name
) ) {
1248 $this->mName
= $row->user_name
;
1249 $this->mFrom
= 'name';
1250 $this->setItemLoaded( 'name' );
1255 if ( isset( $row->user_real_name
) ) {
1256 $this->mRealName
= $row->user_real_name
;
1257 $this->setItemLoaded( 'realname' );
1262 if ( isset( $row->user_id
) ) {
1263 $this->mId
= intval( $row->user_id
);
1264 $this->mFrom
= 'id';
1265 $this->setItemLoaded( 'id' );
1270 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1271 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1274 if ( isset( $row->user_editcount
) ) {
1275 $this->mEditCount
= $row->user_editcount
;
1280 if ( isset( $row->user_password
) ) {
1281 // Check for *really* old password hashes that don't even have a type
1282 // The old hash format was just an md5 hex hash, with no type information
1283 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password
) ) {
1284 $row->user_password
= ":A:{$this->mId}:{$row->user_password}";
1288 $this->mPassword
= $passwordFactory->newFromCiphertext( $row->user_password
);
1289 } catch ( PasswordError
$e ) {
1290 wfDebug( 'Invalid password hash found in database.' );
1291 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1295 $this->mNewpassword
= $passwordFactory->newFromCiphertext( $row->user_newpassword
);
1296 } catch ( PasswordError
$e ) {
1297 wfDebug( 'Invalid password hash found in database.' );
1298 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1301 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1302 $this->mPasswordExpires
= wfTimestampOrNull( TS_MW
, $row->user_password_expires
);
1305 if ( isset( $row->user_email
) ) {
1306 $this->mEmail
= $row->user_email
;
1307 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1308 $this->mToken
= $row->user_token
;
1309 if ( $this->mToken
== '' ) {
1310 $this->mToken
= null;
1312 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1313 $this->mEmailToken
= $row->user_email_token
;
1314 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1315 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1321 $this->mLoadedItems
= true;
1324 if ( is_array( $data ) ) {
1325 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1326 $this->mGroups
= $data['user_groups'];
1328 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1329 $this->loadOptions( $data['user_properties'] );
1335 * Load the data for this user object from another user object.
1339 protected function loadFromUserObject( $user ) {
1341 $user->loadGroups();
1342 $user->loadOptions();
1343 foreach ( self
::$mCacheVars as $var ) {
1344 $this->$var = $user->$var;
1349 * Load the groups from the database if they aren't already loaded.
1351 private function loadGroups() {
1352 if ( is_null( $this->mGroups
) ) {
1353 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1354 ?
wfGetDB( DB_MASTER
)
1355 : wfGetDB( DB_SLAVE
);
1356 $res = $db->select( 'user_groups',
1357 array( 'ug_group' ),
1358 array( 'ug_user' => $this->mId
),
1360 $this->mGroups
= array();
1361 foreach ( $res as $row ) {
1362 $this->mGroups
[] = $row->ug_group
;
1368 * Load the user's password hashes from the database
1370 * This is usually called in a scenario where the actual User object was
1371 * loaded from the cache, and then password comparison needs to be performed.
1372 * Password hashes are not stored in memcached.
1376 private function loadPasswords() {
1377 if ( $this->getId() !== 0 &&
1378 ( $this->mPassword
=== null ||
$this->mNewpassword
=== null )
1380 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1381 ?
wfGetDB( DB_MASTER
)
1382 : wfGetDB( DB_SLAVE
);
1384 $this->loadFromRow( $db->selectRow(
1386 array( 'user_password', 'user_newpassword',
1387 'user_newpass_time', 'user_password_expires' ),
1388 array( 'user_id' => $this->getId() ),
1395 * Add the user to the group if he/she meets given criteria.
1397 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1398 * possible to remove manually via Special:UserRights. In such case it
1399 * will not be re-added automatically. The user will also not lose the
1400 * group if they no longer meet the criteria.
1402 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1404 * @return array Array of groups the user has been promoted to.
1406 * @see $wgAutopromoteOnce
1408 public function addAutopromoteOnceGroups( $event ) {
1409 global $wgAutopromoteOnceLogInRC, $wgAuth;
1411 if ( wfReadOnly() ||
!$this->getId() ) {
1415 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1416 if ( !count( $toPromote ) ) {
1420 if ( !$this->checkAndSetTouched() ) {
1421 return array(); // raced out (bug T48834)
1424 $oldGroups = $this->getGroups(); // previous groups
1425 foreach ( $toPromote as $group ) {
1426 $this->addGroup( $group );
1429 // update groups in external authentication database
1430 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1432 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1434 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1435 $logEntry->setPerformer( $this );
1436 $logEntry->setTarget( $this->getUserPage() );
1437 $logEntry->setParameters( array(
1438 '4::oldgroups' => $oldGroups,
1439 '5::newgroups' => $newGroups,
1441 $logid = $logEntry->insert();
1442 if ( $wgAutopromoteOnceLogInRC ) {
1443 $logEntry->publish( $logid );
1450 * Bump user_touched if it didn't change since this object was loaded
1452 * On success, the mTouched field is updated.
1453 * The user serialization cache is always cleared.
1455 * @return bool Whether user_touched was actually updated
1458 protected function checkAndSetTouched() {
1461 if ( !$this->mId
) {
1462 return false; // anon
1465 // Get a new user_touched that is higher than the old one
1466 $oldTouched = $this->mTouched
;
1467 $newTouched = $this->newTouchedTimestamp();
1469 $dbw = wfGetDB( DB_MASTER
);
1470 $dbw->update( 'user',
1471 array( 'user_touched' => $dbw->timestamp( $newTouched ) ),
1473 'user_id' => $this->mId
,
1474 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1478 $success = ( $dbw->affectedRows() > 0 );
1481 $this->mTouched
= $newTouched;
1484 // Clears on failure too since that is desired if the cache is stale
1485 $this->clearSharedCache();
1491 * Clear various cached data stored in this object. The cache of the user table
1492 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1494 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1495 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1497 public function clearInstanceCache( $reloadFrom = false ) {
1498 $this->mNewtalk
= -1;
1499 $this->mDatePreference
= null;
1500 $this->mBlockedby
= -1; # Unset
1501 $this->mHash
= false;
1502 $this->mRights
= null;
1503 $this->mEffectiveGroups
= null;
1504 $this->mImplicitGroups
= null;
1505 $this->mGroups
= null;
1506 $this->mOptions
= null;
1507 $this->mOptionsLoaded
= false;
1508 $this->mEditCount
= null;
1510 if ( $reloadFrom ) {
1511 $this->mLoadedItems
= array();
1512 $this->mFrom
= $reloadFrom;
1517 * Combine the language default options with any site-specific options
1518 * and add the default language variants.
1520 * @return array Array of String options
1522 public static function getDefaultOptions() {
1523 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1525 static $defOpt = null;
1526 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1527 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1528 // mid-request and see that change reflected in the return value of this function.
1529 // Which is insane and would never happen during normal MW operation
1533 $defOpt = $wgDefaultUserOptions;
1534 // Default language setting
1535 $defOpt['language'] = $wgContLang->getCode();
1536 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1537 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1539 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1540 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1542 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1544 Hooks
::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1550 * Get a given default option value.
1552 * @param string $opt Name of option to retrieve
1553 * @return string Default option value
1555 public static function getDefaultOption( $opt ) {
1556 $defOpts = self
::getDefaultOptions();
1557 if ( isset( $defOpts[$opt] ) ) {
1558 return $defOpts[$opt];
1565 * Get blocking information
1566 * @param bool $bFromSlave Whether to check the slave database first.
1567 * To improve performance, non-critical checks are done against slaves.
1568 * Check when actually saving should be done against master.
1570 private function getBlockedStatus( $bFromSlave = true ) {
1571 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1573 if ( -1 != $this->mBlockedby
) {
1577 wfDebug( __METHOD__
. ": checking...\n" );
1579 // Initialize data...
1580 // Otherwise something ends up stomping on $this->mBlockedby when
1581 // things get lazy-loaded later, causing false positive block hits
1582 // due to -1 !== 0. Probably session-related... Nothing should be
1583 // overwriting mBlockedby, surely?
1586 # We only need to worry about passing the IP address to the Block generator if the
1587 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1588 # know which IP address they're actually coming from
1589 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1590 $ip = $this->getRequest()->getIP();
1596 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1599 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1600 && !in_array( $ip, $wgProxyWhitelist )
1603 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1605 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1606 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1607 $block->setTarget( $ip );
1608 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1610 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1611 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1612 $block->setTarget( $ip );
1616 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1617 if ( !$block instanceof Block
1618 && $wgApplyIpBlocksToXff
1620 && !$this->isAllowed( 'proxyunbannable' )
1621 && !in_array( $ip, $wgProxyWhitelist )
1623 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1624 $xff = array_map( 'trim', explode( ',', $xff ) );
1625 $xff = array_diff( $xff, array( $ip ) );
1626 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1627 $block = Block
::chooseBlock( $xffblocks, $xff );
1628 if ( $block instanceof Block
) {
1629 # Mangle the reason to alert the user that the block
1630 # originated from matching the X-Forwarded-For header.
1631 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1635 if ( $block instanceof Block
) {
1636 wfDebug( __METHOD__
. ": Found block.\n" );
1637 $this->mBlock
= $block;
1638 $this->mBlockedby
= $block->getByName();
1639 $this->mBlockreason
= $block->mReason
;
1640 $this->mHideName
= $block->mHideName
;
1641 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1643 $this->mBlockedby
= '';
1644 $this->mHideName
= 0;
1645 $this->mAllowUsertalk
= false;
1649 Hooks
::run( 'GetBlockedStatus', array( &$this ) );
1654 * Whether the given IP is in a DNS blacklist.
1656 * @param string $ip IP to check
1657 * @param bool $checkWhitelist Whether to check the whitelist first
1658 * @return bool True if blacklisted.
1660 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1661 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1663 if ( !$wgEnableDnsBlacklist ) {
1667 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1671 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1675 * Whether the given IP is in a given DNS blacklist.
1677 * @param string $ip IP to check
1678 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1679 * @return bool True if blacklisted.
1681 public function inDnsBlacklist( $ip, $bases ) {
1684 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1685 if ( IP
::isIPv4( $ip ) ) {
1686 // Reverse IP, bug 21255
1687 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1689 foreach ( (array)$bases as $base ) {
1691 // If we have an access key, use that too (ProjectHoneypot, etc.)
1692 if ( is_array( $base ) ) {
1693 if ( count( $base ) >= 2 ) {
1694 // Access key is 1, base URL is 0
1695 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1697 $host = "$ipReversed.{$base[0]}";
1700 $host = "$ipReversed.$base";
1704 $ipList = gethostbynamel( $host );
1707 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1711 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1720 * Check if an IP address is in the local proxy list
1726 public static function isLocallyBlockedProxy( $ip ) {
1727 global $wgProxyList;
1729 if ( !$wgProxyList ) {
1733 if ( !is_array( $wgProxyList ) ) {
1734 // Load from the specified file
1735 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1738 if ( !is_array( $wgProxyList ) ) {
1740 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1742 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1743 // Old-style flipped proxy list
1752 * Is this user subject to rate limiting?
1754 * @return bool True if rate limited
1756 public function isPingLimitable() {
1757 global $wgRateLimitsExcludedIPs;
1758 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1759 // No other good way currently to disable rate limits
1760 // for specific IPs. :P
1761 // But this is a crappy hack and should die.
1764 return !$this->isAllowed( 'noratelimit' );
1768 * Primitive rate limits: enforce maximum actions per time period
1769 * to put a brake on flooding.
1771 * The method generates both a generic profiling point and a per action one
1772 * (suffix being "-$action".
1774 * @note When using a shared cache like memcached, IP-address
1775 * last-hit counters will be shared across wikis.
1777 * @param string $action Action to enforce; 'edit' if unspecified
1778 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1779 * @return bool True if a rate limiter was tripped
1781 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1782 // Call the 'PingLimiter' hook
1784 if ( !Hooks
::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1788 global $wgRateLimits;
1789 if ( !isset( $wgRateLimits[$action] ) ) {
1793 // Some groups shouldn't trigger the ping limiter, ever
1794 if ( !$this->isPingLimitable() ) {
1800 $limits = $wgRateLimits[$action];
1802 $id = $this->getId();
1805 if ( isset( $limits['anon'] ) && $id == 0 ) {
1806 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1809 if ( isset( $limits['user'] ) && $id != 0 ) {
1810 $userLimit = $limits['user'];
1812 if ( $this->isNewbie() ) {
1813 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1814 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1816 if ( isset( $limits['ip'] ) ) {
1817 $ip = $this->getRequest()->getIP();
1818 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1820 if ( isset( $limits['subnet'] ) ) {
1821 $ip = $this->getRequest()->getIP();
1824 if ( IP
::isIPv6( $ip ) ) {
1825 $parts = IP
::parseRange( "$ip/64" );
1826 $subnet = $parts[0];
1827 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1829 $subnet = $matches[1];
1831 if ( $subnet !== false ) {
1832 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1836 // Check for group-specific permissions
1837 // If more than one group applies, use the group with the highest limit
1838 foreach ( $this->getGroups() as $group ) {
1839 if ( isset( $limits[$group] ) ) {
1840 if ( $userLimit === false
1841 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1843 $userLimit = $limits[$group];
1847 // Set the user limit key
1848 if ( $userLimit !== false ) {
1849 list( $max, $period ) = $userLimit;
1850 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1851 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1855 foreach ( $keys as $key => $limit ) {
1856 list( $max, $period ) = $limit;
1857 $summary = "(limit $max in {$period}s)";
1858 $count = $wgMemc->get( $key );
1861 if ( $count >= $max ) {
1862 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1863 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1866 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1869 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1870 if ( $incrBy > 0 ) {
1871 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1874 if ( $incrBy > 0 ) {
1875 $wgMemc->incr( $key, $incrBy );
1883 * Check if user is blocked
1885 * @param bool $bFromSlave Whether to check the slave database instead of
1886 * the master. Hacked from false due to horrible probs on site.
1887 * @return bool True if blocked, false otherwise
1889 public function isBlocked( $bFromSlave = true ) {
1890 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1894 * Get the block affecting the user, or null if the user is not blocked
1896 * @param bool $bFromSlave Whether to check the slave database instead of the master
1897 * @return Block|null
1899 public function getBlock( $bFromSlave = true ) {
1900 $this->getBlockedStatus( $bFromSlave );
1901 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1905 * Check if user is blocked from editing a particular article
1907 * @param Title $title Title to check
1908 * @param bool $bFromSlave Whether to check the slave database instead of the master
1911 public function isBlockedFrom( $title, $bFromSlave = false ) {
1912 global $wgBlockAllowsUTEdit;
1914 $blocked = $this->isBlocked( $bFromSlave );
1915 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1916 // If a user's name is suppressed, they cannot make edits anywhere
1917 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1918 && $title->getNamespace() == NS_USER_TALK
) {
1920 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1923 Hooks
::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1929 * If user is blocked, return the name of the user who placed the block
1930 * @return string Name of blocker
1932 public function blockedBy() {
1933 $this->getBlockedStatus();
1934 return $this->mBlockedby
;
1938 * If user is blocked, return the specified reason for the block
1939 * @return string Blocking reason
1941 public function blockedFor() {
1942 $this->getBlockedStatus();
1943 return $this->mBlockreason
;
1947 * If user is blocked, return the ID for the block
1948 * @return int Block ID
1950 public function getBlockId() {
1951 $this->getBlockedStatus();
1952 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1956 * Check if user is blocked on all wikis.
1957 * Do not use for actual edit permission checks!
1958 * This is intended for quick UI checks.
1960 * @param string $ip IP address, uses current client if none given
1961 * @return bool True if blocked, false otherwise
1963 public function isBlockedGlobally( $ip = '' ) {
1964 if ( $this->mBlockedGlobally
!== null ) {
1965 return $this->mBlockedGlobally
;
1967 // User is already an IP?
1968 if ( IP
::isIPAddress( $this->getName() ) ) {
1969 $ip = $this->getName();
1971 $ip = $this->getRequest()->getIP();
1974 Hooks
::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1975 $this->mBlockedGlobally
= (bool)$blocked;
1976 return $this->mBlockedGlobally
;
1980 * Check if user account is locked
1982 * @return bool True if locked, false otherwise
1984 public function isLocked() {
1985 if ( $this->mLocked
!== null ) {
1986 return $this->mLocked
;
1989 $authUser = $wgAuth->getUserInstance( $this );
1990 $this->mLocked
= (bool)$authUser->isLocked();
1991 return $this->mLocked
;
1995 * Check if user account is hidden
1997 * @return bool True if hidden, false otherwise
1999 public function isHidden() {
2000 if ( $this->mHideName
!== null ) {
2001 return $this->mHideName
;
2003 $this->getBlockedStatus();
2004 if ( !$this->mHideName
) {
2006 $authUser = $wgAuth->getUserInstance( $this );
2007 $this->mHideName
= (bool)$authUser->isHidden();
2009 return $this->mHideName
;
2013 * Get the user's ID.
2014 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2016 public function getId() {
2017 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2018 // Special case, we know the user is anonymous
2020 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2021 // Don't load if this was initialized from an ID
2028 * Set the user and reload all fields according to a given ID
2029 * @param int $v User ID to reload
2031 public function setId( $v ) {
2033 $this->clearInstanceCache( 'id' );
2037 * Get the user name, or the IP of an anonymous user
2038 * @return string User's name or IP address
2040 public function getName() {
2041 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2042 // Special case optimisation
2043 return $this->mName
;
2046 if ( $this->mName
=== false ) {
2048 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2050 return $this->mName
;
2055 * Set the user name.
2057 * This does not reload fields from the database according to the given
2058 * name. Rather, it is used to create a temporary "nonexistent user" for
2059 * later addition to the database. It can also be used to set the IP
2060 * address for an anonymous user to something other than the current
2063 * @note User::newFromName() has roughly the same function, when the named user
2065 * @param string $str New user name to set
2067 public function setName( $str ) {
2069 $this->mName
= $str;
2073 * Get the user's name escaped by underscores.
2074 * @return string Username escaped by underscores.
2076 public function getTitleKey() {
2077 return str_replace( ' ', '_', $this->getName() );
2081 * Check if the user has new messages.
2082 * @return bool True if the user has new messages
2084 public function getNewtalk() {
2087 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2088 if ( $this->mNewtalk
=== -1 ) {
2089 $this->mNewtalk
= false; # reset talk page status
2091 // Check memcached separately for anons, who have no
2092 // entire User object stored in there.
2093 if ( !$this->mId
) {
2094 global $wgDisableAnonTalk;
2095 if ( $wgDisableAnonTalk ) {
2096 // Anon newtalk disabled by configuration.
2097 $this->mNewtalk
= false;
2099 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2102 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2106 return (bool)$this->mNewtalk
;
2110 * Return the data needed to construct links for new talk page message
2111 * alerts. If there are new messages, this will return an associative array
2112 * with the following data:
2113 * wiki: The database name of the wiki
2114 * link: Root-relative link to the user's talk page
2115 * rev: The last talk page revision that the user has seen or null. This
2116 * is useful for building diff links.
2117 * If there are no new messages, it returns an empty array.
2118 * @note This function was designed to accomodate multiple talk pages, but
2119 * currently only returns a single link and revision.
2122 public function getNewMessageLinks() {
2124 if ( !Hooks
::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2126 } elseif ( !$this->getNewtalk() ) {
2129 $utp = $this->getTalkPage();
2130 $dbr = wfGetDB( DB_SLAVE
);
2131 // Get the "last viewed rev" timestamp from the oldest message notification
2132 $timestamp = $dbr->selectField( 'user_newtalk',
2133 'MIN(user_last_timestamp)',
2134 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2136 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2137 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2141 * Get the revision ID for the last talk page revision viewed by the talk
2143 * @return int|null Revision ID or null
2145 public function getNewMessageRevisionId() {
2146 $newMessageRevisionId = null;
2147 $newMessageLinks = $this->getNewMessageLinks();
2148 if ( $newMessageLinks ) {
2149 // Note: getNewMessageLinks() never returns more than a single link
2150 // and it is always for the same wiki, but we double-check here in
2151 // case that changes some time in the future.
2152 if ( count( $newMessageLinks ) === 1
2153 && $newMessageLinks[0]['wiki'] === wfWikiID()
2154 && $newMessageLinks[0]['rev']
2156 $newMessageRevision = $newMessageLinks[0]['rev'];
2157 $newMessageRevisionId = $newMessageRevision->getId();
2160 return $newMessageRevisionId;
2164 * Internal uncached check for new messages
2167 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2168 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2169 * @return bool True if the user has new messages
2171 protected function checkNewtalk( $field, $id ) {
2172 $dbr = wfGetDB( DB_SLAVE
);
2174 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__
);
2176 return $ok !== false;
2180 * Add or update the new messages flag
2181 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2182 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2183 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2184 * @return bool True if successful, false otherwise
2186 protected function updateNewtalk( $field, $id, $curRev = null ) {
2187 // Get timestamp of the talk page revision prior to the current one
2188 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2189 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2190 // Mark the user as having new messages since this revision
2191 $dbw = wfGetDB( DB_MASTER
);
2192 $dbw->insert( 'user_newtalk',
2193 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2196 if ( $dbw->affectedRows() ) {
2197 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2200 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2206 * Clear the new messages flag for the given user
2207 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2208 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2209 * @return bool True if successful, false otherwise
2211 protected function deleteNewtalk( $field, $id ) {
2212 $dbw = wfGetDB( DB_MASTER
);
2213 $dbw->delete( 'user_newtalk',
2214 array( $field => $id ),
2216 if ( $dbw->affectedRows() ) {
2217 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2220 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2226 * Update the 'You have new messages!' status.
2227 * @param bool $val Whether the user has new messages
2228 * @param Revision $curRev New, as yet unseen revision of the user talk
2229 * page. Ignored if null or !$val.
2231 public function setNewtalk( $val, $curRev = null ) {
2232 if ( wfReadOnly() ) {
2237 $this->mNewtalk
= $val;
2239 if ( $this->isAnon() ) {
2241 $id = $this->getName();
2244 $id = $this->getId();
2248 $changed = $this->updateNewtalk( $field, $id, $curRev );
2250 $changed = $this->deleteNewtalk( $field, $id );
2254 $this->invalidateCache();
2259 * Generate a current or new-future timestamp to be stored in the
2260 * user_touched field when we update things.
2261 * @return string Timestamp in TS_MW format
2263 private function newTouchedTimestamp() {
2264 global $wgClockSkewFudge;
2266 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2267 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2268 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2275 * Clear user data from memcached.
2276 * Use after applying fun updates to the database; caller's
2277 * responsibility to update user_touched if appropriate.
2279 * Called implicitly from invalidateCache() and saveSettings().
2281 public function clearSharedCache() {
2282 $id = $this->getId();
2284 $key = wfMemcKey( 'user', 'id', $id );
2285 ObjectCache
::getMainWANInstance()->delete( $key );
2290 * Immediately touch the user data cache for this account
2292 * Calls touch() and removes account data from memcached
2294 public function invalidateCache() {
2296 $this->clearSharedCache();
2300 * Update the "touched" timestamp for the user
2302 * This is useful on various login/logout events when making sure that
2303 * a browser or proxy that has multiple tenants does not suffer cache
2304 * pollution where the new user sees the old users content. The value
2305 * of getTouched() is checked when determining 304 vs 200 responses.
2306 * Unlike invalidateCache(), this preserves the User object cache and
2307 * avoids database writes.
2311 public function touch() {
2312 $id = $this->getId();
2314 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2315 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2316 $this->mQuickTouched
= null;
2321 * Validate the cache for this account.
2322 * @param string $timestamp A timestamp in TS_MW format
2325 public function validateCache( $timestamp ) {
2326 return ( $timestamp >= $this->getTouched() );
2330 * Get the user touched timestamp
2332 * Use this value only to validate caches via inequalities
2333 * such as in the case of HTTP If-Modified-Since response logic
2335 * @return string TS_MW Timestamp
2337 public function getTouched() {
2341 if ( $this->mQuickTouched
=== null ) {
2342 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2343 $cache = ObjectCache
::getMainWANInstance();
2345 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2348 return max( $this->mTouched
, $this->mQuickTouched
);
2351 return $this->mTouched
;
2355 * Get the user_touched timestamp field (time of last DB updates)
2356 * @return string TS_MW Timestamp
2359 public function getDBTouched() {
2362 return $this->mTouched
;
2369 public function getPassword() {
2370 $this->loadPasswords();
2372 return $this->mPassword
;
2379 public function getTemporaryPassword() {
2380 $this->loadPasswords();
2382 return $this->mNewpassword
;
2386 * Set the password and reset the random token.
2387 * Calls through to authentication plugin if necessary;
2388 * will have no effect if the auth plugin refuses to
2389 * pass the change through or if the legal password
2392 * As a special case, setting the password to null
2393 * wipes it, so the account cannot be logged in until
2394 * a new password is set, for instance via e-mail.
2396 * @param string $str New password to set
2397 * @throws PasswordError On failure
2401 public function setPassword( $str ) {
2404 $this->loadPasswords();
2406 if ( $str !== null ) {
2407 if ( !$wgAuth->allowPasswordChange() ) {
2408 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2411 $status = $this->checkPasswordValidity( $str );
2412 if ( !$status->isGood() ) {
2413 throw new PasswordError( $status->getMessage()->text() );
2417 if ( !$wgAuth->setPassword( $this, $str ) ) {
2418 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2421 $this->setInternalPassword( $str );
2427 * Set the password and reset the random token unconditionally.
2429 * @param string|null $str New password to set or null to set an invalid
2430 * password hash meaning that the user will not be able to log in
2431 * through the web interface.
2433 public function setInternalPassword( $str ) {
2436 $passwordFactory = self
::getPasswordFactory();
2437 $this->mPassword
= $passwordFactory->newFromPlaintext( $str );
2439 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
2440 $this->mNewpassTime
= null;
2444 * Get the user's current token.
2445 * @param bool $forceCreation Force the generation of a new token if the
2446 * user doesn't have one (default=true for backwards compatibility).
2447 * @return string Token
2449 public function getToken( $forceCreation = true ) {
2451 if ( !$this->mToken
&& $forceCreation ) {
2454 return $this->mToken
;
2458 * Set the random token (used for persistent authentication)
2459 * Called from loadDefaults() among other places.
2461 * @param string|bool $token If specified, set the token to this value
2463 public function setToken( $token = false ) {
2466 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2468 $this->mToken
= $token;
2473 * Set the password for a password reminder or new account email
2475 * @param string $str New password to set or null to set an invalid
2476 * password hash meaning that the user will not be able to use it
2477 * @param bool $throttle If true, reset the throttle timestamp to the present
2479 public function setNewpassword( $str, $throttle = true ) {
2480 $this->loadPasswords();
2482 $this->mNewpassword
= self
::getPasswordFactory()->newFromPlaintext( $str );
2483 if ( $str === null ) {
2484 $this->mNewpassTime
= null;
2485 } elseif ( $throttle ) {
2486 $this->mNewpassTime
= wfTimestampNow();
2491 * Has password reminder email been sent within the last
2492 * $wgPasswordReminderResendTime hours?
2495 public function isPasswordReminderThrottled() {
2496 global $wgPasswordReminderResendTime;
2498 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2501 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2502 return time() < $expiry;
2506 * Get the user's e-mail address
2507 * @return string User's email address
2509 public function getEmail() {
2511 Hooks
::run( 'UserGetEmail', array( $this, &$this->mEmail
) );
2512 return $this->mEmail
;
2516 * Get the timestamp of the user's e-mail authentication
2517 * @return string TS_MW timestamp
2519 public function getEmailAuthenticationTimestamp() {
2521 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2522 return $this->mEmailAuthenticated
;
2526 * Set the user's e-mail address
2527 * @param string $str New e-mail address
2529 public function setEmail( $str ) {
2531 if ( $str == $this->mEmail
) {
2534 $this->invalidateEmail();
2535 $this->mEmail
= $str;
2536 Hooks
::run( 'UserSetEmail', array( $this, &$this->mEmail
) );
2540 * Set the user's e-mail address and a confirmation mail if needed.
2543 * @param string $str New e-mail address
2546 public function setEmailWithConfirmation( $str ) {
2547 global $wgEnableEmail, $wgEmailAuthentication;
2549 if ( !$wgEnableEmail ) {
2550 return Status
::newFatal( 'emaildisabled' );
2553 $oldaddr = $this->getEmail();
2554 if ( $str === $oldaddr ) {
2555 return Status
::newGood( true );
2558 $this->setEmail( $str );
2560 if ( $str !== '' && $wgEmailAuthentication ) {
2561 // Send a confirmation request to the new address if needed
2562 $type = $oldaddr != '' ?
'changed' : 'set';
2563 $result = $this->sendConfirmationMail( $type );
2564 if ( $result->isGood() ) {
2565 // Say to the caller that a confirmation mail has been sent
2566 $result->value
= 'eauth';
2569 $result = Status
::newGood( true );
2576 * Get the user's real name
2577 * @return string User's real name
2579 public function getRealName() {
2580 if ( !$this->isItemLoaded( 'realname' ) ) {
2584 return $this->mRealName
;
2588 * Set the user's real name
2589 * @param string $str New real name
2591 public function setRealName( $str ) {
2593 $this->mRealName
= $str;
2597 * Get the user's current setting for a given option.
2599 * @param string $oname The option to check
2600 * @param string $defaultOverride A default value returned if the option does not exist
2601 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2602 * @return string User's current value for the option
2603 * @see getBoolOption()
2604 * @see getIntOption()
2606 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2607 global $wgHiddenPrefs;
2608 $this->loadOptions();
2610 # We want 'disabled' preferences to always behave as the default value for
2611 # users, even if they have set the option explicitly in their settings (ie they
2612 # set it, and then it was disabled removing their ability to change it). But
2613 # we don't want to erase the preferences in the database in case the preference
2614 # is re-enabled again. So don't touch $mOptions, just override the returned value
2615 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2616 return self
::getDefaultOption( $oname );
2619 if ( array_key_exists( $oname, $this->mOptions
) ) {
2620 return $this->mOptions
[$oname];
2622 return $defaultOverride;
2627 * Get all user's options
2629 * @param int $flags Bitwise combination of:
2630 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2631 * to the default value. (Since 1.25)
2634 public function getOptions( $flags = 0 ) {
2635 global $wgHiddenPrefs;
2636 $this->loadOptions();
2637 $options = $this->mOptions
;
2639 # We want 'disabled' preferences to always behave as the default value for
2640 # users, even if they have set the option explicitly in their settings (ie they
2641 # set it, and then it was disabled removing their ability to change it). But
2642 # we don't want to erase the preferences in the database in case the preference
2643 # is re-enabled again. So don't touch $mOptions, just override the returned value
2644 foreach ( $wgHiddenPrefs as $pref ) {
2645 $default = self
::getDefaultOption( $pref );
2646 if ( $default !== null ) {
2647 $options[$pref] = $default;
2651 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2652 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2659 * Get the user's current setting for a given option, as a boolean value.
2661 * @param string $oname The option to check
2662 * @return bool User's current value for the option
2665 public function getBoolOption( $oname ) {
2666 return (bool)$this->getOption( $oname );
2670 * Get the user's current setting for a given option, as an integer value.
2672 * @param string $oname The option to check
2673 * @param int $defaultOverride A default value returned if the option does not exist
2674 * @return int User's current value for the option
2677 public function getIntOption( $oname, $defaultOverride = 0 ) {
2678 $val = $this->getOption( $oname );
2680 $val = $defaultOverride;
2682 return intval( $val );
2686 * Set the given option for a user.
2688 * You need to call saveSettings() to actually write to the database.
2690 * @param string $oname The option to set
2691 * @param mixed $val New value to set
2693 public function setOption( $oname, $val ) {
2694 $this->loadOptions();
2696 // Explicitly NULL values should refer to defaults
2697 if ( is_null( $val ) ) {
2698 $val = self
::getDefaultOption( $oname );
2701 $this->mOptions
[$oname] = $val;
2705 * Get a token stored in the preferences (like the watchlist one),
2706 * resetting it if it's empty (and saving changes).
2708 * @param string $oname The option name to retrieve the token from
2709 * @return string|bool User's current value for the option, or false if this option is disabled.
2710 * @see resetTokenFromOption()
2713 public function getTokenFromOption( $oname ) {
2714 global $wgHiddenPrefs;
2715 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2719 $token = $this->getOption( $oname );
2721 $token = $this->resetTokenFromOption( $oname );
2722 if ( !wfReadOnly() ) {
2723 $this->saveSettings();
2730 * Reset a token stored in the preferences (like the watchlist one).
2731 * *Does not* save user's preferences (similarly to setOption()).
2733 * @param string $oname The option name to reset the token in
2734 * @return string|bool New token value, or false if this option is disabled.
2735 * @see getTokenFromOption()
2738 public function resetTokenFromOption( $oname ) {
2739 global $wgHiddenPrefs;
2740 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2744 $token = MWCryptRand
::generateHex( 40 );
2745 $this->setOption( $oname, $token );
2750 * Return a list of the types of user options currently returned by
2751 * User::getOptionKinds().
2753 * Currently, the option kinds are:
2754 * - 'registered' - preferences which are registered in core MediaWiki or
2755 * by extensions using the UserGetDefaultOptions hook.
2756 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2757 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2758 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2759 * be used by user scripts.
2760 * - 'special' - "preferences" that are not accessible via User::getOptions
2761 * or User::setOptions.
2762 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2763 * These are usually legacy options, removed in newer versions.
2765 * The API (and possibly others) use this function to determine the possible
2766 * option types for validation purposes, so make sure to update this when a
2767 * new option kind is added.
2769 * @see User::getOptionKinds
2770 * @return array Option kinds
2772 public static function listOptionKinds() {
2775 'registered-multiselect',
2776 'registered-checkmatrix',
2784 * Return an associative array mapping preferences keys to the kind of a preference they're
2785 * used for. Different kinds are handled differently when setting or reading preferences.
2787 * See User::listOptionKinds for the list of valid option types that can be provided.
2789 * @see User::listOptionKinds
2790 * @param IContextSource $context
2791 * @param array $options Assoc. array with options keys to check as keys.
2792 * Defaults to $this->mOptions.
2793 * @return array The key => kind mapping data
2795 public function getOptionKinds( IContextSource
$context, $options = null ) {
2796 $this->loadOptions();
2797 if ( $options === null ) {
2798 $options = $this->mOptions
;
2801 $prefs = Preferences
::getPreferences( $this, $context );
2804 // Pull out the "special" options, so they don't get converted as
2805 // multiselect or checkmatrix.
2806 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2807 foreach ( $specialOptions as $name => $value ) {
2808 unset( $prefs[$name] );
2811 // Multiselect and checkmatrix options are stored in the database with
2812 // one key per option, each having a boolean value. Extract those keys.
2813 $multiselectOptions = array();
2814 foreach ( $prefs as $name => $info ) {
2815 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2816 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2817 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2818 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2820 foreach ( $opts as $value ) {
2821 $multiselectOptions["$prefix$value"] = true;
2824 unset( $prefs[$name] );
2827 $checkmatrixOptions = array();
2828 foreach ( $prefs as $name => $info ) {
2829 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2830 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2831 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2832 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2833 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2835 foreach ( $columns as $column ) {
2836 foreach ( $rows as $row ) {
2837 $checkmatrixOptions["$prefix$column-$row"] = true;
2841 unset( $prefs[$name] );
2845 // $value is ignored
2846 foreach ( $options as $key => $value ) {
2847 if ( isset( $prefs[$key] ) ) {
2848 $mapping[$key] = 'registered';
2849 } elseif ( isset( $multiselectOptions[$key] ) ) {
2850 $mapping[$key] = 'registered-multiselect';
2851 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2852 $mapping[$key] = 'registered-checkmatrix';
2853 } elseif ( isset( $specialOptions[$key] ) ) {
2854 $mapping[$key] = 'special';
2855 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2856 $mapping[$key] = 'userjs';
2858 $mapping[$key] = 'unused';
2866 * Reset certain (or all) options to the site defaults
2868 * The optional parameter determines which kinds of preferences will be reset.
2869 * Supported values are everything that can be reported by getOptionKinds()
2870 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2872 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2873 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2874 * for backwards-compatibility.
2875 * @param IContextSource|null $context Context source used when $resetKinds
2876 * does not contain 'all', passed to getOptionKinds().
2877 * Defaults to RequestContext::getMain() when null.
2879 public function resetOptions(
2880 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2881 IContextSource
$context = null
2884 $defaultOptions = self
::getDefaultOptions();
2886 if ( !is_array( $resetKinds ) ) {
2887 $resetKinds = array( $resetKinds );
2890 if ( in_array( 'all', $resetKinds ) ) {
2891 $newOptions = $defaultOptions;
2893 if ( $context === null ) {
2894 $context = RequestContext
::getMain();
2897 $optionKinds = $this->getOptionKinds( $context );
2898 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2899 $newOptions = array();
2901 // Use default values for the options that should be deleted, and
2902 // copy old values for the ones that shouldn't.
2903 foreach ( $this->mOptions
as $key => $value ) {
2904 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2905 if ( array_key_exists( $key, $defaultOptions ) ) {
2906 $newOptions[$key] = $defaultOptions[$key];
2909 $newOptions[$key] = $value;
2914 Hooks
::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2916 $this->mOptions
= $newOptions;
2917 $this->mOptionsLoaded
= true;
2921 * Get the user's preferred date format.
2922 * @return string User's preferred date format
2924 public function getDatePreference() {
2925 // Important migration for old data rows
2926 if ( is_null( $this->mDatePreference
) ) {
2928 $value = $this->getOption( 'date' );
2929 $map = $wgLang->getDatePreferenceMigrationMap();
2930 if ( isset( $map[$value] ) ) {
2931 $value = $map[$value];
2933 $this->mDatePreference
= $value;
2935 return $this->mDatePreference
;
2939 * Determine based on the wiki configuration and the user's options,
2940 * whether this user must be over HTTPS no matter what.
2944 public function requiresHTTPS() {
2945 global $wgSecureLogin;
2946 if ( !$wgSecureLogin ) {
2949 $https = $this->getBoolOption( 'prefershttps' );
2950 Hooks
::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2952 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2959 * Get the user preferred stub threshold
2963 public function getStubThreshold() {
2964 global $wgMaxArticleSize; # Maximum article size, in Kb
2965 $threshold = $this->getIntOption( 'stubthreshold' );
2966 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2967 // If they have set an impossible value, disable the preference
2968 // so we can use the parser cache again.
2975 * Get the permissions this user has.
2976 * @return array Array of String permission names
2978 public function getRights() {
2979 if ( is_null( $this->mRights
) ) {
2980 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2981 Hooks
::run( 'UserGetRights', array( $this, &$this->mRights
) );
2982 // Force reindexation of rights when a hook has unset one of them
2983 $this->mRights
= array_values( array_unique( $this->mRights
) );
2985 return $this->mRights
;
2989 * Get the list of explicit group memberships this user has.
2990 * The implicit * and user groups are not included.
2991 * @return array Array of String internal group names
2993 public function getGroups() {
2995 $this->loadGroups();
2996 return $this->mGroups
;
3000 * Get the list of implicit group memberships this user has.
3001 * This includes all explicit groups, plus 'user' if logged in,
3002 * '*' for all accounts, and autopromoted groups
3003 * @param bool $recache Whether to avoid the cache
3004 * @return array Array of String internal group names
3006 public function getEffectiveGroups( $recache = false ) {
3007 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3008 $this->mEffectiveGroups
= array_unique( array_merge(
3009 $this->getGroups(), // explicit groups
3010 $this->getAutomaticGroups( $recache ) // implicit groups
3012 // Hook for additional groups
3013 Hooks
::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
3014 // Force reindexation of groups when a hook has unset one of them
3015 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3017 return $this->mEffectiveGroups
;
3021 * Get the list of implicit group memberships this user has.
3022 * This includes 'user' if logged in, '*' for all accounts,
3023 * and autopromoted groups
3024 * @param bool $recache Whether to avoid the cache
3025 * @return array Array of String internal group names
3027 public function getAutomaticGroups( $recache = false ) {
3028 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3029 $this->mImplicitGroups
= array( '*' );
3030 if ( $this->getId() ) {
3031 $this->mImplicitGroups
[] = 'user';
3033 $this->mImplicitGroups
= array_unique( array_merge(
3034 $this->mImplicitGroups
,
3035 Autopromote
::getAutopromoteGroups( $this )
3039 // Assure data consistency with rights/groups,
3040 // as getEffectiveGroups() depends on this function
3041 $this->mEffectiveGroups
= null;
3044 return $this->mImplicitGroups
;
3048 * Returns the groups the user has belonged to.
3050 * The user may still belong to the returned groups. Compare with getGroups().
3052 * The function will not return groups the user had belonged to before MW 1.17
3054 * @return array Names of the groups the user has belonged to.
3056 public function getFormerGroups() {
3059 if ( is_null( $this->mFormerGroups
) ) {
3060 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3061 ?
wfGetDB( DB_MASTER
)
3062 : wfGetDB( DB_SLAVE
);
3063 $res = $db->select( 'user_former_groups',
3064 array( 'ufg_group' ),
3065 array( 'ufg_user' => $this->mId
),
3067 $this->mFormerGroups
= array();
3068 foreach ( $res as $row ) {
3069 $this->mFormerGroups
[] = $row->ufg_group
;
3073 return $this->mFormerGroups
;
3077 * Get the user's edit count.
3078 * @return int|null Null for anonymous users
3080 public function getEditCount() {
3081 if ( !$this->getId() ) {
3085 if ( $this->mEditCount
=== null ) {
3086 /* Populate the count, if it has not been populated yet */
3087 $dbr = wfGetDB( DB_SLAVE
);
3088 // check if the user_editcount field has been initialized
3089 $count = $dbr->selectField(
3090 'user', 'user_editcount',
3091 array( 'user_id' => $this->mId
),
3095 if ( $count === null ) {
3096 // it has not been initialized. do so.
3097 $count = $this->initEditCount();
3099 $this->mEditCount
= $count;
3101 return (int)$this->mEditCount
;
3105 * Add the user to the given group.
3106 * This takes immediate effect.
3107 * @param string $group Name of the group to add
3110 public function addGroup( $group ) {
3113 if ( !Hooks
::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3117 $dbw = wfGetDB( DB_MASTER
);
3118 if ( $this->getId() ) {
3119 $dbw->insert( 'user_groups',
3121 'ug_user' => $this->getID(),
3122 'ug_group' => $group,
3125 array( 'IGNORE' ) );
3128 $this->loadGroups();
3129 $this->mGroups
[] = $group;
3130 // In case loadGroups was not called before, we now have the right twice.
3131 // Get rid of the duplicate.
3132 $this->mGroups
= array_unique( $this->mGroups
);
3134 // Refresh the groups caches, and clear the rights cache so it will be
3135 // refreshed on the next call to $this->getRights().
3136 $this->getEffectiveGroups( true );
3137 $this->mRights
= null;
3139 $this->invalidateCache();
3145 * Remove the user from the given group.
3146 * This takes immediate effect.
3147 * @param string $group Name of the group to remove
3150 public function removeGroup( $group ) {
3152 if ( !Hooks
::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3156 $dbw = wfGetDB( DB_MASTER
);
3157 $dbw->delete( 'user_groups',
3159 'ug_user' => $this->getID(),
3160 'ug_group' => $group,
3163 // Remember that the user was in this group
3164 $dbw->insert( 'user_former_groups',
3166 'ufg_user' => $this->getID(),
3167 'ufg_group' => $group,
3173 $this->loadGroups();
3174 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3176 // Refresh the groups caches, and clear the rights cache so it will be
3177 // refreshed on the next call to $this->getRights().
3178 $this->getEffectiveGroups( true );
3179 $this->mRights
= null;
3181 $this->invalidateCache();
3187 * Get whether the user is logged in
3190 public function isLoggedIn() {
3191 return $this->getID() != 0;
3195 * Get whether the user is anonymous
3198 public function isAnon() {
3199 return !$this->isLoggedIn();
3203 * Check if user is allowed to access a feature / make an action
3205 * @param string $permissions,... Permissions to test
3206 * @return bool True if user is allowed to perform *any* of the given actions
3208 public function isAllowedAny( /*...*/ ) {
3209 $permissions = func_get_args();
3210 foreach ( $permissions as $permission ) {
3211 if ( $this->isAllowed( $permission ) ) {
3220 * @param string $permissions,... Permissions to test
3221 * @return bool True if the user is allowed to perform *all* of the given actions
3223 public function isAllowedAll( /*...*/ ) {
3224 $permissions = func_get_args();
3225 foreach ( $permissions as $permission ) {
3226 if ( !$this->isAllowed( $permission ) ) {
3234 * Internal mechanics of testing a permission
3235 * @param string $action
3238 public function isAllowed( $action = '' ) {
3239 if ( $action === '' ) {
3240 return true; // In the spirit of DWIM
3242 // Patrolling may not be enabled
3243 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3244 global $wgUseRCPatrol, $wgUseNPPatrol;
3245 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3249 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3250 // by misconfiguration: 0 == 'foo'
3251 return in_array( $action, $this->getRights(), true );
3255 * Check whether to enable recent changes patrol features for this user
3256 * @return bool True or false
3258 public function useRCPatrol() {
3259 global $wgUseRCPatrol;
3260 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3264 * Check whether to enable new pages patrol features for this user
3265 * @return bool True or false
3267 public function useNPPatrol() {
3268 global $wgUseRCPatrol, $wgUseNPPatrol;
3270 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3271 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3276 * Get the WebRequest object to use with this object
3278 * @return WebRequest
3280 public function getRequest() {
3281 if ( $this->mRequest
) {
3282 return $this->mRequest
;
3290 * Get the current skin, loading it if required
3291 * @return Skin The current skin
3292 * @todo FIXME: Need to check the old failback system [AV]
3293 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3295 public function getSkin() {
3296 wfDeprecated( __METHOD__
, '1.18' );
3297 return RequestContext
::getMain()->getSkin();
3301 * Get a WatchedItem for this user and $title.
3303 * @since 1.22 $checkRights parameter added
3304 * @param Title $title
3305 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3306 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3307 * @return WatchedItem
3309 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3310 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3312 if ( isset( $this->mWatchedItems
[$key] ) ) {
3313 return $this->mWatchedItems
[$key];
3316 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3317 $this->mWatchedItems
= array();
3320 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3321 return $this->mWatchedItems
[$key];
3325 * Check the watched status of an article.
3326 * @since 1.22 $checkRights parameter added
3327 * @param Title $title Title of the article to look at
3328 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3329 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3332 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3333 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3338 * @since 1.22 $checkRights parameter added
3339 * @param Title $title Title of the article to look at
3340 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3341 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3343 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3344 $this->getWatchedItem( $title, $checkRights )->addWatch();
3345 $this->invalidateCache();
3349 * Stop watching an article.
3350 * @since 1.22 $checkRights parameter added
3351 * @param Title $title Title of the article to look at
3352 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3353 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3355 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3356 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3357 $this->invalidateCache();
3361 * Clear the user's notification timestamp for the given title.
3362 * If e-notif e-mails are on, they will receive notification mails on
3363 * the next change of the page if it's watched etc.
3364 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3365 * @param Title $title Title of the article to look at
3366 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3368 public function clearNotification( &$title, $oldid = 0 ) {
3369 global $wgUseEnotif, $wgShowUpdatedMarker;
3371 // Do nothing if the database is locked to writes
3372 if ( wfReadOnly() ) {
3376 // Do nothing if not allowed to edit the watchlist
3377 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3381 // If we're working on user's talk page, we should update the talk page message indicator
3382 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3383 if ( !Hooks
::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3387 $nextid = $oldid ?
$title->getNextRevisionID( $oldid ) : null;
3389 if ( !$oldid ||
!$nextid ) {
3390 // If we're looking at the latest revision, we should definitely clear it
3391 $this->setNewtalk( false );
3393 // Otherwise we should update its revision, if it's present
3394 if ( $this->getNewtalk() ) {
3395 // Naturally the other one won't clear by itself
3396 $this->setNewtalk( false );
3397 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3402 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3406 if ( $this->isAnon() ) {
3407 // Nothing else to do...
3411 // Only update the timestamp if the page is being watched.
3412 // The query to find out if it is watched is cached both in memcached and per-invocation,
3413 // and when it does have to be executed, it can be on a slave
3414 // If this is the user's newtalk page, we always update the timestamp
3416 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3420 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3421 $force, $oldid, WatchedItem
::DEFERRED
3426 * Resets all of the given user's page-change notification timestamps.
3427 * If e-notif e-mails are on, they will receive notification mails on
3428 * the next change of any watched page.
3429 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3431 public function clearAllNotifications() {
3432 if ( wfReadOnly() ) {
3436 // Do nothing if not allowed to edit the watchlist
3437 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3441 global $wgUseEnotif, $wgShowUpdatedMarker;
3442 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3443 $this->setNewtalk( false );
3446 $id = $this->getId();
3448 $dbw = wfGetDB( DB_MASTER
);
3449 $dbw->update( 'watchlist',
3450 array( /* SET */ 'wl_notificationtimestamp' => null ),
3451 array( /* WHERE */ 'wl_user' => $id ),
3454 // We also need to clear here the "you have new message" notification for the own user_talk page;
3455 // it's cleared one page view later in WikiPage::doViewUpdates().
3460 * Set a cookie on the user's client. Wrapper for
3461 * WebResponse::setCookie
3462 * @param string $name Name of the cookie to set
3463 * @param string $value Value to set
3464 * @param int $exp Expiration time, as a UNIX time value;
3465 * if 0 or not specified, use the default $wgCookieExpiration
3466 * @param bool $secure
3467 * true: Force setting the secure attribute when setting the cookie
3468 * false: Force NOT setting the secure attribute when setting the cookie
3469 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3470 * @param array $params Array of options sent passed to WebResponse::setcookie()
3471 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3474 protected function setCookie(
3475 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3477 if ( $request === null ) {
3478 $request = $this->getRequest();
3480 $params['secure'] = $secure;
3481 $request->response()->setcookie( $name, $value, $exp, $params );
3485 * Clear a cookie on the user's client
3486 * @param string $name Name of the cookie to clear
3487 * @param bool $secure
3488 * true: Force setting the secure attribute when setting the cookie
3489 * false: Force NOT setting the secure attribute when setting the cookie
3490 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3491 * @param array $params Array of options sent passed to WebResponse::setcookie()
3493 protected function clearCookie( $name, $secure = null, $params = array() ) {
3494 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3498 * Set an extended login cookie on the user's client. The expiry of the cookie
3499 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3502 * @see User::setCookie
3504 * @param string $name Name of the cookie to set
3505 * @param string $value Value to set
3506 * @param bool $secure
3507 * true: Force setting the secure attribute when setting the cookie
3508 * false: Force NOT setting the secure attribute when setting the cookie
3509 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3511 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3512 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3515 $exp +
= $wgExtendedLoginCookieExpiration !== null
3516 ?
$wgExtendedLoginCookieExpiration
3517 : $wgCookieExpiration;
3519 $this->setCookie( $name, $value, $exp, $secure );
3523 * Set the default cookies for this session on the user's client.
3525 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3527 * @param bool $secure Whether to force secure/insecure cookies or use default
3528 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3530 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3531 global $wgExtendedLoginCookies;
3533 if ( $request === null ) {
3534 $request = $this->getRequest();
3538 if ( 0 == $this->mId
) {
3541 if ( !$this->mToken
) {
3542 // When token is empty or NULL generate a new one and then save it to the database
3543 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3544 // Simply by setting every cell in the user_token column to NULL and letting them be
3545 // regenerated as users log back into the wiki.
3547 if ( !wfReadOnly() ) {
3548 $this->saveSettings();
3552 'wsUserID' => $this->mId
,
3553 'wsToken' => $this->mToken
,
3554 'wsUserName' => $this->getName()
3557 'UserID' => $this->mId
,
3558 'UserName' => $this->getName(),
3560 if ( $rememberMe ) {
3561 $cookies['Token'] = $this->mToken
;
3563 $cookies['Token'] = false;
3566 Hooks
::run( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3568 foreach ( $session as $name => $value ) {
3569 $request->setSessionData( $name, $value );
3571 foreach ( $cookies as $name => $value ) {
3572 if ( $value === false ) {
3573 $this->clearCookie( $name );
3574 } elseif ( $rememberMe && in_array( $name, $wgExtendedLoginCookies ) ) {
3575 $this->setExtendedLoginCookie( $name, $value, $secure );
3577 $this->setCookie( $name, $value, 0, $secure, array(), $request );
3582 * If wpStickHTTPS was selected, also set an insecure cookie that
3583 * will cause the site to redirect the user to HTTPS, if they access
3584 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3585 * as the one set by centralauth (bug 53538). Also set it to session, or
3586 * standard time setting, based on if rememberme was set.
3588 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3592 $rememberMe ?
0 : null,
3594 array( 'prefix' => '' ) // no prefix
3600 * Log this user out.
3602 public function logout() {
3603 if ( Hooks
::run( 'UserLogout', array( &$this ) ) ) {
3609 * Clear the user's cookies and session, and reset the instance cache.
3612 public function doLogout() {
3613 $this->clearInstanceCache( 'defaults' );
3615 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3617 $this->clearCookie( 'UserID' );
3618 $this->clearCookie( 'Token' );
3619 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3621 // Remember when user logged out, to prevent seeing cached pages
3622 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3626 * Save this user's settings into the database.
3627 * @todo Only rarely do all these fields need to be set!
3629 public function saveSettings() {
3632 if ( wfReadOnly() ) {
3633 // @TODO: caller should deal with this instead!
3634 // This should really just be an exception.
3635 MWExceptionHandler
::logException( new DBExpectedError(
3637 "Could not update user with ID '{$this->mId}'; DB is read-only."
3643 $this->loadPasswords();
3644 if ( 0 == $this->mId
) {
3648 // Get a new user_touched that is higher than the old one.
3649 // This will be used for a CAS check as a last-resort safety
3650 // check against race conditions and slave lag.
3651 $oldTouched = $this->mTouched
;
3652 $newTouched = $this->newTouchedTimestamp();
3654 if ( !$wgAuth->allowSetLocalPassword() ) {
3655 $this->mPassword
= self
::getPasswordFactory()->newFromCiphertext( null );
3658 $dbw = wfGetDB( DB_MASTER
);
3659 $dbw->update( 'user',
3661 'user_name' => $this->mName
,
3662 'user_password' => $this->mPassword
->toString(),
3663 'user_newpassword' => $this->mNewpassword
->toString(),
3664 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3665 'user_real_name' => $this->mRealName
,
3666 'user_email' => $this->mEmail
,
3667 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3668 'user_touched' => $dbw->timestamp( $newTouched ),
3669 'user_token' => strval( $this->mToken
),
3670 'user_email_token' => $this->mEmailToken
,
3671 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3672 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires
),
3673 ), array( /* WHERE */
3674 'user_id' => $this->mId
,
3675 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3679 if ( !$dbw->affectedRows() ) {
3680 // Maybe the problem was a missed cache update; clear it to be safe
3681 $this->clearSharedCache();
3682 // User was changed in the meantime or loaded with stale data
3683 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3684 MWExceptionHandler
::logException( new MWException(
3685 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3686 "the version of the user to be saved is older than the current version."
3692 $this->mTouched
= $newTouched;
3693 $this->saveOptions();
3695 Hooks
::run( 'UserSaveSettings', array( $this ) );
3696 $this->clearSharedCache();
3697 $this->getUserPage()->invalidateCache();
3699 // T95839: clear the cache again post-commit to reduce race conditions
3700 // where stale values are written back to the cache by other threads.
3701 // Note: this *still* doesn't deal with REPEATABLE-READ snapshot lag...
3703 $dbw->onTransactionIdle( function() use ( $that ) {
3704 $that->clearSharedCache();
3709 * If only this user's username is known, and it exists, return the user ID.
3711 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3714 public function idForName( $flags = 0 ) {
3715 $s = trim( $this->getName() );
3720 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3721 ?
wfGetDB( DB_MASTER
)
3722 : wfGetDB( DB_SLAVE
);
3724 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3725 ?
array( 'FOR UPDATE' )
3728 $id = $db->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
, $options );
3729 if ( $id === false ) {
3737 * Add a user to the database, return the user object
3739 * @param string $name Username to add
3740 * @param array $params Array of Strings Non-default parameters to save to
3741 * the database as user_* fields:
3742 * - password: The user's password hash. Password logins will be disabled
3743 * if this is omitted.
3744 * - newpassword: Hash for a temporary password that has been mailed to
3746 * - email: The user's email address.
3747 * - email_authenticated: The email authentication timestamp.
3748 * - real_name: The user's real name.
3749 * - options: An associative array of non-default options.
3750 * - token: Random authentication token. Do not set.
3751 * - registration: Registration timestamp. Do not set.
3753 * @return User|null User object, or null if the username already exists.
3755 public static function createNew( $name, $params = array() ) {
3758 $user->loadPasswords();
3759 $user->setToken(); // init token
3760 if ( isset( $params['options'] ) ) {
3761 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3762 unset( $params['options'] );
3764 $dbw = wfGetDB( DB_MASTER
);
3765 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3768 'user_id' => $seqVal,
3769 'user_name' => $name,
3770 'user_password' => $user->mPassword
->toString(),
3771 'user_newpassword' => $user->mNewpassword
->toString(),
3772 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3773 'user_email' => $user->mEmail
,
3774 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3775 'user_real_name' => $user->mRealName
,
3776 'user_token' => strval( $user->mToken
),
3777 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3778 'user_editcount' => 0,
3779 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3781 foreach ( $params as $name => $value ) {
3782 $fields["user_$name"] = $value;
3784 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3785 if ( $dbw->affectedRows() ) {
3786 $newUser = User
::newFromId( $dbw->insertId() );
3794 * Add this existing user object to the database. If the user already
3795 * exists, a fatal status object is returned, and the user object is
3796 * initialised with the data from the database.
3798 * Previously, this function generated a DB error due to a key conflict
3799 * if the user already existed. Many extension callers use this function
3800 * in code along the lines of:
3802 * $user = User::newFromName( $name );
3803 * if ( !$user->isLoggedIn() ) {
3804 * $user->addToDatabase();
3806 * // do something with $user...
3808 * However, this was vulnerable to a race condition (bug 16020). By
3809 * initialising the user object if the user exists, we aim to support this
3810 * calling sequence as far as possible.
3812 * Note that if the user exists, this function will acquire a write lock,
3813 * so it is still advisable to make the call conditional on isLoggedIn(),
3814 * and to commit the transaction after calling.
3816 * @throws MWException
3819 public function addToDatabase() {
3821 $this->loadPasswords();
3822 if ( !$this->mToken
) {
3823 $this->setToken(); // init token
3826 $this->mTouched
= $this->newTouchedTimestamp();
3828 $dbw = wfGetDB( DB_MASTER
);
3829 $inWrite = $dbw->writesOrCallbacksPending();
3830 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3831 $dbw->insert( 'user',
3833 'user_id' => $seqVal,
3834 'user_name' => $this->mName
,
3835 'user_password' => $this->mPassword
->toString(),
3836 'user_newpassword' => $this->mNewpassword
->toString(),
3837 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3838 'user_email' => $this->mEmail
,
3839 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3840 'user_real_name' => $this->mRealName
,
3841 'user_token' => strval( $this->mToken
),
3842 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3843 'user_editcount' => 0,
3844 'user_touched' => $dbw->timestamp( $this->mTouched
),
3848 if ( !$dbw->affectedRows() ) {
3849 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3850 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3852 // Can't commit due to pending writes that may need atomicity.
3853 // This may cause some lock contention unlike the case below.
3854 $options = array( 'LOCK IN SHARE MODE' );
3855 $flags = self
::READ_LOCKING
;
3857 // Often, this case happens early in views before any writes when
3858 // using CentralAuth. It's should be OK to commit and break the snapshot.
3859 $dbw->commit( __METHOD__
, 'flush' );
3861 $flags = self
::READ_LATEST
;
3863 $this->mId
= $dbw->selectField( 'user', 'user_id',
3864 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3867 if ( $this->loadFromDatabase( $flags ) ) {
3872 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3873 "to insert user '{$this->mName}' row, but it was not present in select!" );
3875 return Status
::newFatal( 'userexists' );
3877 $this->mId
= $dbw->insertId();
3879 // Clear instance cache other than user table data, which is already accurate
3880 $this->clearInstanceCache();
3882 $this->saveOptions();
3883 return Status
::newGood();
3887 * If this user is logged-in and blocked,
3888 * block any IP address they've successfully logged in from.
3889 * @return bool A block was spread
3891 public function spreadAnyEditBlock() {
3892 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3893 return $this->spreadBlock();
3899 * If this (non-anonymous) user is blocked,
3900 * block the IP address they've successfully logged in from.
3901 * @return bool A block was spread
3903 protected function spreadBlock() {
3904 wfDebug( __METHOD__
. "()\n" );
3906 if ( $this->mId
== 0 ) {
3910 $userblock = Block
::newFromTarget( $this->getName() );
3911 if ( !$userblock ) {
3915 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3919 * Get whether the user is explicitly blocked from account creation.
3920 * @return bool|Block
3922 public function isBlockedFromCreateAccount() {
3923 $this->getBlockedStatus();
3924 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3925 return $this->mBlock
;
3928 # bug 13611: if the IP address the user is trying to create an account from is
3929 # blocked with createaccount disabled, prevent new account creation there even
3930 # when the user is logged in
3931 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3932 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3934 return $this->mBlockedFromCreateAccount
instanceof Block
3935 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3936 ?
$this->mBlockedFromCreateAccount
3941 * Get whether the user is blocked from using Special:Emailuser.
3944 public function isBlockedFromEmailuser() {
3945 $this->getBlockedStatus();
3946 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3950 * Get whether the user is allowed to create an account.
3953 public function isAllowedToCreateAccount() {
3954 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3958 * Get this user's personal page title.
3960 * @return Title User's personal page title
3962 public function getUserPage() {
3963 return Title
::makeTitle( NS_USER
, $this->getName() );
3967 * Get this user's talk page title.
3969 * @return Title User's talk page title
3971 public function getTalkPage() {
3972 $title = $this->getUserPage();
3973 return $title->getTalkPage();
3977 * Determine whether the user is a newbie. Newbies are either
3978 * anonymous IPs, or the most recently created accounts.
3981 public function isNewbie() {
3982 return !$this->isAllowed( 'autoconfirmed' );
3986 * Check to see if the given clear-text password is one of the accepted passwords
3987 * @param string $password User password
3988 * @return bool True if the given password is correct, otherwise False
3990 public function checkPassword( $password ) {
3991 global $wgAuth, $wgLegacyEncoding;
3993 $this->loadPasswords();
3995 // Some passwords will give a fatal Status, which means there is
3996 // some sort of technical or security reason for this password to
3997 // be completely invalid and should never be checked (e.g., T64685)
3998 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4002 // Certain authentication plugins do NOT want to save
4003 // domain passwords in a mysql database, so we should
4004 // check this (in case $wgAuth->strict() is false).
4005 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4007 } elseif ( $wgAuth->strict() ) {
4008 // Auth plugin doesn't allow local authentication
4010 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4011 // Auth plugin doesn't allow local authentication for this user name
4015 if ( !$this->mPassword
->equals( $password ) ) {
4016 if ( $wgLegacyEncoding ) {
4017 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4018 // Check for this with iconv
4019 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4020 if ( $cp1252Password === $password ||
!$this->mPassword
->equals( $cp1252Password ) ) {
4028 $passwordFactory = self
::getPasswordFactory();
4029 if ( $passwordFactory->needsUpdate( $this->mPassword
) && !wfReadOnly() ) {
4030 $this->mPassword
= $passwordFactory->newFromPlaintext( $password );
4031 $this->saveSettings();
4038 * Check if the given clear-text password matches the temporary password
4039 * sent by e-mail for password reset operations.
4041 * @param string $plaintext
4043 * @return bool True if matches, false otherwise
4045 public function checkTemporaryPassword( $plaintext ) {
4046 global $wgNewPasswordExpiry;
4049 $this->loadPasswords();
4050 if ( $this->mNewpassword
->equals( $plaintext ) ) {
4051 if ( is_null( $this->mNewpassTime
) ) {
4054 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
4055 return ( time() < $expiry );
4062 * Alias for getEditToken.
4063 * @deprecated since 1.19, use getEditToken instead.
4065 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4066 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4067 * @return string The new edit token
4069 public function editToken( $salt = '', $request = null ) {
4070 wfDeprecated( __METHOD__
, '1.19' );
4071 return $this->getEditToken( $salt, $request );
4075 * Internal implementation for self::getEditToken() and
4076 * self::matchEditToken().
4078 * @param string|array $salt
4079 * @param WebRequest $request
4080 * @param string|int $timestamp
4083 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
4084 if ( $this->isAnon() ) {
4085 return self
::EDIT_TOKEN_SUFFIX
;
4087 $token = $request->getSessionData( 'wsEditToken' );
4088 if ( $token === null ) {
4089 $token = MWCryptRand
::generateHex( 32 );
4090 $request->setSessionData( 'wsEditToken', $token );
4092 if ( is_array( $salt ) ) {
4093 $salt = implode( '|', $salt );
4095 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
4096 dechex( $timestamp ) .
4097 self
::EDIT_TOKEN_SUFFIX
;
4102 * Initialize (if necessary) and return a session token value
4103 * which can be used in edit forms to show that the user's
4104 * login credentials aren't being hijacked with a foreign form
4109 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4110 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4111 * @return string The new edit token
4113 public function getEditToken( $salt = '', $request = null ) {
4114 return $this->getEditTokenAtTimestamp(
4115 $salt, $request ?
: $this->getRequest(), wfTimestamp()
4120 * Generate a looking random token for various uses.
4122 * @return string The new random token
4123 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
4124 * wfRandomString for pseudo-randomness.
4126 public static function generateToken() {
4127 return MWCryptRand
::generateHex( 32 );
4131 * Get the embedded timestamp from a token.
4132 * @param string $val Input token
4135 public static function getEditTokenTimestamp( $val ) {
4136 $suffixLen = strlen( self
::EDIT_TOKEN_SUFFIX
);
4137 if ( strlen( $val ) <= 32 +
$suffixLen ) {
4141 return hexdec( substr( $val, 32, -$suffixLen ) );
4145 * Check given value against the token value stored in the session.
4146 * A match should confirm that the form was submitted from the
4147 * user's own login session, not a form submission from a third-party
4150 * @param string $val Input value to compare
4151 * @param string $salt Optional function-specific data for hashing
4152 * @param WebRequest|null $request Object to use or null to use $wgRequest
4153 * @param int $maxage Fail tokens older than this, in seconds
4154 * @return bool Whether the token matches
4156 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4157 if ( $this->isAnon() ) {
4158 return $val === self
::EDIT_TOKEN_SUFFIX
;
4161 $timestamp = self
::getEditTokenTimestamp( $val );
4162 if ( $timestamp === null ) {
4165 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
4170 $sessionToken = $this->getEditTokenAtTimestamp(
4171 $salt, $request ?
: $this->getRequest(), $timestamp
4174 if ( $val != $sessionToken ) {
4175 wfDebug( "User::matchEditToken: broken session data\n" );
4178 return hash_equals( $sessionToken, $val );
4182 * Check given value against the token value stored in the session,
4183 * ignoring the suffix.
4185 * @param string $val Input value to compare
4186 * @param string $salt Optional function-specific data for hashing
4187 * @param WebRequest|null $request Object to use or null to use $wgRequest
4188 * @param int $maxage Fail tokens older than this, in seconds
4189 * @return bool Whether the token matches
4191 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4192 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4193 return $this->matchEditToken( $val, $salt, $request, $maxage );
4197 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4198 * mail to the user's given address.
4200 * @param string $type Message to send, either "created", "changed" or "set"
4203 public function sendConfirmationMail( $type = 'created' ) {
4205 $expiration = null; // gets passed-by-ref and defined in next line.
4206 $token = $this->confirmationToken( $expiration );
4207 $url = $this->confirmationTokenUrl( $token );
4208 $invalidateURL = $this->invalidationTokenUrl( $token );
4209 $this->saveSettings();
4211 if ( $type == 'created' ||
$type === false ) {
4212 $message = 'confirmemail_body';
4213 } elseif ( $type === true ) {
4214 $message = 'confirmemail_body_changed';
4216 // Messages: confirmemail_body_changed, confirmemail_body_set
4217 $message = 'confirmemail_body_' . $type;
4220 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4221 wfMessage( $message,
4222 $this->getRequest()->getIP(),
4225 $wgLang->timeanddate( $expiration, false ),
4227 $wgLang->date( $expiration, false ),
4228 $wgLang->time( $expiration, false ) )->text() );
4232 * Send an e-mail to this user's account. Does not check for
4233 * confirmed status or validity.
4235 * @param string $subject Message subject
4236 * @param string $body Message body
4237 * @param string $from Optional From address; if unspecified, default
4238 * $wgPasswordSender will be used.
4239 * @param string $replyto Reply-To address
4242 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4243 if ( is_null( $from ) ) {
4244 global $wgPasswordSender;
4245 $sender = new MailAddress( $wgPasswordSender,
4246 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4248 $sender = MailAddress
::newFromUser( $from );
4251 $to = MailAddress
::newFromUser( $this );
4252 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
4256 * Generate, store, and return a new e-mail confirmation code.
4257 * A hash (unsalted, since it's used as a key) is stored.
4259 * @note Call saveSettings() after calling this function to commit
4260 * this change to the database.
4262 * @param string &$expiration Accepts the expiration time
4263 * @return string New token
4265 protected function confirmationToken( &$expiration ) {
4266 global $wgUserEmailConfirmationTokenExpiry;
4268 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4269 $expiration = wfTimestamp( TS_MW
, $expires );
4271 $token = MWCryptRand
::generateHex( 32 );
4272 $hash = md5( $token );
4273 $this->mEmailToken
= $hash;
4274 $this->mEmailTokenExpires
= $expiration;
4279 * Return a URL the user can use to confirm their email address.
4280 * @param string $token Accepts the email confirmation token
4281 * @return string New token URL
4283 protected function confirmationTokenUrl( $token ) {
4284 return $this->getTokenUrl( 'ConfirmEmail', $token );
4288 * Return a URL the user can use to invalidate their email address.
4289 * @param string $token Accepts the email confirmation token
4290 * @return string New token URL
4292 protected function invalidationTokenUrl( $token ) {
4293 return $this->getTokenUrl( 'InvalidateEmail', $token );
4297 * Internal function to format the e-mail validation/invalidation URLs.
4298 * This uses a quickie hack to use the
4299 * hardcoded English names of the Special: pages, for ASCII safety.
4301 * @note Since these URLs get dropped directly into emails, using the
4302 * short English names avoids insanely long URL-encoded links, which
4303 * also sometimes can get corrupted in some browsers/mailers
4304 * (bug 6957 with Gmail and Internet Explorer).
4306 * @param string $page Special page
4307 * @param string $token Token
4308 * @return string Formatted URL
4310 protected function getTokenUrl( $page, $token ) {
4311 // Hack to bypass localization of 'Special:'
4312 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4313 return $title->getCanonicalURL();
4317 * Mark the e-mail address confirmed.
4319 * @note Call saveSettings() after calling this function to commit the change.
4323 public function confirmEmail() {
4324 // Check if it's already confirmed, so we don't touch the database
4325 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4326 if ( !$this->isEmailConfirmed() ) {
4327 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4328 Hooks
::run( 'ConfirmEmailComplete', array( $this ) );
4334 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4335 * address if it was already confirmed.
4337 * @note Call saveSettings() after calling this function to commit the change.
4338 * @return bool Returns true
4340 public function invalidateEmail() {
4342 $this->mEmailToken
= null;
4343 $this->mEmailTokenExpires
= null;
4344 $this->setEmailAuthenticationTimestamp( null );
4346 Hooks
::run( 'InvalidateEmailComplete', array( $this ) );
4351 * Set the e-mail authentication timestamp.
4352 * @param string $timestamp TS_MW timestamp
4354 public function setEmailAuthenticationTimestamp( $timestamp ) {
4356 $this->mEmailAuthenticated
= $timestamp;
4357 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4361 * Is this user allowed to send e-mails within limits of current
4362 * site configuration?
4365 public function canSendEmail() {
4366 global $wgEnableEmail, $wgEnableUserEmail;
4367 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4370 $canSend = $this->isEmailConfirmed();
4371 Hooks
::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4376 * Is this user allowed to receive e-mails within limits of current
4377 * site configuration?
4380 public function canReceiveEmail() {
4381 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4385 * Is this user's e-mail address valid-looking and confirmed within
4386 * limits of the current site configuration?
4388 * @note If $wgEmailAuthentication is on, this may require the user to have
4389 * confirmed their address by returning a code or using a password
4390 * sent to the address from the wiki.
4394 public function isEmailConfirmed() {
4395 global $wgEmailAuthentication;
4398 if ( Hooks
::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4399 if ( $this->isAnon() ) {
4402 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4405 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4415 * Check whether there is an outstanding request for e-mail confirmation.
4418 public function isEmailConfirmationPending() {
4419 global $wgEmailAuthentication;
4420 return $wgEmailAuthentication &&
4421 !$this->isEmailConfirmed() &&
4422 $this->mEmailToken
&&
4423 $this->mEmailTokenExpires
> wfTimestamp();
4427 * Get the timestamp of account creation.
4429 * @return string|bool|null Timestamp of account creation, false for
4430 * non-existent/anonymous user accounts, or null if existing account
4431 * but information is not in database.
4433 public function getRegistration() {
4434 if ( $this->isAnon() ) {
4438 return $this->mRegistration
;
4442 * Get the timestamp of the first edit
4444 * @return string|bool Timestamp of first edit, or false for
4445 * non-existent/anonymous user accounts.
4447 public function getFirstEditTimestamp() {
4448 if ( $this->getId() == 0 ) {
4449 return false; // anons
4451 $dbr = wfGetDB( DB_SLAVE
);
4452 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4453 array( 'rev_user' => $this->getId() ),
4455 array( 'ORDER BY' => 'rev_timestamp ASC' )
4458 return false; // no edits
4460 return wfTimestamp( TS_MW
, $time );
4464 * Get the permissions associated with a given list of groups
4466 * @param array $groups Array of Strings List of internal group names
4467 * @return array Array of Strings List of permission key names for given groups combined
4469 public static function getGroupPermissions( $groups ) {
4470 global $wgGroupPermissions, $wgRevokePermissions;
4472 // grant every granted permission first
4473 foreach ( $groups as $group ) {
4474 if ( isset( $wgGroupPermissions[$group] ) ) {
4475 $rights = array_merge( $rights,
4476 // array_filter removes empty items
4477 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4480 // now revoke the revoked permissions
4481 foreach ( $groups as $group ) {
4482 if ( isset( $wgRevokePermissions[$group] ) ) {
4483 $rights = array_diff( $rights,
4484 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4487 return array_unique( $rights );
4491 * Get all the groups who have a given permission
4493 * @param string $role Role to check
4494 * @return array Array of Strings List of internal group names with the given permission
4496 public static function getGroupsWithPermission( $role ) {
4497 global $wgGroupPermissions;
4498 $allowedGroups = array();
4499 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4500 if ( self
::groupHasPermission( $group, $role ) ) {
4501 $allowedGroups[] = $group;
4504 return $allowedGroups;
4508 * Check, if the given group has the given permission
4510 * If you're wanting to check whether all users have a permission, use
4511 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4515 * @param string $group Group to check
4516 * @param string $role Role to check
4519 public static function groupHasPermission( $group, $role ) {
4520 global $wgGroupPermissions, $wgRevokePermissions;
4521 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4522 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4526 * Check if all users have the given permission
4529 * @param string $right Right to check
4532 public static function isEveryoneAllowed( $right ) {
4533 global $wgGroupPermissions, $wgRevokePermissions;
4534 static $cache = array();
4536 // Use the cached results, except in unit tests which rely on
4537 // being able change the permission mid-request
4538 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4539 return $cache[$right];
4542 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4543 $cache[$right] = false;
4547 // If it's revoked anywhere, then everyone doesn't have it
4548 foreach ( $wgRevokePermissions as $rights ) {
4549 if ( isset( $rights[$right] ) && $rights[$right] ) {
4550 $cache[$right] = false;
4555 // Allow extensions (e.g. OAuth) to say false
4556 if ( !Hooks
::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4557 $cache[$right] = false;
4561 $cache[$right] = true;
4566 * Get the localized descriptive name for a group, if it exists
4568 * @param string $group Internal group name
4569 * @return string Localized descriptive group name
4571 public static function getGroupName( $group ) {
4572 $msg = wfMessage( "group-$group" );
4573 return $msg->isBlank() ?
$group : $msg->text();
4577 * Get the localized descriptive name for a member of a group, if it exists
4579 * @param string $group Internal group name
4580 * @param string $username Username for gender (since 1.19)
4581 * @return string Localized name for group member
4583 public static function getGroupMember( $group, $username = '#' ) {
4584 $msg = wfMessage( "group-$group-member", $username );
4585 return $msg->isBlank() ?
$group : $msg->text();
4589 * Return the set of defined explicit groups.
4590 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4591 * are not included, as they are defined automatically, not in the database.
4592 * @return array Array of internal group names
4594 public static function getAllGroups() {
4595 global $wgGroupPermissions, $wgRevokePermissions;
4597 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4598 self
::getImplicitGroups()
4603 * Get a list of all available permissions.
4604 * @return string[] Array of permission names
4606 public static function getAllRights() {
4607 if ( self
::$mAllRights === false ) {
4608 global $wgAvailableRights;
4609 if ( count( $wgAvailableRights ) ) {
4610 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4612 self
::$mAllRights = self
::$mCoreRights;
4614 Hooks
::run( 'UserGetAllRights', array( &self
::$mAllRights ) );
4616 return self
::$mAllRights;
4620 * Get a list of implicit groups
4621 * @return array Array of Strings Array of internal group names
4623 public static function getImplicitGroups() {
4624 global $wgImplicitGroups;
4626 $groups = $wgImplicitGroups;
4627 # Deprecated, use $wgImplicitGroups instead
4628 Hooks
::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4634 * Get the title of a page describing a particular group
4636 * @param string $group Internal group name
4637 * @return Title|bool Title of the page if it exists, false otherwise
4639 public static function getGroupPage( $group ) {
4640 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4641 if ( $msg->exists() ) {
4642 $title = Title
::newFromText( $msg->text() );
4643 if ( is_object( $title ) ) {
4651 * Create a link to the group in HTML, if available;
4652 * else return the group name.
4654 * @param string $group Internal name of the group
4655 * @param string $text The text of the link
4656 * @return string HTML link to the group
4658 public static function makeGroupLinkHTML( $group, $text = '' ) {
4659 if ( $text == '' ) {
4660 $text = self
::getGroupName( $group );
4662 $title = self
::getGroupPage( $group );
4664 return Linker
::link( $title, htmlspecialchars( $text ) );
4666 return htmlspecialchars( $text );
4671 * Create a link to the group in Wikitext, if available;
4672 * else return the group name.
4674 * @param string $group Internal name of the group
4675 * @param string $text The text of the link
4676 * @return string Wikilink to the group
4678 public static function makeGroupLinkWiki( $group, $text = '' ) {
4679 if ( $text == '' ) {
4680 $text = self
::getGroupName( $group );
4682 $title = self
::getGroupPage( $group );
4684 $page = $title->getFullText();
4685 return "[[$page|$text]]";
4692 * Returns an array of the groups that a particular group can add/remove.
4694 * @param string $group The group to check for whether it can add/remove
4695 * @return array Array( 'add' => array( addablegroups ),
4696 * 'remove' => array( removablegroups ),
4697 * 'add-self' => array( addablegroups to self),
4698 * 'remove-self' => array( removable groups from self) )
4700 public static function changeableByGroup( $group ) {
4701 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4705 'remove' => array(),
4706 'add-self' => array(),
4707 'remove-self' => array()
4710 if ( empty( $wgAddGroups[$group] ) ) {
4711 // Don't add anything to $groups
4712 } elseif ( $wgAddGroups[$group] === true ) {
4713 // You get everything
4714 $groups['add'] = self
::getAllGroups();
4715 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4716 $groups['add'] = $wgAddGroups[$group];
4719 // Same thing for remove
4720 if ( empty( $wgRemoveGroups[$group] ) ) {
4722 } elseif ( $wgRemoveGroups[$group] === true ) {
4723 $groups['remove'] = self
::getAllGroups();
4724 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4725 $groups['remove'] = $wgRemoveGroups[$group];
4728 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4729 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4730 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4731 if ( is_int( $key ) ) {
4732 $wgGroupsAddToSelf['user'][] = $value;
4737 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4738 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4739 if ( is_int( $key ) ) {
4740 $wgGroupsRemoveFromSelf['user'][] = $value;
4745 // Now figure out what groups the user can add to him/herself
4746 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4748 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4749 // No idea WHY this would be used, but it's there
4750 $groups['add-self'] = User
::getAllGroups();
4751 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4752 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4755 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4757 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4758 $groups['remove-self'] = User
::getAllGroups();
4759 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4760 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4767 * Returns an array of groups that this user can add and remove
4768 * @return array Array( 'add' => array( addablegroups ),
4769 * 'remove' => array( removablegroups ),
4770 * 'add-self' => array( addablegroups to self),
4771 * 'remove-self' => array( removable groups from self) )
4773 public function changeableGroups() {
4774 if ( $this->isAllowed( 'userrights' ) ) {
4775 // This group gives the right to modify everything (reverse-
4776 // compatibility with old "userrights lets you change
4778 // Using array_merge to make the groups reindexed
4779 $all = array_merge( User
::getAllGroups() );
4783 'add-self' => array(),
4784 'remove-self' => array()
4788 // Okay, it's not so simple, we will have to go through the arrays
4791 'remove' => array(),
4792 'add-self' => array(),
4793 'remove-self' => array()
4795 $addergroups = $this->getEffectiveGroups();
4797 foreach ( $addergroups as $addergroup ) {
4798 $groups = array_merge_recursive(
4799 $groups, $this->changeableByGroup( $addergroup )
4801 $groups['add'] = array_unique( $groups['add'] );
4802 $groups['remove'] = array_unique( $groups['remove'] );
4803 $groups['add-self'] = array_unique( $groups['add-self'] );
4804 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4810 * Deferred version of incEditCountImmediate()
4812 public function incEditCount() {
4814 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $that ) {
4815 $that->incEditCountImmediate();
4820 * Increment the user's edit-count field.
4821 * Will have no effect for anonymous users.
4824 public function incEditCountImmediate() {
4825 if ( $this->isAnon() ) {
4829 $dbw = wfGetDB( DB_MASTER
);
4830 // No rows will be "affected" if user_editcount is NULL
4833 array( 'user_editcount=user_editcount+1' ),
4834 array( 'user_id' => $this->getId() ),
4837 // Lazy initialization check...
4838 if ( $dbw->affectedRows() == 0 ) {
4839 // Now here's a goddamn hack...
4840 $dbr = wfGetDB( DB_SLAVE
);
4841 if ( $dbr !== $dbw ) {
4842 // If we actually have a slave server, the count is
4843 // at least one behind because the current transaction
4844 // has not been committed and replicated.
4845 $this->initEditCount( 1 );
4847 // But if DB_SLAVE is selecting the master, then the
4848 // count we just read includes the revision that was
4849 // just added in the working transaction.
4850 $this->initEditCount();
4853 // Edit count in user cache too
4854 $this->invalidateCache();
4858 * Initialize user_editcount from data out of the revision table
4860 * @param int $add Edits to add to the count from the revision table
4861 * @return int Number of edits
4863 protected function initEditCount( $add = 0 ) {
4864 // Pull from a slave to be less cruel to servers
4865 // Accuracy isn't the point anyway here
4866 $dbr = wfGetDB( DB_SLAVE
);
4867 $count = (int)$dbr->selectField(
4870 array( 'rev_user' => $this->getId() ),
4873 $count = $count +
$add;
4875 $dbw = wfGetDB( DB_MASTER
);
4878 array( 'user_editcount' => $count ),
4879 array( 'user_id' => $this->getId() ),
4887 * Get the description of a given right
4889 * @param string $right Right to query
4890 * @return string Localized description of the right
4892 public static function getRightDescription( $right ) {
4893 $key = "right-$right";
4894 $msg = wfMessage( $key );
4895 return $msg->isBlank() ?
$right : $msg->text();
4899 * Make a new-style password hash
4901 * @param string $password Plain-text password
4902 * @param bool|string $salt Optional salt, may be random or the user ID.
4903 * If unspecified or false, will generate one automatically
4904 * @return string Password hash
4905 * @deprecated since 1.24, use Password class
4907 public static function crypt( $password, $salt = false ) {
4908 wfDeprecated( __METHOD__
, '1.24' );
4909 $hash = self
::getPasswordFactory()->newFromPlaintext( $password );
4910 return $hash->toString();
4914 * Compare a password hash with a plain-text password. Requires the user
4915 * ID if there's a chance that the hash is an old-style hash.
4917 * @param string $hash Password hash
4918 * @param string $password Plain-text password to compare
4919 * @param string|bool $userId User ID for old-style password salt
4922 * @deprecated since 1.24, use Password class
4924 public static function comparePasswords( $hash, $password, $userId = false ) {
4925 wfDeprecated( __METHOD__
, '1.24' );
4927 // Check for *really* old password hashes that don't even have a type
4928 // The old hash format was just an md5 hex hash, with no type information
4929 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4930 global $wgPasswordSalt;
4931 if ( $wgPasswordSalt ) {
4932 $password = ":B:{$userId}:{$hash}";
4934 $password = ":A:{$hash}";
4938 $hash = self
::getPasswordFactory()->newFromCiphertext( $hash );
4939 return $hash->equals( $password );
4943 * Add a newuser log entry for this user.
4944 * Before 1.19 the return value was always true.
4946 * @param string|bool $action Account creation type.
4947 * - String, one of the following values:
4948 * - 'create' for an anonymous user creating an account for himself.
4949 * This will force the action's performer to be the created user itself,
4950 * no matter the value of $wgUser
4951 * - 'create2' for a logged in user creating an account for someone else
4952 * - 'byemail' when the created user will receive its password by e-mail
4953 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4954 * - Boolean means whether the account was created by e-mail (deprecated):
4955 * - true will be converted to 'byemail'
4956 * - false will be converted to 'create' if this object is the same as
4957 * $wgUser and to 'create2' otherwise
4959 * @param string $reason User supplied reason
4961 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4963 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4964 global $wgUser, $wgNewUserLog;
4965 if ( empty( $wgNewUserLog ) ) {
4966 return true; // disabled
4969 if ( $action === true ) {
4970 $action = 'byemail';
4971 } elseif ( $action === false ) {
4972 if ( $this->equals( $wgUser ) ) {
4975 $action = 'create2';
4979 if ( $action === 'create' ||
$action === 'autocreate' ) {
4982 $performer = $wgUser;
4985 $logEntry = new ManualLogEntry( 'newusers', $action );
4986 $logEntry->setPerformer( $performer );
4987 $logEntry->setTarget( $this->getUserPage() );
4988 $logEntry->setComment( $reason );
4989 $logEntry->setParameters( array(
4990 '4::userid' => $this->getId(),
4992 $logid = $logEntry->insert();
4994 if ( $action !== 'autocreate' ) {
4995 $logEntry->publish( $logid );
5002 * Add an autocreate newuser log entry for this user
5003 * Used by things like CentralAuth and perhaps other authplugins.
5004 * Consider calling addNewUserLogEntry() directly instead.
5008 public function addNewUserLogEntryAutoCreate() {
5009 $this->addNewUserLogEntry( 'autocreate' );
5015 * Load the user options either from cache, the database or an array
5017 * @param array $data Rows for the current user out of the user_properties table
5019 protected function loadOptions( $data = null ) {
5024 if ( $this->mOptionsLoaded
) {
5028 $this->mOptions
= self
::getDefaultOptions();
5030 if ( !$this->getId() ) {
5031 // For unlogged-in users, load language/variant options from request.
5032 // There's no need to do it for logged-in users: they can set preferences,
5033 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5034 // so don't override user's choice (especially when the user chooses site default).
5035 $variant = $wgContLang->getDefaultVariant();
5036 $this->mOptions
['variant'] = $variant;
5037 $this->mOptions
['language'] = $variant;
5038 $this->mOptionsLoaded
= true;
5042 // Maybe load from the object
5043 if ( !is_null( $this->mOptionOverrides
) ) {
5044 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5045 foreach ( $this->mOptionOverrides
as $key => $value ) {
5046 $this->mOptions
[$key] = $value;
5049 if ( !is_array( $data ) ) {
5050 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5051 // Load from database
5052 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5053 ?
wfGetDB( DB_MASTER
)
5054 : wfGetDB( DB_SLAVE
);
5056 $res = $dbr->select(
5058 array( 'up_property', 'up_value' ),
5059 array( 'up_user' => $this->getId() ),
5063 $this->mOptionOverrides
= array();
5065 foreach ( $res as $row ) {
5066 $data[$row->up_property
] = $row->up_value
;
5069 foreach ( $data as $property => $value ) {
5070 $this->mOptionOverrides
[$property] = $value;
5071 $this->mOptions
[$property] = $value;
5075 $this->mOptionsLoaded
= true;
5077 Hooks
::run( 'UserLoadOptions', array( $this, &$this->mOptions
) );
5081 * Saves the non-default options for this user, as previously set e.g. via
5082 * setOption(), in the database's "user_properties" (preferences) table.
5083 * Usually used via saveSettings().
5085 protected function saveOptions() {
5086 $this->loadOptions();
5088 // Not using getOptions(), to keep hidden preferences in database
5089 $saveOptions = $this->mOptions
;
5091 // Allow hooks to abort, for instance to save to a global profile.
5092 // Reset options to default state before saving.
5093 if ( !Hooks
::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5097 $userId = $this->getId();
5099 $insert_rows = array(); // all the new preference rows
5100 foreach ( $saveOptions as $key => $value ) {
5101 // Don't bother storing default values
5102 $defaultOption = self
::getDefaultOption( $key );
5103 if ( ( $defaultOption === null && $value !== false && $value !== null )
5104 ||
$value != $defaultOption
5106 $insert_rows[] = array(
5107 'up_user' => $userId,
5108 'up_property' => $key,
5109 'up_value' => $value,
5114 $dbw = wfGetDB( DB_MASTER
);
5116 $res = $dbw->select( 'user_properties',
5117 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
5119 // Find prior rows that need to be removed or updated. These rows will
5120 // all be deleted (the later so that INSERT IGNORE applies the new values).
5121 $keysDelete = array();
5122 foreach ( $res as $row ) {
5123 if ( !isset( $saveOptions[$row->up_property
] )
5124 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5126 $keysDelete[] = $row->up_property
;
5130 if ( count( $keysDelete ) ) {
5131 // Do the DELETE by PRIMARY KEY for prior rows.
5132 // In the past a very large portion of calls to this function are for setting
5133 // 'rememberpassword' for new accounts (a preference that has since been removed).
5134 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5135 // caused gap locks on [max user ID,+infinity) which caused high contention since
5136 // updates would pile up on each other as they are for higher (newer) user IDs.
5137 // It might not be necessary these days, but it shouldn't hurt either.
5138 $dbw->delete( 'user_properties',
5139 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
5141 // Insert the new preference rows
5142 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
5146 * Lazily instantiate and return a factory object for making passwords
5148 * @return PasswordFactory
5150 public static function getPasswordFactory() {
5151 if ( self
::$mPasswordFactory === null ) {
5152 self
::$mPasswordFactory = new PasswordFactory();
5153 self
::$mPasswordFactory->init( RequestContext
::getMain()->getConfig() );
5156 return self
::$mPasswordFactory;
5160 * Provide an array of HTML5 attributes to put on an input element
5161 * intended for the user to enter a new password. This may include
5162 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5164 * Do *not* use this when asking the user to enter his current password!
5165 * Regardless of configuration, users may have invalid passwords for whatever
5166 * reason (e.g., they were set before requirements were tightened up).
5167 * Only use it when asking for a new password, like on account creation or
5170 * Obviously, you still need to do server-side checking.
5172 * NOTE: A combination of bugs in various browsers means that this function
5173 * actually just returns array() unconditionally at the moment. May as
5174 * well keep it around for when the browser bugs get fixed, though.
5176 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5178 * @return array Array of HTML attributes suitable for feeding to
5179 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5180 * That will get confused by the boolean attribute syntax used.)
5182 public static function passwordChangeInputAttribs() {
5183 global $wgMinimalPasswordLength;
5185 if ( $wgMinimalPasswordLength == 0 ) {
5189 # Note that the pattern requirement will always be satisfied if the
5190 # input is empty, so we need required in all cases.
5192 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5193 # if e-mail confirmation is being used. Since HTML5 input validation
5194 # is b0rked anyway in some browsers, just return nothing. When it's
5195 # re-enabled, fix this code to not output required for e-mail
5197 #$ret = array( 'required' );
5200 # We can't actually do this right now, because Opera 9.6 will print out
5201 # the entered password visibly in its error message! When other
5202 # browsers add support for this attribute, or Opera fixes its support,
5203 # we can add support with a version check to avoid doing this on Opera
5204 # versions where it will be a problem. Reported to Opera as
5205 # DSK-262266, but they don't have a public bug tracker for us to follow.
5207 if ( $wgMinimalPasswordLength > 1 ) {
5208 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5209 $ret['title'] = wfMessage( 'passwordtooshort' )
5210 ->numParams( $wgMinimalPasswordLength )->text();
5218 * Return the list of user fields that should be selected to create
5219 * a new user object.
5222 public static function selectFields() {
5230 'user_email_authenticated',
5232 'user_email_token_expires',
5233 'user_registration',
5239 * Factory function for fatal permission-denied errors
5242 * @param string $permission User right required
5245 static function newFatalPermissionDeniedStatus( $permission ) {
5248 $groups = array_map(
5249 array( 'User', 'makeGroupLinkWiki' ),
5250 User
::getGroupsWithPermission( $permission )
5254 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5256 return Status
::newFatal( 'badaccess-group0' );
5261 * Checks if two user objects point to the same user.
5267 public function equals( User
$user ) {
5268 return $this->getName() === $user->getName();