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',
174 'userrights-interwiki',
181 * String Cached results of getAllRights()
183 protected static $mAllRights = false;
185 /** @name Cache variables */
195 public $mNewpassword;
197 public $mNewpassTime;
205 public $mEmailAuthenticated;
207 protected $mEmailToken;
209 protected $mEmailTokenExpires;
211 protected $mRegistration;
213 protected $mEditCount;
217 protected $mOptionOverrides;
219 protected $mPasswordExpires;
223 * Bool Whether the cache variables have been loaded.
226 public $mOptionsLoaded;
229 * Array with already loaded items or true if all items have been loaded.
231 protected $mLoadedItems = array();
235 * String Initialization data source if mLoadedItems!==true. May be one of:
236 * - 'defaults' anonymous user initialised from class defaults
237 * - 'name' initialise from mName
238 * - 'id' initialise from mId
239 * - 'session' log in from cookies or session if possible
241 * Use the User::newFrom*() family of functions to set this.
246 * Lazy-initialized variables, invalidated with clearInstanceCache
250 protected $mDatePreference;
258 protected $mBlockreason;
260 protected $mEffectiveGroups;
262 protected $mImplicitGroups;
264 protected $mFormerGroups;
266 protected $mBlockedGlobally;
283 protected $mAllowUsertalk;
286 private $mBlockedFromCreateAccount = false;
289 private $mWatchedItems = array();
291 public static $idCacheByName = array();
294 * Lightweight constructor for an anonymous user.
295 * Use the User::newFrom* factory functions for other kinds of users.
299 * @see newFromConfirmationCode()
300 * @see newFromSession()
303 public function __construct() {
304 $this->clearInstanceCache( 'defaults' );
310 public function __toString() {
311 return $this->getName();
315 * Load the user table data for this object from the source given by mFrom.
317 public function load() {
318 if ( $this->mLoadedItems
=== true ) {
321 wfProfileIn( __METHOD__
);
323 // Set it now to avoid infinite recursion in accessors
324 $this->mLoadedItems
= true;
326 switch ( $this->mFrom
) {
328 $this->loadDefaults();
331 $this->mId
= self
::idFromName( $this->mName
);
333 // Nonexistent user placeholder object
334 $this->loadDefaults( $this->mName
);
343 if ( !$this->loadFromSession() ) {
344 // Loading from session failed. Load defaults.
345 $this->loadDefaults();
347 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
350 wfProfileOut( __METHOD__
);
351 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
353 wfProfileOut( __METHOD__
);
357 * Load user table data, given mId has already been set.
358 * @return bool false if the ID does not exist, true otherwise
360 public function loadFromId() {
362 if ( $this->mId
== 0 ) {
363 $this->loadDefaults();
368 $key = wfMemcKey( 'user', 'id', $this->mId
);
369 $data = $wgMemc->get( $key );
370 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
371 // Object is expired, load from DB
376 wfDebug( "User: cache miss for user {$this->mId}\n" );
378 if ( !$this->loadFromDatabase() ) {
379 // Can't load from ID, user is anonymous
382 $this->saveToCache();
384 wfDebug( "User: got user {$this->mId} from cache\n" );
385 // Restore from cache
386 foreach ( self
::$mCacheVars as $name ) {
387 $this->$name = $data[$name];
391 $this->mLoadedItems
= true;
397 * Save user data to the shared cache
399 public function saveToCache() {
402 $this->loadOptions();
403 if ( $this->isAnon() ) {
404 // Anonymous users are uncached
408 foreach ( self
::$mCacheVars as $name ) {
409 $data[$name] = $this->$name;
411 $data['mVersion'] = MW_USER_VERSION
;
412 $key = wfMemcKey( 'user', 'id', $this->mId
);
414 $wgMemc->set( $key, $data );
417 /** @name newFrom*() static factory methods */
421 * Static factory method for creation from username.
423 * This is slightly less efficient than newFromId(), so use newFromId() if
424 * you have both an ID and a name handy.
426 * @param string $name Username, validated by Title::newFromText()
427 * @param string|bool $validate Validate username. Takes the same parameters as
428 * User::getCanonicalName(), except that true is accepted as an alias
429 * for 'valid', for BC.
431 * @return User|bool User object, or false if the username is invalid
432 * (e.g. if it contains illegal characters or is an IP address). If the
433 * username is not present in the database, the result will be a user object
434 * with a name, zero user ID and default settings.
436 public static function newFromName( $name, $validate = 'valid' ) {
437 if ( $validate === true ) {
440 $name = self
::getCanonicalName( $name, $validate );
441 if ( $name === false ) {
444 // Create unloaded user object
448 $u->setItemLoaded( 'name' );
454 * Static factory method for creation from a given user ID.
456 * @param int $id Valid user ID
457 * @return User The corresponding User object
459 public static function newFromId( $id ) {
463 $u->setItemLoaded( 'id' );
468 * Factory method to fetch whichever user has a given email confirmation code.
469 * This code is generated when an account is created or its e-mail address
472 * If the code is invalid or has expired, returns NULL.
474 * @param string $code Confirmation code
477 public static function newFromConfirmationCode( $code ) {
478 $dbr = wfGetDB( DB_SLAVE
);
479 $id = $dbr->selectField( 'user', 'user_id', array(
480 'user_email_token' => md5( $code ),
481 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
483 if ( $id !== false ) {
484 return User
::newFromId( $id );
491 * Create a new user object using data from session or cookies. If the
492 * login credentials are invalid, the result is an anonymous user.
494 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
497 public static function newFromSession( WebRequest
$request = null ) {
499 $user->mFrom
= 'session';
500 $user->mRequest
= $request;
505 * Create a new user object from a user row.
506 * The row should have the following fields from the user table in it:
507 * - either user_name or user_id to load further data if needed (or both)
509 * - all other fields (email, password, etc.)
510 * It is useless to provide the remaining fields if either user_id,
511 * user_name and user_real_name are not provided because the whole row
512 * will be loaded once more from the database when accessing them.
514 * @param stdClass $row A row from the user table
515 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
518 public static function newFromRow( $row, $data = null ) {
520 $user->loadFromRow( $row, $data );
527 * Get the username corresponding to a given user ID
528 * @param int $id User ID
529 * @return string|bool The corresponding username
531 public static function whoIs( $id ) {
532 return UserCache
::singleton()->getProp( $id, 'name' );
536 * Get the real name of a user given their user ID
538 * @param int $id User ID
539 * @return string|bool The corresponding user's real name
541 public static function whoIsReal( $id ) {
542 return UserCache
::singleton()->getProp( $id, 'real_name' );
546 * Get database id given a user name
547 * @param string $name Username
548 * @return int|null The corresponding user's ID, or null if user is nonexistent
550 public static function idFromName( $name ) {
551 $nt = Title
::makeTitleSafe( NS_USER
, $name );
552 if ( is_null( $nt ) ) {
557 if ( isset( self
::$idCacheByName[$name] ) ) {
558 return self
::$idCacheByName[$name];
561 $dbr = wfGetDB( DB_SLAVE
);
562 $s = $dbr->selectRow(
565 array( 'user_name' => $nt->getText() ),
569 if ( $s === false ) {
572 $result = $s->user_id
;
575 self
::$idCacheByName[$name] = $result;
577 if ( count( self
::$idCacheByName ) > 1000 ) {
578 self
::$idCacheByName = array();
585 * Reset the cache used in idFromName(). For use in tests.
587 public static function resetIdByNameCache() {
588 self
::$idCacheByName = array();
592 * Does the string match an anonymous IPv4 address?
594 * This function exists for username validation, in order to reject
595 * usernames which are similar in form to IP addresses. Strings such
596 * as 300.300.300.300 will return true because it looks like an IP
597 * address, despite not being strictly valid.
599 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
600 * address because the usemod software would "cloak" anonymous IP
601 * addresses like this, if we allowed accounts like this to be created
602 * new users could get the old edits of these anonymous users.
604 * @param string $name Name to match
607 public static function isIP( $name ) {
608 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
609 || IP
::isIPv6( $name );
613 * Is the input a valid username?
615 * Checks if the input is a valid username, we don't want an empty string,
616 * an IP address, anything that contains slashes (would mess up subpages),
617 * is longer than the maximum allowed username size or doesn't begin with
620 * @param string $name Name to match
623 public static function isValidUserName( $name ) {
624 global $wgContLang, $wgMaxNameChars;
627 || User
::isIP( $name )
628 ||
strpos( $name, '/' ) !== false
629 ||
strlen( $name ) > $wgMaxNameChars
630 ||
$name != $wgContLang->ucfirst( $name ) ) {
631 wfDebugLog( 'username', __METHOD__
.
632 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
636 // Ensure that the name can't be misresolved as a different title,
637 // such as with extra namespace keys at the start.
638 $parsed = Title
::newFromText( $name );
639 if ( is_null( $parsed )
640 ||
$parsed->getNamespace()
641 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
642 wfDebugLog( 'username', __METHOD__
.
643 ": '$name' invalid due to ambiguous prefixes" );
647 // Check an additional blacklist of troublemaker characters.
648 // Should these be merged into the title char list?
649 $unicodeBlacklist = '/[' .
650 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
651 '\x{00a0}' . # non-breaking space
652 '\x{2000}-\x{200f}' . # various whitespace
653 '\x{2028}-\x{202f}' . # breaks and control chars
654 '\x{3000}' . # ideographic space
655 '\x{e000}-\x{f8ff}' . # private use
657 if ( preg_match( $unicodeBlacklist, $name ) ) {
658 wfDebugLog( 'username', __METHOD__
.
659 ": '$name' invalid due to blacklisted characters" );
667 * Usernames which fail to pass this function will be blocked
668 * from user login and new account registrations, but may be used
669 * internally by batch processes.
671 * If an account already exists in this form, login will be blocked
672 * by a failure to pass this function.
674 * @param string $name Name to match
677 public static function isUsableName( $name ) {
678 global $wgReservedUsernames;
679 // Must be a valid username, obviously ;)
680 if ( !self
::isValidUserName( $name ) ) {
684 static $reservedUsernames = false;
685 if ( !$reservedUsernames ) {
686 $reservedUsernames = $wgReservedUsernames;
687 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
690 // Certain names may be reserved for batch processes.
691 foreach ( $reservedUsernames as $reserved ) {
692 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
693 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
695 if ( $reserved == $name ) {
703 * Usernames which fail to pass this function will be blocked
704 * from new account registrations, but may be used internally
705 * either by batch processes or by user accounts which have
706 * already been created.
708 * Additional blacklisting may be added here rather than in
709 * isValidUserName() to avoid disrupting existing accounts.
711 * @param string $name String to match
714 public static function isCreatableName( $name ) {
715 global $wgInvalidUsernameCharacters;
717 // Ensure that the username isn't longer than 235 bytes, so that
718 // (at least for the builtin skins) user javascript and css files
719 // will work. (bug 23080)
720 if ( strlen( $name ) > 235 ) {
721 wfDebugLog( 'username', __METHOD__
.
722 ": '$name' invalid due to length" );
726 // Preg yells if you try to give it an empty string
727 if ( $wgInvalidUsernameCharacters !== '' ) {
728 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
729 wfDebugLog( 'username', __METHOD__
.
730 ": '$name' invalid due to wgInvalidUsernameCharacters" );
735 return self
::isUsableName( $name );
739 * Is the input a valid password for this user?
741 * @param string $password Desired password
744 public function isValidPassword( $password ) {
745 //simple boolean wrapper for getPasswordValidity
746 return $this->getPasswordValidity( $password ) === true;
751 * Given unvalidated password input, return error message on failure.
753 * @param string $password Desired password
754 * @return bool|string|array true on success, string or array of error message on failure
756 public function getPasswordValidity( $password ) {
757 $result = $this->checkPasswordValidity( $password );
758 if ( $result->isGood() ) {
762 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
763 $messages[] = $error['message'];
765 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
766 $messages[] = $warning['message'];
768 if ( count( $messages ) === 1 ) {
776 * Check if this is a valid password for this user. Status will be good if
777 * the password is valid, or have an array of error messages if not.
779 * @param string $password Desired password
783 public function checkPasswordValidity( $password ) {
784 global $wgMinimalPasswordLength, $wgContLang;
786 static $blockedLogins = array(
787 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
788 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
791 $status = Status
::newGood();
793 $result = false; //init $result to false for the internal checks
795 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
796 $status->error( $result );
800 if ( $result === false ) {
801 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
802 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
804 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
805 $status->error( 'password-name-match' );
807 } elseif ( isset( $blockedLogins[$this->getName()] )
808 && $password == $blockedLogins[$this->getName()]
810 $status->error( 'password-login-forbidden' );
813 //it seems weird returning a Good status here, but this is because of the
814 //initialization of $result to false above. If the hook is never run or it
815 //doesn't modify $result, then we will likely get down into this if with
819 } elseif ( $result === true ) {
822 $status->error( $result );
823 return $status; //the isValidPassword hook set a string $result and returned true
828 * Expire a user's password
830 * @param int $ts Optional timestamp to convert, default 0 for the current time
832 public function expirePassword( $ts = 0 ) {
834 $timestamp = wfTimestamp( TS_MW
, $ts );
835 $this->mPasswordExpires
= $timestamp;
836 $this->saveSettings();
840 * Clear the password expiration for a user
842 * @param bool $load Ensure user object is loaded first
844 public function resetPasswordExpiration( $load = true ) {
845 global $wgPasswordExpirationDays;
850 if ( $wgPasswordExpirationDays ) {
851 $newExpire = wfTimestamp(
853 time() +
( $wgPasswordExpirationDays * 24 * 3600 )
856 // Give extensions a chance to force an expiration
857 wfRunHooks( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
858 $this->mPasswordExpires
= $newExpire;
862 * Check if the user's password is expired.
863 * TODO: Put this and password length into a PasswordPolicy object
865 * @return string|bool The expiration type, or false if not expired
866 * hard: A password change is required to login
867 * soft: Allow login, but encourage password change
868 * false: Password is not expired
870 public function getPasswordExpired() {
871 global $wgPasswordExpireGrace;
873 $now = wfTimestamp();
874 $expiration = $this->getPasswordExpireDate();
875 $expUnix = wfTimestamp( TS_UNIX
, $expiration );
876 if ( $expiration !== null && $expUnix < $now ) {
877 $expired = ( $expUnix +
$wgPasswordExpireGrace < $now ) ?
'hard' : 'soft';
883 * Get this user's password expiration date. Since this may be using
884 * the cached User object, we assume that whatever mechanism is setting
885 * the expiration date is also expiring the User cache.
887 * @return string|bool The datestamp of the expiration, or null if not set
889 public function getPasswordExpireDate() {
891 return $this->mPasswordExpires
;
895 * Does a string look like an e-mail address?
897 * This validates an email address using an HTML5 specification found at:
898 * http://www.whatwg.org/html/states-of-the-type-attribute.html#valid-e-mail-address
899 * Which as of 2011-01-24 says:
901 * A valid e-mail address is a string that matches the ABNF production
902 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
903 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
906 * This function is an implementation of the specification as requested in
909 * Client-side forms will use the same standard validation rules via JS or
910 * HTML 5 validation; additional restrictions can be enforced server-side
911 * by extensions via the 'isValidEmailAddr' hook.
913 * Note that this validation doesn't 100% match RFC 2822, but is believed
914 * to be liberal enough for wide use. Some invalid addresses will still
915 * pass validation here.
917 * @param string $addr E-mail address
919 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
921 public static function isValidEmailAddr( $addr ) {
922 wfDeprecated( __METHOD__
, '1.18' );
923 return Sanitizer
::validateEmail( $addr );
927 * Given unvalidated user input, return a canonical username, or false if
928 * the username is invalid.
929 * @param string $name User input
930 * @param string|bool $validate Type of validation to use:
931 * - false No validation
932 * - 'valid' Valid for batch processes
933 * - 'usable' Valid for batch processes and login
934 * - 'creatable' Valid for batch processes, login and account creation
936 * @throws MWException
937 * @return bool|string
939 public static function getCanonicalName( $name, $validate = 'valid' ) {
940 // Force usernames to capital
942 $name = $wgContLang->ucfirst( $name );
944 # Reject names containing '#'; these will be cleaned up
945 # with title normalisation, but then it's too late to
947 if ( strpos( $name, '#' ) !== false ) {
951 // Clean up name according to title rules
952 $t = ( $validate === 'valid' ) ?
953 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
954 // Check for invalid titles
955 if ( is_null( $t ) ) {
959 // Reject various classes of invalid names
961 $name = $wgAuth->getCanonicalName( $t->getText() );
963 switch ( $validate ) {
967 if ( !User
::isValidUserName( $name ) ) {
972 if ( !User
::isUsableName( $name ) ) {
977 if ( !User
::isCreatableName( $name ) ) {
982 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
988 * Count the number of edits of a user
990 * @param int $uid User ID to check
991 * @return int The user's edit count
993 * @deprecated since 1.21 in favour of User::getEditCount
995 public static function edits( $uid ) {
996 wfDeprecated( __METHOD__
, '1.21' );
997 $user = self
::newFromId( $uid );
998 return $user->getEditCount();
1002 * Return a random password.
1004 * @return string New random password
1006 public static function randomPassword() {
1007 global $wgMinimalPasswordLength;
1008 // Decide the final password length based on our min password length,
1009 // stopping at a minimum of 10 chars.
1010 $length = max( 10, $wgMinimalPasswordLength );
1011 // Multiply by 1.25 to get the number of hex characters we need
1012 $length = $length * 1.25;
1013 // Generate random hex chars
1014 $hex = MWCryptRand
::generateHex( $length );
1015 // Convert from base 16 to base 32 to get a proper password like string
1016 return wfBaseConvert( $hex, 16, 32 );
1020 * Set cached properties to default.
1022 * @note This no longer clears uncached lazy-initialised properties;
1023 * the constructor does that instead.
1025 * @param string|bool $name
1027 public function loadDefaults( $name = false ) {
1028 wfProfileIn( __METHOD__
);
1031 $this->mName
= $name;
1032 $this->mRealName
= '';
1033 $this->mPassword
= $this->mNewpassword
= '';
1034 $this->mNewpassTime
= null;
1036 $this->mOptionOverrides
= null;
1037 $this->mOptionsLoaded
= false;
1039 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1040 if ( $loggedOut !== null ) {
1041 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1043 $this->mTouched
= '1'; # Allow any pages to be cached
1046 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1047 $this->mEmailAuthenticated
= null;
1048 $this->mEmailToken
= '';
1049 $this->mEmailTokenExpires
= null;
1050 $this->mPasswordExpires
= null;
1051 $this->resetPasswordExpiration( false );
1052 $this->mRegistration
= wfTimestamp( TS_MW
);
1053 $this->mGroups
= array();
1055 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
1057 wfProfileOut( __METHOD__
);
1061 * Return whether an item has been loaded.
1063 * @param string $item Item to check. Current possibilities:
1067 * @param string $all 'all' to check if the whole object has been loaded
1068 * or any other string to check if only the item is available (e.g.
1072 public function isItemLoaded( $item, $all = 'all' ) {
1073 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1074 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1078 * Set that an item has been loaded
1080 * @param string $item
1082 protected function setItemLoaded( $item ) {
1083 if ( is_array( $this->mLoadedItems
) ) {
1084 $this->mLoadedItems
[$item] = true;
1089 * Load user data from the session or login cookie.
1090 * @return bool True if the user is logged in, false otherwise.
1092 private function loadFromSession() {
1094 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
1095 if ( $result !== null ) {
1099 $request = $this->getRequest();
1101 $cookieId = $request->getCookie( 'UserID' );
1102 $sessId = $request->getSessionData( 'wsUserID' );
1104 if ( $cookieId !== null ) {
1105 $sId = intval( $cookieId );
1106 if ( $sessId !== null && $cookieId != $sessId ) {
1107 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1108 cookie user ID ($sId) don't match!" );
1111 $request->setSessionData( 'wsUserID', $sId );
1112 } elseif ( $sessId !== null && $sessId != 0 ) {
1118 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1119 $sName = $request->getSessionData( 'wsUserName' );
1120 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1121 $sName = $request->getCookie( 'UserName' );
1122 $request->setSessionData( 'wsUserName', $sName );
1127 $proposedUser = User
::newFromId( $sId );
1128 if ( !$proposedUser->isLoggedIn() ) {
1133 global $wgBlockDisablesLogin;
1134 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1135 // User blocked and we've disabled blocked user logins
1139 if ( $request->getSessionData( 'wsToken' ) ) {
1141 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1143 } elseif ( $request->getCookie( 'Token' ) ) {
1144 # Get the token from DB/cache and clean it up to remove garbage padding.
1145 # This deals with historical problems with bugs and the default column value.
1146 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1147 // Make comparison in constant time (bug 61346)
1148 $passwordCorrect = strlen( $token )
1149 && hash_equals( $token, $request->getCookie( 'Token' ) );
1152 // No session or persistent login cookie
1156 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1157 $this->loadFromUserObject( $proposedUser );
1158 $request->setSessionData( 'wsToken', $this->mToken
);
1159 wfDebug( "User: logged in from $from\n" );
1162 // Invalid credentials
1163 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1169 * Load user and user_group data from the database.
1170 * $this->mId must be set, this is how the user is identified.
1172 * @param integer $flags Supports User::READ_LOCKING
1173 * @return bool True if the user exists, false if the user is anonymous
1175 public function loadFromDatabase( $flags = 0 ) {
1177 $this->mId
= intval( $this->mId
);
1180 if ( !$this->mId
) {
1181 $this->loadDefaults();
1185 $dbr = wfGetDB( DB_MASTER
);
1186 $s = $dbr->selectRow(
1188 self
::selectFields(),
1189 array( 'user_id' => $this->mId
),
1191 ( $flags & self
::READ_LOCKING
== self
::READ_LOCKING
)
1192 ?
array( 'LOCK IN SHARE MODE' )
1196 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1198 if ( $s !== false ) {
1199 // Initialise user table data
1200 $this->loadFromRow( $s );
1201 $this->mGroups
= null; // deferred
1202 $this->getEditCount(); // revalidation for nulls
1207 $this->loadDefaults();
1213 * Initialize this object from a row from the user table.
1215 * @param stdClass $row Row from the user table to load.
1216 * @param array $data Further user data to load into the object
1218 * user_groups Array with groups out of the user_groups table
1219 * user_properties Array with properties out of the user_properties table
1221 public function loadFromRow( $row, $data = null ) {
1224 $this->mGroups
= null; // deferred
1226 if ( isset( $row->user_name
) ) {
1227 $this->mName
= $row->user_name
;
1228 $this->mFrom
= 'name';
1229 $this->setItemLoaded( 'name' );
1234 if ( isset( $row->user_real_name
) ) {
1235 $this->mRealName
= $row->user_real_name
;
1236 $this->setItemLoaded( 'realname' );
1241 if ( isset( $row->user_id
) ) {
1242 $this->mId
= intval( $row->user_id
);
1243 $this->mFrom
= 'id';
1244 $this->setItemLoaded( 'id' );
1249 if ( isset( $row->user_editcount
) ) {
1250 $this->mEditCount
= $row->user_editcount
;
1255 if ( isset( $row->user_password
) ) {
1256 $this->mPassword
= $row->user_password
;
1257 $this->mNewpassword
= $row->user_newpassword
;
1258 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1259 $this->mEmail
= $row->user_email
;
1260 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1261 $this->mToken
= $row->user_token
;
1262 if ( $this->mToken
== '' ) {
1263 $this->mToken
= null;
1265 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1266 $this->mEmailToken
= $row->user_email_token
;
1267 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1268 $this->mPasswordExpires
= wfTimestampOrNull( TS_MW
, $row->user_password_expires
);
1269 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1275 $this->mLoadedItems
= true;
1278 if ( is_array( $data ) ) {
1279 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1280 $this->mGroups
= $data['user_groups'];
1282 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1283 $this->loadOptions( $data['user_properties'] );
1289 * Load the data for this user object from another user object.
1293 protected function loadFromUserObject( $user ) {
1295 $user->loadGroups();
1296 $user->loadOptions();
1297 foreach ( self
::$mCacheVars as $var ) {
1298 $this->$var = $user->$var;
1303 * Load the groups from the database if they aren't already loaded.
1305 private function loadGroups() {
1306 if ( is_null( $this->mGroups
) ) {
1307 $dbr = wfGetDB( DB_MASTER
);
1308 $res = $dbr->select( 'user_groups',
1309 array( 'ug_group' ),
1310 array( 'ug_user' => $this->mId
),
1312 $this->mGroups
= array();
1313 foreach ( $res as $row ) {
1314 $this->mGroups
[] = $row->ug_group
;
1320 * Add the user to the group if he/she meets given criteria.
1322 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1323 * possible to remove manually via Special:UserRights. In such case it
1324 * will not be re-added automatically. The user will also not lose the
1325 * group if they no longer meet the criteria.
1327 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1329 * @return array Array of groups the user has been promoted to.
1331 * @see $wgAutopromoteOnce
1333 public function addAutopromoteOnceGroups( $event ) {
1334 global $wgAutopromoteOnceLogInRC, $wgAuth;
1336 $toPromote = array();
1337 if ( $this->getId() ) {
1338 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1339 if ( count( $toPromote ) ) {
1340 $oldGroups = $this->getGroups(); // previous groups
1342 foreach ( $toPromote as $group ) {
1343 $this->addGroup( $group );
1345 // update groups in external authentication database
1346 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1348 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1350 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1351 $logEntry->setPerformer( $this );
1352 $logEntry->setTarget( $this->getUserPage() );
1353 $logEntry->setParameters( array(
1354 '4::oldgroups' => $oldGroups,
1355 '5::newgroups' => $newGroups,
1357 $logid = $logEntry->insert();
1358 if ( $wgAutopromoteOnceLogInRC ) {
1359 $logEntry->publish( $logid );
1367 * Clear various cached data stored in this object. The cache of the user table
1368 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1370 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1371 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1373 public function clearInstanceCache( $reloadFrom = false ) {
1374 $this->mNewtalk
= -1;
1375 $this->mDatePreference
= null;
1376 $this->mBlockedby
= -1; # Unset
1377 $this->mHash
= false;
1378 $this->mRights
= null;
1379 $this->mEffectiveGroups
= null;
1380 $this->mImplicitGroups
= null;
1381 $this->mGroups
= null;
1382 $this->mOptions
= null;
1383 $this->mOptionsLoaded
= false;
1384 $this->mEditCount
= null;
1386 if ( $reloadFrom ) {
1387 $this->mLoadedItems
= array();
1388 $this->mFrom
= $reloadFrom;
1393 * Combine the language default options with any site-specific options
1394 * and add the default language variants.
1396 * @return array Array of String options
1398 public static function getDefaultOptions() {
1399 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1401 static $defOpt = null;
1402 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1403 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1404 // mid-request and see that change reflected in the return value of this function.
1405 // Which is insane and would never happen during normal MW operation
1409 $defOpt = $wgDefaultUserOptions;
1410 // Default language setting
1411 $defOpt['language'] = $wgContLang->getCode();
1412 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1413 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1415 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1416 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1418 $defOpt['skin'] = $wgDefaultSkin;
1420 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1426 * Get a given default option value.
1428 * @param string $opt Name of option to retrieve
1429 * @return string Default option value
1431 public static function getDefaultOption( $opt ) {
1432 $defOpts = self
::getDefaultOptions();
1433 if ( isset( $defOpts[$opt] ) ) {
1434 return $defOpts[$opt];
1441 * Get blocking information
1442 * @param bool $bFromSlave Whether to check the slave database first.
1443 * To improve performance, non-critical checks are done against slaves.
1444 * Check when actually saving should be done against master.
1446 private function getBlockedStatus( $bFromSlave = true ) {
1447 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1449 if ( -1 != $this->mBlockedby
) {
1453 wfProfileIn( __METHOD__
);
1454 wfDebug( __METHOD__
. ": checking...\n" );
1456 // Initialize data...
1457 // Otherwise something ends up stomping on $this->mBlockedby when
1458 // things get lazy-loaded later, causing false positive block hits
1459 // due to -1 !== 0. Probably session-related... Nothing should be
1460 // overwriting mBlockedby, surely?
1463 # We only need to worry about passing the IP address to the Block generator if the
1464 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1465 # know which IP address they're actually coming from
1466 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1467 $ip = $this->getRequest()->getIP();
1473 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1476 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1477 && !in_array( $ip, $wgProxyWhitelist )
1480 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1482 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1483 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1484 $block->setTarget( $ip );
1485 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1487 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1488 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1489 $block->setTarget( $ip );
1493 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1494 if ( !$block instanceof Block
1495 && $wgApplyIpBlocksToXff
1497 && !$this->isAllowed( 'proxyunbannable' )
1498 && !in_array( $ip, $wgProxyWhitelist )
1500 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1501 $xff = array_map( 'trim', explode( ',', $xff ) );
1502 $xff = array_diff( $xff, array( $ip ) );
1503 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1504 $block = Block
::chooseBlock( $xffblocks, $xff );
1505 if ( $block instanceof Block
) {
1506 # Mangle the reason to alert the user that the block
1507 # originated from matching the X-Forwarded-For header.
1508 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1512 if ( $block instanceof Block
) {
1513 wfDebug( __METHOD__
. ": Found block.\n" );
1514 $this->mBlock
= $block;
1515 $this->mBlockedby
= $block->getByName();
1516 $this->mBlockreason
= $block->mReason
;
1517 $this->mHideName
= $block->mHideName
;
1518 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1520 $this->mBlockedby
= '';
1521 $this->mHideName
= 0;
1522 $this->mAllowUsertalk
= false;
1526 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1528 wfProfileOut( __METHOD__
);
1532 * Whether the given IP is in a DNS blacklist.
1534 * @param string $ip IP to check
1535 * @param bool $checkWhitelist Whether to check the whitelist first
1536 * @return bool True if blacklisted.
1538 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1539 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1540 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1542 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs ) {
1546 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1550 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1551 return $this->inDnsBlacklist( $ip, $urls );
1555 * Whether the given IP is in a given DNS blacklist.
1557 * @param string $ip IP to check
1558 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1559 * @return bool True if blacklisted.
1561 public function inDnsBlacklist( $ip, $bases ) {
1562 wfProfileIn( __METHOD__
);
1565 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1566 if ( IP
::isIPv4( $ip ) ) {
1567 // Reverse IP, bug 21255
1568 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1570 foreach ( (array)$bases as $base ) {
1572 // If we have an access key, use that too (ProjectHoneypot, etc.)
1573 if ( is_array( $base ) ) {
1574 if ( count( $base ) >= 2 ) {
1575 // Access key is 1, base URL is 0
1576 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1578 $host = "$ipReversed.{$base[0]}";
1581 $host = "$ipReversed.$base";
1585 $ipList = gethostbynamel( $host );
1588 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1592 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1597 wfProfileOut( __METHOD__
);
1602 * Check if an IP address is in the local proxy list
1608 public static function isLocallyBlockedProxy( $ip ) {
1609 global $wgProxyList;
1611 if ( !$wgProxyList ) {
1614 wfProfileIn( __METHOD__
);
1616 if ( !is_array( $wgProxyList ) ) {
1617 // Load from the specified file
1618 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1621 if ( !is_array( $wgProxyList ) ) {
1623 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1625 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1626 // Old-style flipped proxy list
1631 wfProfileOut( __METHOD__
);
1636 * Is this user subject to rate limiting?
1638 * @return bool True if rate limited
1640 public function isPingLimitable() {
1641 global $wgRateLimitsExcludedIPs;
1642 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1643 // No other good way currently to disable rate limits
1644 // for specific IPs. :P
1645 // But this is a crappy hack and should die.
1648 return !$this->isAllowed( 'noratelimit' );
1652 * Primitive rate limits: enforce maximum actions per time period
1653 * to put a brake on flooding.
1655 * The method generates both a generic profiling point and a per action one
1656 * (suffix being "-$action".
1658 * @note When using a shared cache like memcached, IP-address
1659 * last-hit counters will be shared across wikis.
1661 * @param string $action Action to enforce; 'edit' if unspecified
1662 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1663 * @return bool True if a rate limiter was tripped
1665 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1666 // Call the 'PingLimiter' hook
1668 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1672 global $wgRateLimits;
1673 if ( !isset( $wgRateLimits[$action] ) ) {
1677 // Some groups shouldn't trigger the ping limiter, ever
1678 if ( !$this->isPingLimitable() ) {
1683 wfProfileIn( __METHOD__
);
1684 wfProfileIn( __METHOD__
. '-' . $action );
1686 $limits = $wgRateLimits[$action];
1688 $id = $this->getId();
1691 if ( isset( $limits['anon'] ) && $id == 0 ) {
1692 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1695 if ( isset( $limits['user'] ) && $id != 0 ) {
1696 $userLimit = $limits['user'];
1698 if ( $this->isNewbie() ) {
1699 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1700 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1702 if ( isset( $limits['ip'] ) ) {
1703 $ip = $this->getRequest()->getIP();
1704 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1706 if ( isset( $limits['subnet'] ) ) {
1707 $ip = $this->getRequest()->getIP();
1710 if ( IP
::isIPv6( $ip ) ) {
1711 $parts = IP
::parseRange( "$ip/64" );
1712 $subnet = $parts[0];
1713 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1715 $subnet = $matches[1];
1717 if ( $subnet !== false ) {
1718 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1722 // Check for group-specific permissions
1723 // If more than one group applies, use the group with the highest limit
1724 foreach ( $this->getGroups() as $group ) {
1725 if ( isset( $limits[$group] ) ) {
1726 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1727 $userLimit = $limits[$group];
1731 // Set the user limit key
1732 if ( $userLimit !== false ) {
1733 list( $max, $period ) = $userLimit;
1734 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1735 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1739 foreach ( $keys as $key => $limit ) {
1740 list( $max, $period ) = $limit;
1741 $summary = "(limit $max in {$period}s)";
1742 $count = $wgMemc->get( $key );
1745 if ( $count >= $max ) {
1746 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1747 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1750 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1753 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1754 if ( $incrBy > 0 ) {
1755 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1758 if ( $incrBy > 0 ) {
1759 $wgMemc->incr( $key, $incrBy );
1763 wfProfileOut( __METHOD__
. '-' . $action );
1764 wfProfileOut( __METHOD__
);
1769 * Check if user is blocked
1771 * @param bool $bFromSlave Whether to check the slave database instead of
1772 * the master. Hacked from false due to horrible probs on site.
1773 * @return bool True if blocked, false otherwise
1775 public function isBlocked( $bFromSlave = true ) {
1776 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1780 * Get the block affecting the user, or null if the user is not blocked
1782 * @param bool $bFromSlave Whether to check the slave database instead of the master
1783 * @return Block|null
1785 public function getBlock( $bFromSlave = true ) {
1786 $this->getBlockedStatus( $bFromSlave );
1787 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1791 * Check if user is blocked from editing a particular article
1793 * @param Title $title Title to check
1794 * @param bool $bFromSlave Whether to check the slave database instead of the master
1797 public function isBlockedFrom( $title, $bFromSlave = false ) {
1798 global $wgBlockAllowsUTEdit;
1799 wfProfileIn( __METHOD__
);
1801 $blocked = $this->isBlocked( $bFromSlave );
1802 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1803 // If a user's name is suppressed, they cannot make edits anywhere
1804 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1805 && $title->getNamespace() == NS_USER_TALK
) {
1807 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1810 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1812 wfProfileOut( __METHOD__
);
1817 * If user is blocked, return the name of the user who placed the block
1818 * @return string Name of blocker
1820 public function blockedBy() {
1821 $this->getBlockedStatus();
1822 return $this->mBlockedby
;
1826 * If user is blocked, return the specified reason for the block
1827 * @return string Blocking reason
1829 public function blockedFor() {
1830 $this->getBlockedStatus();
1831 return $this->mBlockreason
;
1835 * If user is blocked, return the ID for the block
1836 * @return int Block ID
1838 public function getBlockId() {
1839 $this->getBlockedStatus();
1840 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1844 * Check if user is blocked on all wikis.
1845 * Do not use for actual edit permission checks!
1846 * This is intended for quick UI checks.
1848 * @param string $ip IP address, uses current client if none given
1849 * @return bool True if blocked, false otherwise
1851 public function isBlockedGlobally( $ip = '' ) {
1852 if ( $this->mBlockedGlobally
!== null ) {
1853 return $this->mBlockedGlobally
;
1855 // User is already an IP?
1856 if ( IP
::isIPAddress( $this->getName() ) ) {
1857 $ip = $this->getName();
1859 $ip = $this->getRequest()->getIP();
1862 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1863 $this->mBlockedGlobally
= (bool)$blocked;
1864 return $this->mBlockedGlobally
;
1868 * Check if user account is locked
1870 * @return bool True if locked, false otherwise
1872 public function isLocked() {
1873 if ( $this->mLocked
!== null ) {
1874 return $this->mLocked
;
1877 StubObject
::unstub( $wgAuth );
1878 $authUser = $wgAuth->getUserInstance( $this );
1879 $this->mLocked
= (bool)$authUser->isLocked();
1880 return $this->mLocked
;
1884 * Check if user account is hidden
1886 * @return bool True if hidden, false otherwise
1888 public function isHidden() {
1889 if ( $this->mHideName
!== null ) {
1890 return $this->mHideName
;
1892 $this->getBlockedStatus();
1893 if ( !$this->mHideName
) {
1895 StubObject
::unstub( $wgAuth );
1896 $authUser = $wgAuth->getUserInstance( $this );
1897 $this->mHideName
= (bool)$authUser->isHidden();
1899 return $this->mHideName
;
1903 * Get the user's ID.
1904 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1906 public function getId() {
1907 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1908 // Special case, we know the user is anonymous
1910 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1911 // Don't load if this was initialized from an ID
1918 * Set the user and reload all fields according to a given ID
1919 * @param int $v User ID to reload
1921 public function setId( $v ) {
1923 $this->clearInstanceCache( 'id' );
1927 * Get the user name, or the IP of an anonymous user
1928 * @return string User's name or IP address
1930 public function getName() {
1931 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1932 // Special case optimisation
1933 return $this->mName
;
1936 if ( $this->mName
=== false ) {
1938 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1940 return $this->mName
;
1945 * Set the user name.
1947 * This does not reload fields from the database according to the given
1948 * name. Rather, it is used to create a temporary "nonexistent user" for
1949 * later addition to the database. It can also be used to set the IP
1950 * address for an anonymous user to something other than the current
1953 * @note User::newFromName() has roughly the same function, when the named user
1955 * @param string $str New user name to set
1957 public function setName( $str ) {
1959 $this->mName
= $str;
1963 * Get the user's name escaped by underscores.
1964 * @return string Username escaped by underscores.
1966 public function getTitleKey() {
1967 return str_replace( ' ', '_', $this->getName() );
1971 * Check if the user has new messages.
1972 * @return bool True if the user has new messages
1974 public function getNewtalk() {
1977 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1978 if ( $this->mNewtalk
=== -1 ) {
1979 $this->mNewtalk
= false; # reset talk page status
1981 // Check memcached separately for anons, who have no
1982 // entire User object stored in there.
1983 if ( !$this->mId
) {
1984 global $wgDisableAnonTalk;
1985 if ( $wgDisableAnonTalk ) {
1986 // Anon newtalk disabled by configuration.
1987 $this->mNewtalk
= false;
1990 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1991 $newtalk = $wgMemc->get( $key );
1992 if ( strval( $newtalk ) !== '' ) {
1993 $this->mNewtalk
= (bool)$newtalk;
1995 // Since we are caching this, make sure it is up to date by getting it
1997 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1998 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
2002 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2006 return (bool)$this->mNewtalk
;
2010 * Return the data needed to construct links for new talk page message
2011 * alerts. If there are new messages, this will return an associative array
2012 * with the following data:
2013 * wiki: The database name of the wiki
2014 * link: Root-relative link to the user's talk page
2015 * rev: The last talk page revision that the user has seen or null. This
2016 * is useful for building diff links.
2017 * If there are no new messages, it returns an empty array.
2018 * @note This function was designed to accomodate multiple talk pages, but
2019 * currently only returns a single link and revision.
2022 public function getNewMessageLinks() {
2024 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2026 } elseif ( !$this->getNewtalk() ) {
2029 $utp = $this->getTalkPage();
2030 $dbr = wfGetDB( DB_SLAVE
);
2031 // Get the "last viewed rev" timestamp from the oldest message notification
2032 $timestamp = $dbr->selectField( 'user_newtalk',
2033 'MIN(user_last_timestamp)',
2034 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2036 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2037 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2041 * Get the revision ID for the last talk page revision viewed by the talk
2043 * @return int|null Revision ID or null
2045 public function getNewMessageRevisionId() {
2046 $newMessageRevisionId = null;
2047 $newMessageLinks = $this->getNewMessageLinks();
2048 if ( $newMessageLinks ) {
2049 // Note: getNewMessageLinks() never returns more than a single link
2050 // and it is always for the same wiki, but we double-check here in
2051 // case that changes some time in the future.
2052 if ( count( $newMessageLinks ) === 1
2053 && $newMessageLinks[0]['wiki'] === wfWikiID()
2054 && $newMessageLinks[0]['rev']
2056 $newMessageRevision = $newMessageLinks[0]['rev'];
2057 $newMessageRevisionId = $newMessageRevision->getId();
2060 return $newMessageRevisionId;
2064 * Internal uncached check for new messages
2067 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2068 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2069 * @param bool $fromMaster true to fetch from the master, false for a slave
2070 * @return bool True if the user has new messages
2072 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2073 if ( $fromMaster ) {
2074 $db = wfGetDB( DB_MASTER
);
2076 $db = wfGetDB( DB_SLAVE
);
2078 $ok = $db->selectField( 'user_newtalk', $field,
2079 array( $field => $id ), __METHOD__
);
2080 return $ok !== false;
2084 * Add or update the new messages flag
2085 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2086 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2087 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2088 * @return bool True if successful, false otherwise
2090 protected function updateNewtalk( $field, $id, $curRev = null ) {
2091 // Get timestamp of the talk page revision prior to the current one
2092 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2093 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2094 // Mark the user as having new messages since this revision
2095 $dbw = wfGetDB( DB_MASTER
);
2096 $dbw->insert( 'user_newtalk',
2097 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2100 if ( $dbw->affectedRows() ) {
2101 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2104 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2110 * Clear the new messages flag for the given user
2111 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2112 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2113 * @return bool True if successful, false otherwise
2115 protected function deleteNewtalk( $field, $id ) {
2116 $dbw = wfGetDB( DB_MASTER
);
2117 $dbw->delete( 'user_newtalk',
2118 array( $field => $id ),
2120 if ( $dbw->affectedRows() ) {
2121 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2124 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2130 * Update the 'You have new messages!' status.
2131 * @param bool $val Whether the user has new messages
2132 * @param Revision $curRev New, as yet unseen revision of the user talk
2133 * page. Ignored if null or !$val.
2135 public function setNewtalk( $val, $curRev = null ) {
2136 if ( wfReadOnly() ) {
2141 $this->mNewtalk
= $val;
2143 if ( $this->isAnon() ) {
2145 $id = $this->getName();
2148 $id = $this->getId();
2153 $changed = $this->updateNewtalk( $field, $id, $curRev );
2155 $changed = $this->deleteNewtalk( $field, $id );
2158 if ( $this->isAnon() ) {
2159 // Anons have a separate memcached space, since
2160 // user records aren't kept for them.
2161 $key = wfMemcKey( 'newtalk', 'ip', $id );
2162 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
2165 $this->invalidateCache();
2170 * Generate a current or new-future timestamp to be stored in the
2171 * user_touched field when we update things.
2172 * @return string Timestamp in TS_MW format
2174 private static function newTouchedTimestamp() {
2175 global $wgClockSkewFudge;
2176 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2180 * Clear user data from memcached.
2181 * Use after applying fun updates to the database; caller's
2182 * responsibility to update user_touched if appropriate.
2184 * Called implicitly from invalidateCache() and saveSettings().
2186 private function clearSharedCache() {
2190 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
2195 * Immediately touch the user data cache for this account.
2196 * Updates user_touched field, and removes account data from memcached
2197 * for reload on the next hit.
2199 public function invalidateCache() {
2200 if ( wfReadOnly() ) {
2205 $this->mTouched
= self
::newTouchedTimestamp();
2207 $dbw = wfGetDB( DB_MASTER
);
2208 $userid = $this->mId
;
2209 $touched = $this->mTouched
;
2210 $method = __METHOD__
;
2211 $dbw->onTransactionIdle( function() use ( $dbw, $userid, $touched, $method ) {
2212 // Prevent contention slams by checking user_touched first
2213 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2214 $needsPurge = $dbw->selectField( 'user', '1',
2215 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2216 if ( $needsPurge ) {
2217 $dbw->update( 'user',
2218 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2219 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2224 $this->clearSharedCache();
2229 * Validate the cache for this account.
2230 * @param string $timestamp A timestamp in TS_MW format
2233 public function validateCache( $timestamp ) {
2235 return ( $timestamp >= $this->mTouched
);
2239 * Get the user touched timestamp
2240 * @return string Timestamp
2242 public function getTouched() {
2244 return $this->mTouched
;
2248 * Set the password and reset the random token.
2249 * Calls through to authentication plugin if necessary;
2250 * will have no effect if the auth plugin refuses to
2251 * pass the change through or if the legal password
2254 * As a special case, setting the password to null
2255 * wipes it, so the account cannot be logged in until
2256 * a new password is set, for instance via e-mail.
2258 * @param string $str New password to set
2259 * @throws PasswordError on failure
2263 public function setPassword( $str ) {
2266 if ( $str !== null ) {
2267 if ( !$wgAuth->allowPasswordChange() ) {
2268 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2271 if ( !$this->isValidPassword( $str ) ) {
2272 global $wgMinimalPasswordLength;
2273 $valid = $this->getPasswordValidity( $str );
2274 if ( is_array( $valid ) ) {
2275 $message = array_shift( $valid );
2279 $params = array( $wgMinimalPasswordLength );
2281 throw new PasswordError( wfMessage( $message, $params )->text() );
2285 if ( !$wgAuth->setPassword( $this, $str ) ) {
2286 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2289 $this->setInternalPassword( $str );
2295 * Set the password and reset the random token unconditionally.
2297 * @param string|null $str New password to set or null to set an invalid
2298 * password hash meaning that the user will not be able to log in
2299 * through the web interface.
2301 public function setInternalPassword( $str ) {
2305 if ( $str === null ) {
2306 // Save an invalid hash...
2307 $this->mPassword
= '';
2309 $this->mPassword
= self
::crypt( $str );
2311 $this->mNewpassword
= '';
2312 $this->mNewpassTime
= null;
2316 * Get the user's current token.
2317 * @param bool $forceCreation Force the generation of a new token if the
2318 * user doesn't have one (default=true for backwards compatibility).
2319 * @return string Token
2321 public function getToken( $forceCreation = true ) {
2323 if ( !$this->mToken
&& $forceCreation ) {
2326 return $this->mToken
;
2330 * Set the random token (used for persistent authentication)
2331 * Called from loadDefaults() among other places.
2333 * @param string|bool $token If specified, set the token to this value
2335 public function setToken( $token = false ) {
2338 $this->mToken
= MWCryptRand
::generateHex( USER_TOKEN_LENGTH
);
2340 $this->mToken
= $token;
2345 * Set the password for a password reminder or new account email
2347 * @param string $str New password to set or null to set an invalid
2348 * password hash meaning that the user will not be able to use it
2349 * @param bool $throttle If true, reset the throttle timestamp to the present
2351 public function setNewpassword( $str, $throttle = true ) {
2354 if ( $str === null ) {
2355 $this->mNewpassword
= '';
2356 $this->mNewpassTime
= null;
2358 $this->mNewpassword
= self
::crypt( $str );
2360 $this->mNewpassTime
= wfTimestampNow();
2366 * Has password reminder email been sent within the last
2367 * $wgPasswordReminderResendTime hours?
2370 public function isPasswordReminderThrottled() {
2371 global $wgPasswordReminderResendTime;
2373 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2376 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2377 return time() < $expiry;
2381 * Get the user's e-mail address
2382 * @return string User's email address
2384 public function getEmail() {
2386 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
2387 return $this->mEmail
;
2391 * Get the timestamp of the user's e-mail authentication
2392 * @return string TS_MW timestamp
2394 public function getEmailAuthenticationTimestamp() {
2396 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2397 return $this->mEmailAuthenticated
;
2401 * Set the user's e-mail address
2402 * @param string $str New e-mail address
2404 public function setEmail( $str ) {
2406 if ( $str == $this->mEmail
) {
2409 $this->mEmail
= $str;
2410 $this->invalidateEmail();
2411 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
2415 * Set the user's e-mail address and a confirmation mail if needed.
2418 * @param string $str New e-mail address
2421 public function setEmailWithConfirmation( $str ) {
2422 global $wgEnableEmail, $wgEmailAuthentication;
2424 if ( !$wgEnableEmail ) {
2425 return Status
::newFatal( 'emaildisabled' );
2428 $oldaddr = $this->getEmail();
2429 if ( $str === $oldaddr ) {
2430 return Status
::newGood( true );
2433 $this->setEmail( $str );
2435 if ( $str !== '' && $wgEmailAuthentication ) {
2436 // Send a confirmation request to the new address if needed
2437 $type = $oldaddr != '' ?
'changed' : 'set';
2438 $result = $this->sendConfirmationMail( $type );
2439 if ( $result->isGood() ) {
2440 // Say the the caller that a confirmation mail has been sent
2441 $result->value
= 'eauth';
2444 $result = Status
::newGood( true );
2451 * Get the user's real name
2452 * @return string User's real name
2454 public function getRealName() {
2455 if ( !$this->isItemLoaded( 'realname' ) ) {
2459 return $this->mRealName
;
2463 * Set the user's real name
2464 * @param string $str New real name
2466 public function setRealName( $str ) {
2468 $this->mRealName
= $str;
2472 * Get the user's current setting for a given option.
2474 * @param string $oname The option to check
2475 * @param string $defaultOverride A default value returned if the option does not exist
2476 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2477 * @return string User's current value for the option
2478 * @see getBoolOption()
2479 * @see getIntOption()
2481 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2482 global $wgHiddenPrefs;
2483 $this->loadOptions();
2485 # We want 'disabled' preferences to always behave as the default value for
2486 # users, even if they have set the option explicitly in their settings (ie they
2487 # set it, and then it was disabled removing their ability to change it). But
2488 # we don't want to erase the preferences in the database in case the preference
2489 # is re-enabled again. So don't touch $mOptions, just override the returned value
2490 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2491 return self
::getDefaultOption( $oname );
2494 if ( array_key_exists( $oname, $this->mOptions
) ) {
2495 return $this->mOptions
[$oname];
2497 return $defaultOverride;
2502 * Get all user's options
2506 public function getOptions() {
2507 global $wgHiddenPrefs;
2508 $this->loadOptions();
2509 $options = $this->mOptions
;
2511 # We want 'disabled' preferences to always behave as the default value for
2512 # users, even if they have set the option explicitly in their settings (ie they
2513 # set it, and then it was disabled removing their ability to change it). But
2514 # we don't want to erase the preferences in the database in case the preference
2515 # is re-enabled again. So don't touch $mOptions, just override the returned value
2516 foreach ( $wgHiddenPrefs as $pref ) {
2517 $default = self
::getDefaultOption( $pref );
2518 if ( $default !== null ) {
2519 $options[$pref] = $default;
2527 * Get the user's current setting for a given option, as a boolean value.
2529 * @param string $oname The option to check
2530 * @return bool User's current value for the option
2533 public function getBoolOption( $oname ) {
2534 return (bool)$this->getOption( $oname );
2538 * Get the user's current setting for a given option, as an integer value.
2540 * @param string $oname The option to check
2541 * @param int $defaultOverride A default value returned if the option does not exist
2542 * @return int User's current value for the option
2545 public function getIntOption( $oname, $defaultOverride = 0 ) {
2546 $val = $this->getOption( $oname );
2548 $val = $defaultOverride;
2550 return intval( $val );
2554 * Set the given option for a user.
2556 * You need to call saveSettings() to actually write to the database.
2558 * @param string $oname The option to set
2559 * @param mixed $val New value to set
2561 public function setOption( $oname, $val ) {
2562 $this->loadOptions();
2564 // Explicitly NULL values should refer to defaults
2565 if ( is_null( $val ) ) {
2566 $val = self
::getDefaultOption( $oname );
2569 $this->mOptions
[$oname] = $val;
2573 * Get a token stored in the preferences (like the watchlist one),
2574 * resetting it if it's empty (and saving changes).
2576 * @param string $oname The option name to retrieve the token from
2577 * @return string|bool User's current value for the option, or false if this option is disabled.
2578 * @see resetTokenFromOption()
2581 public function getTokenFromOption( $oname ) {
2582 global $wgHiddenPrefs;
2583 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2587 $token = $this->getOption( $oname );
2589 $token = $this->resetTokenFromOption( $oname );
2590 $this->saveSettings();
2596 * Reset a token stored in the preferences (like the watchlist one).
2597 * *Does not* save user's preferences (similarly to setOption()).
2599 * @param string $oname The option name to reset the token in
2600 * @return string|bool New token value, or false if this option is disabled.
2601 * @see getTokenFromOption()
2604 public function resetTokenFromOption( $oname ) {
2605 global $wgHiddenPrefs;
2606 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2610 $token = MWCryptRand
::generateHex( 40 );
2611 $this->setOption( $oname, $token );
2616 * Return a list of the types of user options currently returned by
2617 * User::getOptionKinds().
2619 * Currently, the option kinds are:
2620 * - 'registered' - preferences which are registered in core MediaWiki or
2621 * by extensions using the UserGetDefaultOptions hook.
2622 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2623 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2624 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2625 * be used by user scripts.
2626 * - 'special' - "preferences" that are not accessible via User::getOptions
2627 * or User::setOptions.
2628 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2629 * These are usually legacy options, removed in newer versions.
2631 * The API (and possibly others) use this function to determine the possible
2632 * option types for validation purposes, so make sure to update this when a
2633 * new option kind is added.
2635 * @see User::getOptionKinds
2636 * @return array Option kinds
2638 public static function listOptionKinds() {
2641 'registered-multiselect',
2642 'registered-checkmatrix',
2650 * Return an associative array mapping preferences keys to the kind of a preference they're
2651 * used for. Different kinds are handled differently when setting or reading preferences.
2653 * See User::listOptionKinds for the list of valid option types that can be provided.
2655 * @see User::listOptionKinds
2656 * @param IContextSource $context
2657 * @param array $options Assoc. array with options keys to check as keys.
2658 * Defaults to $this->mOptions.
2659 * @return array the key => kind mapping data
2661 public function getOptionKinds( IContextSource
$context, $options = null ) {
2662 $this->loadOptions();
2663 if ( $options === null ) {
2664 $options = $this->mOptions
;
2667 $prefs = Preferences
::getPreferences( $this, $context );
2670 // Pull out the "special" options, so they don't get converted as
2671 // multiselect or checkmatrix.
2672 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2673 foreach ( $specialOptions as $name => $value ) {
2674 unset( $prefs[$name] );
2677 // Multiselect and checkmatrix options are stored in the database with
2678 // one key per option, each having a boolean value. Extract those keys.
2679 $multiselectOptions = array();
2680 foreach ( $prefs as $name => $info ) {
2681 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2682 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2683 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2684 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2686 foreach ( $opts as $value ) {
2687 $multiselectOptions["$prefix$value"] = true;
2690 unset( $prefs[$name] );
2693 $checkmatrixOptions = array();
2694 foreach ( $prefs as $name => $info ) {
2695 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2696 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2697 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2698 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2699 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2701 foreach ( $columns as $column ) {
2702 foreach ( $rows as $row ) {
2703 $checkmatrixOptions["$prefix-$column-$row"] = true;
2707 unset( $prefs[$name] );
2711 // $value is ignored
2712 foreach ( $options as $key => $value ) {
2713 if ( isset( $prefs[$key] ) ) {
2714 $mapping[$key] = 'registered';
2715 } elseif ( isset( $multiselectOptions[$key] ) ) {
2716 $mapping[$key] = 'registered-multiselect';
2717 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2718 $mapping[$key] = 'registered-checkmatrix';
2719 } elseif ( isset( $specialOptions[$key] ) ) {
2720 $mapping[$key] = 'special';
2721 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2722 $mapping[$key] = 'userjs';
2724 $mapping[$key] = 'unused';
2732 * Reset certain (or all) options to the site defaults
2734 * The optional parameter determines which kinds of preferences will be reset.
2735 * Supported values are everything that can be reported by getOptionKinds()
2736 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2738 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2739 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2740 * for backwards-compatibility.
2741 * @param IContextSource|null $context Context source used when $resetKinds
2742 * does not contain 'all', passed to getOptionKinds().
2743 * Defaults to RequestContext::getMain() when null.
2745 public function resetOptions(
2746 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2747 IContextSource
$context = null
2750 $defaultOptions = self
::getDefaultOptions();
2752 if ( !is_array( $resetKinds ) ) {
2753 $resetKinds = array( $resetKinds );
2756 if ( in_array( 'all', $resetKinds ) ) {
2757 $newOptions = $defaultOptions;
2759 if ( $context === null ) {
2760 $context = RequestContext
::getMain();
2763 $optionKinds = $this->getOptionKinds( $context );
2764 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2765 $newOptions = array();
2767 // Use default values for the options that should be deleted, and
2768 // copy old values for the ones that shouldn't.
2769 foreach ( $this->mOptions
as $key => $value ) {
2770 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2771 if ( array_key_exists( $key, $defaultOptions ) ) {
2772 $newOptions[$key] = $defaultOptions[$key];
2775 $newOptions[$key] = $value;
2780 $this->mOptions
= $newOptions;
2781 $this->mOptionsLoaded
= true;
2785 * Get the user's preferred date format.
2786 * @return string User's preferred date format
2788 public function getDatePreference() {
2789 // Important migration for old data rows
2790 if ( is_null( $this->mDatePreference
) ) {
2792 $value = $this->getOption( 'date' );
2793 $map = $wgLang->getDatePreferenceMigrationMap();
2794 if ( isset( $map[$value] ) ) {
2795 $value = $map[$value];
2797 $this->mDatePreference
= $value;
2799 return $this->mDatePreference
;
2803 * Determine based on the wiki configuration and the user's options,
2804 * whether this user must be over HTTPS no matter what.
2808 public function requiresHTTPS() {
2809 global $wgSecureLogin;
2810 if ( !$wgSecureLogin ) {
2813 $https = $this->getBoolOption( 'prefershttps' );
2814 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2816 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2823 * Get the user preferred stub threshold
2827 public function getStubThreshold() {
2828 global $wgMaxArticleSize; # Maximum article size, in Kb
2829 $threshold = $this->getIntOption( 'stubthreshold' );
2830 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2831 // If they have set an impossible value, disable the preference
2832 // so we can use the parser cache again.
2839 * Get the permissions this user has.
2840 * @return array Array of String permission names
2842 public function getRights() {
2843 if ( is_null( $this->mRights
) ) {
2844 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2845 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2846 // Force reindexation of rights when a hook has unset one of them
2847 $this->mRights
= array_values( array_unique( $this->mRights
) );
2849 return $this->mRights
;
2853 * Get the list of explicit group memberships this user has.
2854 * The implicit * and user groups are not included.
2855 * @return array Array of String internal group names
2857 public function getGroups() {
2859 $this->loadGroups();
2860 return $this->mGroups
;
2864 * Get the list of implicit group memberships this user has.
2865 * This includes all explicit groups, plus 'user' if logged in,
2866 * '*' for all accounts, and autopromoted groups
2867 * @param bool $recache Whether to avoid the cache
2868 * @return array Array of String internal group names
2870 public function getEffectiveGroups( $recache = false ) {
2871 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2872 wfProfileIn( __METHOD__
);
2873 $this->mEffectiveGroups
= array_unique( array_merge(
2874 $this->getGroups(), // explicit groups
2875 $this->getAutomaticGroups( $recache ) // implicit groups
2877 // Hook for additional groups
2878 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2879 // Force reindexation of groups when a hook has unset one of them
2880 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
2881 wfProfileOut( __METHOD__
);
2883 return $this->mEffectiveGroups
;
2887 * Get the list of implicit group memberships this user has.
2888 * This includes 'user' if logged in, '*' for all accounts,
2889 * and autopromoted groups
2890 * @param bool $recache Whether to avoid the cache
2891 * @return array Array of String internal group names
2893 public function getAutomaticGroups( $recache = false ) {
2894 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
2895 wfProfileIn( __METHOD__
);
2896 $this->mImplicitGroups
= array( '*' );
2897 if ( $this->getId() ) {
2898 $this->mImplicitGroups
[] = 'user';
2900 $this->mImplicitGroups
= array_unique( array_merge(
2901 $this->mImplicitGroups
,
2902 Autopromote
::getAutopromoteGroups( $this )
2906 // Assure data consistency with rights/groups,
2907 // as getEffectiveGroups() depends on this function
2908 $this->mEffectiveGroups
= null;
2910 wfProfileOut( __METHOD__
);
2912 return $this->mImplicitGroups
;
2916 * Returns the groups the user has belonged to.
2918 * The user may still belong to the returned groups. Compare with getGroups().
2920 * The function will not return groups the user had belonged to before MW 1.17
2922 * @return array Names of the groups the user has belonged to.
2924 public function getFormerGroups() {
2925 if ( is_null( $this->mFormerGroups
) ) {
2926 $dbr = wfGetDB( DB_MASTER
);
2927 $res = $dbr->select( 'user_former_groups',
2928 array( 'ufg_group' ),
2929 array( 'ufg_user' => $this->mId
),
2931 $this->mFormerGroups
= array();
2932 foreach ( $res as $row ) {
2933 $this->mFormerGroups
[] = $row->ufg_group
;
2936 return $this->mFormerGroups
;
2940 * Get the user's edit count.
2941 * @return int|null null for anonymous users
2943 public function getEditCount() {
2944 if ( !$this->getId() ) {
2948 if ( !isset( $this->mEditCount
) ) {
2949 /* Populate the count, if it has not been populated yet */
2950 wfProfileIn( __METHOD__
);
2951 $dbr = wfGetDB( DB_SLAVE
);
2952 // check if the user_editcount field has been initialized
2953 $count = $dbr->selectField(
2954 'user', 'user_editcount',
2955 array( 'user_id' => $this->mId
),
2959 if ( $count === null ) {
2960 // it has not been initialized. do so.
2961 $count = $this->initEditCount();
2963 $this->mEditCount
= $count;
2964 wfProfileOut( __METHOD__
);
2966 return (int)$this->mEditCount
;
2970 * Add the user to the given group.
2971 * This takes immediate effect.
2972 * @param string $group Name of the group to add
2974 public function addGroup( $group ) {
2975 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2976 $dbw = wfGetDB( DB_MASTER
);
2977 if ( $this->getId() ) {
2978 $dbw->insert( 'user_groups',
2980 'ug_user' => $this->getID(),
2981 'ug_group' => $group,
2984 array( 'IGNORE' ) );
2987 $this->loadGroups();
2988 $this->mGroups
[] = $group;
2989 // In case loadGroups was not called before, we now have the right twice.
2990 // Get rid of the duplicate.
2991 $this->mGroups
= array_unique( $this->mGroups
);
2993 // Refresh the groups caches, and clear the rights cache so it will be
2994 // refreshed on the next call to $this->getRights().
2995 $this->getEffectiveGroups( true );
2996 $this->mRights
= null;
2998 $this->invalidateCache();
3002 * Remove the user from the given group.
3003 * This takes immediate effect.
3004 * @param string $group Name of the group to remove
3006 public function removeGroup( $group ) {
3008 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3009 $dbw = wfGetDB( DB_MASTER
);
3010 $dbw->delete( 'user_groups',
3012 'ug_user' => $this->getID(),
3013 'ug_group' => $group,
3015 // Remember that the user was in this group
3016 $dbw->insert( 'user_former_groups',
3018 'ufg_user' => $this->getID(),
3019 'ufg_group' => $group,
3022 array( 'IGNORE' ) );
3024 $this->loadGroups();
3025 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3027 // Refresh the groups caches, and clear the rights cache so it will be
3028 // refreshed on the next call to $this->getRights().
3029 $this->getEffectiveGroups( true );
3030 $this->mRights
= null;
3032 $this->invalidateCache();
3036 * Get whether the user is logged in
3039 public function isLoggedIn() {
3040 return $this->getID() != 0;
3044 * Get whether the user is anonymous
3047 public function isAnon() {
3048 return !$this->isLoggedIn();
3052 * Check if user is allowed to access a feature / make an action
3054 * @internal param \String $varargs permissions to test
3055 * @return bool True if user is allowed to perform *any* of the given actions
3059 public function isAllowedAny( /*...*/ ) {
3060 $permissions = func_get_args();
3061 foreach ( $permissions as $permission ) {
3062 if ( $this->isAllowed( $permission ) ) {
3071 * @internal param $varargs string
3072 * @return bool True if the user is allowed to perform *all* of the given actions
3074 public function isAllowedAll( /*...*/ ) {
3075 $permissions = func_get_args();
3076 foreach ( $permissions as $permission ) {
3077 if ( !$this->isAllowed( $permission ) ) {
3085 * Internal mechanics of testing a permission
3086 * @param string $action
3089 public function isAllowed( $action = '' ) {
3090 if ( $action === '' ) {
3091 return true; // In the spirit of DWIM
3093 // Patrolling may not be enabled
3094 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3095 global $wgUseRCPatrol, $wgUseNPPatrol;
3096 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3100 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3101 // by misconfiguration: 0 == 'foo'
3102 return in_array( $action, $this->getRights(), true );
3106 * Check whether to enable recent changes patrol features for this user
3107 * @return bool True or false
3109 public function useRCPatrol() {
3110 global $wgUseRCPatrol;
3111 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3115 * Check whether to enable new pages patrol features for this user
3116 * @return bool True or false
3118 public function useNPPatrol() {
3119 global $wgUseRCPatrol, $wgUseNPPatrol;
3121 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3122 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3127 * Get the WebRequest object to use with this object
3129 * @return WebRequest
3131 public function getRequest() {
3132 if ( $this->mRequest
) {
3133 return $this->mRequest
;
3141 * Get the current skin, loading it if required
3142 * @return Skin The current skin
3143 * @todo FIXME: Need to check the old failback system [AV]
3144 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3146 public function getSkin() {
3147 wfDeprecated( __METHOD__
, '1.18' );
3148 return RequestContext
::getMain()->getSkin();
3152 * Get a WatchedItem for this user and $title.
3154 * @since 1.22 $checkRights parameter added
3155 * @param Title $title
3156 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3157 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3158 * @return WatchedItem
3160 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3161 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3163 if ( isset( $this->mWatchedItems
[$key] ) ) {
3164 return $this->mWatchedItems
[$key];
3167 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3168 $this->mWatchedItems
= array();
3171 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3172 return $this->mWatchedItems
[$key];
3176 * Check the watched status of an article.
3177 * @since 1.22 $checkRights parameter added
3178 * @param Title $title Title of the article to look at
3179 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3180 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3183 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3184 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3189 * @since 1.22 $checkRights parameter added
3190 * @param Title $title Title of the article to look at
3191 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3192 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3194 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3195 $this->getWatchedItem( $title, $checkRights )->addWatch();
3196 $this->invalidateCache();
3200 * Stop watching an article.
3201 * @since 1.22 $checkRights parameter added
3202 * @param Title $title Title of the article to look at
3203 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3204 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3206 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3207 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3208 $this->invalidateCache();
3212 * Clear the user's notification timestamp for the given title.
3213 * If e-notif e-mails are on, they will receive notification mails on
3214 * the next change of the page if it's watched etc.
3215 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3216 * @param Title $title Title of the article to look at
3217 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3219 public function clearNotification( &$title, $oldid = 0 ) {
3220 global $wgUseEnotif, $wgShowUpdatedMarker;
3222 // Do nothing if the database is locked to writes
3223 if ( wfReadOnly() ) {
3227 // Do nothing if not allowed to edit the watchlist
3228 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3232 // If we're working on user's talk page, we should update the talk page message indicator
3233 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3234 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3238 $nextid = $oldid ?
$title->getNextRevisionID( $oldid ) : null;
3240 if ( !$oldid ||
!$nextid ) {
3241 // If we're looking at the latest revision, we should definitely clear it
3242 $this->setNewtalk( false );
3244 // Otherwise we should update its revision, if it's present
3245 if ( $this->getNewtalk() ) {
3246 // Naturally the other one won't clear by itself
3247 $this->setNewtalk( false );
3248 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3253 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3257 if ( $this->isAnon() ) {
3258 // Nothing else to do...
3262 // Only update the timestamp if the page is being watched.
3263 // The query to find out if it is watched is cached both in memcached and per-invocation,
3264 // and when it does have to be executed, it can be on a slave
3265 // If this is the user's newtalk page, we always update the timestamp
3267 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3271 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3275 * Resets all of the given user's page-change notification timestamps.
3276 * If e-notif e-mails are on, they will receive notification mails on
3277 * the next change of any watched page.
3278 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3280 public function clearAllNotifications() {
3281 if ( wfReadOnly() ) {
3285 // Do nothing if not allowed to edit the watchlist
3286 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3290 global $wgUseEnotif, $wgShowUpdatedMarker;
3291 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3292 $this->setNewtalk( false );
3295 $id = $this->getId();
3297 $dbw = wfGetDB( DB_MASTER
);
3298 $dbw->update( 'watchlist',
3299 array( /* SET */ 'wl_notificationtimestamp' => null ),
3300 array( /* WHERE */ 'wl_user' => $id ),
3303 // We also need to clear here the "you have new message" notification for the own user_talk page;
3304 // it's cleared one page view later in WikiPage::doViewUpdates().
3309 * Set a cookie on the user's client. Wrapper for
3310 * WebResponse::setCookie
3311 * @param string $name Name of the cookie to set
3312 * @param string $value Value to set
3313 * @param int $exp Expiration time, as a UNIX time value;
3314 * if 0 or not specified, use the default $wgCookieExpiration
3315 * @param bool $secure
3316 * true: Force setting the secure attribute when setting the cookie
3317 * false: Force NOT setting the secure attribute when setting the cookie
3318 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3319 * @param array $params Array of options sent passed to WebResponse::setcookie()
3321 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3322 $params['secure'] = $secure;
3323 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3327 * Clear a cookie on the user's client
3328 * @param string $name Name of the cookie to clear
3329 * @param bool $secure
3330 * true: Force setting the secure attribute when setting the cookie
3331 * false: Force NOT setting the secure attribute when setting the cookie
3332 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3333 * @param array $params Array of options sent passed to WebResponse::setcookie()
3335 protected function clearCookie( $name, $secure = null, $params = array() ) {
3336 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3340 * Set the default cookies for this session on the user's client.
3342 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3344 * @param bool $secure Whether to force secure/insecure cookies or use default
3345 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3347 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3348 if ( $request === null ) {
3349 $request = $this->getRequest();
3353 if ( 0 == $this->mId
) {
3356 if ( !$this->mToken
) {
3357 // When token is empty or NULL generate a new one and then save it to the database
3358 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3359 // Simply by setting every cell in the user_token column to NULL and letting them be
3360 // regenerated as users log back into the wiki.
3362 $this->saveSettings();
3365 'wsUserID' => $this->mId
,
3366 'wsToken' => $this->mToken
,
3367 'wsUserName' => $this->getName()
3370 'UserID' => $this->mId
,
3371 'UserName' => $this->getName(),
3373 if ( $rememberMe ) {
3374 $cookies['Token'] = $this->mToken
;
3376 $cookies['Token'] = false;
3379 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3381 foreach ( $session as $name => $value ) {
3382 $request->setSessionData( $name, $value );
3384 foreach ( $cookies as $name => $value ) {
3385 if ( $value === false ) {
3386 $this->clearCookie( $name );
3388 $this->setCookie( $name, $value, 0, $secure );
3393 * If wpStickHTTPS was selected, also set an insecure cookie that
3394 * will cause the site to redirect the user to HTTPS, if they access
3395 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3396 * as the one set by centralauth (bug 53538). Also set it to session, or
3397 * standard time setting, based on if rememberme was set.
3399 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3403 $rememberMe ?
0 : null,
3405 array( 'prefix' => '' ) // no prefix
3411 * Log this user out.
3413 public function logout() {
3414 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3420 * Clear the user's cookies and session, and reset the instance cache.
3423 public function doLogout() {
3424 $this->clearInstanceCache( 'defaults' );
3426 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3428 $this->clearCookie( 'UserID' );
3429 $this->clearCookie( 'Token' );
3430 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3432 // Remember when user logged out, to prevent seeing cached pages
3433 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3437 * Save this user's settings into the database.
3438 * @todo Only rarely do all these fields need to be set!
3440 public function saveSettings() {
3444 if ( wfReadOnly() ) {
3447 if ( 0 == $this->mId
) {
3451 $this->mTouched
= self
::newTouchedTimestamp();
3452 if ( !$wgAuth->allowSetLocalPassword() ) {
3453 $this->mPassword
= '';
3456 $dbw = wfGetDB( DB_MASTER
);
3457 $dbw->update( 'user',
3459 'user_name' => $this->mName
,
3460 'user_password' => $this->mPassword
,
3461 'user_newpassword' => $this->mNewpassword
,
3462 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3463 'user_real_name' => $this->mRealName
,
3464 'user_email' => $this->mEmail
,
3465 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3466 'user_touched' => $dbw->timestamp( $this->mTouched
),
3467 'user_token' => strval( $this->mToken
),
3468 'user_email_token' => $this->mEmailToken
,
3469 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3470 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires
),
3471 ), array( /* WHERE */
3472 'user_id' => $this->mId
3476 $this->saveOptions();
3478 wfRunHooks( 'UserSaveSettings', array( $this ) );
3479 $this->clearSharedCache();
3480 $this->getUserPage()->invalidateCache();
3484 * If only this user's username is known, and it exists, return the user ID.
3487 public function idForName() {
3488 $s = trim( $this->getName() );
3493 $dbr = wfGetDB( DB_SLAVE
);
3494 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
3495 if ( $id === false ) {
3502 * Add a user to the database, return the user object
3504 * @param string $name Username to add
3505 * @param array $params Array of Strings Non-default parameters to save to
3506 * the database as user_* fields:
3507 * - password: The user's password hash. Password logins will be disabled
3508 * if this is omitted.
3509 * - newpassword: Hash for a temporary password that has been mailed to
3511 * - email: The user's email address.
3512 * - email_authenticated: The email authentication timestamp.
3513 * - real_name: The user's real name.
3514 * - options: An associative array of non-default options.
3515 * - token: Random authentication token. Do not set.
3516 * - registration: Registration timestamp. Do not set.
3518 * @return User|null User object, or null if the username already exists.
3520 public static function createNew( $name, $params = array() ) {
3523 $user->setToken(); // init token
3524 if ( isset( $params['options'] ) ) {
3525 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3526 unset( $params['options'] );
3528 $dbw = wfGetDB( DB_MASTER
);
3529 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3532 'user_id' => $seqVal,
3533 'user_name' => $name,
3534 'user_password' => $user->mPassword
,
3535 'user_newpassword' => $user->mNewpassword
,
3536 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3537 'user_email' => $user->mEmail
,
3538 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3539 'user_real_name' => $user->mRealName
,
3540 'user_token' => strval( $user->mToken
),
3541 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3542 'user_editcount' => 0,
3543 'user_touched' => $dbw->timestamp( self
::newTouchedTimestamp() ),
3545 foreach ( $params as $name => $value ) {
3546 $fields["user_$name"] = $value;
3548 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3549 if ( $dbw->affectedRows() ) {
3550 $newUser = User
::newFromId( $dbw->insertId() );
3558 * Add this existing user object to the database. If the user already
3559 * exists, a fatal status object is returned, and the user object is
3560 * initialised with the data from the database.
3562 * Previously, this function generated a DB error due to a key conflict
3563 * if the user already existed. Many extension callers use this function
3564 * in code along the lines of:
3566 * $user = User::newFromName( $name );
3567 * if ( !$user->isLoggedIn() ) {
3568 * $user->addToDatabase();
3570 * // do something with $user...
3572 * However, this was vulnerable to a race condition (bug 16020). By
3573 * initialising the user object if the user exists, we aim to support this
3574 * calling sequence as far as possible.
3576 * Note that if the user exists, this function will acquire a write lock,
3577 * so it is still advisable to make the call conditional on isLoggedIn(),
3578 * and to commit the transaction after calling.
3580 * @throws MWException
3583 public function addToDatabase() {
3585 if ( !$this->mToken
) {
3586 $this->setToken(); // init token
3589 $this->mTouched
= self
::newTouchedTimestamp();
3591 $dbw = wfGetDB( DB_MASTER
);
3592 $inWrite = $dbw->writesOrCallbacksPending();
3593 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3594 $dbw->insert( 'user',
3596 'user_id' => $seqVal,
3597 'user_name' => $this->mName
,
3598 'user_password' => $this->mPassword
,
3599 'user_newpassword' => $this->mNewpassword
,
3600 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3601 'user_email' => $this->mEmail
,
3602 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3603 'user_real_name' => $this->mRealName
,
3604 'user_token' => strval( $this->mToken
),
3605 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3606 'user_editcount' => 0,
3607 'user_touched' => $dbw->timestamp( $this->mTouched
),
3611 if ( !$dbw->affectedRows() ) {
3612 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3613 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3615 // Can't commit due to pending writes that may need atomicity.
3616 // This may cause some lock contention unlike the case below.
3617 $options = array( 'LOCK IN SHARE MODE' );
3618 $flags = self
::READ_LOCKING
;
3620 // Often, this case happens early in views before any writes when
3621 // using CentralAuth. It's should be OK to commit and break the snapshot.
3622 $dbw->commit( __METHOD__
, 'flush' );
3626 $this->mId
= $dbw->selectField( 'user', 'user_id',
3627 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3630 if ( $this->loadFromDatabase( $flags ) ) {
3635 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3636 "to insert user '{$this->mName}' row, but it was not present in select!" );
3638 return Status
::newFatal( 'userexists' );
3640 $this->mId
= $dbw->insertId();
3642 // Clear instance cache other than user table data, which is already accurate
3643 $this->clearInstanceCache();
3645 $this->saveOptions();
3646 return Status
::newGood();
3650 * If this user is logged-in and blocked,
3651 * block any IP address they've successfully logged in from.
3652 * @return bool A block was spread
3654 public function spreadAnyEditBlock() {
3655 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3656 return $this->spreadBlock();
3662 * If this (non-anonymous) user is blocked,
3663 * block the IP address they've successfully logged in from.
3664 * @return bool A block was spread
3666 protected function spreadBlock() {
3667 wfDebug( __METHOD__
. "()\n" );
3669 if ( $this->mId
== 0 ) {
3673 $userblock = Block
::newFromTarget( $this->getName() );
3674 if ( !$userblock ) {
3678 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3682 * Get whether the user is explicitly blocked from account creation.
3683 * @return bool|Block
3685 public function isBlockedFromCreateAccount() {
3686 $this->getBlockedStatus();
3687 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3688 return $this->mBlock
;
3691 # bug 13611: if the IP address the user is trying to create an account from is
3692 # blocked with createaccount disabled, prevent new account creation there even
3693 # when the user is logged in
3694 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3695 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3697 return $this->mBlockedFromCreateAccount
instanceof Block
3698 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3699 ?
$this->mBlockedFromCreateAccount
3704 * Get whether the user is blocked from using Special:Emailuser.
3707 public function isBlockedFromEmailuser() {
3708 $this->getBlockedStatus();
3709 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3713 * Get whether the user is allowed to create an account.
3716 public function isAllowedToCreateAccount() {
3717 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3721 * Get this user's personal page title.
3723 * @return Title User's personal page title
3725 public function getUserPage() {
3726 return Title
::makeTitle( NS_USER
, $this->getName() );
3730 * Get this user's talk page title.
3732 * @return Title User's talk page title
3734 public function getTalkPage() {
3735 $title = $this->getUserPage();
3736 return $title->getTalkPage();
3740 * Determine whether the user is a newbie. Newbies are either
3741 * anonymous IPs, or the most recently created accounts.
3744 public function isNewbie() {
3745 return !$this->isAllowed( 'autoconfirmed' );
3749 * Check to see if the given clear-text password is one of the accepted passwords
3750 * @param string $password user password.
3751 * @return bool True if the given password is correct, otherwise False.
3753 public function checkPassword( $password ) {
3754 global $wgAuth, $wgLegacyEncoding;
3757 // Certain authentication plugins do NOT want to save
3758 // domain passwords in a mysql database, so we should
3759 // check this (in case $wgAuth->strict() is false).
3761 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3763 } elseif ( $wgAuth->strict() ) {
3764 // Auth plugin doesn't allow local authentication
3766 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3767 // Auth plugin doesn't allow local authentication for this user name
3770 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
3772 } elseif ( $wgLegacyEncoding ) {
3773 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3774 // Check for this with iconv
3775 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3776 if ( $cp1252Password != $password
3777 && self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
)
3786 * Check if the given clear-text password matches the temporary password
3787 * sent by e-mail for password reset operations.
3789 * @param string $plaintext
3791 * @return bool True if matches, false otherwise
3793 public function checkTemporaryPassword( $plaintext ) {
3794 global $wgNewPasswordExpiry;
3797 if ( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
3798 if ( is_null( $this->mNewpassTime
) ) {
3801 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3802 return ( time() < $expiry );
3809 * Alias for getEditToken.
3810 * @deprecated since 1.19, use getEditToken instead.
3812 * @param string|array $salt of Strings Optional function-specific data for hashing
3813 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3814 * @return string The new edit token
3816 public function editToken( $salt = '', $request = null ) {
3817 wfDeprecated( __METHOD__
, '1.19' );
3818 return $this->getEditToken( $salt, $request );
3822 * Initialize (if necessary) and return a session token value
3823 * which can be used in edit forms to show that the user's
3824 * login credentials aren't being hijacked with a foreign form
3829 * @param string|array $salt of Strings Optional function-specific data for hashing
3830 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3831 * @return string The new edit token
3833 public function getEditToken( $salt = '', $request = null ) {
3834 if ( $request == null ) {
3835 $request = $this->getRequest();
3838 if ( $this->isAnon() ) {
3839 return EDIT_TOKEN_SUFFIX
;
3841 $token = $request->getSessionData( 'wsEditToken' );
3842 if ( $token === null ) {
3843 $token = MWCryptRand
::generateHex( 32 );
3844 $request->setSessionData( 'wsEditToken', $token );
3846 if ( is_array( $salt ) ) {
3847 $salt = implode( '|', $salt );
3849 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
3854 * Generate a looking random token for various uses.
3856 * @return string The new random token
3857 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
3858 * wfRandomString for pseudo-randomness.
3860 public static function generateToken() {
3861 return MWCryptRand
::generateHex( 32 );
3865 * Check given value against the token value stored in the session.
3866 * A match should confirm that the form was submitted from the
3867 * user's own login session, not a form submission from a third-party
3870 * @param string $val Input value to compare
3871 * @param string $salt Optional function-specific data for hashing
3872 * @param WebRequest|null $request Object to use or null to use $wgRequest
3873 * @return bool Whether the token matches
3875 public function matchEditToken( $val, $salt = '', $request = null ) {
3876 $sessionToken = $this->getEditToken( $salt, $request );
3877 if ( $val != $sessionToken ) {
3878 wfDebug( "User::matchEditToken: broken session data\n" );
3881 return $val == $sessionToken;
3885 * Check given value against the token value stored in the session,
3886 * ignoring the suffix.
3888 * @param string $val Input value to compare
3889 * @param string $salt Optional function-specific data for hashing
3890 * @param WebRequest|null $request object to use or null to use $wgRequest
3891 * @return bool Whether the token matches
3893 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3894 $sessionToken = $this->getEditToken( $salt, $request );
3895 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3899 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3900 * mail to the user's given address.
3902 * @param string $type Message to send, either "created", "changed" or "set"
3905 public function sendConfirmationMail( $type = 'created' ) {
3907 $expiration = null; // gets passed-by-ref and defined in next line.
3908 $token = $this->confirmationToken( $expiration );
3909 $url = $this->confirmationTokenUrl( $token );
3910 $invalidateURL = $this->invalidationTokenUrl( $token );
3911 $this->saveSettings();
3913 if ( $type == 'created' ||
$type === false ) {
3914 $message = 'confirmemail_body';
3915 } elseif ( $type === true ) {
3916 $message = 'confirmemail_body_changed';
3918 // Messages: confirmemail_body_changed, confirmemail_body_set
3919 $message = 'confirmemail_body_' . $type;
3922 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3923 wfMessage( $message,
3924 $this->getRequest()->getIP(),
3927 $wgLang->timeanddate( $expiration, false ),
3929 $wgLang->date( $expiration, false ),
3930 $wgLang->time( $expiration, false ) )->text() );
3934 * Send an e-mail to this user's account. Does not check for
3935 * confirmed status or validity.
3937 * @param string $subject Message subject
3938 * @param string $body Message body
3939 * @param string $from Optional From address; if unspecified, default
3940 * $wgPasswordSender will be used.
3941 * @param string $replyto Reply-To address
3944 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3945 if ( is_null( $from ) ) {
3946 global $wgPasswordSender;
3947 $sender = new MailAddress( $wgPasswordSender,
3948 wfMessage( 'emailsender' )->inContentLanguage()->text() );
3950 $sender = new MailAddress( $from );
3953 $to = new MailAddress( $this );
3954 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
3958 * Generate, store, and return a new e-mail confirmation code.
3959 * A hash (unsalted, since it's used as a key) is stored.
3961 * @note Call saveSettings() after calling this function to commit
3962 * this change to the database.
3964 * @param string &$expiration Accepts the expiration time
3965 * @return string New token
3967 protected function confirmationToken( &$expiration ) {
3968 global $wgUserEmailConfirmationTokenExpiry;
3970 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
3971 $expiration = wfTimestamp( TS_MW
, $expires );
3973 $token = MWCryptRand
::generateHex( 32 );
3974 $hash = md5( $token );
3975 $this->mEmailToken
= $hash;
3976 $this->mEmailTokenExpires
= $expiration;
3981 * Return a URL the user can use to confirm their email address.
3982 * @param string $token Accepts the email confirmation token
3983 * @return string New token URL
3985 protected function confirmationTokenUrl( $token ) {
3986 return $this->getTokenUrl( 'ConfirmEmail', $token );
3990 * Return a URL the user can use to invalidate their email address.
3991 * @param string $token Accepts the email confirmation token
3992 * @return string New token URL
3994 protected function invalidationTokenUrl( $token ) {
3995 return $this->getTokenUrl( 'InvalidateEmail', $token );
3999 * Internal function to format the e-mail validation/invalidation URLs.
4000 * This uses a quickie hack to use the
4001 * hardcoded English names of the Special: pages, for ASCII safety.
4003 * @note Since these URLs get dropped directly into emails, using the
4004 * short English names avoids insanely long URL-encoded links, which
4005 * also sometimes can get corrupted in some browsers/mailers
4006 * (bug 6957 with Gmail and Internet Explorer).
4008 * @param string $page Special page
4009 * @param string $token Token
4010 * @return string Formatted URL
4012 protected function getTokenUrl( $page, $token ) {
4013 // Hack to bypass localization of 'Special:'
4014 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4015 return $title->getCanonicalURL();
4019 * Mark the e-mail address confirmed.
4021 * @note Call saveSettings() after calling this function to commit the change.
4025 public function confirmEmail() {
4026 // Check if it's already confirmed, so we don't touch the database
4027 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4028 if ( !$this->isEmailConfirmed() ) {
4029 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4030 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
4036 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4037 * address if it was already confirmed.
4039 * @note Call saveSettings() after calling this function to commit the change.
4040 * @return bool Returns true
4042 public function invalidateEmail() {
4044 $this->mEmailToken
= null;
4045 $this->mEmailTokenExpires
= null;
4046 $this->setEmailAuthenticationTimestamp( null );
4047 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
4052 * Set the e-mail authentication timestamp.
4053 * @param string $timestamp TS_MW timestamp
4055 public function setEmailAuthenticationTimestamp( $timestamp ) {
4057 $this->mEmailAuthenticated
= $timestamp;
4058 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4062 * Is this user allowed to send e-mails within limits of current
4063 * site configuration?
4066 public function canSendEmail() {
4067 global $wgEnableEmail, $wgEnableUserEmail;
4068 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4071 $canSend = $this->isEmailConfirmed();
4072 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4077 * Is this user allowed to receive e-mails within limits of current
4078 * site configuration?
4081 public function canReceiveEmail() {
4082 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4086 * Is this user's e-mail address valid-looking and confirmed within
4087 * limits of the current site configuration?
4089 * @note If $wgEmailAuthentication is on, this may require the user to have
4090 * confirmed their address by returning a code or using a password
4091 * sent to the address from the wiki.
4095 public function isEmailConfirmed() {
4096 global $wgEmailAuthentication;
4099 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4100 if ( $this->isAnon() ) {
4103 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4106 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4116 * Check whether there is an outstanding request for e-mail confirmation.
4119 public function isEmailConfirmationPending() {
4120 global $wgEmailAuthentication;
4121 return $wgEmailAuthentication &&
4122 !$this->isEmailConfirmed() &&
4123 $this->mEmailToken
&&
4124 $this->mEmailTokenExpires
> wfTimestamp();
4128 * Get the timestamp of account creation.
4130 * @return string|bool|null Timestamp of account creation, false for
4131 * non-existent/anonymous user accounts, or null if existing account
4132 * but information is not in database.
4134 public function getRegistration() {
4135 if ( $this->isAnon() ) {
4139 return $this->mRegistration
;
4143 * Get the timestamp of the first edit
4145 * @return string|bool Timestamp of first edit, or false for
4146 * non-existent/anonymous user accounts.
4148 public function getFirstEditTimestamp() {
4149 if ( $this->getId() == 0 ) {
4150 return false; // anons
4152 $dbr = wfGetDB( DB_SLAVE
);
4153 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4154 array( 'rev_user' => $this->getId() ),
4156 array( 'ORDER BY' => 'rev_timestamp ASC' )
4159 return false; // no edits
4161 return wfTimestamp( TS_MW
, $time );
4165 * Get the permissions associated with a given list of groups
4167 * @param array $groups Array of Strings List of internal group names
4168 * @return array Array of Strings List of permission key names for given groups combined
4170 public static function getGroupPermissions( $groups ) {
4171 global $wgGroupPermissions, $wgRevokePermissions;
4173 // grant every granted permission first
4174 foreach ( $groups as $group ) {
4175 if ( isset( $wgGroupPermissions[$group] ) ) {
4176 $rights = array_merge( $rights,
4177 // array_filter removes empty items
4178 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4181 // now revoke the revoked permissions
4182 foreach ( $groups as $group ) {
4183 if ( isset( $wgRevokePermissions[$group] ) ) {
4184 $rights = array_diff( $rights,
4185 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4188 return array_unique( $rights );
4192 * Get all the groups who have a given permission
4194 * @param string $role Role to check
4195 * @return array Array of Strings List of internal group names with the given permission
4197 public static function getGroupsWithPermission( $role ) {
4198 global $wgGroupPermissions;
4199 $allowedGroups = array();
4200 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4201 if ( self
::groupHasPermission( $group, $role ) ) {
4202 $allowedGroups[] = $group;
4205 return $allowedGroups;
4209 * Check, if the given group has the given permission
4211 * If you're wanting to check whether all users have a permission, use
4212 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4216 * @param string $group Group to check
4217 * @param string $role Role to check
4220 public static function groupHasPermission( $group, $role ) {
4221 global $wgGroupPermissions, $wgRevokePermissions;
4222 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4223 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4227 * Check if all users have the given permission
4230 * @param string $right Right to check
4233 public static function isEveryoneAllowed( $right ) {
4234 global $wgGroupPermissions, $wgRevokePermissions;
4235 static $cache = array();
4237 // Use the cached results, except in unit tests which rely on
4238 // being able change the permission mid-request
4239 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4240 return $cache[$right];
4243 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4244 $cache[$right] = false;
4248 // If it's revoked anywhere, then everyone doesn't have it
4249 foreach ( $wgRevokePermissions as $rights ) {
4250 if ( isset( $rights[$right] ) && $rights[$right] ) {
4251 $cache[$right] = false;
4256 // Allow extensions (e.g. OAuth) to say false
4257 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4258 $cache[$right] = false;
4262 $cache[$right] = true;
4267 * Get the localized descriptive name for a group, if it exists
4269 * @param string $group Internal group name
4270 * @return string Localized descriptive group name
4272 public static function getGroupName( $group ) {
4273 $msg = wfMessage( "group-$group" );
4274 return $msg->isBlank() ?
$group : $msg->text();
4278 * Get the localized descriptive name for a member of a group, if it exists
4280 * @param string $group Internal group name
4281 * @param string $username Username for gender (since 1.19)
4282 * @return string Localized name for group member
4284 public static function getGroupMember( $group, $username = '#' ) {
4285 $msg = wfMessage( "group-$group-member", $username );
4286 return $msg->isBlank() ?
$group : $msg->text();
4290 * Return the set of defined explicit groups.
4291 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4292 * are not included, as they are defined automatically, not in the database.
4293 * @return array Array of internal group names
4295 public static function getAllGroups() {
4296 global $wgGroupPermissions, $wgRevokePermissions;
4298 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4299 self
::getImplicitGroups()
4304 * Get a list of all available permissions.
4305 * @return array Array of permission names
4307 public static function getAllRights() {
4308 if ( self
::$mAllRights === false ) {
4309 global $wgAvailableRights;
4310 if ( count( $wgAvailableRights ) ) {
4311 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4313 self
::$mAllRights = self
::$mCoreRights;
4315 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
4317 return self
::$mAllRights;
4321 * Get a list of implicit groups
4322 * @return array Array of Strings Array of internal group names
4324 public static function getImplicitGroups() {
4325 global $wgImplicitGroups;
4327 $groups = $wgImplicitGroups;
4328 # Deprecated, use $wgImplictGroups instead
4329 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) );
4335 * Get the title of a page describing a particular group
4337 * @param string $group Internal group name
4338 * @return Title|bool Title of the page if it exists, false otherwise
4340 public static function getGroupPage( $group ) {
4341 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4342 if ( $msg->exists() ) {
4343 $title = Title
::newFromText( $msg->text() );
4344 if ( is_object( $title ) ) {
4352 * Create a link to the group in HTML, if available;
4353 * else return the group name.
4355 * @param string $group Internal name of the group
4356 * @param string $text The text of the link
4357 * @return string HTML link to the group
4359 public static function makeGroupLinkHTML( $group, $text = '' ) {
4360 if ( $text == '' ) {
4361 $text = self
::getGroupName( $group );
4363 $title = self
::getGroupPage( $group );
4365 return Linker
::link( $title, htmlspecialchars( $text ) );
4372 * Create a link to the group in Wikitext, if available;
4373 * else return the group name.
4375 * @param string $group Internal name of the group
4376 * @param string $text The text of the link
4377 * @return string Wikilink to the group
4379 public static function makeGroupLinkWiki( $group, $text = '' ) {
4380 if ( $text == '' ) {
4381 $text = self
::getGroupName( $group );
4383 $title = self
::getGroupPage( $group );
4385 $page = $title->getPrefixedText();
4386 return "[[$page|$text]]";
4393 * Returns an array of the groups that a particular group can add/remove.
4395 * @param string $group The group to check for whether it can add/remove
4396 * @return array array( 'add' => array( addablegroups ),
4397 * 'remove' => array( removablegroups ),
4398 * 'add-self' => array( addablegroups to self),
4399 * 'remove-self' => array( removable groups from self) )
4401 public static function changeableByGroup( $group ) {
4402 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4406 'remove' => array(),
4407 'add-self' => array(),
4408 'remove-self' => array()
4411 if ( empty( $wgAddGroups[$group] ) ) {
4412 // Don't add anything to $groups
4413 } elseif ( $wgAddGroups[$group] === true ) {
4414 // You get everything
4415 $groups['add'] = self
::getAllGroups();
4416 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4417 $groups['add'] = $wgAddGroups[$group];
4420 // Same thing for remove
4421 if ( empty( $wgRemoveGroups[$group] ) ) {
4422 } elseif ( $wgRemoveGroups[$group] === true ) {
4423 $groups['remove'] = self
::getAllGroups();
4424 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4425 $groups['remove'] = $wgRemoveGroups[$group];
4428 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4429 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4430 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4431 if ( is_int( $key ) ) {
4432 $wgGroupsAddToSelf['user'][] = $value;
4437 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4438 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4439 if ( is_int( $key ) ) {
4440 $wgGroupsRemoveFromSelf['user'][] = $value;
4445 // Now figure out what groups the user can add to him/herself
4446 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4447 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4448 // No idea WHY this would be used, but it's there
4449 $groups['add-self'] = User
::getAllGroups();
4450 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4451 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4454 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4455 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4456 $groups['remove-self'] = User
::getAllGroups();
4457 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4458 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4465 * Returns an array of groups that this user can add and remove
4466 * @return array array( 'add' => array( addablegroups ),
4467 * 'remove' => array( removablegroups ),
4468 * 'add-self' => array( addablegroups to self),
4469 * 'remove-self' => array( removable groups from self) )
4471 public function changeableGroups() {
4472 if ( $this->isAllowed( 'userrights' ) ) {
4473 // This group gives the right to modify everything (reverse-
4474 // compatibility with old "userrights lets you change
4476 // Using array_merge to make the groups reindexed
4477 $all = array_merge( User
::getAllGroups() );
4481 'add-self' => array(),
4482 'remove-self' => array()
4486 // Okay, it's not so simple, we will have to go through the arrays
4489 'remove' => array(),
4490 'add-self' => array(),
4491 'remove-self' => array()
4493 $addergroups = $this->getEffectiveGroups();
4495 foreach ( $addergroups as $addergroup ) {
4496 $groups = array_merge_recursive(
4497 $groups, $this->changeableByGroup( $addergroup )
4499 $groups['add'] = array_unique( $groups['add'] );
4500 $groups['remove'] = array_unique( $groups['remove'] );
4501 $groups['add-self'] = array_unique( $groups['add-self'] );
4502 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4508 * Increment the user's edit-count field.
4509 * Will have no effect for anonymous users.
4511 public function incEditCount() {
4512 if ( !$this->isAnon() ) {
4513 $dbw = wfGetDB( DB_MASTER
);
4516 array( 'user_editcount=user_editcount+1' ),
4517 array( 'user_id' => $this->getId() ),
4521 // Lazy initialization check...
4522 if ( $dbw->affectedRows() == 0 ) {
4523 // Now here's a goddamn hack...
4524 $dbr = wfGetDB( DB_SLAVE
);
4525 if ( $dbr !== $dbw ) {
4526 // If we actually have a slave server, the count is
4527 // at least one behind because the current transaction
4528 // has not been committed and replicated.
4529 $this->initEditCount( 1 );
4531 // But if DB_SLAVE is selecting the master, then the
4532 // count we just read includes the revision that was
4533 // just added in the working transaction.
4534 $this->initEditCount();
4538 // edit count in user cache too
4539 $this->invalidateCache();
4543 * Initialize user_editcount from data out of the revision table
4545 * @param int $add Edits to add to the count from the revision table
4546 * @return int Number of edits
4548 protected function initEditCount( $add = 0 ) {
4549 // Pull from a slave to be less cruel to servers
4550 // Accuracy isn't the point anyway here
4551 $dbr = wfGetDB( DB_SLAVE
);
4552 $count = (int)$dbr->selectField(
4555 array( 'rev_user' => $this->getId() ),
4558 $count = $count +
$add;
4560 $dbw = wfGetDB( DB_MASTER
);
4563 array( 'user_editcount' => $count ),
4564 array( 'user_id' => $this->getId() ),
4572 * Get the description of a given right
4574 * @param string $right Right to query
4575 * @return string Localized description of the right
4577 public static function getRightDescription( $right ) {
4578 $key = "right-$right";
4579 $msg = wfMessage( $key );
4580 return $msg->isBlank() ?
$right : $msg->text();
4584 * Make an old-style password hash
4586 * @param string $password Plain-text password
4587 * @param string $userId User ID
4588 * @return string Password hash
4590 public static function oldCrypt( $password, $userId ) {
4591 global $wgPasswordSalt;
4592 if ( $wgPasswordSalt ) {
4593 return md5( $userId . '-' . md5( $password ) );
4595 return md5( $password );
4600 * Make a new-style password hash
4602 * @param string $password Plain-text password
4603 * @param bool|string $salt Optional salt, may be random or the user ID.
4604 * If unspecified or false, will generate one automatically
4605 * @return string Password hash
4607 public static function crypt( $password, $salt = false ) {
4608 global $wgPasswordSalt;
4611 if ( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4615 if ( $wgPasswordSalt ) {
4616 if ( $salt === false ) {
4617 $salt = MWCryptRand
::generateHex( 8 );
4619 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4621 return ':A:' . md5( $password );
4626 * Compare a password hash with a plain-text password. Requires the user
4627 * ID if there's a chance that the hash is an old-style hash.
4629 * @param string $hash Password hash
4630 * @param string $password Plain-text password to compare
4631 * @param string|bool $userId User ID for old-style password salt
4635 public static function comparePasswords( $hash, $password, $userId = false ) {
4636 $type = substr( $hash, 0, 3 );
4639 if ( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4643 if ( $type == ':A:' ) {
4645 return md5( $password ) === substr( $hash, 3 );
4646 } elseif ( $type == ':B:' ) {
4648 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4649 return md5( $salt . '-' . md5( $password ) ) === $realHash;
4652 return self
::oldCrypt( $password, $userId ) === $hash;
4657 * Add a newuser log entry for this user.
4658 * Before 1.19 the return value was always true.
4660 * @param string|bool $action Account creation type.
4661 * - String, one of the following values:
4662 * - 'create' for an anonymous user creating an account for himself.
4663 * This will force the action's performer to be the created user itself,
4664 * no matter the value of $wgUser
4665 * - 'create2' for a logged in user creating an account for someone else
4666 * - 'byemail' when the created user will receive its password by e-mail
4667 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4668 * - Boolean means whether the account was created by e-mail (deprecated):
4669 * - true will be converted to 'byemail'
4670 * - false will be converted to 'create' if this object is the same as
4671 * $wgUser and to 'create2' otherwise
4673 * @param string $reason User supplied reason
4675 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4677 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4678 global $wgUser, $wgNewUserLog;
4679 if ( empty( $wgNewUserLog ) ) {
4680 return true; // disabled
4683 if ( $action === true ) {
4684 $action = 'byemail';
4685 } elseif ( $action === false ) {
4686 if ( $this->getName() == $wgUser->getName() ) {
4689 $action = 'create2';
4693 if ( $action === 'create' ||
$action === 'autocreate' ) {
4696 $performer = $wgUser;
4699 $logEntry = new ManualLogEntry( 'newusers', $action );
4700 $logEntry->setPerformer( $performer );
4701 $logEntry->setTarget( $this->getUserPage() );
4702 $logEntry->setComment( $reason );
4703 $logEntry->setParameters( array(
4704 '4::userid' => $this->getId(),
4706 $logid = $logEntry->insert();
4708 if ( $action !== 'autocreate' ) {
4709 $logEntry->publish( $logid );
4716 * Add an autocreate newuser log entry for this user
4717 * Used by things like CentralAuth and perhaps other authplugins.
4718 * Consider calling addNewUserLogEntry() directly instead.
4722 public function addNewUserLogEntryAutoCreate() {
4723 $this->addNewUserLogEntry( 'autocreate' );
4729 * Load the user options either from cache, the database or an array
4731 * @param array $data Rows for the current user out of the user_properties table
4733 protected function loadOptions( $data = null ) {
4738 if ( $this->mOptionsLoaded
) {
4742 $this->mOptions
= self
::getDefaultOptions();
4744 if ( !$this->getId() ) {
4745 // For unlogged-in users, load language/variant options from request.
4746 // There's no need to do it for logged-in users: they can set preferences,
4747 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4748 // so don't override user's choice (especially when the user chooses site default).
4749 $variant = $wgContLang->getDefaultVariant();
4750 $this->mOptions
['variant'] = $variant;
4751 $this->mOptions
['language'] = $variant;
4752 $this->mOptionsLoaded
= true;
4756 // Maybe load from the object
4757 if ( !is_null( $this->mOptionOverrides
) ) {
4758 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4759 foreach ( $this->mOptionOverrides
as $key => $value ) {
4760 $this->mOptions
[$key] = $value;
4763 if ( !is_array( $data ) ) {
4764 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4765 // Load from database
4766 $dbr = wfGetDB( DB_SLAVE
);
4768 $res = $dbr->select(
4770 array( 'up_property', 'up_value' ),
4771 array( 'up_user' => $this->getId() ),
4775 $this->mOptionOverrides
= array();
4777 foreach ( $res as $row ) {
4778 $data[$row->up_property
] = $row->up_value
;
4781 foreach ( $data as $property => $value ) {
4782 $this->mOptionOverrides
[$property] = $value;
4783 $this->mOptions
[$property] = $value;
4787 $this->mOptionsLoaded
= true;
4789 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
4793 * Saves the non-default options for this user, as previously set e.g. via
4794 * setOption(), in the database's "user_properties" (preferences) table.
4795 * Usually used via saveSettings().
4797 protected function saveOptions() {
4798 $this->loadOptions();
4800 // Not using getOptions(), to keep hidden preferences in database
4801 $saveOptions = $this->mOptions
;
4803 // Allow hooks to abort, for instance to save to a global profile.
4804 // Reset options to default state before saving.
4805 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4809 $userId = $this->getId();
4811 $insert_rows = array(); // all the new preference rows
4812 foreach ( $saveOptions as $key => $value ) {
4813 // Don't bother storing default values
4814 $defaultOption = self
::getDefaultOption( $key );
4815 if ( ( $defaultOption === null && $value !== false && $value !== null )
4816 ||
$value != $defaultOption
4818 $insert_rows[] = array(
4819 'up_user' => $userId,
4820 'up_property' => $key,
4821 'up_value' => $value,
4826 $dbw = wfGetDB( DB_MASTER
);
4828 $res = $dbw->select( 'user_properties',
4829 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
4831 // Find prior rows that need to be removed or updated. These rows will
4832 // all be deleted (the later so that INSERT IGNORE applies the new values).
4833 $keysDelete = array();
4834 foreach ( $res as $row ) {
4835 if ( !isset( $saveOptions[$row->up_property
] )
4836 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
4838 $keysDelete[] = $row->up_property
;
4842 if ( count( $keysDelete ) ) {
4843 // Do the DELETE by PRIMARY KEY for prior rows.
4844 // In the past a very large portion of calls to this function are for setting
4845 // 'rememberpassword' for new accounts (a preference that has since been removed).
4846 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4847 // caused gap locks on [max user ID,+infinity) which caused high contention since
4848 // updates would pile up on each other as they are for higher (newer) user IDs.
4849 // It might not be necessary these days, but it shouldn't hurt either.
4850 $dbw->delete( 'user_properties',
4851 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
4853 // Insert the new preference rows
4854 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
4858 * Provide an array of HTML5 attributes to put on an input element
4859 * intended for the user to enter a new password. This may include
4860 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4862 * Do *not* use this when asking the user to enter his current password!
4863 * Regardless of configuration, users may have invalid passwords for whatever
4864 * reason (e.g., they were set before requirements were tightened up).
4865 * Only use it when asking for a new password, like on account creation or
4868 * Obviously, you still need to do server-side checking.
4870 * NOTE: A combination of bugs in various browsers means that this function
4871 * actually just returns array() unconditionally at the moment. May as
4872 * well keep it around for when the browser bugs get fixed, though.
4874 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4876 * @return array Array of HTML attributes suitable for feeding to
4877 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4878 * That will get confused by the boolean attribute syntax used.)
4880 public static function passwordChangeInputAttribs() {
4881 global $wgMinimalPasswordLength;
4883 if ( $wgMinimalPasswordLength == 0 ) {
4887 # Note that the pattern requirement will always be satisfied if the
4888 # input is empty, so we need required in all cases.
4890 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4891 # if e-mail confirmation is being used. Since HTML5 input validation
4892 # is b0rked anyway in some browsers, just return nothing. When it's
4893 # re-enabled, fix this code to not output required for e-mail
4895 #$ret = array( 'required' );
4898 # We can't actually do this right now, because Opera 9.6 will print out
4899 # the entered password visibly in its error message! When other
4900 # browsers add support for this attribute, or Opera fixes its support,
4901 # we can add support with a version check to avoid doing this on Opera
4902 # versions where it will be a problem. Reported to Opera as
4903 # DSK-262266, but they don't have a public bug tracker for us to follow.
4905 if ( $wgMinimalPasswordLength > 1 ) {
4906 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4907 $ret['title'] = wfMessage( 'passwordtooshort' )
4908 ->numParams( $wgMinimalPasswordLength )->text();
4916 * Return the list of user fields that should be selected to create
4917 * a new user object.
4920 public static function selectFields() {
4927 'user_newpass_time',
4931 'user_email_authenticated',
4933 'user_email_token_expires',
4934 'user_password_expires',
4935 'user_registration',
4941 * Factory function for fatal permission-denied errors
4944 * @param string $permission User right required
4947 static function newFatalPermissionDeniedStatus( $permission ) {
4950 $groups = array_map(
4951 array( 'User', 'makeGroupLinkWiki' ),
4952 User
::getGroupsWithPermission( $permission )
4956 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4958 return Status
::newFatal( 'badaccess-group0' );