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() {
413 if ( $this->mId
== 0 ) {
414 $this->loadDefaults();
418 $cache = ObjectCache
::getMainWANInstance();
419 $key = wfMemcKey( 'user', 'id', $this->mId
);
420 $data = $cache->get( $key );
421 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
426 wfDebug( "User: got user {$this->mId} from cache\n" );
428 // Restore from cache
429 foreach ( self
::$mCacheVars as $name ) {
430 $this->$name = $data[$name];
437 * Save user data to the shared cache
439 * This method should not be called outside the User class
441 public function saveToCache() {
444 $this->loadOptions();
446 if ( $this->isAnon() ) {
447 // Anonymous users are uncached
451 $cache = ObjectCache
::getMainWANInstance();
453 // The cache needs good consistency due to its high TTL, so the user
454 // should have been loaded from the master to avoid lag amplification.
455 if ( !( $this->queryFlagsUsed
& self
::READ_LATEST
) ) {
456 wfWarn( "Cannot cache slave-loaded User object with ID '{$this->mId}'." );
461 foreach ( self
::$mCacheVars as $name ) {
462 $data[$name] = $this->$name;
464 $data['mVersion'] = self
::VERSION
;
465 $key = wfMemcKey( 'user', 'id', $this->mId
);
467 $cache->set( $key, $data );
470 /** @name newFrom*() static factory methods */
474 * Static factory method for creation from username.
476 * This is slightly less efficient than newFromId(), so use newFromId() if
477 * you have both an ID and a name handy.
479 * @param string $name Username, validated by Title::newFromText()
480 * @param string|bool $validate Validate username. Takes the same parameters as
481 * User::getCanonicalName(), except that true is accepted as an alias
482 * for 'valid', for BC.
484 * @return User|bool User object, or false if the username is invalid
485 * (e.g. if it contains illegal characters or is an IP address). If the
486 * username is not present in the database, the result will be a user object
487 * with a name, zero user ID and default settings.
489 public static function newFromName( $name, $validate = 'valid' ) {
490 if ( $validate === true ) {
493 $name = self
::getCanonicalName( $name, $validate );
494 if ( $name === false ) {
497 // Create unloaded user object
501 $u->setItemLoaded( 'name' );
507 * Static factory method for creation from a given user ID.
509 * @param int $id Valid user ID
510 * @return User The corresponding User object
512 public static function newFromId( $id ) {
516 $u->setItemLoaded( 'id' );
521 * Factory method to fetch whichever user has a given email confirmation code.
522 * This code is generated when an account is created or its e-mail address
525 * If the code is invalid or has expired, returns NULL.
527 * @param string $code Confirmation code
530 public static function newFromConfirmationCode( $code ) {
531 $dbr = wfGetDB( DB_SLAVE
);
532 $id = $dbr->selectField( 'user', 'user_id', array(
533 'user_email_token' => md5( $code ),
534 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
536 if ( $id !== false ) {
537 return User
::newFromId( $id );
544 * Create a new user object using data from session or cookies. If the
545 * login credentials are invalid, the result is an anonymous user.
547 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
550 public static function newFromSession( WebRequest
$request = null ) {
552 $user->mFrom
= 'session';
553 $user->mRequest
= $request;
558 * Create a new user object from a user row.
559 * The row should have the following fields from the user table in it:
560 * - either user_name or user_id to load further data if needed (or both)
562 * - all other fields (email, password, etc.)
563 * It is useless to provide the remaining fields if either user_id,
564 * user_name and user_real_name are not provided because the whole row
565 * will be loaded once more from the database when accessing them.
567 * @param stdClass $row A row from the user table
568 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
571 public static function newFromRow( $row, $data = null ) {
573 $user->loadFromRow( $row, $data );
580 * Get the username corresponding to a given user ID
581 * @param int $id User ID
582 * @return string|bool The corresponding username
584 public static function whoIs( $id ) {
585 return UserCache
::singleton()->getProp( $id, 'name' );
589 * Get the real name of a user given their user ID
591 * @param int $id User ID
592 * @return string|bool The corresponding user's real name
594 public static function whoIsReal( $id ) {
595 return UserCache
::singleton()->getProp( $id, 'real_name' );
599 * Get database id given a user name
600 * @param string $name Username
601 * @return int|null The corresponding user's ID, or null if user is nonexistent
603 public static function idFromName( $name ) {
604 $nt = Title
::makeTitleSafe( NS_USER
, $name );
605 if ( is_null( $nt ) ) {
610 if ( isset( self
::$idCacheByName[$name] ) ) {
611 return self
::$idCacheByName[$name];
614 $dbr = wfGetDB( DB_SLAVE
);
615 $s = $dbr->selectRow(
618 array( 'user_name' => $nt->getText() ),
622 if ( $s === false ) {
625 $result = $s->user_id
;
628 self
::$idCacheByName[$name] = $result;
630 if ( count( self
::$idCacheByName ) > 1000 ) {
631 self
::$idCacheByName = array();
638 * Reset the cache used in idFromName(). For use in tests.
640 public static function resetIdByNameCache() {
641 self
::$idCacheByName = array();
645 * Does the string match an anonymous IPv4 address?
647 * This function exists for username validation, in order to reject
648 * usernames which are similar in form to IP addresses. Strings such
649 * as 300.300.300.300 will return true because it looks like an IP
650 * address, despite not being strictly valid.
652 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
653 * address because the usemod software would "cloak" anonymous IP
654 * addresses like this, if we allowed accounts like this to be created
655 * new users could get the old edits of these anonymous users.
657 * @param string $name Name to match
660 public static function isIP( $name ) {
661 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
662 || IP
::isIPv6( $name );
666 * Is the input a valid username?
668 * Checks if the input is a valid username, we don't want an empty string,
669 * an IP address, anything that contains slashes (would mess up subpages),
670 * is longer than the maximum allowed username size or doesn't begin with
673 * @param string $name Name to match
676 public static function isValidUserName( $name ) {
677 global $wgContLang, $wgMaxNameChars;
680 || User
::isIP( $name )
681 ||
strpos( $name, '/' ) !== false
682 ||
strlen( $name ) > $wgMaxNameChars
683 ||
$name != $wgContLang->ucfirst( $name )
685 wfDebugLog( 'username', __METHOD__
.
686 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
690 // Ensure that the name can't be misresolved as a different title,
691 // such as with extra namespace keys at the start.
692 $parsed = Title
::newFromText( $name );
693 if ( is_null( $parsed )
694 ||
$parsed->getNamespace()
695 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
696 wfDebugLog( 'username', __METHOD__
.
697 ": '$name' invalid due to ambiguous prefixes" );
701 // Check an additional blacklist of troublemaker characters.
702 // Should these be merged into the title char list?
703 $unicodeBlacklist = '/[' .
704 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
705 '\x{00a0}' . # non-breaking space
706 '\x{2000}-\x{200f}' . # various whitespace
707 '\x{2028}-\x{202f}' . # breaks and control chars
708 '\x{3000}' . # ideographic space
709 '\x{e000}-\x{f8ff}' . # private use
711 if ( preg_match( $unicodeBlacklist, $name ) ) {
712 wfDebugLog( 'username', __METHOD__
.
713 ": '$name' invalid due to blacklisted characters" );
721 * Usernames which fail to pass this function will be blocked
722 * from user login and new account registrations, but may be used
723 * internally by batch processes.
725 * If an account already exists in this form, login will be blocked
726 * by a failure to pass this function.
728 * @param string $name Name to match
731 public static function isUsableName( $name ) {
732 global $wgReservedUsernames;
733 // Must be a valid username, obviously ;)
734 if ( !self
::isValidUserName( $name ) ) {
738 static $reservedUsernames = false;
739 if ( !$reservedUsernames ) {
740 $reservedUsernames = $wgReservedUsernames;
741 Hooks
::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
744 // Certain names may be reserved for batch processes.
745 foreach ( $reservedUsernames as $reserved ) {
746 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
747 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
749 if ( $reserved == $name ) {
757 * Usernames which fail to pass this function will be blocked
758 * from new account registrations, but may be used internally
759 * either by batch processes or by user accounts which have
760 * already been created.
762 * Additional blacklisting may be added here rather than in
763 * isValidUserName() to avoid disrupting existing accounts.
765 * @param string $name String to match
768 public static function isCreatableName( $name ) {
769 global $wgInvalidUsernameCharacters;
771 // Ensure that the username isn't longer than 235 bytes, so that
772 // (at least for the builtin skins) user javascript and css files
773 // will work. (bug 23080)
774 if ( strlen( $name ) > 235 ) {
775 wfDebugLog( 'username', __METHOD__
.
776 ": '$name' invalid due to length" );
780 // Preg yells if you try to give it an empty string
781 if ( $wgInvalidUsernameCharacters !== '' ) {
782 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
783 wfDebugLog( 'username', __METHOD__
.
784 ": '$name' invalid due to wgInvalidUsernameCharacters" );
789 return self
::isUsableName( $name );
793 * Is the input a valid password for this user?
795 * @param string $password Desired password
798 public function isValidPassword( $password ) {
799 //simple boolean wrapper for getPasswordValidity
800 return $this->getPasswordValidity( $password ) === true;
805 * Given unvalidated password input, return error message on failure.
807 * @param string $password Desired password
808 * @return bool|string|array True on success, string or array of error message on failure
810 public function getPasswordValidity( $password ) {
811 $result = $this->checkPasswordValidity( $password );
812 if ( $result->isGood() ) {
816 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
817 $messages[] = $error['message'];
819 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
820 $messages[] = $warning['message'];
822 if ( count( $messages ) === 1 ) {
830 * Check if this is a valid password for this user
832 * Create a Status object based on the password's validity.
833 * The Status should be set to fatal if the user should not
834 * be allowed to log in, and should have any errors that
835 * would block changing the password.
837 * If the return value of this is not OK, the password
838 * should not be checked. If the return value is not Good,
839 * the password can be checked, but the user should not be
840 * able to set their password to this.
842 * @param string $password Desired password
846 public function checkPasswordValidity( $password ) {
847 global $wgMinimalPasswordLength, $wgMaximalPasswordLength, $wgContLang;
849 static $blockedLogins = array(
850 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
851 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
854 $status = Status
::newGood();
856 $result = false; //init $result to false for the internal checks
858 if ( !Hooks
::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
859 $status->error( $result );
863 if ( $result === false ) {
864 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
865 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
867 } elseif ( strlen( $password ) > $wgMaximalPasswordLength ) {
868 // T64685: Password too long, might cause DoS attack
869 $status->fatal( 'passwordtoolong', $wgMaximalPasswordLength );
871 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
872 $status->error( 'password-name-match' );
874 } elseif ( isset( $blockedLogins[$this->getName()] )
875 && $password == $blockedLogins[$this->getName()]
877 $status->error( 'password-login-forbidden' );
880 //it seems weird returning a Good status here, but this is because of the
881 //initialization of $result to false above. If the hook is never run or it
882 //doesn't modify $result, then we will likely get down into this if with
886 } elseif ( $result === true ) {
889 $status->error( $result );
890 return $status; //the isValidPassword hook set a string $result and returned true
895 * Expire a user's password
897 * @param int $ts Optional timestamp to convert, default 0 for the current time
899 public function expirePassword( $ts = 0 ) {
900 $this->loadPasswords();
901 $timestamp = wfTimestamp( TS_MW
, $ts );
902 $this->mPasswordExpires
= $timestamp;
903 $this->saveSettings();
907 * Clear the password expiration for a user
909 * @param bool $load Ensure user object is loaded first
911 public function resetPasswordExpiration( $load = true ) {
912 global $wgPasswordExpirationDays;
917 if ( $wgPasswordExpirationDays ) {
918 $newExpire = wfTimestamp(
920 time() +
( $wgPasswordExpirationDays * 24 * 3600 )
923 // Give extensions a chance to force an expiration
924 Hooks
::run( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
925 $this->mPasswordExpires
= $newExpire;
929 * Check if the user's password is expired.
930 * TODO: Put this and password length into a PasswordPolicy object
932 * @return string|bool The expiration type, or false if not expired
933 * hard: A password change is required to login
934 * soft: Allow login, but encourage password change
935 * false: Password is not expired
937 public function getPasswordExpired() {
938 global $wgPasswordExpireGrace;
940 $now = wfTimestamp();
941 $expiration = $this->getPasswordExpireDate();
942 $expUnix = wfTimestamp( TS_UNIX
, $expiration );
943 if ( $expiration !== null && $expUnix < $now ) {
944 $expired = ( $expUnix +
$wgPasswordExpireGrace < $now ) ?
'hard' : 'soft';
950 * Get this user's password expiration date. Since this may be using
951 * the cached User object, we assume that whatever mechanism is setting
952 * the expiration date is also expiring the User cache.
954 * @return string|bool The datestamp of the expiration, or null if not set
956 public function getPasswordExpireDate() {
958 return $this->mPasswordExpires
;
962 * Given unvalidated user input, return a canonical username, or false if
963 * the username is invalid.
964 * @param string $name User input
965 * @param string|bool $validate Type of validation to use:
966 * - false No validation
967 * - 'valid' Valid for batch processes
968 * - 'usable' Valid for batch processes and login
969 * - 'creatable' Valid for batch processes, login and account creation
971 * @throws MWException
972 * @return bool|string
974 public static function getCanonicalName( $name, $validate = 'valid' ) {
975 // Force usernames to capital
977 $name = $wgContLang->ucfirst( $name );
979 # Reject names containing '#'; these will be cleaned up
980 # with title normalisation, but then it's too late to
982 if ( strpos( $name, '#' ) !== false ) {
986 // Clean up name according to title rules,
987 // but only when validation is requested (bug 12654)
988 $t = ( $validate !== false ) ?
989 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
990 // Check for invalid titles
991 if ( is_null( $t ) ) {
995 // Reject various classes of invalid names
997 $name = $wgAuth->getCanonicalName( $t->getText() );
999 switch ( $validate ) {
1003 if ( !User
::isValidUserName( $name ) ) {
1008 if ( !User
::isUsableName( $name ) ) {
1013 if ( !User
::isCreatableName( $name ) ) {
1018 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
1024 * Count the number of edits of a user
1026 * @param int $uid User ID to check
1027 * @return int The user's edit count
1029 * @deprecated since 1.21 in favour of User::getEditCount
1031 public static function edits( $uid ) {
1032 wfDeprecated( __METHOD__
, '1.21' );
1033 $user = self
::newFromId( $uid );
1034 return $user->getEditCount();
1038 * Return a random password.
1040 * @return string New random password
1042 public static function randomPassword() {
1043 global $wgMinimalPasswordLength;
1044 // Decide the final password length based on our min password length,
1045 // stopping at a minimum of 10 chars.
1046 $length = max( 10, $wgMinimalPasswordLength );
1047 // Multiply by 1.25 to get the number of hex characters we need
1048 $length = $length * 1.25;
1049 // Generate random hex chars
1050 $hex = MWCryptRand
::generateHex( $length );
1051 // Convert from base 16 to base 32 to get a proper password like string
1052 return wfBaseConvert( $hex, 16, 32 );
1056 * Set cached properties to default.
1058 * @note This no longer clears uncached lazy-initialised properties;
1059 * the constructor does that instead.
1061 * @param string|bool $name
1063 public function loadDefaults( $name = false ) {
1065 $passwordFactory = self
::getPasswordFactory();
1068 $this->mName
= $name;
1069 $this->mRealName
= '';
1070 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1071 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1072 $this->mNewpassTime
= null;
1074 $this->mOptionOverrides
= null;
1075 $this->mOptionsLoaded
= false;
1077 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1078 if ( $loggedOut !== null ) {
1079 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1081 $this->mTouched
= '1'; # Allow any pages to be cached
1084 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1085 $this->mEmailAuthenticated
= null;
1086 $this->mEmailToken
= '';
1087 $this->mEmailTokenExpires
= null;
1088 $this->mPasswordExpires
= null;
1089 $this->resetPasswordExpiration( false );
1090 $this->mRegistration
= wfTimestamp( TS_MW
);
1091 $this->mGroups
= array();
1093 Hooks
::run( 'UserLoadDefaults', array( $this, $name ) );
1097 * Return whether an item has been loaded.
1099 * @param string $item Item to check. Current possibilities:
1103 * @param string $all 'all' to check if the whole object has been loaded
1104 * or any other string to check if only the item is available (e.g.
1108 public function isItemLoaded( $item, $all = 'all' ) {
1109 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1110 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1114 * Set that an item has been loaded
1116 * @param string $item
1118 protected function setItemLoaded( $item ) {
1119 if ( is_array( $this->mLoadedItems
) ) {
1120 $this->mLoadedItems
[$item] = true;
1125 * Load user data from the session or login cookie.
1127 * @return bool True if the user is logged in, false otherwise.
1129 private function loadFromSession() {
1131 Hooks
::run( 'UserLoadFromSession', array( $this, &$result ) );
1132 if ( $result !== null ) {
1136 $request = $this->getRequest();
1138 $cookieId = $request->getCookie( 'UserID' );
1139 $sessId = $request->getSessionData( 'wsUserID' );
1141 if ( $cookieId !== null ) {
1142 $sId = intval( $cookieId );
1143 if ( $sessId !== null && $cookieId != $sessId ) {
1144 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1145 cookie user ID ($sId) don't match!" );
1148 $request->setSessionData( 'wsUserID', $sId );
1149 } elseif ( $sessId !== null && $sessId != 0 ) {
1155 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1156 $sName = $request->getSessionData( 'wsUserName' );
1157 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1158 $sName = $request->getCookie( 'UserName' );
1159 $request->setSessionData( 'wsUserName', $sName );
1164 $proposedUser = User
::newFromId( $sId );
1165 $proposedUser->load( self
::READ_LATEST
);
1166 if ( !$proposedUser->isLoggedIn() ) {
1171 global $wgBlockDisablesLogin;
1172 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1173 // User blocked and we've disabled blocked user logins
1177 if ( $request->getSessionData( 'wsToken' ) ) {
1179 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1181 } elseif ( $request->getCookie( 'Token' ) ) {
1182 # Get the token from DB/cache and clean it up to remove garbage padding.
1183 # This deals with historical problems with bugs and the default column value.
1184 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1185 // Make comparison in constant time (bug 61346)
1186 $passwordCorrect = strlen( $token )
1187 && hash_equals( $token, $request->getCookie( 'Token' ) );
1190 // No session or persistent login cookie
1194 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1195 $this->loadFromUserObject( $proposedUser );
1196 $request->setSessionData( 'wsToken', $this->mToken
);
1197 wfDebug( "User: logged in from $from\n" );
1200 // Invalid credentials
1201 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1207 * Load user and user_group data from the database.
1208 * $this->mId must be set, this is how the user is identified.
1210 * @param integer $flags User::READ_* constant bitfield
1211 * @return bool True if the user exists, false if the user is anonymous
1213 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1215 $this->mId
= intval( $this->mId
);
1218 if ( !$this->mId
) {
1219 $this->loadDefaults();
1223 $db = ( $flags & self
::READ_LATEST
)
1224 ?
wfGetDB( DB_MASTER
)
1225 : wfGetDB( DB_SLAVE
);
1227 $s = $db->selectRow(
1229 self
::selectFields(),
1230 array( 'user_id' => $this->mId
),
1232 ( $flags & self
::READ_LOCKING
== self
::READ_LOCKING
)
1233 ?
array( 'LOCK IN SHARE MODE' )
1237 $this->queryFlagsUsed
= $flags;
1238 Hooks
::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1240 if ( $s !== false ) {
1241 // Initialise user table data
1242 $this->loadFromRow( $s );
1243 $this->mGroups
= null; // deferred
1244 $this->getEditCount(); // revalidation for nulls
1249 $this->loadDefaults();
1255 * Initialize this object from a row from the user table.
1257 * @param stdClass $row Row from the user table to load.
1258 * @param array $data Further user data to load into the object
1260 * user_groups Array with groups out of the user_groups table
1261 * user_properties Array with properties out of the user_properties table
1263 protected function loadFromRow( $row, $data = null ) {
1265 $passwordFactory = self
::getPasswordFactory();
1267 $this->mGroups
= null; // deferred
1269 if ( isset( $row->user_name
) ) {
1270 $this->mName
= $row->user_name
;
1271 $this->mFrom
= 'name';
1272 $this->setItemLoaded( 'name' );
1277 if ( isset( $row->user_real_name
) ) {
1278 $this->mRealName
= $row->user_real_name
;
1279 $this->setItemLoaded( 'realname' );
1284 if ( isset( $row->user_id
) ) {
1285 $this->mId
= intval( $row->user_id
);
1286 $this->mFrom
= 'id';
1287 $this->setItemLoaded( 'id' );
1292 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1293 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1296 if ( isset( $row->user_editcount
) ) {
1297 $this->mEditCount
= $row->user_editcount
;
1302 if ( isset( $row->user_password
) ) {
1303 // Check for *really* old password hashes that don't even have a type
1304 // The old hash format was just an md5 hex hash, with no type information
1305 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password
) ) {
1306 $row->user_password
= ":A:{$this->mId}:{$row->user_password}";
1310 $this->mPassword
= $passwordFactory->newFromCiphertext( $row->user_password
);
1311 } catch ( PasswordError
$e ) {
1312 wfDebug( 'Invalid password hash found in database.' );
1313 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1317 $this->mNewpassword
= $passwordFactory->newFromCiphertext( $row->user_newpassword
);
1318 } catch ( PasswordError
$e ) {
1319 wfDebug( 'Invalid password hash found in database.' );
1320 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1323 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1324 $this->mPasswordExpires
= wfTimestampOrNull( TS_MW
, $row->user_password_expires
);
1327 if ( isset( $row->user_email
) ) {
1328 $this->mEmail
= $row->user_email
;
1329 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1330 $this->mToken
= $row->user_token
;
1331 if ( $this->mToken
== '' ) {
1332 $this->mToken
= null;
1334 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1335 $this->mEmailToken
= $row->user_email_token
;
1336 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1337 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1343 $this->mLoadedItems
= true;
1346 if ( is_array( $data ) ) {
1347 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1348 $this->mGroups
= $data['user_groups'];
1350 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1351 $this->loadOptions( $data['user_properties'] );
1357 * Load the data for this user object from another user object.
1361 protected function loadFromUserObject( $user ) {
1363 $user->loadGroups();
1364 $user->loadOptions();
1365 foreach ( self
::$mCacheVars as $var ) {
1366 $this->$var = $user->$var;
1371 * Load the groups from the database if they aren't already loaded.
1373 private function loadGroups() {
1374 if ( is_null( $this->mGroups
) ) {
1375 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1376 ?
wfGetDB( DB_MASTER
)
1377 : wfGetDB( DB_SLAVE
);
1378 $res = $db->select( 'user_groups',
1379 array( 'ug_group' ),
1380 array( 'ug_user' => $this->mId
),
1382 $this->mGroups
= array();
1383 foreach ( $res as $row ) {
1384 $this->mGroups
[] = $row->ug_group
;
1390 * Load the user's password hashes from the database
1392 * This is usually called in a scenario where the actual User object was
1393 * loaded from the cache, and then password comparison needs to be performed.
1394 * Password hashes are not stored in memcached.
1398 private function loadPasswords() {
1399 if ( $this->getId() !== 0 &&
1400 ( $this->mPassword
=== null ||
$this->mNewpassword
=== null )
1402 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1403 ?
wfGetDB( DB_MASTER
)
1404 : wfGetDB( DB_SLAVE
);
1406 $this->loadFromRow( $db->selectRow(
1408 array( 'user_password', 'user_newpassword',
1409 'user_newpass_time', 'user_password_expires' ),
1410 array( 'user_id' => $this->getId() ),
1417 * Add the user to the group if he/she meets given criteria.
1419 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1420 * possible to remove manually via Special:UserRights. In such case it
1421 * will not be re-added automatically. The user will also not lose the
1422 * group if they no longer meet the criteria.
1424 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1426 * @return array Array of groups the user has been promoted to.
1428 * @see $wgAutopromoteOnce
1430 public function addAutopromoteOnceGroups( $event ) {
1431 global $wgAutopromoteOnceLogInRC, $wgAuth;
1433 if ( wfReadOnly() ||
!$this->getId() ) {
1437 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1438 if ( !count( $toPromote ) ) {
1442 if ( !$this->checkAndSetTouched() ) {
1443 return array(); // raced out (bug T48834)
1446 $oldGroups = $this->getGroups(); // previous groups
1447 foreach ( $toPromote as $group ) {
1448 $this->addGroup( $group );
1451 // update groups in external authentication database
1452 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1454 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1456 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1457 $logEntry->setPerformer( $this );
1458 $logEntry->setTarget( $this->getUserPage() );
1459 $logEntry->setParameters( array(
1460 '4::oldgroups' => $oldGroups,
1461 '5::newgroups' => $newGroups,
1463 $logid = $logEntry->insert();
1464 if ( $wgAutopromoteOnceLogInRC ) {
1465 $logEntry->publish( $logid );
1472 * Bump user_touched if it didn't change since this object was loaded
1474 * On success, the mTouched field is updated.
1475 * The user serialization cache is always cleared.
1477 * @return bool Whether user_touched was actually updated
1480 protected function checkAndSetTouched() {
1483 if ( !$this->mId
) {
1484 return false; // anon
1487 // Get a new user_touched that is higher than the old one
1488 $oldTouched = $this->mTouched
;
1489 $newTouched = $this->newTouchedTimestamp();
1491 $dbw = wfGetDB( DB_MASTER
);
1492 $dbw->update( 'user',
1493 array( 'user_touched' => $dbw->timestamp( $newTouched ) ),
1495 'user_id' => $this->mId
,
1496 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1500 $success = ( $dbw->affectedRows() > 0 );
1503 $this->mTouched
= $newTouched;
1506 // Clears on failure too since that is desired if the cache is stale
1507 $this->clearSharedCache();
1513 * Clear various cached data stored in this object. The cache of the user table
1514 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1516 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1517 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1519 public function clearInstanceCache( $reloadFrom = false ) {
1520 $this->mNewtalk
= -1;
1521 $this->mDatePreference
= null;
1522 $this->mBlockedby
= -1; # Unset
1523 $this->mHash
= false;
1524 $this->mRights
= null;
1525 $this->mEffectiveGroups
= null;
1526 $this->mImplicitGroups
= null;
1527 $this->mGroups
= null;
1528 $this->mOptions
= null;
1529 $this->mOptionsLoaded
= false;
1530 $this->mEditCount
= null;
1532 if ( $reloadFrom ) {
1533 $this->mLoadedItems
= array();
1534 $this->mFrom
= $reloadFrom;
1539 * Combine the language default options with any site-specific options
1540 * and add the default language variants.
1542 * @return array Array of String options
1544 public static function getDefaultOptions() {
1545 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1547 static $defOpt = null;
1548 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1549 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1550 // mid-request and see that change reflected in the return value of this function.
1551 // Which is insane and would never happen during normal MW operation
1555 $defOpt = $wgDefaultUserOptions;
1556 // Default language setting
1557 $defOpt['language'] = $wgContLang->getCode();
1558 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1559 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1561 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1562 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1564 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1566 Hooks
::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1572 * Get a given default option value.
1574 * @param string $opt Name of option to retrieve
1575 * @return string Default option value
1577 public static function getDefaultOption( $opt ) {
1578 $defOpts = self
::getDefaultOptions();
1579 if ( isset( $defOpts[$opt] ) ) {
1580 return $defOpts[$opt];
1587 * Get blocking information
1588 * @param bool $bFromSlave Whether to check the slave database first.
1589 * To improve performance, non-critical checks are done against slaves.
1590 * Check when actually saving should be done against master.
1592 private function getBlockedStatus( $bFromSlave = true ) {
1593 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1595 if ( -1 != $this->mBlockedby
) {
1599 wfDebug( __METHOD__
. ": checking...\n" );
1601 // Initialize data...
1602 // Otherwise something ends up stomping on $this->mBlockedby when
1603 // things get lazy-loaded later, causing false positive block hits
1604 // due to -1 !== 0. Probably session-related... Nothing should be
1605 // overwriting mBlockedby, surely?
1608 # We only need to worry about passing the IP address to the Block generator if the
1609 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1610 # know which IP address they're actually coming from
1611 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1612 $ip = $this->getRequest()->getIP();
1618 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1621 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1622 && !in_array( $ip, $wgProxyWhitelist )
1625 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1627 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1628 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1629 $block->setTarget( $ip );
1630 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1632 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1633 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1634 $block->setTarget( $ip );
1638 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1639 if ( !$block instanceof Block
1640 && $wgApplyIpBlocksToXff
1642 && !$this->isAllowed( 'proxyunbannable' )
1643 && !in_array( $ip, $wgProxyWhitelist )
1645 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1646 $xff = array_map( 'trim', explode( ',', $xff ) );
1647 $xff = array_diff( $xff, array( $ip ) );
1648 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1649 $block = Block
::chooseBlock( $xffblocks, $xff );
1650 if ( $block instanceof Block
) {
1651 # Mangle the reason to alert the user that the block
1652 # originated from matching the X-Forwarded-For header.
1653 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1657 if ( $block instanceof Block
) {
1658 wfDebug( __METHOD__
. ": Found block.\n" );
1659 $this->mBlock
= $block;
1660 $this->mBlockedby
= $block->getByName();
1661 $this->mBlockreason
= $block->mReason
;
1662 $this->mHideName
= $block->mHideName
;
1663 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1665 $this->mBlockedby
= '';
1666 $this->mHideName
= 0;
1667 $this->mAllowUsertalk
= false;
1671 Hooks
::run( 'GetBlockedStatus', array( &$this ) );
1676 * Whether the given IP is in a DNS blacklist.
1678 * @param string $ip IP to check
1679 * @param bool $checkWhitelist Whether to check the whitelist first
1680 * @return bool True if blacklisted.
1682 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1683 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1685 if ( !$wgEnableDnsBlacklist ) {
1689 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1693 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1697 * Whether the given IP is in a given DNS blacklist.
1699 * @param string $ip IP to check
1700 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1701 * @return bool True if blacklisted.
1703 public function inDnsBlacklist( $ip, $bases ) {
1706 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1707 if ( IP
::isIPv4( $ip ) ) {
1708 // Reverse IP, bug 21255
1709 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1711 foreach ( (array)$bases as $base ) {
1713 // If we have an access key, use that too (ProjectHoneypot, etc.)
1714 if ( is_array( $base ) ) {
1715 if ( count( $base ) >= 2 ) {
1716 // Access key is 1, base URL is 0
1717 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1719 $host = "$ipReversed.{$base[0]}";
1722 $host = "$ipReversed.$base";
1726 $ipList = gethostbynamel( $host );
1729 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1733 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1742 * Check if an IP address is in the local proxy list
1748 public static function isLocallyBlockedProxy( $ip ) {
1749 global $wgProxyList;
1751 if ( !$wgProxyList ) {
1755 if ( !is_array( $wgProxyList ) ) {
1756 // Load from the specified file
1757 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1760 if ( !is_array( $wgProxyList ) ) {
1762 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1764 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1765 // Old-style flipped proxy list
1774 * Is this user subject to rate limiting?
1776 * @return bool True if rate limited
1778 public function isPingLimitable() {
1779 global $wgRateLimitsExcludedIPs;
1780 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1781 // No other good way currently to disable rate limits
1782 // for specific IPs. :P
1783 // But this is a crappy hack and should die.
1786 return !$this->isAllowed( 'noratelimit' );
1790 * Primitive rate limits: enforce maximum actions per time period
1791 * to put a brake on flooding.
1793 * The method generates both a generic profiling point and a per action one
1794 * (suffix being "-$action".
1796 * @note When using a shared cache like memcached, IP-address
1797 * last-hit counters will be shared across wikis.
1799 * @param string $action Action to enforce; 'edit' if unspecified
1800 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1801 * @return bool True if a rate limiter was tripped
1803 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1804 // Call the 'PingLimiter' hook
1806 if ( !Hooks
::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1810 global $wgRateLimits;
1811 if ( !isset( $wgRateLimits[$action] ) ) {
1815 // Some groups shouldn't trigger the ping limiter, ever
1816 if ( !$this->isPingLimitable() ) {
1822 $limits = $wgRateLimits[$action];
1824 $id = $this->getId();
1827 if ( isset( $limits['anon'] ) && $id == 0 ) {
1828 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1831 if ( isset( $limits['user'] ) && $id != 0 ) {
1832 $userLimit = $limits['user'];
1834 if ( $this->isNewbie() ) {
1835 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1836 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1838 if ( isset( $limits['ip'] ) ) {
1839 $ip = $this->getRequest()->getIP();
1840 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1842 if ( isset( $limits['subnet'] ) ) {
1843 $ip = $this->getRequest()->getIP();
1846 if ( IP
::isIPv6( $ip ) ) {
1847 $parts = IP
::parseRange( "$ip/64" );
1848 $subnet = $parts[0];
1849 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1851 $subnet = $matches[1];
1853 if ( $subnet !== false ) {
1854 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1858 // Check for group-specific permissions
1859 // If more than one group applies, use the group with the highest limit
1860 foreach ( $this->getGroups() as $group ) {
1861 if ( isset( $limits[$group] ) ) {
1862 if ( $userLimit === false
1863 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1865 $userLimit = $limits[$group];
1869 // Set the user limit key
1870 if ( $userLimit !== false ) {
1871 list( $max, $period ) = $userLimit;
1872 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1873 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1877 foreach ( $keys as $key => $limit ) {
1878 list( $max, $period ) = $limit;
1879 $summary = "(limit $max in {$period}s)";
1880 $count = $wgMemc->get( $key );
1883 if ( $count >= $max ) {
1884 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1885 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1888 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1891 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1892 if ( $incrBy > 0 ) {
1893 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1896 if ( $incrBy > 0 ) {
1897 $wgMemc->incr( $key, $incrBy );
1905 * Check if user is blocked
1907 * @param bool $bFromSlave Whether to check the slave database instead of
1908 * the master. Hacked from false due to horrible probs on site.
1909 * @return bool True if blocked, false otherwise
1911 public function isBlocked( $bFromSlave = true ) {
1912 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1916 * Get the block affecting the user, or null if the user is not blocked
1918 * @param bool $bFromSlave Whether to check the slave database instead of the master
1919 * @return Block|null
1921 public function getBlock( $bFromSlave = true ) {
1922 $this->getBlockedStatus( $bFromSlave );
1923 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1927 * Check if user is blocked from editing a particular article
1929 * @param Title $title Title to check
1930 * @param bool $bFromSlave Whether to check the slave database instead of the master
1933 public function isBlockedFrom( $title, $bFromSlave = false ) {
1934 global $wgBlockAllowsUTEdit;
1936 $blocked = $this->isBlocked( $bFromSlave );
1937 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1938 // If a user's name is suppressed, they cannot make edits anywhere
1939 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1940 && $title->getNamespace() == NS_USER_TALK
) {
1942 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1945 Hooks
::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1951 * If user is blocked, return the name of the user who placed the block
1952 * @return string Name of blocker
1954 public function blockedBy() {
1955 $this->getBlockedStatus();
1956 return $this->mBlockedby
;
1960 * If user is blocked, return the specified reason for the block
1961 * @return string Blocking reason
1963 public function blockedFor() {
1964 $this->getBlockedStatus();
1965 return $this->mBlockreason
;
1969 * If user is blocked, return the ID for the block
1970 * @return int Block ID
1972 public function getBlockId() {
1973 $this->getBlockedStatus();
1974 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1978 * Check if user is blocked on all wikis.
1979 * Do not use for actual edit permission checks!
1980 * This is intended for quick UI checks.
1982 * @param string $ip IP address, uses current client if none given
1983 * @return bool True if blocked, false otherwise
1985 public function isBlockedGlobally( $ip = '' ) {
1986 if ( $this->mBlockedGlobally
!== null ) {
1987 return $this->mBlockedGlobally
;
1989 // User is already an IP?
1990 if ( IP
::isIPAddress( $this->getName() ) ) {
1991 $ip = $this->getName();
1993 $ip = $this->getRequest()->getIP();
1996 Hooks
::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1997 $this->mBlockedGlobally
= (bool)$blocked;
1998 return $this->mBlockedGlobally
;
2002 * Check if user account is locked
2004 * @return bool True if locked, false otherwise
2006 public function isLocked() {
2007 if ( $this->mLocked
!== null ) {
2008 return $this->mLocked
;
2011 $authUser = $wgAuth->getUserInstance( $this );
2012 $this->mLocked
= (bool)$authUser->isLocked();
2013 return $this->mLocked
;
2017 * Check if user account is hidden
2019 * @return bool True if hidden, false otherwise
2021 public function isHidden() {
2022 if ( $this->mHideName
!== null ) {
2023 return $this->mHideName
;
2025 $this->getBlockedStatus();
2026 if ( !$this->mHideName
) {
2028 $authUser = $wgAuth->getUserInstance( $this );
2029 $this->mHideName
= (bool)$authUser->isHidden();
2031 return $this->mHideName
;
2035 * Get the user's ID.
2036 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2038 public function getId() {
2039 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2040 // Special case, we know the user is anonymous
2042 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2043 // Don't load if this was initialized from an ID
2050 * Set the user and reload all fields according to a given ID
2051 * @param int $v User ID to reload
2053 public function setId( $v ) {
2055 $this->clearInstanceCache( 'id' );
2059 * Get the user name, or the IP of an anonymous user
2060 * @return string User's name or IP address
2062 public function getName() {
2063 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2064 // Special case optimisation
2065 return $this->mName
;
2068 if ( $this->mName
=== false ) {
2070 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2072 return $this->mName
;
2077 * Set the user name.
2079 * This does not reload fields from the database according to the given
2080 * name. Rather, it is used to create a temporary "nonexistent user" for
2081 * later addition to the database. It can also be used to set the IP
2082 * address for an anonymous user to something other than the current
2085 * @note User::newFromName() has roughly the same function, when the named user
2087 * @param string $str New user name to set
2089 public function setName( $str ) {
2091 $this->mName
= $str;
2095 * Get the user's name escaped by underscores.
2096 * @return string Username escaped by underscores.
2098 public function getTitleKey() {
2099 return str_replace( ' ', '_', $this->getName() );
2103 * Check if the user has new messages.
2104 * @return bool True if the user has new messages
2106 public function getNewtalk() {
2109 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2110 if ( $this->mNewtalk
=== -1 ) {
2111 $this->mNewtalk
= false; # reset talk page status
2113 // Check memcached separately for anons, who have no
2114 // entire User object stored in there.
2115 if ( !$this->mId
) {
2116 global $wgDisableAnonTalk;
2117 if ( $wgDisableAnonTalk ) {
2118 // Anon newtalk disabled by configuration.
2119 $this->mNewtalk
= false;
2121 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2124 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2128 return (bool)$this->mNewtalk
;
2132 * Return the data needed to construct links for new talk page message
2133 * alerts. If there are new messages, this will return an associative array
2134 * with the following data:
2135 * wiki: The database name of the wiki
2136 * link: Root-relative link to the user's talk page
2137 * rev: The last talk page revision that the user has seen or null. This
2138 * is useful for building diff links.
2139 * If there are no new messages, it returns an empty array.
2140 * @note This function was designed to accomodate multiple talk pages, but
2141 * currently only returns a single link and revision.
2144 public function getNewMessageLinks() {
2146 if ( !Hooks
::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2148 } elseif ( !$this->getNewtalk() ) {
2151 $utp = $this->getTalkPage();
2152 $dbr = wfGetDB( DB_SLAVE
);
2153 // Get the "last viewed rev" timestamp from the oldest message notification
2154 $timestamp = $dbr->selectField( 'user_newtalk',
2155 'MIN(user_last_timestamp)',
2156 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2158 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2159 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2163 * Get the revision ID for the last talk page revision viewed by the talk
2165 * @return int|null Revision ID or null
2167 public function getNewMessageRevisionId() {
2168 $newMessageRevisionId = null;
2169 $newMessageLinks = $this->getNewMessageLinks();
2170 if ( $newMessageLinks ) {
2171 // Note: getNewMessageLinks() never returns more than a single link
2172 // and it is always for the same wiki, but we double-check here in
2173 // case that changes some time in the future.
2174 if ( count( $newMessageLinks ) === 1
2175 && $newMessageLinks[0]['wiki'] === wfWikiID()
2176 && $newMessageLinks[0]['rev']
2178 $newMessageRevision = $newMessageLinks[0]['rev'];
2179 $newMessageRevisionId = $newMessageRevision->getId();
2182 return $newMessageRevisionId;
2186 * Internal uncached check for new messages
2189 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2190 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2191 * @return bool True if the user has new messages
2193 protected function checkNewtalk( $field, $id ) {
2194 $dbr = wfGetDB( DB_SLAVE
);
2196 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__
);
2198 return $ok !== false;
2202 * Add or update the new messages flag
2203 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2204 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2205 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2206 * @return bool True if successful, false otherwise
2208 protected function updateNewtalk( $field, $id, $curRev = null ) {
2209 // Get timestamp of the talk page revision prior to the current one
2210 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2211 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2212 // Mark the user as having new messages since this revision
2213 $dbw = wfGetDB( DB_MASTER
);
2214 $dbw->insert( 'user_newtalk',
2215 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2218 if ( $dbw->affectedRows() ) {
2219 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2222 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2228 * Clear the new messages flag for the given user
2229 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2230 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2231 * @return bool True if successful, false otherwise
2233 protected function deleteNewtalk( $field, $id ) {
2234 $dbw = wfGetDB( DB_MASTER
);
2235 $dbw->delete( 'user_newtalk',
2236 array( $field => $id ),
2238 if ( $dbw->affectedRows() ) {
2239 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2242 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2248 * Update the 'You have new messages!' status.
2249 * @param bool $val Whether the user has new messages
2250 * @param Revision $curRev New, as yet unseen revision of the user talk
2251 * page. Ignored if null or !$val.
2253 public function setNewtalk( $val, $curRev = null ) {
2254 if ( wfReadOnly() ) {
2259 $this->mNewtalk
= $val;
2261 if ( $this->isAnon() ) {
2263 $id = $this->getName();
2266 $id = $this->getId();
2270 $changed = $this->updateNewtalk( $field, $id, $curRev );
2272 $changed = $this->deleteNewtalk( $field, $id );
2276 $this->invalidateCache();
2281 * Generate a current or new-future timestamp to be stored in the
2282 * user_touched field when we update things.
2283 * @return string Timestamp in TS_MW format
2285 private function newTouchedTimestamp() {
2286 global $wgClockSkewFudge;
2288 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2289 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2290 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2297 * Clear user data from memcached.
2298 * Use after applying fun updates to the database; caller's
2299 * responsibility to update user_touched if appropriate.
2301 * Called implicitly from invalidateCache() and saveSettings().
2303 public function clearSharedCache() {
2304 $id = $this->getId();
2306 $cache = ObjectCache
::getMainWANInstance();
2307 $cache->delete( wfMemcKey( 'user', 'id', $id ) );
2312 * Immediately touch the user data cache for this account
2314 * Calls touch() and removes account data from memcached
2316 public function invalidateCache() {
2318 $this->clearSharedCache();
2322 * Update the "touched" timestamp for the user
2324 * This is useful on various login/logout events when making sure that
2325 * a browser or proxy that has multiple tenants does not suffer cache
2326 * pollution where the new user sees the old users content. The value
2327 * of getTouched() is checked when determining 304 vs 200 responses.
2328 * Unlike invalidateCache(), this preserves the User object cache and
2329 * avoids database writes.
2333 public function touch() {
2337 $this->mQuickTouched
= $this->newTouchedTimestamp();
2339 $cache = ObjectCache
::getMainWANInstance();
2340 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2341 $cache->touchCheckKey( $key );
2346 * Validate the cache for this account.
2347 * @param string $timestamp A timestamp in TS_MW format
2350 public function validateCache( $timestamp ) {
2351 return ( $timestamp >= $this->getTouched() );
2355 * Get the user touched timestamp
2356 * @return string TS_MW Timestamp
2358 public function getTouched() {
2362 if ( $this->mQuickTouched
=== null ) {
2363 $cache = ObjectCache
::getMainWANInstance();
2364 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2366 $timestamp = $cache->getCheckKeyTime( $key );
2368 $this->mQuickTouched
= wfTimestamp( TS_MW
, $timestamp );
2370 # Set the timestamp to get HTTP 304 cache hits
2375 return max( $this->mTouched
, $this->mQuickTouched
);
2378 return $this->mTouched
;
2382 * Get the user_touched timestamp field (time of last DB updates)
2383 * @return string TS_MW Timestamp
2386 protected function getDBTouched() {
2389 return $this->mTouched
;
2396 public function getPassword() {
2397 $this->loadPasswords();
2399 return $this->mPassword
;
2406 public function getTemporaryPassword() {
2407 $this->loadPasswords();
2409 return $this->mNewpassword
;
2413 * Set the password and reset the random token.
2414 * Calls through to authentication plugin if necessary;
2415 * will have no effect if the auth plugin refuses to
2416 * pass the change through or if the legal password
2419 * As a special case, setting the password to null
2420 * wipes it, so the account cannot be logged in until
2421 * a new password is set, for instance via e-mail.
2423 * @param string $str New password to set
2424 * @throws PasswordError On failure
2428 public function setPassword( $str ) {
2431 $this->loadPasswords();
2433 if ( $str !== null ) {
2434 if ( !$wgAuth->allowPasswordChange() ) {
2435 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2438 $status = $this->checkPasswordValidity( $str );
2439 if ( !$status->isGood() ) {
2440 throw new PasswordError( $status->getMessage()->text() );
2444 if ( !$wgAuth->setPassword( $this, $str ) ) {
2445 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2448 $this->setInternalPassword( $str );
2454 * Set the password and reset the random token unconditionally.
2456 * @param string|null $str New password to set or null to set an invalid
2457 * password hash meaning that the user will not be able to log in
2458 * through the web interface.
2460 public function setInternalPassword( $str ) {
2463 $passwordFactory = self
::getPasswordFactory();
2464 $this->mPassword
= $passwordFactory->newFromPlaintext( $str );
2466 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
2467 $this->mNewpassTime
= null;
2471 * Get the user's current token.
2472 * @param bool $forceCreation Force the generation of a new token if the
2473 * user doesn't have one (default=true for backwards compatibility).
2474 * @return string Token
2476 public function getToken( $forceCreation = true ) {
2478 if ( !$this->mToken
&& $forceCreation ) {
2481 return $this->mToken
;
2485 * Set the random token (used for persistent authentication)
2486 * Called from loadDefaults() among other places.
2488 * @param string|bool $token If specified, set the token to this value
2490 public function setToken( $token = false ) {
2493 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2495 $this->mToken
= $token;
2500 * Set the password for a password reminder or new account email
2502 * @param string $str New password to set or null to set an invalid
2503 * password hash meaning that the user will not be able to use it
2504 * @param bool $throttle If true, reset the throttle timestamp to the present
2506 public function setNewpassword( $str, $throttle = true ) {
2507 $this->loadPasswords();
2509 $this->mNewpassword
= self
::getPasswordFactory()->newFromPlaintext( $str );
2510 if ( $str === null ) {
2511 $this->mNewpassTime
= null;
2512 } elseif ( $throttle ) {
2513 $this->mNewpassTime
= wfTimestampNow();
2518 * Has password reminder email been sent within the last
2519 * $wgPasswordReminderResendTime hours?
2522 public function isPasswordReminderThrottled() {
2523 global $wgPasswordReminderResendTime;
2525 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2528 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2529 return time() < $expiry;
2533 * Get the user's e-mail address
2534 * @return string User's email address
2536 public function getEmail() {
2538 Hooks
::run( 'UserGetEmail', array( $this, &$this->mEmail
) );
2539 return $this->mEmail
;
2543 * Get the timestamp of the user's e-mail authentication
2544 * @return string TS_MW timestamp
2546 public function getEmailAuthenticationTimestamp() {
2548 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2549 return $this->mEmailAuthenticated
;
2553 * Set the user's e-mail address
2554 * @param string $str New e-mail address
2556 public function setEmail( $str ) {
2558 if ( $str == $this->mEmail
) {
2561 $this->invalidateEmail();
2562 $this->mEmail
= $str;
2563 Hooks
::run( 'UserSetEmail', array( $this, &$this->mEmail
) );
2567 * Set the user's e-mail address and a confirmation mail if needed.
2570 * @param string $str New e-mail address
2573 public function setEmailWithConfirmation( $str ) {
2574 global $wgEnableEmail, $wgEmailAuthentication;
2576 if ( !$wgEnableEmail ) {
2577 return Status
::newFatal( 'emaildisabled' );
2580 $oldaddr = $this->getEmail();
2581 if ( $str === $oldaddr ) {
2582 return Status
::newGood( true );
2585 $this->setEmail( $str );
2587 if ( $str !== '' && $wgEmailAuthentication ) {
2588 // Send a confirmation request to the new address if needed
2589 $type = $oldaddr != '' ?
'changed' : 'set';
2590 $result = $this->sendConfirmationMail( $type );
2591 if ( $result->isGood() ) {
2592 // Say to the caller that a confirmation mail has been sent
2593 $result->value
= 'eauth';
2596 $result = Status
::newGood( true );
2603 * Get the user's real name
2604 * @return string User's real name
2606 public function getRealName() {
2607 if ( !$this->isItemLoaded( 'realname' ) ) {
2611 return $this->mRealName
;
2615 * Set the user's real name
2616 * @param string $str New real name
2618 public function setRealName( $str ) {
2620 $this->mRealName
= $str;
2624 * Get the user's current setting for a given option.
2626 * @param string $oname The option to check
2627 * @param string $defaultOverride A default value returned if the option does not exist
2628 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2629 * @return string User's current value for the option
2630 * @see getBoolOption()
2631 * @see getIntOption()
2633 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2634 global $wgHiddenPrefs;
2635 $this->loadOptions();
2637 # We want 'disabled' preferences to always behave as the default value for
2638 # users, even if they have set the option explicitly in their settings (ie they
2639 # set it, and then it was disabled removing their ability to change it). But
2640 # we don't want to erase the preferences in the database in case the preference
2641 # is re-enabled again. So don't touch $mOptions, just override the returned value
2642 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2643 return self
::getDefaultOption( $oname );
2646 if ( array_key_exists( $oname, $this->mOptions
) ) {
2647 return $this->mOptions
[$oname];
2649 return $defaultOverride;
2654 * Get all user's options
2656 * @param int $flags Bitwise combination of:
2657 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2658 * to the default value. (Since 1.25)
2661 public function getOptions( $flags = 0 ) {
2662 global $wgHiddenPrefs;
2663 $this->loadOptions();
2664 $options = $this->mOptions
;
2666 # We want 'disabled' preferences to always behave as the default value for
2667 # users, even if they have set the option explicitly in their settings (ie they
2668 # set it, and then it was disabled removing their ability to change it). But
2669 # we don't want to erase the preferences in the database in case the preference
2670 # is re-enabled again. So don't touch $mOptions, just override the returned value
2671 foreach ( $wgHiddenPrefs as $pref ) {
2672 $default = self
::getDefaultOption( $pref );
2673 if ( $default !== null ) {
2674 $options[$pref] = $default;
2678 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2679 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2686 * Get the user's current setting for a given option, as a boolean value.
2688 * @param string $oname The option to check
2689 * @return bool User's current value for the option
2692 public function getBoolOption( $oname ) {
2693 return (bool)$this->getOption( $oname );
2697 * Get the user's current setting for a given option, as an integer value.
2699 * @param string $oname The option to check
2700 * @param int $defaultOverride A default value returned if the option does not exist
2701 * @return int User's current value for the option
2704 public function getIntOption( $oname, $defaultOverride = 0 ) {
2705 $val = $this->getOption( $oname );
2707 $val = $defaultOverride;
2709 return intval( $val );
2713 * Set the given option for a user.
2715 * You need to call saveSettings() to actually write to the database.
2717 * @param string $oname The option to set
2718 * @param mixed $val New value to set
2720 public function setOption( $oname, $val ) {
2721 $this->loadOptions();
2723 // Explicitly NULL values should refer to defaults
2724 if ( is_null( $val ) ) {
2725 $val = self
::getDefaultOption( $oname );
2728 $this->mOptions
[$oname] = $val;
2732 * Get a token stored in the preferences (like the watchlist one),
2733 * resetting it if it's empty (and saving changes).
2735 * @param string $oname The option name to retrieve the token from
2736 * @return string|bool User's current value for the option, or false if this option is disabled.
2737 * @see resetTokenFromOption()
2740 public function getTokenFromOption( $oname ) {
2741 global $wgHiddenPrefs;
2742 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2746 $token = $this->getOption( $oname );
2748 $token = $this->resetTokenFromOption( $oname );
2749 if ( !wfReadOnly() ) {
2750 $this->saveSettings();
2757 * Reset a token stored in the preferences (like the watchlist one).
2758 * *Does not* save user's preferences (similarly to setOption()).
2760 * @param string $oname The option name to reset the token in
2761 * @return string|bool New token value, or false if this option is disabled.
2762 * @see getTokenFromOption()
2765 public function resetTokenFromOption( $oname ) {
2766 global $wgHiddenPrefs;
2767 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2771 $token = MWCryptRand
::generateHex( 40 );
2772 $this->setOption( $oname, $token );
2777 * Return a list of the types of user options currently returned by
2778 * User::getOptionKinds().
2780 * Currently, the option kinds are:
2781 * - 'registered' - preferences which are registered in core MediaWiki or
2782 * by extensions using the UserGetDefaultOptions hook.
2783 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2784 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2785 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2786 * be used by user scripts.
2787 * - 'special' - "preferences" that are not accessible via User::getOptions
2788 * or User::setOptions.
2789 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2790 * These are usually legacy options, removed in newer versions.
2792 * The API (and possibly others) use this function to determine the possible
2793 * option types for validation purposes, so make sure to update this when a
2794 * new option kind is added.
2796 * @see User::getOptionKinds
2797 * @return array Option kinds
2799 public static function listOptionKinds() {
2802 'registered-multiselect',
2803 'registered-checkmatrix',
2811 * Return an associative array mapping preferences keys to the kind of a preference they're
2812 * used for. Different kinds are handled differently when setting or reading preferences.
2814 * See User::listOptionKinds for the list of valid option types that can be provided.
2816 * @see User::listOptionKinds
2817 * @param IContextSource $context
2818 * @param array $options Assoc. array with options keys to check as keys.
2819 * Defaults to $this->mOptions.
2820 * @return array The key => kind mapping data
2822 public function getOptionKinds( IContextSource
$context, $options = null ) {
2823 $this->loadOptions();
2824 if ( $options === null ) {
2825 $options = $this->mOptions
;
2828 $prefs = Preferences
::getPreferences( $this, $context );
2831 // Pull out the "special" options, so they don't get converted as
2832 // multiselect or checkmatrix.
2833 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2834 foreach ( $specialOptions as $name => $value ) {
2835 unset( $prefs[$name] );
2838 // Multiselect and checkmatrix options are stored in the database with
2839 // one key per option, each having a boolean value. Extract those keys.
2840 $multiselectOptions = array();
2841 foreach ( $prefs as $name => $info ) {
2842 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2843 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2844 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2845 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2847 foreach ( $opts as $value ) {
2848 $multiselectOptions["$prefix$value"] = true;
2851 unset( $prefs[$name] );
2854 $checkmatrixOptions = array();
2855 foreach ( $prefs as $name => $info ) {
2856 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2857 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2858 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2859 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2860 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2862 foreach ( $columns as $column ) {
2863 foreach ( $rows as $row ) {
2864 $checkmatrixOptions["$prefix$column-$row"] = true;
2868 unset( $prefs[$name] );
2872 // $value is ignored
2873 foreach ( $options as $key => $value ) {
2874 if ( isset( $prefs[$key] ) ) {
2875 $mapping[$key] = 'registered';
2876 } elseif ( isset( $multiselectOptions[$key] ) ) {
2877 $mapping[$key] = 'registered-multiselect';
2878 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2879 $mapping[$key] = 'registered-checkmatrix';
2880 } elseif ( isset( $specialOptions[$key] ) ) {
2881 $mapping[$key] = 'special';
2882 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2883 $mapping[$key] = 'userjs';
2885 $mapping[$key] = 'unused';
2893 * Reset certain (or all) options to the site defaults
2895 * The optional parameter determines which kinds of preferences will be reset.
2896 * Supported values are everything that can be reported by getOptionKinds()
2897 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2899 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2900 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2901 * for backwards-compatibility.
2902 * @param IContextSource|null $context Context source used when $resetKinds
2903 * does not contain 'all', passed to getOptionKinds().
2904 * Defaults to RequestContext::getMain() when null.
2906 public function resetOptions(
2907 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2908 IContextSource
$context = null
2911 $defaultOptions = self
::getDefaultOptions();
2913 if ( !is_array( $resetKinds ) ) {
2914 $resetKinds = array( $resetKinds );
2917 if ( in_array( 'all', $resetKinds ) ) {
2918 $newOptions = $defaultOptions;
2920 if ( $context === null ) {
2921 $context = RequestContext
::getMain();
2924 $optionKinds = $this->getOptionKinds( $context );
2925 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2926 $newOptions = array();
2928 // Use default values for the options that should be deleted, and
2929 // copy old values for the ones that shouldn't.
2930 foreach ( $this->mOptions
as $key => $value ) {
2931 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2932 if ( array_key_exists( $key, $defaultOptions ) ) {
2933 $newOptions[$key] = $defaultOptions[$key];
2936 $newOptions[$key] = $value;
2941 Hooks
::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2943 $this->mOptions
= $newOptions;
2944 $this->mOptionsLoaded
= true;
2948 * Get the user's preferred date format.
2949 * @return string User's preferred date format
2951 public function getDatePreference() {
2952 // Important migration for old data rows
2953 if ( is_null( $this->mDatePreference
) ) {
2955 $value = $this->getOption( 'date' );
2956 $map = $wgLang->getDatePreferenceMigrationMap();
2957 if ( isset( $map[$value] ) ) {
2958 $value = $map[$value];
2960 $this->mDatePreference
= $value;
2962 return $this->mDatePreference
;
2966 * Determine based on the wiki configuration and the user's options,
2967 * whether this user must be over HTTPS no matter what.
2971 public function requiresHTTPS() {
2972 global $wgSecureLogin;
2973 if ( !$wgSecureLogin ) {
2976 $https = $this->getBoolOption( 'prefershttps' );
2977 Hooks
::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2979 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2986 * Get the user preferred stub threshold
2990 public function getStubThreshold() {
2991 global $wgMaxArticleSize; # Maximum article size, in Kb
2992 $threshold = $this->getIntOption( 'stubthreshold' );
2993 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2994 // If they have set an impossible value, disable the preference
2995 // so we can use the parser cache again.
3002 * Get the permissions this user has.
3003 * @return array Array of String permission names
3005 public function getRights() {
3006 if ( is_null( $this->mRights
) ) {
3007 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3008 Hooks
::run( 'UserGetRights', array( $this, &$this->mRights
) );
3009 // Force reindexation of rights when a hook has unset one of them
3010 $this->mRights
= array_values( array_unique( $this->mRights
) );
3012 return $this->mRights
;
3016 * Get the list of explicit group memberships this user has.
3017 * The implicit * and user groups are not included.
3018 * @return array Array of String internal group names
3020 public function getGroups() {
3022 $this->loadGroups();
3023 return $this->mGroups
;
3027 * Get the list of implicit group memberships this user has.
3028 * This includes all explicit groups, plus 'user' if logged in,
3029 * '*' for all accounts, and autopromoted groups
3030 * @param bool $recache Whether to avoid the cache
3031 * @return array Array of String internal group names
3033 public function getEffectiveGroups( $recache = false ) {
3034 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3035 $this->mEffectiveGroups
= array_unique( array_merge(
3036 $this->getGroups(), // explicit groups
3037 $this->getAutomaticGroups( $recache ) // implicit groups
3039 // Hook for additional groups
3040 Hooks
::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
3041 // Force reindexation of groups when a hook has unset one of them
3042 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3044 return $this->mEffectiveGroups
;
3048 * Get the list of implicit group memberships this user has.
3049 * This includes 'user' if logged in, '*' for all accounts,
3050 * and autopromoted groups
3051 * @param bool $recache Whether to avoid the cache
3052 * @return array Array of String internal group names
3054 public function getAutomaticGroups( $recache = false ) {
3055 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3056 $this->mImplicitGroups
= array( '*' );
3057 if ( $this->getId() ) {
3058 $this->mImplicitGroups
[] = 'user';
3060 $this->mImplicitGroups
= array_unique( array_merge(
3061 $this->mImplicitGroups
,
3062 Autopromote
::getAutopromoteGroups( $this )
3066 // Assure data consistency with rights/groups,
3067 // as getEffectiveGroups() depends on this function
3068 $this->mEffectiveGroups
= null;
3071 return $this->mImplicitGroups
;
3075 * Returns the groups the user has belonged to.
3077 * The user may still belong to the returned groups. Compare with getGroups().
3079 * The function will not return groups the user had belonged to before MW 1.17
3081 * @return array Names of the groups the user has belonged to.
3083 public function getFormerGroups() {
3086 if ( is_null( $this->mFormerGroups
) ) {
3087 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3088 ?
wfGetDB( DB_MASTER
)
3089 : wfGetDB( DB_SLAVE
);
3090 $res = $db->select( 'user_former_groups',
3091 array( 'ufg_group' ),
3092 array( 'ufg_user' => $this->mId
),
3094 $this->mFormerGroups
= array();
3095 foreach ( $res as $row ) {
3096 $this->mFormerGroups
[] = $row->ufg_group
;
3100 return $this->mFormerGroups
;
3104 * Get the user's edit count.
3105 * @return int|null Null for anonymous users
3107 public function getEditCount() {
3108 if ( !$this->getId() ) {
3112 if ( $this->mEditCount
=== null ) {
3113 /* Populate the count, if it has not been populated yet */
3114 $dbr = wfGetDB( DB_SLAVE
);
3115 // check if the user_editcount field has been initialized
3116 $count = $dbr->selectField(
3117 'user', 'user_editcount',
3118 array( 'user_id' => $this->mId
),
3122 if ( $count === null ) {
3123 // it has not been initialized. do so.
3124 $count = $this->initEditCount();
3126 $this->mEditCount
= $count;
3128 return (int)$this->mEditCount
;
3132 * Add the user to the given group.
3133 * This takes immediate effect.
3134 * @param string $group Name of the group to add
3137 public function addGroup( $group ) {
3140 if ( !Hooks
::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3144 $dbw = wfGetDB( DB_MASTER
);
3145 if ( $this->getId() ) {
3146 $dbw->insert( 'user_groups',
3148 'ug_user' => $this->getID(),
3149 'ug_group' => $group,
3152 array( 'IGNORE' ) );
3155 $this->loadGroups();
3156 $this->mGroups
[] = $group;
3157 // In case loadGroups was not called before, we now have the right twice.
3158 // Get rid of the duplicate.
3159 $this->mGroups
= array_unique( $this->mGroups
);
3161 // Refresh the groups caches, and clear the rights cache so it will be
3162 // refreshed on the next call to $this->getRights().
3163 $this->getEffectiveGroups( true );
3164 $this->mRights
= null;
3166 $this->invalidateCache();
3172 * Remove the user from the given group.
3173 * This takes immediate effect.
3174 * @param string $group Name of the group to remove
3177 public function removeGroup( $group ) {
3179 if ( !Hooks
::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3183 $dbw = wfGetDB( DB_MASTER
);
3184 $dbw->delete( 'user_groups',
3186 'ug_user' => $this->getID(),
3187 'ug_group' => $group,
3190 // Remember that the user was in this group
3191 $dbw->insert( 'user_former_groups',
3193 'ufg_user' => $this->getID(),
3194 'ufg_group' => $group,
3200 $this->loadGroups();
3201 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3203 // Refresh the groups caches, and clear the rights cache so it will be
3204 // refreshed on the next call to $this->getRights().
3205 $this->getEffectiveGroups( true );
3206 $this->mRights
= null;
3208 $this->invalidateCache();
3214 * Get whether the user is logged in
3217 public function isLoggedIn() {
3218 return $this->getID() != 0;
3222 * Get whether the user is anonymous
3225 public function isAnon() {
3226 return !$this->isLoggedIn();
3230 * Check if user is allowed to access a feature / make an action
3232 * @param string $permissions,... Permissions to test
3233 * @return bool True if user is allowed to perform *any* of the given actions
3235 public function isAllowedAny( /*...*/ ) {
3236 $permissions = func_get_args();
3237 foreach ( $permissions as $permission ) {
3238 if ( $this->isAllowed( $permission ) ) {
3247 * @param string $permissions,... Permissions to test
3248 * @return bool True if the user is allowed to perform *all* of the given actions
3250 public function isAllowedAll( /*...*/ ) {
3251 $permissions = func_get_args();
3252 foreach ( $permissions as $permission ) {
3253 if ( !$this->isAllowed( $permission ) ) {
3261 * Internal mechanics of testing a permission
3262 * @param string $action
3265 public function isAllowed( $action = '' ) {
3266 if ( $action === '' ) {
3267 return true; // In the spirit of DWIM
3269 // Patrolling may not be enabled
3270 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3271 global $wgUseRCPatrol, $wgUseNPPatrol;
3272 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3276 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3277 // by misconfiguration: 0 == 'foo'
3278 return in_array( $action, $this->getRights(), true );
3282 * Check whether to enable recent changes patrol features for this user
3283 * @return bool True or false
3285 public function useRCPatrol() {
3286 global $wgUseRCPatrol;
3287 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3291 * Check whether to enable new pages patrol features for this user
3292 * @return bool True or false
3294 public function useNPPatrol() {
3295 global $wgUseRCPatrol, $wgUseNPPatrol;
3297 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3298 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3303 * Get the WebRequest object to use with this object
3305 * @return WebRequest
3307 public function getRequest() {
3308 if ( $this->mRequest
) {
3309 return $this->mRequest
;
3317 * Get the current skin, loading it if required
3318 * @return Skin The current skin
3319 * @todo FIXME: Need to check the old failback system [AV]
3320 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3322 public function getSkin() {
3323 wfDeprecated( __METHOD__
, '1.18' );
3324 return RequestContext
::getMain()->getSkin();
3328 * Get a WatchedItem for this user and $title.
3330 * @since 1.22 $checkRights parameter added
3331 * @param Title $title
3332 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3333 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3334 * @return WatchedItem
3336 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3337 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3339 if ( isset( $this->mWatchedItems
[$key] ) ) {
3340 return $this->mWatchedItems
[$key];
3343 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3344 $this->mWatchedItems
= array();
3347 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3348 return $this->mWatchedItems
[$key];
3352 * Check the watched status of an article.
3353 * @since 1.22 $checkRights parameter added
3354 * @param Title $title Title of the article to look at
3355 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3356 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3359 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3360 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3365 * @since 1.22 $checkRights parameter added
3366 * @param Title $title Title of the article to look at
3367 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3368 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3370 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3371 $this->getWatchedItem( $title, $checkRights )->addWatch();
3372 $this->invalidateCache();
3376 * Stop watching an article.
3377 * @since 1.22 $checkRights parameter added
3378 * @param Title $title Title of the article to look at
3379 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3380 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3382 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3383 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3384 $this->invalidateCache();
3388 * Clear the user's notification timestamp for the given title.
3389 * If e-notif e-mails are on, they will receive notification mails on
3390 * the next change of the page if it's watched etc.
3391 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3392 * @param Title $title Title of the article to look at
3393 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3395 public function clearNotification( &$title, $oldid = 0 ) {
3396 global $wgUseEnotif, $wgShowUpdatedMarker;
3398 // Do nothing if the database is locked to writes
3399 if ( wfReadOnly() ) {
3403 // Do nothing if not allowed to edit the watchlist
3404 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3408 // If we're working on user's talk page, we should update the talk page message indicator
3409 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3410 if ( !Hooks
::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3414 $nextid = $oldid ?
$title->getNextRevisionID( $oldid ) : null;
3416 if ( !$oldid ||
!$nextid ) {
3417 // If we're looking at the latest revision, we should definitely clear it
3418 $this->setNewtalk( false );
3420 // Otherwise we should update its revision, if it's present
3421 if ( $this->getNewtalk() ) {
3422 // Naturally the other one won't clear by itself
3423 $this->setNewtalk( false );
3424 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3429 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3433 if ( $this->isAnon() ) {
3434 // Nothing else to do...
3438 // Only update the timestamp if the page is being watched.
3439 // The query to find out if it is watched is cached both in memcached and per-invocation,
3440 // and when it does have to be executed, it can be on a slave
3441 // If this is the user's newtalk page, we always update the timestamp
3443 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3447 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3448 $force, $oldid, WatchedItem
::DEFERRED
3453 * Resets all of the given user's page-change notification timestamps.
3454 * If e-notif e-mails are on, they will receive notification mails on
3455 * the next change of any watched page.
3456 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3458 public function clearAllNotifications() {
3459 if ( wfReadOnly() ) {
3463 // Do nothing if not allowed to edit the watchlist
3464 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3468 global $wgUseEnotif, $wgShowUpdatedMarker;
3469 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3470 $this->setNewtalk( false );
3473 $id = $this->getId();
3475 $dbw = wfGetDB( DB_MASTER
);
3476 $dbw->update( 'watchlist',
3477 array( /* SET */ 'wl_notificationtimestamp' => null ),
3478 array( /* WHERE */ 'wl_user' => $id ),
3481 // We also need to clear here the "you have new message" notification for the own user_talk page;
3482 // it's cleared one page view later in WikiPage::doViewUpdates().
3487 * Set a cookie on the user's client. Wrapper for
3488 * WebResponse::setCookie
3489 * @param string $name Name of the cookie to set
3490 * @param string $value Value to set
3491 * @param int $exp Expiration time, as a UNIX time value;
3492 * if 0 or not specified, use the default $wgCookieExpiration
3493 * @param bool $secure
3494 * true: Force setting the secure attribute when setting the cookie
3495 * false: Force NOT setting the secure attribute when setting the cookie
3496 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3497 * @param array $params Array of options sent passed to WebResponse::setcookie()
3498 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3501 protected function setCookie(
3502 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3504 if ( $request === null ) {
3505 $request = $this->getRequest();
3507 $params['secure'] = $secure;
3508 $request->response()->setcookie( $name, $value, $exp, $params );
3512 * Clear a cookie on the user's client
3513 * @param string $name Name of the cookie to clear
3514 * @param bool $secure
3515 * true: Force setting the secure attribute when setting the cookie
3516 * false: Force NOT setting the secure attribute when setting the cookie
3517 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3518 * @param array $params Array of options sent passed to WebResponse::setcookie()
3520 protected function clearCookie( $name, $secure = null, $params = array() ) {
3521 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3525 * Set the default cookies for this session on the user's client.
3527 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3529 * @param bool $secure Whether to force secure/insecure cookies or use default
3530 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3532 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3533 if ( $request === null ) {
3534 $request = $this->getRequest();
3538 if ( 0 == $this->mId
) {
3541 if ( !$this->mToken
) {
3542 // When token is empty or NULL generate a new one and then save it to the database
3543 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3544 // Simply by setting every cell in the user_token column to NULL and letting them be
3545 // regenerated as users log back into the wiki.
3547 if ( !wfReadOnly() ) {
3548 $this->saveSettings();
3552 'wsUserID' => $this->mId
,
3553 'wsToken' => $this->mToken
,
3554 'wsUserName' => $this->getName()
3557 'UserID' => $this->mId
,
3558 'UserName' => $this->getName(),
3560 if ( $rememberMe ) {
3561 $cookies['Token'] = $this->mToken
;
3563 $cookies['Token'] = false;
3566 Hooks
::run( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3568 foreach ( $session as $name => $value ) {
3569 $request->setSessionData( $name, $value );
3571 foreach ( $cookies as $name => $value ) {
3572 if ( $value === false ) {
3573 $this->clearCookie( $name );
3575 $this->setCookie( $name, $value, 0, $secure, array(), $request );
3580 * If wpStickHTTPS was selected, also set an insecure cookie that
3581 * will cause the site to redirect the user to HTTPS, if they access
3582 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3583 * as the one set by centralauth (bug 53538). Also set it to session, or
3584 * standard time setting, based on if rememberme was set.
3586 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3590 $rememberMe ?
0 : null,
3592 array( 'prefix' => '' ) // no prefix
3598 * Log this user out.
3600 public function logout() {
3601 if ( Hooks
::run( 'UserLogout', array( &$this ) ) ) {
3607 * Clear the user's cookies and session, and reset the instance cache.
3610 public function doLogout() {
3611 $this->clearInstanceCache( 'defaults' );
3613 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3615 $this->clearCookie( 'UserID' );
3616 $this->clearCookie( 'Token' );
3617 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3619 // Remember when user logged out, to prevent seeing cached pages
3620 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3624 * Save this user's settings into the database.
3625 * @todo Only rarely do all these fields need to be set!
3627 public function saveSettings() {
3630 if ( wfReadOnly() ) {
3631 // @TODO: caller should deal with this instead!
3632 // This should really just be an exception.
3633 MWExceptionHandler
::logException( new DBExpectedError(
3635 "Could not update user with ID '{$this->mId}'; DB is read-only."
3641 $this->loadPasswords();
3642 if ( 0 == $this->mId
) {
3646 // This method is for updating existing users, so the user should
3647 // have been loaded from the master to begin with to avoid problems.
3648 if ( !( $this->queryFlagsUsed
& self
::READ_LATEST
) ) {
3649 wfWarn( "Attempting to save slave-loaded User object with ID '{$this->mId}'." );
3652 // Get a new user_touched that is higher than the old one.
3653 // This will be used for a CAS check as a last-resort safety
3654 // check against race conditions and slave lag.
3655 $oldTouched = $this->mTouched
;
3656 $newTouched = $this->newTouchedTimestamp();
3658 if ( !$wgAuth->allowSetLocalPassword() ) {
3659 $this->mPassword
= self
::getPasswordFactory()->newFromCiphertext( null );
3662 $dbw = wfGetDB( DB_MASTER
);
3663 $dbw->update( 'user',
3665 'user_name' => $this->mName
,
3666 'user_password' => $this->mPassword
->toString(),
3667 'user_newpassword' => $this->mNewpassword
->toString(),
3668 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3669 'user_real_name' => $this->mRealName
,
3670 'user_email' => $this->mEmail
,
3671 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3672 'user_touched' => $dbw->timestamp( $newTouched ),
3673 'user_token' => strval( $this->mToken
),
3674 'user_email_token' => $this->mEmailToken
,
3675 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3676 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires
),
3677 ), array( /* WHERE */
3678 'user_id' => $this->mId
,
3679 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3683 if ( !$dbw->affectedRows() ) {
3684 // Maybe the problem was a missed cache update; clear it to be safe
3685 $this->clearSharedCache();
3686 // User was changed in the meantime or loaded with stale data
3687 MWExceptionHandler
::logException( new MWException(
3688 "CAS update failed on user_touched for user ID '{$this->mId}';" .
3689 "the version of the user to be saved is older than the current version."
3695 $this->mTouched
= $newTouched;
3696 $this->saveOptions();
3698 Hooks
::run( 'UserSaveSettings', array( $this ) );
3699 $this->clearSharedCache();
3700 $this->getUserPage()->invalidateCache();
3702 // T95839: clear the cache again post-commit to reduce race conditions
3703 // where stale values are written back to the cache by other threads.
3704 // Note: this *still* doesn't deal with REPEATABLE-READ snapshot lag...
3706 $dbw->onTransactionIdle( function() use ( $that ) {
3707 $that->clearSharedCache();
3712 * If only this user's username is known, and it exists, return the user ID.
3715 public function idForName() {
3716 $s = trim( $this->getName() );
3721 $dbr = wfGetDB( DB_SLAVE
);
3722 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
3723 if ( $id === false ) {
3730 * Add a user to the database, return the user object
3732 * @param string $name Username to add
3733 * @param array $params Array of Strings Non-default parameters to save to
3734 * the database as user_* fields:
3735 * - password: The user's password hash. Password logins will be disabled
3736 * if this is omitted.
3737 * - newpassword: Hash for a temporary password that has been mailed to
3739 * - email: The user's email address.
3740 * - email_authenticated: The email authentication timestamp.
3741 * - real_name: The user's real name.
3742 * - options: An associative array of non-default options.
3743 * - token: Random authentication token. Do not set.
3744 * - registration: Registration timestamp. Do not set.
3746 * @return User|null User object, or null if the username already exists.
3748 public static function createNew( $name, $params = array() ) {
3751 $user->loadPasswords();
3752 $user->setToken(); // init token
3753 if ( isset( $params['options'] ) ) {
3754 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3755 unset( $params['options'] );
3757 $dbw = wfGetDB( DB_MASTER
);
3758 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3761 'user_id' => $seqVal,
3762 'user_name' => $name,
3763 'user_password' => $user->mPassword
->toString(),
3764 'user_newpassword' => $user->mNewpassword
->toString(),
3765 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3766 'user_email' => $user->mEmail
,
3767 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3768 'user_real_name' => $user->mRealName
,
3769 'user_token' => strval( $user->mToken
),
3770 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3771 'user_editcount' => 0,
3772 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3774 foreach ( $params as $name => $value ) {
3775 $fields["user_$name"] = $value;
3777 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3778 if ( $dbw->affectedRows() ) {
3779 $newUser = User
::newFromId( $dbw->insertId() );
3787 * Add this existing user object to the database. If the user already
3788 * exists, a fatal status object is returned, and the user object is
3789 * initialised with the data from the database.
3791 * Previously, this function generated a DB error due to a key conflict
3792 * if the user already existed. Many extension callers use this function
3793 * in code along the lines of:
3795 * $user = User::newFromName( $name );
3796 * if ( !$user->isLoggedIn() ) {
3797 * $user->addToDatabase();
3799 * // do something with $user...
3801 * However, this was vulnerable to a race condition (bug 16020). By
3802 * initialising the user object if the user exists, we aim to support this
3803 * calling sequence as far as possible.
3805 * Note that if the user exists, this function will acquire a write lock,
3806 * so it is still advisable to make the call conditional on isLoggedIn(),
3807 * and to commit the transaction after calling.
3809 * @throws MWException
3812 public function addToDatabase() {
3814 $this->loadPasswords();
3815 if ( !$this->mToken
) {
3816 $this->setToken(); // init token
3819 $this->mTouched
= $this->newTouchedTimestamp();
3821 $dbw = wfGetDB( DB_MASTER
);
3822 $inWrite = $dbw->writesOrCallbacksPending();
3823 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3824 $dbw->insert( 'user',
3826 'user_id' => $seqVal,
3827 'user_name' => $this->mName
,
3828 'user_password' => $this->mPassword
->toString(),
3829 'user_newpassword' => $this->mNewpassword
->toString(),
3830 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3831 'user_email' => $this->mEmail
,
3832 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3833 'user_real_name' => $this->mRealName
,
3834 'user_token' => strval( $this->mToken
),
3835 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3836 'user_editcount' => 0,
3837 'user_touched' => $dbw->timestamp( $this->mTouched
),
3841 if ( !$dbw->affectedRows() ) {
3842 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3843 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3845 // Can't commit due to pending writes that may need atomicity.
3846 // This may cause some lock contention unlike the case below.
3847 $options = array( 'LOCK IN SHARE MODE' );
3848 $flags = self
::READ_LOCKING
;
3850 // Often, this case happens early in views before any writes when
3851 // using CentralAuth. It's should be OK to commit and break the snapshot.
3852 $dbw->commit( __METHOD__
, 'flush' );
3854 $flags = self
::READ_LATEST
;
3856 $this->mId
= $dbw->selectField( 'user', 'user_id',
3857 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3860 if ( $this->loadFromDatabase( $flags ) ) {
3865 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3866 "to insert user '{$this->mName}' row, but it was not present in select!" );
3868 return Status
::newFatal( 'userexists' );
3870 $this->mId
= $dbw->insertId();
3872 // Clear instance cache other than user table data, which is already accurate
3873 $this->clearInstanceCache();
3875 $this->saveOptions();
3876 return Status
::newGood();
3880 * If this user is logged-in and blocked,
3881 * block any IP address they've successfully logged in from.
3882 * @return bool A block was spread
3884 public function spreadAnyEditBlock() {
3885 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3886 return $this->spreadBlock();
3892 * If this (non-anonymous) user is blocked,
3893 * block the IP address they've successfully logged in from.
3894 * @return bool A block was spread
3896 protected function spreadBlock() {
3897 wfDebug( __METHOD__
. "()\n" );
3899 if ( $this->mId
== 0 ) {
3903 $userblock = Block
::newFromTarget( $this->getName() );
3904 if ( !$userblock ) {
3908 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3912 * Get whether the user is explicitly blocked from account creation.
3913 * @return bool|Block
3915 public function isBlockedFromCreateAccount() {
3916 $this->getBlockedStatus();
3917 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3918 return $this->mBlock
;
3921 # bug 13611: if the IP address the user is trying to create an account from is
3922 # blocked with createaccount disabled, prevent new account creation there even
3923 # when the user is logged in
3924 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3925 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3927 return $this->mBlockedFromCreateAccount
instanceof Block
3928 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3929 ?
$this->mBlockedFromCreateAccount
3934 * Get whether the user is blocked from using Special:Emailuser.
3937 public function isBlockedFromEmailuser() {
3938 $this->getBlockedStatus();
3939 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3943 * Get whether the user is allowed to create an account.
3946 public function isAllowedToCreateAccount() {
3947 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3951 * Get this user's personal page title.
3953 * @return Title User's personal page title
3955 public function getUserPage() {
3956 return Title
::makeTitle( NS_USER
, $this->getName() );
3960 * Get this user's talk page title.
3962 * @return Title User's talk page title
3964 public function getTalkPage() {
3965 $title = $this->getUserPage();
3966 return $title->getTalkPage();
3970 * Determine whether the user is a newbie. Newbies are either
3971 * anonymous IPs, or the most recently created accounts.
3974 public function isNewbie() {
3975 return !$this->isAllowed( 'autoconfirmed' );
3979 * Check to see if the given clear-text password is one of the accepted passwords
3980 * @param string $password User password
3981 * @return bool True if the given password is correct, otherwise False
3983 public function checkPassword( $password ) {
3984 global $wgAuth, $wgLegacyEncoding;
3986 $this->loadPasswords();
3988 // Some passwords will give a fatal Status, which means there is
3989 // some sort of technical or security reason for this password to
3990 // be completely invalid and should never be checked (e.g., T64685)
3991 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
3995 // Certain authentication plugins do NOT want to save
3996 // domain passwords in a mysql database, so we should
3997 // check this (in case $wgAuth->strict() is false).
3998 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4000 } elseif ( $wgAuth->strict() ) {
4001 // Auth plugin doesn't allow local authentication
4003 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4004 // Auth plugin doesn't allow local authentication for this user name
4008 if ( !$this->mPassword
->equals( $password ) ) {
4009 if ( $wgLegacyEncoding ) {
4010 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4011 // Check for this with iconv
4012 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4013 if ( $cp1252Password === $password ||
!$this->mPassword
->equals( $cp1252Password ) ) {
4021 $passwordFactory = self
::getPasswordFactory();
4022 if ( $passwordFactory->needsUpdate( $this->mPassword
) && !wfReadOnly() ) {
4023 $this->mPassword
= $passwordFactory->newFromPlaintext( $password );
4024 $this->saveSettings();
4031 * Check if the given clear-text password matches the temporary password
4032 * sent by e-mail for password reset operations.
4034 * @param string $plaintext
4036 * @return bool True if matches, false otherwise
4038 public function checkTemporaryPassword( $plaintext ) {
4039 global $wgNewPasswordExpiry;
4042 $this->loadPasswords();
4043 if ( $this->mNewpassword
->equals( $plaintext ) ) {
4044 if ( is_null( $this->mNewpassTime
) ) {
4047 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
4048 return ( time() < $expiry );
4055 * Alias for getEditToken.
4056 * @deprecated since 1.19, use getEditToken instead.
4058 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4059 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4060 * @return string The new edit token
4062 public function editToken( $salt = '', $request = null ) {
4063 wfDeprecated( __METHOD__
, '1.19' );
4064 return $this->getEditToken( $salt, $request );
4068 * Internal implementation for self::getEditToken() and
4069 * self::matchEditToken().
4071 * @param string|array $salt
4072 * @param WebRequest $request
4073 * @param string|int $timestamp
4076 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
4077 if ( $this->isAnon() ) {
4078 return self
::EDIT_TOKEN_SUFFIX
;
4080 $token = $request->getSessionData( 'wsEditToken' );
4081 if ( $token === null ) {
4082 $token = MWCryptRand
::generateHex( 32 );
4083 $request->setSessionData( 'wsEditToken', $token );
4085 if ( is_array( $salt ) ) {
4086 $salt = implode( '|', $salt );
4088 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
4089 dechex( $timestamp ) .
4090 self
::EDIT_TOKEN_SUFFIX
;
4095 * Initialize (if necessary) and return a session token value
4096 * which can be used in edit forms to show that the user's
4097 * login credentials aren't being hijacked with a foreign form
4102 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4103 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4104 * @return string The new edit token
4106 public function getEditToken( $salt = '', $request = null ) {
4107 return $this->getEditTokenAtTimestamp(
4108 $salt, $request ?
: $this->getRequest(), wfTimestamp()
4113 * Generate a looking random token for various uses.
4115 * @return string The new random token
4116 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
4117 * wfRandomString for pseudo-randomness.
4119 public static function generateToken() {
4120 return MWCryptRand
::generateHex( 32 );
4124 * Get the embedded timestamp from a token.
4125 * @param string $val Input token
4128 public static function getEditTokenTimestamp( $val ) {
4129 $suffixLen = strlen( self
::EDIT_TOKEN_SUFFIX
);
4130 if ( strlen( $val ) <= 32 +
$suffixLen ) {
4134 return hexdec( substr( $val, 32, -$suffixLen ) );
4138 * Check given value against the token value stored in the session.
4139 * A match should confirm that the form was submitted from the
4140 * user's own login session, not a form submission from a third-party
4143 * @param string $val Input value to compare
4144 * @param string $salt Optional function-specific data for hashing
4145 * @param WebRequest|null $request Object to use or null to use $wgRequest
4146 * @param int $maxage Fail tokens older than this, in seconds
4147 * @return bool Whether the token matches
4149 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4150 if ( $this->isAnon() ) {
4151 return $val === self
::EDIT_TOKEN_SUFFIX
;
4154 $timestamp = self
::getEditTokenTimestamp( $val );
4155 if ( $timestamp === null ) {
4158 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
4163 $sessionToken = $this->getEditTokenAtTimestamp(
4164 $salt, $request ?
: $this->getRequest(), $timestamp
4167 if ( $val != $sessionToken ) {
4168 wfDebug( "User::matchEditToken: broken session data\n" );
4171 return hash_equals( $sessionToken, $val );
4175 * Check given value against the token value stored in the session,
4176 * ignoring the suffix.
4178 * @param string $val Input value to compare
4179 * @param string $salt Optional function-specific data for hashing
4180 * @param WebRequest|null $request Object to use or null to use $wgRequest
4181 * @param int $maxage Fail tokens older than this, in seconds
4182 * @return bool Whether the token matches
4184 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4185 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4186 return $this->matchEditToken( $val, $salt, $request, $maxage );
4190 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4191 * mail to the user's given address.
4193 * @param string $type Message to send, either "created", "changed" or "set"
4196 public function sendConfirmationMail( $type = 'created' ) {
4198 $expiration = null; // gets passed-by-ref and defined in next line.
4199 $token = $this->confirmationToken( $expiration );
4200 $url = $this->confirmationTokenUrl( $token );
4201 $invalidateURL = $this->invalidationTokenUrl( $token );
4202 $this->saveSettings();
4204 if ( $type == 'created' ||
$type === false ) {
4205 $message = 'confirmemail_body';
4206 } elseif ( $type === true ) {
4207 $message = 'confirmemail_body_changed';
4209 // Messages: confirmemail_body_changed, confirmemail_body_set
4210 $message = 'confirmemail_body_' . $type;
4213 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4214 wfMessage( $message,
4215 $this->getRequest()->getIP(),
4218 $wgLang->timeanddate( $expiration, false ),
4220 $wgLang->date( $expiration, false ),
4221 $wgLang->time( $expiration, false ) )->text() );
4225 * Send an e-mail to this user's account. Does not check for
4226 * confirmed status or validity.
4228 * @param string $subject Message subject
4229 * @param string $body Message body
4230 * @param string $from Optional From address; if unspecified, default
4231 * $wgPasswordSender will be used.
4232 * @param string $replyto Reply-To address
4235 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4236 if ( is_null( $from ) ) {
4237 global $wgPasswordSender;
4238 $sender = new MailAddress( $wgPasswordSender,
4239 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4241 $sender = MailAddress
::newFromUser( $from );
4244 $to = MailAddress
::newFromUser( $this );
4245 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
4249 * Generate, store, and return a new e-mail confirmation code.
4250 * A hash (unsalted, since it's used as a key) is stored.
4252 * @note Call saveSettings() after calling this function to commit
4253 * this change to the database.
4255 * @param string &$expiration Accepts the expiration time
4256 * @return string New token
4258 protected function confirmationToken( &$expiration ) {
4259 global $wgUserEmailConfirmationTokenExpiry;
4261 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4262 $expiration = wfTimestamp( TS_MW
, $expires );
4264 $token = MWCryptRand
::generateHex( 32 );
4265 $hash = md5( $token );
4266 $this->mEmailToken
= $hash;
4267 $this->mEmailTokenExpires
= $expiration;
4272 * Return a URL the user can use to confirm their email address.
4273 * @param string $token Accepts the email confirmation token
4274 * @return string New token URL
4276 protected function confirmationTokenUrl( $token ) {
4277 return $this->getTokenUrl( 'ConfirmEmail', $token );
4281 * Return a URL the user can use to invalidate their email address.
4282 * @param string $token Accepts the email confirmation token
4283 * @return string New token URL
4285 protected function invalidationTokenUrl( $token ) {
4286 return $this->getTokenUrl( 'InvalidateEmail', $token );
4290 * Internal function to format the e-mail validation/invalidation URLs.
4291 * This uses a quickie hack to use the
4292 * hardcoded English names of the Special: pages, for ASCII safety.
4294 * @note Since these URLs get dropped directly into emails, using the
4295 * short English names avoids insanely long URL-encoded links, which
4296 * also sometimes can get corrupted in some browsers/mailers
4297 * (bug 6957 with Gmail and Internet Explorer).
4299 * @param string $page Special page
4300 * @param string $token Token
4301 * @return string Formatted URL
4303 protected function getTokenUrl( $page, $token ) {
4304 // Hack to bypass localization of 'Special:'
4305 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4306 return $title->getCanonicalURL();
4310 * Mark the e-mail address confirmed.
4312 * @note Call saveSettings() after calling this function to commit the change.
4316 public function confirmEmail() {
4317 // Check if it's already confirmed, so we don't touch the database
4318 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4319 if ( !$this->isEmailConfirmed() ) {
4320 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4321 Hooks
::run( 'ConfirmEmailComplete', array( $this ) );
4327 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4328 * address if it was already confirmed.
4330 * @note Call saveSettings() after calling this function to commit the change.
4331 * @return bool Returns true
4333 public function invalidateEmail() {
4335 $this->mEmailToken
= null;
4336 $this->mEmailTokenExpires
= null;
4337 $this->setEmailAuthenticationTimestamp( null );
4339 Hooks
::run( 'InvalidateEmailComplete', array( $this ) );
4344 * Set the e-mail authentication timestamp.
4345 * @param string $timestamp TS_MW timestamp
4347 public function setEmailAuthenticationTimestamp( $timestamp ) {
4349 $this->mEmailAuthenticated
= $timestamp;
4350 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4354 * Is this user allowed to send e-mails within limits of current
4355 * site configuration?
4358 public function canSendEmail() {
4359 global $wgEnableEmail, $wgEnableUserEmail;
4360 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4363 $canSend = $this->isEmailConfirmed();
4364 Hooks
::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4369 * Is this user allowed to receive e-mails within limits of current
4370 * site configuration?
4373 public function canReceiveEmail() {
4374 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4378 * Is this user's e-mail address valid-looking and confirmed within
4379 * limits of the current site configuration?
4381 * @note If $wgEmailAuthentication is on, this may require the user to have
4382 * confirmed their address by returning a code or using a password
4383 * sent to the address from the wiki.
4387 public function isEmailConfirmed() {
4388 global $wgEmailAuthentication;
4391 if ( Hooks
::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4392 if ( $this->isAnon() ) {
4395 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4398 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4408 * Check whether there is an outstanding request for e-mail confirmation.
4411 public function isEmailConfirmationPending() {
4412 global $wgEmailAuthentication;
4413 return $wgEmailAuthentication &&
4414 !$this->isEmailConfirmed() &&
4415 $this->mEmailToken
&&
4416 $this->mEmailTokenExpires
> wfTimestamp();
4420 * Get the timestamp of account creation.
4422 * @return string|bool|null Timestamp of account creation, false for
4423 * non-existent/anonymous user accounts, or null if existing account
4424 * but information is not in database.
4426 public function getRegistration() {
4427 if ( $this->isAnon() ) {
4431 return $this->mRegistration
;
4435 * Get the timestamp of the first edit
4437 * @return string|bool Timestamp of first edit, or false for
4438 * non-existent/anonymous user accounts.
4440 public function getFirstEditTimestamp() {
4441 if ( $this->getId() == 0 ) {
4442 return false; // anons
4444 $dbr = wfGetDB( DB_SLAVE
);
4445 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4446 array( 'rev_user' => $this->getId() ),
4448 array( 'ORDER BY' => 'rev_timestamp ASC' )
4451 return false; // no edits
4453 return wfTimestamp( TS_MW
, $time );
4457 * Get the permissions associated with a given list of groups
4459 * @param array $groups Array of Strings List of internal group names
4460 * @return array Array of Strings List of permission key names for given groups combined
4462 public static function getGroupPermissions( $groups ) {
4463 global $wgGroupPermissions, $wgRevokePermissions;
4465 // grant every granted permission first
4466 foreach ( $groups as $group ) {
4467 if ( isset( $wgGroupPermissions[$group] ) ) {
4468 $rights = array_merge( $rights,
4469 // array_filter removes empty items
4470 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4473 // now revoke the revoked permissions
4474 foreach ( $groups as $group ) {
4475 if ( isset( $wgRevokePermissions[$group] ) ) {
4476 $rights = array_diff( $rights,
4477 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4480 return array_unique( $rights );
4484 * Get all the groups who have a given permission
4486 * @param string $role Role to check
4487 * @return array Array of Strings List of internal group names with the given permission
4489 public static function getGroupsWithPermission( $role ) {
4490 global $wgGroupPermissions;
4491 $allowedGroups = array();
4492 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4493 if ( self
::groupHasPermission( $group, $role ) ) {
4494 $allowedGroups[] = $group;
4497 return $allowedGroups;
4501 * Check, if the given group has the given permission
4503 * If you're wanting to check whether all users have a permission, use
4504 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4508 * @param string $group Group to check
4509 * @param string $role Role to check
4512 public static function groupHasPermission( $group, $role ) {
4513 global $wgGroupPermissions, $wgRevokePermissions;
4514 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4515 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4519 * Check if all users have the given permission
4522 * @param string $right Right to check
4525 public static function isEveryoneAllowed( $right ) {
4526 global $wgGroupPermissions, $wgRevokePermissions;
4527 static $cache = array();
4529 // Use the cached results, except in unit tests which rely on
4530 // being able change the permission mid-request
4531 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4532 return $cache[$right];
4535 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4536 $cache[$right] = false;
4540 // If it's revoked anywhere, then everyone doesn't have it
4541 foreach ( $wgRevokePermissions as $rights ) {
4542 if ( isset( $rights[$right] ) && $rights[$right] ) {
4543 $cache[$right] = false;
4548 // Allow extensions (e.g. OAuth) to say false
4549 if ( !Hooks
::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4550 $cache[$right] = false;
4554 $cache[$right] = true;
4559 * Get the localized descriptive name for a group, if it exists
4561 * @param string $group Internal group name
4562 * @return string Localized descriptive group name
4564 public static function getGroupName( $group ) {
4565 $msg = wfMessage( "group-$group" );
4566 return $msg->isBlank() ?
$group : $msg->text();
4570 * Get the localized descriptive name for a member of a group, if it exists
4572 * @param string $group Internal group name
4573 * @param string $username Username for gender (since 1.19)
4574 * @return string Localized name for group member
4576 public static function getGroupMember( $group, $username = '#' ) {
4577 $msg = wfMessage( "group-$group-member", $username );
4578 return $msg->isBlank() ?
$group : $msg->text();
4582 * Return the set of defined explicit groups.
4583 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4584 * are not included, as they are defined automatically, not in the database.
4585 * @return array Array of internal group names
4587 public static function getAllGroups() {
4588 global $wgGroupPermissions, $wgRevokePermissions;
4590 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4591 self
::getImplicitGroups()
4596 * Get a list of all available permissions.
4597 * @return string[] Array of permission names
4599 public static function getAllRights() {
4600 if ( self
::$mAllRights === false ) {
4601 global $wgAvailableRights;
4602 if ( count( $wgAvailableRights ) ) {
4603 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4605 self
::$mAllRights = self
::$mCoreRights;
4607 Hooks
::run( 'UserGetAllRights', array( &self
::$mAllRights ) );
4609 return self
::$mAllRights;
4613 * Get a list of implicit groups
4614 * @return array Array of Strings Array of internal group names
4616 public static function getImplicitGroups() {
4617 global $wgImplicitGroups;
4619 $groups = $wgImplicitGroups;
4620 # Deprecated, use $wgImplicitGroups instead
4621 Hooks
::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4627 * Get the title of a page describing a particular group
4629 * @param string $group Internal group name
4630 * @return Title|bool Title of the page if it exists, false otherwise
4632 public static function getGroupPage( $group ) {
4633 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4634 if ( $msg->exists() ) {
4635 $title = Title
::newFromText( $msg->text() );
4636 if ( is_object( $title ) ) {
4644 * Create a link to the group in HTML, if available;
4645 * else return the group name.
4647 * @param string $group Internal name of the group
4648 * @param string $text The text of the link
4649 * @return string HTML link to the group
4651 public static function makeGroupLinkHTML( $group, $text = '' ) {
4652 if ( $text == '' ) {
4653 $text = self
::getGroupName( $group );
4655 $title = self
::getGroupPage( $group );
4657 return Linker
::link( $title, htmlspecialchars( $text ) );
4659 return htmlspecialchars( $text );
4664 * Create a link to the group in Wikitext, if available;
4665 * else return the group name.
4667 * @param string $group Internal name of the group
4668 * @param string $text The text of the link
4669 * @return string Wikilink to the group
4671 public static function makeGroupLinkWiki( $group, $text = '' ) {
4672 if ( $text == '' ) {
4673 $text = self
::getGroupName( $group );
4675 $title = self
::getGroupPage( $group );
4677 $page = $title->getFullText();
4678 return "[[$page|$text]]";
4685 * Returns an array of the groups that a particular group can add/remove.
4687 * @param string $group The group to check for whether it can add/remove
4688 * @return array Array( 'add' => array( addablegroups ),
4689 * 'remove' => array( removablegroups ),
4690 * 'add-self' => array( addablegroups to self),
4691 * 'remove-self' => array( removable groups from self) )
4693 public static function changeableByGroup( $group ) {
4694 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4698 'remove' => array(),
4699 'add-self' => array(),
4700 'remove-self' => array()
4703 if ( empty( $wgAddGroups[$group] ) ) {
4704 // Don't add anything to $groups
4705 } elseif ( $wgAddGroups[$group] === true ) {
4706 // You get everything
4707 $groups['add'] = self
::getAllGroups();
4708 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4709 $groups['add'] = $wgAddGroups[$group];
4712 // Same thing for remove
4713 if ( empty( $wgRemoveGroups[$group] ) ) {
4715 } elseif ( $wgRemoveGroups[$group] === true ) {
4716 $groups['remove'] = self
::getAllGroups();
4717 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4718 $groups['remove'] = $wgRemoveGroups[$group];
4721 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4722 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4723 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4724 if ( is_int( $key ) ) {
4725 $wgGroupsAddToSelf['user'][] = $value;
4730 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4731 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4732 if ( is_int( $key ) ) {
4733 $wgGroupsRemoveFromSelf['user'][] = $value;
4738 // Now figure out what groups the user can add to him/herself
4739 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4741 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4742 // No idea WHY this would be used, but it's there
4743 $groups['add-self'] = User
::getAllGroups();
4744 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4745 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4748 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4750 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4751 $groups['remove-self'] = User
::getAllGroups();
4752 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4753 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4760 * Returns an array of groups that this user can add and remove
4761 * @return array Array( 'add' => array( addablegroups ),
4762 * 'remove' => array( removablegroups ),
4763 * 'add-self' => array( addablegroups to self),
4764 * 'remove-self' => array( removable groups from self) )
4766 public function changeableGroups() {
4767 if ( $this->isAllowed( 'userrights' ) ) {
4768 // This group gives the right to modify everything (reverse-
4769 // compatibility with old "userrights lets you change
4771 // Using array_merge to make the groups reindexed
4772 $all = array_merge( User
::getAllGroups() );
4776 'add-self' => array(),
4777 'remove-self' => array()
4781 // Okay, it's not so simple, we will have to go through the arrays
4784 'remove' => array(),
4785 'add-self' => array(),
4786 'remove-self' => array()
4788 $addergroups = $this->getEffectiveGroups();
4790 foreach ( $addergroups as $addergroup ) {
4791 $groups = array_merge_recursive(
4792 $groups, $this->changeableByGroup( $addergroup )
4794 $groups['add'] = array_unique( $groups['add'] );
4795 $groups['remove'] = array_unique( $groups['remove'] );
4796 $groups['add-self'] = array_unique( $groups['add-self'] );
4797 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4803 * Deferred version of incEditCountImmediate()
4805 public function incEditCount() {
4807 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $that ) {
4808 $that->incEditCountImmediate();
4813 * Increment the user's edit-count field.
4814 * Will have no effect for anonymous users.
4817 public function incEditCountImmediate() {
4818 if ( $this->isAnon() ) {
4822 $dbw = wfGetDB( DB_MASTER
);
4823 // No rows will be "affected" if user_editcount is NULL
4826 array( 'user_editcount=user_editcount+1' ),
4827 array( 'user_id' => $this->getId() ),
4830 // Lazy initialization check...
4831 if ( $dbw->affectedRows() == 0 ) {
4832 // Now here's a goddamn hack...
4833 $dbr = wfGetDB( DB_SLAVE
);
4834 if ( $dbr !== $dbw ) {
4835 // If we actually have a slave server, the count is
4836 // at least one behind because the current transaction
4837 // has not been committed and replicated.
4838 $this->initEditCount( 1 );
4840 // But if DB_SLAVE is selecting the master, then the
4841 // count we just read includes the revision that was
4842 // just added in the working transaction.
4843 $this->initEditCount();
4846 // Edit count in user cache too
4847 $this->invalidateCache();
4851 * Initialize user_editcount from data out of the revision table
4853 * @param int $add Edits to add to the count from the revision table
4854 * @return int Number of edits
4856 protected function initEditCount( $add = 0 ) {
4857 // Pull from a slave to be less cruel to servers
4858 // Accuracy isn't the point anyway here
4859 $dbr = wfGetDB( DB_SLAVE
);
4860 $count = (int)$dbr->selectField(
4863 array( 'rev_user' => $this->getId() ),
4866 $count = $count +
$add;
4868 $dbw = wfGetDB( DB_MASTER
);
4871 array( 'user_editcount' => $count ),
4872 array( 'user_id' => $this->getId() ),
4880 * Get the description of a given right
4882 * @param string $right Right to query
4883 * @return string Localized description of the right
4885 public static function getRightDescription( $right ) {
4886 $key = "right-$right";
4887 $msg = wfMessage( $key );
4888 return $msg->isBlank() ?
$right : $msg->text();
4892 * Make a new-style password hash
4894 * @param string $password Plain-text password
4895 * @param bool|string $salt Optional salt, may be random or the user ID.
4896 * If unspecified or false, will generate one automatically
4897 * @return string Password hash
4898 * @deprecated since 1.24, use Password class
4900 public static function crypt( $password, $salt = false ) {
4901 wfDeprecated( __METHOD__
, '1.24' );
4902 $hash = self
::getPasswordFactory()->newFromPlaintext( $password );
4903 return $hash->toString();
4907 * Compare a password hash with a plain-text password. Requires the user
4908 * ID if there's a chance that the hash is an old-style hash.
4910 * @param string $hash Password hash
4911 * @param string $password Plain-text password to compare
4912 * @param string|bool $userId User ID for old-style password salt
4915 * @deprecated since 1.24, use Password class
4917 public static function comparePasswords( $hash, $password, $userId = false ) {
4918 wfDeprecated( __METHOD__
, '1.24' );
4920 // Check for *really* old password hashes that don't even have a type
4921 // The old hash format was just an md5 hex hash, with no type information
4922 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4923 global $wgPasswordSalt;
4924 if ( $wgPasswordSalt ) {
4925 $password = ":B:{$userId}:{$hash}";
4927 $password = ":A:{$hash}";
4931 $hash = self
::getPasswordFactory()->newFromCiphertext( $hash );
4932 return $hash->equals( $password );
4936 * Add a newuser log entry for this user.
4937 * Before 1.19 the return value was always true.
4939 * @param string|bool $action Account creation type.
4940 * - String, one of the following values:
4941 * - 'create' for an anonymous user creating an account for himself.
4942 * This will force the action's performer to be the created user itself,
4943 * no matter the value of $wgUser
4944 * - 'create2' for a logged in user creating an account for someone else
4945 * - 'byemail' when the created user will receive its password by e-mail
4946 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4947 * - Boolean means whether the account was created by e-mail (deprecated):
4948 * - true will be converted to 'byemail'
4949 * - false will be converted to 'create' if this object is the same as
4950 * $wgUser and to 'create2' otherwise
4952 * @param string $reason User supplied reason
4954 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4956 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4957 global $wgUser, $wgNewUserLog;
4958 if ( empty( $wgNewUserLog ) ) {
4959 return true; // disabled
4962 if ( $action === true ) {
4963 $action = 'byemail';
4964 } elseif ( $action === false ) {
4965 if ( $this->equals( $wgUser ) ) {
4968 $action = 'create2';
4972 if ( $action === 'create' ||
$action === 'autocreate' ) {
4975 $performer = $wgUser;
4978 $logEntry = new ManualLogEntry( 'newusers', $action );
4979 $logEntry->setPerformer( $performer );
4980 $logEntry->setTarget( $this->getUserPage() );
4981 $logEntry->setComment( $reason );
4982 $logEntry->setParameters( array(
4983 '4::userid' => $this->getId(),
4985 $logid = $logEntry->insert();
4987 if ( $action !== 'autocreate' ) {
4988 $logEntry->publish( $logid );
4995 * Add an autocreate newuser log entry for this user
4996 * Used by things like CentralAuth and perhaps other authplugins.
4997 * Consider calling addNewUserLogEntry() directly instead.
5001 public function addNewUserLogEntryAutoCreate() {
5002 $this->addNewUserLogEntry( 'autocreate' );
5008 * Load the user options either from cache, the database or an array
5010 * @param array $data Rows for the current user out of the user_properties table
5012 protected function loadOptions( $data = null ) {
5017 if ( $this->mOptionsLoaded
) {
5021 $this->mOptions
= self
::getDefaultOptions();
5023 if ( !$this->getId() ) {
5024 // For unlogged-in users, load language/variant options from request.
5025 // There's no need to do it for logged-in users: they can set preferences,
5026 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5027 // so don't override user's choice (especially when the user chooses site default).
5028 $variant = $wgContLang->getDefaultVariant();
5029 $this->mOptions
['variant'] = $variant;
5030 $this->mOptions
['language'] = $variant;
5031 $this->mOptionsLoaded
= true;
5035 // Maybe load from the object
5036 if ( !is_null( $this->mOptionOverrides
) ) {
5037 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5038 foreach ( $this->mOptionOverrides
as $key => $value ) {
5039 $this->mOptions
[$key] = $value;
5042 if ( !is_array( $data ) ) {
5043 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5044 // Load from database
5045 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5046 ?
wfGetDB( DB_MASTER
)
5047 : wfGetDB( DB_SLAVE
);
5049 $res = $dbr->select(
5051 array( 'up_property', 'up_value' ),
5052 array( 'up_user' => $this->getId() ),
5056 $this->mOptionOverrides
= array();
5058 foreach ( $res as $row ) {
5059 $data[$row->up_property
] = $row->up_value
;
5062 foreach ( $data as $property => $value ) {
5063 $this->mOptionOverrides
[$property] = $value;
5064 $this->mOptions
[$property] = $value;
5068 $this->mOptionsLoaded
= true;
5070 Hooks
::run( 'UserLoadOptions', array( $this, &$this->mOptions
) );
5074 * Saves the non-default options for this user, as previously set e.g. via
5075 * setOption(), in the database's "user_properties" (preferences) table.
5076 * Usually used via saveSettings().
5078 protected function saveOptions() {
5079 $this->loadOptions();
5081 // Not using getOptions(), to keep hidden preferences in database
5082 $saveOptions = $this->mOptions
;
5084 // Allow hooks to abort, for instance to save to a global profile.
5085 // Reset options to default state before saving.
5086 if ( !Hooks
::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5090 $userId = $this->getId();
5092 $insert_rows = array(); // all the new preference rows
5093 foreach ( $saveOptions as $key => $value ) {
5094 // Don't bother storing default values
5095 $defaultOption = self
::getDefaultOption( $key );
5096 if ( ( $defaultOption === null && $value !== false && $value !== null )
5097 ||
$value != $defaultOption
5099 $insert_rows[] = array(
5100 'up_user' => $userId,
5101 'up_property' => $key,
5102 'up_value' => $value,
5107 $dbw = wfGetDB( DB_MASTER
);
5109 $res = $dbw->select( 'user_properties',
5110 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
5112 // Find prior rows that need to be removed or updated. These rows will
5113 // all be deleted (the later so that INSERT IGNORE applies the new values).
5114 $keysDelete = array();
5115 foreach ( $res as $row ) {
5116 if ( !isset( $saveOptions[$row->up_property
] )
5117 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5119 $keysDelete[] = $row->up_property
;
5123 if ( count( $keysDelete ) ) {
5124 // Do the DELETE by PRIMARY KEY for prior rows.
5125 // In the past a very large portion of calls to this function are for setting
5126 // 'rememberpassword' for new accounts (a preference that has since been removed).
5127 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5128 // caused gap locks on [max user ID,+infinity) which caused high contention since
5129 // updates would pile up on each other as they are for higher (newer) user IDs.
5130 // It might not be necessary these days, but it shouldn't hurt either.
5131 $dbw->delete( 'user_properties',
5132 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
5134 // Insert the new preference rows
5135 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
5139 * Lazily instantiate and return a factory object for making passwords
5141 * @return PasswordFactory
5143 public static function getPasswordFactory() {
5144 if ( self
::$mPasswordFactory === null ) {
5145 self
::$mPasswordFactory = new PasswordFactory();
5146 self
::$mPasswordFactory->init( RequestContext
::getMain()->getConfig() );
5149 return self
::$mPasswordFactory;
5153 * Provide an array of HTML5 attributes to put on an input element
5154 * intended for the user to enter a new password. This may include
5155 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5157 * Do *not* use this when asking the user to enter his current password!
5158 * Regardless of configuration, users may have invalid passwords for whatever
5159 * reason (e.g., they were set before requirements were tightened up).
5160 * Only use it when asking for a new password, like on account creation or
5163 * Obviously, you still need to do server-side checking.
5165 * NOTE: A combination of bugs in various browsers means that this function
5166 * actually just returns array() unconditionally at the moment. May as
5167 * well keep it around for when the browser bugs get fixed, though.
5169 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5171 * @return array Array of HTML attributes suitable for feeding to
5172 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5173 * That will get confused by the boolean attribute syntax used.)
5175 public static function passwordChangeInputAttribs() {
5176 global $wgMinimalPasswordLength;
5178 if ( $wgMinimalPasswordLength == 0 ) {
5182 # Note that the pattern requirement will always be satisfied if the
5183 # input is empty, so we need required in all cases.
5185 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5186 # if e-mail confirmation is being used. Since HTML5 input validation
5187 # is b0rked anyway in some browsers, just return nothing. When it's
5188 # re-enabled, fix this code to not output required for e-mail
5190 #$ret = array( 'required' );
5193 # We can't actually do this right now, because Opera 9.6 will print out
5194 # the entered password visibly in its error message! When other
5195 # browsers add support for this attribute, or Opera fixes its support,
5196 # we can add support with a version check to avoid doing this on Opera
5197 # versions where it will be a problem. Reported to Opera as
5198 # DSK-262266, but they don't have a public bug tracker for us to follow.
5200 if ( $wgMinimalPasswordLength > 1 ) {
5201 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5202 $ret['title'] = wfMessage( 'passwordtooshort' )
5203 ->numParams( $wgMinimalPasswordLength )->text();
5211 * Return the list of user fields that should be selected to create
5212 * a new user object.
5215 public static function selectFields() {
5223 'user_email_authenticated',
5225 'user_email_token_expires',
5226 'user_registration',
5232 * Factory function for fatal permission-denied errors
5235 * @param string $permission User right required
5238 static function newFatalPermissionDeniedStatus( $permission ) {
5241 $groups = array_map(
5242 array( 'User', 'makeGroupLinkWiki' ),
5243 User
::getGroupsWithPermission( $permission )
5247 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5249 return Status
::newFatal( 'badaccess-group0' );
5254 * Checks if two user objects point to the same user.
5260 public function equals( User
$user ) {
5261 return $this->getName() === $user->getName();