3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * String Some punctuation to prevent editing from broken text-mangling proxies.
27 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
30 * The User object encapsulates all of the user-specific settings (user_id,
31 * name, rights, password, email address, options, last login time). Client
32 * classes use the getXXX() functions to access these fields. These functions
33 * do all the work of determining whether the user is logged in,
34 * whether the requested option can be satisfied from cookies or
35 * whether a database query is needed. Most of the settings needed
36 * for rendering normal pages are set in the cookie to minimize use
39 class User
implements IDBAccessObject
{
41 * @const int Number of characters in user_token field.
43 const TOKEN_LENGTH
= 32;
46 * Global constant made accessible as class constants so that autoloader
49 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
52 * @const int Serialized record version.
57 * Maximum items in $mWatchedItems
59 const MAX_WATCHED_ITEMS_CACHE
= 100;
62 * Exclude user options that are set to their default value.
65 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
68 * @var PasswordFactory Lazily loaded factory object for passwords
70 private static $mPasswordFactory = null;
73 * Array of Strings List of member variables which are saved to the
74 * shared cache (memcached). Any operation which changes the
75 * corresponding database fields must call a cache-clearing function.
78 protected static $mCacheVars = array(
86 'mEmailAuthenticated',
93 // user_properties table
98 * Array of Strings Core rights.
99 * Each of these should have a corresponding message of the form
103 protected static $mCoreRights = array(
132 'editusercssjs', #deprecated
145 'move-categorypages',
146 'move-rootuserpages',
150 'override-export-depth',
174 'userrights-interwiki',
182 * String Cached results of getAllRights()
184 protected static $mAllRights = false;
186 /** @name Cache variables */
195 * @todo Make this actually private
201 * @todo Make this actually private
204 public $mNewpassword;
206 public $mNewpassTime;
209 /** @var string TS_MW timestamp from the DB */
211 /** @var string TS_MW timestamp from cache */
212 protected $mQuickTouched;
216 public $mEmailAuthenticated;
218 protected $mEmailToken;
220 protected $mEmailTokenExpires;
222 protected $mRegistration;
224 protected $mEditCount;
228 protected $mOptionOverrides;
230 protected $mPasswordExpires;
234 * Bool Whether the cache variables have been loaded.
237 public $mOptionsLoaded;
240 * Array with already loaded items or true if all items have been loaded.
242 protected $mLoadedItems = array();
246 * String Initialization data source if mLoadedItems!==true. May be one of:
247 * - 'defaults' anonymous user initialised from class defaults
248 * - 'name' initialise from mName
249 * - 'id' initialise from mId
250 * - 'session' log in from cookies or session if possible
252 * Use the User::newFrom*() family of functions to set this.
257 * Lazy-initialized variables, invalidated with clearInstanceCache
261 protected $mDatePreference;
269 protected $mBlockreason;
271 protected $mEffectiveGroups;
273 protected $mImplicitGroups;
275 protected $mFormerGroups;
277 protected $mBlockedGlobally;
294 protected $mAllowUsertalk;
297 private $mBlockedFromCreateAccount = false;
300 private $mWatchedItems = array();
302 /** @var integer User::READ_* constant bitfield used to load data */
303 protected $queryFlagsUsed = self
::READ_NORMAL
;
305 public static $idCacheByName = array();
308 * Lightweight constructor for an anonymous user.
309 * Use the User::newFrom* factory functions for other kinds of users.
313 * @see newFromConfirmationCode()
314 * @see newFromSession()
317 public function __construct() {
318 $this->clearInstanceCache( 'defaults' );
324 public function __toString() {
325 return $this->getName();
329 * Load the user table data for this object from the source given by mFrom.
331 * @param integer $flags User::READ_* constant bitfield
333 public function load( $flags = self
::READ_LATEST
) {
334 if ( $this->mLoadedItems
=== true ) {
338 // Set it now to avoid infinite recursion in accessors
339 $this->mLoadedItems
= true;
340 $this->queryFlagsUsed
= $flags;
342 switch ( $this->mFrom
) {
344 $this->loadDefaults();
347 // @TODO: this gets the ID from a slave, assuming renames
348 // are rare. This should be controllable and more consistent.
349 $this->mId
= self
::idFromName( $this->mName
);
351 // Nonexistent user placeholder object
352 $this->loadDefaults( $this->mName
);
354 $this->loadFromId( $flags );
358 $this->loadFromId( $flags );
361 if ( !$this->loadFromSession() ) {
362 // Loading from session failed. Load defaults.
363 $this->loadDefaults();
365 Hooks
::run( 'UserLoadAfterLoadFromSession', array( $this ) );
368 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
373 * Load user table data, given mId has already been set.
374 * @param integer $flags User::READ_* constant bitfield
375 * @return bool False if the ID does not exist, true otherwise
377 public function loadFromId( $flags = self
::READ_LATEST
) {
378 if ( $this->mId
== 0 ) {
379 $this->loadDefaults();
384 $cache = $this->loadFromCache();
386 wfDebug( "User: cache miss for user {$this->mId}\n" );
388 if ( !$this->loadFromDatabase( $flags ) ) {
389 // Can't load from ID, user is anonymous
392 if ( $flags & self
::READ_LATEST
) {
393 // Only save master data back to the cache to keep it consistent.
394 // @TODO: save it anyway and have callers specifiy $flags and have
395 // load() called as needed. That requires updating MANY callers...
396 $this->saveToCache();
400 $this->mLoadedItems
= true;
401 $this->queryFlagsUsed
= $flags;
407 * Load user data from shared cache, given mId has already been set.
409 * @return bool false if the ID does not exist or data is invalid, true otherwise
412 protected function loadFromCache() {
415 if ( $this->mId
== 0 ) {
416 $this->loadDefaults();
420 $key = wfMemcKey( 'user', 'id', $this->mId
);
421 $data = $wgMemc->get( $key );
422 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
427 wfDebug( "User: got user {$this->mId} from cache\n" );
429 // Restore from cache
430 foreach ( self
::$mCacheVars as $name ) {
431 $this->$name = $data[$name];
438 * Save user data to the shared cache
440 * This method should not be called outside the User class
442 public function saveToCache() {
447 $this->loadOptions();
449 if ( $this->isAnon() ) {
450 // Anonymous users are uncached
454 // The cache needs good consistency due to its high TTL, so the user
455 // should have been loaded from the master to avoid lag amplification.
456 if ( !( $this->queryFlagsUsed
& self
::READ_LATEST
) ) {
457 wfWarn( "Cannot cache slave-loaded User object with ID '{$this->mId}'." );
462 foreach ( self
::$mCacheVars as $name ) {
463 $data[$name] = $this->$name;
465 $data['mVersion'] = self
::VERSION
;
466 $key = wfMemcKey( 'user', 'id', $this->mId
);
468 $wgMemc->set( $key, $data );
471 /** @name newFrom*() static factory methods */
475 * Static factory method for creation from username.
477 * This is slightly less efficient than newFromId(), so use newFromId() if
478 * you have both an ID and a name handy.
480 * @param string $name Username, validated by Title::newFromText()
481 * @param string|bool $validate Validate username. Takes the same parameters as
482 * User::getCanonicalName(), except that true is accepted as an alias
483 * for 'valid', for BC.
485 * @return User|bool User object, or false if the username is invalid
486 * (e.g. if it contains illegal characters or is an IP address). If the
487 * username is not present in the database, the result will be a user object
488 * with a name, zero user ID and default settings.
490 public static function newFromName( $name, $validate = 'valid' ) {
491 if ( $validate === true ) {
494 $name = self
::getCanonicalName( $name, $validate );
495 if ( $name === false ) {
498 // Create unloaded user object
502 $u->setItemLoaded( 'name' );
508 * Static factory method for creation from a given user ID.
510 * @param int $id Valid user ID
511 * @return User The corresponding User object
513 public static function newFromId( $id ) {
517 $u->setItemLoaded( 'id' );
522 * Factory method to fetch whichever user has a given email confirmation code.
523 * This code is generated when an account is created or its e-mail address
526 * If the code is invalid or has expired, returns NULL.
528 * @param string $code Confirmation code
531 public static function newFromConfirmationCode( $code ) {
532 $dbr = wfGetDB( DB_SLAVE
);
533 $id = $dbr->selectField( 'user', 'user_id', array(
534 'user_email_token' => md5( $code ),
535 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
537 if ( $id !== false ) {
538 return User
::newFromId( $id );
545 * Create a new user object using data from session or cookies. If the
546 * login credentials are invalid, the result is an anonymous user.
548 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
551 public static function newFromSession( WebRequest
$request = null ) {
553 $user->mFrom
= 'session';
554 $user->mRequest
= $request;
559 * Create a new user object from a user row.
560 * The row should have the following fields from the user table in it:
561 * - either user_name or user_id to load further data if needed (or both)
563 * - all other fields (email, password, etc.)
564 * It is useless to provide the remaining fields if either user_id,
565 * user_name and user_real_name are not provided because the whole row
566 * will be loaded once more from the database when accessing them.
568 * @param stdClass $row A row from the user table
569 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
572 public static function newFromRow( $row, $data = null ) {
574 $user->loadFromRow( $row, $data );
581 * Get the username corresponding to a given user ID
582 * @param int $id User ID
583 * @return string|bool The corresponding username
585 public static function whoIs( $id ) {
586 return UserCache
::singleton()->getProp( $id, 'name' );
590 * Get the real name of a user given their user ID
592 * @param int $id User ID
593 * @return string|bool The corresponding user's real name
595 public static function whoIsReal( $id ) {
596 return UserCache
::singleton()->getProp( $id, 'real_name' );
600 * Get database id given a user name
601 * @param string $name Username
602 * @return int|null The corresponding user's ID, or null if user is nonexistent
604 public static function idFromName( $name ) {
605 $nt = Title
::makeTitleSafe( NS_USER
, $name );
606 if ( is_null( $nt ) ) {
611 if ( isset( self
::$idCacheByName[$name] ) ) {
612 return self
::$idCacheByName[$name];
615 $dbr = wfGetDB( DB_SLAVE
);
616 $s = $dbr->selectRow(
619 array( 'user_name' => $nt->getText() ),
623 if ( $s === false ) {
626 $result = $s->user_id
;
629 self
::$idCacheByName[$name] = $result;
631 if ( count( self
::$idCacheByName ) > 1000 ) {
632 self
::$idCacheByName = array();
639 * Reset the cache used in idFromName(). For use in tests.
641 public static function resetIdByNameCache() {
642 self
::$idCacheByName = array();
646 * Does the string match an anonymous IPv4 address?
648 * This function exists for username validation, in order to reject
649 * usernames which are similar in form to IP addresses. Strings such
650 * as 300.300.300.300 will return true because it looks like an IP
651 * address, despite not being strictly valid.
653 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
654 * address because the usemod software would "cloak" anonymous IP
655 * addresses like this, if we allowed accounts like this to be created
656 * new users could get the old edits of these anonymous users.
658 * @param string $name Name to match
661 public static function isIP( $name ) {
662 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
663 || IP
::isIPv6( $name );
667 * Is the input a valid username?
669 * Checks if the input is a valid username, we don't want an empty string,
670 * an IP address, anything that contains slashes (would mess up subpages),
671 * is longer than the maximum allowed username size or doesn't begin with
674 * @param string $name Name to match
677 public static function isValidUserName( $name ) {
678 global $wgContLang, $wgMaxNameChars;
681 || User
::isIP( $name )
682 ||
strpos( $name, '/' ) !== false
683 ||
strlen( $name ) > $wgMaxNameChars
684 ||
$name != $wgContLang->ucfirst( $name )
686 wfDebugLog( 'username', __METHOD__
.
687 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
691 // Ensure that the name can't be misresolved as a different title,
692 // such as with extra namespace keys at the start.
693 $parsed = Title
::newFromText( $name );
694 if ( is_null( $parsed )
695 ||
$parsed->getNamespace()
696 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
697 wfDebugLog( 'username', __METHOD__
.
698 ": '$name' invalid due to ambiguous prefixes" );
702 // Check an additional blacklist of troublemaker characters.
703 // Should these be merged into the title char list?
704 $unicodeBlacklist = '/[' .
705 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
706 '\x{00a0}' . # non-breaking space
707 '\x{2000}-\x{200f}' . # various whitespace
708 '\x{2028}-\x{202f}' . # breaks and control chars
709 '\x{3000}' . # ideographic space
710 '\x{e000}-\x{f8ff}' . # private use
712 if ( preg_match( $unicodeBlacklist, $name ) ) {
713 wfDebugLog( 'username', __METHOD__
.
714 ": '$name' invalid due to blacklisted characters" );
722 * Usernames which fail to pass this function will be blocked
723 * from user login and new account registrations, but may be used
724 * internally by batch processes.
726 * If an account already exists in this form, login will be blocked
727 * by a failure to pass this function.
729 * @param string $name Name to match
732 public static function isUsableName( $name ) {
733 global $wgReservedUsernames;
734 // Must be a valid username, obviously ;)
735 if ( !self
::isValidUserName( $name ) ) {
739 static $reservedUsernames = false;
740 if ( !$reservedUsernames ) {
741 $reservedUsernames = $wgReservedUsernames;
742 Hooks
::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
745 // Certain names may be reserved for batch processes.
746 foreach ( $reservedUsernames as $reserved ) {
747 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
748 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
750 if ( $reserved == $name ) {
758 * Usernames which fail to pass this function will be blocked
759 * from new account registrations, but may be used internally
760 * either by batch processes or by user accounts which have
761 * already been created.
763 * Additional blacklisting may be added here rather than in
764 * isValidUserName() to avoid disrupting existing accounts.
766 * @param string $name String to match
769 public static function isCreatableName( $name ) {
770 global $wgInvalidUsernameCharacters;
772 // Ensure that the username isn't longer than 235 bytes, so that
773 // (at least for the builtin skins) user javascript and css files
774 // will work. (bug 23080)
775 if ( strlen( $name ) > 235 ) {
776 wfDebugLog( 'username', __METHOD__
.
777 ": '$name' invalid due to length" );
781 // Preg yells if you try to give it an empty string
782 if ( $wgInvalidUsernameCharacters !== '' ) {
783 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
784 wfDebugLog( 'username', __METHOD__
.
785 ": '$name' invalid due to wgInvalidUsernameCharacters" );
790 return self
::isUsableName( $name );
794 * Is the input a valid password for this user?
796 * @param string $password Desired password
799 public function isValidPassword( $password ) {
800 //simple boolean wrapper for getPasswordValidity
801 return $this->getPasswordValidity( $password ) === true;
806 * Given unvalidated password input, return error message on failure.
808 * @param string $password Desired password
809 * @return bool|string|array True on success, string or array of error message on failure
811 public function getPasswordValidity( $password ) {
812 $result = $this->checkPasswordValidity( $password );
813 if ( $result->isGood() ) {
817 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
818 $messages[] = $error['message'];
820 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
821 $messages[] = $warning['message'];
823 if ( count( $messages ) === 1 ) {
831 * Check if this is a valid password for this user
833 * Create a Status object based on the password's validity.
834 * The Status should be set to fatal if the user should not
835 * be allowed to log in, and should have any errors that
836 * would block changing the password.
838 * If the return value of this is not OK, the password
839 * should not be checked. If the return value is not Good,
840 * the password can be checked, but the user should not be
841 * able to set their password to this.
843 * @param string $password Desired password
847 public function checkPasswordValidity( $password ) {
848 global $wgMinimalPasswordLength, $wgMaximalPasswordLength, $wgContLang;
850 static $blockedLogins = array(
851 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
852 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
855 $status = Status
::newGood();
857 $result = false; //init $result to false for the internal checks
859 if ( !Hooks
::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
860 $status->error( $result );
864 if ( $result === false ) {
865 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
866 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
868 } elseif ( strlen( $password ) > $wgMaximalPasswordLength ) {
869 // T64685: Password too long, might cause DoS attack
870 $status->fatal( 'passwordtoolong', $wgMaximalPasswordLength );
872 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
873 $status->error( 'password-name-match' );
875 } elseif ( isset( $blockedLogins[$this->getName()] )
876 && $password == $blockedLogins[$this->getName()]
878 $status->error( 'password-login-forbidden' );
881 //it seems weird returning a Good status here, but this is because of the
882 //initialization of $result to false above. If the hook is never run or it
883 //doesn't modify $result, then we will likely get down into this if with
887 } elseif ( $result === true ) {
890 $status->error( $result );
891 return $status; //the isValidPassword hook set a string $result and returned true
896 * Expire a user's password
898 * @param int $ts Optional timestamp to convert, default 0 for the current time
900 public function expirePassword( $ts = 0 ) {
901 $this->loadPasswords();
902 $timestamp = wfTimestamp( TS_MW
, $ts );
903 $this->mPasswordExpires
= $timestamp;
904 $this->saveSettings();
908 * Clear the password expiration for a user
910 * @param bool $load Ensure user object is loaded first
912 public function resetPasswordExpiration( $load = true ) {
913 global $wgPasswordExpirationDays;
918 if ( $wgPasswordExpirationDays ) {
919 $newExpire = wfTimestamp(
921 time() +
( $wgPasswordExpirationDays * 24 * 3600 )
924 // Give extensions a chance to force an expiration
925 Hooks
::run( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
926 $this->mPasswordExpires
= $newExpire;
930 * Check if the user's password is expired.
931 * TODO: Put this and password length into a PasswordPolicy object
933 * @return string|bool The expiration type, or false if not expired
934 * hard: A password change is required to login
935 * soft: Allow login, but encourage password change
936 * false: Password is not expired
938 public function getPasswordExpired() {
939 global $wgPasswordExpireGrace;
941 $now = wfTimestamp();
942 $expiration = $this->getPasswordExpireDate();
943 $expUnix = wfTimestamp( TS_UNIX
, $expiration );
944 if ( $expiration !== null && $expUnix < $now ) {
945 $expired = ( $expUnix +
$wgPasswordExpireGrace < $now ) ?
'hard' : 'soft';
951 * Get this user's password expiration date. Since this may be using
952 * the cached User object, we assume that whatever mechanism is setting
953 * the expiration date is also expiring the User cache.
955 * @return string|bool The datestamp of the expiration, or null if not set
957 public function getPasswordExpireDate() {
959 return $this->mPasswordExpires
;
963 * Given unvalidated user input, return a canonical username, or false if
964 * the username is invalid.
965 * @param string $name User input
966 * @param string|bool $validate Type of validation to use:
967 * - false No validation
968 * - 'valid' Valid for batch processes
969 * - 'usable' Valid for batch processes and login
970 * - 'creatable' Valid for batch processes, login and account creation
972 * @throws MWException
973 * @return bool|string
975 public static function getCanonicalName( $name, $validate = 'valid' ) {
976 // Force usernames to capital
978 $name = $wgContLang->ucfirst( $name );
980 # Reject names containing '#'; these will be cleaned up
981 # with title normalisation, but then it's too late to
983 if ( strpos( $name, '#' ) !== false ) {
987 // Clean up name according to title rules,
988 // but only when validation is requested (bug 12654)
989 $t = ( $validate !== false ) ?
990 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
991 // Check for invalid titles
992 if ( is_null( $t ) ) {
996 // Reject various classes of invalid names
998 $name = $wgAuth->getCanonicalName( $t->getText() );
1000 switch ( $validate ) {
1004 if ( !User
::isValidUserName( $name ) ) {
1009 if ( !User
::isUsableName( $name ) ) {
1014 if ( !User
::isCreatableName( $name ) ) {
1019 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
1025 * Count the number of edits of a user
1027 * @param int $uid User ID to check
1028 * @return int The user's edit count
1030 * @deprecated since 1.21 in favour of User::getEditCount
1032 public static function edits( $uid ) {
1033 wfDeprecated( __METHOD__
, '1.21' );
1034 $user = self
::newFromId( $uid );
1035 return $user->getEditCount();
1039 * Return a random password.
1041 * @return string New random password
1043 public static function randomPassword() {
1044 global $wgMinimalPasswordLength;
1045 // Decide the final password length based on our min password length,
1046 // stopping at a minimum of 10 chars.
1047 $length = max( 10, $wgMinimalPasswordLength );
1048 // Multiply by 1.25 to get the number of hex characters we need
1049 $length = $length * 1.25;
1050 // Generate random hex chars
1051 $hex = MWCryptRand
::generateHex( $length );
1052 // Convert from base 16 to base 32 to get a proper password like string
1053 return wfBaseConvert( $hex, 16, 32 );
1057 * Set cached properties to default.
1059 * @note This no longer clears uncached lazy-initialised properties;
1060 * the constructor does that instead.
1062 * @param string|bool $name
1064 public function loadDefaults( $name = false ) {
1066 $passwordFactory = self
::getPasswordFactory();
1069 $this->mName
= $name;
1070 $this->mRealName
= '';
1071 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1072 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1073 $this->mNewpassTime
= null;
1075 $this->mOptionOverrides
= null;
1076 $this->mOptionsLoaded
= false;
1078 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1079 if ( $loggedOut !== null ) {
1080 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1082 $this->mTouched
= '1'; # Allow any pages to be cached
1085 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1086 $this->mEmailAuthenticated
= null;
1087 $this->mEmailToken
= '';
1088 $this->mEmailTokenExpires
= null;
1089 $this->mPasswordExpires
= null;
1090 $this->resetPasswordExpiration( false );
1091 $this->mRegistration
= wfTimestamp( TS_MW
);
1092 $this->mGroups
= array();
1094 Hooks
::run( 'UserLoadDefaults', array( $this, $name ) );
1098 * Return whether an item has been loaded.
1100 * @param string $item Item to check. Current possibilities:
1104 * @param string $all 'all' to check if the whole object has been loaded
1105 * or any other string to check if only the item is available (e.g.
1109 public function isItemLoaded( $item, $all = 'all' ) {
1110 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1111 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1115 * Set that an item has been loaded
1117 * @param string $item
1119 protected function setItemLoaded( $item ) {
1120 if ( is_array( $this->mLoadedItems
) ) {
1121 $this->mLoadedItems
[$item] = true;
1126 * Load user data from the session or login cookie.
1128 * @return bool True if the user is logged in, false otherwise.
1130 private function loadFromSession() {
1132 Hooks
::run( 'UserLoadFromSession', array( $this, &$result ) );
1133 if ( $result !== null ) {
1137 $request = $this->getRequest();
1139 $cookieId = $request->getCookie( 'UserID' );
1140 $sessId = $request->getSessionData( 'wsUserID' );
1142 if ( $cookieId !== null ) {
1143 $sId = intval( $cookieId );
1144 if ( $sessId !== null && $cookieId != $sessId ) {
1145 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1146 cookie user ID ($sId) don't match!" );
1149 $request->setSessionData( 'wsUserID', $sId );
1150 } elseif ( $sessId !== null && $sessId != 0 ) {
1156 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1157 $sName = $request->getSessionData( 'wsUserName' );
1158 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1159 $sName = $request->getCookie( 'UserName' );
1160 $request->setSessionData( 'wsUserName', $sName );
1165 $proposedUser = User
::newFromId( $sId );
1166 $proposedUser->load( self
::READ_LATEST
);
1167 if ( !$proposedUser->isLoggedIn() ) {
1172 global $wgBlockDisablesLogin;
1173 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1174 // User blocked and we've disabled blocked user logins
1178 if ( $request->getSessionData( 'wsToken' ) ) {
1180 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1182 } elseif ( $request->getCookie( 'Token' ) ) {
1183 # Get the token from DB/cache and clean it up to remove garbage padding.
1184 # This deals with historical problems with bugs and the default column value.
1185 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1186 // Make comparison in constant time (bug 61346)
1187 $passwordCorrect = strlen( $token )
1188 && hash_equals( $token, $request->getCookie( 'Token' ) );
1191 // No session or persistent login cookie
1195 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1196 $this->loadFromUserObject( $proposedUser );
1197 $request->setSessionData( 'wsToken', $this->mToken
);
1198 wfDebug( "User: logged in from $from\n" );
1201 // Invalid credentials
1202 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1208 * Load user and user_group data from the database.
1209 * $this->mId must be set, this is how the user is identified.
1211 * @param integer $flags User::READ_* constant bitfield
1212 * @return bool True if the user exists, false if the user is anonymous
1214 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1216 $this->mId
= intval( $this->mId
);
1219 if ( !$this->mId
) {
1220 $this->loadDefaults();
1224 $db = ( $flags & self
::READ_LATEST
)
1225 ?
wfGetDB( DB_MASTER
)
1226 : wfGetDB( DB_SLAVE
);
1228 $s = $db->selectRow(
1230 self
::selectFields(),
1231 array( 'user_id' => $this->mId
),
1233 ( $flags & self
::READ_LOCKING
== self
::READ_LOCKING
)
1234 ?
array( 'LOCK IN SHARE MODE' )
1238 $this->queryFlagsUsed
= $flags;
1239 Hooks
::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1241 if ( $s !== false ) {
1242 // Initialise user table data
1243 $this->loadFromRow( $s );
1244 $this->mGroups
= null; // deferred
1245 $this->getEditCount(); // revalidation for nulls
1250 $this->loadDefaults();
1256 * Initialize this object from a row from the user table.
1258 * @param stdClass $row Row from the user table to load.
1259 * @param array $data Further user data to load into the object
1261 * user_groups Array with groups out of the user_groups table
1262 * user_properties Array with properties out of the user_properties table
1264 protected function loadFromRow( $row, $data = null ) {
1266 $passwordFactory = self
::getPasswordFactory();
1268 $this->mGroups
= null; // deferred
1270 if ( isset( $row->user_name
) ) {
1271 $this->mName
= $row->user_name
;
1272 $this->mFrom
= 'name';
1273 $this->setItemLoaded( 'name' );
1278 if ( isset( $row->user_real_name
) ) {
1279 $this->mRealName
= $row->user_real_name
;
1280 $this->setItemLoaded( 'realname' );
1285 if ( isset( $row->user_id
) ) {
1286 $this->mId
= intval( $row->user_id
);
1287 $this->mFrom
= 'id';
1288 $this->setItemLoaded( 'id' );
1293 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1294 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1297 if ( isset( $row->user_editcount
) ) {
1298 $this->mEditCount
= $row->user_editcount
;
1303 if ( isset( $row->user_password
) ) {
1304 // Check for *really* old password hashes that don't even have a type
1305 // The old hash format was just an md5 hex hash, with no type information
1306 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password
) ) {
1307 $row->user_password
= ":A:{$this->mId}:{$row->user_password}";
1311 $this->mPassword
= $passwordFactory->newFromCiphertext( $row->user_password
);
1312 } catch ( PasswordError
$e ) {
1313 wfDebug( 'Invalid password hash found in database.' );
1314 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1318 $this->mNewpassword
= $passwordFactory->newFromCiphertext( $row->user_newpassword
);
1319 } catch ( PasswordError
$e ) {
1320 wfDebug( 'Invalid password hash found in database.' );
1321 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1324 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1325 $this->mPasswordExpires
= wfTimestampOrNull( TS_MW
, $row->user_password_expires
);
1328 if ( isset( $row->user_email
) ) {
1329 $this->mEmail
= $row->user_email
;
1330 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1331 $this->mToken
= $row->user_token
;
1332 if ( $this->mToken
== '' ) {
1333 $this->mToken
= null;
1335 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1336 $this->mEmailToken
= $row->user_email_token
;
1337 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1338 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1344 $this->mLoadedItems
= true;
1347 if ( is_array( $data ) ) {
1348 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1349 $this->mGroups
= $data['user_groups'];
1351 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1352 $this->loadOptions( $data['user_properties'] );
1358 * Load the data for this user object from another user object.
1362 protected function loadFromUserObject( $user ) {
1364 $user->loadGroups();
1365 $user->loadOptions();
1366 foreach ( self
::$mCacheVars as $var ) {
1367 $this->$var = $user->$var;
1372 * Load the groups from the database if they aren't already loaded.
1374 private function loadGroups() {
1375 if ( is_null( $this->mGroups
) ) {
1376 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1377 ?
wfGetDB( DB_MASTER
)
1378 : wfGetDB( DB_SLAVE
);
1379 $res = $db->select( 'user_groups',
1380 array( 'ug_group' ),
1381 array( 'ug_user' => $this->mId
),
1383 $this->mGroups
= array();
1384 foreach ( $res as $row ) {
1385 $this->mGroups
[] = $row->ug_group
;
1391 * Load the user's password hashes from the database
1393 * This is usually called in a scenario where the actual User object was
1394 * loaded from the cache, and then password comparison needs to be performed.
1395 * Password hashes are not stored in memcached.
1399 private function loadPasswords() {
1400 if ( $this->getId() !== 0 &&
1401 ( $this->mPassword
=== null ||
$this->mNewpassword
=== null )
1403 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1404 ?
wfGetDB( DB_MASTER
)
1405 : wfGetDB( DB_SLAVE
);
1407 $this->loadFromRow( $db->selectRow(
1409 array( 'user_password', 'user_newpassword',
1410 'user_newpass_time', 'user_password_expires' ),
1411 array( 'user_id' => $this->getId() ),
1418 * Add the user to the group if he/she meets given criteria.
1420 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1421 * possible to remove manually via Special:UserRights. In such case it
1422 * will not be re-added automatically. The user will also not lose the
1423 * group if they no longer meet the criteria.
1425 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1427 * @return array Array of groups the user has been promoted to.
1429 * @see $wgAutopromoteOnce
1431 public function addAutopromoteOnceGroups( $event ) {
1432 global $wgAutopromoteOnceLogInRC, $wgAuth;
1434 if ( wfReadOnly() ||
!$this->getId() ) {
1438 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1439 if ( !count( $toPromote ) ) {
1443 if ( !$this->checkAndSetTouched() ) {
1444 return array(); // raced out (bug T48834)
1447 $oldGroups = $this->getGroups(); // previous groups
1448 foreach ( $toPromote as $group ) {
1449 $this->addGroup( $group );
1452 // update groups in external authentication database
1453 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1455 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1457 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1458 $logEntry->setPerformer( $this );
1459 $logEntry->setTarget( $this->getUserPage() );
1460 $logEntry->setParameters( array(
1461 '4::oldgroups' => $oldGroups,
1462 '5::newgroups' => $newGroups,
1464 $logid = $logEntry->insert();
1465 if ( $wgAutopromoteOnceLogInRC ) {
1466 $logEntry->publish( $logid );
1473 * Bump user_touched if it didn't change since this object was loaded
1475 * On success, the mTouched field is updated.
1476 * The user serialization cache is always cleared.
1478 * @return bool Whether user_touched was actually updated
1481 protected function checkAndSetTouched() {
1484 if ( !$this->mId
) {
1485 return false; // anon
1488 // Get a new user_touched that is higher than the old one
1489 $oldTouched = $this->mTouched
;
1490 $newTouched = $this->newTouchedTimestamp();
1492 $dbw = wfGetDB( DB_MASTER
);
1493 $dbw->update( 'user',
1494 array( 'user_touched' => $dbw->timestamp( $newTouched ) ),
1496 'user_id' => $this->mId
,
1497 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1501 $success = ( $dbw->affectedRows() > 0 );
1504 $this->mTouched
= $newTouched;
1507 // Clears on failure too since that is desired if the cache is stale
1508 $this->clearSharedCache();
1514 * Clear various cached data stored in this object. The cache of the user table
1515 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1517 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1518 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1520 public function clearInstanceCache( $reloadFrom = false ) {
1521 $this->mNewtalk
= -1;
1522 $this->mDatePreference
= null;
1523 $this->mBlockedby
= -1; # Unset
1524 $this->mHash
= false;
1525 $this->mRights
= null;
1526 $this->mEffectiveGroups
= null;
1527 $this->mImplicitGroups
= null;
1528 $this->mGroups
= null;
1529 $this->mOptions
= null;
1530 $this->mOptionsLoaded
= false;
1531 $this->mEditCount
= null;
1533 if ( $reloadFrom ) {
1534 $this->mLoadedItems
= array();
1535 $this->mFrom
= $reloadFrom;
1540 * Combine the language default options with any site-specific options
1541 * and add the default language variants.
1543 * @return array Array of String options
1545 public static function getDefaultOptions() {
1546 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1548 static $defOpt = null;
1549 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1550 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1551 // mid-request and see that change reflected in the return value of this function.
1552 // Which is insane and would never happen during normal MW operation
1556 $defOpt = $wgDefaultUserOptions;
1557 // Default language setting
1558 $defOpt['language'] = $wgContLang->getCode();
1559 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1560 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1562 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1563 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1565 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1567 Hooks
::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1573 * Get a given default option value.
1575 * @param string $opt Name of option to retrieve
1576 * @return string Default option value
1578 public static function getDefaultOption( $opt ) {
1579 $defOpts = self
::getDefaultOptions();
1580 if ( isset( $defOpts[$opt] ) ) {
1581 return $defOpts[$opt];
1588 * Get blocking information
1589 * @param bool $bFromSlave Whether to check the slave database first.
1590 * To improve performance, non-critical checks are done against slaves.
1591 * Check when actually saving should be done against master.
1593 private function getBlockedStatus( $bFromSlave = true ) {
1594 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1596 if ( -1 != $this->mBlockedby
) {
1600 wfDebug( __METHOD__
. ": checking...\n" );
1602 // Initialize data...
1603 // Otherwise something ends up stomping on $this->mBlockedby when
1604 // things get lazy-loaded later, causing false positive block hits
1605 // due to -1 !== 0. Probably session-related... Nothing should be
1606 // overwriting mBlockedby, surely?
1609 # We only need to worry about passing the IP address to the Block generator if the
1610 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1611 # know which IP address they're actually coming from
1612 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1613 $ip = $this->getRequest()->getIP();
1619 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1622 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1623 && !in_array( $ip, $wgProxyWhitelist )
1626 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1628 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1629 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1630 $block->setTarget( $ip );
1631 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1633 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1634 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1635 $block->setTarget( $ip );
1639 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1640 if ( !$block instanceof Block
1641 && $wgApplyIpBlocksToXff
1643 && !$this->isAllowed( 'proxyunbannable' )
1644 && !in_array( $ip, $wgProxyWhitelist )
1646 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1647 $xff = array_map( 'trim', explode( ',', $xff ) );
1648 $xff = array_diff( $xff, array( $ip ) );
1649 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1650 $block = Block
::chooseBlock( $xffblocks, $xff );
1651 if ( $block instanceof Block
) {
1652 # Mangle the reason to alert the user that the block
1653 # originated from matching the X-Forwarded-For header.
1654 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1658 if ( $block instanceof Block
) {
1659 wfDebug( __METHOD__
. ": Found block.\n" );
1660 $this->mBlock
= $block;
1661 $this->mBlockedby
= $block->getByName();
1662 $this->mBlockreason
= $block->mReason
;
1663 $this->mHideName
= $block->mHideName
;
1664 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1666 $this->mBlockedby
= '';
1667 $this->mHideName
= 0;
1668 $this->mAllowUsertalk
= false;
1672 Hooks
::run( 'GetBlockedStatus', array( &$this ) );
1677 * Whether the given IP is in a DNS blacklist.
1679 * @param string $ip IP to check
1680 * @param bool $checkWhitelist Whether to check the whitelist first
1681 * @return bool True if blacklisted.
1683 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1684 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1686 if ( !$wgEnableDnsBlacklist ) {
1690 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1694 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1698 * Whether the given IP is in a given DNS blacklist.
1700 * @param string $ip IP to check
1701 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1702 * @return bool True if blacklisted.
1704 public function inDnsBlacklist( $ip, $bases ) {
1707 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1708 if ( IP
::isIPv4( $ip ) ) {
1709 // Reverse IP, bug 21255
1710 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1712 foreach ( (array)$bases as $base ) {
1714 // If we have an access key, use that too (ProjectHoneypot, etc.)
1715 if ( is_array( $base ) ) {
1716 if ( count( $base ) >= 2 ) {
1717 // Access key is 1, base URL is 0
1718 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1720 $host = "$ipReversed.{$base[0]}";
1723 $host = "$ipReversed.$base";
1727 $ipList = gethostbynamel( $host );
1730 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1734 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1743 * Check if an IP address is in the local proxy list
1749 public static function isLocallyBlockedProxy( $ip ) {
1750 global $wgProxyList;
1752 if ( !$wgProxyList ) {
1756 if ( !is_array( $wgProxyList ) ) {
1757 // Load from the specified file
1758 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1761 if ( !is_array( $wgProxyList ) ) {
1763 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1765 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1766 // Old-style flipped proxy list
1775 * Is this user subject to rate limiting?
1777 * @return bool True if rate limited
1779 public function isPingLimitable() {
1780 global $wgRateLimitsExcludedIPs;
1781 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1782 // No other good way currently to disable rate limits
1783 // for specific IPs. :P
1784 // But this is a crappy hack and should die.
1787 return !$this->isAllowed( 'noratelimit' );
1791 * Primitive rate limits: enforce maximum actions per time period
1792 * to put a brake on flooding.
1794 * The method generates both a generic profiling point and a per action one
1795 * (suffix being "-$action".
1797 * @note When using a shared cache like memcached, IP-address
1798 * last-hit counters will be shared across wikis.
1800 * @param string $action Action to enforce; 'edit' if unspecified
1801 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1802 * @return bool True if a rate limiter was tripped
1804 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1805 // Call the 'PingLimiter' hook
1807 if ( !Hooks
::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1811 global $wgRateLimits;
1812 if ( !isset( $wgRateLimits[$action] ) ) {
1816 // Some groups shouldn't trigger the ping limiter, ever
1817 if ( !$this->isPingLimitable() ) {
1823 $limits = $wgRateLimits[$action];
1825 $id = $this->getId();
1828 if ( isset( $limits['anon'] ) && $id == 0 ) {
1829 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1832 if ( isset( $limits['user'] ) && $id != 0 ) {
1833 $userLimit = $limits['user'];
1835 if ( $this->isNewbie() ) {
1836 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1837 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1839 if ( isset( $limits['ip'] ) ) {
1840 $ip = $this->getRequest()->getIP();
1841 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1843 if ( isset( $limits['subnet'] ) ) {
1844 $ip = $this->getRequest()->getIP();
1847 if ( IP
::isIPv6( $ip ) ) {
1848 $parts = IP
::parseRange( "$ip/64" );
1849 $subnet = $parts[0];
1850 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1852 $subnet = $matches[1];
1854 if ( $subnet !== false ) {
1855 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1859 // Check for group-specific permissions
1860 // If more than one group applies, use the group with the highest limit
1861 foreach ( $this->getGroups() as $group ) {
1862 if ( isset( $limits[$group] ) ) {
1863 if ( $userLimit === false
1864 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1866 $userLimit = $limits[$group];
1870 // Set the user limit key
1871 if ( $userLimit !== false ) {
1872 list( $max, $period ) = $userLimit;
1873 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1874 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1878 foreach ( $keys as $key => $limit ) {
1879 list( $max, $period ) = $limit;
1880 $summary = "(limit $max in {$period}s)";
1881 $count = $wgMemc->get( $key );
1884 if ( $count >= $max ) {
1885 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1886 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1889 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1892 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1893 if ( $incrBy > 0 ) {
1894 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1897 if ( $incrBy > 0 ) {
1898 $wgMemc->incr( $key, $incrBy );
1906 * Check if user is blocked
1908 * @param bool $bFromSlave Whether to check the slave database instead of
1909 * the master. Hacked from false due to horrible probs on site.
1910 * @return bool True if blocked, false otherwise
1912 public function isBlocked( $bFromSlave = true ) {
1913 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1917 * Get the block affecting the user, or null if the user is not blocked
1919 * @param bool $bFromSlave Whether to check the slave database instead of the master
1920 * @return Block|null
1922 public function getBlock( $bFromSlave = true ) {
1923 $this->getBlockedStatus( $bFromSlave );
1924 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1928 * Check if user is blocked from editing a particular article
1930 * @param Title $title Title to check
1931 * @param bool $bFromSlave Whether to check the slave database instead of the master
1934 public function isBlockedFrom( $title, $bFromSlave = false ) {
1935 global $wgBlockAllowsUTEdit;
1937 $blocked = $this->isBlocked( $bFromSlave );
1938 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1939 // If a user's name is suppressed, they cannot make edits anywhere
1940 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1941 && $title->getNamespace() == NS_USER_TALK
) {
1943 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1946 Hooks
::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1952 * If user is blocked, return the name of the user who placed the block
1953 * @return string Name of blocker
1955 public function blockedBy() {
1956 $this->getBlockedStatus();
1957 return $this->mBlockedby
;
1961 * If user is blocked, return the specified reason for the block
1962 * @return string Blocking reason
1964 public function blockedFor() {
1965 $this->getBlockedStatus();
1966 return $this->mBlockreason
;
1970 * If user is blocked, return the ID for the block
1971 * @return int Block ID
1973 public function getBlockId() {
1974 $this->getBlockedStatus();
1975 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1979 * Check if user is blocked on all wikis.
1980 * Do not use for actual edit permission checks!
1981 * This is intended for quick UI checks.
1983 * @param string $ip IP address, uses current client if none given
1984 * @return bool True if blocked, false otherwise
1986 public function isBlockedGlobally( $ip = '' ) {
1987 if ( $this->mBlockedGlobally
!== null ) {
1988 return $this->mBlockedGlobally
;
1990 // User is already an IP?
1991 if ( IP
::isIPAddress( $this->getName() ) ) {
1992 $ip = $this->getName();
1994 $ip = $this->getRequest()->getIP();
1997 Hooks
::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1998 $this->mBlockedGlobally
= (bool)$blocked;
1999 return $this->mBlockedGlobally
;
2003 * Check if user account is locked
2005 * @return bool True if locked, false otherwise
2007 public function isLocked() {
2008 if ( $this->mLocked
!== null ) {
2009 return $this->mLocked
;
2012 $authUser = $wgAuth->getUserInstance( $this );
2013 $this->mLocked
= (bool)$authUser->isLocked();
2014 return $this->mLocked
;
2018 * Check if user account is hidden
2020 * @return bool True if hidden, false otherwise
2022 public function isHidden() {
2023 if ( $this->mHideName
!== null ) {
2024 return $this->mHideName
;
2026 $this->getBlockedStatus();
2027 if ( !$this->mHideName
) {
2029 $authUser = $wgAuth->getUserInstance( $this );
2030 $this->mHideName
= (bool)$authUser->isHidden();
2032 return $this->mHideName
;
2036 * Get the user's ID.
2037 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2039 public function getId() {
2040 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2041 // Special case, we know the user is anonymous
2043 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2044 // Don't load if this was initialized from an ID
2051 * Set the user and reload all fields according to a given ID
2052 * @param int $v User ID to reload
2054 public function setId( $v ) {
2056 $this->clearInstanceCache( 'id' );
2060 * Get the user name, or the IP of an anonymous user
2061 * @return string User's name or IP address
2063 public function getName() {
2064 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2065 // Special case optimisation
2066 return $this->mName
;
2069 if ( $this->mName
=== false ) {
2071 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2073 return $this->mName
;
2078 * Set the user name.
2080 * This does not reload fields from the database according to the given
2081 * name. Rather, it is used to create a temporary "nonexistent user" for
2082 * later addition to the database. It can also be used to set the IP
2083 * address for an anonymous user to something other than the current
2086 * @note User::newFromName() has roughly the same function, when the named user
2088 * @param string $str New user name to set
2090 public function setName( $str ) {
2092 $this->mName
= $str;
2096 * Get the user's name escaped by underscores.
2097 * @return string Username escaped by underscores.
2099 public function getTitleKey() {
2100 return str_replace( ' ', '_', $this->getName() );
2104 * Check if the user has new messages.
2105 * @return bool True if the user has new messages
2107 public function getNewtalk() {
2110 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2111 if ( $this->mNewtalk
=== -1 ) {
2112 $this->mNewtalk
= false; # reset talk page status
2114 // Check memcached separately for anons, who have no
2115 // entire User object stored in there.
2116 if ( !$this->mId
) {
2117 global $wgDisableAnonTalk;
2118 if ( $wgDisableAnonTalk ) {
2119 // Anon newtalk disabled by configuration.
2120 $this->mNewtalk
= false;
2122 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2125 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2129 return (bool)$this->mNewtalk
;
2133 * Return the data needed to construct links for new talk page message
2134 * alerts. If there are new messages, this will return an associative array
2135 * with the following data:
2136 * wiki: The database name of the wiki
2137 * link: Root-relative link to the user's talk page
2138 * rev: The last talk page revision that the user has seen or null. This
2139 * is useful for building diff links.
2140 * If there are no new messages, it returns an empty array.
2141 * @note This function was designed to accomodate multiple talk pages, but
2142 * currently only returns a single link and revision.
2145 public function getNewMessageLinks() {
2147 if ( !Hooks
::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2149 } elseif ( !$this->getNewtalk() ) {
2152 $utp = $this->getTalkPage();
2153 $dbr = wfGetDB( DB_SLAVE
);
2154 // Get the "last viewed rev" timestamp from the oldest message notification
2155 $timestamp = $dbr->selectField( 'user_newtalk',
2156 'MIN(user_last_timestamp)',
2157 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2159 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2160 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2164 * Get the revision ID for the last talk page revision viewed by the talk
2166 * @return int|null Revision ID or null
2168 public function getNewMessageRevisionId() {
2169 $newMessageRevisionId = null;
2170 $newMessageLinks = $this->getNewMessageLinks();
2171 if ( $newMessageLinks ) {
2172 // Note: getNewMessageLinks() never returns more than a single link
2173 // and it is always for the same wiki, but we double-check here in
2174 // case that changes some time in the future.
2175 if ( count( $newMessageLinks ) === 1
2176 && $newMessageLinks[0]['wiki'] === wfWikiID()
2177 && $newMessageLinks[0]['rev']
2179 $newMessageRevision = $newMessageLinks[0]['rev'];
2180 $newMessageRevisionId = $newMessageRevision->getId();
2183 return $newMessageRevisionId;
2187 * Internal uncached check for new messages
2190 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2191 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2192 * @return bool True if the user has new messages
2194 protected function checkNewtalk( $field, $id ) {
2195 $dbr = wfGetDB( DB_SLAVE
);
2197 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__
);
2199 return $ok !== false;
2203 * Add or update the new messages flag
2204 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2205 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2206 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2207 * @return bool True if successful, false otherwise
2209 protected function updateNewtalk( $field, $id, $curRev = null ) {
2210 // Get timestamp of the talk page revision prior to the current one
2211 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2212 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2213 // Mark the user as having new messages since this revision
2214 $dbw = wfGetDB( DB_MASTER
);
2215 $dbw->insert( 'user_newtalk',
2216 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2219 if ( $dbw->affectedRows() ) {
2220 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2223 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2229 * Clear the new messages flag for the given user
2230 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2231 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2232 * @return bool True if successful, false otherwise
2234 protected function deleteNewtalk( $field, $id ) {
2235 $dbw = wfGetDB( DB_MASTER
);
2236 $dbw->delete( 'user_newtalk',
2237 array( $field => $id ),
2239 if ( $dbw->affectedRows() ) {
2240 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2243 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2249 * Update the 'You have new messages!' status.
2250 * @param bool $val Whether the user has new messages
2251 * @param Revision $curRev New, as yet unseen revision of the user talk
2252 * page. Ignored if null or !$val.
2254 public function setNewtalk( $val, $curRev = null ) {
2255 if ( wfReadOnly() ) {
2260 $this->mNewtalk
= $val;
2262 if ( $this->isAnon() ) {
2264 $id = $this->getName();
2267 $id = $this->getId();
2271 $changed = $this->updateNewtalk( $field, $id, $curRev );
2273 $changed = $this->deleteNewtalk( $field, $id );
2277 $this->invalidateCache();
2282 * Generate a current or new-future timestamp to be stored in the
2283 * user_touched field when we update things.
2284 * @return string Timestamp in TS_MW format
2286 private function newTouchedTimestamp() {
2287 global $wgClockSkewFudge;
2289 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2290 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2291 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2298 * Clear user data from memcached.
2299 * Use after applying fun updates to the database; caller's
2300 * responsibility to update user_touched if appropriate.
2302 * Called implicitly from invalidateCache() and saveSettings().
2304 public function clearSharedCache() {
2309 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
2314 * Immediately touch the user data cache for this account
2316 * Calls touch() and removes account data from memcached
2318 public function invalidateCache() {
2320 $this->clearSharedCache();
2324 * Update the "touched" timestamp for the user
2326 * This is useful on various login/logout events when making sure that
2327 * a browser or proxy that has multiple tenants does not suffer cache
2328 * pollution where the new user sees the old users content. The value
2329 * of getTouched() is checked when determining 304 vs 200 responses.
2330 * Unlike invalidateCache(), this preserves the User object cache and
2331 * avoids database writes.
2335 public function touch() {
2341 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2342 $timestamp = $this->newTouchedTimestamp();
2343 $wgMemc->set( $key, $timestamp );
2344 $this->mQuickTouched
= $timestamp;
2349 * Validate the cache for this account.
2350 * @param string $timestamp A timestamp in TS_MW format
2353 public function validateCache( $timestamp ) {
2354 return ( $timestamp >= $this->getTouched() );
2358 * Get the user touched timestamp
2359 * @return string TS_MW Timestamp
2361 public function getTouched() {
2367 if ( $this->mQuickTouched
=== null ) {
2368 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2369 $timestamp = $wgMemc->get( $key );
2371 $this->mQuickTouched
= $timestamp;
2373 # Set the timestamp to get HTTP 304 cache hits
2378 return max( $this->mTouched
, $this->mQuickTouched
);
2381 return $this->mTouched
;
2385 * Get the user_touched timestamp field (time of last DB updates)
2386 * @return string TS_MW Timestamp
2389 protected function getDBTouched() {
2392 return $this->mTouched
;
2399 public function getPassword() {
2400 $this->loadPasswords();
2402 return $this->mPassword
;
2409 public function getTemporaryPassword() {
2410 $this->loadPasswords();
2412 return $this->mNewpassword
;
2416 * Set the password and reset the random token.
2417 * Calls through to authentication plugin if necessary;
2418 * will have no effect if the auth plugin refuses to
2419 * pass the change through or if the legal password
2422 * As a special case, setting the password to null
2423 * wipes it, so the account cannot be logged in until
2424 * a new password is set, for instance via e-mail.
2426 * @param string $str New password to set
2427 * @throws PasswordError On failure
2431 public function setPassword( $str ) {
2434 $this->loadPasswords();
2436 if ( $str !== null ) {
2437 if ( !$wgAuth->allowPasswordChange() ) {
2438 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2441 $status = $this->checkPasswordValidity( $str );
2442 if ( !$status->isGood() ) {
2443 throw new PasswordError( $status->getMessage()->text() );
2447 if ( !$wgAuth->setPassword( $this, $str ) ) {
2448 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2451 $this->setInternalPassword( $str );
2457 * Set the password and reset the random token unconditionally.
2459 * @param string|null $str New password to set or null to set an invalid
2460 * password hash meaning that the user will not be able to log in
2461 * through the web interface.
2463 public function setInternalPassword( $str ) {
2466 $passwordFactory = self
::getPasswordFactory();
2467 $this->mPassword
= $passwordFactory->newFromPlaintext( $str );
2469 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
2470 $this->mNewpassTime
= null;
2474 * Get the user's current token.
2475 * @param bool $forceCreation Force the generation of a new token if the
2476 * user doesn't have one (default=true for backwards compatibility).
2477 * @return string Token
2479 public function getToken( $forceCreation = true ) {
2481 if ( !$this->mToken
&& $forceCreation ) {
2484 return $this->mToken
;
2488 * Set the random token (used for persistent authentication)
2489 * Called from loadDefaults() among other places.
2491 * @param string|bool $token If specified, set the token to this value
2493 public function setToken( $token = false ) {
2496 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2498 $this->mToken
= $token;
2503 * Set the password for a password reminder or new account email
2505 * @param string $str New password to set or null to set an invalid
2506 * password hash meaning that the user will not be able to use it
2507 * @param bool $throttle If true, reset the throttle timestamp to the present
2509 public function setNewpassword( $str, $throttle = true ) {
2510 $this->loadPasswords();
2512 $this->mNewpassword
= self
::getPasswordFactory()->newFromPlaintext( $str );
2513 if ( $str === null ) {
2514 $this->mNewpassTime
= null;
2515 } elseif ( $throttle ) {
2516 $this->mNewpassTime
= wfTimestampNow();
2521 * Has password reminder email been sent within the last
2522 * $wgPasswordReminderResendTime hours?
2525 public function isPasswordReminderThrottled() {
2526 global $wgPasswordReminderResendTime;
2528 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2531 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2532 return time() < $expiry;
2536 * Get the user's e-mail address
2537 * @return string User's email address
2539 public function getEmail() {
2541 Hooks
::run( 'UserGetEmail', array( $this, &$this->mEmail
) );
2542 return $this->mEmail
;
2546 * Get the timestamp of the user's e-mail authentication
2547 * @return string TS_MW timestamp
2549 public function getEmailAuthenticationTimestamp() {
2551 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2552 return $this->mEmailAuthenticated
;
2556 * Set the user's e-mail address
2557 * @param string $str New e-mail address
2559 public function setEmail( $str ) {
2561 if ( $str == $this->mEmail
) {
2564 $this->invalidateEmail();
2565 $this->mEmail
= $str;
2566 Hooks
::run( 'UserSetEmail', array( $this, &$this->mEmail
) );
2570 * Set the user's e-mail address and a confirmation mail if needed.
2573 * @param string $str New e-mail address
2576 public function setEmailWithConfirmation( $str ) {
2577 global $wgEnableEmail, $wgEmailAuthentication;
2579 if ( !$wgEnableEmail ) {
2580 return Status
::newFatal( 'emaildisabled' );
2583 $oldaddr = $this->getEmail();
2584 if ( $str === $oldaddr ) {
2585 return Status
::newGood( true );
2588 $this->setEmail( $str );
2590 if ( $str !== '' && $wgEmailAuthentication ) {
2591 // Send a confirmation request to the new address if needed
2592 $type = $oldaddr != '' ?
'changed' : 'set';
2593 $result = $this->sendConfirmationMail( $type );
2594 if ( $result->isGood() ) {
2595 // Say to the caller that a confirmation mail has been sent
2596 $result->value
= 'eauth';
2599 $result = Status
::newGood( true );
2606 * Get the user's real name
2607 * @return string User's real name
2609 public function getRealName() {
2610 if ( !$this->isItemLoaded( 'realname' ) ) {
2614 return $this->mRealName
;
2618 * Set the user's real name
2619 * @param string $str New real name
2621 public function setRealName( $str ) {
2623 $this->mRealName
= $str;
2627 * Get the user's current setting for a given option.
2629 * @param string $oname The option to check
2630 * @param string $defaultOverride A default value returned if the option does not exist
2631 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2632 * @return string User's current value for the option
2633 * @see getBoolOption()
2634 * @see getIntOption()
2636 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2637 global $wgHiddenPrefs;
2638 $this->loadOptions();
2640 # We want 'disabled' preferences to always behave as the default value for
2641 # users, even if they have set the option explicitly in their settings (ie they
2642 # set it, and then it was disabled removing their ability to change it). But
2643 # we don't want to erase the preferences in the database in case the preference
2644 # is re-enabled again. So don't touch $mOptions, just override the returned value
2645 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2646 return self
::getDefaultOption( $oname );
2649 if ( array_key_exists( $oname, $this->mOptions
) ) {
2650 return $this->mOptions
[$oname];
2652 return $defaultOverride;
2657 * Get all user's options
2659 * @param int $flags Bitwise combination of:
2660 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2661 * to the default value. (Since 1.25)
2664 public function getOptions( $flags = 0 ) {
2665 global $wgHiddenPrefs;
2666 $this->loadOptions();
2667 $options = $this->mOptions
;
2669 # We want 'disabled' preferences to always behave as the default value for
2670 # users, even if they have set the option explicitly in their settings (ie they
2671 # set it, and then it was disabled removing their ability to change it). But
2672 # we don't want to erase the preferences in the database in case the preference
2673 # is re-enabled again. So don't touch $mOptions, just override the returned value
2674 foreach ( $wgHiddenPrefs as $pref ) {
2675 $default = self
::getDefaultOption( $pref );
2676 if ( $default !== null ) {
2677 $options[$pref] = $default;
2681 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2682 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2689 * Get the user's current setting for a given option, as a boolean value.
2691 * @param string $oname The option to check
2692 * @return bool User's current value for the option
2695 public function getBoolOption( $oname ) {
2696 return (bool)$this->getOption( $oname );
2700 * Get the user's current setting for a given option, as an integer value.
2702 * @param string $oname The option to check
2703 * @param int $defaultOverride A default value returned if the option does not exist
2704 * @return int User's current value for the option
2707 public function getIntOption( $oname, $defaultOverride = 0 ) {
2708 $val = $this->getOption( $oname );
2710 $val = $defaultOverride;
2712 return intval( $val );
2716 * Set the given option for a user.
2718 * You need to call saveSettings() to actually write to the database.
2720 * @param string $oname The option to set
2721 * @param mixed $val New value to set
2723 public function setOption( $oname, $val ) {
2724 $this->loadOptions();
2726 // Explicitly NULL values should refer to defaults
2727 if ( is_null( $val ) ) {
2728 $val = self
::getDefaultOption( $oname );
2731 $this->mOptions
[$oname] = $val;
2735 * Get a token stored in the preferences (like the watchlist one),
2736 * resetting it if it's empty (and saving changes).
2738 * @param string $oname The option name to retrieve the token from
2739 * @return string|bool User's current value for the option, or false if this option is disabled.
2740 * @see resetTokenFromOption()
2743 public function getTokenFromOption( $oname ) {
2744 global $wgHiddenPrefs;
2745 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2749 $token = $this->getOption( $oname );
2751 $token = $this->resetTokenFromOption( $oname );
2752 if ( !wfReadOnly() ) {
2753 $this->saveSettings();
2760 * Reset a token stored in the preferences (like the watchlist one).
2761 * *Does not* save user's preferences (similarly to setOption()).
2763 * @param string $oname The option name to reset the token in
2764 * @return string|bool New token value, or false if this option is disabled.
2765 * @see getTokenFromOption()
2768 public function resetTokenFromOption( $oname ) {
2769 global $wgHiddenPrefs;
2770 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2774 $token = MWCryptRand
::generateHex( 40 );
2775 $this->setOption( $oname, $token );
2780 * Return a list of the types of user options currently returned by
2781 * User::getOptionKinds().
2783 * Currently, the option kinds are:
2784 * - 'registered' - preferences which are registered in core MediaWiki or
2785 * by extensions using the UserGetDefaultOptions hook.
2786 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2787 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2788 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2789 * be used by user scripts.
2790 * - 'special' - "preferences" that are not accessible via User::getOptions
2791 * or User::setOptions.
2792 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2793 * These are usually legacy options, removed in newer versions.
2795 * The API (and possibly others) use this function to determine the possible
2796 * option types for validation purposes, so make sure to update this when a
2797 * new option kind is added.
2799 * @see User::getOptionKinds
2800 * @return array Option kinds
2802 public static function listOptionKinds() {
2805 'registered-multiselect',
2806 'registered-checkmatrix',
2814 * Return an associative array mapping preferences keys to the kind of a preference they're
2815 * used for. Different kinds are handled differently when setting or reading preferences.
2817 * See User::listOptionKinds for the list of valid option types that can be provided.
2819 * @see User::listOptionKinds
2820 * @param IContextSource $context
2821 * @param array $options Assoc. array with options keys to check as keys.
2822 * Defaults to $this->mOptions.
2823 * @return array The key => kind mapping data
2825 public function getOptionKinds( IContextSource
$context, $options = null ) {
2826 $this->loadOptions();
2827 if ( $options === null ) {
2828 $options = $this->mOptions
;
2831 $prefs = Preferences
::getPreferences( $this, $context );
2834 // Pull out the "special" options, so they don't get converted as
2835 // multiselect or checkmatrix.
2836 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2837 foreach ( $specialOptions as $name => $value ) {
2838 unset( $prefs[$name] );
2841 // Multiselect and checkmatrix options are stored in the database with
2842 // one key per option, each having a boolean value. Extract those keys.
2843 $multiselectOptions = array();
2844 foreach ( $prefs as $name => $info ) {
2845 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2846 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2847 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2848 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2850 foreach ( $opts as $value ) {
2851 $multiselectOptions["$prefix$value"] = true;
2854 unset( $prefs[$name] );
2857 $checkmatrixOptions = array();
2858 foreach ( $prefs as $name => $info ) {
2859 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2860 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2861 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2862 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2863 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2865 foreach ( $columns as $column ) {
2866 foreach ( $rows as $row ) {
2867 $checkmatrixOptions["$prefix$column-$row"] = true;
2871 unset( $prefs[$name] );
2875 // $value is ignored
2876 foreach ( $options as $key => $value ) {
2877 if ( isset( $prefs[$key] ) ) {
2878 $mapping[$key] = 'registered';
2879 } elseif ( isset( $multiselectOptions[$key] ) ) {
2880 $mapping[$key] = 'registered-multiselect';
2881 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2882 $mapping[$key] = 'registered-checkmatrix';
2883 } elseif ( isset( $specialOptions[$key] ) ) {
2884 $mapping[$key] = 'special';
2885 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2886 $mapping[$key] = 'userjs';
2888 $mapping[$key] = 'unused';
2896 * Reset certain (or all) options to the site defaults
2898 * The optional parameter determines which kinds of preferences will be reset.
2899 * Supported values are everything that can be reported by getOptionKinds()
2900 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2902 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2903 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2904 * for backwards-compatibility.
2905 * @param IContextSource|null $context Context source used when $resetKinds
2906 * does not contain 'all', passed to getOptionKinds().
2907 * Defaults to RequestContext::getMain() when null.
2909 public function resetOptions(
2910 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2911 IContextSource
$context = null
2914 $defaultOptions = self
::getDefaultOptions();
2916 if ( !is_array( $resetKinds ) ) {
2917 $resetKinds = array( $resetKinds );
2920 if ( in_array( 'all', $resetKinds ) ) {
2921 $newOptions = $defaultOptions;
2923 if ( $context === null ) {
2924 $context = RequestContext
::getMain();
2927 $optionKinds = $this->getOptionKinds( $context );
2928 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2929 $newOptions = array();
2931 // Use default values for the options that should be deleted, and
2932 // copy old values for the ones that shouldn't.
2933 foreach ( $this->mOptions
as $key => $value ) {
2934 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2935 if ( array_key_exists( $key, $defaultOptions ) ) {
2936 $newOptions[$key] = $defaultOptions[$key];
2939 $newOptions[$key] = $value;
2944 Hooks
::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2946 $this->mOptions
= $newOptions;
2947 $this->mOptionsLoaded
= true;
2951 * Get the user's preferred date format.
2952 * @return string User's preferred date format
2954 public function getDatePreference() {
2955 // Important migration for old data rows
2956 if ( is_null( $this->mDatePreference
) ) {
2958 $value = $this->getOption( 'date' );
2959 $map = $wgLang->getDatePreferenceMigrationMap();
2960 if ( isset( $map[$value] ) ) {
2961 $value = $map[$value];
2963 $this->mDatePreference
= $value;
2965 return $this->mDatePreference
;
2969 * Determine based on the wiki configuration and the user's options,
2970 * whether this user must be over HTTPS no matter what.
2974 public function requiresHTTPS() {
2975 global $wgSecureLogin;
2976 if ( !$wgSecureLogin ) {
2979 $https = $this->getBoolOption( 'prefershttps' );
2980 Hooks
::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2982 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2989 * Get the user preferred stub threshold
2993 public function getStubThreshold() {
2994 global $wgMaxArticleSize; # Maximum article size, in Kb
2995 $threshold = $this->getIntOption( 'stubthreshold' );
2996 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2997 // If they have set an impossible value, disable the preference
2998 // so we can use the parser cache again.
3005 * Get the permissions this user has.
3006 * @return array Array of String permission names
3008 public function getRights() {
3009 if ( is_null( $this->mRights
) ) {
3010 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3011 Hooks
::run( 'UserGetRights', array( $this, &$this->mRights
) );
3012 // Force reindexation of rights when a hook has unset one of them
3013 $this->mRights
= array_values( array_unique( $this->mRights
) );
3015 return $this->mRights
;
3019 * Get the list of explicit group memberships this user has.
3020 * The implicit * and user groups are not included.
3021 * @return array Array of String internal group names
3023 public function getGroups() {
3025 $this->loadGroups();
3026 return $this->mGroups
;
3030 * Get the list of implicit group memberships this user has.
3031 * This includes all explicit groups, plus 'user' if logged in,
3032 * '*' for all accounts, and autopromoted groups
3033 * @param bool $recache Whether to avoid the cache
3034 * @return array Array of String internal group names
3036 public function getEffectiveGroups( $recache = false ) {
3037 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3038 $this->mEffectiveGroups
= array_unique( array_merge(
3039 $this->getGroups(), // explicit groups
3040 $this->getAutomaticGroups( $recache ) // implicit groups
3042 // Hook for additional groups
3043 Hooks
::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
3044 // Force reindexation of groups when a hook has unset one of them
3045 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3047 return $this->mEffectiveGroups
;
3051 * Get the list of implicit group memberships this user has.
3052 * This includes 'user' if logged in, '*' for all accounts,
3053 * and autopromoted groups
3054 * @param bool $recache Whether to avoid the cache
3055 * @return array Array of String internal group names
3057 public function getAutomaticGroups( $recache = false ) {
3058 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3059 $this->mImplicitGroups
= array( '*' );
3060 if ( $this->getId() ) {
3061 $this->mImplicitGroups
[] = 'user';
3063 $this->mImplicitGroups
= array_unique( array_merge(
3064 $this->mImplicitGroups
,
3065 Autopromote
::getAutopromoteGroups( $this )
3069 // Assure data consistency with rights/groups,
3070 // as getEffectiveGroups() depends on this function
3071 $this->mEffectiveGroups
= null;
3074 return $this->mImplicitGroups
;
3078 * Returns the groups the user has belonged to.
3080 * The user may still belong to the returned groups. Compare with getGroups().
3082 * The function will not return groups the user had belonged to before MW 1.17
3084 * @return array Names of the groups the user has belonged to.
3086 public function getFormerGroups() {
3089 if ( is_null( $this->mFormerGroups
) ) {
3090 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3091 ?
wfGetDB( DB_MASTER
)
3092 : wfGetDB( DB_SLAVE
);
3093 $res = $db->select( 'user_former_groups',
3094 array( 'ufg_group' ),
3095 array( 'ufg_user' => $this->mId
),
3097 $this->mFormerGroups
= array();
3098 foreach ( $res as $row ) {
3099 $this->mFormerGroups
[] = $row->ufg_group
;
3103 return $this->mFormerGroups
;
3107 * Get the user's edit count.
3108 * @return int|null Null for anonymous users
3110 public function getEditCount() {
3111 if ( !$this->getId() ) {
3115 if ( $this->mEditCount
=== null ) {
3116 /* Populate the count, if it has not been populated yet */
3117 $dbr = wfGetDB( DB_SLAVE
);
3118 // check if the user_editcount field has been initialized
3119 $count = $dbr->selectField(
3120 'user', 'user_editcount',
3121 array( 'user_id' => $this->mId
),
3125 if ( $count === null ) {
3126 // it has not been initialized. do so.
3127 $count = $this->initEditCount();
3129 $this->mEditCount
= $count;
3131 return (int)$this->mEditCount
;
3135 * Add the user to the given group.
3136 * This takes immediate effect.
3137 * @param string $group Name of the group to add
3140 public function addGroup( $group ) {
3143 if ( !Hooks
::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3147 $dbw = wfGetDB( DB_MASTER
);
3148 if ( $this->getId() ) {
3149 $dbw->insert( 'user_groups',
3151 'ug_user' => $this->getID(),
3152 'ug_group' => $group,
3155 array( 'IGNORE' ) );
3158 $this->loadGroups();
3159 $this->mGroups
[] = $group;
3160 // In case loadGroups was not called before, we now have the right twice.
3161 // Get rid of the duplicate.
3162 $this->mGroups
= array_unique( $this->mGroups
);
3164 // Refresh the groups caches, and clear the rights cache so it will be
3165 // refreshed on the next call to $this->getRights().
3166 $this->getEffectiveGroups( true );
3167 $this->mRights
= null;
3169 $this->invalidateCache();
3175 * Remove the user from the given group.
3176 * This takes immediate effect.
3177 * @param string $group Name of the group to remove
3180 public function removeGroup( $group ) {
3182 if ( !Hooks
::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3186 $dbw = wfGetDB( DB_MASTER
);
3187 $dbw->delete( 'user_groups',
3189 'ug_user' => $this->getID(),
3190 'ug_group' => $group,
3193 // Remember that the user was in this group
3194 $dbw->insert( 'user_former_groups',
3196 'ufg_user' => $this->getID(),
3197 'ufg_group' => $group,
3203 $this->loadGroups();
3204 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3206 // Refresh the groups caches, and clear the rights cache so it will be
3207 // refreshed on the next call to $this->getRights().
3208 $this->getEffectiveGroups( true );
3209 $this->mRights
= null;
3211 $this->invalidateCache();
3217 * Get whether the user is logged in
3220 public function isLoggedIn() {
3221 return $this->getID() != 0;
3225 * Get whether the user is anonymous
3228 public function isAnon() {
3229 return !$this->isLoggedIn();
3233 * Check if user is allowed to access a feature / make an action
3235 * @param string $permissions,... Permissions to test
3236 * @return bool True if user is allowed to perform *any* of the given actions
3238 public function isAllowedAny( /*...*/ ) {
3239 $permissions = func_get_args();
3240 foreach ( $permissions as $permission ) {
3241 if ( $this->isAllowed( $permission ) ) {
3250 * @param string $permissions,... Permissions to test
3251 * @return bool True if the user is allowed to perform *all* of the given actions
3253 public function isAllowedAll( /*...*/ ) {
3254 $permissions = func_get_args();
3255 foreach ( $permissions as $permission ) {
3256 if ( !$this->isAllowed( $permission ) ) {
3264 * Internal mechanics of testing a permission
3265 * @param string $action
3268 public function isAllowed( $action = '' ) {
3269 if ( $action === '' ) {
3270 return true; // In the spirit of DWIM
3272 // Patrolling may not be enabled
3273 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3274 global $wgUseRCPatrol, $wgUseNPPatrol;
3275 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3279 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3280 // by misconfiguration: 0 == 'foo'
3281 return in_array( $action, $this->getRights(), true );
3285 * Check whether to enable recent changes patrol features for this user
3286 * @return bool True or false
3288 public function useRCPatrol() {
3289 global $wgUseRCPatrol;
3290 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3294 * Check whether to enable new pages patrol features for this user
3295 * @return bool True or false
3297 public function useNPPatrol() {
3298 global $wgUseRCPatrol, $wgUseNPPatrol;
3300 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3301 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3306 * Get the WebRequest object to use with this object
3308 * @return WebRequest
3310 public function getRequest() {
3311 if ( $this->mRequest
) {
3312 return $this->mRequest
;
3320 * Get the current skin, loading it if required
3321 * @return Skin The current skin
3322 * @todo FIXME: Need to check the old failback system [AV]
3323 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3325 public function getSkin() {
3326 wfDeprecated( __METHOD__
, '1.18' );
3327 return RequestContext
::getMain()->getSkin();
3331 * Get a WatchedItem for this user and $title.
3333 * @since 1.22 $checkRights parameter added
3334 * @param Title $title
3335 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3336 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3337 * @return WatchedItem
3339 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3340 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3342 if ( isset( $this->mWatchedItems
[$key] ) ) {
3343 return $this->mWatchedItems
[$key];
3346 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3347 $this->mWatchedItems
= array();
3350 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3351 return $this->mWatchedItems
[$key];
3355 * Check the watched status of an article.
3356 * @since 1.22 $checkRights parameter added
3357 * @param Title $title Title of the article to look at
3358 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3359 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3362 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3363 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3368 * @since 1.22 $checkRights parameter added
3369 * @param Title $title Title of the article to look at
3370 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3371 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3373 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3374 $this->getWatchedItem( $title, $checkRights )->addWatch();
3375 $this->invalidateCache();
3379 * Stop watching an article.
3380 * @since 1.22 $checkRights parameter added
3381 * @param Title $title Title of the article to look at
3382 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3383 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3385 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3386 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3387 $this->invalidateCache();
3391 * Clear the user's notification timestamp for the given title.
3392 * If e-notif e-mails are on, they will receive notification mails on
3393 * the next change of the page if it's watched etc.
3394 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3395 * @param Title $title Title of the article to look at
3396 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3398 public function clearNotification( &$title, $oldid = 0 ) {
3399 global $wgUseEnotif, $wgShowUpdatedMarker;
3401 // Do nothing if the database is locked to writes
3402 if ( wfReadOnly() ) {
3406 // Do nothing if not allowed to edit the watchlist
3407 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3411 // If we're working on user's talk page, we should update the talk page message indicator
3412 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3413 if ( !Hooks
::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3417 $nextid = $oldid ?
$title->getNextRevisionID( $oldid ) : null;
3419 if ( !$oldid ||
!$nextid ) {
3420 // If we're looking at the latest revision, we should definitely clear it
3421 $this->setNewtalk( false );
3423 // Otherwise we should update its revision, if it's present
3424 if ( $this->getNewtalk() ) {
3425 // Naturally the other one won't clear by itself
3426 $this->setNewtalk( false );
3427 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3432 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3436 if ( $this->isAnon() ) {
3437 // Nothing else to do...
3441 // Only update the timestamp if the page is being watched.
3442 // The query to find out if it is watched is cached both in memcached and per-invocation,
3443 // and when it does have to be executed, it can be on a slave
3444 // If this is the user's newtalk page, we always update the timestamp
3446 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3450 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3451 $force, $oldid, WatchedItem
::DEFERRED
3456 * Resets all of the given user's page-change notification timestamps.
3457 * If e-notif e-mails are on, they will receive notification mails on
3458 * the next change of any watched page.
3459 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3461 public function clearAllNotifications() {
3462 if ( wfReadOnly() ) {
3466 // Do nothing if not allowed to edit the watchlist
3467 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3471 global $wgUseEnotif, $wgShowUpdatedMarker;
3472 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3473 $this->setNewtalk( false );
3476 $id = $this->getId();
3478 $dbw = wfGetDB( DB_MASTER
);
3479 $dbw->update( 'watchlist',
3480 array( /* SET */ 'wl_notificationtimestamp' => null ),
3481 array( /* WHERE */ 'wl_user' => $id ),
3484 // We also need to clear here the "you have new message" notification for the own user_talk page;
3485 // it's cleared one page view later in WikiPage::doViewUpdates().
3490 * Set a cookie on the user's client. Wrapper for
3491 * WebResponse::setCookie
3492 * @param string $name Name of the cookie to set
3493 * @param string $value Value to set
3494 * @param int $exp Expiration time, as a UNIX time value;
3495 * if 0 or not specified, use the default $wgCookieExpiration
3496 * @param bool $secure
3497 * true: Force setting the secure attribute when setting the cookie
3498 * false: Force NOT setting the secure attribute when setting the cookie
3499 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3500 * @param array $params Array of options sent passed to WebResponse::setcookie()
3501 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3504 protected function setCookie(
3505 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3507 if ( $request === null ) {
3508 $request = $this->getRequest();
3510 $params['secure'] = $secure;
3511 $request->response()->setcookie( $name, $value, $exp, $params );
3515 * Clear a cookie on the user's client
3516 * @param string $name Name of the cookie to clear
3517 * @param bool $secure
3518 * true: Force setting the secure attribute when setting the cookie
3519 * false: Force NOT setting the secure attribute when setting the cookie
3520 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3521 * @param array $params Array of options sent passed to WebResponse::setcookie()
3523 protected function clearCookie( $name, $secure = null, $params = array() ) {
3524 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3528 * Set the default cookies for this session on the user's client.
3530 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3532 * @param bool $secure Whether to force secure/insecure cookies or use default
3533 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3535 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3536 if ( $request === null ) {
3537 $request = $this->getRequest();
3541 if ( 0 == $this->mId
) {
3544 if ( !$this->mToken
) {
3545 // When token is empty or NULL generate a new one and then save it to the database
3546 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3547 // Simply by setting every cell in the user_token column to NULL and letting them be
3548 // regenerated as users log back into the wiki.
3550 if ( !wfReadOnly() ) {
3551 $this->saveSettings();
3555 'wsUserID' => $this->mId
,
3556 'wsToken' => $this->mToken
,
3557 'wsUserName' => $this->getName()
3560 'UserID' => $this->mId
,
3561 'UserName' => $this->getName(),
3563 if ( $rememberMe ) {
3564 $cookies['Token'] = $this->mToken
;
3566 $cookies['Token'] = false;
3569 Hooks
::run( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3571 foreach ( $session as $name => $value ) {
3572 $request->setSessionData( $name, $value );
3574 foreach ( $cookies as $name => $value ) {
3575 if ( $value === false ) {
3576 $this->clearCookie( $name );
3578 $this->setCookie( $name, $value, 0, $secure, array(), $request );
3583 * If wpStickHTTPS was selected, also set an insecure cookie that
3584 * will cause the site to redirect the user to HTTPS, if they access
3585 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3586 * as the one set by centralauth (bug 53538). Also set it to session, or
3587 * standard time setting, based on if rememberme was set.
3589 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3593 $rememberMe ?
0 : null,
3595 array( 'prefix' => '' ) // no prefix
3601 * Log this user out.
3603 public function logout() {
3604 if ( Hooks
::run( 'UserLogout', array( &$this ) ) ) {
3610 * Clear the user's cookies and session, and reset the instance cache.
3613 public function doLogout() {
3614 $this->clearInstanceCache( 'defaults' );
3616 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3618 $this->clearCookie( 'UserID' );
3619 $this->clearCookie( 'Token' );
3620 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3622 // Remember when user logged out, to prevent seeing cached pages
3623 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3627 * Save this user's settings into the database.
3628 * @todo Only rarely do all these fields need to be set!
3630 public function saveSettings() {
3633 if ( wfReadOnly() ) {
3634 // @TODO: caller should deal with this instead!
3635 // This should really just be an exception.
3636 MWExceptionHandler
::logException( new DBExpectedError(
3638 "Could not update user with ID '{$this->mId}'; DB is read-only."
3644 $this->loadPasswords();
3645 if ( 0 == $this->mId
) {
3649 // This method is for updating existing users, so the user should
3650 // have been loaded from the master to begin with to avoid problems.
3651 if ( !( $this->queryFlagsUsed
& self
::READ_LATEST
) ) {
3652 wfWarn( "Attempting to save slave-loaded User object with ID '{$this->mId}'." );
3655 // Get a new user_touched that is higher than the old one.
3656 // This will be used for a CAS check as a last-resort safety
3657 // check against race conditions and slave lag.
3658 $oldTouched = $this->mTouched
;
3659 $newTouched = $this->newTouchedTimestamp();
3661 if ( !$wgAuth->allowSetLocalPassword() ) {
3662 $this->mPassword
= self
::getPasswordFactory()->newFromCiphertext( null );
3665 $dbw = wfGetDB( DB_MASTER
);
3666 $dbw->update( 'user',
3668 'user_name' => $this->mName
,
3669 'user_password' => $this->mPassword
->toString(),
3670 'user_newpassword' => $this->mNewpassword
->toString(),
3671 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3672 'user_real_name' => $this->mRealName
,
3673 'user_email' => $this->mEmail
,
3674 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3675 'user_touched' => $dbw->timestamp( $newTouched ),
3676 'user_token' => strval( $this->mToken
),
3677 'user_email_token' => $this->mEmailToken
,
3678 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3679 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires
),
3680 ), array( /* WHERE */
3681 'user_id' => $this->mId
,
3682 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3686 if ( !$dbw->affectedRows() ) {
3687 // Maybe the problem was a missed cache update; clear it to be safe
3688 $this->clearSharedCache();
3689 // User was changed in the meantime or loaded with stale data
3690 MWExceptionHandler
::logException( new MWException(
3691 "CAS update failed on user_touched for user ID '{$this->mId}';" .
3692 "the version of the user to be saved is older than the current version."
3698 $this->mTouched
= $newTouched;
3699 $this->saveOptions();
3701 Hooks
::run( 'UserSaveSettings', array( $this ) );
3702 $this->clearSharedCache();
3703 $this->getUserPage()->invalidateCache();
3705 // T95839: clear the cache again post-commit to reduce race conditions
3706 // where stale values are written back to the cache by other threads.
3707 // Note: this *still* doesn't deal with REPEATABLE-READ snapshot lag...
3709 $dbw->onTransactionIdle( function() use ( $that ) {
3710 $that->clearSharedCache();
3715 * If only this user's username is known, and it exists, return the user ID.
3718 public function idForName() {
3719 $s = trim( $this->getName() );
3724 $dbr = wfGetDB( DB_SLAVE
);
3725 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
3726 if ( $id === false ) {
3733 * Add a user to the database, return the user object
3735 * @param string $name Username to add
3736 * @param array $params Array of Strings Non-default parameters to save to
3737 * the database as user_* fields:
3738 * - password: The user's password hash. Password logins will be disabled
3739 * if this is omitted.
3740 * - newpassword: Hash for a temporary password that has been mailed to
3742 * - email: The user's email address.
3743 * - email_authenticated: The email authentication timestamp.
3744 * - real_name: The user's real name.
3745 * - options: An associative array of non-default options.
3746 * - token: Random authentication token. Do not set.
3747 * - registration: Registration timestamp. Do not set.
3749 * @return User|null User object, or null if the username already exists.
3751 public static function createNew( $name, $params = array() ) {
3754 $user->loadPasswords();
3755 $user->setToken(); // init token
3756 if ( isset( $params['options'] ) ) {
3757 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3758 unset( $params['options'] );
3760 $dbw = wfGetDB( DB_MASTER
);
3761 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3764 'user_id' => $seqVal,
3765 'user_name' => $name,
3766 'user_password' => $user->mPassword
->toString(),
3767 'user_newpassword' => $user->mNewpassword
->toString(),
3768 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3769 'user_email' => $user->mEmail
,
3770 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3771 'user_real_name' => $user->mRealName
,
3772 'user_token' => strval( $user->mToken
),
3773 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3774 'user_editcount' => 0,
3775 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3777 foreach ( $params as $name => $value ) {
3778 $fields["user_$name"] = $value;
3780 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3781 if ( $dbw->affectedRows() ) {
3782 $newUser = User
::newFromId( $dbw->insertId() );
3790 * Add this existing user object to the database. If the user already
3791 * exists, a fatal status object is returned, and the user object is
3792 * initialised with the data from the database.
3794 * Previously, this function generated a DB error due to a key conflict
3795 * if the user already existed. Many extension callers use this function
3796 * in code along the lines of:
3798 * $user = User::newFromName( $name );
3799 * if ( !$user->isLoggedIn() ) {
3800 * $user->addToDatabase();
3802 * // do something with $user...
3804 * However, this was vulnerable to a race condition (bug 16020). By
3805 * initialising the user object if the user exists, we aim to support this
3806 * calling sequence as far as possible.
3808 * Note that if the user exists, this function will acquire a write lock,
3809 * so it is still advisable to make the call conditional on isLoggedIn(),
3810 * and to commit the transaction after calling.
3812 * @throws MWException
3815 public function addToDatabase() {
3817 $this->loadPasswords();
3818 if ( !$this->mToken
) {
3819 $this->setToken(); // init token
3822 $this->mTouched
= $this->newTouchedTimestamp();
3824 $dbw = wfGetDB( DB_MASTER
);
3825 $inWrite = $dbw->writesOrCallbacksPending();
3826 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3827 $dbw->insert( 'user',
3829 'user_id' => $seqVal,
3830 'user_name' => $this->mName
,
3831 'user_password' => $this->mPassword
->toString(),
3832 'user_newpassword' => $this->mNewpassword
->toString(),
3833 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3834 'user_email' => $this->mEmail
,
3835 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3836 'user_real_name' => $this->mRealName
,
3837 'user_token' => strval( $this->mToken
),
3838 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3839 'user_editcount' => 0,
3840 'user_touched' => $dbw->timestamp( $this->mTouched
),
3844 if ( !$dbw->affectedRows() ) {
3845 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3846 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3848 // Can't commit due to pending writes that may need atomicity.
3849 // This may cause some lock contention unlike the case below.
3850 $options = array( 'LOCK IN SHARE MODE' );
3851 $flags = self
::READ_LOCKING
;
3853 // Often, this case happens early in views before any writes when
3854 // using CentralAuth. It's should be OK to commit and break the snapshot.
3855 $dbw->commit( __METHOD__
, 'flush' );
3857 $flags = self
::READ_LATEST
;
3859 $this->mId
= $dbw->selectField( 'user', 'user_id',
3860 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3863 if ( $this->loadFromDatabase( $flags ) ) {
3868 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3869 "to insert user '{$this->mName}' row, but it was not present in select!" );
3871 return Status
::newFatal( 'userexists' );
3873 $this->mId
= $dbw->insertId();
3875 // Clear instance cache other than user table data, which is already accurate
3876 $this->clearInstanceCache();
3878 $this->saveOptions();
3879 return Status
::newGood();
3883 * If this user is logged-in and blocked,
3884 * block any IP address they've successfully logged in from.
3885 * @return bool A block was spread
3887 public function spreadAnyEditBlock() {
3888 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3889 return $this->spreadBlock();
3895 * If this (non-anonymous) user is blocked,
3896 * block the IP address they've successfully logged in from.
3897 * @return bool A block was spread
3899 protected function spreadBlock() {
3900 wfDebug( __METHOD__
. "()\n" );
3902 if ( $this->mId
== 0 ) {
3906 $userblock = Block
::newFromTarget( $this->getName() );
3907 if ( !$userblock ) {
3911 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3915 * Get whether the user is explicitly blocked from account creation.
3916 * @return bool|Block
3918 public function isBlockedFromCreateAccount() {
3919 $this->getBlockedStatus();
3920 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3921 return $this->mBlock
;
3924 # bug 13611: if the IP address the user is trying to create an account from is
3925 # blocked with createaccount disabled, prevent new account creation there even
3926 # when the user is logged in
3927 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3928 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3930 return $this->mBlockedFromCreateAccount
instanceof Block
3931 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3932 ?
$this->mBlockedFromCreateAccount
3937 * Get whether the user is blocked from using Special:Emailuser.
3940 public function isBlockedFromEmailuser() {
3941 $this->getBlockedStatus();
3942 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3946 * Get whether the user is allowed to create an account.
3949 public function isAllowedToCreateAccount() {
3950 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3954 * Get this user's personal page title.
3956 * @return Title User's personal page title
3958 public function getUserPage() {
3959 return Title
::makeTitle( NS_USER
, $this->getName() );
3963 * Get this user's talk page title.
3965 * @return Title User's talk page title
3967 public function getTalkPage() {
3968 $title = $this->getUserPage();
3969 return $title->getTalkPage();
3973 * Determine whether the user is a newbie. Newbies are either
3974 * anonymous IPs, or the most recently created accounts.
3977 public function isNewbie() {
3978 return !$this->isAllowed( 'autoconfirmed' );
3982 * Check to see if the given clear-text password is one of the accepted passwords
3983 * @param string $password User password
3984 * @return bool True if the given password is correct, otherwise False
3986 public function checkPassword( $password ) {
3987 global $wgAuth, $wgLegacyEncoding;
3989 $this->loadPasswords();
3991 // Some passwords will give a fatal Status, which means there is
3992 // some sort of technical or security reason for this password to
3993 // be completely invalid and should never be checked (e.g., T64685)
3994 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
3998 // Certain authentication plugins do NOT want to save
3999 // domain passwords in a mysql database, so we should
4000 // check this (in case $wgAuth->strict() is false).
4001 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4003 } elseif ( $wgAuth->strict() ) {
4004 // Auth plugin doesn't allow local authentication
4006 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4007 // Auth plugin doesn't allow local authentication for this user name
4011 if ( !$this->mPassword
->equals( $password ) ) {
4012 if ( $wgLegacyEncoding ) {
4013 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4014 // Check for this with iconv
4015 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4016 if ( $cp1252Password === $password ||
!$this->mPassword
->equals( $cp1252Password ) ) {
4024 $passwordFactory = self
::getPasswordFactory();
4025 if ( $passwordFactory->needsUpdate( $this->mPassword
) && !wfReadOnly() ) {
4026 $this->mPassword
= $passwordFactory->newFromPlaintext( $password );
4027 $this->saveSettings();
4034 * Check if the given clear-text password matches the temporary password
4035 * sent by e-mail for password reset operations.
4037 * @param string $plaintext
4039 * @return bool True if matches, false otherwise
4041 public function checkTemporaryPassword( $plaintext ) {
4042 global $wgNewPasswordExpiry;
4045 $this->loadPasswords();
4046 if ( $this->mNewpassword
->equals( $plaintext ) ) {
4047 if ( is_null( $this->mNewpassTime
) ) {
4050 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
4051 return ( time() < $expiry );
4058 * Alias for getEditToken.
4059 * @deprecated since 1.19, use getEditToken instead.
4061 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4062 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4063 * @return string The new edit token
4065 public function editToken( $salt = '', $request = null ) {
4066 wfDeprecated( __METHOD__
, '1.19' );
4067 return $this->getEditToken( $salt, $request );
4071 * Internal implementation for self::getEditToken() and
4072 * self::matchEditToken().
4074 * @param string|array $salt
4075 * @param WebRequest $request
4076 * @param string|int $timestamp
4079 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
4080 if ( $this->isAnon() ) {
4081 return self
::EDIT_TOKEN_SUFFIX
;
4083 $token = $request->getSessionData( 'wsEditToken' );
4084 if ( $token === null ) {
4085 $token = MWCryptRand
::generateHex( 32 );
4086 $request->setSessionData( 'wsEditToken', $token );
4088 if ( is_array( $salt ) ) {
4089 $salt = implode( '|', $salt );
4091 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
4092 dechex( $timestamp ) .
4093 self
::EDIT_TOKEN_SUFFIX
;
4098 * Initialize (if necessary) and return a session token value
4099 * which can be used in edit forms to show that the user's
4100 * login credentials aren't being hijacked with a foreign form
4105 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4106 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4107 * @return string The new edit token
4109 public function getEditToken( $salt = '', $request = null ) {
4110 return $this->getEditTokenAtTimestamp(
4111 $salt, $request ?
: $this->getRequest(), wfTimestamp()
4116 * Generate a looking random token for various uses.
4118 * @return string The new random token
4119 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
4120 * wfRandomString for pseudo-randomness.
4122 public static function generateToken() {
4123 return MWCryptRand
::generateHex( 32 );
4127 * Get the embedded timestamp from a token.
4128 * @param string $val Input token
4131 public static function getEditTokenTimestamp( $val ) {
4132 $suffixLen = strlen( self
::EDIT_TOKEN_SUFFIX
);
4133 if ( strlen( $val ) <= 32 +
$suffixLen ) {
4137 return hexdec( substr( $val, 32, -$suffixLen ) );
4141 * Check given value against the token value stored in the session.
4142 * A match should confirm that the form was submitted from the
4143 * user's own login session, not a form submission from a third-party
4146 * @param string $val Input value to compare
4147 * @param string $salt Optional function-specific data for hashing
4148 * @param WebRequest|null $request Object to use or null to use $wgRequest
4149 * @param int $maxage Fail tokens older than this, in seconds
4150 * @return bool Whether the token matches
4152 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4153 if ( $this->isAnon() ) {
4154 return $val === self
::EDIT_TOKEN_SUFFIX
;
4157 $timestamp = self
::getEditTokenTimestamp( $val );
4158 if ( $timestamp === null ) {
4161 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
4166 $sessionToken = $this->getEditTokenAtTimestamp(
4167 $salt, $request ?
: $this->getRequest(), $timestamp
4170 if ( $val != $sessionToken ) {
4171 wfDebug( "User::matchEditToken: broken session data\n" );
4174 return hash_equals( $sessionToken, $val );
4178 * Check given value against the token value stored in the session,
4179 * ignoring the suffix.
4181 * @param string $val Input value to compare
4182 * @param string $salt Optional function-specific data for hashing
4183 * @param WebRequest|null $request Object to use or null to use $wgRequest
4184 * @param int $maxage Fail tokens older than this, in seconds
4185 * @return bool Whether the token matches
4187 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4188 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4189 return $this->matchEditToken( $val, $salt, $request, $maxage );
4193 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4194 * mail to the user's given address.
4196 * @param string $type Message to send, either "created", "changed" or "set"
4199 public function sendConfirmationMail( $type = 'created' ) {
4201 $expiration = null; // gets passed-by-ref and defined in next line.
4202 $token = $this->confirmationToken( $expiration );
4203 $url = $this->confirmationTokenUrl( $token );
4204 $invalidateURL = $this->invalidationTokenUrl( $token );
4205 $this->saveSettings();
4207 if ( $type == 'created' ||
$type === false ) {
4208 $message = 'confirmemail_body';
4209 } elseif ( $type === true ) {
4210 $message = 'confirmemail_body_changed';
4212 // Messages: confirmemail_body_changed, confirmemail_body_set
4213 $message = 'confirmemail_body_' . $type;
4216 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4217 wfMessage( $message,
4218 $this->getRequest()->getIP(),
4221 $wgLang->timeanddate( $expiration, false ),
4223 $wgLang->date( $expiration, false ),
4224 $wgLang->time( $expiration, false ) )->text() );
4228 * Send an e-mail to this user's account. Does not check for
4229 * confirmed status or validity.
4231 * @param string $subject Message subject
4232 * @param string $body Message body
4233 * @param string $from Optional From address; if unspecified, default
4234 * $wgPasswordSender will be used.
4235 * @param string $replyto Reply-To address
4238 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4239 if ( is_null( $from ) ) {
4240 global $wgPasswordSender;
4241 $sender = new MailAddress( $wgPasswordSender,
4242 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4244 $sender = MailAddress
::newFromUser( $from );
4247 $to = MailAddress
::newFromUser( $this );
4248 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
4252 * Generate, store, and return a new e-mail confirmation code.
4253 * A hash (unsalted, since it's used as a key) is stored.
4255 * @note Call saveSettings() after calling this function to commit
4256 * this change to the database.
4258 * @param string &$expiration Accepts the expiration time
4259 * @return string New token
4261 protected function confirmationToken( &$expiration ) {
4262 global $wgUserEmailConfirmationTokenExpiry;
4264 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4265 $expiration = wfTimestamp( TS_MW
, $expires );
4267 $token = MWCryptRand
::generateHex( 32 );
4268 $hash = md5( $token );
4269 $this->mEmailToken
= $hash;
4270 $this->mEmailTokenExpires
= $expiration;
4275 * Return a URL the user can use to confirm their email address.
4276 * @param string $token Accepts the email confirmation token
4277 * @return string New token URL
4279 protected function confirmationTokenUrl( $token ) {
4280 return $this->getTokenUrl( 'ConfirmEmail', $token );
4284 * Return a URL the user can use to invalidate their email address.
4285 * @param string $token Accepts the email confirmation token
4286 * @return string New token URL
4288 protected function invalidationTokenUrl( $token ) {
4289 return $this->getTokenUrl( 'InvalidateEmail', $token );
4293 * Internal function to format the e-mail validation/invalidation URLs.
4294 * This uses a quickie hack to use the
4295 * hardcoded English names of the Special: pages, for ASCII safety.
4297 * @note Since these URLs get dropped directly into emails, using the
4298 * short English names avoids insanely long URL-encoded links, which
4299 * also sometimes can get corrupted in some browsers/mailers
4300 * (bug 6957 with Gmail and Internet Explorer).
4302 * @param string $page Special page
4303 * @param string $token Token
4304 * @return string Formatted URL
4306 protected function getTokenUrl( $page, $token ) {
4307 // Hack to bypass localization of 'Special:'
4308 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4309 return $title->getCanonicalURL();
4313 * Mark the e-mail address confirmed.
4315 * @note Call saveSettings() after calling this function to commit the change.
4319 public function confirmEmail() {
4320 // Check if it's already confirmed, so we don't touch the database
4321 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4322 if ( !$this->isEmailConfirmed() ) {
4323 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4324 Hooks
::run( 'ConfirmEmailComplete', array( $this ) );
4330 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4331 * address if it was already confirmed.
4333 * @note Call saveSettings() after calling this function to commit the change.
4334 * @return bool Returns true
4336 public function invalidateEmail() {
4338 $this->mEmailToken
= null;
4339 $this->mEmailTokenExpires
= null;
4340 $this->setEmailAuthenticationTimestamp( null );
4342 Hooks
::run( 'InvalidateEmailComplete', array( $this ) );
4347 * Set the e-mail authentication timestamp.
4348 * @param string $timestamp TS_MW timestamp
4350 public function setEmailAuthenticationTimestamp( $timestamp ) {
4352 $this->mEmailAuthenticated
= $timestamp;
4353 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4357 * Is this user allowed to send e-mails within limits of current
4358 * site configuration?
4361 public function canSendEmail() {
4362 global $wgEnableEmail, $wgEnableUserEmail;
4363 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4366 $canSend = $this->isEmailConfirmed();
4367 Hooks
::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4372 * Is this user allowed to receive e-mails within limits of current
4373 * site configuration?
4376 public function canReceiveEmail() {
4377 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4381 * Is this user's e-mail address valid-looking and confirmed within
4382 * limits of the current site configuration?
4384 * @note If $wgEmailAuthentication is on, this may require the user to have
4385 * confirmed their address by returning a code or using a password
4386 * sent to the address from the wiki.
4390 public function isEmailConfirmed() {
4391 global $wgEmailAuthentication;
4394 if ( Hooks
::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4395 if ( $this->isAnon() ) {
4398 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4401 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4411 * Check whether there is an outstanding request for e-mail confirmation.
4414 public function isEmailConfirmationPending() {
4415 global $wgEmailAuthentication;
4416 return $wgEmailAuthentication &&
4417 !$this->isEmailConfirmed() &&
4418 $this->mEmailToken
&&
4419 $this->mEmailTokenExpires
> wfTimestamp();
4423 * Get the timestamp of account creation.
4425 * @return string|bool|null Timestamp of account creation, false for
4426 * non-existent/anonymous user accounts, or null if existing account
4427 * but information is not in database.
4429 public function getRegistration() {
4430 if ( $this->isAnon() ) {
4434 return $this->mRegistration
;
4438 * Get the timestamp of the first edit
4440 * @return string|bool Timestamp of first edit, or false for
4441 * non-existent/anonymous user accounts.
4443 public function getFirstEditTimestamp() {
4444 if ( $this->getId() == 0 ) {
4445 return false; // anons
4447 $dbr = wfGetDB( DB_SLAVE
);
4448 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4449 array( 'rev_user' => $this->getId() ),
4451 array( 'ORDER BY' => 'rev_timestamp ASC' )
4454 return false; // no edits
4456 return wfTimestamp( TS_MW
, $time );
4460 * Get the permissions associated with a given list of groups
4462 * @param array $groups Array of Strings List of internal group names
4463 * @return array Array of Strings List of permission key names for given groups combined
4465 public static function getGroupPermissions( $groups ) {
4466 global $wgGroupPermissions, $wgRevokePermissions;
4468 // grant every granted permission first
4469 foreach ( $groups as $group ) {
4470 if ( isset( $wgGroupPermissions[$group] ) ) {
4471 $rights = array_merge( $rights,
4472 // array_filter removes empty items
4473 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4476 // now revoke the revoked permissions
4477 foreach ( $groups as $group ) {
4478 if ( isset( $wgRevokePermissions[$group] ) ) {
4479 $rights = array_diff( $rights,
4480 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4483 return array_unique( $rights );
4487 * Get all the groups who have a given permission
4489 * @param string $role Role to check
4490 * @return array Array of Strings List of internal group names with the given permission
4492 public static function getGroupsWithPermission( $role ) {
4493 global $wgGroupPermissions;
4494 $allowedGroups = array();
4495 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4496 if ( self
::groupHasPermission( $group, $role ) ) {
4497 $allowedGroups[] = $group;
4500 return $allowedGroups;
4504 * Check, if the given group has the given permission
4506 * If you're wanting to check whether all users have a permission, use
4507 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4511 * @param string $group Group to check
4512 * @param string $role Role to check
4515 public static function groupHasPermission( $group, $role ) {
4516 global $wgGroupPermissions, $wgRevokePermissions;
4517 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4518 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4522 * Check if all users have the given permission
4525 * @param string $right Right to check
4528 public static function isEveryoneAllowed( $right ) {
4529 global $wgGroupPermissions, $wgRevokePermissions;
4530 static $cache = array();
4532 // Use the cached results, except in unit tests which rely on
4533 // being able change the permission mid-request
4534 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4535 return $cache[$right];
4538 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4539 $cache[$right] = false;
4543 // If it's revoked anywhere, then everyone doesn't have it
4544 foreach ( $wgRevokePermissions as $rights ) {
4545 if ( isset( $rights[$right] ) && $rights[$right] ) {
4546 $cache[$right] = false;
4551 // Allow extensions (e.g. OAuth) to say false
4552 if ( !Hooks
::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4553 $cache[$right] = false;
4557 $cache[$right] = true;
4562 * Get the localized descriptive name for a group, if it exists
4564 * @param string $group Internal group name
4565 * @return string Localized descriptive group name
4567 public static function getGroupName( $group ) {
4568 $msg = wfMessage( "group-$group" );
4569 return $msg->isBlank() ?
$group : $msg->text();
4573 * Get the localized descriptive name for a member of a group, if it exists
4575 * @param string $group Internal group name
4576 * @param string $username Username for gender (since 1.19)
4577 * @return string Localized name for group member
4579 public static function getGroupMember( $group, $username = '#' ) {
4580 $msg = wfMessage( "group-$group-member", $username );
4581 return $msg->isBlank() ?
$group : $msg->text();
4585 * Return the set of defined explicit groups.
4586 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4587 * are not included, as they are defined automatically, not in the database.
4588 * @return array Array of internal group names
4590 public static function getAllGroups() {
4591 global $wgGroupPermissions, $wgRevokePermissions;
4593 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4594 self
::getImplicitGroups()
4599 * Get a list of all available permissions.
4600 * @return string[] Array of permission names
4602 public static function getAllRights() {
4603 if ( self
::$mAllRights === false ) {
4604 global $wgAvailableRights;
4605 if ( count( $wgAvailableRights ) ) {
4606 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4608 self
::$mAllRights = self
::$mCoreRights;
4610 Hooks
::run( 'UserGetAllRights', array( &self
::$mAllRights ) );
4612 return self
::$mAllRights;
4616 * Get a list of implicit groups
4617 * @return array Array of Strings Array of internal group names
4619 public static function getImplicitGroups() {
4620 global $wgImplicitGroups;
4622 $groups = $wgImplicitGroups;
4623 # Deprecated, use $wgImplicitGroups instead
4624 Hooks
::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4630 * Get the title of a page describing a particular group
4632 * @param string $group Internal group name
4633 * @return Title|bool Title of the page if it exists, false otherwise
4635 public static function getGroupPage( $group ) {
4636 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4637 if ( $msg->exists() ) {
4638 $title = Title
::newFromText( $msg->text() );
4639 if ( is_object( $title ) ) {
4647 * Create a link to the group in HTML, if available;
4648 * else return the group name.
4650 * @param string $group Internal name of the group
4651 * @param string $text The text of the link
4652 * @return string HTML link to the group
4654 public static function makeGroupLinkHTML( $group, $text = '' ) {
4655 if ( $text == '' ) {
4656 $text = self
::getGroupName( $group );
4658 $title = self
::getGroupPage( $group );
4660 return Linker
::link( $title, htmlspecialchars( $text ) );
4662 return htmlspecialchars( $text );
4667 * Create a link to the group in Wikitext, if available;
4668 * else return the group name.
4670 * @param string $group Internal name of the group
4671 * @param string $text The text of the link
4672 * @return string Wikilink to the group
4674 public static function makeGroupLinkWiki( $group, $text = '' ) {
4675 if ( $text == '' ) {
4676 $text = self
::getGroupName( $group );
4678 $title = self
::getGroupPage( $group );
4680 $page = $title->getFullText();
4681 return "[[$page|$text]]";
4688 * Returns an array of the groups that a particular group can add/remove.
4690 * @param string $group The group to check for whether it can add/remove
4691 * @return array Array( 'add' => array( addablegroups ),
4692 * 'remove' => array( removablegroups ),
4693 * 'add-self' => array( addablegroups to self),
4694 * 'remove-self' => array( removable groups from self) )
4696 public static function changeableByGroup( $group ) {
4697 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4701 'remove' => array(),
4702 'add-self' => array(),
4703 'remove-self' => array()
4706 if ( empty( $wgAddGroups[$group] ) ) {
4707 // Don't add anything to $groups
4708 } elseif ( $wgAddGroups[$group] === true ) {
4709 // You get everything
4710 $groups['add'] = self
::getAllGroups();
4711 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4712 $groups['add'] = $wgAddGroups[$group];
4715 // Same thing for remove
4716 if ( empty( $wgRemoveGroups[$group] ) ) {
4718 } elseif ( $wgRemoveGroups[$group] === true ) {
4719 $groups['remove'] = self
::getAllGroups();
4720 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4721 $groups['remove'] = $wgRemoveGroups[$group];
4724 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4725 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4726 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4727 if ( is_int( $key ) ) {
4728 $wgGroupsAddToSelf['user'][] = $value;
4733 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4734 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4735 if ( is_int( $key ) ) {
4736 $wgGroupsRemoveFromSelf['user'][] = $value;
4741 // Now figure out what groups the user can add to him/herself
4742 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4744 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4745 // No idea WHY this would be used, but it's there
4746 $groups['add-self'] = User
::getAllGroups();
4747 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4748 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4751 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4753 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4754 $groups['remove-self'] = User
::getAllGroups();
4755 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4756 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4763 * Returns an array of groups that this user can add and remove
4764 * @return array Array( 'add' => array( addablegroups ),
4765 * 'remove' => array( removablegroups ),
4766 * 'add-self' => array( addablegroups to self),
4767 * 'remove-self' => array( removable groups from self) )
4769 public function changeableGroups() {
4770 if ( $this->isAllowed( 'userrights' ) ) {
4771 // This group gives the right to modify everything (reverse-
4772 // compatibility with old "userrights lets you change
4774 // Using array_merge to make the groups reindexed
4775 $all = array_merge( User
::getAllGroups() );
4779 'add-self' => array(),
4780 'remove-self' => array()
4784 // Okay, it's not so simple, we will have to go through the arrays
4787 'remove' => array(),
4788 'add-self' => array(),
4789 'remove-self' => array()
4791 $addergroups = $this->getEffectiveGroups();
4793 foreach ( $addergroups as $addergroup ) {
4794 $groups = array_merge_recursive(
4795 $groups, $this->changeableByGroup( $addergroup )
4797 $groups['add'] = array_unique( $groups['add'] );
4798 $groups['remove'] = array_unique( $groups['remove'] );
4799 $groups['add-self'] = array_unique( $groups['add-self'] );
4800 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4806 * Deferred version of incEditCountImmediate()
4808 public function incEditCount() {
4810 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $that ) {
4811 $that->incEditCountImmediate();
4816 * Increment the user's edit-count field.
4817 * Will have no effect for anonymous users.
4820 public function incEditCountImmediate() {
4821 if ( $this->isAnon() ) {
4825 $dbw = wfGetDB( DB_MASTER
);
4826 // No rows will be "affected" if user_editcount is NULL
4829 array( 'user_editcount=user_editcount+1' ),
4830 array( 'user_id' => $this->getId() ),
4833 // Lazy initialization check...
4834 if ( $dbw->affectedRows() == 0 ) {
4835 // Now here's a goddamn hack...
4836 $dbr = wfGetDB( DB_SLAVE
);
4837 if ( $dbr !== $dbw ) {
4838 // If we actually have a slave server, the count is
4839 // at least one behind because the current transaction
4840 // has not been committed and replicated.
4841 $this->initEditCount( 1 );
4843 // But if DB_SLAVE is selecting the master, then the
4844 // count we just read includes the revision that was
4845 // just added in the working transaction.
4846 $this->initEditCount();
4849 // Edit count in user cache too
4850 $this->invalidateCache();
4854 * Initialize user_editcount from data out of the revision table
4856 * @param int $add Edits to add to the count from the revision table
4857 * @return int Number of edits
4859 protected function initEditCount( $add = 0 ) {
4860 // Pull from a slave to be less cruel to servers
4861 // Accuracy isn't the point anyway here
4862 $dbr = wfGetDB( DB_SLAVE
);
4863 $count = (int)$dbr->selectField(
4866 array( 'rev_user' => $this->getId() ),
4869 $count = $count +
$add;
4871 $dbw = wfGetDB( DB_MASTER
);
4874 array( 'user_editcount' => $count ),
4875 array( 'user_id' => $this->getId() ),
4883 * Get the description of a given right
4885 * @param string $right Right to query
4886 * @return string Localized description of the right
4888 public static function getRightDescription( $right ) {
4889 $key = "right-$right";
4890 $msg = wfMessage( $key );
4891 return $msg->isBlank() ?
$right : $msg->text();
4895 * Make a new-style password hash
4897 * @param string $password Plain-text password
4898 * @param bool|string $salt Optional salt, may be random or the user ID.
4899 * If unspecified or false, will generate one automatically
4900 * @return string Password hash
4901 * @deprecated since 1.24, use Password class
4903 public static function crypt( $password, $salt = false ) {
4904 wfDeprecated( __METHOD__
, '1.24' );
4905 $hash = self
::getPasswordFactory()->newFromPlaintext( $password );
4906 return $hash->toString();
4910 * Compare a password hash with a plain-text password. Requires the user
4911 * ID if there's a chance that the hash is an old-style hash.
4913 * @param string $hash Password hash
4914 * @param string $password Plain-text password to compare
4915 * @param string|bool $userId User ID for old-style password salt
4918 * @deprecated since 1.24, use Password class
4920 public static function comparePasswords( $hash, $password, $userId = false ) {
4921 wfDeprecated( __METHOD__
, '1.24' );
4923 // Check for *really* old password hashes that don't even have a type
4924 // The old hash format was just an md5 hex hash, with no type information
4925 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4926 global $wgPasswordSalt;
4927 if ( $wgPasswordSalt ) {
4928 $password = ":B:{$userId}:{$hash}";
4930 $password = ":A:{$hash}";
4934 $hash = self
::getPasswordFactory()->newFromCiphertext( $hash );
4935 return $hash->equals( $password );
4939 * Add a newuser log entry for this user.
4940 * Before 1.19 the return value was always true.
4942 * @param string|bool $action Account creation type.
4943 * - String, one of the following values:
4944 * - 'create' for an anonymous user creating an account for himself.
4945 * This will force the action's performer to be the created user itself,
4946 * no matter the value of $wgUser
4947 * - 'create2' for a logged in user creating an account for someone else
4948 * - 'byemail' when the created user will receive its password by e-mail
4949 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4950 * - Boolean means whether the account was created by e-mail (deprecated):
4951 * - true will be converted to 'byemail'
4952 * - false will be converted to 'create' if this object is the same as
4953 * $wgUser and to 'create2' otherwise
4955 * @param string $reason User supplied reason
4957 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4959 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4960 global $wgUser, $wgNewUserLog;
4961 if ( empty( $wgNewUserLog ) ) {
4962 return true; // disabled
4965 if ( $action === true ) {
4966 $action = 'byemail';
4967 } elseif ( $action === false ) {
4968 if ( $this->equals( $wgUser ) ) {
4971 $action = 'create2';
4975 if ( $action === 'create' ||
$action === 'autocreate' ) {
4978 $performer = $wgUser;
4981 $logEntry = new ManualLogEntry( 'newusers', $action );
4982 $logEntry->setPerformer( $performer );
4983 $logEntry->setTarget( $this->getUserPage() );
4984 $logEntry->setComment( $reason );
4985 $logEntry->setParameters( array(
4986 '4::userid' => $this->getId(),
4988 $logid = $logEntry->insert();
4990 if ( $action !== 'autocreate' ) {
4991 $logEntry->publish( $logid );
4998 * Add an autocreate newuser log entry for this user
4999 * Used by things like CentralAuth and perhaps other authplugins.
5000 * Consider calling addNewUserLogEntry() directly instead.
5004 public function addNewUserLogEntryAutoCreate() {
5005 $this->addNewUserLogEntry( 'autocreate' );
5011 * Load the user options either from cache, the database or an array
5013 * @param array $data Rows for the current user out of the user_properties table
5015 protected function loadOptions( $data = null ) {
5020 if ( $this->mOptionsLoaded
) {
5024 $this->mOptions
= self
::getDefaultOptions();
5026 if ( !$this->getId() ) {
5027 // For unlogged-in users, load language/variant options from request.
5028 // There's no need to do it for logged-in users: they can set preferences,
5029 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5030 // so don't override user's choice (especially when the user chooses site default).
5031 $variant = $wgContLang->getDefaultVariant();
5032 $this->mOptions
['variant'] = $variant;
5033 $this->mOptions
['language'] = $variant;
5034 $this->mOptionsLoaded
= true;
5038 // Maybe load from the object
5039 if ( !is_null( $this->mOptionOverrides
) ) {
5040 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5041 foreach ( $this->mOptionOverrides
as $key => $value ) {
5042 $this->mOptions
[$key] = $value;
5045 if ( !is_array( $data ) ) {
5046 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5047 // Load from database
5048 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5049 ?
wfGetDB( DB_MASTER
)
5050 : wfGetDB( DB_SLAVE
);
5052 $res = $dbr->select(
5054 array( 'up_property', 'up_value' ),
5055 array( 'up_user' => $this->getId() ),
5059 $this->mOptionOverrides
= array();
5061 foreach ( $res as $row ) {
5062 $data[$row->up_property
] = $row->up_value
;
5065 foreach ( $data as $property => $value ) {
5066 $this->mOptionOverrides
[$property] = $value;
5067 $this->mOptions
[$property] = $value;
5071 $this->mOptionsLoaded
= true;
5073 Hooks
::run( 'UserLoadOptions', array( $this, &$this->mOptions
) );
5077 * Saves the non-default options for this user, as previously set e.g. via
5078 * setOption(), in the database's "user_properties" (preferences) table.
5079 * Usually used via saveSettings().
5081 protected function saveOptions() {
5082 $this->loadOptions();
5084 // Not using getOptions(), to keep hidden preferences in database
5085 $saveOptions = $this->mOptions
;
5087 // Allow hooks to abort, for instance to save to a global profile.
5088 // Reset options to default state before saving.
5089 if ( !Hooks
::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5093 $userId = $this->getId();
5095 $insert_rows = array(); // all the new preference rows
5096 foreach ( $saveOptions as $key => $value ) {
5097 // Don't bother storing default values
5098 $defaultOption = self
::getDefaultOption( $key );
5099 if ( ( $defaultOption === null && $value !== false && $value !== null )
5100 ||
$value != $defaultOption
5102 $insert_rows[] = array(
5103 'up_user' => $userId,
5104 'up_property' => $key,
5105 'up_value' => $value,
5110 $dbw = wfGetDB( DB_MASTER
);
5112 $res = $dbw->select( 'user_properties',
5113 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
5115 // Find prior rows that need to be removed or updated. These rows will
5116 // all be deleted (the later so that INSERT IGNORE applies the new values).
5117 $keysDelete = array();
5118 foreach ( $res as $row ) {
5119 if ( !isset( $saveOptions[$row->up_property
] )
5120 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5122 $keysDelete[] = $row->up_property
;
5126 if ( count( $keysDelete ) ) {
5127 // Do the DELETE by PRIMARY KEY for prior rows.
5128 // In the past a very large portion of calls to this function are for setting
5129 // 'rememberpassword' for new accounts (a preference that has since been removed).
5130 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5131 // caused gap locks on [max user ID,+infinity) which caused high contention since
5132 // updates would pile up on each other as they are for higher (newer) user IDs.
5133 // It might not be necessary these days, but it shouldn't hurt either.
5134 $dbw->delete( 'user_properties',
5135 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
5137 // Insert the new preference rows
5138 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
5142 * Lazily instantiate and return a factory object for making passwords
5144 * @return PasswordFactory
5146 public static function getPasswordFactory() {
5147 if ( self
::$mPasswordFactory === null ) {
5148 self
::$mPasswordFactory = new PasswordFactory();
5149 self
::$mPasswordFactory->init( RequestContext
::getMain()->getConfig() );
5152 return self
::$mPasswordFactory;
5156 * Provide an array of HTML5 attributes to put on an input element
5157 * intended for the user to enter a new password. This may include
5158 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5160 * Do *not* use this when asking the user to enter his current password!
5161 * Regardless of configuration, users may have invalid passwords for whatever
5162 * reason (e.g., they were set before requirements were tightened up).
5163 * Only use it when asking for a new password, like on account creation or
5166 * Obviously, you still need to do server-side checking.
5168 * NOTE: A combination of bugs in various browsers means that this function
5169 * actually just returns array() unconditionally at the moment. May as
5170 * well keep it around for when the browser bugs get fixed, though.
5172 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5174 * @return array Array of HTML attributes suitable for feeding to
5175 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5176 * That will get confused by the boolean attribute syntax used.)
5178 public static function passwordChangeInputAttribs() {
5179 global $wgMinimalPasswordLength;
5181 if ( $wgMinimalPasswordLength == 0 ) {
5185 # Note that the pattern requirement will always be satisfied if the
5186 # input is empty, so we need required in all cases.
5188 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5189 # if e-mail confirmation is being used. Since HTML5 input validation
5190 # is b0rked anyway in some browsers, just return nothing. When it's
5191 # re-enabled, fix this code to not output required for e-mail
5193 #$ret = array( 'required' );
5196 # We can't actually do this right now, because Opera 9.6 will print out
5197 # the entered password visibly in its error message! When other
5198 # browsers add support for this attribute, or Opera fixes its support,
5199 # we can add support with a version check to avoid doing this on Opera
5200 # versions where it will be a problem. Reported to Opera as
5201 # DSK-262266, but they don't have a public bug tracker for us to follow.
5203 if ( $wgMinimalPasswordLength > 1 ) {
5204 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5205 $ret['title'] = wfMessage( 'passwordtooshort' )
5206 ->numParams( $wgMinimalPasswordLength )->text();
5214 * Return the list of user fields that should be selected to create
5215 * a new user object.
5218 public static function selectFields() {
5226 'user_email_authenticated',
5228 'user_email_token_expires',
5229 'user_registration',
5235 * Factory function for fatal permission-denied errors
5238 * @param string $permission User right required
5241 static function newFatalPermissionDeniedStatus( $permission ) {
5244 $groups = array_map(
5245 array( 'User', 'makeGroupLinkWiki' ),
5246 User
::getGroupsWithPermission( $permission )
5250 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5252 return Status
::newFatal( 'badaccess-group0' );
5257 * Checks if two user objects point to the same user.
5263 public function equals( User
$user ) {
5264 return $this->getName() === $user->getName();