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
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 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 static $mCoreRights = array(
134 'editusercssjs', #deprecated
146 'move-rootuserpages',
150 'override-export-depth',
173 'userrights-interwiki',
179 * String Cached results of getAllRights()
181 static $mAllRights = false;
183 /** @name Cache variables */
185 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
186 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
187 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mEditCount,
188 $mGroups, $mOptionOverrides;
190 protected $mPasswordExpires;
194 * Bool Whether the cache variables have been loaded.
200 * Array with already loaded items or true if all items have been loaded.
202 private $mLoadedItems = array();
206 * String Initialization data source if mLoadedItems!==true. May be one of:
207 * - 'defaults' anonymous user initialised from class defaults
208 * - 'name' initialise from mName
209 * - 'id' initialise from mId
210 * - 'session' log in from cookies or session if possible
212 * Use the User::newFrom*() family of functions to set this.
217 * Lazy-initialized variables, invalidated with clearInstanceCache
219 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mRights,
220 $mBlockreason, $mEffectiveGroups, $mImplicitGroups, $mFormerGroups, $mBlockedGlobally,
221 $mLocked, $mHideName, $mOptions;
241 private $mBlockedFromCreateAccount = false;
246 private $mWatchedItems = array();
248 static $idCacheByName = array();
251 * Lightweight constructor for an anonymous user.
252 * Use the User::newFrom* factory functions for other kinds of users.
256 * @see newFromConfirmationCode()
257 * @see newFromSession()
260 public function __construct() {
261 $this->clearInstanceCache( 'defaults' );
267 public function __toString() {
268 return $this->getName();
272 * Load the user table data for this object from the source given by mFrom.
274 public function load() {
275 if ( $this->mLoadedItems
=== true ) {
278 wfProfileIn( __METHOD__
);
280 // Set it now to avoid infinite recursion in accessors
281 $this->mLoadedItems
= true;
283 switch ( $this->mFrom
) {
285 $this->loadDefaults();
288 $this->mId
= self
::idFromName( $this->mName
);
290 // Nonexistent user placeholder object
291 $this->loadDefaults( $this->mName
);
300 if ( !$this->loadFromSession() ) {
301 // Loading from session failed. Load defaults.
302 $this->loadDefaults();
304 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
307 wfProfileOut( __METHOD__
);
308 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
310 wfProfileOut( __METHOD__
);
314 * Load user table data, given mId has already been set.
315 * @return bool false if the ID does not exist, true otherwise
317 public function loadFromId() {
319 if ( $this->mId
== 0 ) {
320 $this->loadDefaults();
325 $key = wfMemcKey( 'user', 'id', $this->mId
);
326 $data = $wgMemc->get( $key );
327 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
328 // Object is expired, load from DB
333 wfDebug( "User: cache miss for user {$this->mId}\n" );
335 if ( !$this->loadFromDatabase() ) {
336 // Can't load from ID, user is anonymous
339 $this->saveToCache();
341 wfDebug( "User: got user {$this->mId} from cache\n" );
342 // Restore from cache
343 foreach ( self
::$mCacheVars as $name ) {
344 $this->$name = $data[$name];
348 $this->mLoadedItems
= true;
354 * Save user data to the shared cache
356 public function saveToCache() {
359 $this->loadOptions();
360 if ( $this->isAnon() ) {
361 // Anonymous users are uncached
365 foreach ( self
::$mCacheVars as $name ) {
366 $data[$name] = $this->$name;
368 $data['mVersion'] = MW_USER_VERSION
;
369 $key = wfMemcKey( 'user', 'id', $this->mId
);
371 $wgMemc->set( $key, $data );
374 /** @name newFrom*() static factory methods */
378 * Static factory method for creation from username.
380 * This is slightly less efficient than newFromId(), so use newFromId() if
381 * you have both an ID and a name handy.
383 * @param string $name Username, validated by Title::newFromText()
384 * @param string|bool $validate Validate username. Takes the same parameters as
385 * User::getCanonicalName(), except that true is accepted as an alias
386 * for 'valid', for BC.
388 * @return User|bool User object, or false if the username is invalid
389 * (e.g. if it contains illegal characters or is an IP address). If the
390 * username is not present in the database, the result will be a user object
391 * with a name, zero user ID and default settings.
393 public static function newFromName( $name, $validate = 'valid' ) {
394 if ( $validate === true ) {
397 $name = self
::getCanonicalName( $name, $validate );
398 if ( $name === false ) {
401 // Create unloaded user object
405 $u->setItemLoaded( 'name' );
411 * Static factory method for creation from a given user ID.
413 * @param int $id Valid user ID
414 * @return User The corresponding User object
416 public static function newFromId( $id ) {
420 $u->setItemLoaded( 'id' );
425 * Factory method to fetch whichever user has a given email confirmation code.
426 * This code is generated when an account is created or its e-mail address
429 * If the code is invalid or has expired, returns NULL.
431 * @param string $code Confirmation code
434 public static function newFromConfirmationCode( $code ) {
435 $dbr = wfGetDB( DB_SLAVE
);
436 $id = $dbr->selectField( 'user', 'user_id', array(
437 'user_email_token' => md5( $code ),
438 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
440 if ( $id !== false ) {
441 return User
::newFromId( $id );
448 * Create a new user object using data from session or cookies. If the
449 * login credentials are invalid, the result is an anonymous user.
451 * @param WebRequest $request Object to use; $wgRequest will be used if omitted.
452 * @return User object
454 public static function newFromSession( WebRequest
$request = null ) {
456 $user->mFrom
= 'session';
457 $user->mRequest
= $request;
462 * Create a new user object from a user row.
463 * The row should have the following fields from the user table in it:
464 * - either user_name or user_id to load further data if needed (or both)
466 * - all other fields (email, password, etc.)
467 * It is useless to provide the remaining fields if either user_id,
468 * user_name and user_real_name are not provided because the whole row
469 * will be loaded once more from the database when accessing them.
471 * @param stdClass $row A row from the user table
472 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
475 public static function newFromRow( $row, $data = null ) {
477 $user->loadFromRow( $row, $data );
484 * Get the username corresponding to a given user ID
485 * @param int $id User ID
486 * @return string|bool The corresponding username
488 public static function whoIs( $id ) {
489 return UserCache
::singleton()->getProp( $id, 'name' );
493 * Get the real name of a user given their user ID
495 * @param int $id User ID
496 * @return string|bool The corresponding user's real name
498 public static function whoIsReal( $id ) {
499 return UserCache
::singleton()->getProp( $id, 'real_name' );
503 * Get database id given a user name
504 * @param string $name Username
505 * @return int|null The corresponding user's ID, or null if user is nonexistent
507 public static function idFromName( $name ) {
508 $nt = Title
::makeTitleSafe( NS_USER
, $name );
509 if ( is_null( $nt ) ) {
514 if ( isset( self
::$idCacheByName[$name] ) ) {
515 return self
::$idCacheByName[$name];
518 $dbr = wfGetDB( DB_SLAVE
);
519 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
521 if ( $s === false ) {
524 $result = $s->user_id
;
527 self
::$idCacheByName[$name] = $result;
529 if ( count( self
::$idCacheByName ) > 1000 ) {
530 self
::$idCacheByName = array();
537 * Reset the cache used in idFromName(). For use in tests.
539 public static function resetIdByNameCache() {
540 self
::$idCacheByName = array();
544 * Does the string match an anonymous IPv4 address?
546 * This function exists for username validation, in order to reject
547 * usernames which are similar in form to IP addresses. Strings such
548 * as 300.300.300.300 will return true because it looks like an IP
549 * address, despite not being strictly valid.
551 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
552 * address because the usemod software would "cloak" anonymous IP
553 * addresses like this, if we allowed accounts like this to be created
554 * new users could get the old edits of these anonymous users.
556 * @param string $name Name to match
559 public static function isIP( $name ) {
560 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name ) || IP
::isIPv6( $name );
564 * Is the input a valid username?
566 * Checks if the input is a valid username, we don't want an empty string,
567 * an IP address, anything that contains slashes (would mess up subpages),
568 * is longer than the maximum allowed username size or doesn't begin with
571 * @param string $name Name to match
574 public static function isValidUserName( $name ) {
575 global $wgContLang, $wgMaxNameChars;
578 || User
::isIP( $name )
579 ||
strpos( $name, '/' ) !== false
580 ||
strlen( $name ) > $wgMaxNameChars
581 ||
$name != $wgContLang->ucfirst( $name ) ) {
582 wfDebugLog( 'username', __METHOD__
.
583 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
587 // Ensure that the name can't be misresolved as a different title,
588 // such as with extra namespace keys at the start.
589 $parsed = Title
::newFromText( $name );
590 if ( is_null( $parsed )
591 ||
$parsed->getNamespace()
592 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
593 wfDebugLog( 'username', __METHOD__
.
594 ": '$name' invalid due to ambiguous prefixes" );
598 // Check an additional blacklist of troublemaker characters.
599 // Should these be merged into the title char list?
600 $unicodeBlacklist = '/[' .
601 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
602 '\x{00a0}' . # non-breaking space
603 '\x{2000}-\x{200f}' . # various whitespace
604 '\x{2028}-\x{202f}' . # breaks and control chars
605 '\x{3000}' . # ideographic space
606 '\x{e000}-\x{f8ff}' . # private use
608 if ( preg_match( $unicodeBlacklist, $name ) ) {
609 wfDebugLog( 'username', __METHOD__
.
610 ": '$name' invalid due to blacklisted characters" );
618 * Usernames which fail to pass this function will be blocked
619 * from user login and new account registrations, but may be used
620 * internally by batch processes.
622 * If an account already exists in this form, login will be blocked
623 * by a failure to pass this function.
625 * @param string $name Name to match
628 public static function isUsableName( $name ) {
629 global $wgReservedUsernames;
630 // Must be a valid username, obviously ;)
631 if ( !self
::isValidUserName( $name ) ) {
635 static $reservedUsernames = false;
636 if ( !$reservedUsernames ) {
637 $reservedUsernames = $wgReservedUsernames;
638 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
641 // Certain names may be reserved for batch processes.
642 foreach ( $reservedUsernames as $reserved ) {
643 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
644 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
646 if ( $reserved == $name ) {
654 * Usernames which fail to pass this function will be blocked
655 * from new account registrations, but may be used internally
656 * either by batch processes or by user accounts which have
657 * already been created.
659 * Additional blacklisting may be added here rather than in
660 * isValidUserName() to avoid disrupting existing accounts.
662 * @param string $name to match
665 public static function isCreatableName( $name ) {
666 global $wgInvalidUsernameCharacters;
668 // Ensure that the username isn't longer than 235 bytes, so that
669 // (at least for the builtin skins) user javascript and css files
670 // will work. (bug 23080)
671 if ( strlen( $name ) > 235 ) {
672 wfDebugLog( 'username', __METHOD__
.
673 ": '$name' invalid due to length" );
677 // Preg yells if you try to give it an empty string
678 if ( $wgInvalidUsernameCharacters !== '' ) {
679 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
680 wfDebugLog( 'username', __METHOD__
.
681 ": '$name' invalid due to wgInvalidUsernameCharacters" );
686 return self
::isUsableName( $name );
690 * Is the input a valid password for this user?
692 * @param string $password Desired password
695 public function isValidPassword( $password ) {
696 //simple boolean wrapper for getPasswordValidity
697 return $this->getPasswordValidity( $password ) === true;
702 * Given unvalidated password input, return error message on failure.
704 * @param string $password Desired password
705 * @return mixed: true on success, string or array of error message on failure
707 public function getPasswordValidity( $password ) {
708 $result = $this->checkPasswordValidity( $password );
709 if ( $result->isGood() ) {
713 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
714 $messages[] = $error['message'];
716 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
717 $messages[] = $warning['message'];
719 if ( count( $messages ) === 1 ) {
727 * Check if this is a valid password for this user. Status will be good if
728 * the password is valid, or have an array of error messages if not.
730 * @param string $password Desired password
734 public function checkPasswordValidity( $password ) {
735 global $wgMinimalPasswordLength, $wgContLang;
737 static $blockedLogins = array(
738 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
739 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
742 $status = Status
::newGood();
744 $result = false; //init $result to false for the internal checks
746 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
747 $status->error( $result );
751 if ( $result === false ) {
752 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
753 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
755 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
756 $status->error( 'password-name-match' );
758 } elseif ( isset( $blockedLogins[$this->getName()] ) && $password == $blockedLogins[$this->getName()] ) {
759 $status->error( 'password-login-forbidden' );
762 //it seems weird returning a Good status here, but this is because of the
763 //initialization of $result to false above. If the hook is never run or it
764 //doesn't modify $result, then we will likely get down into this if with
768 } elseif ( $result === true ) {
771 $status->error( $result );
772 return $status; //the isValidPassword hook set a string $result and returned true
777 * Expire a user's password
779 * @param $ts Mixed: optional timestamp to convert, default 0 for the current time
781 public function expirePassword( $ts = 0 ) {
783 $timestamp = wfTimestamp( TS_MW
, $ts );
784 $this->mPasswordExpires
= $timestamp;
785 $this->saveSettings();
789 * Clear the password expiration for a user
791 * @param bool $load ensure user object is loaded first
793 public function resetPasswordExpiration( $load = true ) {
794 global $wgPasswordExpirationDays;
799 if ( $wgPasswordExpirationDays ) {
800 $newExpire = wfTimestamp(
802 time() +
( $wgPasswordExpirationDays * 24 * 3600 )
805 // Give extensions a chance to force an expiration
806 wfRunHooks( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
807 $this->mPasswordExpires
= $newExpire;
811 * Check if the user's password is expired.
812 * TODO: Put this and password length into a PasswordPolicy object
814 * @return string|bool The expiration type, or false if not expired
815 * hard: A password change is required to login
816 * soft: Allow login, but encourage password change
817 * false: Password is not expired
819 public function getPasswordExpired() {
820 global $wgPasswordExpireGrace;
822 $now = wfTimestamp();
823 $expiration = $this->getPasswordExpireDate();
824 $expUnix = wfTimestamp( TS_UNIX
, $expiration );
825 if ( $expiration !== null && $expUnix < $now ) {
826 $expired = ( $expUnix +
$wgPasswordExpireGrace < $now ) ?
'hard' : 'soft';
832 * Get this user's password expiration date. Since this may be using
833 * the cached User object, we assume that whatever mechanism is setting
834 * the expiration date is also expiring the User cache.
836 * @return string|false the datestamp of the expiration, or null if not set
838 public function getPasswordExpireDate() {
840 return $this->mPasswordExpires
;
844 * Does a string look like an e-mail address?
846 * This validates an email address using an HTML5 specification found at:
847 * http://www.whatwg.org/html/states-of-the-type-attribute.html#valid-e-mail-address
848 * Which as of 2011-01-24 says:
850 * A valid e-mail address is a string that matches the ABNF production
851 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
852 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
855 * This function is an implementation of the specification as requested in
858 * Client-side forms will use the same standard validation rules via JS or
859 * HTML 5 validation; additional restrictions can be enforced server-side
860 * by extensions via the 'isValidEmailAddr' hook.
862 * Note that this validation doesn't 100% match RFC 2822, but is believed
863 * to be liberal enough for wide use. Some invalid addresses will still
864 * pass validation here.
866 * @param string $addr E-mail address
868 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
870 public static function isValidEmailAddr( $addr ) {
871 wfDeprecated( __METHOD__
, '1.18' );
872 return Sanitizer
::validateEmail( $addr );
876 * Given unvalidated user input, return a canonical username, or false if
877 * the username is invalid.
878 * @param string $name User input
879 * @param string|bool $validate type of validation to use:
880 * - false No validation
881 * - 'valid' Valid for batch processes
882 * - 'usable' Valid for batch processes and login
883 * - 'creatable' Valid for batch processes, login and account creation
885 * @throws MWException
886 * @return bool|string
888 public static function getCanonicalName( $name, $validate = 'valid' ) {
889 // Force usernames to capital
891 $name = $wgContLang->ucfirst( $name );
893 # Reject names containing '#'; these will be cleaned up
894 # with title normalisation, but then it's too late to
896 if ( strpos( $name, '#' ) !== false ) {
900 // Clean up name according to title rules
901 $t = ( $validate === 'valid' ) ?
902 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
903 // Check for invalid titles
904 if ( is_null( $t ) ) {
908 // Reject various classes of invalid names
910 $name = $wgAuth->getCanonicalName( $t->getText() );
912 switch ( $validate ) {
916 if ( !User
::isValidUserName( $name ) ) {
921 if ( !User
::isUsableName( $name ) ) {
926 if ( !User
::isCreatableName( $name ) ) {
931 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
937 * Count the number of edits of a user
939 * @param int $uid User ID to check
940 * @return int The user's edit count
942 * @deprecated since 1.21 in favour of User::getEditCount
944 public static function edits( $uid ) {
945 wfDeprecated( __METHOD__
, '1.21' );
946 $user = self
::newFromId( $uid );
947 return $user->getEditCount();
951 * Return a random password.
953 * @return string New random password
955 public static function randomPassword() {
956 global $wgMinimalPasswordLength;
957 // Decide the final password length based on our min password length, stopping at a minimum of 10 chars
958 $length = max( 10, $wgMinimalPasswordLength );
959 // Multiply by 1.25 to get the number of hex characters we need
960 $length = $length * 1.25;
961 // Generate random hex chars
962 $hex = MWCryptRand
::generateHex( $length );
963 // Convert from base 16 to base 32 to get a proper password like string
964 return wfBaseConvert( $hex, 16, 32 );
968 * Set cached properties to default.
970 * @note This no longer clears uncached lazy-initialised properties;
971 * the constructor does that instead.
973 * @param $name string|bool
975 public function loadDefaults( $name = false ) {
976 wfProfileIn( __METHOD__
);
979 $this->mName
= $name;
980 $this->mRealName
= '';
981 $this->mPassword
= $this->mNewpassword
= '';
982 $this->mNewpassTime
= null;
984 $this->mOptionOverrides
= null;
985 $this->mOptionsLoaded
= false;
987 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
988 if ( $loggedOut !== null ) {
989 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
991 $this->mTouched
= '1'; # Allow any pages to be cached
994 $this->mToken
= null; // Don't run cryptographic functions till we need a token
995 $this->mEmailAuthenticated
= null;
996 $this->mEmailToken
= '';
997 $this->mEmailTokenExpires
= null;
998 $this->mPasswordExpires
= null;
999 $this->resetPasswordExpiration( false );
1000 $this->mRegistration
= wfTimestamp( TS_MW
);
1001 $this->mGroups
= array();
1003 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
1005 wfProfileOut( __METHOD__
);
1009 * Return whether an item has been loaded.
1011 * @param string $item item to check. Current possibilities:
1015 * @param string $all 'all' to check if the whole object has been loaded
1016 * or any other string to check if only the item is available (e.g.
1020 public function isItemLoaded( $item, $all = 'all' ) {
1021 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1022 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1026 * Set that an item has been loaded
1028 * @param string $item
1030 protected function setItemLoaded( $item ) {
1031 if ( is_array( $this->mLoadedItems
) ) {
1032 $this->mLoadedItems
[$item] = true;
1037 * Load user data from the session or login cookie.
1038 * @return bool True if the user is logged in, false otherwise.
1040 private function loadFromSession() {
1042 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
1043 if ( $result !== null ) {
1047 $request = $this->getRequest();
1049 $cookieId = $request->getCookie( 'UserID' );
1050 $sessId = $request->getSessionData( 'wsUserID' );
1052 if ( $cookieId !== null ) {
1053 $sId = intval( $cookieId );
1054 if ( $sessId !== null && $cookieId != $sessId ) {
1055 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1056 cookie user ID ($sId) don't match!" );
1059 $request->setSessionData( 'wsUserID', $sId );
1060 } elseif ( $sessId !== null && $sessId != 0 ) {
1066 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1067 $sName = $request->getSessionData( 'wsUserName' );
1068 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1069 $sName = $request->getCookie( 'UserName' );
1070 $request->setSessionData( 'wsUserName', $sName );
1075 $proposedUser = User
::newFromId( $sId );
1076 if ( !$proposedUser->isLoggedIn() ) {
1081 global $wgBlockDisablesLogin;
1082 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1083 // User blocked and we've disabled blocked user logins
1087 if ( $request->getSessionData( 'wsToken' ) ) {
1088 $passwordCorrect = ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1090 } elseif ( $request->getCookie( 'Token' ) ) {
1091 # Get the token from DB/cache and clean it up to remove garbage padding.
1092 # This deals with historical problems with bugs and the default column value.
1093 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1094 // Make comparison in constant time (bug 61346)
1095 $passwordCorrect = strlen( $token ) && $this->compareSecrets( $token, $request->getCookie( 'Token' ) );
1098 // No session or persistent login cookie
1102 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1103 $this->loadFromUserObject( $proposedUser );
1104 $request->setSessionData( 'wsToken', $this->mToken
);
1105 wfDebug( "User: logged in from $from\n" );
1108 // Invalid credentials
1109 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1115 * A comparison of two strings, not vulnerable to timing attacks
1116 * @param string $answer the secret string that you are comparing against.
1117 * @param string $test compare this string to the $answer.
1118 * @return bool True if the strings are the same, false otherwise
1120 protected function compareSecrets( $answer, $test ) {
1121 if ( strlen( $answer ) !== strlen( $test ) ) {
1122 $passwordCorrect = false;
1125 for ( $i = 0; $i < strlen( $answer ); $i++
) {
1126 $result |
= ord( $answer[$i] ) ^
ord( $test[$i] );
1128 $passwordCorrect = ( $result == 0 );
1130 return $passwordCorrect;
1134 * Load user and user_group data from the database.
1135 * $this->mId must be set, this is how the user is identified.
1137 * @return bool True if the user exists, false if the user is anonymous
1139 public function loadFromDatabase() {
1141 $this->mId
= intval( $this->mId
);
1144 if ( !$this->mId
) {
1145 $this->loadDefaults();
1149 $dbr = wfGetDB( DB_MASTER
);
1150 $s = $dbr->selectRow( 'user', self
::selectFields(), array( 'user_id' => $this->mId
), __METHOD__
);
1152 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1154 if ( $s !== false ) {
1155 // Initialise user table data
1156 $this->loadFromRow( $s );
1157 $this->mGroups
= null; // deferred
1158 $this->getEditCount(); // revalidation for nulls
1163 $this->loadDefaults();
1169 * Initialize this object from a row from the user table.
1171 * @param stdClass $row Row from the user table to load.
1172 * @param array $data Further user data to load into the object
1174 * user_groups Array with groups out of the user_groups table
1175 * user_properties Array with properties out of the user_properties table
1177 public function loadFromRow( $row, $data = null ) {
1180 $this->mGroups
= null; // deferred
1182 if ( isset( $row->user_name
) ) {
1183 $this->mName
= $row->user_name
;
1184 $this->mFrom
= 'name';
1185 $this->setItemLoaded( 'name' );
1190 if ( isset( $row->user_real_name
) ) {
1191 $this->mRealName
= $row->user_real_name
;
1192 $this->setItemLoaded( 'realname' );
1197 if ( isset( $row->user_id
) ) {
1198 $this->mId
= intval( $row->user_id
);
1199 $this->mFrom
= 'id';
1200 $this->setItemLoaded( 'id' );
1205 if ( isset( $row->user_editcount
) ) {
1206 $this->mEditCount
= $row->user_editcount
;
1211 if ( isset( $row->user_password
) ) {
1212 $this->mPassword
= $row->user_password
;
1213 $this->mNewpassword
= $row->user_newpassword
;
1214 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1215 $this->mEmail
= $row->user_email
;
1216 if ( isset( $row->user_options
) ) {
1217 $this->decodeOptions( $row->user_options
);
1219 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1220 $this->mToken
= $row->user_token
;
1221 if ( $this->mToken
== '' ) {
1222 $this->mToken
= null;
1224 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1225 $this->mEmailToken
= $row->user_email_token
;
1226 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1227 $this->mPasswordExpires
= wfTimestampOrNull( TS_MW
, $row->user_password_expires
);
1228 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1234 $this->mLoadedItems
= true;
1237 if ( is_array( $data ) ) {
1238 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1239 $this->mGroups
= $data['user_groups'];
1241 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1242 $this->loadOptions( $data['user_properties'] );
1248 * Load the data for this user object from another user object.
1252 protected function loadFromUserObject( $user ) {
1254 $user->loadGroups();
1255 $user->loadOptions();
1256 foreach ( self
::$mCacheVars as $var ) {
1257 $this->$var = $user->$var;
1262 * Load the groups from the database if they aren't already loaded.
1264 private function loadGroups() {
1265 if ( is_null( $this->mGroups
) ) {
1266 $dbr = wfGetDB( DB_MASTER
);
1267 $res = $dbr->select( 'user_groups',
1268 array( 'ug_group' ),
1269 array( 'ug_user' => $this->mId
),
1271 $this->mGroups
= array();
1272 foreach ( $res as $row ) {
1273 $this->mGroups
[] = $row->ug_group
;
1279 * Add the user to the group if he/she meets given criteria.
1281 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1282 * possible to remove manually via Special:UserRights. In such case it
1283 * will not be re-added automatically. The user will also not lose the
1284 * group if they no longer meet the criteria.
1286 * @param string $event key in $wgAutopromoteOnce (each one has groups/criteria)
1288 * @return array Array of groups the user has been promoted to.
1290 * @see $wgAutopromoteOnce
1292 public function addAutopromoteOnceGroups( $event ) {
1293 global $wgAutopromoteOnceLogInRC, $wgAuth;
1295 $toPromote = array();
1296 if ( $this->getId() ) {
1297 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1298 if ( count( $toPromote ) ) {
1299 $oldGroups = $this->getGroups(); // previous groups
1301 foreach ( $toPromote as $group ) {
1302 $this->addGroup( $group );
1304 // update groups in external authentication database
1305 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1307 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1309 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1310 $logEntry->setPerformer( $this );
1311 $logEntry->setTarget( $this->getUserPage() );
1312 $logEntry->setParameters( array(
1313 '4::oldgroups' => $oldGroups,
1314 '5::newgroups' => $newGroups,
1316 $logid = $logEntry->insert();
1317 if ( $wgAutopromoteOnceLogInRC ) {
1318 $logEntry->publish( $logid );
1326 * Clear various cached data stored in this object. The cache of the user table
1327 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1329 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1330 * given source. May be "name", "id", "defaults", "session", or false for
1333 public function clearInstanceCache( $reloadFrom = false ) {
1334 $this->mNewtalk
= -1;
1335 $this->mDatePreference
= null;
1336 $this->mBlockedby
= -1; # Unset
1337 $this->mHash
= false;
1338 $this->mRights
= null;
1339 $this->mEffectiveGroups
= null;
1340 $this->mImplicitGroups
= null;
1341 $this->mGroups
= null;
1342 $this->mOptions
= null;
1343 $this->mOptionsLoaded
= false;
1344 $this->mEditCount
= null;
1346 if ( $reloadFrom ) {
1347 $this->mLoadedItems
= array();
1348 $this->mFrom
= $reloadFrom;
1353 * Combine the language default options with any site-specific options
1354 * and add the default language variants.
1356 * @return Array of String options
1358 public static function getDefaultOptions() {
1359 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1361 static $defOpt = null;
1362 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1363 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1364 // mid-request and see that change reflected in the return value of this function.
1365 // Which is insane and would never happen during normal MW operation
1369 $defOpt = $wgDefaultUserOptions;
1370 // Default language setting
1371 $defOpt['language'] = $wgContLang->getCode();
1372 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1373 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1375 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1376 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1378 $defOpt['skin'] = $wgDefaultSkin;
1380 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1386 * Get a given default option value.
1388 * @param string $opt Name of option to retrieve
1389 * @return string Default option value
1391 public static function getDefaultOption( $opt ) {
1392 $defOpts = self
::getDefaultOptions();
1393 if ( isset( $defOpts[$opt] ) ) {
1394 return $defOpts[$opt];
1401 * Get blocking information
1402 * @param bool $bFromSlave Whether to check the slave database first. To
1403 * improve performance, non-critical checks are done
1404 * against slaves. Check when actually saving should be
1405 * done against master.
1407 private function getBlockedStatus( $bFromSlave = true ) {
1408 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1410 if ( -1 != $this->mBlockedby
) {
1414 wfProfileIn( __METHOD__
);
1415 wfDebug( __METHOD__
. ": checking...\n" );
1417 // Initialize data...
1418 // Otherwise something ends up stomping on $this->mBlockedby when
1419 // things get lazy-loaded later, causing false positive block hits
1420 // due to -1 !== 0. Probably session-related... Nothing should be
1421 // overwriting mBlockedby, surely?
1424 # We only need to worry about passing the IP address to the Block generator if the
1425 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1426 # know which IP address they're actually coming from
1427 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1428 $ip = $this->getRequest()->getIP();
1434 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1437 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1438 && !in_array( $ip, $wgProxyWhitelist )
1441 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1443 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1444 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1445 $block->setTarget( $ip );
1446 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1448 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1449 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1450 $block->setTarget( $ip );
1454 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1455 if ( !$block instanceof Block
1456 && $wgApplyIpBlocksToXff
1458 && !$this->isAllowed( 'proxyunbannable' )
1459 && !in_array( $ip, $wgProxyWhitelist )
1461 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1462 $xff = array_map( 'trim', explode( ',', $xff ) );
1463 $xff = array_diff( $xff, array( $ip ) );
1464 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1465 $block = Block
::chooseBlock( $xffblocks, $xff );
1466 if ( $block instanceof Block
) {
1467 # Mangle the reason to alert the user that the block
1468 # originated from matching the X-Forwarded-For header.
1469 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1473 if ( $block instanceof Block
) {
1474 wfDebug( __METHOD__
. ": Found block.\n" );
1475 $this->mBlock
= $block;
1476 $this->mBlockedby
= $block->getByName();
1477 $this->mBlockreason
= $block->mReason
;
1478 $this->mHideName
= $block->mHideName
;
1479 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1481 $this->mBlockedby
= '';
1482 $this->mHideName
= 0;
1483 $this->mAllowUsertalk
= false;
1487 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1489 wfProfileOut( __METHOD__
);
1493 * Whether the given IP is in a DNS blacklist.
1495 * @param string $ip IP to check
1496 * @param bool $checkWhitelist whether to check the whitelist first
1497 * @return bool True if blacklisted.
1499 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1500 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1501 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1503 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs ) {
1507 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1511 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1512 return $this->inDnsBlacklist( $ip, $urls );
1516 * Whether the given IP is in a given DNS blacklist.
1518 * @param string $ip IP to check
1519 * @param string|array $bases of Strings: URL of the DNS blacklist
1520 * @return bool True if blacklisted.
1522 public function inDnsBlacklist( $ip, $bases ) {
1523 wfProfileIn( __METHOD__
);
1526 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1527 if ( IP
::isIPv4( $ip ) ) {
1528 // Reverse IP, bug 21255
1529 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1531 foreach ( (array)$bases as $base ) {
1533 // If we have an access key, use that too (ProjectHoneypot, etc.)
1534 if ( is_array( $base ) ) {
1535 if ( count( $base ) >= 2 ) {
1536 // Access key is 1, base URL is 0
1537 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1539 $host = "$ipReversed.{$base[0]}";
1542 $host = "$ipReversed.$base";
1546 $ipList = gethostbynamel( $host );
1549 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1553 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1558 wfProfileOut( __METHOD__
);
1563 * Check if an IP address is in the local proxy list
1569 public static function isLocallyBlockedProxy( $ip ) {
1570 global $wgProxyList;
1572 if ( !$wgProxyList ) {
1575 wfProfileIn( __METHOD__
);
1577 if ( !is_array( $wgProxyList ) ) {
1578 // Load from the specified file
1579 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1582 if ( !is_array( $wgProxyList ) ) {
1584 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1586 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1587 // Old-style flipped proxy list
1592 wfProfileOut( __METHOD__
);
1597 * Is this user subject to rate limiting?
1599 * @return bool True if rate limited
1601 public function isPingLimitable() {
1602 global $wgRateLimitsExcludedIPs;
1603 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1604 // No other good way currently to disable rate limits
1605 // for specific IPs. :P
1606 // But this is a crappy hack and should die.
1609 return !$this->isAllowed( 'noratelimit' );
1613 * Primitive rate limits: enforce maximum actions per time period
1614 * to put a brake on flooding.
1616 * @note When using a shared cache like memcached, IP-address
1617 * last-hit counters will be shared across wikis.
1619 * @param string $action Action to enforce; 'edit' if unspecified
1620 * @param integer $incrBy Positive amount to increment counter by [defaults to 1]
1621 * @return bool True if a rate limiter was tripped
1623 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1624 // Call the 'PingLimiter' hook
1626 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1630 global $wgRateLimits;
1631 if ( !isset( $wgRateLimits[$action] ) ) {
1635 // Some groups shouldn't trigger the ping limiter, ever
1636 if ( !$this->isPingLimitable() ) {
1641 wfProfileIn( __METHOD__
);
1643 $limits = $wgRateLimits[$action];
1645 $id = $this->getId();
1648 if ( isset( $limits['anon'] ) && $id == 0 ) {
1649 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1652 if ( isset( $limits['user'] ) && $id != 0 ) {
1653 $userLimit = $limits['user'];
1655 if ( $this->isNewbie() ) {
1656 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1657 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1659 if ( isset( $limits['ip'] ) ) {
1660 $ip = $this->getRequest()->getIP();
1661 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1663 if ( isset( $limits['subnet'] ) ) {
1664 $ip = $this->getRequest()->getIP();
1667 if ( IP
::isIPv6( $ip ) ) {
1668 $parts = IP
::parseRange( "$ip/64" );
1669 $subnet = $parts[0];
1670 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1672 $subnet = $matches[1];
1674 if ( $subnet !== false ) {
1675 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1679 // Check for group-specific permissions
1680 // If more than one group applies, use the group with the highest limit
1681 foreach ( $this->getGroups() as $group ) {
1682 if ( isset( $limits[$group] ) ) {
1683 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1684 $userLimit = $limits[$group];
1688 // Set the user limit key
1689 if ( $userLimit !== false ) {
1690 list( $max, $period ) = $userLimit;
1691 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1692 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1696 foreach ( $keys as $key => $limit ) {
1697 list( $max, $period ) = $limit;
1698 $summary = "(limit $max in {$period}s)";
1699 $count = $wgMemc->get( $key );
1702 if ( $count >= $max ) {
1703 wfDebugLog( 'ratelimit', $this->getName() . " tripped! $key at $count $summary" );
1706 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1709 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1710 if ( $incrBy > 0 ) {
1711 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1714 if ( $incrBy > 0 ) {
1715 $wgMemc->incr( $key, $incrBy );
1719 wfProfileOut( __METHOD__
);
1724 * Check if user is blocked
1726 * @param bool $bFromSlave Whether to check the slave database instead of the master
1727 * @return bool True if blocked, false otherwise
1729 public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1730 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1734 * Get the block affecting the user, or null if the user is not blocked
1736 * @param bool $bFromSlave Whether to check the slave database instead of the master
1737 * @return Block|null
1739 public function getBlock( $bFromSlave = true ) {
1740 $this->getBlockedStatus( $bFromSlave );
1741 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1745 * Check if user is blocked from editing a particular article
1747 * @param Title $title Title to check
1748 * @param bool $bFromSlave whether to check the slave database instead of the master
1751 public function isBlockedFrom( $title, $bFromSlave = false ) {
1752 global $wgBlockAllowsUTEdit;
1753 wfProfileIn( __METHOD__
);
1755 $blocked = $this->isBlocked( $bFromSlave );
1756 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1757 // If a user's name is suppressed, they cannot make edits anywhere
1758 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1759 && $title->getNamespace() == NS_USER_TALK
) {
1761 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1764 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1766 wfProfileOut( __METHOD__
);
1771 * If user is blocked, return the name of the user who placed the block
1772 * @return string Name of blocker
1774 public function blockedBy() {
1775 $this->getBlockedStatus();
1776 return $this->mBlockedby
;
1780 * If user is blocked, return the specified reason for the block
1781 * @return string Blocking reason
1783 public function blockedFor() {
1784 $this->getBlockedStatus();
1785 return $this->mBlockreason
;
1789 * If user is blocked, return the ID for the block
1790 * @return int Block ID
1792 public function getBlockId() {
1793 $this->getBlockedStatus();
1794 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1798 * Check if user is blocked on all wikis.
1799 * Do not use for actual edit permission checks!
1800 * This is intended for quick UI checks.
1802 * @param string $ip IP address, uses current client if none given
1803 * @return bool True if blocked, false otherwise
1805 public function isBlockedGlobally( $ip = '' ) {
1806 if ( $this->mBlockedGlobally
!== null ) {
1807 return $this->mBlockedGlobally
;
1809 // User is already an IP?
1810 if ( IP
::isIPAddress( $this->getName() ) ) {
1811 $ip = $this->getName();
1813 $ip = $this->getRequest()->getIP();
1816 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1817 $this->mBlockedGlobally
= (bool)$blocked;
1818 return $this->mBlockedGlobally
;
1822 * Check if user account is locked
1824 * @return bool True if locked, false otherwise
1826 public function isLocked() {
1827 if ( $this->mLocked
!== null ) {
1828 return $this->mLocked
;
1831 StubObject
::unstub( $wgAuth );
1832 $authUser = $wgAuth->getUserInstance( $this );
1833 $this->mLocked
= (bool)$authUser->isLocked();
1834 return $this->mLocked
;
1838 * Check if user account is hidden
1840 * @return bool True if hidden, false otherwise
1842 public function isHidden() {
1843 if ( $this->mHideName
!== null ) {
1844 return $this->mHideName
;
1846 $this->getBlockedStatus();
1847 if ( !$this->mHideName
) {
1849 StubObject
::unstub( $wgAuth );
1850 $authUser = $wgAuth->getUserInstance( $this );
1851 $this->mHideName
= (bool)$authUser->isHidden();
1853 return $this->mHideName
;
1857 * Get the user's ID.
1858 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1860 public function getId() {
1861 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1862 // Special case, we know the user is anonymous
1864 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1865 // Don't load if this was initialized from an ID
1872 * Set the user and reload all fields according to a given ID
1873 * @param int $v User ID to reload
1875 public function setId( $v ) {
1877 $this->clearInstanceCache( 'id' );
1881 * Get the user name, or the IP of an anonymous user
1882 * @return string User's name or IP address
1884 public function getName() {
1885 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1886 // Special case optimisation
1887 return $this->mName
;
1890 if ( $this->mName
=== false ) {
1892 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1894 return $this->mName
;
1899 * Set the user name.
1901 * This does not reload fields from the database according to the given
1902 * name. Rather, it is used to create a temporary "nonexistent user" for
1903 * later addition to the database. It can also be used to set the IP
1904 * address for an anonymous user to something other than the current
1907 * @note User::newFromName() has roughly the same function, when the named user
1909 * @param string $str New user name to set
1911 public function setName( $str ) {
1913 $this->mName
= $str;
1917 * Get the user's name escaped by underscores.
1918 * @return string Username escaped by underscores.
1920 public function getTitleKey() {
1921 return str_replace( ' ', '_', $this->getName() );
1925 * Check if the user has new messages.
1926 * @return bool True if the user has new messages
1928 public function getNewtalk() {
1931 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1932 if ( $this->mNewtalk
=== -1 ) {
1933 $this->mNewtalk
= false; # reset talk page status
1935 // Check memcached separately for anons, who have no
1936 // entire User object stored in there.
1937 if ( !$this->mId
) {
1938 global $wgDisableAnonTalk;
1939 if ( $wgDisableAnonTalk ) {
1940 // Anon newtalk disabled by configuration.
1941 $this->mNewtalk
= false;
1944 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1945 $newtalk = $wgMemc->get( $key );
1946 if ( strval( $newtalk ) !== '' ) {
1947 $this->mNewtalk
= (bool)$newtalk;
1949 // Since we are caching this, make sure it is up to date by getting it
1951 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1952 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1956 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1960 return (bool)$this->mNewtalk
;
1964 * Return the data needed to construct links for new talk page message
1965 * alerts. If there are new messages, this will return an associative array
1966 * with the following data:
1967 * wiki: The database name of the wiki
1968 * link: Root-relative link to the user's talk page
1969 * rev: The last talk page revision that the user has seen or null. This
1970 * is useful for building diff links.
1971 * If there are no new messages, it returns an empty array.
1972 * @note This function was designed to accomodate multiple talk pages, but
1973 * currently only returns a single link and revision.
1976 public function getNewMessageLinks() {
1978 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
1980 } elseif ( !$this->getNewtalk() ) {
1983 $utp = $this->getTalkPage();
1984 $dbr = wfGetDB( DB_SLAVE
);
1985 // Get the "last viewed rev" timestamp from the oldest message notification
1986 $timestamp = $dbr->selectField( 'user_newtalk',
1987 'MIN(user_last_timestamp)',
1988 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
1990 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
1991 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
1995 * Get the revision ID for the last talk page revision viewed by the talk
1997 * @return int|null Revision ID or null
1999 public function getNewMessageRevisionId() {
2000 $newMessageRevisionId = null;
2001 $newMessageLinks = $this->getNewMessageLinks();
2002 if ( $newMessageLinks ) {
2003 // Note: getNewMessageLinks() never returns more than a single link
2004 // and it is always for the same wiki, but we double-check here in
2005 // case that changes some time in the future.
2006 if ( count( $newMessageLinks ) === 1
2007 && $newMessageLinks[0]['wiki'] === wfWikiID()
2008 && $newMessageLinks[0]['rev']
2010 $newMessageRevision = $newMessageLinks[0]['rev'];
2011 $newMessageRevisionId = $newMessageRevision->getId();
2014 return $newMessageRevisionId;
2018 * Internal uncached check for new messages
2021 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2022 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2023 * @param bool $fromMaster true to fetch from the master, false for a slave
2024 * @return bool True if the user has new messages
2026 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2027 if ( $fromMaster ) {
2028 $db = wfGetDB( DB_MASTER
);
2030 $db = wfGetDB( DB_SLAVE
);
2032 $ok = $db->selectField( 'user_newtalk', $field,
2033 array( $field => $id ), __METHOD__
);
2034 return $ok !== false;
2038 * Add or update the new messages flag
2039 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2040 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2041 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null.
2042 * @return bool True if successful, false otherwise
2044 protected function updateNewtalk( $field, $id, $curRev = null ) {
2045 // Get timestamp of the talk page revision prior to the current one
2046 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2047 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2048 // Mark the user as having new messages since this revision
2049 $dbw = wfGetDB( DB_MASTER
);
2050 $dbw->insert( 'user_newtalk',
2051 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2054 if ( $dbw->affectedRows() ) {
2055 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2058 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2064 * Clear the new messages flag for the given user
2065 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2066 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2067 * @return bool True if successful, false otherwise
2069 protected function deleteNewtalk( $field, $id ) {
2070 $dbw = wfGetDB( DB_MASTER
);
2071 $dbw->delete( 'user_newtalk',
2072 array( $field => $id ),
2074 if ( $dbw->affectedRows() ) {
2075 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2078 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2084 * Update the 'You have new messages!' status.
2085 * @param bool $val Whether the user has new messages
2086 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null or !$val.
2088 public function setNewtalk( $val, $curRev = null ) {
2089 if ( wfReadOnly() ) {
2094 $this->mNewtalk
= $val;
2096 if ( $this->isAnon() ) {
2098 $id = $this->getName();
2101 $id = $this->getId();
2106 $changed = $this->updateNewtalk( $field, $id, $curRev );
2108 $changed = $this->deleteNewtalk( $field, $id );
2111 if ( $this->isAnon() ) {
2112 // Anons have a separate memcached space, since
2113 // user records aren't kept for them.
2114 $key = wfMemcKey( 'newtalk', 'ip', $id );
2115 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
2118 $this->invalidateCache();
2123 * Generate a current or new-future timestamp to be stored in the
2124 * user_touched field when we update things.
2125 * @return string Timestamp in TS_MW format
2127 private static function newTouchedTimestamp() {
2128 global $wgClockSkewFudge;
2129 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2133 * Clear user data from memcached.
2134 * Use after applying fun updates to the database; caller's
2135 * responsibility to update user_touched if appropriate.
2137 * Called implicitly from invalidateCache() and saveSettings().
2139 private function clearSharedCache() {
2143 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
2148 * Immediately touch the user data cache for this account.
2149 * Updates user_touched field, and removes account data from memcached
2150 * for reload on the next hit.
2152 public function invalidateCache() {
2153 if ( wfReadOnly() ) {
2158 $this->mTouched
= self
::newTouchedTimestamp();
2160 $dbw = wfGetDB( DB_MASTER
);
2161 $userid = $this->mId
;
2162 $touched = $this->mTouched
;
2163 $method = __METHOD__
;
2164 $dbw->onTransactionIdle( function() use ( $dbw, $userid, $touched, $method ) {
2165 // Prevent contention slams by checking user_touched first
2166 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2167 $needsPurge = $dbw->selectField( 'user', '1',
2168 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2169 if ( $needsPurge ) {
2170 $dbw->update( 'user',
2171 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2172 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2177 $this->clearSharedCache();
2182 * Validate the cache for this account.
2183 * @param string $timestamp A timestamp in TS_MW format
2186 public function validateCache( $timestamp ) {
2188 return ( $timestamp >= $this->mTouched
);
2192 * Get the user touched timestamp
2193 * @return string timestamp
2195 public function getTouched() {
2197 return $this->mTouched
;
2201 * Set the password and reset the random token.
2202 * Calls through to authentication plugin if necessary;
2203 * will have no effect if the auth plugin refuses to
2204 * pass the change through or if the legal password
2207 * As a special case, setting the password to null
2208 * wipes it, so the account cannot be logged in until
2209 * a new password is set, for instance via e-mail.
2211 * @param string $str New password to set
2212 * @throws PasswordError on failure
2216 public function setPassword( $str ) {
2219 if ( $str !== null ) {
2220 if ( !$wgAuth->allowPasswordChange() ) {
2221 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2224 if ( !$this->isValidPassword( $str ) ) {
2225 global $wgMinimalPasswordLength;
2226 $valid = $this->getPasswordValidity( $str );
2227 if ( is_array( $valid ) ) {
2228 $message = array_shift( $valid );
2232 $params = array( $wgMinimalPasswordLength );
2234 throw new PasswordError( wfMessage( $message, $params )->text() );
2238 if ( !$wgAuth->setPassword( $this, $str ) ) {
2239 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2242 $this->setInternalPassword( $str );
2248 * Set the password and reset the random token unconditionally.
2250 * @param string|null $str New password to set or null to set an invalid
2251 * password hash meaning that the user will not be able to log in
2252 * through the web interface.
2254 public function setInternalPassword( $str ) {
2258 if ( $str === null ) {
2259 // Save an invalid hash...
2260 $this->mPassword
= '';
2262 $this->mPassword
= self
::crypt( $str );
2264 $this->mNewpassword
= '';
2265 $this->mNewpassTime
= null;
2269 * Get the user's current token.
2270 * @param bool $forceCreation Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility)
2271 * @return string Token
2273 public function getToken( $forceCreation = true ) {
2275 if ( !$this->mToken
&& $forceCreation ) {
2278 return $this->mToken
;
2282 * Set the random token (used for persistent authentication)
2283 * Called from loadDefaults() among other places.
2285 * @param string|bool $token If specified, set the token to this value
2287 public function setToken( $token = false ) {
2290 $this->mToken
= MWCryptRand
::generateHex( USER_TOKEN_LENGTH
);
2292 $this->mToken
= $token;
2297 * Set the password for a password reminder or new account email
2299 * @param $str New password to set or null to set an invalid
2300 * password hash meaning that the user will not be able to use it
2301 * @param bool $throttle If true, reset the throttle timestamp to the present
2303 public function setNewpassword( $str, $throttle = true ) {
2306 if ( $str === null ) {
2307 $this->mNewpassword
= '';
2308 $this->mNewpassTime
= null;
2310 $this->mNewpassword
= self
::crypt( $str );
2312 $this->mNewpassTime
= wfTimestampNow();
2318 * Has password reminder email been sent within the last
2319 * $wgPasswordReminderResendTime hours?
2322 public function isPasswordReminderThrottled() {
2323 global $wgPasswordReminderResendTime;
2325 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2328 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2329 return time() < $expiry;
2333 * Get the user's e-mail address
2334 * @return string User's email address
2336 public function getEmail() {
2338 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
2339 return $this->mEmail
;
2343 * Get the timestamp of the user's e-mail authentication
2344 * @return string TS_MW timestamp
2346 public function getEmailAuthenticationTimestamp() {
2348 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2349 return $this->mEmailAuthenticated
;
2353 * Set the user's e-mail address
2354 * @param string $str New e-mail address
2356 public function setEmail( $str ) {
2358 if ( $str == $this->mEmail
) {
2361 $this->mEmail
= $str;
2362 $this->invalidateEmail();
2363 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
2367 * Set the user's e-mail address and a confirmation mail if needed.
2370 * @param string $str New e-mail address
2373 public function setEmailWithConfirmation( $str ) {
2374 global $wgEnableEmail, $wgEmailAuthentication;
2376 if ( !$wgEnableEmail ) {
2377 return Status
::newFatal( 'emaildisabled' );
2380 $oldaddr = $this->getEmail();
2381 if ( $str === $oldaddr ) {
2382 return Status
::newGood( true );
2385 $this->setEmail( $str );
2387 if ( $str !== '' && $wgEmailAuthentication ) {
2388 // Send a confirmation request to the new address if needed
2389 $type = $oldaddr != '' ?
'changed' : 'set';
2390 $result = $this->sendConfirmationMail( $type );
2391 if ( $result->isGood() ) {
2392 // Say the the caller that a confirmation mail has been sent
2393 $result->value
= 'eauth';
2396 $result = Status
::newGood( true );
2403 * Get the user's real name
2404 * @return string User's real name
2406 public function getRealName() {
2407 if ( !$this->isItemLoaded( 'realname' ) ) {
2411 return $this->mRealName
;
2415 * Set the user's real name
2416 * @param string $str New real name
2418 public function setRealName( $str ) {
2420 $this->mRealName
= $str;
2424 * Get the user's current setting for a given option.
2426 * @param string $oname The option to check
2427 * @param string $defaultOverride A default value returned if the option does not exist
2428 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2429 * @return string User's current value for the option
2430 * @see getBoolOption()
2431 * @see getIntOption()
2433 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2434 global $wgHiddenPrefs;
2435 $this->loadOptions();
2437 # We want 'disabled' preferences to always behave as the default value for
2438 # users, even if they have set the option explicitly in their settings (ie they
2439 # set it, and then it was disabled removing their ability to change it). But
2440 # we don't want to erase the preferences in the database in case the preference
2441 # is re-enabled again. So don't touch $mOptions, just override the returned value
2442 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2443 return self
::getDefaultOption( $oname );
2446 if ( array_key_exists( $oname, $this->mOptions
) ) {
2447 return $this->mOptions
[$oname];
2449 return $defaultOverride;
2454 * Get all user's options
2458 public function getOptions() {
2459 global $wgHiddenPrefs;
2460 $this->loadOptions();
2461 $options = $this->mOptions
;
2463 # We want 'disabled' preferences to always behave as the default value for
2464 # users, even if they have set the option explicitly in their settings (ie they
2465 # set it, and then it was disabled removing their ability to change it). But
2466 # we don't want to erase the preferences in the database in case the preference
2467 # is re-enabled again. So don't touch $mOptions, just override the returned value
2468 foreach ( $wgHiddenPrefs as $pref ) {
2469 $default = self
::getDefaultOption( $pref );
2470 if ( $default !== null ) {
2471 $options[$pref] = $default;
2479 * Get the user's current setting for a given option, as a boolean value.
2481 * @param string $oname The option to check
2482 * @return bool User's current value for the option
2485 public function getBoolOption( $oname ) {
2486 return (bool)$this->getOption( $oname );
2490 * Get the user's current setting for a given option, as an integer value.
2492 * @param string $oname The option to check
2493 * @param int $defaultOverride A default value returned if the option does not exist
2494 * @return int User's current value for the option
2497 public function getIntOption( $oname, $defaultOverride = 0 ) {
2498 $val = $this->getOption( $oname );
2500 $val = $defaultOverride;
2502 return intval( $val );
2506 * Set the given option for a user.
2508 * @param string $oname The option to set
2509 * @param mixed $val New value to set
2511 public function setOption( $oname, $val ) {
2512 $this->loadOptions();
2514 // Explicitly NULL values should refer to defaults
2515 if ( is_null( $val ) ) {
2516 $val = self
::getDefaultOption( $oname );
2519 $this->mOptions
[$oname] = $val;
2523 * Get a token stored in the preferences (like the watchlist one),
2524 * resetting it if it's empty (and saving changes).
2526 * @param string $oname The option name to retrieve the token from
2527 * @return string|bool User's current value for the option, or false if this option is disabled.
2528 * @see resetTokenFromOption()
2531 public function getTokenFromOption( $oname ) {
2532 global $wgHiddenPrefs;
2533 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2537 $token = $this->getOption( $oname );
2539 $token = $this->resetTokenFromOption( $oname );
2540 $this->saveSettings();
2546 * Reset a token stored in the preferences (like the watchlist one).
2547 * *Does not* save user's preferences (similarly to setOption()).
2549 * @param string $oname The option name to reset the token in
2550 * @return string|bool New token value, or false if this option is disabled.
2551 * @see getTokenFromOption()
2554 public function resetTokenFromOption( $oname ) {
2555 global $wgHiddenPrefs;
2556 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2560 $token = MWCryptRand
::generateHex( 40 );
2561 $this->setOption( $oname, $token );
2566 * Return a list of the types of user options currently returned by
2567 * User::getOptionKinds().
2569 * Currently, the option kinds are:
2570 * - 'registered' - preferences which are registered in core MediaWiki or
2571 * by extensions using the UserGetDefaultOptions hook.
2572 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2573 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2574 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2575 * be used by user scripts.
2576 * - 'special' - "preferences" that are not accessible via User::getOptions
2577 * or User::setOptions.
2578 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2579 * These are usually legacy options, removed in newer versions.
2581 * The API (and possibly others) use this function to determine the possible
2582 * option types for validation purposes, so make sure to update this when a
2583 * new option kind is added.
2585 * @see User::getOptionKinds
2586 * @return array Option kinds
2588 public static function listOptionKinds() {
2591 'registered-multiselect',
2592 'registered-checkmatrix',
2600 * Return an associative array mapping preferences keys to the kind of a preference they're
2601 * used for. Different kinds are handled differently when setting or reading preferences.
2603 * See User::listOptionKinds for the list of valid option types that can be provided.
2605 * @see User::listOptionKinds
2606 * @param $context IContextSource
2607 * @param array $options assoc. array with options keys to check as keys. Defaults to $this->mOptions.
2608 * @return array the key => kind mapping data
2610 public function getOptionKinds( IContextSource
$context, $options = null ) {
2611 $this->loadOptions();
2612 if ( $options === null ) {
2613 $options = $this->mOptions
;
2616 $prefs = Preferences
::getPreferences( $this, $context );
2619 // Pull out the "special" options, so they don't get converted as
2620 // multiselect or checkmatrix.
2621 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2622 foreach ( $specialOptions as $name => $value ) {
2623 unset( $prefs[$name] );
2626 // Multiselect and checkmatrix options are stored in the database with
2627 // one key per option, each having a boolean value. Extract those keys.
2628 $multiselectOptions = array();
2629 foreach ( $prefs as $name => $info ) {
2630 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2631 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2632 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2633 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2635 foreach ( $opts as $value ) {
2636 $multiselectOptions["$prefix$value"] = true;
2639 unset( $prefs[$name] );
2642 $checkmatrixOptions = array();
2643 foreach ( $prefs as $name => $info ) {
2644 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2645 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2646 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2647 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2648 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2650 foreach ( $columns as $column ) {
2651 foreach ( $rows as $row ) {
2652 $checkmatrixOptions["$prefix-$column-$row"] = true;
2656 unset( $prefs[$name] );
2660 // $value is ignored
2661 foreach ( $options as $key => $value ) {
2662 if ( isset( $prefs[$key] ) ) {
2663 $mapping[$key] = 'registered';
2664 } elseif ( isset( $multiselectOptions[$key] ) ) {
2665 $mapping[$key] = 'registered-multiselect';
2666 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2667 $mapping[$key] = 'registered-checkmatrix';
2668 } elseif ( isset( $specialOptions[$key] ) ) {
2669 $mapping[$key] = 'special';
2670 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2671 $mapping[$key] = 'userjs';
2673 $mapping[$key] = 'unused';
2681 * Reset certain (or all) options to the site defaults
2683 * The optional parameter determines which kinds of preferences will be reset.
2684 * Supported values are everything that can be reported by getOptionKinds()
2685 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2687 * @param array|string $resetKinds which kinds of preferences to reset. Defaults to
2688 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2689 * for backwards-compatibility.
2690 * @param $context IContextSource|null context source used when $resetKinds
2691 * does not contain 'all', passed to getOptionKinds().
2692 * Defaults to RequestContext::getMain() when null.
2694 public function resetOptions(
2695 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2696 IContextSource
$context = null
2699 $defaultOptions = self
::getDefaultOptions();
2701 if ( !is_array( $resetKinds ) ) {
2702 $resetKinds = array( $resetKinds );
2705 if ( in_array( 'all', $resetKinds ) ) {
2706 $newOptions = $defaultOptions;
2708 if ( $context === null ) {
2709 $context = RequestContext
::getMain();
2712 $optionKinds = $this->getOptionKinds( $context );
2713 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2714 $newOptions = array();
2716 // Use default values for the options that should be deleted, and
2717 // copy old values for the ones that shouldn't.
2718 foreach ( $this->mOptions
as $key => $value ) {
2719 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2720 if ( array_key_exists( $key, $defaultOptions ) ) {
2721 $newOptions[$key] = $defaultOptions[$key];
2724 $newOptions[$key] = $value;
2729 $this->mOptions
= $newOptions;
2730 $this->mOptionsLoaded
= true;
2734 * Get the user's preferred date format.
2735 * @return string User's preferred date format
2737 public function getDatePreference() {
2738 // Important migration for old data rows
2739 if ( is_null( $this->mDatePreference
) ) {
2741 $value = $this->getOption( 'date' );
2742 $map = $wgLang->getDatePreferenceMigrationMap();
2743 if ( isset( $map[$value] ) ) {
2744 $value = $map[$value];
2746 $this->mDatePreference
= $value;
2748 return $this->mDatePreference
;
2752 * Determine based on the wiki configuration and the user's options,
2753 * whether this user must be over HTTPS no matter what.
2757 public function requiresHTTPS() {
2758 global $wgSecureLogin;
2759 if ( !$wgSecureLogin ) {
2762 $https = $this->getBoolOption( 'prefershttps' );
2763 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2765 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2772 * Get the user preferred stub threshold
2776 public function getStubThreshold() {
2777 global $wgMaxArticleSize; # Maximum article size, in Kb
2778 $threshold = $this->getIntOption( 'stubthreshold' );
2779 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2780 // If they have set an impossible value, disable the preference
2781 // so we can use the parser cache again.
2788 * Get the permissions this user has.
2789 * @return Array of String permission names
2791 public function getRights() {
2792 if ( is_null( $this->mRights
) ) {
2793 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2794 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2795 // Force reindexation of rights when a hook has unset one of them
2796 $this->mRights
= array_values( array_unique( $this->mRights
) );
2798 return $this->mRights
;
2802 * Get the list of explicit group memberships this user has.
2803 * The implicit * and user groups are not included.
2804 * @return Array of String internal group names
2806 public function getGroups() {
2808 $this->loadGroups();
2809 return $this->mGroups
;
2813 * Get the list of implicit group memberships this user has.
2814 * This includes all explicit groups, plus 'user' if logged in,
2815 * '*' for all accounts, and autopromoted groups
2816 * @param bool $recache Whether to avoid the cache
2817 * @return Array of String internal group names
2819 public function getEffectiveGroups( $recache = false ) {
2820 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2821 wfProfileIn( __METHOD__
);
2822 $this->mEffectiveGroups
= array_unique( array_merge(
2823 $this->getGroups(), // explicit groups
2824 $this->getAutomaticGroups( $recache ) // implicit groups
2826 // Hook for additional groups
2827 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2828 // Force reindexation of groups when a hook has unset one of them
2829 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
2830 wfProfileOut( __METHOD__
);
2832 return $this->mEffectiveGroups
;
2836 * Get the list of implicit group memberships this user has.
2837 * This includes 'user' if logged in, '*' for all accounts,
2838 * and autopromoted groups
2839 * @param bool $recache Whether to avoid the cache
2840 * @return Array of String internal group names
2842 public function getAutomaticGroups( $recache = false ) {
2843 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
2844 wfProfileIn( __METHOD__
);
2845 $this->mImplicitGroups
= array( '*' );
2846 if ( $this->getId() ) {
2847 $this->mImplicitGroups
[] = 'user';
2849 $this->mImplicitGroups
= array_unique( array_merge(
2850 $this->mImplicitGroups
,
2851 Autopromote
::getAutopromoteGroups( $this )
2855 // Assure data consistency with rights/groups,
2856 // as getEffectiveGroups() depends on this function
2857 $this->mEffectiveGroups
= null;
2859 wfProfileOut( __METHOD__
);
2861 return $this->mImplicitGroups
;
2865 * Returns the groups the user has belonged to.
2867 * The user may still belong to the returned groups. Compare with getGroups().
2869 * The function will not return groups the user had belonged to before MW 1.17
2871 * @return array Names of the groups the user has belonged to.
2873 public function getFormerGroups() {
2874 if ( is_null( $this->mFormerGroups
) ) {
2875 $dbr = wfGetDB( DB_MASTER
);
2876 $res = $dbr->select( 'user_former_groups',
2877 array( 'ufg_group' ),
2878 array( 'ufg_user' => $this->mId
),
2880 $this->mFormerGroups
= array();
2881 foreach ( $res as $row ) {
2882 $this->mFormerGroups
[] = $row->ufg_group
;
2885 return $this->mFormerGroups
;
2889 * Get the user's edit count.
2890 * @return int, null for anonymous users
2892 public function getEditCount() {
2893 if ( !$this->getId() ) {
2897 if ( !isset( $this->mEditCount
) ) {
2898 /* Populate the count, if it has not been populated yet */
2899 wfProfileIn( __METHOD__
);
2900 $dbr = wfGetDB( DB_SLAVE
);
2901 // check if the user_editcount field has been initialized
2902 $count = $dbr->selectField(
2903 'user', 'user_editcount',
2904 array( 'user_id' => $this->mId
),
2908 if ( $count === null ) {
2909 // it has not been initialized. do so.
2910 $count = $this->initEditCount();
2912 $this->mEditCount
= $count;
2913 wfProfileOut( __METHOD__
);
2915 return (int)$this->mEditCount
;
2919 * Add the user to the given group.
2920 * This takes immediate effect.
2921 * @param string $group Name of the group to add
2923 public function addGroup( $group ) {
2924 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2925 $dbw = wfGetDB( DB_MASTER
);
2926 if ( $this->getId() ) {
2927 $dbw->insert( 'user_groups',
2929 'ug_user' => $this->getID(),
2930 'ug_group' => $group,
2933 array( 'IGNORE' ) );
2936 $this->loadGroups();
2937 $this->mGroups
[] = $group;
2938 // In case loadGroups was not called before, we now have the right twice.
2939 // Get rid of the duplicate.
2940 $this->mGroups
= array_unique( $this->mGroups
);
2942 // Refresh the groups caches, and clear the rights cache so it will be
2943 // refreshed on the next call to $this->getRights().
2944 $this->getEffectiveGroups( true );
2945 $this->mRights
= null;
2947 $this->invalidateCache();
2951 * Remove the user from the given group.
2952 * This takes immediate effect.
2953 * @param string $group Name of the group to remove
2955 public function removeGroup( $group ) {
2957 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2958 $dbw = wfGetDB( DB_MASTER
);
2959 $dbw->delete( 'user_groups',
2961 'ug_user' => $this->getID(),
2962 'ug_group' => $group,
2964 // Remember that the user was in this group
2965 $dbw->insert( 'user_former_groups',
2967 'ufg_user' => $this->getID(),
2968 'ufg_group' => $group,
2971 array( 'IGNORE' ) );
2973 $this->loadGroups();
2974 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2976 // Refresh the groups caches, and clear the rights cache so it will be
2977 // refreshed on the next call to $this->getRights().
2978 $this->getEffectiveGroups( true );
2979 $this->mRights
= null;
2981 $this->invalidateCache();
2985 * Get whether the user is logged in
2988 public function isLoggedIn() {
2989 return $this->getID() != 0;
2993 * Get whether the user is anonymous
2996 public function isAnon() {
2997 return !$this->isLoggedIn();
3001 * Check if user is allowed to access a feature / make an action
3003 * @internal param \String $varargs permissions to test
3004 * @return boolean: True if user is allowed to perform *any* of the given actions
3008 public function isAllowedAny( /*...*/ ) {
3009 $permissions = func_get_args();
3010 foreach ( $permissions as $permission ) {
3011 if ( $this->isAllowed( $permission ) ) {
3020 * @internal param $varargs string
3021 * @return bool True if the user is allowed to perform *all* of the given actions
3023 public function isAllowedAll( /*...*/ ) {
3024 $permissions = func_get_args();
3025 foreach ( $permissions as $permission ) {
3026 if ( !$this->isAllowed( $permission ) ) {
3034 * Internal mechanics of testing a permission
3035 * @param string $action
3038 public function isAllowed( $action = '' ) {
3039 if ( $action === '' ) {
3040 return true; // In the spirit of DWIM
3042 // Patrolling may not be enabled
3043 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3044 global $wgUseRCPatrol, $wgUseNPPatrol;
3045 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3049 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3050 // by misconfiguration: 0 == 'foo'
3051 return in_array( $action, $this->getRights(), true );
3055 * Check whether to enable recent changes patrol features for this user
3056 * @return boolean: True or false
3058 public function useRCPatrol() {
3059 global $wgUseRCPatrol;
3060 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3064 * Check whether to enable new pages patrol features for this user
3065 * @return bool True or false
3067 public function useNPPatrol() {
3068 global $wgUseRCPatrol, $wgUseNPPatrol;
3070 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3071 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3076 * Get the WebRequest object to use with this object
3078 * @return WebRequest
3080 public function getRequest() {
3081 if ( $this->mRequest
) {
3082 return $this->mRequest
;
3090 * Get the current skin, loading it if required
3091 * @return Skin The current skin
3092 * @todo FIXME: Need to check the old failback system [AV]
3093 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3095 public function getSkin() {
3096 wfDeprecated( __METHOD__
, '1.18' );
3097 return RequestContext
::getMain()->getSkin();
3101 * Get a WatchedItem for this user and $title.
3103 * @since 1.22 $checkRights parameter added
3104 * @param $title Title
3105 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3106 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3107 * @return WatchedItem
3109 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3110 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3112 if ( isset( $this->mWatchedItems
[$key] ) ) {
3113 return $this->mWatchedItems
[$key];
3116 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3117 $this->mWatchedItems
= array();
3120 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3121 return $this->mWatchedItems
[$key];
3125 * Check the watched status of an article.
3126 * @since 1.22 $checkRights parameter added
3127 * @param $title Title of the article to look at
3128 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3129 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3132 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3133 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3138 * @since 1.22 $checkRights parameter added
3139 * @param $title Title of the article to look at
3140 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3141 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3143 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3144 $this->getWatchedItem( $title, $checkRights )->addWatch();
3145 $this->invalidateCache();
3149 * Stop watching an article.
3150 * @since 1.22 $checkRights parameter added
3151 * @param $title Title of the article to look at
3152 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3153 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3155 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3156 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3157 $this->invalidateCache();
3161 * Clear the user's notification timestamp for the given title.
3162 * If e-notif e-mails are on, they will receive notification mails on
3163 * the next change of the page if it's watched etc.
3164 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3165 * @param $title Title of the article to look at
3166 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3168 public function clearNotification( &$title, $oldid = 0 ) {
3169 global $wgUseEnotif, $wgShowUpdatedMarker;
3171 // Do nothing if the database is locked to writes
3172 if ( wfReadOnly() ) {
3176 // Do nothing if not allowed to edit the watchlist
3177 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3181 // If we're working on user's talk page, we should update the talk page message indicator
3182 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3183 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3187 $nextid = $oldid ?
$title->getNextRevisionID( $oldid ) : null;
3189 if ( !$oldid ||
!$nextid ) {
3190 // If we're looking at the latest revision, we should definitely clear it
3191 $this->setNewtalk( false );
3193 // Otherwise we should update its revision, if it's present
3194 if ( $this->getNewtalk() ) {
3195 // Naturally the other one won't clear by itself
3196 $this->setNewtalk( false );
3197 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3202 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3206 if ( $this->isAnon() ) {
3207 // Nothing else to do...
3211 // Only update the timestamp if the page is being watched.
3212 // The query to find out if it is watched is cached both in memcached and per-invocation,
3213 // and when it does have to be executed, it can be on a slave
3214 // If this is the user's newtalk page, we always update the timestamp
3216 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3220 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3224 * Resets all of the given user's page-change notification timestamps.
3225 * If e-notif e-mails are on, they will receive notification mails on
3226 * the next change of any watched page.
3227 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3229 public function clearAllNotifications() {
3230 if ( wfReadOnly() ) {
3234 // Do nothing if not allowed to edit the watchlist
3235 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3239 global $wgUseEnotif, $wgShowUpdatedMarker;
3240 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3241 $this->setNewtalk( false );
3244 $id = $this->getId();
3246 $dbw = wfGetDB( DB_MASTER
);
3247 $dbw->update( 'watchlist',
3248 array( /* SET */ 'wl_notificationtimestamp' => null ),
3249 array( /* WHERE */ 'wl_user' => $id ),
3252 // We also need to clear here the "you have new message" notification for the own user_talk page;
3253 // it's cleared one page view later in WikiPage::doViewUpdates().
3258 * Set this user's options from an encoded string
3259 * @param string $str Encoded options to import
3261 * @deprecated in 1.19 due to removal of user_options from the user table
3263 private function decodeOptions( $str ) {
3264 wfDeprecated( __METHOD__
, '1.19' );
3269 $this->mOptionsLoaded
= true;
3270 $this->mOptionOverrides
= array();
3272 // If an option is not set in $str, use the default value
3273 $this->mOptions
= self
::getDefaultOptions();
3275 $a = explode( "\n", $str );
3276 foreach ( $a as $s ) {
3278 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
3279 $this->mOptions
[$m[1]] = $m[2];
3280 $this->mOptionOverrides
[$m[1]] = $m[2];
3286 * Set a cookie on the user's client. Wrapper for
3287 * WebResponse::setCookie
3288 * @param string $name Name of the cookie to set
3289 * @param string $value Value to set
3290 * @param int $exp Expiration time, as a UNIX time value;
3291 * if 0 or not specified, use the default $wgCookieExpiration
3292 * @param bool $secure
3293 * true: Force setting the secure attribute when setting the cookie
3294 * false: Force NOT setting the secure attribute when setting the cookie
3295 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3296 * @param array $params Array of options sent passed to WebResponse::setcookie()
3298 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3299 $params['secure'] = $secure;
3300 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3304 * Clear a cookie on the user's client
3305 * @param string $name Name of the cookie to clear
3306 * @param bool $secure
3307 * true: Force setting the secure attribute when setting the cookie
3308 * false: Force NOT setting the secure attribute when setting the cookie
3309 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3310 * @param array $params Array of options sent passed to WebResponse::setcookie()
3312 protected function clearCookie( $name, $secure = null, $params = array() ) {
3313 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3317 * Set the default cookies for this session on the user's client.
3319 * @param $request WebRequest object to use; $wgRequest will be used if null
3321 * @param bool $secure Whether to force secure/insecure cookies or use default
3323 public function setCookies( $request = null, $secure = null ) {
3324 if ( $request === null ) {
3325 $request = $this->getRequest();
3329 if ( 0 == $this->mId
) {
3332 if ( !$this->mToken
) {
3333 // When token is empty or NULL generate a new one and then save it to the database
3334 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3335 // Simply by setting every cell in the user_token column to NULL and letting them be
3336 // regenerated as users log back into the wiki.
3338 $this->saveSettings();
3341 'wsUserID' => $this->mId
,
3342 'wsToken' => $this->mToken
,
3343 'wsUserName' => $this->getName()
3346 'UserID' => $this->mId
,
3347 'UserName' => $this->getName(),
3349 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
3350 $cookies['Token'] = $this->mToken
;
3352 $cookies['Token'] = false;
3355 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3357 foreach ( $session as $name => $value ) {
3358 $request->setSessionData( $name, $value );
3360 foreach ( $cookies as $name => $value ) {
3361 if ( $value === false ) {
3362 $this->clearCookie( $name );
3364 $this->setCookie( $name, $value, 0, $secure );
3369 * If wpStickHTTPS was selected, also set an insecure cookie that
3370 * will cause the site to redirect the user to HTTPS, if they access
3371 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3372 * as the one set by centralauth (bug 53538). Also set it to session, or
3373 * standard time setting, based on if rememberme was set.
3375 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3377 if ( ( 1 == $this->getOption( 'rememberpassword' ) ) ) {
3378 $time = 0; // set to $wgCookieExpiration
3385 array( 'prefix' => '' ) // no prefix
3391 * Log this user out.
3393 public function logout() {
3394 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3400 * Clear the user's cookies and session, and reset the instance cache.
3403 public function doLogout() {
3404 $this->clearInstanceCache( 'defaults' );
3406 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3408 $this->clearCookie( 'UserID' );
3409 $this->clearCookie( 'Token' );
3410 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3412 // Remember when user logged out, to prevent seeing cached pages
3413 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3417 * Save this user's settings into the database.
3418 * @todo Only rarely do all these fields need to be set!
3420 public function saveSettings() {
3424 if ( wfReadOnly() ) {
3427 if ( 0 == $this->mId
) {
3431 $this->mTouched
= self
::newTouchedTimestamp();
3432 if ( !$wgAuth->allowSetLocalPassword() ) {
3433 $this->mPassword
= '';
3436 $dbw = wfGetDB( DB_MASTER
);
3437 $dbw->update( 'user',
3439 'user_name' => $this->mName
,
3440 'user_password' => $this->mPassword
,
3441 'user_newpassword' => $this->mNewpassword
,
3442 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3443 'user_real_name' => $this->mRealName
,
3444 'user_email' => $this->mEmail
,
3445 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3446 'user_touched' => $dbw->timestamp( $this->mTouched
),
3447 'user_token' => strval( $this->mToken
),
3448 'user_email_token' => $this->mEmailToken
,
3449 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3450 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires
),
3451 ), array( /* WHERE */
3452 'user_id' => $this->mId
3456 $this->saveOptions();
3458 wfRunHooks( 'UserSaveSettings', array( $this ) );
3459 $this->clearSharedCache();
3460 $this->getUserPage()->invalidateCache();
3464 * If only this user's username is known, and it exists, return the user ID.
3467 public function idForName() {
3468 $s = trim( $this->getName() );
3473 $dbr = wfGetDB( DB_SLAVE
);
3474 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
3475 if ( $id === false ) {
3482 * Add a user to the database, return the user object
3484 * @param string $name Username to add
3485 * @param array $params of Strings Non-default parameters to save to the database as user_* fields:
3486 * - password The user's password hash. Password logins will be disabled if this is omitted.
3487 * - newpassword Hash for a temporary password that has been mailed to the user
3488 * - email The user's email address
3489 * - email_authenticated The email authentication timestamp
3490 * - real_name The user's real name
3491 * - options An associative array of non-default options
3492 * - token Random authentication token. Do not set.
3493 * - registration Registration timestamp. Do not set.
3495 * @return User object, or null if the username already exists
3497 public static function createNew( $name, $params = array() ) {
3500 $user->setToken(); // init token
3501 if ( isset( $params['options'] ) ) {
3502 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3503 unset( $params['options'] );
3505 $dbw = wfGetDB( DB_MASTER
);
3506 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3509 'user_id' => $seqVal,
3510 'user_name' => $name,
3511 'user_password' => $user->mPassword
,
3512 'user_newpassword' => $user->mNewpassword
,
3513 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3514 'user_email' => $user->mEmail
,
3515 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3516 'user_real_name' => $user->mRealName
,
3517 'user_token' => strval( $user->mToken
),
3518 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3519 'user_editcount' => 0,
3520 'user_touched' => $dbw->timestamp( self
::newTouchedTimestamp() ),
3522 foreach ( $params as $name => $value ) {
3523 $fields["user_$name"] = $value;
3525 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3526 if ( $dbw->affectedRows() ) {
3527 $newUser = User
::newFromId( $dbw->insertId() );
3535 * Add this existing user object to the database. If the user already
3536 * exists, a fatal status object is returned, and the user object is
3537 * initialised with the data from the database.
3539 * Previously, this function generated a DB error due to a key conflict
3540 * if the user already existed. Many extension callers use this function
3541 * in code along the lines of:
3543 * $user = User::newFromName( $name );
3544 * if ( !$user->isLoggedIn() ) {
3545 * $user->addToDatabase();
3547 * // do something with $user...
3549 * However, this was vulnerable to a race condition (bug 16020). By
3550 * initialising the user object if the user exists, we aim to support this
3551 * calling sequence as far as possible.
3553 * Note that if the user exists, this function will acquire a write lock,
3554 * so it is still advisable to make the call conditional on isLoggedIn(),
3555 * and to commit the transaction after calling.
3557 * @throws MWException
3560 public function addToDatabase() {
3562 if ( !$this->mToken
) {
3563 $this->setToken(); // init token
3566 $this->mTouched
= self
::newTouchedTimestamp();
3568 $dbw = wfGetDB( DB_MASTER
);
3569 $inWrite = $dbw->writesOrCallbacksPending();
3570 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3571 $dbw->insert( 'user',
3573 'user_id' => $seqVal,
3574 'user_name' => $this->mName
,
3575 'user_password' => $this->mPassword
,
3576 'user_newpassword' => $this->mNewpassword
,
3577 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3578 'user_email' => $this->mEmail
,
3579 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3580 'user_real_name' => $this->mRealName
,
3581 'user_token' => strval( $this->mToken
),
3582 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3583 'user_editcount' => 0,
3584 'user_touched' => $dbw->timestamp( $this->mTouched
),
3588 if ( !$dbw->affectedRows() ) {
3590 // XXX: Get out of REPEATABLE-READ so the SELECT below works.
3591 // Often this case happens early in views before any writes.
3592 // This shows up at least with CentralAuth.
3593 $dbw->commit( __METHOD__
, 'flush' );
3595 $this->mId
= $dbw->selectField( 'user', 'user_id',
3596 array( 'user_name' => $this->mName
), __METHOD__
);
3599 if ( $this->loadFromDatabase() ) {
3604 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3605 "to insert user '{$this->mName}' row, but it was not present in select!" );
3607 return Status
::newFatal( 'userexists' );
3609 $this->mId
= $dbw->insertId();
3611 // Clear instance cache other than user table data, which is already accurate
3612 $this->clearInstanceCache();
3614 $this->saveOptions();
3615 return Status
::newGood();
3619 * If this user is logged-in and blocked,
3620 * block any IP address they've successfully logged in from.
3621 * @return bool A block was spread
3623 public function spreadAnyEditBlock() {
3624 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3625 return $this->spreadBlock();
3631 * If this (non-anonymous) user is blocked,
3632 * block the IP address they've successfully logged in from.
3633 * @return bool A block was spread
3635 protected function spreadBlock() {
3636 wfDebug( __METHOD__
. "()\n" );
3638 if ( $this->mId
== 0 ) {
3642 $userblock = Block
::newFromTarget( $this->getName() );
3643 if ( !$userblock ) {
3647 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3651 * Get whether the user is explicitly blocked from account creation.
3652 * @return bool|Block
3654 public function isBlockedFromCreateAccount() {
3655 $this->getBlockedStatus();
3656 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3657 return $this->mBlock
;
3660 # bug 13611: if the IP address the user is trying to create an account from is
3661 # blocked with createaccount disabled, prevent new account creation there even
3662 # when the user is logged in
3663 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3664 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3666 return $this->mBlockedFromCreateAccount
instanceof Block
&& $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3667 ?
$this->mBlockedFromCreateAccount
3672 * Get whether the user is blocked from using Special:Emailuser.
3675 public function isBlockedFromEmailuser() {
3676 $this->getBlockedStatus();
3677 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3681 * Get whether the user is allowed to create an account.
3684 public function isAllowedToCreateAccount() {
3685 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3689 * Get this user's personal page title.
3691 * @return Title: User's personal page title
3693 public function getUserPage() {
3694 return Title
::makeTitle( NS_USER
, $this->getName() );
3698 * Get this user's talk page title.
3700 * @return Title: User's talk page title
3702 public function getTalkPage() {
3703 $title = $this->getUserPage();
3704 return $title->getTalkPage();
3708 * Determine whether the user is a newbie. Newbies are either
3709 * anonymous IPs, or the most recently created accounts.
3712 public function isNewbie() {
3713 return !$this->isAllowed( 'autoconfirmed' );
3717 * Check to see if the given clear-text password is one of the accepted passwords
3718 * @param string $password user password.
3719 * @return boolean: True if the given password is correct, otherwise False.
3721 public function checkPassword( $password ) {
3722 global $wgAuth, $wgLegacyEncoding;
3725 // Certain authentication plugins do NOT want to save
3726 // domain passwords in a mysql database, so we should
3727 // check this (in case $wgAuth->strict() is false).
3729 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3731 } elseif ( $wgAuth->strict() ) {
3732 // Auth plugin doesn't allow local authentication
3734 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3735 // Auth plugin doesn't allow local authentication for this user name
3738 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
3740 } elseif ( $wgLegacyEncoding ) {
3741 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3742 // Check for this with iconv
3743 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3744 if ( $cp1252Password != $password
3745 && self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
)
3754 * Check if the given clear-text password matches the temporary password
3755 * sent by e-mail for password reset operations.
3757 * @param $plaintext string
3759 * @return boolean: True if matches, false otherwise
3761 public function checkTemporaryPassword( $plaintext ) {
3762 global $wgNewPasswordExpiry;
3765 if ( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
3766 if ( is_null( $this->mNewpassTime
) ) {
3769 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3770 return ( time() < $expiry );
3777 * Alias for getEditToken.
3778 * @deprecated since 1.19, use getEditToken instead.
3780 * @param string|array $salt of Strings Optional function-specific data for hashing
3781 * @param $request WebRequest object to use or null to use $wgRequest
3782 * @return string The new edit token
3784 public function editToken( $salt = '', $request = null ) {
3785 wfDeprecated( __METHOD__
, '1.19' );
3786 return $this->getEditToken( $salt, $request );
3790 * Initialize (if necessary) and return a session token value
3791 * which can be used in edit forms to show that the user's
3792 * login credentials aren't being hijacked with a foreign form
3797 * @param string|array $salt of Strings Optional function-specific data for hashing
3798 * @param $request WebRequest object to use or null to use $wgRequest
3799 * @return string The new edit token
3801 public function getEditToken( $salt = '', $request = null ) {
3802 if ( $request == null ) {
3803 $request = $this->getRequest();
3806 if ( $this->isAnon() ) {
3807 return EDIT_TOKEN_SUFFIX
;
3809 $token = $request->getSessionData( 'wsEditToken' );
3810 if ( $token === null ) {
3811 $token = MWCryptRand
::generateHex( 32 );
3812 $request->setSessionData( 'wsEditToken', $token );
3814 if ( is_array( $salt ) ) {
3815 $salt = implode( '|', $salt );
3817 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
3822 * Generate a looking random token for various uses.
3824 * @return string The new random token
3825 * @deprecated since 1.20: Use MWCryptRand for secure purposes or wfRandomString for pseudo-randomness
3827 public static function generateToken() {
3828 return MWCryptRand
::generateHex( 32 );
3832 * Check given value against the token value stored in the session.
3833 * A match should confirm that the form was submitted from the
3834 * user's own login session, not a form submission from a third-party
3837 * @param string $val Input value to compare
3838 * @param string $salt Optional function-specific data for hashing
3839 * @param WebRequest $request Object to use or null to use $wgRequest
3840 * @return boolean: Whether the token matches
3842 public function matchEditToken( $val, $salt = '', $request = null ) {
3843 $sessionToken = $this->getEditToken( $salt, $request );
3844 if ( $val != $sessionToken ) {
3845 wfDebug( "User::matchEditToken: broken session data\n" );
3847 return $val == $sessionToken;
3851 * Check given value against the token value stored in the session,
3852 * ignoring the suffix.
3854 * @param string $val Input value to compare
3855 * @param string $salt Optional function-specific data for hashing
3856 * @param WebRequest $request object to use or null to use $wgRequest
3857 * @return boolean: Whether the token matches
3859 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3860 $sessionToken = $this->getEditToken( $salt, $request );
3861 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3865 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3866 * mail to the user's given address.
3868 * @param string $type message to send, either "created", "changed" or "set"
3869 * @return Status object
3871 public function sendConfirmationMail( $type = 'created' ) {
3873 $expiration = null; // gets passed-by-ref and defined in next line.
3874 $token = $this->confirmationToken( $expiration );
3875 $url = $this->confirmationTokenUrl( $token );
3876 $invalidateURL = $this->invalidationTokenUrl( $token );
3877 $this->saveSettings();
3879 if ( $type == 'created' ||
$type === false ) {
3880 $message = 'confirmemail_body';
3881 } elseif ( $type === true ) {
3882 $message = 'confirmemail_body_changed';
3884 // Messages: confirmemail_body_changed, confirmemail_body_set
3885 $message = 'confirmemail_body_' . $type;
3888 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3889 wfMessage( $message,
3890 $this->getRequest()->getIP(),
3893 $wgLang->timeanddate( $expiration, false ),
3895 $wgLang->date( $expiration, false ),
3896 $wgLang->time( $expiration, false ) )->text() );
3900 * Send an e-mail to this user's account. Does not check for
3901 * confirmed status or validity.
3903 * @param string $subject Message subject
3904 * @param string $body Message body
3905 * @param string $from Optional From address; if unspecified, default $wgPasswordSender will be used
3906 * @param string $replyto Reply-To address
3909 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3910 if ( is_null( $from ) ) {
3911 global $wgPasswordSender;
3912 $sender = new MailAddress( $wgPasswordSender,
3913 wfMessage( 'emailsender' )->inContentLanguage()->text() );
3915 $sender = new MailAddress( $from );
3918 $to = new MailAddress( $this );
3919 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
3923 * Generate, store, and return a new e-mail confirmation code.
3924 * A hash (unsalted, since it's used as a key) is stored.
3926 * @note Call saveSettings() after calling this function to commit
3927 * this change to the database.
3929 * @param &$expiration \mixed Accepts the expiration time
3930 * @return string New token
3932 protected function confirmationToken( &$expiration ) {
3933 global $wgUserEmailConfirmationTokenExpiry;
3935 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
3936 $expiration = wfTimestamp( TS_MW
, $expires );
3938 $token = MWCryptRand
::generateHex( 32 );
3939 $hash = md5( $token );
3940 $this->mEmailToken
= $hash;
3941 $this->mEmailTokenExpires
= $expiration;
3946 * Return a URL the user can use to confirm their email address.
3947 * @param string $token Accepts the email confirmation token
3948 * @return string New token URL
3950 protected function confirmationTokenUrl( $token ) {
3951 return $this->getTokenUrl( 'ConfirmEmail', $token );
3955 * Return a URL the user can use to invalidate their email address.
3956 * @param string $token Accepts the email confirmation token
3957 * @return string New token URL
3959 protected function invalidationTokenUrl( $token ) {
3960 return $this->getTokenUrl( 'InvalidateEmail', $token );
3964 * Internal function to format the e-mail validation/invalidation URLs.
3965 * This uses a quickie hack to use the
3966 * hardcoded English names of the Special: pages, for ASCII safety.
3968 * @note Since these URLs get dropped directly into emails, using the
3969 * short English names avoids insanely long URL-encoded links, which
3970 * also sometimes can get corrupted in some browsers/mailers
3971 * (bug 6957 with Gmail and Internet Explorer).
3973 * @param string $page Special page
3974 * @param string $token Token
3975 * @return string Formatted URL
3977 protected function getTokenUrl( $page, $token ) {
3978 // Hack to bypass localization of 'Special:'
3979 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
3980 return $title->getCanonicalURL();
3984 * Mark the e-mail address confirmed.
3986 * @note Call saveSettings() after calling this function to commit the change.
3990 public function confirmEmail() {
3991 // Check if it's already confirmed, so we don't touch the database
3992 // and fire the ConfirmEmailComplete hook on redundant confirmations.
3993 if ( !$this->isEmailConfirmed() ) {
3994 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3995 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
4001 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4002 * address if it was already confirmed.
4004 * @note Call saveSettings() after calling this function to commit the change.
4005 * @return bool Returns true
4007 public function invalidateEmail() {
4009 $this->mEmailToken
= null;
4010 $this->mEmailTokenExpires
= null;
4011 $this->setEmailAuthenticationTimestamp( null );
4012 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
4017 * Set the e-mail authentication timestamp.
4018 * @param string $timestamp TS_MW timestamp
4020 public function setEmailAuthenticationTimestamp( $timestamp ) {
4022 $this->mEmailAuthenticated
= $timestamp;
4023 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4027 * Is this user allowed to send e-mails within limits of current
4028 * site configuration?
4031 public function canSendEmail() {
4032 global $wgEnableEmail, $wgEnableUserEmail;
4033 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4036 $canSend = $this->isEmailConfirmed();
4037 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4042 * Is this user allowed to receive e-mails within limits of current
4043 * site configuration?
4046 public function canReceiveEmail() {
4047 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4051 * Is this user's e-mail address valid-looking and confirmed within
4052 * limits of the current site configuration?
4054 * @note If $wgEmailAuthentication is on, this may require the user to have
4055 * confirmed their address by returning a code or using a password
4056 * sent to the address from the wiki.
4060 public function isEmailConfirmed() {
4061 global $wgEmailAuthentication;
4064 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4065 if ( $this->isAnon() ) {
4068 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4071 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4081 * Check whether there is an outstanding request for e-mail confirmation.
4084 public function isEmailConfirmationPending() {
4085 global $wgEmailAuthentication;
4086 return $wgEmailAuthentication &&
4087 !$this->isEmailConfirmed() &&
4088 $this->mEmailToken
&&
4089 $this->mEmailTokenExpires
> wfTimestamp();
4093 * Get the timestamp of account creation.
4095 * @return string|bool|null Timestamp of account creation, false for
4096 * non-existent/anonymous user accounts, or null if existing account
4097 * but information is not in database.
4099 public function getRegistration() {
4100 if ( $this->isAnon() ) {
4104 return $this->mRegistration
;
4108 * Get the timestamp of the first edit
4110 * @return string|bool Timestamp of first edit, or false for
4111 * non-existent/anonymous user accounts.
4113 public function getFirstEditTimestamp() {
4114 if ( $this->getId() == 0 ) {
4115 return false; // anons
4117 $dbr = wfGetDB( DB_SLAVE
);
4118 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4119 array( 'rev_user' => $this->getId() ),
4121 array( 'ORDER BY' => 'rev_timestamp ASC' )
4124 return false; // no edits
4126 return wfTimestamp( TS_MW
, $time );
4130 * Get the permissions associated with a given list of groups
4132 * @param array $groups of Strings List of internal group names
4133 * @return Array of Strings List of permission key names for given groups combined
4135 public static function getGroupPermissions( $groups ) {
4136 global $wgGroupPermissions, $wgRevokePermissions;
4138 // grant every granted permission first
4139 foreach ( $groups as $group ) {
4140 if ( isset( $wgGroupPermissions[$group] ) ) {
4141 $rights = array_merge( $rights,
4142 // array_filter removes empty items
4143 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4146 // now revoke the revoked permissions
4147 foreach ( $groups as $group ) {
4148 if ( isset( $wgRevokePermissions[$group] ) ) {
4149 $rights = array_diff( $rights,
4150 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4153 return array_unique( $rights );
4157 * Get all the groups who have a given permission
4159 * @param string $role Role to check
4160 * @return Array of Strings List of internal group names with the given permission
4162 public static function getGroupsWithPermission( $role ) {
4163 global $wgGroupPermissions;
4164 $allowedGroups = array();
4165 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4166 if ( self
::groupHasPermission( $group, $role ) ) {
4167 $allowedGroups[] = $group;
4170 return $allowedGroups;
4174 * Check, if the given group has the given permission
4176 * If you're wanting to check whether all users have a permission, use
4177 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4181 * @param string $group Group to check
4182 * @param string $role Role to check
4185 public static function groupHasPermission( $group, $role ) {
4186 global $wgGroupPermissions, $wgRevokePermissions;
4187 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4188 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4192 * Check if all users have the given permission
4195 * @param string $right Right to check
4198 public static function isEveryoneAllowed( $right ) {
4199 global $wgGroupPermissions, $wgRevokePermissions;
4200 static $cache = array();
4202 // Use the cached results, except in unit tests which rely on
4203 // being able change the permission mid-request
4204 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4205 return $cache[$right];
4208 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4209 $cache[$right] = false;
4213 // If it's revoked anywhere, then everyone doesn't have it
4214 foreach ( $wgRevokePermissions as $rights ) {
4215 if ( isset( $rights[$right] ) && $rights[$right] ) {
4216 $cache[$right] = false;
4221 // Allow extensions (e.g. OAuth) to say false
4222 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4223 $cache[$right] = false;
4227 $cache[$right] = true;
4232 * Get the localized descriptive name for a group, if it exists
4234 * @param string $group Internal group name
4235 * @return string Localized descriptive group name
4237 public static function getGroupName( $group ) {
4238 $msg = wfMessage( "group-$group" );
4239 return $msg->isBlank() ?
$group : $msg->text();
4243 * Get the localized descriptive name for a member of a group, if it exists
4245 * @param string $group Internal group name
4246 * @param string $username Username for gender (since 1.19)
4247 * @return string Localized name for group member
4249 public static function getGroupMember( $group, $username = '#' ) {
4250 $msg = wfMessage( "group-$group-member", $username );
4251 return $msg->isBlank() ?
$group : $msg->text();
4255 * Return the set of defined explicit groups.
4256 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4257 * are not included, as they are defined automatically, not in the database.
4258 * @return Array of internal group names
4260 public static function getAllGroups() {
4261 global $wgGroupPermissions, $wgRevokePermissions;
4263 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4264 self
::getImplicitGroups()
4269 * Get a list of all available permissions.
4270 * @return Array of permission names
4272 public static function getAllRights() {
4273 if ( self
::$mAllRights === false ) {
4274 global $wgAvailableRights;
4275 if ( count( $wgAvailableRights ) ) {
4276 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4278 self
::$mAllRights = self
::$mCoreRights;
4280 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
4282 return self
::$mAllRights;
4286 * Get a list of implicit groups
4287 * @return Array of Strings Array of internal group names
4289 public static function getImplicitGroups() {
4290 global $wgImplicitGroups;
4291 $groups = $wgImplicitGroups;
4292 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
4297 * Get the title of a page describing a particular group
4299 * @param string $group Internal group name
4300 * @return Title|bool Title of the page if it exists, false otherwise
4302 public static function getGroupPage( $group ) {
4303 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4304 if ( $msg->exists() ) {
4305 $title = Title
::newFromText( $msg->text() );
4306 if ( is_object( $title ) ) {
4314 * Create a link to the group in HTML, if available;
4315 * else return the group name.
4317 * @param string $group Internal name of the group
4318 * @param string $text The text of the link
4319 * @return string HTML link to the group
4321 public static function makeGroupLinkHTML( $group, $text = '' ) {
4322 if ( $text == '' ) {
4323 $text = self
::getGroupName( $group );
4325 $title = self
::getGroupPage( $group );
4327 return Linker
::link( $title, htmlspecialchars( $text ) );
4334 * Create a link to the group in Wikitext, if available;
4335 * else return the group name.
4337 * @param string $group Internal name of the group
4338 * @param string $text The text of the link
4339 * @return string Wikilink to the group
4341 public static function makeGroupLinkWiki( $group, $text = '' ) {
4342 if ( $text == '' ) {
4343 $text = self
::getGroupName( $group );
4345 $title = self
::getGroupPage( $group );
4347 $page = $title->getPrefixedText();
4348 return "[[$page|$text]]";
4355 * Returns an array of the groups that a particular group can add/remove.
4357 * @param string $group the group to check for whether it can add/remove
4358 * @return Array array( 'add' => array( addablegroups ),
4359 * 'remove' => array( removablegroups ),
4360 * 'add-self' => array( addablegroups to self),
4361 * 'remove-self' => array( removable groups from self) )
4363 public static function changeableByGroup( $group ) {
4364 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4366 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
4367 if ( empty( $wgAddGroups[$group] ) ) {
4368 // Don't add anything to $groups
4369 } elseif ( $wgAddGroups[$group] === true ) {
4370 // You get everything
4371 $groups['add'] = self
::getAllGroups();
4372 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4373 $groups['add'] = $wgAddGroups[$group];
4376 // Same thing for remove
4377 if ( empty( $wgRemoveGroups[$group] ) ) {
4378 } elseif ( $wgRemoveGroups[$group] === true ) {
4379 $groups['remove'] = self
::getAllGroups();
4380 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4381 $groups['remove'] = $wgRemoveGroups[$group];
4384 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4385 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4386 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4387 if ( is_int( $key ) ) {
4388 $wgGroupsAddToSelf['user'][] = $value;
4393 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4394 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4395 if ( is_int( $key ) ) {
4396 $wgGroupsRemoveFromSelf['user'][] = $value;
4401 // Now figure out what groups the user can add to him/herself
4402 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4403 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4404 // No idea WHY this would be used, but it's there
4405 $groups['add-self'] = User
::getAllGroups();
4406 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4407 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4410 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4411 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4412 $groups['remove-self'] = User
::getAllGroups();
4413 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4414 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4421 * Returns an array of groups that this user can add and remove
4422 * @return Array array( 'add' => array( addablegroups ),
4423 * 'remove' => array( removablegroups ),
4424 * 'add-self' => array( addablegroups to self),
4425 * 'remove-self' => array( removable groups from self) )
4427 public function changeableGroups() {
4428 if ( $this->isAllowed( 'userrights' ) ) {
4429 // This group gives the right to modify everything (reverse-
4430 // compatibility with old "userrights lets you change
4432 // Using array_merge to make the groups reindexed
4433 $all = array_merge( User
::getAllGroups() );
4437 'add-self' => array(),
4438 'remove-self' => array()
4442 // Okay, it's not so simple, we will have to go through the arrays
4445 'remove' => array(),
4446 'add-self' => array(),
4447 'remove-self' => array()
4449 $addergroups = $this->getEffectiveGroups();
4451 foreach ( $addergroups as $addergroup ) {
4452 $groups = array_merge_recursive(
4453 $groups, $this->changeableByGroup( $addergroup )
4455 $groups['add'] = array_unique( $groups['add'] );
4456 $groups['remove'] = array_unique( $groups['remove'] );
4457 $groups['add-self'] = array_unique( $groups['add-self'] );
4458 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4464 * Increment the user's edit-count field.
4465 * Will have no effect for anonymous users.
4467 public function incEditCount() {
4468 if ( !$this->isAnon() ) {
4469 $dbw = wfGetDB( DB_MASTER
);
4472 array( 'user_editcount=user_editcount+1' ),
4473 array( 'user_id' => $this->getId() ),
4477 // Lazy initialization check...
4478 if ( $dbw->affectedRows() == 0 ) {
4479 // Now here's a goddamn hack...
4480 $dbr = wfGetDB( DB_SLAVE
);
4481 if ( $dbr !== $dbw ) {
4482 // If we actually have a slave server, the count is
4483 // at least one behind because the current transaction
4484 // has not been committed and replicated.
4485 $this->initEditCount( 1 );
4487 // But if DB_SLAVE is selecting the master, then the
4488 // count we just read includes the revision that was
4489 // just added in the working transaction.
4490 $this->initEditCount();
4494 // edit count in user cache too
4495 $this->invalidateCache();
4499 * Initialize user_editcount from data out of the revision table
4501 * @param $add Integer Edits to add to the count from the revision table
4502 * @return integer Number of edits
4504 protected function initEditCount( $add = 0 ) {
4505 // Pull from a slave to be less cruel to servers
4506 // Accuracy isn't the point anyway here
4507 $dbr = wfGetDB( DB_SLAVE
);
4508 $count = (int)$dbr->selectField(
4511 array( 'rev_user' => $this->getId() ),
4514 $count = $count +
$add;
4516 $dbw = wfGetDB( DB_MASTER
);
4519 array( 'user_editcount' => $count ),
4520 array( 'user_id' => $this->getId() ),
4528 * Get the description of a given right
4530 * @param string $right Right to query
4531 * @return string Localized description of the right
4533 public static function getRightDescription( $right ) {
4534 $key = "right-$right";
4535 $msg = wfMessage( $key );
4536 return $msg->isBlank() ?
$right : $msg->text();
4540 * Make an old-style password hash
4542 * @param string $password Plain-text password
4543 * @param string $userId User ID
4544 * @return string Password hash
4546 public static function oldCrypt( $password, $userId ) {
4547 global $wgPasswordSalt;
4548 if ( $wgPasswordSalt ) {
4549 return md5( $userId . '-' . md5( $password ) );
4551 return md5( $password );
4556 * Make a new-style password hash
4558 * @param string $password Plain-text password
4559 * @param bool|string $salt Optional salt, may be random or the user ID.
4560 * If unspecified or false, will generate one automatically
4561 * @return string Password hash
4563 public static function crypt( $password, $salt = false ) {
4564 global $wgPasswordSalt;
4567 if ( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4571 if ( $wgPasswordSalt ) {
4572 if ( $salt === false ) {
4573 $salt = MWCryptRand
::generateHex( 8 );
4575 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4577 return ':A:' . md5( $password );
4582 * Compare a password hash with a plain-text password. Requires the user
4583 * ID if there's a chance that the hash is an old-style hash.
4585 * @param string $hash Password hash
4586 * @param string $password Plain-text password to compare
4587 * @param string|bool $userId User ID for old-style password salt
4591 public static function comparePasswords( $hash, $password, $userId = false ) {
4592 $type = substr( $hash, 0, 3 );
4595 if ( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4599 if ( $type == ':A:' ) {
4601 return md5( $password ) === substr( $hash, 3 );
4602 } elseif ( $type == ':B:' ) {
4604 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4605 return md5( $salt . '-' . md5( $password ) ) === $realHash;
4608 return self
::oldCrypt( $password, $userId ) === $hash;
4613 * Add a newuser log entry for this user.
4614 * Before 1.19 the return value was always true.
4616 * @param string|bool $action account creation type.
4617 * - String, one of the following values:
4618 * - 'create' for an anonymous user creating an account for himself.
4619 * This will force the action's performer to be the created user itself,
4620 * no matter the value of $wgUser
4621 * - 'create2' for a logged in user creating an account for someone else
4622 * - 'byemail' when the created user will receive its password by e-mail
4623 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4624 * - Boolean means whether the account was created by e-mail (deprecated):
4625 * - true will be converted to 'byemail'
4626 * - false will be converted to 'create' if this object is the same as
4627 * $wgUser and to 'create2' otherwise
4629 * @param string $reason user supplied reason
4631 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4633 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4634 global $wgUser, $wgNewUserLog;
4635 if ( empty( $wgNewUserLog ) ) {
4636 return true; // disabled
4639 if ( $action === true ) {
4640 $action = 'byemail';
4641 } elseif ( $action === false ) {
4642 if ( $this->getName() == $wgUser->getName() ) {
4645 $action = 'create2';
4649 if ( $action === 'create' ||
$action === 'autocreate' ) {
4652 $performer = $wgUser;
4655 $logEntry = new ManualLogEntry( 'newusers', $action );
4656 $logEntry->setPerformer( $performer );
4657 $logEntry->setTarget( $this->getUserPage() );
4658 $logEntry->setComment( $reason );
4659 $logEntry->setParameters( array(
4660 '4::userid' => $this->getId(),
4662 $logid = $logEntry->insert();
4664 if ( $action !== 'autocreate' ) {
4665 $logEntry->publish( $logid );
4672 * Add an autocreate newuser log entry for this user
4673 * Used by things like CentralAuth and perhaps other authplugins.
4674 * Consider calling addNewUserLogEntry() directly instead.
4678 public function addNewUserLogEntryAutoCreate() {
4679 $this->addNewUserLogEntry( 'autocreate' );
4685 * Load the user options either from cache, the database or an array
4687 * @param array $data Rows for the current user out of the user_properties table
4689 protected function loadOptions( $data = null ) {
4694 if ( $this->mOptionsLoaded
) {
4698 $this->mOptions
= self
::getDefaultOptions();
4700 if ( !$this->getId() ) {
4701 // For unlogged-in users, load language/variant options from request.
4702 // There's no need to do it for logged-in users: they can set preferences,
4703 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4704 // so don't override user's choice (especially when the user chooses site default).
4705 $variant = $wgContLang->getDefaultVariant();
4706 $this->mOptions
['variant'] = $variant;
4707 $this->mOptions
['language'] = $variant;
4708 $this->mOptionsLoaded
= true;
4712 // Maybe load from the object
4713 if ( !is_null( $this->mOptionOverrides
) ) {
4714 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4715 foreach ( $this->mOptionOverrides
as $key => $value ) {
4716 $this->mOptions
[$key] = $value;
4719 if ( !is_array( $data ) ) {
4720 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4721 // Load from database
4722 $dbr = wfGetDB( DB_SLAVE
);
4724 $res = $dbr->select(
4726 array( 'up_property', 'up_value' ),
4727 array( 'up_user' => $this->getId() ),
4731 $this->mOptionOverrides
= array();
4733 foreach ( $res as $row ) {
4734 $data[$row->up_property
] = $row->up_value
;
4737 foreach ( $data as $property => $value ) {
4738 $this->mOptionOverrides
[$property] = $value;
4739 $this->mOptions
[$property] = $value;
4743 $this->mOptionsLoaded
= true;
4745 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
4751 protected function saveOptions() {
4752 $this->loadOptions();
4754 // Not using getOptions(), to keep hidden preferences in database
4755 $saveOptions = $this->mOptions
;
4757 // Allow hooks to abort, for instance to save to a global profile.
4758 // Reset options to default state before saving.
4759 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4763 $userId = $this->getId();
4764 $insert_rows = array();
4765 foreach ( $saveOptions as $key => $value ) {
4766 // Don't bother storing default values
4767 $defaultOption = self
::getDefaultOption( $key );
4768 if ( ( is_null( $defaultOption ) &&
4769 !( $value === false ||
is_null( $value ) ) ) ||
4770 $value != $defaultOption
4772 $insert_rows[] = array(
4773 'up_user' => $userId,
4774 'up_property' => $key,
4775 'up_value' => $value,
4780 $dbw = wfGetDB( DB_MASTER
);
4781 // Find and delete any prior preference rows...
4782 $res = $dbw->select( 'user_properties',
4783 array( 'up_property' ), array( 'up_user' => $userId ), __METHOD__
);
4784 $priorKeys = array();
4785 foreach ( $res as $row ) {
4786 $priorKeys[] = $row->up_property
;
4788 if ( count( $priorKeys ) ) {
4789 // Do the DELETE by PRIMARY KEY for prior rows. A very large portion of
4790 // calls to this function are for setting 'rememberpassword' for new accounts.
4791 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4792 // causes gap locks on [max user ID,+infinity) which causes high contention since
4793 // updates will pile up on each other as they are for higher (newer) user IDs.
4794 $dbw->delete( 'user_properties',
4795 array( 'up_user' => $userId, 'up_property' => $priorKeys ), __METHOD__
);
4797 // Insert the new preference rows
4798 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
4802 * Provide an array of HTML5 attributes to put on an input element
4803 * intended for the user to enter a new password. This may include
4804 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4806 * Do *not* use this when asking the user to enter his current password!
4807 * Regardless of configuration, users may have invalid passwords for whatever
4808 * reason (e.g., they were set before requirements were tightened up).
4809 * Only use it when asking for a new password, like on account creation or
4812 * Obviously, you still need to do server-side checking.
4814 * NOTE: A combination of bugs in various browsers means that this function
4815 * actually just returns array() unconditionally at the moment. May as
4816 * well keep it around for when the browser bugs get fixed, though.
4818 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4820 * @return array Array of HTML attributes suitable for feeding to
4821 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4822 * That will get confused by the boolean attribute syntax used.)
4824 public static function passwordChangeInputAttribs() {
4825 global $wgMinimalPasswordLength;
4827 if ( $wgMinimalPasswordLength == 0 ) {
4831 # Note that the pattern requirement will always be satisfied if the
4832 # input is empty, so we need required in all cases.
4834 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4835 # if e-mail confirmation is being used. Since HTML5 input validation
4836 # is b0rked anyway in some browsers, just return nothing. When it's
4837 # re-enabled, fix this code to not output required for e-mail
4839 #$ret = array( 'required' );
4842 # We can't actually do this right now, because Opera 9.6 will print out
4843 # the entered password visibly in its error message! When other
4844 # browsers add support for this attribute, or Opera fixes its support,
4845 # we can add support with a version check to avoid doing this on Opera
4846 # versions where it will be a problem. Reported to Opera as
4847 # DSK-262266, but they don't have a public bug tracker for us to follow.
4849 if ( $wgMinimalPasswordLength > 1 ) {
4850 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4851 $ret['title'] = wfMessage( 'passwordtooshort' )
4852 ->numParams( $wgMinimalPasswordLength )->text();
4860 * Return the list of user fields that should be selected to create
4861 * a new user object.
4864 public static function selectFields() {
4871 'user_newpass_time',
4875 'user_email_authenticated',
4877 'user_email_token_expires',
4878 'user_password_expires',
4879 'user_registration',
4885 * Factory function for fatal permission-denied errors
4888 * @param string $permission User right required
4891 static function newFatalPermissionDeniedStatus( $permission ) {
4894 $groups = array_map(
4895 array( 'User', 'makeGroupLinkWiki' ),
4896 User
::getGroupsWithPermission( $permission )
4900 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4902 return Status
::newFatal( 'badaccess-group0' );