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 * Int Number of characters in user_token field.
27 define( 'USER_TOKEN_LENGTH', 32 );
30 * Int Serialized record version.
33 define( 'MW_USER_VERSION', 9 );
36 * String Some punctuation to prevent editing from broken text-mangling proxies.
39 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
42 * Thrown by User::setPassword() on error.
45 class PasswordError
extends MWException
{
50 * The User object encapsulates all of the user-specific settings (user_id,
51 * name, rights, password, email address, options, last login time). Client
52 * classes use the getXXX() functions to access these fields. These functions
53 * do all the work of determining whether the user is logged in,
54 * whether the requested option can be satisfied from cookies or
55 * whether a database query is needed. Most of the settings needed
56 * for rendering normal pages are set in the cookie to minimize use
59 class User
implements IDBAccessObject
{
61 * Global constants made accessible as class constants so that autoloader
64 const USER_TOKEN_LENGTH
= USER_TOKEN_LENGTH
;
65 const MW_USER_VERSION
= MW_USER_VERSION
;
66 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
69 * Maximum items in $mWatchedItems
71 const MAX_WATCHED_ITEMS_CACHE
= 100;
74 * Array of Strings List of member variables which are saved to the
75 * shared cache (memcached). Any operation which changes the
76 * corresponding database fields must call a cache-clearing function.
79 protected static $mCacheVars = array(
90 'mEmailAuthenticated',
98 // user_properties table
103 * Array of Strings Core rights.
104 * Each of these should have a corresponding message of the form
108 protected static $mCoreRights = array(
134 'editusercssjs', #deprecated
146 'move-categorypages',
147 'move-rootuserpages',
151 'override-export-depth',
175 'userrights-interwiki',
182 * String Cached results of getAllRights()
184 protected static $mAllRights = false;
186 /** @name Cache variables */
196 public $mNewpassword;
198 public $mNewpassTime;
206 public $mEmailAuthenticated;
208 protected $mEmailToken;
210 protected $mEmailTokenExpires;
212 protected $mRegistration;
214 protected $mEditCount;
218 protected $mOptionOverrides;
220 protected $mPasswordExpires;
224 * Bool Whether the cache variables have been loaded.
227 public $mOptionsLoaded;
230 * Array with already loaded items or true if all items have been loaded.
232 protected $mLoadedItems = array();
236 * String Initialization data source if mLoadedItems!==true. May be one of:
237 * - 'defaults' anonymous user initialised from class defaults
238 * - 'name' initialise from mName
239 * - 'id' initialise from mId
240 * - 'session' log in from cookies or session if possible
242 * Use the User::newFrom*() family of functions to set this.
247 * Lazy-initialized variables, invalidated with clearInstanceCache
251 protected $mDatePreference;
259 protected $mBlockreason;
261 protected $mEffectiveGroups;
263 protected $mImplicitGroups;
265 protected $mFormerGroups;
267 protected $mBlockedGlobally;
284 protected $mAllowUsertalk;
287 private $mBlockedFromCreateAccount = false;
290 private $mWatchedItems = array();
292 public static $idCacheByName = array();
295 * Lightweight constructor for an anonymous user.
296 * Use the User::newFrom* factory functions for other kinds of users.
300 * @see newFromConfirmationCode()
301 * @see newFromSession()
304 public function __construct() {
305 $this->clearInstanceCache( 'defaults' );
311 public function __toString() {
312 return $this->getName();
316 * Load the user table data for this object from the source given by mFrom.
318 public function load() {
319 if ( $this->mLoadedItems
=== true ) {
322 wfProfileIn( __METHOD__
);
324 // Set it now to avoid infinite recursion in accessors
325 $this->mLoadedItems
= true;
327 switch ( $this->mFrom
) {
329 $this->loadDefaults();
332 $this->mId
= self
::idFromName( $this->mName
);
334 // Nonexistent user placeholder object
335 $this->loadDefaults( $this->mName
);
344 if ( !$this->loadFromSession() ) {
345 // Loading from session failed. Load defaults.
346 $this->loadDefaults();
348 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
351 wfProfileOut( __METHOD__
);
352 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
354 wfProfileOut( __METHOD__
);
358 * Load user table data, given mId has already been set.
359 * @return bool false if the ID does not exist, true otherwise
361 public function loadFromId() {
363 if ( $this->mId
== 0 ) {
364 $this->loadDefaults();
369 $key = wfMemcKey( 'user', 'id', $this->mId
);
370 $data = $wgMemc->get( $key );
371 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
372 // Object is expired, load from DB
377 wfDebug( "User: cache miss for user {$this->mId}\n" );
379 if ( !$this->loadFromDatabase() ) {
380 // Can't load from ID, user is anonymous
383 $this->saveToCache();
385 wfDebug( "User: got user {$this->mId} from cache\n" );
386 // Restore from cache
387 foreach ( self
::$mCacheVars as $name ) {
388 $this->$name = $data[$name];
392 $this->mLoadedItems
= true;
398 * Save user data to the shared cache
400 public function saveToCache() {
403 $this->loadOptions();
404 if ( $this->isAnon() ) {
405 // Anonymous users are uncached
409 foreach ( self
::$mCacheVars as $name ) {
410 $data[$name] = $this->$name;
412 $data['mVersion'] = MW_USER_VERSION
;
413 $key = wfMemcKey( 'user', 'id', $this->mId
);
415 $wgMemc->set( $key, $data );
418 /** @name newFrom*() static factory methods */
422 * Static factory method for creation from username.
424 * This is slightly less efficient than newFromId(), so use newFromId() if
425 * you have both an ID and a name handy.
427 * @param string $name Username, validated by Title::newFromText()
428 * @param string|bool $validate Validate username. Takes the same parameters as
429 * User::getCanonicalName(), except that true is accepted as an alias
430 * for 'valid', for BC.
432 * @return User|bool User object, or false if the username is invalid
433 * (e.g. if it contains illegal characters or is an IP address). If the
434 * username is not present in the database, the result will be a user object
435 * with a name, zero user ID and default settings.
437 public static function newFromName( $name, $validate = 'valid' ) {
438 if ( $validate === true ) {
441 $name = self
::getCanonicalName( $name, $validate );
442 if ( $name === false ) {
445 // Create unloaded user object
449 $u->setItemLoaded( 'name' );
455 * Static factory method for creation from a given user ID.
457 * @param int $id Valid user ID
458 * @return User The corresponding User object
460 public static function newFromId( $id ) {
464 $u->setItemLoaded( 'id' );
469 * Factory method to fetch whichever user has a given email confirmation code.
470 * This code is generated when an account is created or its e-mail address
473 * If the code is invalid or has expired, returns NULL.
475 * @param string $code Confirmation code
478 public static function newFromConfirmationCode( $code ) {
479 $dbr = wfGetDB( DB_SLAVE
);
480 $id = $dbr->selectField( 'user', 'user_id', array(
481 'user_email_token' => md5( $code ),
482 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
484 if ( $id !== false ) {
485 return User
::newFromId( $id );
492 * Create a new user object using data from session or cookies. If the
493 * login credentials are invalid, the result is an anonymous user.
495 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
498 public static function newFromSession( WebRequest
$request = null ) {
500 $user->mFrom
= 'session';
501 $user->mRequest
= $request;
506 * Create a new user object from a user row.
507 * The row should have the following fields from the user table in it:
508 * - either user_name or user_id to load further data if needed (or both)
510 * - all other fields (email, password, etc.)
511 * It is useless to provide the remaining fields if either user_id,
512 * user_name and user_real_name are not provided because the whole row
513 * will be loaded once more from the database when accessing them.
515 * @param stdClass $row A row from the user table
516 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
519 public static function newFromRow( $row, $data = null ) {
521 $user->loadFromRow( $row, $data );
528 * Get the username corresponding to a given user ID
529 * @param int $id User ID
530 * @return string|bool The corresponding username
532 public static function whoIs( $id ) {
533 return UserCache
::singleton()->getProp( $id, 'name' );
537 * Get the real name of a user given their user ID
539 * @param int $id User ID
540 * @return string|bool The corresponding user's real name
542 public static function whoIsReal( $id ) {
543 return UserCache
::singleton()->getProp( $id, 'real_name' );
547 * Get database id given a user name
548 * @param string $name Username
549 * @return int|null The corresponding user's ID, or null if user is nonexistent
551 public static function idFromName( $name ) {
552 $nt = Title
::makeTitleSafe( NS_USER
, $name );
553 if ( is_null( $nt ) ) {
558 if ( isset( self
::$idCacheByName[$name] ) ) {
559 return self
::$idCacheByName[$name];
562 $dbr = wfGetDB( DB_SLAVE
);
563 $s = $dbr->selectRow(
566 array( 'user_name' => $nt->getText() ),
570 if ( $s === false ) {
573 $result = $s->user_id
;
576 self
::$idCacheByName[$name] = $result;
578 if ( count( self
::$idCacheByName ) > 1000 ) {
579 self
::$idCacheByName = array();
586 * Reset the cache used in idFromName(). For use in tests.
588 public static function resetIdByNameCache() {
589 self
::$idCacheByName = array();
593 * Does the string match an anonymous IPv4 address?
595 * This function exists for username validation, in order to reject
596 * usernames which are similar in form to IP addresses. Strings such
597 * as 300.300.300.300 will return true because it looks like an IP
598 * address, despite not being strictly valid.
600 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
601 * address because the usemod software would "cloak" anonymous IP
602 * addresses like this, if we allowed accounts like this to be created
603 * new users could get the old edits of these anonymous users.
605 * @param string $name Name to match
608 public static function isIP( $name ) {
609 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
610 || IP
::isIPv6( $name );
614 * Is the input a valid username?
616 * Checks if the input is a valid username, we don't want an empty string,
617 * an IP address, anything that contains slashes (would mess up subpages),
618 * is longer than the maximum allowed username size or doesn't begin with
621 * @param string $name Name to match
624 public static function isValidUserName( $name ) {
625 global $wgContLang, $wgMaxNameChars;
628 || User
::isIP( $name )
629 ||
strpos( $name, '/' ) !== false
630 ||
strlen( $name ) > $wgMaxNameChars
631 ||
$name != $wgContLang->ucfirst( $name ) ) {
632 wfDebugLog( 'username', __METHOD__
.
633 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
637 // Ensure that the name can't be misresolved as a different title,
638 // such as with extra namespace keys at the start.
639 $parsed = Title
::newFromText( $name );
640 if ( is_null( $parsed )
641 ||
$parsed->getNamespace()
642 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
643 wfDebugLog( 'username', __METHOD__
.
644 ": '$name' invalid due to ambiguous prefixes" );
648 // Check an additional blacklist of troublemaker characters.
649 // Should these be merged into the title char list?
650 $unicodeBlacklist = '/[' .
651 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
652 '\x{00a0}' . # non-breaking space
653 '\x{2000}-\x{200f}' . # various whitespace
654 '\x{2028}-\x{202f}' . # breaks and control chars
655 '\x{3000}' . # ideographic space
656 '\x{e000}-\x{f8ff}' . # private use
658 if ( preg_match( $unicodeBlacklist, $name ) ) {
659 wfDebugLog( 'username', __METHOD__
.
660 ": '$name' invalid due to blacklisted characters" );
668 * Usernames which fail to pass this function will be blocked
669 * from user login and new account registrations, but may be used
670 * internally by batch processes.
672 * If an account already exists in this form, login will be blocked
673 * by a failure to pass this function.
675 * @param string $name Name to match
678 public static function isUsableName( $name ) {
679 global $wgReservedUsernames;
680 // Must be a valid username, obviously ;)
681 if ( !self
::isValidUserName( $name ) ) {
685 static $reservedUsernames = false;
686 if ( !$reservedUsernames ) {
687 $reservedUsernames = $wgReservedUsernames;
688 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
691 // Certain names may be reserved for batch processes.
692 foreach ( $reservedUsernames as $reserved ) {
693 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
694 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
696 if ( $reserved == $name ) {
704 * Usernames which fail to pass this function will be blocked
705 * from new account registrations, but may be used internally
706 * either by batch processes or by user accounts which have
707 * already been created.
709 * Additional blacklisting may be added here rather than in
710 * isValidUserName() to avoid disrupting existing accounts.
712 * @param string $name String to match
715 public static function isCreatableName( $name ) {
716 global $wgInvalidUsernameCharacters;
718 // Ensure that the username isn't longer than 235 bytes, so that
719 // (at least for the builtin skins) user javascript and css files
720 // will work. (bug 23080)
721 if ( strlen( $name ) > 235 ) {
722 wfDebugLog( 'username', __METHOD__
.
723 ": '$name' invalid due to length" );
727 // Preg yells if you try to give it an empty string
728 if ( $wgInvalidUsernameCharacters !== '' ) {
729 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
730 wfDebugLog( 'username', __METHOD__
.
731 ": '$name' invalid due to wgInvalidUsernameCharacters" );
736 return self
::isUsableName( $name );
740 * Is the input a valid password for this user?
742 * @param string $password Desired password
745 public function isValidPassword( $password ) {
746 //simple boolean wrapper for getPasswordValidity
747 return $this->getPasswordValidity( $password ) === true;
752 * Given unvalidated password input, return error message on failure.
754 * @param string $password Desired password
755 * @return bool|string|array true on success, string or array of error message on failure
757 public function getPasswordValidity( $password ) {
758 $result = $this->checkPasswordValidity( $password );
759 if ( $result->isGood() ) {
763 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
764 $messages[] = $error['message'];
766 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
767 $messages[] = $warning['message'];
769 if ( count( $messages ) === 1 ) {
777 * Check if this is a valid password for this user. Status will be good if
778 * the password is valid, or have an array of error messages if not.
780 * @param string $password Desired password
784 public function checkPasswordValidity( $password ) {
785 global $wgMinimalPasswordLength, $wgContLang;
787 static $blockedLogins = array(
788 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
789 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
792 $status = Status
::newGood();
794 $result = false; //init $result to false for the internal checks
796 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
797 $status->error( $result );
801 if ( $result === false ) {
802 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
803 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
805 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
806 $status->error( 'password-name-match' );
808 } elseif ( isset( $blockedLogins[$this->getName()] )
809 && $password == $blockedLogins[$this->getName()]
811 $status->error( 'password-login-forbidden' );
814 //it seems weird returning a Good status here, but this is because of the
815 //initialization of $result to false above. If the hook is never run or it
816 //doesn't modify $result, then we will likely get down into this if with
820 } elseif ( $result === true ) {
823 $status->error( $result );
824 return $status; //the isValidPassword hook set a string $result and returned true
829 * Expire a user's password
831 * @param int $ts Optional timestamp to convert, default 0 for the current time
833 public function expirePassword( $ts = 0 ) {
835 $timestamp = wfTimestamp( TS_MW
, $ts );
836 $this->mPasswordExpires
= $timestamp;
837 $this->saveSettings();
841 * Clear the password expiration for a user
843 * @param bool $load Ensure user object is loaded first
845 public function resetPasswordExpiration( $load = true ) {
846 global $wgPasswordExpirationDays;
851 if ( $wgPasswordExpirationDays ) {
852 $newExpire = wfTimestamp(
854 time() +
( $wgPasswordExpirationDays * 24 * 3600 )
857 // Give extensions a chance to force an expiration
858 wfRunHooks( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
859 $this->mPasswordExpires
= $newExpire;
863 * Check if the user's password is expired.
864 * TODO: Put this and password length into a PasswordPolicy object
866 * @return string|bool The expiration type, or false if not expired
867 * hard: A password change is required to login
868 * soft: Allow login, but encourage password change
869 * false: Password is not expired
871 public function getPasswordExpired() {
872 global $wgPasswordExpireGrace;
874 $now = wfTimestamp();
875 $expiration = $this->getPasswordExpireDate();
876 $expUnix = wfTimestamp( TS_UNIX
, $expiration );
877 if ( $expiration !== null && $expUnix < $now ) {
878 $expired = ( $expUnix +
$wgPasswordExpireGrace < $now ) ?
'hard' : 'soft';
884 * Get this user's password expiration date. Since this may be using
885 * the cached User object, we assume that whatever mechanism is setting
886 * the expiration date is also expiring the User cache.
888 * @return string|bool The datestamp of the expiration, or null if not set
890 public function getPasswordExpireDate() {
892 return $this->mPasswordExpires
;
896 * Does a string look like an e-mail address?
898 * This validates an email address using an HTML5 specification found at:
899 * http://www.whatwg.org/html/states-of-the-type-attribute.html#valid-e-mail-address
900 * Which as of 2011-01-24 says:
902 * A valid e-mail address is a string that matches the ABNF production
903 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
904 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
907 * This function is an implementation of the specification as requested in
910 * Client-side forms will use the same standard validation rules via JS or
911 * HTML 5 validation; additional restrictions can be enforced server-side
912 * by extensions via the 'isValidEmailAddr' hook.
914 * Note that this validation doesn't 100% match RFC 2822, but is believed
915 * to be liberal enough for wide use. Some invalid addresses will still
916 * pass validation here.
918 * @param string $addr E-mail address
920 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
922 public static function isValidEmailAddr( $addr ) {
923 wfDeprecated( __METHOD__
, '1.18' );
924 return Sanitizer
::validateEmail( $addr );
928 * Given unvalidated user input, return a canonical username, or false if
929 * the username is invalid.
930 * @param string $name User input
931 * @param string|bool $validate Type of validation to use:
932 * - false No validation
933 * - 'valid' Valid for batch processes
934 * - 'usable' Valid for batch processes and login
935 * - 'creatable' Valid for batch processes, login and account creation
937 * @throws MWException
938 * @return bool|string
940 public static function getCanonicalName( $name, $validate = 'valid' ) {
941 // Force usernames to capital
943 $name = $wgContLang->ucfirst( $name );
945 # Reject names containing '#'; these will be cleaned up
946 # with title normalisation, but then it's too late to
948 if ( strpos( $name, '#' ) !== false ) {
952 // Clean up name according to title rules
953 $t = ( $validate === 'valid' ) ?
954 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
955 // Check for invalid titles
956 if ( is_null( $t ) ) {
960 // Reject various classes of invalid names
962 $name = $wgAuth->getCanonicalName( $t->getText() );
964 switch ( $validate ) {
968 if ( !User
::isValidUserName( $name ) ) {
973 if ( !User
::isUsableName( $name ) ) {
978 if ( !User
::isCreatableName( $name ) ) {
983 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
989 * Count the number of edits of a user
991 * @param int $uid User ID to check
992 * @return int The user's edit count
994 * @deprecated since 1.21 in favour of User::getEditCount
996 public static function edits( $uid ) {
997 wfDeprecated( __METHOD__
, '1.21' );
998 $user = self
::newFromId( $uid );
999 return $user->getEditCount();
1003 * Return a random password.
1005 * @return string New random password
1007 public static function randomPassword() {
1008 global $wgMinimalPasswordLength;
1009 // Decide the final password length based on our min password length,
1010 // stopping at a minimum of 10 chars.
1011 $length = max( 10, $wgMinimalPasswordLength );
1012 // Multiply by 1.25 to get the number of hex characters we need
1013 $length = $length * 1.25;
1014 // Generate random hex chars
1015 $hex = MWCryptRand
::generateHex( $length );
1016 // Convert from base 16 to base 32 to get a proper password like string
1017 return wfBaseConvert( $hex, 16, 32 );
1021 * Set cached properties to default.
1023 * @note This no longer clears uncached lazy-initialised properties;
1024 * the constructor does that instead.
1026 * @param string|bool $name
1028 public function loadDefaults( $name = false ) {
1029 wfProfileIn( __METHOD__
);
1032 $this->mName
= $name;
1033 $this->mRealName
= '';
1034 $this->mPassword
= $this->mNewpassword
= '';
1035 $this->mNewpassTime
= null;
1037 $this->mOptionOverrides
= null;
1038 $this->mOptionsLoaded
= false;
1040 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1041 if ( $loggedOut !== null ) {
1042 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1044 $this->mTouched
= '1'; # Allow any pages to be cached
1047 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1048 $this->mEmailAuthenticated
= null;
1049 $this->mEmailToken
= '';
1050 $this->mEmailTokenExpires
= null;
1051 $this->mPasswordExpires
= null;
1052 $this->resetPasswordExpiration( false );
1053 $this->mRegistration
= wfTimestamp( TS_MW
);
1054 $this->mGroups
= array();
1056 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
1058 wfProfileOut( __METHOD__
);
1062 * Return whether an item has been loaded.
1064 * @param string $item Item to check. Current possibilities:
1068 * @param string $all 'all' to check if the whole object has been loaded
1069 * or any other string to check if only the item is available (e.g.
1073 public function isItemLoaded( $item, $all = 'all' ) {
1074 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1075 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1079 * Set that an item has been loaded
1081 * @param string $item
1083 protected function setItemLoaded( $item ) {
1084 if ( is_array( $this->mLoadedItems
) ) {
1085 $this->mLoadedItems
[$item] = true;
1090 * Load user data from the session or login cookie.
1091 * @return bool True if the user is logged in, false otherwise.
1093 private function loadFromSession() {
1095 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
1096 if ( $result !== null ) {
1100 $request = $this->getRequest();
1102 $cookieId = $request->getCookie( 'UserID' );
1103 $sessId = $request->getSessionData( 'wsUserID' );
1105 if ( $cookieId !== null ) {
1106 $sId = intval( $cookieId );
1107 if ( $sessId !== null && $cookieId != $sessId ) {
1108 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1109 cookie user ID ($sId) don't match!" );
1112 $request->setSessionData( 'wsUserID', $sId );
1113 } elseif ( $sessId !== null && $sessId != 0 ) {
1119 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1120 $sName = $request->getSessionData( 'wsUserName' );
1121 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1122 $sName = $request->getCookie( 'UserName' );
1123 $request->setSessionData( 'wsUserName', $sName );
1128 $proposedUser = User
::newFromId( $sId );
1129 if ( !$proposedUser->isLoggedIn() ) {
1134 global $wgBlockDisablesLogin;
1135 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1136 // User blocked and we've disabled blocked user logins
1140 if ( $request->getSessionData( 'wsToken' ) ) {
1142 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1144 } elseif ( $request->getCookie( 'Token' ) ) {
1145 # Get the token from DB/cache and clean it up to remove garbage padding.
1146 # This deals with historical problems with bugs and the default column value.
1147 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1148 // Make comparison in constant time (bug 61346)
1149 $passwordCorrect = strlen( $token )
1150 && hash_equals( $token, $request->getCookie( 'Token' ) );
1153 // No session or persistent login cookie
1157 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1158 $this->loadFromUserObject( $proposedUser );
1159 $request->setSessionData( 'wsToken', $this->mToken
);
1160 wfDebug( "User: logged in from $from\n" );
1163 // Invalid credentials
1164 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1170 * Load user and user_group data from the database.
1171 * $this->mId must be set, this is how the user is identified.
1173 * @param integer $flags Supports User::READ_LOCKING
1174 * @return bool True if the user exists, false if the user is anonymous
1176 public function loadFromDatabase( $flags = 0 ) {
1178 $this->mId
= intval( $this->mId
);
1181 if ( !$this->mId
) {
1182 $this->loadDefaults();
1186 $dbr = wfGetDB( DB_MASTER
);
1187 $s = $dbr->selectRow(
1189 self
::selectFields(),
1190 array( 'user_id' => $this->mId
),
1192 ( $flags & self
::READ_LOCKING
== self
::READ_LOCKING
)
1193 ?
array( 'LOCK IN SHARE MODE' )
1197 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1199 if ( $s !== false ) {
1200 // Initialise user table data
1201 $this->loadFromRow( $s );
1202 $this->mGroups
= null; // deferred
1203 $this->getEditCount(); // revalidation for nulls
1208 $this->loadDefaults();
1214 * Initialize this object from a row from the user table.
1216 * @param stdClass $row Row from the user table to load.
1217 * @param array $data Further user data to load into the object
1219 * user_groups Array with groups out of the user_groups table
1220 * user_properties Array with properties out of the user_properties table
1222 public function loadFromRow( $row, $data = null ) {
1225 $this->mGroups
= null; // deferred
1227 if ( isset( $row->user_name
) ) {
1228 $this->mName
= $row->user_name
;
1229 $this->mFrom
= 'name';
1230 $this->setItemLoaded( 'name' );
1235 if ( isset( $row->user_real_name
) ) {
1236 $this->mRealName
= $row->user_real_name
;
1237 $this->setItemLoaded( 'realname' );
1242 if ( isset( $row->user_id
) ) {
1243 $this->mId
= intval( $row->user_id
);
1244 $this->mFrom
= 'id';
1245 $this->setItemLoaded( 'id' );
1250 if ( isset( $row->user_editcount
) ) {
1251 $this->mEditCount
= $row->user_editcount
;
1256 if ( isset( $row->user_password
) ) {
1257 $this->mPassword
= $row->user_password
;
1258 $this->mNewpassword
= $row->user_newpassword
;
1259 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1260 $this->mEmail
= $row->user_email
;
1261 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1262 $this->mToken
= $row->user_token
;
1263 if ( $this->mToken
== '' ) {
1264 $this->mToken
= null;
1266 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1267 $this->mEmailToken
= $row->user_email_token
;
1268 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1269 $this->mPasswordExpires
= wfTimestampOrNull( TS_MW
, $row->user_password_expires
);
1270 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1276 $this->mLoadedItems
= true;
1279 if ( is_array( $data ) ) {
1280 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1281 $this->mGroups
= $data['user_groups'];
1283 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1284 $this->loadOptions( $data['user_properties'] );
1290 * Load the data for this user object from another user object.
1294 protected function loadFromUserObject( $user ) {
1296 $user->loadGroups();
1297 $user->loadOptions();
1298 foreach ( self
::$mCacheVars as $var ) {
1299 $this->$var = $user->$var;
1304 * Load the groups from the database if they aren't already loaded.
1306 private function loadGroups() {
1307 if ( is_null( $this->mGroups
) ) {
1308 $dbr = wfGetDB( DB_MASTER
);
1309 $res = $dbr->select( 'user_groups',
1310 array( 'ug_group' ),
1311 array( 'ug_user' => $this->mId
),
1313 $this->mGroups
= array();
1314 foreach ( $res as $row ) {
1315 $this->mGroups
[] = $row->ug_group
;
1321 * Add the user to the group if he/she meets given criteria.
1323 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1324 * possible to remove manually via Special:UserRights. In such case it
1325 * will not be re-added automatically. The user will also not lose the
1326 * group if they no longer meet the criteria.
1328 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1330 * @return array Array of groups the user has been promoted to.
1332 * @see $wgAutopromoteOnce
1334 public function addAutopromoteOnceGroups( $event ) {
1335 global $wgAutopromoteOnceLogInRC, $wgAuth;
1337 $toPromote = array();
1338 if ( $this->getId() ) {
1339 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1340 if ( count( $toPromote ) ) {
1341 $oldGroups = $this->getGroups(); // previous groups
1343 foreach ( $toPromote as $group ) {
1344 $this->addGroup( $group );
1346 // update groups in external authentication database
1347 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1349 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1351 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1352 $logEntry->setPerformer( $this );
1353 $logEntry->setTarget( $this->getUserPage() );
1354 $logEntry->setParameters( array(
1355 '4::oldgroups' => $oldGroups,
1356 '5::newgroups' => $newGroups,
1358 $logid = $logEntry->insert();
1359 if ( $wgAutopromoteOnceLogInRC ) {
1360 $logEntry->publish( $logid );
1368 * Clear various cached data stored in this object. The cache of the user table
1369 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1371 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1372 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1374 public function clearInstanceCache( $reloadFrom = false ) {
1375 $this->mNewtalk
= -1;
1376 $this->mDatePreference
= null;
1377 $this->mBlockedby
= -1; # Unset
1378 $this->mHash
= false;
1379 $this->mRights
= null;
1380 $this->mEffectiveGroups
= null;
1381 $this->mImplicitGroups
= null;
1382 $this->mGroups
= null;
1383 $this->mOptions
= null;
1384 $this->mOptionsLoaded
= false;
1385 $this->mEditCount
= null;
1387 if ( $reloadFrom ) {
1388 $this->mLoadedItems
= array();
1389 $this->mFrom
= $reloadFrom;
1394 * Combine the language default options with any site-specific options
1395 * and add the default language variants.
1397 * @return array Array of String options
1399 public static function getDefaultOptions() {
1400 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1402 static $defOpt = null;
1403 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1404 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1405 // mid-request and see that change reflected in the return value of this function.
1406 // Which is insane and would never happen during normal MW operation
1410 $defOpt = $wgDefaultUserOptions;
1411 // Default language setting
1412 $defOpt['language'] = $wgContLang->getCode();
1413 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1414 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1416 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1417 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1419 $defOpt['skin'] = $wgDefaultSkin;
1421 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1427 * Get a given default option value.
1429 * @param string $opt Name of option to retrieve
1430 * @return string Default option value
1432 public static function getDefaultOption( $opt ) {
1433 $defOpts = self
::getDefaultOptions();
1434 if ( isset( $defOpts[$opt] ) ) {
1435 return $defOpts[$opt];
1442 * Get blocking information
1443 * @param bool $bFromSlave Whether to check the slave database first.
1444 * To improve performance, non-critical checks are done against slaves.
1445 * Check when actually saving should be done against master.
1447 private function getBlockedStatus( $bFromSlave = true ) {
1448 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1450 if ( -1 != $this->mBlockedby
) {
1454 wfProfileIn( __METHOD__
);
1455 wfDebug( __METHOD__
. ": checking...\n" );
1457 // Initialize data...
1458 // Otherwise something ends up stomping on $this->mBlockedby when
1459 // things get lazy-loaded later, causing false positive block hits
1460 // due to -1 !== 0. Probably session-related... Nothing should be
1461 // overwriting mBlockedby, surely?
1464 # We only need to worry about passing the IP address to the Block generator if the
1465 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1466 # know which IP address they're actually coming from
1467 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1468 $ip = $this->getRequest()->getIP();
1474 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1477 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1478 && !in_array( $ip, $wgProxyWhitelist )
1481 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1483 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1484 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1485 $block->setTarget( $ip );
1486 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1488 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1489 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1490 $block->setTarget( $ip );
1494 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1495 if ( !$block instanceof Block
1496 && $wgApplyIpBlocksToXff
1498 && !$this->isAllowed( 'proxyunbannable' )
1499 && !in_array( $ip, $wgProxyWhitelist )
1501 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1502 $xff = array_map( 'trim', explode( ',', $xff ) );
1503 $xff = array_diff( $xff, array( $ip ) );
1504 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1505 $block = Block
::chooseBlock( $xffblocks, $xff );
1506 if ( $block instanceof Block
) {
1507 # Mangle the reason to alert the user that the block
1508 # originated from matching the X-Forwarded-For header.
1509 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1513 if ( $block instanceof Block
) {
1514 wfDebug( __METHOD__
. ": Found block.\n" );
1515 $this->mBlock
= $block;
1516 $this->mBlockedby
= $block->getByName();
1517 $this->mBlockreason
= $block->mReason
;
1518 $this->mHideName
= $block->mHideName
;
1519 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1521 $this->mBlockedby
= '';
1522 $this->mHideName
= 0;
1523 $this->mAllowUsertalk
= false;
1527 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1529 wfProfileOut( __METHOD__
);
1533 * Whether the given IP is in a DNS blacklist.
1535 * @param string $ip IP to check
1536 * @param bool $checkWhitelist Whether to check the whitelist first
1537 * @return bool True if blacklisted.
1539 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1540 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1541 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1543 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs ) {
1547 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1551 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1552 return $this->inDnsBlacklist( $ip, $urls );
1556 * Whether the given IP is in a given DNS blacklist.
1558 * @param string $ip IP to check
1559 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1560 * @return bool True if blacklisted.
1562 public function inDnsBlacklist( $ip, $bases ) {
1563 wfProfileIn( __METHOD__
);
1566 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1567 if ( IP
::isIPv4( $ip ) ) {
1568 // Reverse IP, bug 21255
1569 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1571 foreach ( (array)$bases as $base ) {
1573 // If we have an access key, use that too (ProjectHoneypot, etc.)
1574 if ( is_array( $base ) ) {
1575 if ( count( $base ) >= 2 ) {
1576 // Access key is 1, base URL is 0
1577 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1579 $host = "$ipReversed.{$base[0]}";
1582 $host = "$ipReversed.$base";
1586 $ipList = gethostbynamel( $host );
1589 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1593 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1598 wfProfileOut( __METHOD__
);
1603 * Check if an IP address is in the local proxy list
1609 public static function isLocallyBlockedProxy( $ip ) {
1610 global $wgProxyList;
1612 if ( !$wgProxyList ) {
1615 wfProfileIn( __METHOD__
);
1617 if ( !is_array( $wgProxyList ) ) {
1618 // Load from the specified file
1619 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1622 if ( !is_array( $wgProxyList ) ) {
1624 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1626 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1627 // Old-style flipped proxy list
1632 wfProfileOut( __METHOD__
);
1637 * Is this user subject to rate limiting?
1639 * @return bool True if rate limited
1641 public function isPingLimitable() {
1642 global $wgRateLimitsExcludedIPs;
1643 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1644 // No other good way currently to disable rate limits
1645 // for specific IPs. :P
1646 // But this is a crappy hack and should die.
1649 return !$this->isAllowed( 'noratelimit' );
1653 * Primitive rate limits: enforce maximum actions per time period
1654 * to put a brake on flooding.
1656 * The method generates both a generic profiling point and a per action one
1657 * (suffix being "-$action".
1659 * @note When using a shared cache like memcached, IP-address
1660 * last-hit counters will be shared across wikis.
1662 * @param string $action Action to enforce; 'edit' if unspecified
1663 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1664 * @return bool True if a rate limiter was tripped
1666 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1667 // Call the 'PingLimiter' hook
1669 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1673 global $wgRateLimits;
1674 if ( !isset( $wgRateLimits[$action] ) ) {
1678 // Some groups shouldn't trigger the ping limiter, ever
1679 if ( !$this->isPingLimitable() ) {
1684 wfProfileIn( __METHOD__
);
1685 wfProfileIn( __METHOD__
. '-' . $action );
1687 $limits = $wgRateLimits[$action];
1689 $id = $this->getId();
1692 if ( isset( $limits['anon'] ) && $id == 0 ) {
1693 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1696 if ( isset( $limits['user'] ) && $id != 0 ) {
1697 $userLimit = $limits['user'];
1699 if ( $this->isNewbie() ) {
1700 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1701 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1703 if ( isset( $limits['ip'] ) ) {
1704 $ip = $this->getRequest()->getIP();
1705 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1707 if ( isset( $limits['subnet'] ) ) {
1708 $ip = $this->getRequest()->getIP();
1711 if ( IP
::isIPv6( $ip ) ) {
1712 $parts = IP
::parseRange( "$ip/64" );
1713 $subnet = $parts[0];
1714 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1716 $subnet = $matches[1];
1718 if ( $subnet !== false ) {
1719 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1723 // Check for group-specific permissions
1724 // If more than one group applies, use the group with the highest limit
1725 foreach ( $this->getGroups() as $group ) {
1726 if ( isset( $limits[$group] ) ) {
1727 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1728 $userLimit = $limits[$group];
1732 // Set the user limit key
1733 if ( $userLimit !== false ) {
1734 list( $max, $period ) = $userLimit;
1735 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1736 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1740 foreach ( $keys as $key => $limit ) {
1741 list( $max, $period ) = $limit;
1742 $summary = "(limit $max in {$period}s)";
1743 $count = $wgMemc->get( $key );
1746 if ( $count >= $max ) {
1747 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1748 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1751 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1754 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1755 if ( $incrBy > 0 ) {
1756 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1759 if ( $incrBy > 0 ) {
1760 $wgMemc->incr( $key, $incrBy );
1764 wfProfileOut( __METHOD__
. '-' . $action );
1765 wfProfileOut( __METHOD__
);
1770 * Check if user is blocked
1772 * @param bool $bFromSlave Whether to check the slave database instead of
1773 * the master. Hacked from false due to horrible probs on site.
1774 * @return bool True if blocked, false otherwise
1776 public function isBlocked( $bFromSlave = true ) {
1777 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1781 * Get the block affecting the user, or null if the user is not blocked
1783 * @param bool $bFromSlave Whether to check the slave database instead of the master
1784 * @return Block|null
1786 public function getBlock( $bFromSlave = true ) {
1787 $this->getBlockedStatus( $bFromSlave );
1788 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1792 * Check if user is blocked from editing a particular article
1794 * @param Title $title Title to check
1795 * @param bool $bFromSlave Whether to check the slave database instead of the master
1798 public function isBlockedFrom( $title, $bFromSlave = false ) {
1799 global $wgBlockAllowsUTEdit;
1800 wfProfileIn( __METHOD__
);
1802 $blocked = $this->isBlocked( $bFromSlave );
1803 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1804 // If a user's name is suppressed, they cannot make edits anywhere
1805 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1806 && $title->getNamespace() == NS_USER_TALK
) {
1808 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1811 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1813 wfProfileOut( __METHOD__
);
1818 * If user is blocked, return the name of the user who placed the block
1819 * @return string Name of blocker
1821 public function blockedBy() {
1822 $this->getBlockedStatus();
1823 return $this->mBlockedby
;
1827 * If user is blocked, return the specified reason for the block
1828 * @return string Blocking reason
1830 public function blockedFor() {
1831 $this->getBlockedStatus();
1832 return $this->mBlockreason
;
1836 * If user is blocked, return the ID for the block
1837 * @return int Block ID
1839 public function getBlockId() {
1840 $this->getBlockedStatus();
1841 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1845 * Check if user is blocked on all wikis.
1846 * Do not use for actual edit permission checks!
1847 * This is intended for quick UI checks.
1849 * @param string $ip IP address, uses current client if none given
1850 * @return bool True if blocked, false otherwise
1852 public function isBlockedGlobally( $ip = '' ) {
1853 if ( $this->mBlockedGlobally
!== null ) {
1854 return $this->mBlockedGlobally
;
1856 // User is already an IP?
1857 if ( IP
::isIPAddress( $this->getName() ) ) {
1858 $ip = $this->getName();
1860 $ip = $this->getRequest()->getIP();
1863 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1864 $this->mBlockedGlobally
= (bool)$blocked;
1865 return $this->mBlockedGlobally
;
1869 * Check if user account is locked
1871 * @return bool True if locked, false otherwise
1873 public function isLocked() {
1874 if ( $this->mLocked
!== null ) {
1875 return $this->mLocked
;
1878 StubObject
::unstub( $wgAuth );
1879 $authUser = $wgAuth->getUserInstance( $this );
1880 $this->mLocked
= (bool)$authUser->isLocked();
1881 return $this->mLocked
;
1885 * Check if user account is hidden
1887 * @return bool True if hidden, false otherwise
1889 public function isHidden() {
1890 if ( $this->mHideName
!== null ) {
1891 return $this->mHideName
;
1893 $this->getBlockedStatus();
1894 if ( !$this->mHideName
) {
1896 StubObject
::unstub( $wgAuth );
1897 $authUser = $wgAuth->getUserInstance( $this );
1898 $this->mHideName
= (bool)$authUser->isHidden();
1900 return $this->mHideName
;
1904 * Get the user's ID.
1905 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1907 public function getId() {
1908 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1909 // Special case, we know the user is anonymous
1911 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1912 // Don't load if this was initialized from an ID
1919 * Set the user and reload all fields according to a given ID
1920 * @param int $v User ID to reload
1922 public function setId( $v ) {
1924 $this->clearInstanceCache( 'id' );
1928 * Get the user name, or the IP of an anonymous user
1929 * @return string User's name or IP address
1931 public function getName() {
1932 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1933 // Special case optimisation
1934 return $this->mName
;
1937 if ( $this->mName
=== false ) {
1939 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1941 return $this->mName
;
1946 * Set the user name.
1948 * This does not reload fields from the database according to the given
1949 * name. Rather, it is used to create a temporary "nonexistent user" for
1950 * later addition to the database. It can also be used to set the IP
1951 * address for an anonymous user to something other than the current
1954 * @note User::newFromName() has roughly the same function, when the named user
1956 * @param string $str New user name to set
1958 public function setName( $str ) {
1960 $this->mName
= $str;
1964 * Get the user's name escaped by underscores.
1965 * @return string Username escaped by underscores.
1967 public function getTitleKey() {
1968 return str_replace( ' ', '_', $this->getName() );
1972 * Check if the user has new messages.
1973 * @return bool True if the user has new messages
1975 public function getNewtalk() {
1978 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1979 if ( $this->mNewtalk
=== -1 ) {
1980 $this->mNewtalk
= false; # reset talk page status
1982 // Check memcached separately for anons, who have no
1983 // entire User object stored in there.
1984 if ( !$this->mId
) {
1985 global $wgDisableAnonTalk;
1986 if ( $wgDisableAnonTalk ) {
1987 // Anon newtalk disabled by configuration.
1988 $this->mNewtalk
= false;
1991 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1992 $newtalk = $wgMemc->get( $key );
1993 if ( strval( $newtalk ) !== '' ) {
1994 $this->mNewtalk
= (bool)$newtalk;
1996 // Since we are caching this, make sure it is up to date by getting it
1998 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1999 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
2003 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2007 return (bool)$this->mNewtalk
;
2011 * Return the data needed to construct links for new talk page message
2012 * alerts. If there are new messages, this will return an associative array
2013 * with the following data:
2014 * wiki: The database name of the wiki
2015 * link: Root-relative link to the user's talk page
2016 * rev: The last talk page revision that the user has seen or null. This
2017 * is useful for building diff links.
2018 * If there are no new messages, it returns an empty array.
2019 * @note This function was designed to accomodate multiple talk pages, but
2020 * currently only returns a single link and revision.
2023 public function getNewMessageLinks() {
2025 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2027 } elseif ( !$this->getNewtalk() ) {
2030 $utp = $this->getTalkPage();
2031 $dbr = wfGetDB( DB_SLAVE
);
2032 // Get the "last viewed rev" timestamp from the oldest message notification
2033 $timestamp = $dbr->selectField( 'user_newtalk',
2034 'MIN(user_last_timestamp)',
2035 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2037 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2038 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2042 * Get the revision ID for the last talk page revision viewed by the talk
2044 * @return int|null Revision ID or null
2046 public function getNewMessageRevisionId() {
2047 $newMessageRevisionId = null;
2048 $newMessageLinks = $this->getNewMessageLinks();
2049 if ( $newMessageLinks ) {
2050 // Note: getNewMessageLinks() never returns more than a single link
2051 // and it is always for the same wiki, but we double-check here in
2052 // case that changes some time in the future.
2053 if ( count( $newMessageLinks ) === 1
2054 && $newMessageLinks[0]['wiki'] === wfWikiID()
2055 && $newMessageLinks[0]['rev']
2057 $newMessageRevision = $newMessageLinks[0]['rev'];
2058 $newMessageRevisionId = $newMessageRevision->getId();
2061 return $newMessageRevisionId;
2065 * Internal uncached check for new messages
2068 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2069 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2070 * @param bool $fromMaster true to fetch from the master, false for a slave
2071 * @return bool True if the user has new messages
2073 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2074 if ( $fromMaster ) {
2075 $db = wfGetDB( DB_MASTER
);
2077 $db = wfGetDB( DB_SLAVE
);
2079 $ok = $db->selectField( 'user_newtalk', $field,
2080 array( $field => $id ), __METHOD__
);
2081 return $ok !== false;
2085 * Add or update the new messages flag
2086 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2087 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2088 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2089 * @return bool True if successful, false otherwise
2091 protected function updateNewtalk( $field, $id, $curRev = null ) {
2092 // Get timestamp of the talk page revision prior to the current one
2093 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2094 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2095 // Mark the user as having new messages since this revision
2096 $dbw = wfGetDB( DB_MASTER
);
2097 $dbw->insert( 'user_newtalk',
2098 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2101 if ( $dbw->affectedRows() ) {
2102 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2105 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2111 * Clear the new messages flag for the given user
2112 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2113 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2114 * @return bool True if successful, false otherwise
2116 protected function deleteNewtalk( $field, $id ) {
2117 $dbw = wfGetDB( DB_MASTER
);
2118 $dbw->delete( 'user_newtalk',
2119 array( $field => $id ),
2121 if ( $dbw->affectedRows() ) {
2122 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2125 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2131 * Update the 'You have new messages!' status.
2132 * @param bool $val Whether the user has new messages
2133 * @param Revision $curRev New, as yet unseen revision of the user talk
2134 * page. Ignored if null or !$val.
2136 public function setNewtalk( $val, $curRev = null ) {
2137 if ( wfReadOnly() ) {
2142 $this->mNewtalk
= $val;
2144 if ( $this->isAnon() ) {
2146 $id = $this->getName();
2149 $id = $this->getId();
2154 $changed = $this->updateNewtalk( $field, $id, $curRev );
2156 $changed = $this->deleteNewtalk( $field, $id );
2159 if ( $this->isAnon() ) {
2160 // Anons have a separate memcached space, since
2161 // user records aren't kept for them.
2162 $key = wfMemcKey( 'newtalk', 'ip', $id );
2163 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
2166 $this->invalidateCache();
2171 * Generate a current or new-future timestamp to be stored in the
2172 * user_touched field when we update things.
2173 * @return string Timestamp in TS_MW format
2175 private static function newTouchedTimestamp() {
2176 global $wgClockSkewFudge;
2177 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2181 * Clear user data from memcached.
2182 * Use after applying fun updates to the database; caller's
2183 * responsibility to update user_touched if appropriate.
2185 * Called implicitly from invalidateCache() and saveSettings().
2187 private function clearSharedCache() {
2191 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
2196 * Immediately touch the user data cache for this account.
2197 * Updates user_touched field, and removes account data from memcached
2198 * for reload on the next hit.
2200 public function invalidateCache() {
2201 if ( wfReadOnly() ) {
2206 $this->mTouched
= self
::newTouchedTimestamp();
2208 $dbw = wfGetDB( DB_MASTER
);
2209 $userid = $this->mId
;
2210 $touched = $this->mTouched
;
2211 $method = __METHOD__
;
2212 $dbw->onTransactionIdle( function() use ( $dbw, $userid, $touched, $method ) {
2213 // Prevent contention slams by checking user_touched first
2214 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2215 $needsPurge = $dbw->selectField( 'user', '1',
2216 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2217 if ( $needsPurge ) {
2218 $dbw->update( 'user',
2219 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2220 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2225 $this->clearSharedCache();
2230 * Validate the cache for this account.
2231 * @param string $timestamp A timestamp in TS_MW format
2234 public function validateCache( $timestamp ) {
2236 return ( $timestamp >= $this->mTouched
);
2240 * Get the user touched timestamp
2241 * @return string Timestamp
2243 public function getTouched() {
2245 return $this->mTouched
;
2249 * Set the password and reset the random token.
2250 * Calls through to authentication plugin if necessary;
2251 * will have no effect if the auth plugin refuses to
2252 * pass the change through or if the legal password
2255 * As a special case, setting the password to null
2256 * wipes it, so the account cannot be logged in until
2257 * a new password is set, for instance via e-mail.
2259 * @param string $str New password to set
2260 * @throws PasswordError on failure
2264 public function setPassword( $str ) {
2267 if ( $str !== null ) {
2268 if ( !$wgAuth->allowPasswordChange() ) {
2269 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2272 if ( !$this->isValidPassword( $str ) ) {
2273 global $wgMinimalPasswordLength;
2274 $valid = $this->getPasswordValidity( $str );
2275 if ( is_array( $valid ) ) {
2276 $message = array_shift( $valid );
2280 $params = array( $wgMinimalPasswordLength );
2282 throw new PasswordError( wfMessage( $message, $params )->text() );
2286 if ( !$wgAuth->setPassword( $this, $str ) ) {
2287 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2290 $this->setInternalPassword( $str );
2296 * Set the password and reset the random token unconditionally.
2298 * @param string|null $str New password to set or null to set an invalid
2299 * password hash meaning that the user will not be able to log in
2300 * through the web interface.
2302 public function setInternalPassword( $str ) {
2306 if ( $str === null ) {
2307 // Save an invalid hash...
2308 $this->mPassword
= '';
2310 $this->mPassword
= self
::crypt( $str );
2312 $this->mNewpassword
= '';
2313 $this->mNewpassTime
= null;
2317 * Get the user's current token.
2318 * @param bool $forceCreation Force the generation of a new token if the
2319 * user doesn't have one (default=true for backwards compatibility).
2320 * @return string Token
2322 public function getToken( $forceCreation = true ) {
2324 if ( !$this->mToken
&& $forceCreation ) {
2327 return $this->mToken
;
2331 * Set the random token (used for persistent authentication)
2332 * Called from loadDefaults() among other places.
2334 * @param string|bool $token If specified, set the token to this value
2336 public function setToken( $token = false ) {
2339 $this->mToken
= MWCryptRand
::generateHex( USER_TOKEN_LENGTH
);
2341 $this->mToken
= $token;
2346 * Set the password for a password reminder or new account email
2348 * @param string $str New password to set or null to set an invalid
2349 * password hash meaning that the user will not be able to use it
2350 * @param bool $throttle If true, reset the throttle timestamp to the present
2352 public function setNewpassword( $str, $throttle = true ) {
2355 if ( $str === null ) {
2356 $this->mNewpassword
= '';
2357 $this->mNewpassTime
= null;
2359 $this->mNewpassword
= self
::crypt( $str );
2361 $this->mNewpassTime
= wfTimestampNow();
2367 * Has password reminder email been sent within the last
2368 * $wgPasswordReminderResendTime hours?
2371 public function isPasswordReminderThrottled() {
2372 global $wgPasswordReminderResendTime;
2374 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2377 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2378 return time() < $expiry;
2382 * Get the user's e-mail address
2383 * @return string User's email address
2385 public function getEmail() {
2387 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
2388 return $this->mEmail
;
2392 * Get the timestamp of the user's e-mail authentication
2393 * @return string TS_MW timestamp
2395 public function getEmailAuthenticationTimestamp() {
2397 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2398 return $this->mEmailAuthenticated
;
2402 * Set the user's e-mail address
2403 * @param string $str New e-mail address
2405 public function setEmail( $str ) {
2407 if ( $str == $this->mEmail
) {
2410 $this->mEmail
= $str;
2411 $this->invalidateEmail();
2412 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
2416 * Set the user's e-mail address and a confirmation mail if needed.
2419 * @param string $str New e-mail address
2422 public function setEmailWithConfirmation( $str ) {
2423 global $wgEnableEmail, $wgEmailAuthentication;
2425 if ( !$wgEnableEmail ) {
2426 return Status
::newFatal( 'emaildisabled' );
2429 $oldaddr = $this->getEmail();
2430 if ( $str === $oldaddr ) {
2431 return Status
::newGood( true );
2434 $this->setEmail( $str );
2436 if ( $str !== '' && $wgEmailAuthentication ) {
2437 // Send a confirmation request to the new address if needed
2438 $type = $oldaddr != '' ?
'changed' : 'set';
2439 $result = $this->sendConfirmationMail( $type );
2440 if ( $result->isGood() ) {
2441 // Say the the caller that a confirmation mail has been sent
2442 $result->value
= 'eauth';
2445 $result = Status
::newGood( true );
2452 * Get the user's real name
2453 * @return string User's real name
2455 public function getRealName() {
2456 if ( !$this->isItemLoaded( 'realname' ) ) {
2460 return $this->mRealName
;
2464 * Set the user's real name
2465 * @param string $str New real name
2467 public function setRealName( $str ) {
2469 $this->mRealName
= $str;
2473 * Get the user's current setting for a given option.
2475 * @param string $oname The option to check
2476 * @param string $defaultOverride A default value returned if the option does not exist
2477 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2478 * @return string User's current value for the option
2479 * @see getBoolOption()
2480 * @see getIntOption()
2482 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2483 global $wgHiddenPrefs;
2484 $this->loadOptions();
2486 # We want 'disabled' preferences to always behave as the default value for
2487 # users, even if they have set the option explicitly in their settings (ie they
2488 # set it, and then it was disabled removing their ability to change it). But
2489 # we don't want to erase the preferences in the database in case the preference
2490 # is re-enabled again. So don't touch $mOptions, just override the returned value
2491 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2492 return self
::getDefaultOption( $oname );
2495 if ( array_key_exists( $oname, $this->mOptions
) ) {
2496 return $this->mOptions
[$oname];
2498 return $defaultOverride;
2503 * Get all user's options
2507 public function getOptions() {
2508 global $wgHiddenPrefs;
2509 $this->loadOptions();
2510 $options = $this->mOptions
;
2512 # We want 'disabled' preferences to always behave as the default value for
2513 # users, even if they have set the option explicitly in their settings (ie they
2514 # set it, and then it was disabled removing their ability to change it). But
2515 # we don't want to erase the preferences in the database in case the preference
2516 # is re-enabled again. So don't touch $mOptions, just override the returned value
2517 foreach ( $wgHiddenPrefs as $pref ) {
2518 $default = self
::getDefaultOption( $pref );
2519 if ( $default !== null ) {
2520 $options[$pref] = $default;
2528 * Get the user's current setting for a given option, as a boolean value.
2530 * @param string $oname The option to check
2531 * @return bool User's current value for the option
2534 public function getBoolOption( $oname ) {
2535 return (bool)$this->getOption( $oname );
2539 * Get the user's current setting for a given option, as an integer value.
2541 * @param string $oname The option to check
2542 * @param int $defaultOverride A default value returned if the option does not exist
2543 * @return int User's current value for the option
2546 public function getIntOption( $oname, $defaultOverride = 0 ) {
2547 $val = $this->getOption( $oname );
2549 $val = $defaultOverride;
2551 return intval( $val );
2555 * Set the given option for a user.
2557 * You need to call saveSettings() to actually write to the database.
2559 * @param string $oname The option to set
2560 * @param mixed $val New value to set
2562 public function setOption( $oname, $val ) {
2563 $this->loadOptions();
2565 // Explicitly NULL values should refer to defaults
2566 if ( is_null( $val ) ) {
2567 $val = self
::getDefaultOption( $oname );
2570 $this->mOptions
[$oname] = $val;
2574 * Get a token stored in the preferences (like the watchlist one),
2575 * resetting it if it's empty (and saving changes).
2577 * @param string $oname The option name to retrieve the token from
2578 * @return string|bool User's current value for the option, or false if this option is disabled.
2579 * @see resetTokenFromOption()
2582 public function getTokenFromOption( $oname ) {
2583 global $wgHiddenPrefs;
2584 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2588 $token = $this->getOption( $oname );
2590 $token = $this->resetTokenFromOption( $oname );
2591 $this->saveSettings();
2597 * Reset a token stored in the preferences (like the watchlist one).
2598 * *Does not* save user's preferences (similarly to setOption()).
2600 * @param string $oname The option name to reset the token in
2601 * @return string|bool New token value, or false if this option is disabled.
2602 * @see getTokenFromOption()
2605 public function resetTokenFromOption( $oname ) {
2606 global $wgHiddenPrefs;
2607 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2611 $token = MWCryptRand
::generateHex( 40 );
2612 $this->setOption( $oname, $token );
2617 * Return a list of the types of user options currently returned by
2618 * User::getOptionKinds().
2620 * Currently, the option kinds are:
2621 * - 'registered' - preferences which are registered in core MediaWiki or
2622 * by extensions using the UserGetDefaultOptions hook.
2623 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2624 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2625 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2626 * be used by user scripts.
2627 * - 'special' - "preferences" that are not accessible via User::getOptions
2628 * or User::setOptions.
2629 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2630 * These are usually legacy options, removed in newer versions.
2632 * The API (and possibly others) use this function to determine the possible
2633 * option types for validation purposes, so make sure to update this when a
2634 * new option kind is added.
2636 * @see User::getOptionKinds
2637 * @return array Option kinds
2639 public static function listOptionKinds() {
2642 'registered-multiselect',
2643 'registered-checkmatrix',
2651 * Return an associative array mapping preferences keys to the kind of a preference they're
2652 * used for. Different kinds are handled differently when setting or reading preferences.
2654 * See User::listOptionKinds for the list of valid option types that can be provided.
2656 * @see User::listOptionKinds
2657 * @param IContextSource $context
2658 * @param array $options Assoc. array with options keys to check as keys.
2659 * Defaults to $this->mOptions.
2660 * @return array the key => kind mapping data
2662 public function getOptionKinds( IContextSource
$context, $options = null ) {
2663 $this->loadOptions();
2664 if ( $options === null ) {
2665 $options = $this->mOptions
;
2668 $prefs = Preferences
::getPreferences( $this, $context );
2671 // Pull out the "special" options, so they don't get converted as
2672 // multiselect or checkmatrix.
2673 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2674 foreach ( $specialOptions as $name => $value ) {
2675 unset( $prefs[$name] );
2678 // Multiselect and checkmatrix options are stored in the database with
2679 // one key per option, each having a boolean value. Extract those keys.
2680 $multiselectOptions = array();
2681 foreach ( $prefs as $name => $info ) {
2682 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2683 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2684 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2685 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2687 foreach ( $opts as $value ) {
2688 $multiselectOptions["$prefix$value"] = true;
2691 unset( $prefs[$name] );
2694 $checkmatrixOptions = array();
2695 foreach ( $prefs as $name => $info ) {
2696 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2697 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2698 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2699 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2700 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2702 foreach ( $columns as $column ) {
2703 foreach ( $rows as $row ) {
2704 $checkmatrixOptions["$prefix-$column-$row"] = true;
2708 unset( $prefs[$name] );
2712 // $value is ignored
2713 foreach ( $options as $key => $value ) {
2714 if ( isset( $prefs[$key] ) ) {
2715 $mapping[$key] = 'registered';
2716 } elseif ( isset( $multiselectOptions[$key] ) ) {
2717 $mapping[$key] = 'registered-multiselect';
2718 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2719 $mapping[$key] = 'registered-checkmatrix';
2720 } elseif ( isset( $specialOptions[$key] ) ) {
2721 $mapping[$key] = 'special';
2722 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2723 $mapping[$key] = 'userjs';
2725 $mapping[$key] = 'unused';
2733 * Reset certain (or all) options to the site defaults
2735 * The optional parameter determines which kinds of preferences will be reset.
2736 * Supported values are everything that can be reported by getOptionKinds()
2737 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2739 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2740 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2741 * for backwards-compatibility.
2742 * @param IContextSource|null $context Context source used when $resetKinds
2743 * does not contain 'all', passed to getOptionKinds().
2744 * Defaults to RequestContext::getMain() when null.
2746 public function resetOptions(
2747 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2748 IContextSource
$context = null
2751 $defaultOptions = self
::getDefaultOptions();
2753 if ( !is_array( $resetKinds ) ) {
2754 $resetKinds = array( $resetKinds );
2757 if ( in_array( 'all', $resetKinds ) ) {
2758 $newOptions = $defaultOptions;
2760 if ( $context === null ) {
2761 $context = RequestContext
::getMain();
2764 $optionKinds = $this->getOptionKinds( $context );
2765 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2766 $newOptions = array();
2768 // Use default values for the options that should be deleted, and
2769 // copy old values for the ones that shouldn't.
2770 foreach ( $this->mOptions
as $key => $value ) {
2771 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2772 if ( array_key_exists( $key, $defaultOptions ) ) {
2773 $newOptions[$key] = $defaultOptions[$key];
2776 $newOptions[$key] = $value;
2781 $this->mOptions
= $newOptions;
2782 $this->mOptionsLoaded
= true;
2786 * Get the user's preferred date format.
2787 * @return string User's preferred date format
2789 public function getDatePreference() {
2790 // Important migration for old data rows
2791 if ( is_null( $this->mDatePreference
) ) {
2793 $value = $this->getOption( 'date' );
2794 $map = $wgLang->getDatePreferenceMigrationMap();
2795 if ( isset( $map[$value] ) ) {
2796 $value = $map[$value];
2798 $this->mDatePreference
= $value;
2800 return $this->mDatePreference
;
2804 * Determine based on the wiki configuration and the user's options,
2805 * whether this user must be over HTTPS no matter what.
2809 public function requiresHTTPS() {
2810 global $wgSecureLogin;
2811 if ( !$wgSecureLogin ) {
2814 $https = $this->getBoolOption( 'prefershttps' );
2815 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2817 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2824 * Get the user preferred stub threshold
2828 public function getStubThreshold() {
2829 global $wgMaxArticleSize; # Maximum article size, in Kb
2830 $threshold = $this->getIntOption( 'stubthreshold' );
2831 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2832 // If they have set an impossible value, disable the preference
2833 // so we can use the parser cache again.
2840 * Get the permissions this user has.
2841 * @return array Array of String permission names
2843 public function getRights() {
2844 if ( is_null( $this->mRights
) ) {
2845 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2846 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2847 // Force reindexation of rights when a hook has unset one of them
2848 $this->mRights
= array_values( array_unique( $this->mRights
) );
2850 return $this->mRights
;
2854 * Get the list of explicit group memberships this user has.
2855 * The implicit * and user groups are not included.
2856 * @return array Array of String internal group names
2858 public function getGroups() {
2860 $this->loadGroups();
2861 return $this->mGroups
;
2865 * Get the list of implicit group memberships this user has.
2866 * This includes all explicit groups, plus 'user' if logged in,
2867 * '*' for all accounts, and autopromoted groups
2868 * @param bool $recache Whether to avoid the cache
2869 * @return array Array of String internal group names
2871 public function getEffectiveGroups( $recache = false ) {
2872 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2873 wfProfileIn( __METHOD__
);
2874 $this->mEffectiveGroups
= array_unique( array_merge(
2875 $this->getGroups(), // explicit groups
2876 $this->getAutomaticGroups( $recache ) // implicit groups
2878 // Hook for additional groups
2879 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2880 // Force reindexation of groups when a hook has unset one of them
2881 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
2882 wfProfileOut( __METHOD__
);
2884 return $this->mEffectiveGroups
;
2888 * Get the list of implicit group memberships this user has.
2889 * This includes 'user' if logged in, '*' for all accounts,
2890 * and autopromoted groups
2891 * @param bool $recache Whether to avoid the cache
2892 * @return array Array of String internal group names
2894 public function getAutomaticGroups( $recache = false ) {
2895 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
2896 wfProfileIn( __METHOD__
);
2897 $this->mImplicitGroups
= array( '*' );
2898 if ( $this->getId() ) {
2899 $this->mImplicitGroups
[] = 'user';
2901 $this->mImplicitGroups
= array_unique( array_merge(
2902 $this->mImplicitGroups
,
2903 Autopromote
::getAutopromoteGroups( $this )
2907 // Assure data consistency with rights/groups,
2908 // as getEffectiveGroups() depends on this function
2909 $this->mEffectiveGroups
= null;
2911 wfProfileOut( __METHOD__
);
2913 return $this->mImplicitGroups
;
2917 * Returns the groups the user has belonged to.
2919 * The user may still belong to the returned groups. Compare with getGroups().
2921 * The function will not return groups the user had belonged to before MW 1.17
2923 * @return array Names of the groups the user has belonged to.
2925 public function getFormerGroups() {
2926 if ( is_null( $this->mFormerGroups
) ) {
2927 $dbr = wfGetDB( DB_MASTER
);
2928 $res = $dbr->select( 'user_former_groups',
2929 array( 'ufg_group' ),
2930 array( 'ufg_user' => $this->mId
),
2932 $this->mFormerGroups
= array();
2933 foreach ( $res as $row ) {
2934 $this->mFormerGroups
[] = $row->ufg_group
;
2937 return $this->mFormerGroups
;
2941 * Get the user's edit count.
2942 * @return int|null null for anonymous users
2944 public function getEditCount() {
2945 if ( !$this->getId() ) {
2949 if ( !isset( $this->mEditCount
) ) {
2950 /* Populate the count, if it has not been populated yet */
2951 wfProfileIn( __METHOD__
);
2952 $dbr = wfGetDB( DB_SLAVE
);
2953 // check if the user_editcount field has been initialized
2954 $count = $dbr->selectField(
2955 'user', 'user_editcount',
2956 array( 'user_id' => $this->mId
),
2960 if ( $count === null ) {
2961 // it has not been initialized. do so.
2962 $count = $this->initEditCount();
2964 $this->mEditCount
= $count;
2965 wfProfileOut( __METHOD__
);
2967 return (int)$this->mEditCount
;
2971 * Add the user to the given group.
2972 * This takes immediate effect.
2973 * @param string $group Name of the group to add
2975 public function addGroup( $group ) {
2976 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2977 $dbw = wfGetDB( DB_MASTER
);
2978 if ( $this->getId() ) {
2979 $dbw->insert( 'user_groups',
2981 'ug_user' => $this->getID(),
2982 'ug_group' => $group,
2985 array( 'IGNORE' ) );
2988 $this->loadGroups();
2989 $this->mGroups
[] = $group;
2990 // In case loadGroups was not called before, we now have the right twice.
2991 // Get rid of the duplicate.
2992 $this->mGroups
= array_unique( $this->mGroups
);
2994 // Refresh the groups caches, and clear the rights cache so it will be
2995 // refreshed on the next call to $this->getRights().
2996 $this->getEffectiveGroups( true );
2997 $this->mRights
= null;
2999 $this->invalidateCache();
3003 * Remove the user from the given group.
3004 * This takes immediate effect.
3005 * @param string $group Name of the group to remove
3007 public function removeGroup( $group ) {
3009 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3010 $dbw = wfGetDB( DB_MASTER
);
3011 $dbw->delete( 'user_groups',
3013 'ug_user' => $this->getID(),
3014 'ug_group' => $group,
3016 // Remember that the user was in this group
3017 $dbw->insert( 'user_former_groups',
3019 'ufg_user' => $this->getID(),
3020 'ufg_group' => $group,
3023 array( 'IGNORE' ) );
3025 $this->loadGroups();
3026 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3028 // Refresh the groups caches, and clear the rights cache so it will be
3029 // refreshed on the next call to $this->getRights().
3030 $this->getEffectiveGroups( true );
3031 $this->mRights
= null;
3033 $this->invalidateCache();
3037 * Get whether the user is logged in
3040 public function isLoggedIn() {
3041 return $this->getID() != 0;
3045 * Get whether the user is anonymous
3048 public function isAnon() {
3049 return !$this->isLoggedIn();
3053 * Check if user is allowed to access a feature / make an action
3055 * @internal param \String $varargs permissions to test
3056 * @return bool True if user is allowed to perform *any* of the given actions
3060 public function isAllowedAny( /*...*/ ) {
3061 $permissions = func_get_args();
3062 foreach ( $permissions as $permission ) {
3063 if ( $this->isAllowed( $permission ) ) {
3072 * @internal param $varargs string
3073 * @return bool True if the user is allowed to perform *all* of the given actions
3075 public function isAllowedAll( /*...*/ ) {
3076 $permissions = func_get_args();
3077 foreach ( $permissions as $permission ) {
3078 if ( !$this->isAllowed( $permission ) ) {
3086 * Internal mechanics of testing a permission
3087 * @param string $action
3090 public function isAllowed( $action = '' ) {
3091 if ( $action === '' ) {
3092 return true; // In the spirit of DWIM
3094 // Patrolling may not be enabled
3095 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3096 global $wgUseRCPatrol, $wgUseNPPatrol;
3097 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3101 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3102 // by misconfiguration: 0 == 'foo'
3103 return in_array( $action, $this->getRights(), true );
3107 * Check whether to enable recent changes patrol features for this user
3108 * @return bool True or false
3110 public function useRCPatrol() {
3111 global $wgUseRCPatrol;
3112 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3116 * Check whether to enable new pages patrol features for this user
3117 * @return bool True or false
3119 public function useNPPatrol() {
3120 global $wgUseRCPatrol, $wgUseNPPatrol;
3122 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3123 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3128 * Get the WebRequest object to use with this object
3130 * @return WebRequest
3132 public function getRequest() {
3133 if ( $this->mRequest
) {
3134 return $this->mRequest
;
3142 * Get the current skin, loading it if required
3143 * @return Skin The current skin
3144 * @todo FIXME: Need to check the old failback system [AV]
3145 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3147 public function getSkin() {
3148 wfDeprecated( __METHOD__
, '1.18' );
3149 return RequestContext
::getMain()->getSkin();
3153 * Get a WatchedItem for this user and $title.
3155 * @since 1.22 $checkRights parameter added
3156 * @param Title $title
3157 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3158 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3159 * @return WatchedItem
3161 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3162 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3164 if ( isset( $this->mWatchedItems
[$key] ) ) {
3165 return $this->mWatchedItems
[$key];
3168 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3169 $this->mWatchedItems
= array();
3172 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3173 return $this->mWatchedItems
[$key];
3177 * Check the watched status of an article.
3178 * @since 1.22 $checkRights parameter added
3179 * @param Title $title Title of the article to look at
3180 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3181 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3184 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3185 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3190 * @since 1.22 $checkRights parameter added
3191 * @param Title $title Title of the article to look at
3192 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3193 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3195 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3196 $this->getWatchedItem( $title, $checkRights )->addWatch();
3197 $this->invalidateCache();
3201 * Stop watching an article.
3202 * @since 1.22 $checkRights parameter added
3203 * @param Title $title Title of the article to look at
3204 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3205 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3207 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3208 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3209 $this->invalidateCache();
3213 * Clear the user's notification timestamp for the given title.
3214 * If e-notif e-mails are on, they will receive notification mails on
3215 * the next change of the page if it's watched etc.
3216 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3217 * @param Title $title Title of the article to look at
3218 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3220 public function clearNotification( &$title, $oldid = 0 ) {
3221 global $wgUseEnotif, $wgShowUpdatedMarker;
3223 // Do nothing if the database is locked to writes
3224 if ( wfReadOnly() ) {
3228 // Do nothing if not allowed to edit the watchlist
3229 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3233 // If we're working on user's talk page, we should update the talk page message indicator
3234 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3235 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3239 $nextid = $oldid ?
$title->getNextRevisionID( $oldid ) : null;
3241 if ( !$oldid ||
!$nextid ) {
3242 // If we're looking at the latest revision, we should definitely clear it
3243 $this->setNewtalk( false );
3245 // Otherwise we should update its revision, if it's present
3246 if ( $this->getNewtalk() ) {
3247 // Naturally the other one won't clear by itself
3248 $this->setNewtalk( false );
3249 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3254 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3258 if ( $this->isAnon() ) {
3259 // Nothing else to do...
3263 // Only update the timestamp if the page is being watched.
3264 // The query to find out if it is watched is cached both in memcached and per-invocation,
3265 // and when it does have to be executed, it can be on a slave
3266 // If this is the user's newtalk page, we always update the timestamp
3268 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3272 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3276 * Resets all of the given user's page-change notification timestamps.
3277 * If e-notif e-mails are on, they will receive notification mails on
3278 * the next change of any watched page.
3279 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3281 public function clearAllNotifications() {
3282 if ( wfReadOnly() ) {
3286 // Do nothing if not allowed to edit the watchlist
3287 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3291 global $wgUseEnotif, $wgShowUpdatedMarker;
3292 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3293 $this->setNewtalk( false );
3296 $id = $this->getId();
3298 $dbw = wfGetDB( DB_MASTER
);
3299 $dbw->update( 'watchlist',
3300 array( /* SET */ 'wl_notificationtimestamp' => null ),
3301 array( /* WHERE */ 'wl_user' => $id ),
3304 // We also need to clear here the "you have new message" notification for the own user_talk page;
3305 // it's cleared one page view later in WikiPage::doViewUpdates().
3310 * Set a cookie on the user's client. Wrapper for
3311 * WebResponse::setCookie
3312 * @param string $name Name of the cookie to set
3313 * @param string $value Value to set
3314 * @param int $exp Expiration time, as a UNIX time value;
3315 * if 0 or not specified, use the default $wgCookieExpiration
3316 * @param bool $secure
3317 * true: Force setting the secure attribute when setting the cookie
3318 * false: Force NOT setting the secure attribute when setting the cookie
3319 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3320 * @param array $params Array of options sent passed to WebResponse::setcookie()
3322 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3323 $params['secure'] = $secure;
3324 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3328 * Clear a cookie on the user's client
3329 * @param string $name Name of the cookie to clear
3330 * @param bool $secure
3331 * true: Force setting the secure attribute when setting the cookie
3332 * false: Force NOT setting the secure attribute when setting the cookie
3333 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3334 * @param array $params Array of options sent passed to WebResponse::setcookie()
3336 protected function clearCookie( $name, $secure = null, $params = array() ) {
3337 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3341 * Set the default cookies for this session on the user's client.
3343 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3345 * @param bool $secure Whether to force secure/insecure cookies or use default
3346 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3348 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3349 if ( $request === null ) {
3350 $request = $this->getRequest();
3354 if ( 0 == $this->mId
) {
3357 if ( !$this->mToken
) {
3358 // When token is empty or NULL generate a new one and then save it to the database
3359 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3360 // Simply by setting every cell in the user_token column to NULL and letting them be
3361 // regenerated as users log back into the wiki.
3363 $this->saveSettings();
3366 'wsUserID' => $this->mId
,
3367 'wsToken' => $this->mToken
,
3368 'wsUserName' => $this->getName()
3371 'UserID' => $this->mId
,
3372 'UserName' => $this->getName(),
3374 if ( $rememberMe ) {
3375 $cookies['Token'] = $this->mToken
;
3377 $cookies['Token'] = false;
3380 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3382 foreach ( $session as $name => $value ) {
3383 $request->setSessionData( $name, $value );
3385 foreach ( $cookies as $name => $value ) {
3386 if ( $value === false ) {
3387 $this->clearCookie( $name );
3389 $this->setCookie( $name, $value, 0, $secure );
3394 * If wpStickHTTPS was selected, also set an insecure cookie that
3395 * will cause the site to redirect the user to HTTPS, if they access
3396 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3397 * as the one set by centralauth (bug 53538). Also set it to session, or
3398 * standard time setting, based on if rememberme was set.
3400 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3404 $rememberMe ?
0 : null,
3406 array( 'prefix' => '' ) // no prefix
3412 * Log this user out.
3414 public function logout() {
3415 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3421 * Clear the user's cookies and session, and reset the instance cache.
3424 public function doLogout() {
3425 $this->clearInstanceCache( 'defaults' );
3427 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3429 $this->clearCookie( 'UserID' );
3430 $this->clearCookie( 'Token' );
3431 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3433 // Remember when user logged out, to prevent seeing cached pages
3434 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3438 * Save this user's settings into the database.
3439 * @todo Only rarely do all these fields need to be set!
3441 public function saveSettings() {
3445 if ( wfReadOnly() ) {
3448 if ( 0 == $this->mId
) {
3452 $this->mTouched
= self
::newTouchedTimestamp();
3453 if ( !$wgAuth->allowSetLocalPassword() ) {
3454 $this->mPassword
= '';
3457 $dbw = wfGetDB( DB_MASTER
);
3458 $dbw->update( 'user',
3460 'user_name' => $this->mName
,
3461 'user_password' => $this->mPassword
,
3462 'user_newpassword' => $this->mNewpassword
,
3463 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3464 'user_real_name' => $this->mRealName
,
3465 'user_email' => $this->mEmail
,
3466 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3467 'user_touched' => $dbw->timestamp( $this->mTouched
),
3468 'user_token' => strval( $this->mToken
),
3469 'user_email_token' => $this->mEmailToken
,
3470 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3471 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires
),
3472 ), array( /* WHERE */
3473 'user_id' => $this->mId
3477 $this->saveOptions();
3479 wfRunHooks( 'UserSaveSettings', array( $this ) );
3480 $this->clearSharedCache();
3481 $this->getUserPage()->invalidateCache();
3485 * If only this user's username is known, and it exists, return the user ID.
3488 public function idForName() {
3489 $s = trim( $this->getName() );
3494 $dbr = wfGetDB( DB_SLAVE
);
3495 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
3496 if ( $id === false ) {
3503 * Add a user to the database, return the user object
3505 * @param string $name Username to add
3506 * @param array $params Array of Strings Non-default parameters to save to
3507 * the database as user_* fields:
3508 * - password: The user's password hash. Password logins will be disabled
3509 * if this is omitted.
3510 * - newpassword: Hash for a temporary password that has been mailed to
3512 * - email: The user's email address.
3513 * - email_authenticated: The email authentication timestamp.
3514 * - real_name: The user's real name.
3515 * - options: An associative array of non-default options.
3516 * - token: Random authentication token. Do not set.
3517 * - registration: Registration timestamp. Do not set.
3519 * @return User|null User object, or null if the username already exists.
3521 public static function createNew( $name, $params = array() ) {
3524 $user->setToken(); // init token
3525 if ( isset( $params['options'] ) ) {
3526 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3527 unset( $params['options'] );
3529 $dbw = wfGetDB( DB_MASTER
);
3530 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3533 'user_id' => $seqVal,
3534 'user_name' => $name,
3535 'user_password' => $user->mPassword
,
3536 'user_newpassword' => $user->mNewpassword
,
3537 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3538 'user_email' => $user->mEmail
,
3539 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3540 'user_real_name' => $user->mRealName
,
3541 'user_token' => strval( $user->mToken
),
3542 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3543 'user_editcount' => 0,
3544 'user_touched' => $dbw->timestamp( self
::newTouchedTimestamp() ),
3546 foreach ( $params as $name => $value ) {
3547 $fields["user_$name"] = $value;
3549 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3550 if ( $dbw->affectedRows() ) {
3551 $newUser = User
::newFromId( $dbw->insertId() );
3559 * Add this existing user object to the database. If the user already
3560 * exists, a fatal status object is returned, and the user object is
3561 * initialised with the data from the database.
3563 * Previously, this function generated a DB error due to a key conflict
3564 * if the user already existed. Many extension callers use this function
3565 * in code along the lines of:
3567 * $user = User::newFromName( $name );
3568 * if ( !$user->isLoggedIn() ) {
3569 * $user->addToDatabase();
3571 * // do something with $user...
3573 * However, this was vulnerable to a race condition (bug 16020). By
3574 * initialising the user object if the user exists, we aim to support this
3575 * calling sequence as far as possible.
3577 * Note that if the user exists, this function will acquire a write lock,
3578 * so it is still advisable to make the call conditional on isLoggedIn(),
3579 * and to commit the transaction after calling.
3581 * @throws MWException
3584 public function addToDatabase() {
3586 if ( !$this->mToken
) {
3587 $this->setToken(); // init token
3590 $this->mTouched
= self
::newTouchedTimestamp();
3592 $dbw = wfGetDB( DB_MASTER
);
3593 $inWrite = $dbw->writesOrCallbacksPending();
3594 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3595 $dbw->insert( 'user',
3597 'user_id' => $seqVal,
3598 'user_name' => $this->mName
,
3599 'user_password' => $this->mPassword
,
3600 'user_newpassword' => $this->mNewpassword
,
3601 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3602 'user_email' => $this->mEmail
,
3603 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3604 'user_real_name' => $this->mRealName
,
3605 'user_token' => strval( $this->mToken
),
3606 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3607 'user_editcount' => 0,
3608 'user_touched' => $dbw->timestamp( $this->mTouched
),
3612 if ( !$dbw->affectedRows() ) {
3613 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3614 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3616 // Can't commit due to pending writes that may need atomicity.
3617 // This may cause some lock contention unlike the case below.
3618 $options = array( 'LOCK IN SHARE MODE' );
3619 $flags = self
::READ_LOCKING
;
3621 // Often, this case happens early in views before any writes when
3622 // using CentralAuth. It's should be OK to commit and break the snapshot.
3623 $dbw->commit( __METHOD__
, 'flush' );
3627 $this->mId
= $dbw->selectField( 'user', 'user_id',
3628 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3631 if ( $this->loadFromDatabase( $flags ) ) {
3636 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3637 "to insert user '{$this->mName}' row, but it was not present in select!" );
3639 return Status
::newFatal( 'userexists' );
3641 $this->mId
= $dbw->insertId();
3643 // Clear instance cache other than user table data, which is already accurate
3644 $this->clearInstanceCache();
3646 $this->saveOptions();
3647 return Status
::newGood();
3651 * If this user is logged-in and blocked,
3652 * block any IP address they've successfully logged in from.
3653 * @return bool A block was spread
3655 public function spreadAnyEditBlock() {
3656 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3657 return $this->spreadBlock();
3663 * If this (non-anonymous) user is blocked,
3664 * block the IP address they've successfully logged in from.
3665 * @return bool A block was spread
3667 protected function spreadBlock() {
3668 wfDebug( __METHOD__
. "()\n" );
3670 if ( $this->mId
== 0 ) {
3674 $userblock = Block
::newFromTarget( $this->getName() );
3675 if ( !$userblock ) {
3679 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3683 * Get whether the user is explicitly blocked from account creation.
3684 * @return bool|Block
3686 public function isBlockedFromCreateAccount() {
3687 $this->getBlockedStatus();
3688 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3689 return $this->mBlock
;
3692 # bug 13611: if the IP address the user is trying to create an account from is
3693 # blocked with createaccount disabled, prevent new account creation there even
3694 # when the user is logged in
3695 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3696 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3698 return $this->mBlockedFromCreateAccount
instanceof Block
3699 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3700 ?
$this->mBlockedFromCreateAccount
3705 * Get whether the user is blocked from using Special:Emailuser.
3708 public function isBlockedFromEmailuser() {
3709 $this->getBlockedStatus();
3710 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3714 * Get whether the user is allowed to create an account.
3717 public function isAllowedToCreateAccount() {
3718 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3722 * Get this user's personal page title.
3724 * @return Title User's personal page title
3726 public function getUserPage() {
3727 return Title
::makeTitle( NS_USER
, $this->getName() );
3731 * Get this user's talk page title.
3733 * @return Title User's talk page title
3735 public function getTalkPage() {
3736 $title = $this->getUserPage();
3737 return $title->getTalkPage();
3741 * Determine whether the user is a newbie. Newbies are either
3742 * anonymous IPs, or the most recently created accounts.
3745 public function isNewbie() {
3746 return !$this->isAllowed( 'autoconfirmed' );
3750 * Check to see if the given clear-text password is one of the accepted passwords
3751 * @param string $password user password.
3752 * @return bool True if the given password is correct, otherwise False.
3754 public function checkPassword( $password ) {
3755 global $wgAuth, $wgLegacyEncoding;
3758 // Certain authentication plugins do NOT want to save
3759 // domain passwords in a mysql database, so we should
3760 // check this (in case $wgAuth->strict() is false).
3762 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3764 } elseif ( $wgAuth->strict() ) {
3765 // Auth plugin doesn't allow local authentication
3767 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3768 // Auth plugin doesn't allow local authentication for this user name
3771 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
3773 } elseif ( $wgLegacyEncoding ) {
3774 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3775 // Check for this with iconv
3776 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3777 if ( $cp1252Password != $password
3778 && self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
)
3787 * Check if the given clear-text password matches the temporary password
3788 * sent by e-mail for password reset operations.
3790 * @param string $plaintext
3792 * @return bool True if matches, false otherwise
3794 public function checkTemporaryPassword( $plaintext ) {
3795 global $wgNewPasswordExpiry;
3798 if ( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
3799 if ( is_null( $this->mNewpassTime
) ) {
3802 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3803 return ( time() < $expiry );
3810 * Alias for getEditToken.
3811 * @deprecated since 1.19, use getEditToken instead.
3813 * @param string|array $salt of Strings Optional function-specific data for hashing
3814 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3815 * @return string The new edit token
3817 public function editToken( $salt = '', $request = null ) {
3818 wfDeprecated( __METHOD__
, '1.19' );
3819 return $this->getEditToken( $salt, $request );
3823 * Initialize (if necessary) and return a session token value
3824 * which can be used in edit forms to show that the user's
3825 * login credentials aren't being hijacked with a foreign form
3830 * @param string|array $salt of Strings Optional function-specific data for hashing
3831 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3832 * @return string The new edit token
3834 public function getEditToken( $salt = '', $request = null ) {
3835 if ( $request == null ) {
3836 $request = $this->getRequest();
3839 if ( $this->isAnon() ) {
3840 return EDIT_TOKEN_SUFFIX
;
3842 $token = $request->getSessionData( 'wsEditToken' );
3843 if ( $token === null ) {
3844 $token = MWCryptRand
::generateHex( 32 );
3845 $request->setSessionData( 'wsEditToken', $token );
3847 if ( is_array( $salt ) ) {
3848 $salt = implode( '|', $salt );
3850 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
3855 * Generate a looking random token for various uses.
3857 * @return string The new random token
3858 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
3859 * wfRandomString for pseudo-randomness.
3861 public static function generateToken() {
3862 return MWCryptRand
::generateHex( 32 );
3866 * Check given value against the token value stored in the session.
3867 * A match should confirm that the form was submitted from the
3868 * user's own login session, not a form submission from a third-party
3871 * @param string $val Input value to compare
3872 * @param string $salt Optional function-specific data for hashing
3873 * @param WebRequest|null $request Object to use or null to use $wgRequest
3874 * @return bool Whether the token matches
3876 public function matchEditToken( $val, $salt = '', $request = null ) {
3877 $sessionToken = $this->getEditToken( $salt, $request );
3878 if ( $val != $sessionToken ) {
3879 wfDebug( "User::matchEditToken: broken session data\n" );
3882 return $val == $sessionToken;
3886 * Check given value against the token value stored in the session,
3887 * ignoring the suffix.
3889 * @param string $val Input value to compare
3890 * @param string $salt Optional function-specific data for hashing
3891 * @param WebRequest|null $request object to use or null to use $wgRequest
3892 * @return bool Whether the token matches
3894 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3895 $sessionToken = $this->getEditToken( $salt, $request );
3896 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3900 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3901 * mail to the user's given address.
3903 * @param string $type Message to send, either "created", "changed" or "set"
3906 public function sendConfirmationMail( $type = 'created' ) {
3908 $expiration = null; // gets passed-by-ref and defined in next line.
3909 $token = $this->confirmationToken( $expiration );
3910 $url = $this->confirmationTokenUrl( $token );
3911 $invalidateURL = $this->invalidationTokenUrl( $token );
3912 $this->saveSettings();
3914 if ( $type == 'created' ||
$type === false ) {
3915 $message = 'confirmemail_body';
3916 } elseif ( $type === true ) {
3917 $message = 'confirmemail_body_changed';
3919 // Messages: confirmemail_body_changed, confirmemail_body_set
3920 $message = 'confirmemail_body_' . $type;
3923 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3924 wfMessage( $message,
3925 $this->getRequest()->getIP(),
3928 $wgLang->timeanddate( $expiration, false ),
3930 $wgLang->date( $expiration, false ),
3931 $wgLang->time( $expiration, false ) )->text() );
3935 * Send an e-mail to this user's account. Does not check for
3936 * confirmed status or validity.
3938 * @param string $subject Message subject
3939 * @param string $body Message body
3940 * @param string $from Optional From address; if unspecified, default
3941 * $wgPasswordSender will be used.
3942 * @param string $replyto Reply-To address
3945 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3946 if ( is_null( $from ) ) {
3947 global $wgPasswordSender;
3948 $sender = new MailAddress( $wgPasswordSender,
3949 wfMessage( 'emailsender' )->inContentLanguage()->text() );
3951 $sender = new MailAddress( $from );
3954 $to = new MailAddress( $this );
3955 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
3959 * Generate, store, and return a new e-mail confirmation code.
3960 * A hash (unsalted, since it's used as a key) is stored.
3962 * @note Call saveSettings() after calling this function to commit
3963 * this change to the database.
3965 * @param string &$expiration Accepts the expiration time
3966 * @return string New token
3968 protected function confirmationToken( &$expiration ) {
3969 global $wgUserEmailConfirmationTokenExpiry;
3971 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
3972 $expiration = wfTimestamp( TS_MW
, $expires );
3974 $token = MWCryptRand
::generateHex( 32 );
3975 $hash = md5( $token );
3976 $this->mEmailToken
= $hash;
3977 $this->mEmailTokenExpires
= $expiration;
3982 * Return a URL the user can use to confirm their email address.
3983 * @param string $token Accepts the email confirmation token
3984 * @return string New token URL
3986 protected function confirmationTokenUrl( $token ) {
3987 return $this->getTokenUrl( 'ConfirmEmail', $token );
3991 * Return a URL the user can use to invalidate their email address.
3992 * @param string $token Accepts the email confirmation token
3993 * @return string New token URL
3995 protected function invalidationTokenUrl( $token ) {
3996 return $this->getTokenUrl( 'InvalidateEmail', $token );
4000 * Internal function to format the e-mail validation/invalidation URLs.
4001 * This uses a quickie hack to use the
4002 * hardcoded English names of the Special: pages, for ASCII safety.
4004 * @note Since these URLs get dropped directly into emails, using the
4005 * short English names avoids insanely long URL-encoded links, which
4006 * also sometimes can get corrupted in some browsers/mailers
4007 * (bug 6957 with Gmail and Internet Explorer).
4009 * @param string $page Special page
4010 * @param string $token Token
4011 * @return string Formatted URL
4013 protected function getTokenUrl( $page, $token ) {
4014 // Hack to bypass localization of 'Special:'
4015 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4016 return $title->getCanonicalURL();
4020 * Mark the e-mail address confirmed.
4022 * @note Call saveSettings() after calling this function to commit the change.
4026 public function confirmEmail() {
4027 // Check if it's already confirmed, so we don't touch the database
4028 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4029 if ( !$this->isEmailConfirmed() ) {
4030 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4031 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
4037 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4038 * address if it was already confirmed.
4040 * @note Call saveSettings() after calling this function to commit the change.
4041 * @return bool Returns true
4043 public function invalidateEmail() {
4045 $this->mEmailToken
= null;
4046 $this->mEmailTokenExpires
= null;
4047 $this->setEmailAuthenticationTimestamp( null );
4048 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
4053 * Set the e-mail authentication timestamp.
4054 * @param string $timestamp TS_MW timestamp
4056 public function setEmailAuthenticationTimestamp( $timestamp ) {
4058 $this->mEmailAuthenticated
= $timestamp;
4059 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4063 * Is this user allowed to send e-mails within limits of current
4064 * site configuration?
4067 public function canSendEmail() {
4068 global $wgEnableEmail, $wgEnableUserEmail;
4069 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4072 $canSend = $this->isEmailConfirmed();
4073 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4078 * Is this user allowed to receive e-mails within limits of current
4079 * site configuration?
4082 public function canReceiveEmail() {
4083 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4087 * Is this user's e-mail address valid-looking and confirmed within
4088 * limits of the current site configuration?
4090 * @note If $wgEmailAuthentication is on, this may require the user to have
4091 * confirmed their address by returning a code or using a password
4092 * sent to the address from the wiki.
4096 public function isEmailConfirmed() {
4097 global $wgEmailAuthentication;
4100 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4101 if ( $this->isAnon() ) {
4104 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4107 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4117 * Check whether there is an outstanding request for e-mail confirmation.
4120 public function isEmailConfirmationPending() {
4121 global $wgEmailAuthentication;
4122 return $wgEmailAuthentication &&
4123 !$this->isEmailConfirmed() &&
4124 $this->mEmailToken
&&
4125 $this->mEmailTokenExpires
> wfTimestamp();
4129 * Get the timestamp of account creation.
4131 * @return string|bool|null Timestamp of account creation, false for
4132 * non-existent/anonymous user accounts, or null if existing account
4133 * but information is not in database.
4135 public function getRegistration() {
4136 if ( $this->isAnon() ) {
4140 return $this->mRegistration
;
4144 * Get the timestamp of the first edit
4146 * @return string|bool Timestamp of first edit, or false for
4147 * non-existent/anonymous user accounts.
4149 public function getFirstEditTimestamp() {
4150 if ( $this->getId() == 0 ) {
4151 return false; // anons
4153 $dbr = wfGetDB( DB_SLAVE
);
4154 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4155 array( 'rev_user' => $this->getId() ),
4157 array( 'ORDER BY' => 'rev_timestamp ASC' )
4160 return false; // no edits
4162 return wfTimestamp( TS_MW
, $time );
4166 * Get the permissions associated with a given list of groups
4168 * @param array $groups Array of Strings List of internal group names
4169 * @return array Array of Strings List of permission key names for given groups combined
4171 public static function getGroupPermissions( $groups ) {
4172 global $wgGroupPermissions, $wgRevokePermissions;
4174 // grant every granted permission first
4175 foreach ( $groups as $group ) {
4176 if ( isset( $wgGroupPermissions[$group] ) ) {
4177 $rights = array_merge( $rights,
4178 // array_filter removes empty items
4179 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4182 // now revoke the revoked permissions
4183 foreach ( $groups as $group ) {
4184 if ( isset( $wgRevokePermissions[$group] ) ) {
4185 $rights = array_diff( $rights,
4186 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4189 return array_unique( $rights );
4193 * Get all the groups who have a given permission
4195 * @param string $role Role to check
4196 * @return array Array of Strings List of internal group names with the given permission
4198 public static function getGroupsWithPermission( $role ) {
4199 global $wgGroupPermissions;
4200 $allowedGroups = array();
4201 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4202 if ( self
::groupHasPermission( $group, $role ) ) {
4203 $allowedGroups[] = $group;
4206 return $allowedGroups;
4210 * Check, if the given group has the given permission
4212 * If you're wanting to check whether all users have a permission, use
4213 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4217 * @param string $group Group to check
4218 * @param string $role Role to check
4221 public static function groupHasPermission( $group, $role ) {
4222 global $wgGroupPermissions, $wgRevokePermissions;
4223 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4224 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4228 * Check if all users have the given permission
4231 * @param string $right Right to check
4234 public static function isEveryoneAllowed( $right ) {
4235 global $wgGroupPermissions, $wgRevokePermissions;
4236 static $cache = array();
4238 // Use the cached results, except in unit tests which rely on
4239 // being able change the permission mid-request
4240 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4241 return $cache[$right];
4244 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4245 $cache[$right] = false;
4249 // If it's revoked anywhere, then everyone doesn't have it
4250 foreach ( $wgRevokePermissions as $rights ) {
4251 if ( isset( $rights[$right] ) && $rights[$right] ) {
4252 $cache[$right] = false;
4257 // Allow extensions (e.g. OAuth) to say false
4258 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4259 $cache[$right] = false;
4263 $cache[$right] = true;
4268 * Get the localized descriptive name for a group, if it exists
4270 * @param string $group Internal group name
4271 * @return string Localized descriptive group name
4273 public static function getGroupName( $group ) {
4274 $msg = wfMessage( "group-$group" );
4275 return $msg->isBlank() ?
$group : $msg->text();
4279 * Get the localized descriptive name for a member of a group, if it exists
4281 * @param string $group Internal group name
4282 * @param string $username Username for gender (since 1.19)
4283 * @return string Localized name for group member
4285 public static function getGroupMember( $group, $username = '#' ) {
4286 $msg = wfMessage( "group-$group-member", $username );
4287 return $msg->isBlank() ?
$group : $msg->text();
4291 * Return the set of defined explicit groups.
4292 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4293 * are not included, as they are defined automatically, not in the database.
4294 * @return array Array of internal group names
4296 public static function getAllGroups() {
4297 global $wgGroupPermissions, $wgRevokePermissions;
4299 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4300 self
::getImplicitGroups()
4305 * Get a list of all available permissions.
4306 * @return array Array of permission names
4308 public static function getAllRights() {
4309 if ( self
::$mAllRights === false ) {
4310 global $wgAvailableRights;
4311 if ( count( $wgAvailableRights ) ) {
4312 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4314 self
::$mAllRights = self
::$mCoreRights;
4316 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
4318 return self
::$mAllRights;
4322 * Get a list of implicit groups
4323 * @return array Array of Strings Array of internal group names
4325 public static function getImplicitGroups() {
4326 global $wgImplicitGroups;
4328 $groups = $wgImplicitGroups;
4329 # Deprecated, use $wgImplictGroups instead
4330 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) );
4336 * Get the title of a page describing a particular group
4338 * @param string $group Internal group name
4339 * @return Title|bool Title of the page if it exists, false otherwise
4341 public static function getGroupPage( $group ) {
4342 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4343 if ( $msg->exists() ) {
4344 $title = Title
::newFromText( $msg->text() );
4345 if ( is_object( $title ) ) {
4353 * Create a link to the group in HTML, if available;
4354 * else return the group name.
4356 * @param string $group Internal name of the group
4357 * @param string $text The text of the link
4358 * @return string HTML link to the group
4360 public static function makeGroupLinkHTML( $group, $text = '' ) {
4361 if ( $text == '' ) {
4362 $text = self
::getGroupName( $group );
4364 $title = self
::getGroupPage( $group );
4366 return Linker
::link( $title, htmlspecialchars( $text ) );
4373 * Create a link to the group in Wikitext, if available;
4374 * else return the group name.
4376 * @param string $group Internal name of the group
4377 * @param string $text The text of the link
4378 * @return string Wikilink to the group
4380 public static function makeGroupLinkWiki( $group, $text = '' ) {
4381 if ( $text == '' ) {
4382 $text = self
::getGroupName( $group );
4384 $title = self
::getGroupPage( $group );
4386 $page = $title->getPrefixedText();
4387 return "[[$page|$text]]";
4394 * Returns an array of the groups that a particular group can add/remove.
4396 * @param string $group The group to check for whether it can add/remove
4397 * @return array array( 'add' => array( addablegroups ),
4398 * 'remove' => array( removablegroups ),
4399 * 'add-self' => array( addablegroups to self),
4400 * 'remove-self' => array( removable groups from self) )
4402 public static function changeableByGroup( $group ) {
4403 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4407 'remove' => array(),
4408 'add-self' => array(),
4409 'remove-self' => array()
4412 if ( empty( $wgAddGroups[$group] ) ) {
4413 // Don't add anything to $groups
4414 } elseif ( $wgAddGroups[$group] === true ) {
4415 // You get everything
4416 $groups['add'] = self
::getAllGroups();
4417 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4418 $groups['add'] = $wgAddGroups[$group];
4421 // Same thing for remove
4422 if ( empty( $wgRemoveGroups[$group] ) ) {
4423 } elseif ( $wgRemoveGroups[$group] === true ) {
4424 $groups['remove'] = self
::getAllGroups();
4425 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4426 $groups['remove'] = $wgRemoveGroups[$group];
4429 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4430 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4431 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4432 if ( is_int( $key ) ) {
4433 $wgGroupsAddToSelf['user'][] = $value;
4438 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4439 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4440 if ( is_int( $key ) ) {
4441 $wgGroupsRemoveFromSelf['user'][] = $value;
4446 // Now figure out what groups the user can add to him/herself
4447 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4448 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4449 // No idea WHY this would be used, but it's there
4450 $groups['add-self'] = User
::getAllGroups();
4451 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4452 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4455 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4456 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4457 $groups['remove-self'] = User
::getAllGroups();
4458 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4459 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4466 * Returns an array of groups that this user can add and remove
4467 * @return array array( 'add' => array( addablegroups ),
4468 * 'remove' => array( removablegroups ),
4469 * 'add-self' => array( addablegroups to self),
4470 * 'remove-self' => array( removable groups from self) )
4472 public function changeableGroups() {
4473 if ( $this->isAllowed( 'userrights' ) ) {
4474 // This group gives the right to modify everything (reverse-
4475 // compatibility with old "userrights lets you change
4477 // Using array_merge to make the groups reindexed
4478 $all = array_merge( User
::getAllGroups() );
4482 'add-self' => array(),
4483 'remove-self' => array()
4487 // Okay, it's not so simple, we will have to go through the arrays
4490 'remove' => array(),
4491 'add-self' => array(),
4492 'remove-self' => array()
4494 $addergroups = $this->getEffectiveGroups();
4496 foreach ( $addergroups as $addergroup ) {
4497 $groups = array_merge_recursive(
4498 $groups, $this->changeableByGroup( $addergroup )
4500 $groups['add'] = array_unique( $groups['add'] );
4501 $groups['remove'] = array_unique( $groups['remove'] );
4502 $groups['add-self'] = array_unique( $groups['add-self'] );
4503 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4509 * Increment the user's edit-count field.
4510 * Will have no effect for anonymous users.
4512 public function incEditCount() {
4513 if ( !$this->isAnon() ) {
4514 $dbw = wfGetDB( DB_MASTER
);
4517 array( 'user_editcount=user_editcount+1' ),
4518 array( 'user_id' => $this->getId() ),
4522 // Lazy initialization check...
4523 if ( $dbw->affectedRows() == 0 ) {
4524 // Now here's a goddamn hack...
4525 $dbr = wfGetDB( DB_SLAVE
);
4526 if ( $dbr !== $dbw ) {
4527 // If we actually have a slave server, the count is
4528 // at least one behind because the current transaction
4529 // has not been committed and replicated.
4530 $this->initEditCount( 1 );
4532 // But if DB_SLAVE is selecting the master, then the
4533 // count we just read includes the revision that was
4534 // just added in the working transaction.
4535 $this->initEditCount();
4539 // edit count in user cache too
4540 $this->invalidateCache();
4544 * Initialize user_editcount from data out of the revision table
4546 * @param int $add Edits to add to the count from the revision table
4547 * @return int Number of edits
4549 protected function initEditCount( $add = 0 ) {
4550 // Pull from a slave to be less cruel to servers
4551 // Accuracy isn't the point anyway here
4552 $dbr = wfGetDB( DB_SLAVE
);
4553 $count = (int)$dbr->selectField(
4556 array( 'rev_user' => $this->getId() ),
4559 $count = $count +
$add;
4561 $dbw = wfGetDB( DB_MASTER
);
4564 array( 'user_editcount' => $count ),
4565 array( 'user_id' => $this->getId() ),
4573 * Get the description of a given right
4575 * @param string $right Right to query
4576 * @return string Localized description of the right
4578 public static function getRightDescription( $right ) {
4579 $key = "right-$right";
4580 $msg = wfMessage( $key );
4581 return $msg->isBlank() ?
$right : $msg->text();
4585 * Make an old-style password hash
4587 * @param string $password Plain-text password
4588 * @param string $userId User ID
4589 * @return string Password hash
4591 public static function oldCrypt( $password, $userId ) {
4592 global $wgPasswordSalt;
4593 if ( $wgPasswordSalt ) {
4594 return md5( $userId . '-' . md5( $password ) );
4596 return md5( $password );
4601 * Make a new-style password hash
4603 * @param string $password Plain-text password
4604 * @param bool|string $salt Optional salt, may be random or the user ID.
4605 * If unspecified or false, will generate one automatically
4606 * @return string Password hash
4608 public static function crypt( $password, $salt = false ) {
4609 global $wgPasswordSalt;
4612 if ( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4616 if ( $wgPasswordSalt ) {
4617 if ( $salt === false ) {
4618 $salt = MWCryptRand
::generateHex( 8 );
4620 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4622 return ':A:' . md5( $password );
4627 * Compare a password hash with a plain-text password. Requires the user
4628 * ID if there's a chance that the hash is an old-style hash.
4630 * @param string $hash Password hash
4631 * @param string $password Plain-text password to compare
4632 * @param string|bool $userId User ID for old-style password salt
4636 public static function comparePasswords( $hash, $password, $userId = false ) {
4637 $type = substr( $hash, 0, 3 );
4640 if ( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4644 if ( $type == ':A:' ) {
4646 return md5( $password ) === substr( $hash, 3 );
4647 } elseif ( $type == ':B:' ) {
4649 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4650 return md5( $salt . '-' . md5( $password ) ) === $realHash;
4653 return self
::oldCrypt( $password, $userId ) === $hash;
4658 * Add a newuser log entry for this user.
4659 * Before 1.19 the return value was always true.
4661 * @param string|bool $action Account creation type.
4662 * - String, one of the following values:
4663 * - 'create' for an anonymous user creating an account for himself.
4664 * This will force the action's performer to be the created user itself,
4665 * no matter the value of $wgUser
4666 * - 'create2' for a logged in user creating an account for someone else
4667 * - 'byemail' when the created user will receive its password by e-mail
4668 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4669 * - Boolean means whether the account was created by e-mail (deprecated):
4670 * - true will be converted to 'byemail'
4671 * - false will be converted to 'create' if this object is the same as
4672 * $wgUser and to 'create2' otherwise
4674 * @param string $reason User supplied reason
4676 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4678 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4679 global $wgUser, $wgNewUserLog;
4680 if ( empty( $wgNewUserLog ) ) {
4681 return true; // disabled
4684 if ( $action === true ) {
4685 $action = 'byemail';
4686 } elseif ( $action === false ) {
4687 if ( $this->getName() == $wgUser->getName() ) {
4690 $action = 'create2';
4694 if ( $action === 'create' ||
$action === 'autocreate' ) {
4697 $performer = $wgUser;
4700 $logEntry = new ManualLogEntry( 'newusers', $action );
4701 $logEntry->setPerformer( $performer );
4702 $logEntry->setTarget( $this->getUserPage() );
4703 $logEntry->setComment( $reason );
4704 $logEntry->setParameters( array(
4705 '4::userid' => $this->getId(),
4707 $logid = $logEntry->insert();
4709 if ( $action !== 'autocreate' ) {
4710 $logEntry->publish( $logid );
4717 * Add an autocreate newuser log entry for this user
4718 * Used by things like CentralAuth and perhaps other authplugins.
4719 * Consider calling addNewUserLogEntry() directly instead.
4723 public function addNewUserLogEntryAutoCreate() {
4724 $this->addNewUserLogEntry( 'autocreate' );
4730 * Load the user options either from cache, the database or an array
4732 * @param array $data Rows for the current user out of the user_properties table
4734 protected function loadOptions( $data = null ) {
4739 if ( $this->mOptionsLoaded
) {
4743 $this->mOptions
= self
::getDefaultOptions();
4745 if ( !$this->getId() ) {
4746 // For unlogged-in users, load language/variant options from request.
4747 // There's no need to do it for logged-in users: they can set preferences,
4748 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4749 // so don't override user's choice (especially when the user chooses site default).
4750 $variant = $wgContLang->getDefaultVariant();
4751 $this->mOptions
['variant'] = $variant;
4752 $this->mOptions
['language'] = $variant;
4753 $this->mOptionsLoaded
= true;
4757 // Maybe load from the object
4758 if ( !is_null( $this->mOptionOverrides
) ) {
4759 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4760 foreach ( $this->mOptionOverrides
as $key => $value ) {
4761 $this->mOptions
[$key] = $value;
4764 if ( !is_array( $data ) ) {
4765 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4766 // Load from database
4767 $dbr = wfGetDB( DB_SLAVE
);
4769 $res = $dbr->select(
4771 array( 'up_property', 'up_value' ),
4772 array( 'up_user' => $this->getId() ),
4776 $this->mOptionOverrides
= array();
4778 foreach ( $res as $row ) {
4779 $data[$row->up_property
] = $row->up_value
;
4782 foreach ( $data as $property => $value ) {
4783 $this->mOptionOverrides
[$property] = $value;
4784 $this->mOptions
[$property] = $value;
4788 $this->mOptionsLoaded
= true;
4790 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
4794 * Saves the non-default options for this user, as previously set e.g. via
4795 * setOption(), in the database's "user_properties" (preferences) table.
4796 * Usually used via saveSettings().
4798 protected function saveOptions() {
4799 $this->loadOptions();
4801 // Not using getOptions(), to keep hidden preferences in database
4802 $saveOptions = $this->mOptions
;
4804 // Allow hooks to abort, for instance to save to a global profile.
4805 // Reset options to default state before saving.
4806 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4810 $userId = $this->getId();
4812 $insert_rows = array(); // all the new preference rows
4813 foreach ( $saveOptions as $key => $value ) {
4814 // Don't bother storing default values
4815 $defaultOption = self
::getDefaultOption( $key );
4816 if ( ( $defaultOption === null && $value !== false && $value !== null )
4817 ||
$value != $defaultOption
4819 $insert_rows[] = array(
4820 'up_user' => $userId,
4821 'up_property' => $key,
4822 'up_value' => $value,
4827 $dbw = wfGetDB( DB_MASTER
);
4829 $res = $dbw->select( 'user_properties',
4830 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
4832 // Find prior rows that need to be removed or updated. These rows will
4833 // all be deleted (the later so that INSERT IGNORE applies the new values).
4834 $keysDelete = array();
4835 foreach ( $res as $row ) {
4836 if ( !isset( $saveOptions[$row->up_property
] )
4837 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
4839 $keysDelete[] = $row->up_property
;
4843 if ( count( $keysDelete ) ) {
4844 // Do the DELETE by PRIMARY KEY for prior rows.
4845 // In the past a very large portion of calls to this function are for setting
4846 // 'rememberpassword' for new accounts (a preference that has since been removed).
4847 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4848 // caused gap locks on [max user ID,+infinity) which caused high contention since
4849 // updates would pile up on each other as they are for higher (newer) user IDs.
4850 // It might not be necessary these days, but it shouldn't hurt either.
4851 $dbw->delete( 'user_properties',
4852 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
4854 // Insert the new preference rows
4855 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
4859 * Provide an array of HTML5 attributes to put on an input element
4860 * intended for the user to enter a new password. This may include
4861 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4863 * Do *not* use this when asking the user to enter his current password!
4864 * Regardless of configuration, users may have invalid passwords for whatever
4865 * reason (e.g., they were set before requirements were tightened up).
4866 * Only use it when asking for a new password, like on account creation or
4869 * Obviously, you still need to do server-side checking.
4871 * NOTE: A combination of bugs in various browsers means that this function
4872 * actually just returns array() unconditionally at the moment. May as
4873 * well keep it around for when the browser bugs get fixed, though.
4875 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4877 * @return array Array of HTML attributes suitable for feeding to
4878 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4879 * That will get confused by the boolean attribute syntax used.)
4881 public static function passwordChangeInputAttribs() {
4882 global $wgMinimalPasswordLength;
4884 if ( $wgMinimalPasswordLength == 0 ) {
4888 # Note that the pattern requirement will always be satisfied if the
4889 # input is empty, so we need required in all cases.
4891 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4892 # if e-mail confirmation is being used. Since HTML5 input validation
4893 # is b0rked anyway in some browsers, just return nothing. When it's
4894 # re-enabled, fix this code to not output required for e-mail
4896 #$ret = array( 'required' );
4899 # We can't actually do this right now, because Opera 9.6 will print out
4900 # the entered password visibly in its error message! When other
4901 # browsers add support for this attribute, or Opera fixes its support,
4902 # we can add support with a version check to avoid doing this on Opera
4903 # versions where it will be a problem. Reported to Opera as
4904 # DSK-262266, but they don't have a public bug tracker for us to follow.
4906 if ( $wgMinimalPasswordLength > 1 ) {
4907 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4908 $ret['title'] = wfMessage( 'passwordtooshort' )
4909 ->numParams( $wgMinimalPasswordLength )->text();
4917 * Return the list of user fields that should be selected to create
4918 * a new user object.
4921 public static function selectFields() {
4928 'user_newpass_time',
4932 'user_email_authenticated',
4934 'user_email_token_expires',
4935 'user_password_expires',
4936 'user_registration',
4942 * Factory function for fatal permission-denied errors
4945 * @param string $permission User right required
4948 static function newFatalPermissionDeniedStatus( $permission ) {
4951 $groups = array_map(
4952 array( 'User', 'makeGroupLinkWiki' ),
4953 User
::getGroupsWithPermission( $permission )
4957 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4959 return Status
::newFatal( 'badaccess-group0' );