3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * String Some punctuation to prevent editing from broken text-mangling proxies.
27 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
30 * The User object encapsulates all of the user-specific settings (user_id,
31 * name, rights, password, email address, options, last login time). Client
32 * classes use the getXXX() functions to access these fields. These functions
33 * do all the work of determining whether the user is logged in,
34 * whether the requested option can be satisfied from cookies or
35 * whether a database query is needed. Most of the settings needed
36 * for rendering normal pages are set in the cookie to minimize use
39 class User
implements IDBAccessObject
{
41 * @const int Number of characters in user_token field.
43 const TOKEN_LENGTH
= 32;
46 * Global constant made accessible as class constants so that autoloader
49 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
52 * @const int Serialized record version.
57 * Maximum items in $mWatchedItems
59 const MAX_WATCHED_ITEMS_CACHE
= 100;
62 * Exclude user options that are set to their default value.
65 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
68 * @var PasswordFactory Lazily loaded factory object for passwords
70 private static $mPasswordFactory = null;
73 * Array of Strings List of member variables which are saved to the
74 * shared cache (memcached). Any operation which changes the
75 * corresponding database fields must call a cache-clearing function.
78 protected static $mCacheVars = array(
86 'mEmailAuthenticated',
93 // user_properties table
98 * Array of Strings Core rights.
99 * Each of these should have a corresponding message of the form
103 protected static $mCoreRights = array(
130 'editusercssjs', #deprecated
143 'move-categorypages',
144 'move-rootuserpages',
148 'override-export-depth',
172 'userrights-interwiki',
180 * String Cached results of getAllRights()
182 protected static $mAllRights = false;
184 /** @name Cache variables */
193 * @todo Make this actually private
199 * @todo Make this actually private
202 public $mNewpassword;
204 public $mNewpassTime;
207 /** @var string TS_MW timestamp from the DB */
209 /** @var string TS_MW timestamp from cache */
210 protected $mQuickTouched;
214 public $mEmailAuthenticated;
216 protected $mEmailToken;
218 protected $mEmailTokenExpires;
220 protected $mRegistration;
222 protected $mEditCount;
226 protected $mOptionOverrides;
228 protected $mPasswordExpires;
232 * Bool Whether the cache variables have been loaded.
235 public $mOptionsLoaded;
238 * Array with already loaded items or true if all items have been loaded.
240 protected $mLoadedItems = array();
244 * String Initialization data source if mLoadedItems!==true. May be one of:
245 * - 'defaults' anonymous user initialised from class defaults
246 * - 'name' initialise from mName
247 * - 'id' initialise from mId
248 * - 'session' log in from cookies or session if possible
250 * Use the User::newFrom*() family of functions to set this.
255 * Lazy-initialized variables, invalidated with clearInstanceCache
259 protected $mDatePreference;
267 protected $mBlockreason;
269 protected $mEffectiveGroups;
271 protected $mImplicitGroups;
273 protected $mFormerGroups;
275 protected $mBlockedGlobally;
292 protected $mAllowUsertalk;
295 private $mBlockedFromCreateAccount = false;
298 private $mWatchedItems = array();
300 /** @var integer User::READ_* constant bitfield used to load data */
301 protected $queryFlagsUsed = self
::READ_NORMAL
;
303 public static $idCacheByName = array();
306 * Lightweight constructor for an anonymous user.
307 * Use the User::newFrom* factory functions for other kinds of users.
311 * @see newFromConfirmationCode()
312 * @see newFromSession()
315 public function __construct() {
316 $this->clearInstanceCache( 'defaults' );
322 public function __toString() {
323 return $this->getName();
327 * Load the user table data for this object from the source given by mFrom.
329 * @param integer $flags User::READ_* constant bitfield
331 public function load( $flags = self
::READ_LATEST
) {
332 if ( $this->mLoadedItems
=== true ) {
336 // Set it now to avoid infinite recursion in accessors
337 $this->mLoadedItems
= true;
338 $this->queryFlagsUsed
= $flags;
340 switch ( $this->mFrom
) {
342 $this->loadDefaults();
345 // @TODO: this gets the ID from a slave, assuming renames
346 // are rare. This should be controllable and more consistent.
347 $this->mId
= self
::idFromName( $this->mName
);
349 // Nonexistent user placeholder object
350 $this->loadDefaults( $this->mName
);
352 $this->loadFromId( $flags );
356 $this->loadFromId( $flags );
359 if ( !$this->loadFromSession() ) {
360 // Loading from session failed. Load defaults.
361 $this->loadDefaults();
363 Hooks
::run( 'UserLoadAfterLoadFromSession', array( $this ) );
366 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
371 * Load user table data, given mId has already been set.
372 * @param integer $flags User::READ_* constant bitfield
373 * @return bool False if the ID does not exist, true otherwise
375 public function loadFromId( $flags = self
::READ_LATEST
) {
376 if ( $this->mId
== 0 ) {
377 $this->loadDefaults();
382 $cache = $this->loadFromCache();
384 wfDebug( "User: cache miss for user {$this->mId}\n" );
386 if ( !$this->loadFromDatabase( $flags ) ) {
387 // Can't load from ID, user is anonymous
390 if ( $flags & self
::READ_LATEST
) {
391 // Only save master data back to the cache to keep it consistent.
392 // @TODO: save it anyway and have callers specifiy $flags and have
393 // load() called as needed. That requires updating MANY callers...
394 $this->saveToCache();
398 $this->mLoadedItems
= true;
399 $this->queryFlagsUsed
= $flags;
405 * Load user data from shared cache, given mId has already been set.
407 * @return bool false if the ID does not exist or data is invalid, true otherwise
410 protected function loadFromCache() {
413 if ( $this->mId
== 0 ) {
414 $this->loadDefaults();
418 $key = wfMemcKey( 'user', 'id', $this->mId
);
419 $data = $wgMemc->get( $key );
420 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
425 wfDebug( "User: got user {$this->mId} from cache\n" );
427 // Restore from cache
428 foreach ( self
::$mCacheVars as $name ) {
429 $this->$name = $data[$name];
436 * Save user data to the shared cache
438 * This method should not be called outside the User class
440 public function saveToCache() {
445 $this->loadOptions();
447 if ( $this->isAnon() ) {
448 // Anonymous users are uncached
452 // The cache needs good consistency due to its high TTL, so the user
453 // should have been loaded from the master to avoid lag amplification.
454 if ( !( $this->queryFlagsUsed
& self
::READ_LATEST
) ) {
455 wfWarn( "Cannot cache slave-loaded User object with ID '{$this->mId}'." );
460 foreach ( self
::$mCacheVars as $name ) {
461 $data[$name] = $this->$name;
463 $data['mVersion'] = self
::VERSION
;
464 $key = wfMemcKey( 'user', 'id', $this->mId
);
466 $wgMemc->set( $key, $data );
469 /** @name newFrom*() static factory methods */
473 * Static factory method for creation from username.
475 * This is slightly less efficient than newFromId(), so use newFromId() if
476 * you have both an ID and a name handy.
478 * @param string $name Username, validated by Title::newFromText()
479 * @param string|bool $validate Validate username. Takes the same parameters as
480 * User::getCanonicalName(), except that true is accepted as an alias
481 * for 'valid', for BC.
483 * @return User|bool User object, or false if the username is invalid
484 * (e.g. if it contains illegal characters or is an IP address). If the
485 * username is not present in the database, the result will be a user object
486 * with a name, zero user ID and default settings.
488 public static function newFromName( $name, $validate = 'valid' ) {
489 if ( $validate === true ) {
492 $name = self
::getCanonicalName( $name, $validate );
493 if ( $name === false ) {
496 // Create unloaded user object
500 $u->setItemLoaded( 'name' );
506 * Static factory method for creation from a given user ID.
508 * @param int $id Valid user ID
509 * @return User The corresponding User object
511 public static function newFromId( $id ) {
515 $u->setItemLoaded( 'id' );
520 * Factory method to fetch whichever user has a given email confirmation code.
521 * This code is generated when an account is created or its e-mail address
524 * If the code is invalid or has expired, returns NULL.
526 * @param string $code Confirmation code
529 public static function newFromConfirmationCode( $code ) {
530 $dbr = wfGetDB( DB_SLAVE
);
531 $id = $dbr->selectField( 'user', 'user_id', array(
532 'user_email_token' => md5( $code ),
533 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
535 if ( $id !== false ) {
536 return User
::newFromId( $id );
543 * Create a new user object using data from session or cookies. If the
544 * login credentials are invalid, the result is an anonymous user.
546 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
549 public static function newFromSession( WebRequest
$request = null ) {
551 $user->mFrom
= 'session';
552 $user->mRequest
= $request;
557 * Create a new user object from a user row.
558 * The row should have the following fields from the user table in it:
559 * - either user_name or user_id to load further data if needed (or both)
561 * - all other fields (email, password, etc.)
562 * It is useless to provide the remaining fields if either user_id,
563 * user_name and user_real_name are not provided because the whole row
564 * will be loaded once more from the database when accessing them.
566 * @param stdClass $row A row from the user table
567 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
570 public static function newFromRow( $row, $data = null ) {
572 $user->loadFromRow( $row, $data );
579 * Get the username corresponding to a given user ID
580 * @param int $id User ID
581 * @return string|bool The corresponding username
583 public static function whoIs( $id ) {
584 return UserCache
::singleton()->getProp( $id, 'name' );
588 * Get the real name of a user given their user ID
590 * @param int $id User ID
591 * @return string|bool The corresponding user's real name
593 public static function whoIsReal( $id ) {
594 return UserCache
::singleton()->getProp( $id, 'real_name' );
598 * Get database id given a user name
599 * @param string $name Username
600 * @return int|null The corresponding user's ID, or null if user is nonexistent
602 public static function idFromName( $name ) {
603 $nt = Title
::makeTitleSafe( NS_USER
, $name );
604 if ( is_null( $nt ) ) {
609 if ( isset( self
::$idCacheByName[$name] ) ) {
610 return self
::$idCacheByName[$name];
613 $dbr = wfGetDB( DB_SLAVE
);
614 $s = $dbr->selectRow(
617 array( 'user_name' => $nt->getText() ),
621 if ( $s === false ) {
624 $result = $s->user_id
;
627 self
::$idCacheByName[$name] = $result;
629 if ( count( self
::$idCacheByName ) > 1000 ) {
630 self
::$idCacheByName = array();
637 * Reset the cache used in idFromName(). For use in tests.
639 public static function resetIdByNameCache() {
640 self
::$idCacheByName = array();
644 * Does the string match an anonymous IPv4 address?
646 * This function exists for username validation, in order to reject
647 * usernames which are similar in form to IP addresses. Strings such
648 * as 300.300.300.300 will return true because it looks like an IP
649 * address, despite not being strictly valid.
651 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
652 * address because the usemod software would "cloak" anonymous IP
653 * addresses like this, if we allowed accounts like this to be created
654 * new users could get the old edits of these anonymous users.
656 * @param string $name Name to match
659 public static function isIP( $name ) {
660 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
661 || IP
::isIPv6( $name );
665 * Is the input a valid username?
667 * Checks if the input is a valid username, we don't want an empty string,
668 * an IP address, anything that contains slashes (would mess up subpages),
669 * is longer than the maximum allowed username size or doesn't begin with
672 * @param string $name Name to match
675 public static function isValidUserName( $name ) {
676 global $wgContLang, $wgMaxNameChars;
679 || User
::isIP( $name )
680 ||
strpos( $name, '/' ) !== false
681 ||
strlen( $name ) > $wgMaxNameChars
682 ||
$name != $wgContLang->ucfirst( $name )
684 wfDebugLog( 'username', __METHOD__
.
685 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
689 // Ensure that the name can't be misresolved as a different title,
690 // such as with extra namespace keys at the start.
691 $parsed = Title
::newFromText( $name );
692 if ( is_null( $parsed )
693 ||
$parsed->getNamespace()
694 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
695 wfDebugLog( 'username', __METHOD__
.
696 ": '$name' invalid due to ambiguous prefixes" );
700 // Check an additional blacklist of troublemaker characters.
701 // Should these be merged into the title char list?
702 $unicodeBlacklist = '/[' .
703 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
704 '\x{00a0}' . # non-breaking space
705 '\x{2000}-\x{200f}' . # various whitespace
706 '\x{2028}-\x{202f}' . # breaks and control chars
707 '\x{3000}' . # ideographic space
708 '\x{e000}-\x{f8ff}' . # private use
710 if ( preg_match( $unicodeBlacklist, $name ) ) {
711 wfDebugLog( 'username', __METHOD__
.
712 ": '$name' invalid due to blacklisted characters" );
720 * Usernames which fail to pass this function will be blocked
721 * from user login and new account registrations, but may be used
722 * internally by batch processes.
724 * If an account already exists in this form, login will be blocked
725 * by a failure to pass this function.
727 * @param string $name Name to match
730 public static function isUsableName( $name ) {
731 global $wgReservedUsernames;
732 // Must be a valid username, obviously ;)
733 if ( !self
::isValidUserName( $name ) ) {
737 static $reservedUsernames = false;
738 if ( !$reservedUsernames ) {
739 $reservedUsernames = $wgReservedUsernames;
740 Hooks
::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
743 // Certain names may be reserved for batch processes.
744 foreach ( $reservedUsernames as $reserved ) {
745 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
746 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
748 if ( $reserved == $name ) {
756 * Usernames which fail to pass this function will be blocked
757 * from new account registrations, but may be used internally
758 * either by batch processes or by user accounts which have
759 * already been created.
761 * Additional blacklisting may be added here rather than in
762 * isValidUserName() to avoid disrupting existing accounts.
764 * @param string $name String to match
767 public static function isCreatableName( $name ) {
768 global $wgInvalidUsernameCharacters;
770 // Ensure that the username isn't longer than 235 bytes, so that
771 // (at least for the builtin skins) user javascript and css files
772 // will work. (bug 23080)
773 if ( strlen( $name ) > 235 ) {
774 wfDebugLog( 'username', __METHOD__
.
775 ": '$name' invalid due to length" );
779 // Preg yells if you try to give it an empty string
780 if ( $wgInvalidUsernameCharacters !== '' ) {
781 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
782 wfDebugLog( 'username', __METHOD__
.
783 ": '$name' invalid due to wgInvalidUsernameCharacters" );
788 return self
::isUsableName( $name );
792 * Is the input a valid password for this user?
794 * @param string $password Desired password
797 public function isValidPassword( $password ) {
798 //simple boolean wrapper for getPasswordValidity
799 return $this->getPasswordValidity( $password ) === true;
804 * Given unvalidated password input, return error message on failure.
806 * @param string $password Desired password
807 * @return bool|string|array True on success, string or array of error message on failure
809 public function getPasswordValidity( $password ) {
810 $result = $this->checkPasswordValidity( $password );
811 if ( $result->isGood() ) {
815 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
816 $messages[] = $error['message'];
818 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
819 $messages[] = $warning['message'];
821 if ( count( $messages ) === 1 ) {
829 * Check if this is a valid password for this user
831 * Create a Status object based on the password's validity.
832 * The Status should be set to fatal if the user should not
833 * be allowed to log in, and should have any errors that
834 * would block changing the password.
836 * If the return value of this is not OK, the password
837 * should not be checked. If the return value is not Good,
838 * the password can be checked, but the user should not be
839 * able to set their password to this.
841 * @param string $password Desired password
845 public function checkPasswordValidity( $password ) {
846 global $wgMinimalPasswordLength, $wgMaximalPasswordLength, $wgContLang;
848 static $blockedLogins = array(
849 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
850 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
853 $status = Status
::newGood();
855 $result = false; //init $result to false for the internal checks
857 if ( !Hooks
::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
858 $status->error( $result );
862 if ( $result === false ) {
863 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
864 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
866 } elseif ( strlen( $password ) > $wgMaximalPasswordLength ) {
867 // T64685: Password too long, might cause DoS attack
868 $status->fatal( 'passwordtoolong', $wgMaximalPasswordLength );
870 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
871 $status->error( 'password-name-match' );
873 } elseif ( isset( $blockedLogins[$this->getName()] )
874 && $password == $blockedLogins[$this->getName()]
876 $status->error( 'password-login-forbidden' );
879 //it seems weird returning a Good status here, but this is because of the
880 //initialization of $result to false above. If the hook is never run or it
881 //doesn't modify $result, then we will likely get down into this if with
885 } elseif ( $result === true ) {
888 $status->error( $result );
889 return $status; //the isValidPassword hook set a string $result and returned true
894 * Expire a user's password
896 * @param int $ts Optional timestamp to convert, default 0 for the current time
898 public function expirePassword( $ts = 0 ) {
899 $this->loadPasswords();
900 $timestamp = wfTimestamp( TS_MW
, $ts );
901 $this->mPasswordExpires
= $timestamp;
902 $this->saveSettings();
906 * Clear the password expiration for a user
908 * @param bool $load Ensure user object is loaded first
910 public function resetPasswordExpiration( $load = true ) {
911 global $wgPasswordExpirationDays;
916 if ( $wgPasswordExpirationDays ) {
917 $newExpire = wfTimestamp(
919 time() +
( $wgPasswordExpirationDays * 24 * 3600 )
922 // Give extensions a chance to force an expiration
923 Hooks
::run( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
924 $this->mPasswordExpires
= $newExpire;
928 * Check if the user's password is expired.
929 * TODO: Put this and password length into a PasswordPolicy object
931 * @return string|bool The expiration type, or false if not expired
932 * hard: A password change is required to login
933 * soft: Allow login, but encourage password change
934 * false: Password is not expired
936 public function getPasswordExpired() {
937 global $wgPasswordExpireGrace;
939 $now = wfTimestamp();
940 $expiration = $this->getPasswordExpireDate();
941 $expUnix = wfTimestamp( TS_UNIX
, $expiration );
942 if ( $expiration !== null && $expUnix < $now ) {
943 $expired = ( $expUnix +
$wgPasswordExpireGrace < $now ) ?
'hard' : 'soft';
949 * Get this user's password expiration date. Since this may be using
950 * the cached User object, we assume that whatever mechanism is setting
951 * the expiration date is also expiring the User cache.
953 * @return string|bool The datestamp of the expiration, or null if not set
955 public function getPasswordExpireDate() {
957 return $this->mPasswordExpires
;
961 * Given unvalidated user input, return a canonical username, or false if
962 * the username is invalid.
963 * @param string $name User input
964 * @param string|bool $validate Type of validation to use:
965 * - false No validation
966 * - 'valid' Valid for batch processes
967 * - 'usable' Valid for batch processes and login
968 * - 'creatable' Valid for batch processes, login and account creation
970 * @throws MWException
971 * @return bool|string
973 public static function getCanonicalName( $name, $validate = 'valid' ) {
974 // Force usernames to capital
976 $name = $wgContLang->ucfirst( $name );
978 # Reject names containing '#'; these will be cleaned up
979 # with title normalisation, but then it's too late to
981 if ( strpos( $name, '#' ) !== false ) {
985 // Clean up name according to title rules,
986 // but only when validation is requested (bug 12654)
987 $t = ( $validate !== false ) ?
988 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
989 // Check for invalid titles
990 if ( is_null( $t ) ) {
994 // Reject various classes of invalid names
996 $name = $wgAuth->getCanonicalName( $t->getText() );
998 switch ( $validate ) {
1002 if ( !User
::isValidUserName( $name ) ) {
1007 if ( !User
::isUsableName( $name ) ) {
1012 if ( !User
::isCreatableName( $name ) ) {
1017 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
1023 * Count the number of edits of a user
1025 * @param int $uid User ID to check
1026 * @return int The user's edit count
1028 * @deprecated since 1.21 in favour of User::getEditCount
1030 public static function edits( $uid ) {
1031 wfDeprecated( __METHOD__
, '1.21' );
1032 $user = self
::newFromId( $uid );
1033 return $user->getEditCount();
1037 * Return a random password.
1039 * @return string New random password
1041 public static function randomPassword() {
1042 global $wgMinimalPasswordLength;
1043 // Decide the final password length based on our min password length,
1044 // stopping at a minimum of 10 chars.
1045 $length = max( 10, $wgMinimalPasswordLength );
1046 // Multiply by 1.25 to get the number of hex characters we need
1047 $length = $length * 1.25;
1048 // Generate random hex chars
1049 $hex = MWCryptRand
::generateHex( $length );
1050 // Convert from base 16 to base 32 to get a proper password like string
1051 return wfBaseConvert( $hex, 16, 32 );
1055 * Set cached properties to default.
1057 * @note This no longer clears uncached lazy-initialised properties;
1058 * the constructor does that instead.
1060 * @param string|bool $name
1062 public function loadDefaults( $name = false ) {
1064 $passwordFactory = self
::getPasswordFactory();
1067 $this->mName
= $name;
1068 $this->mRealName
= '';
1069 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1070 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1071 $this->mNewpassTime
= null;
1073 $this->mOptionOverrides
= null;
1074 $this->mOptionsLoaded
= false;
1076 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1077 if ( $loggedOut !== null ) {
1078 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1080 $this->mTouched
= '1'; # Allow any pages to be cached
1083 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1084 $this->mEmailAuthenticated
= null;
1085 $this->mEmailToken
= '';
1086 $this->mEmailTokenExpires
= null;
1087 $this->mPasswordExpires
= null;
1088 $this->resetPasswordExpiration( false );
1089 $this->mRegistration
= wfTimestamp( TS_MW
);
1090 $this->mGroups
= array();
1092 Hooks
::run( 'UserLoadDefaults', array( $this, $name ) );
1096 * Return whether an item has been loaded.
1098 * @param string $item Item to check. Current possibilities:
1102 * @param string $all 'all' to check if the whole object has been loaded
1103 * or any other string to check if only the item is available (e.g.
1107 public function isItemLoaded( $item, $all = 'all' ) {
1108 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1109 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1113 * Set that an item has been loaded
1115 * @param string $item
1117 protected function setItemLoaded( $item ) {
1118 if ( is_array( $this->mLoadedItems
) ) {
1119 $this->mLoadedItems
[$item] = true;
1124 * Load user data from the session or login cookie.
1126 * @return bool True if the user is logged in, false otherwise.
1128 private function loadFromSession() {
1130 Hooks
::run( 'UserLoadFromSession', array( $this, &$result ) );
1131 if ( $result !== null ) {
1135 $request = $this->getRequest();
1137 $cookieId = $request->getCookie( 'UserID' );
1138 $sessId = $request->getSessionData( 'wsUserID' );
1140 if ( $cookieId !== null ) {
1141 $sId = intval( $cookieId );
1142 if ( $sessId !== null && $cookieId != $sessId ) {
1143 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1144 cookie user ID ($sId) don't match!" );
1147 $request->setSessionData( 'wsUserID', $sId );
1148 } elseif ( $sessId !== null && $sessId != 0 ) {
1154 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1155 $sName = $request->getSessionData( 'wsUserName' );
1156 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1157 $sName = $request->getCookie( 'UserName' );
1158 $request->setSessionData( 'wsUserName', $sName );
1163 $proposedUser = User
::newFromId( $sId );
1164 $proposedUser->load( self
::READ_LATEST
);
1165 if ( !$proposedUser->isLoggedIn() ) {
1170 global $wgBlockDisablesLogin;
1171 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1172 // User blocked and we've disabled blocked user logins
1176 if ( $request->getSessionData( 'wsToken' ) ) {
1178 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1180 } elseif ( $request->getCookie( 'Token' ) ) {
1181 # Get the token from DB/cache and clean it up to remove garbage padding.
1182 # This deals with historical problems with bugs and the default column value.
1183 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1184 // Make comparison in constant time (bug 61346)
1185 $passwordCorrect = strlen( $token )
1186 && hash_equals( $token, $request->getCookie( 'Token' ) );
1189 // No session or persistent login cookie
1193 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1194 $this->loadFromUserObject( $proposedUser );
1195 $request->setSessionData( 'wsToken', $this->mToken
);
1196 wfDebug( "User: logged in from $from\n" );
1199 // Invalid credentials
1200 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1206 * Load user and user_group data from the database.
1207 * $this->mId must be set, this is how the user is identified.
1209 * @param integer $flags User::READ_* constant bitfield
1210 * @return bool True if the user exists, false if the user is anonymous
1212 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1214 $this->mId
= intval( $this->mId
);
1217 if ( !$this->mId
) {
1218 $this->loadDefaults();
1222 $db = ( $flags & self
::READ_LATEST
)
1223 ?
wfGetDB( DB_MASTER
)
1224 : wfGetDB( DB_SLAVE
);
1226 $s = $db->selectRow(
1228 self
::selectFields(),
1229 array( 'user_id' => $this->mId
),
1231 ( $flags & self
::READ_LOCKING
== self
::READ_LOCKING
)
1232 ?
array( 'LOCK IN SHARE MODE' )
1236 $this->queryFlagsUsed
= $flags;
1237 Hooks
::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1239 if ( $s !== false ) {
1240 // Initialise user table data
1241 $this->loadFromRow( $s );
1242 $this->mGroups
= null; // deferred
1243 $this->getEditCount(); // revalidation for nulls
1248 $this->loadDefaults();
1254 * Initialize this object from a row from the user table.
1256 * @param stdClass $row Row from the user table to load.
1257 * @param array $data Further user data to load into the object
1259 * user_groups Array with groups out of the user_groups table
1260 * user_properties Array with properties out of the user_properties table
1262 protected function loadFromRow( $row, $data = null ) {
1264 $passwordFactory = self
::getPasswordFactory();
1266 $this->mGroups
= null; // deferred
1268 if ( isset( $row->user_name
) ) {
1269 $this->mName
= $row->user_name
;
1270 $this->mFrom
= 'name';
1271 $this->setItemLoaded( 'name' );
1276 if ( isset( $row->user_real_name
) ) {
1277 $this->mRealName
= $row->user_real_name
;
1278 $this->setItemLoaded( 'realname' );
1283 if ( isset( $row->user_id
) ) {
1284 $this->mId
= intval( $row->user_id
);
1285 $this->mFrom
= 'id';
1286 $this->setItemLoaded( 'id' );
1291 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1292 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1295 if ( isset( $row->user_editcount
) ) {
1296 $this->mEditCount
= $row->user_editcount
;
1301 if ( isset( $row->user_password
) ) {
1302 // Check for *really* old password hashes that don't even have a type
1303 // The old hash format was just an md5 hex hash, with no type information
1304 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password
) ) {
1305 $row->user_password
= ":A:{$this->mId}:{$row->user_password}";
1309 $this->mPassword
= $passwordFactory->newFromCiphertext( $row->user_password
);
1310 } catch ( PasswordError
$e ) {
1311 wfDebug( 'Invalid password hash found in database.' );
1312 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1316 $this->mNewpassword
= $passwordFactory->newFromCiphertext( $row->user_newpassword
);
1317 } catch ( PasswordError
$e ) {
1318 wfDebug( 'Invalid password hash found in database.' );
1319 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1322 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1323 $this->mPasswordExpires
= wfTimestampOrNull( TS_MW
, $row->user_password_expires
);
1326 if ( isset( $row->user_email
) ) {
1327 $this->mEmail
= $row->user_email
;
1328 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1329 $this->mToken
= $row->user_token
;
1330 if ( $this->mToken
== '' ) {
1331 $this->mToken
= null;
1333 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1334 $this->mEmailToken
= $row->user_email_token
;
1335 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1336 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1342 $this->mLoadedItems
= true;
1345 if ( is_array( $data ) ) {
1346 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1347 $this->mGroups
= $data['user_groups'];
1349 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1350 $this->loadOptions( $data['user_properties'] );
1356 * Load the data for this user object from another user object.
1360 protected function loadFromUserObject( $user ) {
1362 $user->loadGroups();
1363 $user->loadOptions();
1364 foreach ( self
::$mCacheVars as $var ) {
1365 $this->$var = $user->$var;
1370 * Load the groups from the database if they aren't already loaded.
1372 private function loadGroups() {
1373 if ( is_null( $this->mGroups
) ) {
1374 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1375 ?
wfGetDB( DB_MASTER
)
1376 : wfGetDB( DB_SLAVE
);
1377 $res = $dbr->select( 'user_groups',
1378 array( 'ug_group' ),
1379 array( 'ug_user' => $this->mId
),
1381 $this->mGroups
= array();
1382 foreach ( $res as $row ) {
1383 $this->mGroups
[] = $row->ug_group
;
1389 * Load the user's password hashes from the database
1391 * This is usually called in a scenario where the actual User object was
1392 * loaded from the cache, and then password comparison needs to be performed.
1393 * Password hashes are not stored in memcached.
1397 private function loadPasswords() {
1398 if ( $this->getId() !== 0 && ( $this->mPassword
=== null ||
$this->mNewpassword
=== null ) ) {
1399 $this->loadFromRow( wfGetDB( DB_MASTER
)->selectRow(
1401 array( 'user_password', 'user_newpassword', 'user_newpass_time', 'user_password_expires' ),
1402 array( 'user_id' => $this->getId() ),
1409 * Add the user to the group if he/she meets given criteria.
1411 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1412 * possible to remove manually via Special:UserRights. In such case it
1413 * will not be re-added automatically. The user will also not lose the
1414 * group if they no longer meet the criteria.
1416 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1418 * @return array Array of groups the user has been promoted to.
1420 * @see $wgAutopromoteOnce
1422 public function addAutopromoteOnceGroups( $event ) {
1423 global $wgAutopromoteOnceLogInRC, $wgAuth;
1425 if ( wfReadOnly() ||
!$this->getId() ) {
1429 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1430 if ( !count( $toPromote ) ) {
1434 if ( !$this->checkAndSetTouched() ) {
1435 return array(); // raced out (bug T48834)
1438 $oldGroups = $this->getGroups(); // previous groups
1439 foreach ( $toPromote as $group ) {
1440 $this->addGroup( $group );
1443 // update groups in external authentication database
1444 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1446 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1448 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1449 $logEntry->setPerformer( $this );
1450 $logEntry->setTarget( $this->getUserPage() );
1451 $logEntry->setParameters( array(
1452 '4::oldgroups' => $oldGroups,
1453 '5::newgroups' => $newGroups,
1455 $logid = $logEntry->insert();
1456 if ( $wgAutopromoteOnceLogInRC ) {
1457 $logEntry->publish( $logid );
1464 * Bump user_touched if it didn't change since this object was loaded
1466 * On success, the mTouched field is updated.
1467 * The user serialization cache is always cleared.
1469 * @return bool Whether user_touched was actually updated
1472 protected function checkAndSetTouched() {
1475 if ( !$this->mId
) {
1476 return false; // anon
1479 // Get a new user_touched that is higher than the old one
1480 $oldTouched = $this->mTouched
;
1481 $newTouched = $this->newTouchedTimestamp();
1483 $dbw = wfGetDB( DB_MASTER
);
1484 $dbw->update( 'user',
1485 array( 'user_touched' => $dbw->timestamp( $newTouched ) ),
1487 'user_id' => $this->mId
,
1488 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1492 $success = ( $dbw->affectedRows() > 0 );
1495 $this->mTouched
= $newTouched;
1498 // Clears on failure too since that is desired if the cache is stale
1499 $this->clearSharedCache();
1505 * Clear various cached data stored in this object. The cache of the user table
1506 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1508 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1509 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1511 public function clearInstanceCache( $reloadFrom = false ) {
1512 $this->mNewtalk
= -1;
1513 $this->mDatePreference
= null;
1514 $this->mBlockedby
= -1; # Unset
1515 $this->mHash
= false;
1516 $this->mRights
= null;
1517 $this->mEffectiveGroups
= null;
1518 $this->mImplicitGroups
= null;
1519 $this->mGroups
= null;
1520 $this->mOptions
= null;
1521 $this->mOptionsLoaded
= false;
1522 $this->mEditCount
= null;
1524 if ( $reloadFrom ) {
1525 $this->mLoadedItems
= array();
1526 $this->mFrom
= $reloadFrom;
1531 * Combine the language default options with any site-specific options
1532 * and add the default language variants.
1534 * @return array Array of String options
1536 public static function getDefaultOptions() {
1537 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1539 static $defOpt = null;
1540 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1541 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1542 // mid-request and see that change reflected in the return value of this function.
1543 // Which is insane and would never happen during normal MW operation
1547 $defOpt = $wgDefaultUserOptions;
1548 // Default language setting
1549 $defOpt['language'] = $wgContLang->getCode();
1550 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1551 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1553 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1554 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1556 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1558 Hooks
::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1564 * Get a given default option value.
1566 * @param string $opt Name of option to retrieve
1567 * @return string Default option value
1569 public static function getDefaultOption( $opt ) {
1570 $defOpts = self
::getDefaultOptions();
1571 if ( isset( $defOpts[$opt] ) ) {
1572 return $defOpts[$opt];
1579 * Get blocking information
1580 * @param bool $bFromSlave Whether to check the slave database first.
1581 * To improve performance, non-critical checks are done against slaves.
1582 * Check when actually saving should be done against master.
1584 private function getBlockedStatus( $bFromSlave = true ) {
1585 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1587 if ( -1 != $this->mBlockedby
) {
1591 wfDebug( __METHOD__
. ": checking...\n" );
1593 // Initialize data...
1594 // Otherwise something ends up stomping on $this->mBlockedby when
1595 // things get lazy-loaded later, causing false positive block hits
1596 // due to -1 !== 0. Probably session-related... Nothing should be
1597 // overwriting mBlockedby, surely?
1600 # We only need to worry about passing the IP address to the Block generator if the
1601 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1602 # know which IP address they're actually coming from
1603 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1604 $ip = $this->getRequest()->getIP();
1610 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1613 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1614 && !in_array( $ip, $wgProxyWhitelist )
1617 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1619 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1620 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1621 $block->setTarget( $ip );
1622 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1624 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1625 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1626 $block->setTarget( $ip );
1630 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1631 if ( !$block instanceof Block
1632 && $wgApplyIpBlocksToXff
1634 && !$this->isAllowed( 'proxyunbannable' )
1635 && !in_array( $ip, $wgProxyWhitelist )
1637 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1638 $xff = array_map( 'trim', explode( ',', $xff ) );
1639 $xff = array_diff( $xff, array( $ip ) );
1640 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1641 $block = Block
::chooseBlock( $xffblocks, $xff );
1642 if ( $block instanceof Block
) {
1643 # Mangle the reason to alert the user that the block
1644 # originated from matching the X-Forwarded-For header.
1645 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1649 if ( $block instanceof Block
) {
1650 wfDebug( __METHOD__
. ": Found block.\n" );
1651 $this->mBlock
= $block;
1652 $this->mBlockedby
= $block->getByName();
1653 $this->mBlockreason
= $block->mReason
;
1654 $this->mHideName
= $block->mHideName
;
1655 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1657 $this->mBlockedby
= '';
1658 $this->mHideName
= 0;
1659 $this->mAllowUsertalk
= false;
1663 Hooks
::run( 'GetBlockedStatus', array( &$this ) );
1668 * Whether the given IP is in a DNS blacklist.
1670 * @param string $ip IP to check
1671 * @param bool $checkWhitelist Whether to check the whitelist first
1672 * @return bool True if blacklisted.
1674 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1675 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1677 if ( !$wgEnableDnsBlacklist ) {
1681 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1685 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1689 * Whether the given IP is in a given DNS blacklist.
1691 * @param string $ip IP to check
1692 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1693 * @return bool True if blacklisted.
1695 public function inDnsBlacklist( $ip, $bases ) {
1698 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1699 if ( IP
::isIPv4( $ip ) ) {
1700 // Reverse IP, bug 21255
1701 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1703 foreach ( (array)$bases as $base ) {
1705 // If we have an access key, use that too (ProjectHoneypot, etc.)
1706 if ( is_array( $base ) ) {
1707 if ( count( $base ) >= 2 ) {
1708 // Access key is 1, base URL is 0
1709 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1711 $host = "$ipReversed.{$base[0]}";
1714 $host = "$ipReversed.$base";
1718 $ipList = gethostbynamel( $host );
1721 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1725 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1734 * Check if an IP address is in the local proxy list
1740 public static function isLocallyBlockedProxy( $ip ) {
1741 global $wgProxyList;
1743 if ( !$wgProxyList ) {
1747 if ( !is_array( $wgProxyList ) ) {
1748 // Load from the specified file
1749 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1752 if ( !is_array( $wgProxyList ) ) {
1754 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1756 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1757 // Old-style flipped proxy list
1766 * Is this user subject to rate limiting?
1768 * @return bool True if rate limited
1770 public function isPingLimitable() {
1771 global $wgRateLimitsExcludedIPs;
1772 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1773 // No other good way currently to disable rate limits
1774 // for specific IPs. :P
1775 // But this is a crappy hack and should die.
1778 return !$this->isAllowed( 'noratelimit' );
1782 * Primitive rate limits: enforce maximum actions per time period
1783 * to put a brake on flooding.
1785 * The method generates both a generic profiling point and a per action one
1786 * (suffix being "-$action".
1788 * @note When using a shared cache like memcached, IP-address
1789 * last-hit counters will be shared across wikis.
1791 * @param string $action Action to enforce; 'edit' if unspecified
1792 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1793 * @return bool True if a rate limiter was tripped
1795 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1796 // Call the 'PingLimiter' hook
1798 if ( !Hooks
::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1802 global $wgRateLimits;
1803 if ( !isset( $wgRateLimits[$action] ) ) {
1807 // Some groups shouldn't trigger the ping limiter, ever
1808 if ( !$this->isPingLimitable() ) {
1814 $limits = $wgRateLimits[$action];
1816 $id = $this->getId();
1819 if ( isset( $limits['anon'] ) && $id == 0 ) {
1820 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1823 if ( isset( $limits['user'] ) && $id != 0 ) {
1824 $userLimit = $limits['user'];
1826 if ( $this->isNewbie() ) {
1827 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1828 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1830 if ( isset( $limits['ip'] ) ) {
1831 $ip = $this->getRequest()->getIP();
1832 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1834 if ( isset( $limits['subnet'] ) ) {
1835 $ip = $this->getRequest()->getIP();
1838 if ( IP
::isIPv6( $ip ) ) {
1839 $parts = IP
::parseRange( "$ip/64" );
1840 $subnet = $parts[0];
1841 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1843 $subnet = $matches[1];
1845 if ( $subnet !== false ) {
1846 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1850 // Check for group-specific permissions
1851 // If more than one group applies, use the group with the highest limit
1852 foreach ( $this->getGroups() as $group ) {
1853 if ( isset( $limits[$group] ) ) {
1854 if ( $userLimit === false
1855 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1857 $userLimit = $limits[$group];
1861 // Set the user limit key
1862 if ( $userLimit !== false ) {
1863 list( $max, $period ) = $userLimit;
1864 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1865 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1869 foreach ( $keys as $key => $limit ) {
1870 list( $max, $period ) = $limit;
1871 $summary = "(limit $max in {$period}s)";
1872 $count = $wgMemc->get( $key );
1875 if ( $count >= $max ) {
1876 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1877 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1880 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1883 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1884 if ( $incrBy > 0 ) {
1885 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1888 if ( $incrBy > 0 ) {
1889 $wgMemc->incr( $key, $incrBy );
1897 * Check if user is blocked
1899 * @param bool $bFromSlave Whether to check the slave database instead of
1900 * the master. Hacked from false due to horrible probs on site.
1901 * @return bool True if blocked, false otherwise
1903 public function isBlocked( $bFromSlave = true ) {
1904 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1908 * Get the block affecting the user, or null if the user is not blocked
1910 * @param bool $bFromSlave Whether to check the slave database instead of the master
1911 * @return Block|null
1913 public function getBlock( $bFromSlave = true ) {
1914 $this->getBlockedStatus( $bFromSlave );
1915 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1919 * Check if user is blocked from editing a particular article
1921 * @param Title $title Title to check
1922 * @param bool $bFromSlave Whether to check the slave database instead of the master
1925 public function isBlockedFrom( $title, $bFromSlave = false ) {
1926 global $wgBlockAllowsUTEdit;
1928 $blocked = $this->isBlocked( $bFromSlave );
1929 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1930 // If a user's name is suppressed, they cannot make edits anywhere
1931 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1932 && $title->getNamespace() == NS_USER_TALK
) {
1934 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1937 Hooks
::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1943 * If user is blocked, return the name of the user who placed the block
1944 * @return string Name of blocker
1946 public function blockedBy() {
1947 $this->getBlockedStatus();
1948 return $this->mBlockedby
;
1952 * If user is blocked, return the specified reason for the block
1953 * @return string Blocking reason
1955 public function blockedFor() {
1956 $this->getBlockedStatus();
1957 return $this->mBlockreason
;
1961 * If user is blocked, return the ID for the block
1962 * @return int Block ID
1964 public function getBlockId() {
1965 $this->getBlockedStatus();
1966 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1970 * Check if user is blocked on all wikis.
1971 * Do not use for actual edit permission checks!
1972 * This is intended for quick UI checks.
1974 * @param string $ip IP address, uses current client if none given
1975 * @return bool True if blocked, false otherwise
1977 public function isBlockedGlobally( $ip = '' ) {
1978 if ( $this->mBlockedGlobally
!== null ) {
1979 return $this->mBlockedGlobally
;
1981 // User is already an IP?
1982 if ( IP
::isIPAddress( $this->getName() ) ) {
1983 $ip = $this->getName();
1985 $ip = $this->getRequest()->getIP();
1988 Hooks
::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1989 $this->mBlockedGlobally
= (bool)$blocked;
1990 return $this->mBlockedGlobally
;
1994 * Check if user account is locked
1996 * @return bool True if locked, false otherwise
1998 public function isLocked() {
1999 if ( $this->mLocked
!== null ) {
2000 return $this->mLocked
;
2003 $authUser = $wgAuth->getUserInstance( $this );
2004 $this->mLocked
= (bool)$authUser->isLocked();
2005 return $this->mLocked
;
2009 * Check if user account is hidden
2011 * @return bool True if hidden, false otherwise
2013 public function isHidden() {
2014 if ( $this->mHideName
!== null ) {
2015 return $this->mHideName
;
2017 $this->getBlockedStatus();
2018 if ( !$this->mHideName
) {
2020 $authUser = $wgAuth->getUserInstance( $this );
2021 $this->mHideName
= (bool)$authUser->isHidden();
2023 return $this->mHideName
;
2027 * Get the user's ID.
2028 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2030 public function getId() {
2031 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2032 // Special case, we know the user is anonymous
2034 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2035 // Don't load if this was initialized from an ID
2042 * Set the user and reload all fields according to a given ID
2043 * @param int $v User ID to reload
2045 public function setId( $v ) {
2047 $this->clearInstanceCache( 'id' );
2051 * Get the user name, or the IP of an anonymous user
2052 * @return string User's name or IP address
2054 public function getName() {
2055 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2056 // Special case optimisation
2057 return $this->mName
;
2060 if ( $this->mName
=== false ) {
2062 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2064 return $this->mName
;
2069 * Set the user name.
2071 * This does not reload fields from the database according to the given
2072 * name. Rather, it is used to create a temporary "nonexistent user" for
2073 * later addition to the database. It can also be used to set the IP
2074 * address for an anonymous user to something other than the current
2077 * @note User::newFromName() has roughly the same function, when the named user
2079 * @param string $str New user name to set
2081 public function setName( $str ) {
2083 $this->mName
= $str;
2087 * Get the user's name escaped by underscores.
2088 * @return string Username escaped by underscores.
2090 public function getTitleKey() {
2091 return str_replace( ' ', '_', $this->getName() );
2095 * Check if the user has new messages.
2096 * @return bool True if the user has new messages
2098 public function getNewtalk() {
2101 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2102 if ( $this->mNewtalk
=== -1 ) {
2103 $this->mNewtalk
= false; # reset talk page status
2105 // Check memcached separately for anons, who have no
2106 // entire User object stored in there.
2107 if ( !$this->mId
) {
2108 global $wgDisableAnonTalk;
2109 if ( $wgDisableAnonTalk ) {
2110 // Anon newtalk disabled by configuration.
2111 $this->mNewtalk
= false;
2113 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2116 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2120 return (bool)$this->mNewtalk
;
2124 * Return the data needed to construct links for new talk page message
2125 * alerts. If there are new messages, this will return an associative array
2126 * with the following data:
2127 * wiki: The database name of the wiki
2128 * link: Root-relative link to the user's talk page
2129 * rev: The last talk page revision that the user has seen or null. This
2130 * is useful for building diff links.
2131 * If there are no new messages, it returns an empty array.
2132 * @note This function was designed to accomodate multiple talk pages, but
2133 * currently only returns a single link and revision.
2136 public function getNewMessageLinks() {
2138 if ( !Hooks
::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2140 } elseif ( !$this->getNewtalk() ) {
2143 $utp = $this->getTalkPage();
2144 $dbr = wfGetDB( DB_SLAVE
);
2145 // Get the "last viewed rev" timestamp from the oldest message notification
2146 $timestamp = $dbr->selectField( 'user_newtalk',
2147 'MIN(user_last_timestamp)',
2148 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2150 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2151 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2155 * Get the revision ID for the last talk page revision viewed by the talk
2157 * @return int|null Revision ID or null
2159 public function getNewMessageRevisionId() {
2160 $newMessageRevisionId = null;
2161 $newMessageLinks = $this->getNewMessageLinks();
2162 if ( $newMessageLinks ) {
2163 // Note: getNewMessageLinks() never returns more than a single link
2164 // and it is always for the same wiki, but we double-check here in
2165 // case that changes some time in the future.
2166 if ( count( $newMessageLinks ) === 1
2167 && $newMessageLinks[0]['wiki'] === wfWikiID()
2168 && $newMessageLinks[0]['rev']
2170 $newMessageRevision = $newMessageLinks[0]['rev'];
2171 $newMessageRevisionId = $newMessageRevision->getId();
2174 return $newMessageRevisionId;
2178 * Internal uncached check for new messages
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 * @return bool True if the user has new messages
2185 protected function checkNewtalk( $field, $id ) {
2186 $dbr = wfGetDB( DB_SLAVE
);
2188 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__
);
2190 return $ok !== false;
2194 * Add or update the new messages flag
2195 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2196 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2197 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2198 * @return bool True if successful, false otherwise
2200 protected function updateNewtalk( $field, $id, $curRev = null ) {
2201 // Get timestamp of the talk page revision prior to the current one
2202 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2203 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2204 // Mark the user as having new messages since this revision
2205 $dbw = wfGetDB( DB_MASTER
);
2206 $dbw->insert( 'user_newtalk',
2207 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2210 if ( $dbw->affectedRows() ) {
2211 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2214 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2220 * Clear the new messages flag for the given user
2221 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2222 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2223 * @return bool True if successful, false otherwise
2225 protected function deleteNewtalk( $field, $id ) {
2226 $dbw = wfGetDB( DB_MASTER
);
2227 $dbw->delete( 'user_newtalk',
2228 array( $field => $id ),
2230 if ( $dbw->affectedRows() ) {
2231 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2234 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2240 * Update the 'You have new messages!' status.
2241 * @param bool $val Whether the user has new messages
2242 * @param Revision $curRev New, as yet unseen revision of the user talk
2243 * page. Ignored if null or !$val.
2245 public function setNewtalk( $val, $curRev = null ) {
2246 if ( wfReadOnly() ) {
2251 $this->mNewtalk
= $val;
2253 if ( $this->isAnon() ) {
2255 $id = $this->getName();
2258 $id = $this->getId();
2263 $changed = $this->updateNewtalk( $field, $id, $curRev );
2265 $changed = $this->deleteNewtalk( $field, $id );
2268 if ( $this->isAnon() ) {
2269 // Anons have a separate memcached space, since
2270 // user records aren't kept for them.
2271 $key = wfMemcKey( 'newtalk', 'ip', $id );
2272 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
2275 $this->invalidateCache();
2280 * Generate a current or new-future timestamp to be stored in the
2281 * user_touched field when we update things.
2282 * @return string Timestamp in TS_MW format
2284 private function newTouchedTimestamp() {
2285 global $wgClockSkewFudge;
2287 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2288 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2289 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2296 * Clear user data from memcached.
2297 * Use after applying fun updates to the database; caller's
2298 * responsibility to update user_touched if appropriate.
2300 * Called implicitly from invalidateCache() and saveSettings().
2302 public function clearSharedCache() {
2307 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
2312 * Immediately touch the user data cache for this account.
2313 * Updates user_touched field, and removes account data from memcached
2314 * for reload on the next hit.
2316 public function invalidateCache() {
2317 if ( wfReadOnly() ) {
2322 $this->mTouched
= $this->newTouchedTimestamp();
2324 $dbw = wfGetDB( DB_MASTER
);
2325 $userid = $this->mId
;
2326 $touched = $this->mTouched
;
2327 $method = __METHOD__
;
2328 $dbw->onTransactionIdle( function () use ( $dbw, $userid, $touched, $method ) {
2329 // Prevent contention slams by checking user_touched first
2330 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2331 $needsPurge = $dbw->selectField( 'user', '1',
2332 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2333 if ( $needsPurge ) {
2334 $dbw->update( 'user',
2335 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2336 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2341 $this->clearSharedCache();
2346 * Update the "touched" timestamp for the user
2348 * This is useful on various login/logout events when making sure that
2349 * a browser or proxy that has multiple tenants does not suffer cache
2350 * pollution where the new user sees the old users content. The value
2351 * of getTouched() is checked when determining 304 vs 200 responses.
2352 * Unlike invalidateCache(), this preserves the User object cache and
2353 * avoids database writes.
2357 public function touch() {
2363 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2364 $timestamp = $this->newTouchedTimestamp();
2365 $wgMemc->set( $key, $timestamp );
2366 $this->mQuickTouched
= $timestamp;
2371 * Validate the cache for this account.
2372 * @param string $timestamp A timestamp in TS_MW format
2375 public function validateCache( $timestamp ) {
2376 return ( $timestamp >= $this->getTouched() );
2380 * Get the user touched timestamp
2381 * @return string TS_MW Timestamp
2383 public function getTouched() {
2389 if ( $this->mQuickTouched
=== null ) {
2390 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2391 $timestamp = $wgMemc->get( $key );
2393 $this->mQuickTouched
= $timestamp;
2395 # Set the timestamp to get HTTP 304 cache hits
2400 return max( $this->mTouched
, $this->mQuickTouched
);
2403 return $this->mTouched
;
2407 * Get the user_touched timestamp field (time of last DB updates)
2408 * @return string TS_MW Timestamp
2411 protected function getDBTouched() {
2414 return $this->mTouched
;
2421 public function getPassword() {
2422 $this->loadPasswords();
2424 return $this->mPassword
;
2431 public function getTemporaryPassword() {
2432 $this->loadPasswords();
2434 return $this->mNewpassword
;
2438 * Set the password and reset the random token.
2439 * Calls through to authentication plugin if necessary;
2440 * will have no effect if the auth plugin refuses to
2441 * pass the change through or if the legal password
2444 * As a special case, setting the password to null
2445 * wipes it, so the account cannot be logged in until
2446 * a new password is set, for instance via e-mail.
2448 * @param string $str New password to set
2449 * @throws PasswordError On failure
2453 public function setPassword( $str ) {
2456 $this->loadPasswords();
2458 if ( $str !== null ) {
2459 if ( !$wgAuth->allowPasswordChange() ) {
2460 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2463 $status = $this->checkPasswordValidity( $str );
2464 if ( !$status->isGood() ) {
2465 throw new PasswordError( $status->getMessage()->text() );
2469 if ( !$wgAuth->setPassword( $this, $str ) ) {
2470 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2473 $this->setInternalPassword( $str );
2479 * Set the password and reset the random token unconditionally.
2481 * @param string|null $str New password to set or null to set an invalid
2482 * password hash meaning that the user will not be able to log in
2483 * through the web interface.
2485 public function setInternalPassword( $str ) {
2488 $passwordFactory = self
::getPasswordFactory();
2489 $this->mPassword
= $passwordFactory->newFromPlaintext( $str );
2491 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
2492 $this->mNewpassTime
= null;
2496 * Get the user's current token.
2497 * @param bool $forceCreation Force the generation of a new token if the
2498 * user doesn't have one (default=true for backwards compatibility).
2499 * @return string Token
2501 public function getToken( $forceCreation = true ) {
2503 if ( !$this->mToken
&& $forceCreation ) {
2506 return $this->mToken
;
2510 * Set the random token (used for persistent authentication)
2511 * Called from loadDefaults() among other places.
2513 * @param string|bool $token If specified, set the token to this value
2515 public function setToken( $token = false ) {
2518 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2520 $this->mToken
= $token;
2525 * Set the password for a password reminder or new account email
2527 * @param string $str New password to set or null to set an invalid
2528 * password hash meaning that the user will not be able to use it
2529 * @param bool $throttle If true, reset the throttle timestamp to the present
2531 public function setNewpassword( $str, $throttle = true ) {
2532 $this->loadPasswords();
2534 $this->mNewpassword
= self
::getPasswordFactory()->newFromPlaintext( $str );
2535 if ( $str === null ) {
2536 $this->mNewpassTime
= null;
2537 } elseif ( $throttle ) {
2538 $this->mNewpassTime
= wfTimestampNow();
2543 * Has password reminder email been sent within the last
2544 * $wgPasswordReminderResendTime hours?
2547 public function isPasswordReminderThrottled() {
2548 global $wgPasswordReminderResendTime;
2550 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2553 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2554 return time() < $expiry;
2558 * Get the user's e-mail address
2559 * @return string User's email address
2561 public function getEmail() {
2563 Hooks
::run( 'UserGetEmail', array( $this, &$this->mEmail
) );
2564 return $this->mEmail
;
2568 * Get the timestamp of the user's e-mail authentication
2569 * @return string TS_MW timestamp
2571 public function getEmailAuthenticationTimestamp() {
2573 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2574 return $this->mEmailAuthenticated
;
2578 * Set the user's e-mail address
2579 * @param string $str New e-mail address
2581 public function setEmail( $str ) {
2583 if ( $str == $this->mEmail
) {
2586 $this->invalidateEmail();
2587 $this->mEmail
= $str;
2588 Hooks
::run( 'UserSetEmail', array( $this, &$this->mEmail
) );
2592 * Set the user's e-mail address and a confirmation mail if needed.
2595 * @param string $str New e-mail address
2598 public function setEmailWithConfirmation( $str ) {
2599 global $wgEnableEmail, $wgEmailAuthentication;
2601 if ( !$wgEnableEmail ) {
2602 return Status
::newFatal( 'emaildisabled' );
2605 $oldaddr = $this->getEmail();
2606 if ( $str === $oldaddr ) {
2607 return Status
::newGood( true );
2610 $this->setEmail( $str );
2612 if ( $str !== '' && $wgEmailAuthentication ) {
2613 // Send a confirmation request to the new address if needed
2614 $type = $oldaddr != '' ?
'changed' : 'set';
2615 $result = $this->sendConfirmationMail( $type );
2616 if ( $result->isGood() ) {
2617 // Say to the caller that a confirmation mail has been sent
2618 $result->value
= 'eauth';
2621 $result = Status
::newGood( true );
2628 * Get the user's real name
2629 * @return string User's real name
2631 public function getRealName() {
2632 if ( !$this->isItemLoaded( 'realname' ) ) {
2636 return $this->mRealName
;
2640 * Set the user's real name
2641 * @param string $str New real name
2643 public function setRealName( $str ) {
2645 $this->mRealName
= $str;
2649 * Get the user's current setting for a given option.
2651 * @param string $oname The option to check
2652 * @param string $defaultOverride A default value returned if the option does not exist
2653 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2654 * @return string User's current value for the option
2655 * @see getBoolOption()
2656 * @see getIntOption()
2658 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2659 global $wgHiddenPrefs;
2660 $this->loadOptions();
2662 # We want 'disabled' preferences to always behave as the default value for
2663 # users, even if they have set the option explicitly in their settings (ie they
2664 # set it, and then it was disabled removing their ability to change it). But
2665 # we don't want to erase the preferences in the database in case the preference
2666 # is re-enabled again. So don't touch $mOptions, just override the returned value
2667 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2668 return self
::getDefaultOption( $oname );
2671 if ( array_key_exists( $oname, $this->mOptions
) ) {
2672 return $this->mOptions
[$oname];
2674 return $defaultOverride;
2679 * Get all user's options
2681 * @param int $flags Bitwise combination of:
2682 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2683 * to the default value. (Since 1.25)
2686 public function getOptions( $flags = 0 ) {
2687 global $wgHiddenPrefs;
2688 $this->loadOptions();
2689 $options = $this->mOptions
;
2691 # We want 'disabled' preferences to always behave as the default value for
2692 # users, even if they have set the option explicitly in their settings (ie they
2693 # set it, and then it was disabled removing their ability to change it). But
2694 # we don't want to erase the preferences in the database in case the preference
2695 # is re-enabled again. So don't touch $mOptions, just override the returned value
2696 foreach ( $wgHiddenPrefs as $pref ) {
2697 $default = self
::getDefaultOption( $pref );
2698 if ( $default !== null ) {
2699 $options[$pref] = $default;
2703 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2704 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2711 * Get the user's current setting for a given option, as a boolean value.
2713 * @param string $oname The option to check
2714 * @return bool User's current value for the option
2717 public function getBoolOption( $oname ) {
2718 return (bool)$this->getOption( $oname );
2722 * Get the user's current setting for a given option, as an integer value.
2724 * @param string $oname The option to check
2725 * @param int $defaultOverride A default value returned if the option does not exist
2726 * @return int User's current value for the option
2729 public function getIntOption( $oname, $defaultOverride = 0 ) {
2730 $val = $this->getOption( $oname );
2732 $val = $defaultOverride;
2734 return intval( $val );
2738 * Set the given option for a user.
2740 * You need to call saveSettings() to actually write to the database.
2742 * @param string $oname The option to set
2743 * @param mixed $val New value to set
2745 public function setOption( $oname, $val ) {
2746 $this->loadOptions();
2748 // Explicitly NULL values should refer to defaults
2749 if ( is_null( $val ) ) {
2750 $val = self
::getDefaultOption( $oname );
2753 $this->mOptions
[$oname] = $val;
2757 * Get a token stored in the preferences (like the watchlist one),
2758 * resetting it if it's empty (and saving changes).
2760 * @param string $oname The option name to retrieve the token from
2761 * @return string|bool User's current value for the option, or false if this option is disabled.
2762 * @see resetTokenFromOption()
2765 public function getTokenFromOption( $oname ) {
2766 global $wgHiddenPrefs;
2767 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2771 $token = $this->getOption( $oname );
2773 $token = $this->resetTokenFromOption( $oname );
2774 if ( !wfReadOnly() ) {
2775 $this->saveSettings();
2782 * Reset a token stored in the preferences (like the watchlist one).
2783 * *Does not* save user's preferences (similarly to setOption()).
2785 * @param string $oname The option name to reset the token in
2786 * @return string|bool New token value, or false if this option is disabled.
2787 * @see getTokenFromOption()
2790 public function resetTokenFromOption( $oname ) {
2791 global $wgHiddenPrefs;
2792 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2796 $token = MWCryptRand
::generateHex( 40 );
2797 $this->setOption( $oname, $token );
2802 * Return a list of the types of user options currently returned by
2803 * User::getOptionKinds().
2805 * Currently, the option kinds are:
2806 * - 'registered' - preferences which are registered in core MediaWiki or
2807 * by extensions using the UserGetDefaultOptions hook.
2808 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2809 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2810 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2811 * be used by user scripts.
2812 * - 'special' - "preferences" that are not accessible via User::getOptions
2813 * or User::setOptions.
2814 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2815 * These are usually legacy options, removed in newer versions.
2817 * The API (and possibly others) use this function to determine the possible
2818 * option types for validation purposes, so make sure to update this when a
2819 * new option kind is added.
2821 * @see User::getOptionKinds
2822 * @return array Option kinds
2824 public static function listOptionKinds() {
2827 'registered-multiselect',
2828 'registered-checkmatrix',
2836 * Return an associative array mapping preferences keys to the kind of a preference they're
2837 * used for. Different kinds are handled differently when setting or reading preferences.
2839 * See User::listOptionKinds for the list of valid option types that can be provided.
2841 * @see User::listOptionKinds
2842 * @param IContextSource $context
2843 * @param array $options Assoc. array with options keys to check as keys.
2844 * Defaults to $this->mOptions.
2845 * @return array The key => kind mapping data
2847 public function getOptionKinds( IContextSource
$context, $options = null ) {
2848 $this->loadOptions();
2849 if ( $options === null ) {
2850 $options = $this->mOptions
;
2853 $prefs = Preferences
::getPreferences( $this, $context );
2856 // Pull out the "special" options, so they don't get converted as
2857 // multiselect or checkmatrix.
2858 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2859 foreach ( $specialOptions as $name => $value ) {
2860 unset( $prefs[$name] );
2863 // Multiselect and checkmatrix options are stored in the database with
2864 // one key per option, each having a boolean value. Extract those keys.
2865 $multiselectOptions = array();
2866 foreach ( $prefs as $name => $info ) {
2867 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2868 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2869 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2870 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2872 foreach ( $opts as $value ) {
2873 $multiselectOptions["$prefix$value"] = true;
2876 unset( $prefs[$name] );
2879 $checkmatrixOptions = array();
2880 foreach ( $prefs as $name => $info ) {
2881 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2882 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2883 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2884 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2885 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2887 foreach ( $columns as $column ) {
2888 foreach ( $rows as $row ) {
2889 $checkmatrixOptions["$prefix$column-$row"] = true;
2893 unset( $prefs[$name] );
2897 // $value is ignored
2898 foreach ( $options as $key => $value ) {
2899 if ( isset( $prefs[$key] ) ) {
2900 $mapping[$key] = 'registered';
2901 } elseif ( isset( $multiselectOptions[$key] ) ) {
2902 $mapping[$key] = 'registered-multiselect';
2903 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2904 $mapping[$key] = 'registered-checkmatrix';
2905 } elseif ( isset( $specialOptions[$key] ) ) {
2906 $mapping[$key] = 'special';
2907 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2908 $mapping[$key] = 'userjs';
2910 $mapping[$key] = 'unused';
2918 * Reset certain (or all) options to the site defaults
2920 * The optional parameter determines which kinds of preferences will be reset.
2921 * Supported values are everything that can be reported by getOptionKinds()
2922 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2924 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2925 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2926 * for backwards-compatibility.
2927 * @param IContextSource|null $context Context source used when $resetKinds
2928 * does not contain 'all', passed to getOptionKinds().
2929 * Defaults to RequestContext::getMain() when null.
2931 public function resetOptions(
2932 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2933 IContextSource
$context = null
2936 $defaultOptions = self
::getDefaultOptions();
2938 if ( !is_array( $resetKinds ) ) {
2939 $resetKinds = array( $resetKinds );
2942 if ( in_array( 'all', $resetKinds ) ) {
2943 $newOptions = $defaultOptions;
2945 if ( $context === null ) {
2946 $context = RequestContext
::getMain();
2949 $optionKinds = $this->getOptionKinds( $context );
2950 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2951 $newOptions = array();
2953 // Use default values for the options that should be deleted, and
2954 // copy old values for the ones that shouldn't.
2955 foreach ( $this->mOptions
as $key => $value ) {
2956 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2957 if ( array_key_exists( $key, $defaultOptions ) ) {
2958 $newOptions[$key] = $defaultOptions[$key];
2961 $newOptions[$key] = $value;
2966 Hooks
::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2968 $this->mOptions
= $newOptions;
2969 $this->mOptionsLoaded
= true;
2973 * Get the user's preferred date format.
2974 * @return string User's preferred date format
2976 public function getDatePreference() {
2977 // Important migration for old data rows
2978 if ( is_null( $this->mDatePreference
) ) {
2980 $value = $this->getOption( 'date' );
2981 $map = $wgLang->getDatePreferenceMigrationMap();
2982 if ( isset( $map[$value] ) ) {
2983 $value = $map[$value];
2985 $this->mDatePreference
= $value;
2987 return $this->mDatePreference
;
2991 * Determine based on the wiki configuration and the user's options,
2992 * whether this user must be over HTTPS no matter what.
2996 public function requiresHTTPS() {
2997 global $wgSecureLogin;
2998 if ( !$wgSecureLogin ) {
3001 $https = $this->getBoolOption( 'prefershttps' );
3002 Hooks
::run( 'UserRequiresHTTPS', array( $this, &$https ) );
3004 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3011 * Get the user preferred stub threshold
3015 public function getStubThreshold() {
3016 global $wgMaxArticleSize; # Maximum article size, in Kb
3017 $threshold = $this->getIntOption( 'stubthreshold' );
3018 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3019 // If they have set an impossible value, disable the preference
3020 // so we can use the parser cache again.
3027 * Get the permissions this user has.
3028 * @return array Array of String permission names
3030 public function getRights() {
3031 if ( is_null( $this->mRights
) ) {
3032 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3033 Hooks
::run( 'UserGetRights', array( $this, &$this->mRights
) );
3034 // Force reindexation of rights when a hook has unset one of them
3035 $this->mRights
= array_values( array_unique( $this->mRights
) );
3037 return $this->mRights
;
3041 * Get the list of explicit group memberships this user has.
3042 * The implicit * and user groups are not included.
3043 * @return array Array of String internal group names
3045 public function getGroups() {
3047 $this->loadGroups();
3048 return $this->mGroups
;
3052 * Get the list of implicit group memberships this user has.
3053 * This includes all explicit groups, plus 'user' if logged in,
3054 * '*' for all accounts, and autopromoted groups
3055 * @param bool $recache Whether to avoid the cache
3056 * @return array Array of String internal group names
3058 public function getEffectiveGroups( $recache = false ) {
3059 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3060 $this->mEffectiveGroups
= array_unique( array_merge(
3061 $this->getGroups(), // explicit groups
3062 $this->getAutomaticGroups( $recache ) // implicit groups
3064 // Hook for additional groups
3065 Hooks
::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
3066 // Force reindexation of groups when a hook has unset one of them
3067 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3069 return $this->mEffectiveGroups
;
3073 * Get the list of implicit group memberships this user has.
3074 * This includes 'user' if logged in, '*' for all accounts,
3075 * and autopromoted groups
3076 * @param bool $recache Whether to avoid the cache
3077 * @return array Array of String internal group names
3079 public function getAutomaticGroups( $recache = false ) {
3080 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3081 $this->mImplicitGroups
= array( '*' );
3082 if ( $this->getId() ) {
3083 $this->mImplicitGroups
[] = 'user';
3085 $this->mImplicitGroups
= array_unique( array_merge(
3086 $this->mImplicitGroups
,
3087 Autopromote
::getAutopromoteGroups( $this )
3091 // Assure data consistency with rights/groups,
3092 // as getEffectiveGroups() depends on this function
3093 $this->mEffectiveGroups
= null;
3096 return $this->mImplicitGroups
;
3100 * Returns the groups the user has belonged to.
3102 * The user may still belong to the returned groups. Compare with getGroups().
3104 * The function will not return groups the user had belonged to before MW 1.17
3106 * @return array Names of the groups the user has belonged to.
3108 public function getFormerGroups() {
3111 if ( is_null( $this->mFormerGroups
) ) {
3112 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3113 ?
wfGetDB( DB_MASTER
)
3114 : wfGetDB( DB_SLAVE
);
3115 $res = $dbr->select( 'user_former_groups',
3116 array( 'ufg_group' ),
3117 array( 'ufg_user' => $this->mId
),
3119 $this->mFormerGroups
= array();
3120 foreach ( $res as $row ) {
3121 $this->mFormerGroups
[] = $row->ufg_group
;
3125 return $this->mFormerGroups
;
3129 * Get the user's edit count.
3130 * @return int|null Null for anonymous users
3132 public function getEditCount() {
3133 if ( !$this->getId() ) {
3137 if ( $this->mEditCount
=== null ) {
3138 /* Populate the count, if it has not been populated yet */
3139 $dbr = wfGetDB( DB_SLAVE
);
3140 // check if the user_editcount field has been initialized
3141 $count = $dbr->selectField(
3142 'user', 'user_editcount',
3143 array( 'user_id' => $this->mId
),
3147 if ( $count === null ) {
3148 // it has not been initialized. do so.
3149 $count = $this->initEditCount();
3151 $this->mEditCount
= $count;
3153 return (int)$this->mEditCount
;
3157 * Add the user to the given group.
3158 * This takes immediate effect.
3159 * @param string $group Name of the group to add
3162 public function addGroup( $group ) {
3165 if ( !Hooks
::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3169 $dbw = wfGetDB( DB_MASTER
);
3170 if ( $this->getId() ) {
3171 $dbw->insert( 'user_groups',
3173 'ug_user' => $this->getID(),
3174 'ug_group' => $group,
3177 array( 'IGNORE' ) );
3180 $this->loadGroups();
3181 $this->mGroups
[] = $group;
3182 // In case loadGroups was not called before, we now have the right twice.
3183 // Get rid of the duplicate.
3184 $this->mGroups
= array_unique( $this->mGroups
);
3186 // Refresh the groups caches, and clear the rights cache so it will be
3187 // refreshed on the next call to $this->getRights().
3188 $this->getEffectiveGroups( true );
3189 $this->mRights
= null;
3191 $this->invalidateCache();
3197 * Remove the user from the given group.
3198 * This takes immediate effect.
3199 * @param string $group Name of the group to remove
3202 public function removeGroup( $group ) {
3204 if ( !Hooks
::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3208 $dbw = wfGetDB( DB_MASTER
);
3209 $dbw->delete( 'user_groups',
3211 'ug_user' => $this->getID(),
3212 'ug_group' => $group,
3215 // Remember that the user was in this group
3216 $dbw->insert( 'user_former_groups',
3218 'ufg_user' => $this->getID(),
3219 'ufg_group' => $group,
3225 $this->loadGroups();
3226 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3228 // Refresh the groups caches, and clear the rights cache so it will be
3229 // refreshed on the next call to $this->getRights().
3230 $this->getEffectiveGroups( true );
3231 $this->mRights
= null;
3233 $this->invalidateCache();
3239 * Get whether the user is logged in
3242 public function isLoggedIn() {
3243 return $this->getID() != 0;
3247 * Get whether the user is anonymous
3250 public function isAnon() {
3251 return !$this->isLoggedIn();
3255 * Check if user is allowed to access a feature / make an action
3257 * @param string $permissions,... Permissions to test
3258 * @return bool True if user is allowed to perform *any* of the given actions
3260 public function isAllowedAny( /*...*/ ) {
3261 $permissions = func_get_args();
3262 foreach ( $permissions as $permission ) {
3263 if ( $this->isAllowed( $permission ) ) {
3272 * @param string $permissions,... Permissions to test
3273 * @return bool True if the user is allowed to perform *all* of the given actions
3275 public function isAllowedAll( /*...*/ ) {
3276 $permissions = func_get_args();
3277 foreach ( $permissions as $permission ) {
3278 if ( !$this->isAllowed( $permission ) ) {
3286 * Internal mechanics of testing a permission
3287 * @param string $action
3290 public function isAllowed( $action = '' ) {
3291 if ( $action === '' ) {
3292 return true; // In the spirit of DWIM
3294 // Patrolling may not be enabled
3295 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3296 global $wgUseRCPatrol, $wgUseNPPatrol;
3297 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3301 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3302 // by misconfiguration: 0 == 'foo'
3303 return in_array( $action, $this->getRights(), true );
3307 * Check whether to enable recent changes patrol features for this user
3308 * @return bool True or false
3310 public function useRCPatrol() {
3311 global $wgUseRCPatrol;
3312 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3316 * Check whether to enable new pages patrol features for this user
3317 * @return bool True or false
3319 public function useNPPatrol() {
3320 global $wgUseRCPatrol, $wgUseNPPatrol;
3322 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3323 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3328 * Get the WebRequest object to use with this object
3330 * @return WebRequest
3332 public function getRequest() {
3333 if ( $this->mRequest
) {
3334 return $this->mRequest
;
3342 * Get the current skin, loading it if required
3343 * @return Skin The current skin
3344 * @todo FIXME: Need to check the old failback system [AV]
3345 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3347 public function getSkin() {
3348 wfDeprecated( __METHOD__
, '1.18' );
3349 return RequestContext
::getMain()->getSkin();
3353 * Get a WatchedItem for this user and $title.
3355 * @since 1.22 $checkRights parameter added
3356 * @param Title $title
3357 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3358 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3359 * @return WatchedItem
3361 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3362 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3364 if ( isset( $this->mWatchedItems
[$key] ) ) {
3365 return $this->mWatchedItems
[$key];
3368 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3369 $this->mWatchedItems
= array();
3372 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3373 return $this->mWatchedItems
[$key];
3377 * Check the watched status of an article.
3378 * @since 1.22 $checkRights parameter added
3379 * @param Title $title Title of the article to look at
3380 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3381 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3384 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3385 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3390 * @since 1.22 $checkRights parameter added
3391 * @param Title $title Title of the article to look at
3392 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3393 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3395 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3396 $this->getWatchedItem( $title, $checkRights )->addWatch();
3397 $this->invalidateCache();
3401 * Stop watching an article.
3402 * @since 1.22 $checkRights parameter added
3403 * @param Title $title Title of the article to look at
3404 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3405 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3407 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3408 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3409 $this->invalidateCache();
3413 * Clear the user's notification timestamp for the given title.
3414 * If e-notif e-mails are on, they will receive notification mails on
3415 * the next change of the page if it's watched etc.
3416 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3417 * @param Title $title Title of the article to look at
3418 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3420 public function clearNotification( &$title, $oldid = 0 ) {
3421 global $wgUseEnotif, $wgShowUpdatedMarker;
3423 // Do nothing if the database is locked to writes
3424 if ( wfReadOnly() ) {
3428 // Do nothing if not allowed to edit the watchlist
3429 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3433 // If we're working on user's talk page, we should update the talk page message indicator
3434 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3435 if ( !Hooks
::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3439 $nextid = $oldid ?
$title->getNextRevisionID( $oldid ) : null;
3441 if ( !$oldid ||
!$nextid ) {
3442 // If we're looking at the latest revision, we should definitely clear it
3443 $this->setNewtalk( false );
3445 // Otherwise we should update its revision, if it's present
3446 if ( $this->getNewtalk() ) {
3447 // Naturally the other one won't clear by itself
3448 $this->setNewtalk( false );
3449 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3454 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3458 if ( $this->isAnon() ) {
3459 // Nothing else to do...
3463 // Only update the timestamp if the page is being watched.
3464 // The query to find out if it is watched is cached both in memcached and per-invocation,
3465 // and when it does have to be executed, it can be on a slave
3466 // If this is the user's newtalk page, we always update the timestamp
3468 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3472 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3476 * Resets all of the given user's page-change notification timestamps.
3477 * If e-notif e-mails are on, they will receive notification mails on
3478 * the next change of any watched page.
3479 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3481 public function clearAllNotifications() {
3482 if ( wfReadOnly() ) {
3486 // Do nothing if not allowed to edit the watchlist
3487 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3491 global $wgUseEnotif, $wgShowUpdatedMarker;
3492 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3493 $this->setNewtalk( false );
3496 $id = $this->getId();
3498 $dbw = wfGetDB( DB_MASTER
);
3499 $dbw->update( 'watchlist',
3500 array( /* SET */ 'wl_notificationtimestamp' => null ),
3501 array( /* WHERE */ 'wl_user' => $id ),
3504 // We also need to clear here the "you have new message" notification for the own user_talk page;
3505 // it's cleared one page view later in WikiPage::doViewUpdates().
3510 * Set a cookie on the user's client. Wrapper for
3511 * WebResponse::setCookie
3512 * @param string $name Name of the cookie to set
3513 * @param string $value Value to set
3514 * @param int $exp Expiration time, as a UNIX time value;
3515 * if 0 or not specified, use the default $wgCookieExpiration
3516 * @param bool $secure
3517 * true: Force setting the secure attribute when setting the cookie
3518 * false: Force NOT setting the secure attribute when setting the cookie
3519 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3520 * @param array $params Array of options sent passed to WebResponse::setcookie()
3521 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3524 protected function setCookie(
3525 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3527 if ( $request === null ) {
3528 $request = $this->getRequest();
3530 $params['secure'] = $secure;
3531 $request->response()->setcookie( $name, $value, $exp, $params );
3535 * Clear a cookie on the user's client
3536 * @param string $name Name of the cookie to clear
3537 * @param bool $secure
3538 * true: Force setting the secure attribute when setting the cookie
3539 * false: Force NOT setting the secure attribute when setting the cookie
3540 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3541 * @param array $params Array of options sent passed to WebResponse::setcookie()
3543 protected function clearCookie( $name, $secure = null, $params = array() ) {
3544 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3548 * Set the default cookies for this session on the user's client.
3550 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3552 * @param bool $secure Whether to force secure/insecure cookies or use default
3553 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3555 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3556 if ( $request === null ) {
3557 $request = $this->getRequest();
3561 if ( 0 == $this->mId
) {
3564 if ( !$this->mToken
) {
3565 // When token is empty or NULL generate a new one and then save it to the database
3566 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3567 // Simply by setting every cell in the user_token column to NULL and letting them be
3568 // regenerated as users log back into the wiki.
3570 if ( !wfReadOnly() ) {
3571 $this->saveSettings();
3575 'wsUserID' => $this->mId
,
3576 'wsToken' => $this->mToken
,
3577 'wsUserName' => $this->getName()
3580 'UserID' => $this->mId
,
3581 'UserName' => $this->getName(),
3583 if ( $rememberMe ) {
3584 $cookies['Token'] = $this->mToken
;
3586 $cookies['Token'] = false;
3589 Hooks
::run( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3591 foreach ( $session as $name => $value ) {
3592 $request->setSessionData( $name, $value );
3594 foreach ( $cookies as $name => $value ) {
3595 if ( $value === false ) {
3596 $this->clearCookie( $name );
3598 $this->setCookie( $name, $value, 0, $secure, array(), $request );
3603 * If wpStickHTTPS was selected, also set an insecure cookie that
3604 * will cause the site to redirect the user to HTTPS, if they access
3605 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3606 * as the one set by centralauth (bug 53538). Also set it to session, or
3607 * standard time setting, based on if rememberme was set.
3609 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3613 $rememberMe ?
0 : null,
3615 array( 'prefix' => '' ) // no prefix
3621 * Log this user out.
3623 public function logout() {
3624 if ( Hooks
::run( 'UserLogout', array( &$this ) ) ) {
3630 * Clear the user's cookies and session, and reset the instance cache.
3633 public function doLogout() {
3634 $this->clearInstanceCache( 'defaults' );
3636 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3638 $this->clearCookie( 'UserID' );
3639 $this->clearCookie( 'Token' );
3640 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3642 // Remember when user logged out, to prevent seeing cached pages
3643 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3647 * Save this user's settings into the database.
3648 * @todo Only rarely do all these fields need to be set!
3650 public function saveSettings() {
3653 if ( wfReadOnly() ) {
3654 // @TODO: caller should deal with this instead!
3655 // This should really just be an exception.
3656 MWExceptionHandler
::logException( new DBExpectedError(
3658 "Could not update user with ID '{$this->mId}'; DB is read-only."
3664 $this->loadPasswords();
3665 if ( 0 == $this->mId
) {
3669 // This method is for updating existing users, so the user should
3670 // have been loaded from the master to begin with to avoid problems.
3671 if ( !( $this->queryFlagsUsed
& self
::READ_LATEST
) ) {
3672 wfWarn( "Attempting to save slave-loaded User object with ID '{$this->mId}'." );
3675 // Get a new user_touched that is higher than the old one.
3676 // This will be used for a CAS check as a last-resort safety
3677 // check against race conditions and slave lag.
3678 $oldTouched = $this->mTouched
;
3679 $this->mTouched
= $this->newTouchedTimestamp();
3681 if ( !$wgAuth->allowSetLocalPassword() ) {
3682 $this->mPassword
= self
::getPasswordFactory()->newFromCiphertext( null );
3685 $dbw = wfGetDB( DB_MASTER
);
3686 $dbw->update( 'user',
3688 'user_name' => $this->mName
,
3689 'user_password' => $this->mPassword
->toString(),
3690 'user_newpassword' => $this->mNewpassword
->toString(),
3691 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3692 'user_real_name' => $this->mRealName
,
3693 'user_email' => $this->mEmail
,
3694 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3695 'user_touched' => $dbw->timestamp( $this->mTouched
),
3696 'user_token' => strval( $this->mToken
),
3697 'user_email_token' => $this->mEmailToken
,
3698 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3699 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires
),
3700 ), array( /* WHERE */
3701 'user_id' => $this->mId
,
3702 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3706 if ( !$dbw->affectedRows() ) {
3707 // User was changed in the meantime or loaded with stale data
3708 MWExceptionHandler
::logException( new MWException(
3709 "CAS update failed on user_touched for user ID '{$this->mId}'."
3711 // Maybe the problem was a missed cache update; clear it to be safe
3712 $this->clearSharedCache();
3717 $this->saveOptions();
3719 Hooks
::run( 'UserSaveSettings', array( $this ) );
3720 $this->clearSharedCache();
3721 $this->getUserPage()->invalidateCache();
3725 * If only this user's username is known, and it exists, return the user ID.
3728 public function idForName() {
3729 $s = trim( $this->getName() );
3734 $dbr = wfGetDB( DB_SLAVE
);
3735 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
3736 if ( $id === false ) {
3743 * Add a user to the database, return the user object
3745 * @param string $name Username to add
3746 * @param array $params Array of Strings Non-default parameters to save to
3747 * the database as user_* fields:
3748 * - password: The user's password hash. Password logins will be disabled
3749 * if this is omitted.
3750 * - newpassword: Hash for a temporary password that has been mailed to
3752 * - email: The user's email address.
3753 * - email_authenticated: The email authentication timestamp.
3754 * - real_name: The user's real name.
3755 * - options: An associative array of non-default options.
3756 * - token: Random authentication token. Do not set.
3757 * - registration: Registration timestamp. Do not set.
3759 * @return User|null User object, or null if the username already exists.
3761 public static function createNew( $name, $params = array() ) {
3764 $user->loadPasswords();
3765 $user->setToken(); // init token
3766 if ( isset( $params['options'] ) ) {
3767 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3768 unset( $params['options'] );
3770 $dbw = wfGetDB( DB_MASTER
);
3771 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3774 'user_id' => $seqVal,
3775 'user_name' => $name,
3776 'user_password' => $user->mPassword
->toString(),
3777 'user_newpassword' => $user->mNewpassword
->toString(),
3778 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3779 'user_email' => $user->mEmail
,
3780 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3781 'user_real_name' => $user->mRealName
,
3782 'user_token' => strval( $user->mToken
),
3783 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3784 'user_editcount' => 0,
3785 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3787 foreach ( $params as $name => $value ) {
3788 $fields["user_$name"] = $value;
3790 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3791 if ( $dbw->affectedRows() ) {
3792 $newUser = User
::newFromId( $dbw->insertId() );
3800 * Add this existing user object to the database. If the user already
3801 * exists, a fatal status object is returned, and the user object is
3802 * initialised with the data from the database.
3804 * Previously, this function generated a DB error due to a key conflict
3805 * if the user already existed. Many extension callers use this function
3806 * in code along the lines of:
3808 * $user = User::newFromName( $name );
3809 * if ( !$user->isLoggedIn() ) {
3810 * $user->addToDatabase();
3812 * // do something with $user...
3814 * However, this was vulnerable to a race condition (bug 16020). By
3815 * initialising the user object if the user exists, we aim to support this
3816 * calling sequence as far as possible.
3818 * Note that if the user exists, this function will acquire a write lock,
3819 * so it is still advisable to make the call conditional on isLoggedIn(),
3820 * and to commit the transaction after calling.
3822 * @throws MWException
3825 public function addToDatabase() {
3827 $this->loadPasswords();
3828 if ( !$this->mToken
) {
3829 $this->setToken(); // init token
3832 $this->mTouched
= $this->newTouchedTimestamp();
3834 $dbw = wfGetDB( DB_MASTER
);
3835 $inWrite = $dbw->writesOrCallbacksPending();
3836 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3837 $dbw->insert( 'user',
3839 'user_id' => $seqVal,
3840 'user_name' => $this->mName
,
3841 'user_password' => $this->mPassword
->toString(),
3842 'user_newpassword' => $this->mNewpassword
->toString(),
3843 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3844 'user_email' => $this->mEmail
,
3845 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3846 'user_real_name' => $this->mRealName
,
3847 'user_token' => strval( $this->mToken
),
3848 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3849 'user_editcount' => 0,
3850 'user_touched' => $dbw->timestamp( $this->mTouched
),
3854 if ( !$dbw->affectedRows() ) {
3855 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3856 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3858 // Can't commit due to pending writes that may need atomicity.
3859 // This may cause some lock contention unlike the case below.
3860 $options = array( 'LOCK IN SHARE MODE' );
3861 $flags = self
::READ_LOCKING
;
3863 // Often, this case happens early in views before any writes when
3864 // using CentralAuth. It's should be OK to commit and break the snapshot.
3865 $dbw->commit( __METHOD__
, 'flush' );
3867 $flags = self
::READ_LATEST
;
3869 $this->mId
= $dbw->selectField( 'user', 'user_id',
3870 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3873 if ( $this->loadFromDatabase( $flags ) ) {
3878 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3879 "to insert user '{$this->mName}' row, but it was not present in select!" );
3881 return Status
::newFatal( 'userexists' );
3883 $this->mId
= $dbw->insertId();
3885 // Clear instance cache other than user table data, which is already accurate
3886 $this->clearInstanceCache();
3888 $this->saveOptions();
3889 return Status
::newGood();
3893 * If this user is logged-in and blocked,
3894 * block any IP address they've successfully logged in from.
3895 * @return bool A block was spread
3897 public function spreadAnyEditBlock() {
3898 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3899 return $this->spreadBlock();
3905 * If this (non-anonymous) user is blocked,
3906 * block the IP address they've successfully logged in from.
3907 * @return bool A block was spread
3909 protected function spreadBlock() {
3910 wfDebug( __METHOD__
. "()\n" );
3912 if ( $this->mId
== 0 ) {
3916 $userblock = Block
::newFromTarget( $this->getName() );
3917 if ( !$userblock ) {
3921 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3925 * Get whether the user is explicitly blocked from account creation.
3926 * @return bool|Block
3928 public function isBlockedFromCreateAccount() {
3929 $this->getBlockedStatus();
3930 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3931 return $this->mBlock
;
3934 # bug 13611: if the IP address the user is trying to create an account from is
3935 # blocked with createaccount disabled, prevent new account creation there even
3936 # when the user is logged in
3937 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3938 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3940 return $this->mBlockedFromCreateAccount
instanceof Block
3941 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3942 ?
$this->mBlockedFromCreateAccount
3947 * Get whether the user is blocked from using Special:Emailuser.
3950 public function isBlockedFromEmailuser() {
3951 $this->getBlockedStatus();
3952 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3956 * Get whether the user is allowed to create an account.
3959 public function isAllowedToCreateAccount() {
3960 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3964 * Get this user's personal page title.
3966 * @return Title User's personal page title
3968 public function getUserPage() {
3969 return Title
::makeTitle( NS_USER
, $this->getName() );
3973 * Get this user's talk page title.
3975 * @return Title User's talk page title
3977 public function getTalkPage() {
3978 $title = $this->getUserPage();
3979 return $title->getTalkPage();
3983 * Determine whether the user is a newbie. Newbies are either
3984 * anonymous IPs, or the most recently created accounts.
3987 public function isNewbie() {
3988 return !$this->isAllowed( 'autoconfirmed' );
3992 * Check to see if the given clear-text password is one of the accepted passwords
3993 * @param string $password User password
3994 * @return bool True if the given password is correct, otherwise False
3996 public function checkPassword( $password ) {
3997 global $wgAuth, $wgLegacyEncoding;
3999 $this->loadPasswords();
4001 // Some passwords will give a fatal Status, which means there is
4002 // some sort of technical or security reason for this password to
4003 // be completely invalid and should never be checked (e.g., T64685)
4004 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4008 // Certain authentication plugins do NOT want to save
4009 // domain passwords in a mysql database, so we should
4010 // check this (in case $wgAuth->strict() is false).
4011 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4013 } elseif ( $wgAuth->strict() ) {
4014 // Auth plugin doesn't allow local authentication
4016 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4017 // Auth plugin doesn't allow local authentication for this user name
4021 if ( !$this->mPassword
->equals( $password ) ) {
4022 if ( $wgLegacyEncoding ) {
4023 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4024 // Check for this with iconv
4025 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4026 if ( $cp1252Password === $password ||
!$this->mPassword
->equals( $cp1252Password ) ) {
4034 $passwordFactory = self
::getPasswordFactory();
4035 if ( $passwordFactory->needsUpdate( $this->mPassword
) && !wfReadOnly() ) {
4036 $this->mPassword
= $passwordFactory->newFromPlaintext( $password );
4037 $this->saveSettings();
4044 * Check if the given clear-text password matches the temporary password
4045 * sent by e-mail for password reset operations.
4047 * @param string $plaintext
4049 * @return bool True if matches, false otherwise
4051 public function checkTemporaryPassword( $plaintext ) {
4052 global $wgNewPasswordExpiry;
4055 $this->loadPasswords();
4056 if ( $this->mNewpassword
->equals( $plaintext ) ) {
4057 if ( is_null( $this->mNewpassTime
) ) {
4060 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
4061 return ( time() < $expiry );
4068 * Alias for getEditToken.
4069 * @deprecated since 1.19, use getEditToken instead.
4071 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4072 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4073 * @return string The new edit token
4075 public function editToken( $salt = '', $request = null ) {
4076 wfDeprecated( __METHOD__
, '1.19' );
4077 return $this->getEditToken( $salt, $request );
4081 * Internal implementation for self::getEditToken() and
4082 * self::matchEditToken().
4084 * @param string|array $salt
4085 * @param WebRequest $request
4086 * @param string|int $timestamp
4089 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
4090 if ( $this->isAnon() ) {
4091 return self
::EDIT_TOKEN_SUFFIX
;
4093 $token = $request->getSessionData( 'wsEditToken' );
4094 if ( $token === null ) {
4095 $token = MWCryptRand
::generateHex( 32 );
4096 $request->setSessionData( 'wsEditToken', $token );
4098 if ( is_array( $salt ) ) {
4099 $salt = implode( '|', $salt );
4101 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
4102 dechex( $timestamp ) .
4103 self
::EDIT_TOKEN_SUFFIX
;
4108 * Initialize (if necessary) and return a session token value
4109 * which can be used in edit forms to show that the user's
4110 * login credentials aren't being hijacked with a foreign form
4115 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4116 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4117 * @return string The new edit token
4119 public function getEditToken( $salt = '', $request = null ) {
4120 return $this->getEditTokenAtTimestamp(
4121 $salt, $request ?
: $this->getRequest(), wfTimestamp()
4126 * Generate a looking random token for various uses.
4128 * @return string The new random token
4129 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
4130 * wfRandomString for pseudo-randomness.
4132 public static function generateToken() {
4133 return MWCryptRand
::generateHex( 32 );
4137 * Get the embedded timestamp from a token.
4138 * @param string $val Input token
4141 public static function getEditTokenTimestamp( $val ) {
4142 $suffixLen = strlen( self
::EDIT_TOKEN_SUFFIX
);
4143 if ( strlen( $val ) <= 32 +
$suffixLen ) {
4147 return hexdec( substr( $val, 32, -$suffixLen ) );
4151 * Check given value against the token value stored in the session.
4152 * A match should confirm that the form was submitted from the
4153 * user's own login session, not a form submission from a third-party
4156 * @param string $val Input value to compare
4157 * @param string $salt Optional function-specific data for hashing
4158 * @param WebRequest|null $request Object to use or null to use $wgRequest
4159 * @param int $maxage Fail tokens older than this, in seconds
4160 * @return bool Whether the token matches
4162 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4163 if ( $this->isAnon() ) {
4164 return $val === self
::EDIT_TOKEN_SUFFIX
;
4167 $timestamp = self
::getEditTokenTimestamp( $val );
4168 if ( $timestamp === null ) {
4171 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
4176 $sessionToken = $this->getEditTokenAtTimestamp(
4177 $salt, $request ?
: $this->getRequest(), $timestamp
4180 if ( $val != $sessionToken ) {
4181 wfDebug( "User::matchEditToken: broken session data\n" );
4184 return hash_equals( $sessionToken, $val );
4188 * Check given value against the token value stored in the session,
4189 * ignoring the suffix.
4191 * @param string $val Input value to compare
4192 * @param string $salt Optional function-specific data for hashing
4193 * @param WebRequest|null $request Object to use or null to use $wgRequest
4194 * @param int $maxage Fail tokens older than this, in seconds
4195 * @return bool Whether the token matches
4197 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4198 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4199 return $this->matchEditToken( $val, $salt, $request, $maxage );
4203 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4204 * mail to the user's given address.
4206 * @param string $type Message to send, either "created", "changed" or "set"
4209 public function sendConfirmationMail( $type = 'created' ) {
4211 $expiration = null; // gets passed-by-ref and defined in next line.
4212 $token = $this->confirmationToken( $expiration );
4213 $url = $this->confirmationTokenUrl( $token );
4214 $invalidateURL = $this->invalidationTokenUrl( $token );
4215 $this->saveSettings();
4217 if ( $type == 'created' ||
$type === false ) {
4218 $message = 'confirmemail_body';
4219 } elseif ( $type === true ) {
4220 $message = 'confirmemail_body_changed';
4222 // Messages: confirmemail_body_changed, confirmemail_body_set
4223 $message = 'confirmemail_body_' . $type;
4226 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4227 wfMessage( $message,
4228 $this->getRequest()->getIP(),
4231 $wgLang->timeanddate( $expiration, false ),
4233 $wgLang->date( $expiration, false ),
4234 $wgLang->time( $expiration, false ) )->text() );
4238 * Send an e-mail to this user's account. Does not check for
4239 * confirmed status or validity.
4241 * @param string $subject Message subject
4242 * @param string $body Message body
4243 * @param string $from Optional From address; if unspecified, default
4244 * $wgPasswordSender will be used.
4245 * @param string $replyto Reply-To address
4248 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4249 if ( is_null( $from ) ) {
4250 global $wgPasswordSender;
4251 $sender = new MailAddress( $wgPasswordSender,
4252 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4254 $sender = MailAddress
::newFromUser( $from );
4257 $to = MailAddress
::newFromUser( $this );
4258 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
4262 * Generate, store, and return a new e-mail confirmation code.
4263 * A hash (unsalted, since it's used as a key) is stored.
4265 * @note Call saveSettings() after calling this function to commit
4266 * this change to the database.
4268 * @param string &$expiration Accepts the expiration time
4269 * @return string New token
4271 protected function confirmationToken( &$expiration ) {
4272 global $wgUserEmailConfirmationTokenExpiry;
4274 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4275 $expiration = wfTimestamp( TS_MW
, $expires );
4277 $token = MWCryptRand
::generateHex( 32 );
4278 $hash = md5( $token );
4279 $this->mEmailToken
= $hash;
4280 $this->mEmailTokenExpires
= $expiration;
4285 * Return a URL the user can use to confirm their email address.
4286 * @param string $token Accepts the email confirmation token
4287 * @return string New token URL
4289 protected function confirmationTokenUrl( $token ) {
4290 return $this->getTokenUrl( 'ConfirmEmail', $token );
4294 * Return a URL the user can use to invalidate their email address.
4295 * @param string $token Accepts the email confirmation token
4296 * @return string New token URL
4298 protected function invalidationTokenUrl( $token ) {
4299 return $this->getTokenUrl( 'InvalidateEmail', $token );
4303 * Internal function to format the e-mail validation/invalidation URLs.
4304 * This uses a quickie hack to use the
4305 * hardcoded English names of the Special: pages, for ASCII safety.
4307 * @note Since these URLs get dropped directly into emails, using the
4308 * short English names avoids insanely long URL-encoded links, which
4309 * also sometimes can get corrupted in some browsers/mailers
4310 * (bug 6957 with Gmail and Internet Explorer).
4312 * @param string $page Special page
4313 * @param string $token Token
4314 * @return string Formatted URL
4316 protected function getTokenUrl( $page, $token ) {
4317 // Hack to bypass localization of 'Special:'
4318 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4319 return $title->getCanonicalURL();
4323 * Mark the e-mail address confirmed.
4325 * @note Call saveSettings() after calling this function to commit the change.
4329 public function confirmEmail() {
4330 // Check if it's already confirmed, so we don't touch the database
4331 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4332 if ( !$this->isEmailConfirmed() ) {
4333 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4334 Hooks
::run( 'ConfirmEmailComplete', array( $this ) );
4340 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4341 * address if it was already confirmed.
4343 * @note Call saveSettings() after calling this function to commit the change.
4344 * @return bool Returns true
4346 public function invalidateEmail() {
4348 $this->mEmailToken
= null;
4349 $this->mEmailTokenExpires
= null;
4350 $this->setEmailAuthenticationTimestamp( null );
4352 Hooks
::run( 'InvalidateEmailComplete', array( $this ) );
4357 * Set the e-mail authentication timestamp.
4358 * @param string $timestamp TS_MW timestamp
4360 public function setEmailAuthenticationTimestamp( $timestamp ) {
4362 $this->mEmailAuthenticated
= $timestamp;
4363 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4367 * Is this user allowed to send e-mails within limits of current
4368 * site configuration?
4371 public function canSendEmail() {
4372 global $wgEnableEmail, $wgEnableUserEmail;
4373 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4376 $canSend = $this->isEmailConfirmed();
4377 Hooks
::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4382 * Is this user allowed to receive e-mails within limits of current
4383 * site configuration?
4386 public function canReceiveEmail() {
4387 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4391 * Is this user's e-mail address valid-looking and confirmed within
4392 * limits of the current site configuration?
4394 * @note If $wgEmailAuthentication is on, this may require the user to have
4395 * confirmed their address by returning a code or using a password
4396 * sent to the address from the wiki.
4400 public function isEmailConfirmed() {
4401 global $wgEmailAuthentication;
4404 if ( Hooks
::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4405 if ( $this->isAnon() ) {
4408 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4411 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4421 * Check whether there is an outstanding request for e-mail confirmation.
4424 public function isEmailConfirmationPending() {
4425 global $wgEmailAuthentication;
4426 return $wgEmailAuthentication &&
4427 !$this->isEmailConfirmed() &&
4428 $this->mEmailToken
&&
4429 $this->mEmailTokenExpires
> wfTimestamp();
4433 * Get the timestamp of account creation.
4435 * @return string|bool|null Timestamp of account creation, false for
4436 * non-existent/anonymous user accounts, or null if existing account
4437 * but information is not in database.
4439 public function getRegistration() {
4440 if ( $this->isAnon() ) {
4444 return $this->mRegistration
;
4448 * Get the timestamp of the first edit
4450 * @return string|bool Timestamp of first edit, or false for
4451 * non-existent/anonymous user accounts.
4453 public function getFirstEditTimestamp() {
4454 if ( $this->getId() == 0 ) {
4455 return false; // anons
4457 $dbr = wfGetDB( DB_SLAVE
);
4458 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4459 array( 'rev_user' => $this->getId() ),
4461 array( 'ORDER BY' => 'rev_timestamp ASC' )
4464 return false; // no edits
4466 return wfTimestamp( TS_MW
, $time );
4470 * Get the permissions associated with a given list of groups
4472 * @param array $groups Array of Strings List of internal group names
4473 * @return array Array of Strings List of permission key names for given groups combined
4475 public static function getGroupPermissions( $groups ) {
4476 global $wgGroupPermissions, $wgRevokePermissions;
4478 // grant every granted permission first
4479 foreach ( $groups as $group ) {
4480 if ( isset( $wgGroupPermissions[$group] ) ) {
4481 $rights = array_merge( $rights,
4482 // array_filter removes empty items
4483 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4486 // now revoke the revoked permissions
4487 foreach ( $groups as $group ) {
4488 if ( isset( $wgRevokePermissions[$group] ) ) {
4489 $rights = array_diff( $rights,
4490 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4493 return array_unique( $rights );
4497 * Get all the groups who have a given permission
4499 * @param string $role Role to check
4500 * @return array Array of Strings List of internal group names with the given permission
4502 public static function getGroupsWithPermission( $role ) {
4503 global $wgGroupPermissions;
4504 $allowedGroups = array();
4505 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4506 if ( self
::groupHasPermission( $group, $role ) ) {
4507 $allowedGroups[] = $group;
4510 return $allowedGroups;
4514 * Check, if the given group has the given permission
4516 * If you're wanting to check whether all users have a permission, use
4517 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4521 * @param string $group Group to check
4522 * @param string $role Role to check
4525 public static function groupHasPermission( $group, $role ) {
4526 global $wgGroupPermissions, $wgRevokePermissions;
4527 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4528 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4532 * Check if all users have the given permission
4535 * @param string $right Right to check
4538 public static function isEveryoneAllowed( $right ) {
4539 global $wgGroupPermissions, $wgRevokePermissions;
4540 static $cache = array();
4542 // Use the cached results, except in unit tests which rely on
4543 // being able change the permission mid-request
4544 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4545 return $cache[$right];
4548 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4549 $cache[$right] = false;
4553 // If it's revoked anywhere, then everyone doesn't have it
4554 foreach ( $wgRevokePermissions as $rights ) {
4555 if ( isset( $rights[$right] ) && $rights[$right] ) {
4556 $cache[$right] = false;
4561 // Allow extensions (e.g. OAuth) to say false
4562 if ( !Hooks
::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4563 $cache[$right] = false;
4567 $cache[$right] = true;
4572 * Get the localized descriptive name for a group, if it exists
4574 * @param string $group Internal group name
4575 * @return string Localized descriptive group name
4577 public static function getGroupName( $group ) {
4578 $msg = wfMessage( "group-$group" );
4579 return $msg->isBlank() ?
$group : $msg->text();
4583 * Get the localized descriptive name for a member of a group, if it exists
4585 * @param string $group Internal group name
4586 * @param string $username Username for gender (since 1.19)
4587 * @return string Localized name for group member
4589 public static function getGroupMember( $group, $username = '#' ) {
4590 $msg = wfMessage( "group-$group-member", $username );
4591 return $msg->isBlank() ?
$group : $msg->text();
4595 * Return the set of defined explicit groups.
4596 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4597 * are not included, as they are defined automatically, not in the database.
4598 * @return array Array of internal group names
4600 public static function getAllGroups() {
4601 global $wgGroupPermissions, $wgRevokePermissions;
4603 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4604 self
::getImplicitGroups()
4609 * Get a list of all available permissions.
4610 * @return string[] Array of permission names
4612 public static function getAllRights() {
4613 if ( self
::$mAllRights === false ) {
4614 global $wgAvailableRights;
4615 if ( count( $wgAvailableRights ) ) {
4616 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4618 self
::$mAllRights = self
::$mCoreRights;
4620 Hooks
::run( 'UserGetAllRights', array( &self
::$mAllRights ) );
4622 return self
::$mAllRights;
4626 * Get a list of implicit groups
4627 * @return array Array of Strings Array of internal group names
4629 public static function getImplicitGroups() {
4630 global $wgImplicitGroups;
4632 $groups = $wgImplicitGroups;
4633 # Deprecated, use $wgImplicitGroups instead
4634 Hooks
::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4640 * Get the title of a page describing a particular group
4642 * @param string $group Internal group name
4643 * @return Title|bool Title of the page if it exists, false otherwise
4645 public static function getGroupPage( $group ) {
4646 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4647 if ( $msg->exists() ) {
4648 $title = Title
::newFromText( $msg->text() );
4649 if ( is_object( $title ) ) {
4657 * Create a link to the group in HTML, if available;
4658 * else return the group name.
4660 * @param string $group Internal name of the group
4661 * @param string $text The text of the link
4662 * @return string HTML link to the group
4664 public static function makeGroupLinkHTML( $group, $text = '' ) {
4665 if ( $text == '' ) {
4666 $text = self
::getGroupName( $group );
4668 $title = self
::getGroupPage( $group );
4670 return Linker
::link( $title, htmlspecialchars( $text ) );
4672 return htmlspecialchars( $text );
4677 * Create a link to the group in Wikitext, if available;
4678 * else return the group name.
4680 * @param string $group Internal name of the group
4681 * @param string $text The text of the link
4682 * @return string Wikilink to the group
4684 public static function makeGroupLinkWiki( $group, $text = '' ) {
4685 if ( $text == '' ) {
4686 $text = self
::getGroupName( $group );
4688 $title = self
::getGroupPage( $group );
4690 $page = $title->getFullText();
4691 return "[[$page|$text]]";
4698 * Returns an array of the groups that a particular group can add/remove.
4700 * @param string $group The group to check for whether it can add/remove
4701 * @return array Array( 'add' => array( addablegroups ),
4702 * 'remove' => array( removablegroups ),
4703 * 'add-self' => array( addablegroups to self),
4704 * 'remove-self' => array( removable groups from self) )
4706 public static function changeableByGroup( $group ) {
4707 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4711 'remove' => array(),
4712 'add-self' => array(),
4713 'remove-self' => array()
4716 if ( empty( $wgAddGroups[$group] ) ) {
4717 // Don't add anything to $groups
4718 } elseif ( $wgAddGroups[$group] === true ) {
4719 // You get everything
4720 $groups['add'] = self
::getAllGroups();
4721 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4722 $groups['add'] = $wgAddGroups[$group];
4725 // Same thing for remove
4726 if ( empty( $wgRemoveGroups[$group] ) ) {
4728 } elseif ( $wgRemoveGroups[$group] === true ) {
4729 $groups['remove'] = self
::getAllGroups();
4730 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4731 $groups['remove'] = $wgRemoveGroups[$group];
4734 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4735 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4736 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4737 if ( is_int( $key ) ) {
4738 $wgGroupsAddToSelf['user'][] = $value;
4743 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4744 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4745 if ( is_int( $key ) ) {
4746 $wgGroupsRemoveFromSelf['user'][] = $value;
4751 // Now figure out what groups the user can add to him/herself
4752 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4754 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4755 // No idea WHY this would be used, but it's there
4756 $groups['add-self'] = User
::getAllGroups();
4757 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4758 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4761 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4763 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4764 $groups['remove-self'] = User
::getAllGroups();
4765 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4766 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4773 * Returns an array of groups that this user can add and remove
4774 * @return array Array( 'add' => array( addablegroups ),
4775 * 'remove' => array( removablegroups ),
4776 * 'add-self' => array( addablegroups to self),
4777 * 'remove-self' => array( removable groups from self) )
4779 public function changeableGroups() {
4780 if ( $this->isAllowed( 'userrights' ) ) {
4781 // This group gives the right to modify everything (reverse-
4782 // compatibility with old "userrights lets you change
4784 // Using array_merge to make the groups reindexed
4785 $all = array_merge( User
::getAllGroups() );
4789 'add-self' => array(),
4790 'remove-self' => array()
4794 // Okay, it's not so simple, we will have to go through the arrays
4797 'remove' => array(),
4798 'add-self' => array(),
4799 'remove-self' => array()
4801 $addergroups = $this->getEffectiveGroups();
4803 foreach ( $addergroups as $addergroup ) {
4804 $groups = array_merge_recursive(
4805 $groups, $this->changeableByGroup( $addergroup )
4807 $groups['add'] = array_unique( $groups['add'] );
4808 $groups['remove'] = array_unique( $groups['remove'] );
4809 $groups['add-self'] = array_unique( $groups['add-self'] );
4810 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4816 * Increment the user's edit-count field.
4817 * Will have no effect for anonymous users.
4819 public function incEditCount() {
4820 if ( !$this->isAnon() ) {
4821 $dbw = wfGetDB( DB_MASTER
);
4824 array( 'user_editcount=user_editcount+1' ),
4825 array( 'user_id' => $this->getId() ),
4829 // Lazy initialization check...
4830 if ( $dbw->affectedRows() == 0 ) {
4831 // Now here's a goddamn hack...
4832 $dbr = wfGetDB( DB_SLAVE
);
4833 if ( $dbr !== $dbw ) {
4834 // If we actually have a slave server, the count is
4835 // at least one behind because the current transaction
4836 // has not been committed and replicated.
4837 $this->initEditCount( 1 );
4839 // But if DB_SLAVE is selecting the master, then the
4840 // count we just read includes the revision that was
4841 // just added in the working transaction.
4842 $this->initEditCount();
4846 // edit count in user cache too
4847 $this->invalidateCache();
4851 * Initialize user_editcount from data out of the revision table
4853 * @param int $add Edits to add to the count from the revision table
4854 * @return int Number of edits
4856 protected function initEditCount( $add = 0 ) {
4857 // Pull from a slave to be less cruel to servers
4858 // Accuracy isn't the point anyway here
4859 $dbr = wfGetDB( DB_SLAVE
);
4860 $count = (int)$dbr->selectField(
4863 array( 'rev_user' => $this->getId() ),
4866 $count = $count +
$add;
4868 $dbw = wfGetDB( DB_MASTER
);
4871 array( 'user_editcount' => $count ),
4872 array( 'user_id' => $this->getId() ),
4880 * Get the description of a given right
4882 * @param string $right Right to query
4883 * @return string Localized description of the right
4885 public static function getRightDescription( $right ) {
4886 $key = "right-$right";
4887 $msg = wfMessage( $key );
4888 return $msg->isBlank() ?
$right : $msg->text();
4892 * Make a new-style password hash
4894 * @param string $password Plain-text password
4895 * @param bool|string $salt Optional salt, may be random or the user ID.
4896 * If unspecified or false, will generate one automatically
4897 * @return string Password hash
4898 * @deprecated since 1.24, use Password class
4900 public static function crypt( $password, $salt = false ) {
4901 wfDeprecated( __METHOD__
, '1.24' );
4902 $hash = self
::getPasswordFactory()->newFromPlaintext( $password );
4903 return $hash->toString();
4907 * Compare a password hash with a plain-text password. Requires the user
4908 * ID if there's a chance that the hash is an old-style hash.
4910 * @param string $hash Password hash
4911 * @param string $password Plain-text password to compare
4912 * @param string|bool $userId User ID for old-style password salt
4915 * @deprecated since 1.24, use Password class
4917 public static function comparePasswords( $hash, $password, $userId = false ) {
4918 wfDeprecated( __METHOD__
, '1.24' );
4920 // Check for *really* old password hashes that don't even have a type
4921 // The old hash format was just an md5 hex hash, with no type information
4922 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4923 global $wgPasswordSalt;
4924 if ( $wgPasswordSalt ) {
4925 $password = ":B:{$userId}:{$hash}";
4927 $password = ":A:{$hash}";
4931 $hash = self
::getPasswordFactory()->newFromCiphertext( $hash );
4932 return $hash->equals( $password );
4936 * Add a newuser log entry for this user.
4937 * Before 1.19 the return value was always true.
4939 * @param string|bool $action Account creation type.
4940 * - String, one of the following values:
4941 * - 'create' for an anonymous user creating an account for himself.
4942 * This will force the action's performer to be the created user itself,
4943 * no matter the value of $wgUser
4944 * - 'create2' for a logged in user creating an account for someone else
4945 * - 'byemail' when the created user will receive its password by e-mail
4946 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4947 * - Boolean means whether the account was created by e-mail (deprecated):
4948 * - true will be converted to 'byemail'
4949 * - false will be converted to 'create' if this object is the same as
4950 * $wgUser and to 'create2' otherwise
4952 * @param string $reason User supplied reason
4954 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4956 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4957 global $wgUser, $wgNewUserLog;
4958 if ( empty( $wgNewUserLog ) ) {
4959 return true; // disabled
4962 if ( $action === true ) {
4963 $action = 'byemail';
4964 } elseif ( $action === false ) {
4965 if ( $this->equals( $wgUser ) ) {
4968 $action = 'create2';
4972 if ( $action === 'create' ||
$action === 'autocreate' ) {
4975 $performer = $wgUser;
4978 $logEntry = new ManualLogEntry( 'newusers', $action );
4979 $logEntry->setPerformer( $performer );
4980 $logEntry->setTarget( $this->getUserPage() );
4981 $logEntry->setComment( $reason );
4982 $logEntry->setParameters( array(
4983 '4::userid' => $this->getId(),
4985 $logid = $logEntry->insert();
4987 if ( $action !== 'autocreate' ) {
4988 $logEntry->publish( $logid );
4995 * Add an autocreate newuser log entry for this user
4996 * Used by things like CentralAuth and perhaps other authplugins.
4997 * Consider calling addNewUserLogEntry() directly instead.
5001 public function addNewUserLogEntryAutoCreate() {
5002 $this->addNewUserLogEntry( 'autocreate' );
5008 * Load the user options either from cache, the database or an array
5010 * @param array $data Rows for the current user out of the user_properties table
5012 protected function loadOptions( $data = null ) {
5017 if ( $this->mOptionsLoaded
) {
5021 $this->mOptions
= self
::getDefaultOptions();
5023 if ( !$this->getId() ) {
5024 // For unlogged-in users, load language/variant options from request.
5025 // There's no need to do it for logged-in users: they can set preferences,
5026 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5027 // so don't override user's choice (especially when the user chooses site default).
5028 $variant = $wgContLang->getDefaultVariant();
5029 $this->mOptions
['variant'] = $variant;
5030 $this->mOptions
['language'] = $variant;
5031 $this->mOptionsLoaded
= true;
5035 // Maybe load from the object
5036 if ( !is_null( $this->mOptionOverrides
) ) {
5037 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5038 foreach ( $this->mOptionOverrides
as $key => $value ) {
5039 $this->mOptions
[$key] = $value;
5042 if ( !is_array( $data ) ) {
5043 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5044 // Load from database
5045 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5046 ?
wfGetDB( DB_MASTER
)
5047 : wfGetDB( DB_SLAVE
);
5049 $res = $dbr->select(
5051 array( 'up_property', 'up_value' ),
5052 array( 'up_user' => $this->getId() ),
5056 $this->mOptionOverrides
= array();
5058 foreach ( $res as $row ) {
5059 $data[$row->up_property
] = $row->up_value
;
5062 foreach ( $data as $property => $value ) {
5063 $this->mOptionOverrides
[$property] = $value;
5064 $this->mOptions
[$property] = $value;
5068 $this->mOptionsLoaded
= true;
5070 Hooks
::run( 'UserLoadOptions', array( $this, &$this->mOptions
) );
5074 * Saves the non-default options for this user, as previously set e.g. via
5075 * setOption(), in the database's "user_properties" (preferences) table.
5076 * Usually used via saveSettings().
5078 protected function saveOptions() {
5079 $this->loadOptions();
5081 // Not using getOptions(), to keep hidden preferences in database
5082 $saveOptions = $this->mOptions
;
5084 // Allow hooks to abort, for instance to save to a global profile.
5085 // Reset options to default state before saving.
5086 if ( !Hooks
::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5090 $userId = $this->getId();
5092 $insert_rows = array(); // all the new preference rows
5093 foreach ( $saveOptions as $key => $value ) {
5094 // Don't bother storing default values
5095 $defaultOption = self
::getDefaultOption( $key );
5096 if ( ( $defaultOption === null && $value !== false && $value !== null )
5097 ||
$value != $defaultOption
5099 $insert_rows[] = array(
5100 'up_user' => $userId,
5101 'up_property' => $key,
5102 'up_value' => $value,
5107 $dbw = wfGetDB( DB_MASTER
);
5109 $res = $dbw->select( 'user_properties',
5110 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
5112 // Find prior rows that need to be removed or updated. These rows will
5113 // all be deleted (the later so that INSERT IGNORE applies the new values).
5114 $keysDelete = array();
5115 foreach ( $res as $row ) {
5116 if ( !isset( $saveOptions[$row->up_property
] )
5117 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5119 $keysDelete[] = $row->up_property
;
5123 if ( count( $keysDelete ) ) {
5124 // Do the DELETE by PRIMARY KEY for prior rows.
5125 // In the past a very large portion of calls to this function are for setting
5126 // 'rememberpassword' for new accounts (a preference that has since been removed).
5127 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5128 // caused gap locks on [max user ID,+infinity) which caused high contention since
5129 // updates would pile up on each other as they are for higher (newer) user IDs.
5130 // It might not be necessary these days, but it shouldn't hurt either.
5131 $dbw->delete( 'user_properties',
5132 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
5134 // Insert the new preference rows
5135 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
5139 * Lazily instantiate and return a factory object for making passwords
5141 * @return PasswordFactory
5143 public static function getPasswordFactory() {
5144 if ( self
::$mPasswordFactory === null ) {
5145 self
::$mPasswordFactory = new PasswordFactory();
5146 self
::$mPasswordFactory->init( RequestContext
::getMain()->getConfig() );
5149 return self
::$mPasswordFactory;
5153 * Provide an array of HTML5 attributes to put on an input element
5154 * intended for the user to enter a new password. This may include
5155 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5157 * Do *not* use this when asking the user to enter his current password!
5158 * Regardless of configuration, users may have invalid passwords for whatever
5159 * reason (e.g., they were set before requirements were tightened up).
5160 * Only use it when asking for a new password, like on account creation or
5163 * Obviously, you still need to do server-side checking.
5165 * NOTE: A combination of bugs in various browsers means that this function
5166 * actually just returns array() unconditionally at the moment. May as
5167 * well keep it around for when the browser bugs get fixed, though.
5169 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5171 * @return array Array of HTML attributes suitable for feeding to
5172 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5173 * That will get confused by the boolean attribute syntax used.)
5175 public static function passwordChangeInputAttribs() {
5176 global $wgMinimalPasswordLength;
5178 if ( $wgMinimalPasswordLength == 0 ) {
5182 # Note that the pattern requirement will always be satisfied if the
5183 # input is empty, so we need required in all cases.
5185 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5186 # if e-mail confirmation is being used. Since HTML5 input validation
5187 # is b0rked anyway in some browsers, just return nothing. When it's
5188 # re-enabled, fix this code to not output required for e-mail
5190 #$ret = array( 'required' );
5193 # We can't actually do this right now, because Opera 9.6 will print out
5194 # the entered password visibly in its error message! When other
5195 # browsers add support for this attribute, or Opera fixes its support,
5196 # we can add support with a version check to avoid doing this on Opera
5197 # versions where it will be a problem. Reported to Opera as
5198 # DSK-262266, but they don't have a public bug tracker for us to follow.
5200 if ( $wgMinimalPasswordLength > 1 ) {
5201 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5202 $ret['title'] = wfMessage( 'passwordtooshort' )
5203 ->numParams( $wgMinimalPasswordLength )->text();
5211 * Return the list of user fields that should be selected to create
5212 * a new user object.
5215 public static function selectFields() {
5223 'user_email_authenticated',
5225 'user_email_token_expires',
5226 'user_registration',
5232 * Factory function for fatal permission-denied errors
5235 * @param string $permission User right required
5238 static function newFatalPermissionDeniedStatus( $permission ) {
5241 $groups = array_map(
5242 array( 'User', 'makeGroupLinkWiki' ),
5243 User
::getGroupsWithPermission( $permission )
5247 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5249 return Status
::newFatal( 'badaccess-group0' );
5254 * Checks if two user objects point to the same user.
5260 public function equals( User
$user ) {
5261 return $this->getName() === $user->getName();