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;
701 * Given unvalidated password input, return error message on failure.
703 * @param string $password Desired password
704 * @return mixed: true on success, string or array of error message on failure
706 public function getPasswordValidity( $password ) {
707 global $wgMinimalPasswordLength, $wgContLang;
709 static $blockedLogins = array(
710 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
711 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
714 $result = false; //init $result to false for the internal checks
716 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
720 if ( $result === false ) {
721 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
722 return 'passwordtooshort';
723 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
724 return 'password-name-match';
725 } elseif ( isset( $blockedLogins[$this->getName()] ) && $password == $blockedLogins[$this->getName()] ) {
726 return 'password-login-forbidden';
728 //it seems weird returning true here, but this is because of the
729 //initialization of $result to false above. If the hook is never run or it
730 //doesn't modify $result, then we will likely get down into this if with
734 } elseif ( $result === true ) {
737 return $result; //the isValidPassword hook set a string $result and returned true
742 * Expire a user's password
744 * @param $ts Mixed: optional timestamp to convert, default 0 for the current time
746 public function expirePassword( $ts = 0 ) {
748 $timestamp = wfTimestamp( TS_MW
, $ts );
749 $this->mPasswordExpires
= $timestamp;
750 $this->saveSettings();
754 * Clear the password expiration for a user
756 * @param bool $load ensure user object is loaded first
758 public function resetPasswordExpiration( $load = true ) {
759 global $wgPasswordExpirationDays;
764 if ( $wgPasswordExpirationDays ) {
765 $newExpire = wfTimestamp(
767 time() +
( $wgPasswordExpirationDays * 24 * 3600 )
770 // Give extensions a chance to force an expiration
771 wfRunHooks( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
772 $this->mPasswordExpires
= $newExpire;
776 * Check if the user's password is expired.
777 * TODO: Put this and password length into a PasswordPolicy object
779 * @return string|bool The expiration type, or false if not expired
780 * hard: A password change is required to login
781 * soft: Allow login, but encourage password change
782 * false: Password is not expired
784 public function getPasswordExpired() {
785 global $wgPasswordExpireGrace;
787 $now = wfTimestamp();
788 $expiration = $this->getPasswordExpireDate();
789 $expUnix = wfTimestamp( TS_UNIX
, $expiration );
790 if ( $expiration !== null && $expUnix < $now ) {
791 $expired = ( $expUnix +
$wgPasswordExpireGrace < $now ) ?
'hard' : 'soft';
797 * Get this user's password expiration date. Since this may be using
798 * the cached User object, we assume that whatever mechanism is setting
799 * the expiration date is also expiring the User cache.
801 * @return string|false the datestamp of the expiration, or null if not set
803 public function getPasswordExpireDate() {
805 return $this->mPasswordExpires
;
809 * Does a string look like an e-mail address?
811 * This validates an email address using an HTML5 specification found at:
812 * http://www.whatwg.org/html/states-of-the-type-attribute.html#valid-e-mail-address
813 * Which as of 2011-01-24 says:
815 * A valid e-mail address is a string that matches the ABNF production
816 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
817 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
820 * This function is an implementation of the specification as requested in
823 * Client-side forms will use the same standard validation rules via JS or
824 * HTML 5 validation; additional restrictions can be enforced server-side
825 * by extensions via the 'isValidEmailAddr' hook.
827 * Note that this validation doesn't 100% match RFC 2822, but is believed
828 * to be liberal enough for wide use. Some invalid addresses will still
829 * pass validation here.
831 * @param string $addr E-mail address
833 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
835 public static function isValidEmailAddr( $addr ) {
836 wfDeprecated( __METHOD__
, '1.18' );
837 return Sanitizer
::validateEmail( $addr );
841 * Given unvalidated user input, return a canonical username, or false if
842 * the username is invalid.
843 * @param string $name User input
844 * @param string|bool $validate type of validation to use:
845 * - false No validation
846 * - 'valid' Valid for batch processes
847 * - 'usable' Valid for batch processes and login
848 * - 'creatable' Valid for batch processes, login and account creation
850 * @throws MWException
851 * @return bool|string
853 public static function getCanonicalName( $name, $validate = 'valid' ) {
854 // Force usernames to capital
856 $name = $wgContLang->ucfirst( $name );
858 # Reject names containing '#'; these will be cleaned up
859 # with title normalisation, but then it's too late to
861 if ( strpos( $name, '#' ) !== false ) {
865 // Clean up name according to title rules
866 $t = ( $validate === 'valid' ) ?
867 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
868 // Check for invalid titles
869 if ( is_null( $t ) ) {
873 // Reject various classes of invalid names
875 $name = $wgAuth->getCanonicalName( $t->getText() );
877 switch ( $validate ) {
881 if ( !User
::isValidUserName( $name ) ) {
886 if ( !User
::isUsableName( $name ) ) {
891 if ( !User
::isCreatableName( $name ) ) {
896 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
902 * Count the number of edits of a user
904 * @param int $uid User ID to check
905 * @return int The user's edit count
907 * @deprecated since 1.21 in favour of User::getEditCount
909 public static function edits( $uid ) {
910 wfDeprecated( __METHOD__
, '1.21' );
911 $user = self
::newFromId( $uid );
912 return $user->getEditCount();
916 * Return a random password.
918 * @return string New random password
920 public static function randomPassword() {
921 global $wgMinimalPasswordLength;
922 // Decide the final password length based on our min password length, stopping at a minimum of 10 chars
923 $length = max( 10, $wgMinimalPasswordLength );
924 // Multiply by 1.25 to get the number of hex characters we need
925 $length = $length * 1.25;
926 // Generate random hex chars
927 $hex = MWCryptRand
::generateHex( $length );
928 // Convert from base 16 to base 32 to get a proper password like string
929 return wfBaseConvert( $hex, 16, 32 );
933 * Set cached properties to default.
935 * @note This no longer clears uncached lazy-initialised properties;
936 * the constructor does that instead.
938 * @param $name string|bool
940 public function loadDefaults( $name = false ) {
941 wfProfileIn( __METHOD__
);
944 $this->mName
= $name;
945 $this->mRealName
= '';
946 $this->mPassword
= $this->mNewpassword
= '';
947 $this->mNewpassTime
= null;
949 $this->mOptionOverrides
= null;
950 $this->mOptionsLoaded
= false;
952 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
953 if ( $loggedOut !== null ) {
954 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
956 $this->mTouched
= '1'; # Allow any pages to be cached
959 $this->mToken
= null; // Don't run cryptographic functions till we need a token
960 $this->mEmailAuthenticated
= null;
961 $this->mEmailToken
= '';
962 $this->mEmailTokenExpires
= null;
963 $this->mPasswordExpires
= null;
964 $this->resetPasswordExpiration( false );
965 $this->mRegistration
= wfTimestamp( TS_MW
);
966 $this->mGroups
= array();
968 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
970 wfProfileOut( __METHOD__
);
974 * Return whether an item has been loaded.
976 * @param string $item item to check. Current possibilities:
980 * @param string $all 'all' to check if the whole object has been loaded
981 * or any other string to check if only the item is available (e.g.
985 public function isItemLoaded( $item, $all = 'all' ) {
986 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
987 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
991 * Set that an item has been loaded
993 * @param string $item
995 protected function setItemLoaded( $item ) {
996 if ( is_array( $this->mLoadedItems
) ) {
997 $this->mLoadedItems
[$item] = true;
1002 * Load user data from the session or login cookie.
1003 * @return bool True if the user is logged in, false otherwise.
1005 private function loadFromSession() {
1007 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
1008 if ( $result !== null ) {
1012 $request = $this->getRequest();
1014 $cookieId = $request->getCookie( 'UserID' );
1015 $sessId = $request->getSessionData( 'wsUserID' );
1017 if ( $cookieId !== null ) {
1018 $sId = intval( $cookieId );
1019 if ( $sessId !== null && $cookieId != $sessId ) {
1020 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1021 cookie user ID ($sId) don't match!" );
1024 $request->setSessionData( 'wsUserID', $sId );
1025 } elseif ( $sessId !== null && $sessId != 0 ) {
1031 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1032 $sName = $request->getSessionData( 'wsUserName' );
1033 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1034 $sName = $request->getCookie( 'UserName' );
1035 $request->setSessionData( 'wsUserName', $sName );
1040 $proposedUser = User
::newFromId( $sId );
1041 if ( !$proposedUser->isLoggedIn() ) {
1046 global $wgBlockDisablesLogin;
1047 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1048 // User blocked and we've disabled blocked user logins
1052 if ( $request->getSessionData( 'wsToken' ) ) {
1053 $passwordCorrect = ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1055 } elseif ( $request->getCookie( 'Token' ) ) {
1056 # Get the token from DB/cache and clean it up to remove garbage padding.
1057 # This deals with historical problems with bugs and the default column value.
1058 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1059 // Make comparison in constant time (bug 61346)
1060 $passwordCorrect = strlen( $token ) && $this->compareSecrets( $token, $request->getCookie( 'Token' ) );
1063 // No session or persistent login cookie
1067 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1068 $this->loadFromUserObject( $proposedUser );
1069 $request->setSessionData( 'wsToken', $this->mToken
);
1070 wfDebug( "User: logged in from $from\n" );
1073 // Invalid credentials
1074 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1080 * A comparison of two strings, not vulnerable to timing attacks
1081 * @param string $answer the secret string that you are comparing against.
1082 * @param string $test compare this string to the $answer.
1083 * @return bool True if the strings are the same, false otherwise
1085 protected function compareSecrets( $answer, $test ) {
1086 if ( strlen( $answer ) !== strlen( $test ) ) {
1087 $passwordCorrect = false;
1090 for ( $i = 0; $i < strlen( $answer ); $i++
) {
1091 $result |
= ord( $answer{$i} ) ^
ord( $test{$i} );
1093 $passwordCorrect = ( $result == 0 );
1095 return $passwordCorrect;
1099 * Load user and user_group data from the database.
1100 * $this->mId must be set, this is how the user is identified.
1102 * @return bool True if the user exists, false if the user is anonymous
1104 public function loadFromDatabase() {
1106 $this->mId
= intval( $this->mId
);
1109 if ( !$this->mId
) {
1110 $this->loadDefaults();
1114 $dbr = wfGetDB( DB_MASTER
);
1115 $s = $dbr->selectRow( 'user', self
::selectFields(), array( 'user_id' => $this->mId
), __METHOD__
);
1117 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1119 if ( $s !== false ) {
1120 // Initialise user table data
1121 $this->loadFromRow( $s );
1122 $this->mGroups
= null; // deferred
1123 $this->getEditCount(); // revalidation for nulls
1128 $this->loadDefaults();
1134 * Initialize this object from a row from the user table.
1136 * @param stdClass $row Row from the user table to load.
1137 * @param array $data Further user data to load into the object
1139 * user_groups Array with groups out of the user_groups table
1140 * user_properties Array with properties out of the user_properties table
1142 public function loadFromRow( $row, $data = null ) {
1145 $this->mGroups
= null; // deferred
1147 if ( isset( $row->user_name
) ) {
1148 $this->mName
= $row->user_name
;
1149 $this->mFrom
= 'name';
1150 $this->setItemLoaded( 'name' );
1155 if ( isset( $row->user_real_name
) ) {
1156 $this->mRealName
= $row->user_real_name
;
1157 $this->setItemLoaded( 'realname' );
1162 if ( isset( $row->user_id
) ) {
1163 $this->mId
= intval( $row->user_id
);
1164 $this->mFrom
= 'id';
1165 $this->setItemLoaded( 'id' );
1170 if ( isset( $row->user_editcount
) ) {
1171 $this->mEditCount
= $row->user_editcount
;
1176 if ( isset( $row->user_password
) ) {
1177 $this->mPassword
= $row->user_password
;
1178 $this->mNewpassword
= $row->user_newpassword
;
1179 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1180 $this->mEmail
= $row->user_email
;
1181 if ( isset( $row->user_options
) ) {
1182 $this->decodeOptions( $row->user_options
);
1184 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1185 $this->mToken
= $row->user_token
;
1186 if ( $this->mToken
== '' ) {
1187 $this->mToken
= null;
1189 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1190 $this->mEmailToken
= $row->user_email_token
;
1191 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1192 $this->mPasswordExpires
= wfTimestampOrNull( TS_MW
, $row->user_password_expires
);
1193 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1199 $this->mLoadedItems
= true;
1202 if ( is_array( $data ) ) {
1203 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1204 $this->mGroups
= $data['user_groups'];
1206 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1207 $this->loadOptions( $data['user_properties'] );
1213 * Load the data for this user object from another user object.
1217 protected function loadFromUserObject( $user ) {
1219 $user->loadGroups();
1220 $user->loadOptions();
1221 foreach ( self
::$mCacheVars as $var ) {
1222 $this->$var = $user->$var;
1227 * Load the groups from the database if they aren't already loaded.
1229 private function loadGroups() {
1230 if ( is_null( $this->mGroups
) ) {
1231 $dbr = wfGetDB( DB_MASTER
);
1232 $res = $dbr->select( 'user_groups',
1233 array( 'ug_group' ),
1234 array( 'ug_user' => $this->mId
),
1236 $this->mGroups
= array();
1237 foreach ( $res as $row ) {
1238 $this->mGroups
[] = $row->ug_group
;
1244 * Add the user to the group if he/she meets given criteria.
1246 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1247 * possible to remove manually via Special:UserRights. In such case it
1248 * will not be re-added automatically. The user will also not lose the
1249 * group if they no longer meet the criteria.
1251 * @param string $event key in $wgAutopromoteOnce (each one has groups/criteria)
1253 * @return array Array of groups the user has been promoted to.
1255 * @see $wgAutopromoteOnce
1257 public function addAutopromoteOnceGroups( $event ) {
1258 global $wgAutopromoteOnceLogInRC, $wgAuth;
1260 $toPromote = array();
1261 if ( $this->getId() ) {
1262 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1263 if ( count( $toPromote ) ) {
1264 $oldGroups = $this->getGroups(); // previous groups
1266 foreach ( $toPromote as $group ) {
1267 $this->addGroup( $group );
1269 // update groups in external authentication database
1270 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1272 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1274 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1275 $logEntry->setPerformer( $this );
1276 $logEntry->setTarget( $this->getUserPage() );
1277 $logEntry->setParameters( array(
1278 '4::oldgroups' => $oldGroups,
1279 '5::newgroups' => $newGroups,
1281 $logid = $logEntry->insert();
1282 if ( $wgAutopromoteOnceLogInRC ) {
1283 $logEntry->publish( $logid );
1291 * Clear various cached data stored in this object. The cache of the user table
1292 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1294 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1295 * given source. May be "name", "id", "defaults", "session", or false for
1298 public function clearInstanceCache( $reloadFrom = false ) {
1299 $this->mNewtalk
= -1;
1300 $this->mDatePreference
= null;
1301 $this->mBlockedby
= -1; # Unset
1302 $this->mHash
= false;
1303 $this->mRights
= null;
1304 $this->mEffectiveGroups
= null;
1305 $this->mImplicitGroups
= null;
1306 $this->mGroups
= null;
1307 $this->mOptions
= null;
1308 $this->mOptionsLoaded
= false;
1309 $this->mEditCount
= null;
1311 if ( $reloadFrom ) {
1312 $this->mLoadedItems
= array();
1313 $this->mFrom
= $reloadFrom;
1318 * Combine the language default options with any site-specific options
1319 * and add the default language variants.
1321 * @return Array of String options
1323 public static function getDefaultOptions() {
1324 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1326 static $defOpt = null;
1327 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1328 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1329 // mid-request and see that change reflected in the return value of this function.
1330 // Which is insane and would never happen during normal MW operation
1334 $defOpt = $wgDefaultUserOptions;
1335 // Default language setting
1336 $defOpt['language'] = $wgContLang->getCode();
1337 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1338 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1340 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1341 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1343 $defOpt['skin'] = $wgDefaultSkin;
1345 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1351 * Get a given default option value.
1353 * @param string $opt Name of option to retrieve
1354 * @return string Default option value
1356 public static function getDefaultOption( $opt ) {
1357 $defOpts = self
::getDefaultOptions();
1358 if ( isset( $defOpts[$opt] ) ) {
1359 return $defOpts[$opt];
1366 * Get blocking information
1367 * @param bool $bFromSlave Whether to check the slave database first. To
1368 * improve performance, non-critical checks are done
1369 * against slaves. Check when actually saving should be
1370 * done against master.
1372 private function getBlockedStatus( $bFromSlave = true ) {
1373 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1375 if ( -1 != $this->mBlockedby
) {
1379 wfProfileIn( __METHOD__
);
1380 wfDebug( __METHOD__
. ": checking...\n" );
1382 // Initialize data...
1383 // Otherwise something ends up stomping on $this->mBlockedby when
1384 // things get lazy-loaded later, causing false positive block hits
1385 // due to -1 !== 0. Probably session-related... Nothing should be
1386 // overwriting mBlockedby, surely?
1389 # We only need to worry about passing the IP address to the Block generator if the
1390 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1391 # know which IP address they're actually coming from
1392 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1393 $ip = $this->getRequest()->getIP();
1399 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1402 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1403 && !in_array( $ip, $wgProxyWhitelist )
1406 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1408 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1409 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1410 $block->setTarget( $ip );
1411 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1413 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1414 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1415 $block->setTarget( $ip );
1419 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1420 if ( !$block instanceof Block
1421 && $wgApplyIpBlocksToXff
1423 && !$this->isAllowed( 'proxyunbannable' )
1424 && !in_array( $ip, $wgProxyWhitelist )
1426 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1427 $xff = array_map( 'trim', explode( ',', $xff ) );
1428 $xff = array_diff( $xff, array( $ip ) );
1429 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1430 $block = Block
::chooseBlock( $xffblocks, $xff );
1431 if ( $block instanceof Block
) {
1432 # Mangle the reason to alert the user that the block
1433 # originated from matching the X-Forwarded-For header.
1434 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1438 if ( $block instanceof Block
) {
1439 wfDebug( __METHOD__
. ": Found block.\n" );
1440 $this->mBlock
= $block;
1441 $this->mBlockedby
= $block->getByName();
1442 $this->mBlockreason
= $block->mReason
;
1443 $this->mHideName
= $block->mHideName
;
1444 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1446 $this->mBlockedby
= '';
1447 $this->mHideName
= 0;
1448 $this->mAllowUsertalk
= false;
1452 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1454 wfProfileOut( __METHOD__
);
1458 * Whether the given IP is in a DNS blacklist.
1460 * @param string $ip IP to check
1461 * @param bool $checkWhitelist whether to check the whitelist first
1462 * @return bool True if blacklisted.
1464 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1465 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1466 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1468 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs ) {
1472 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1476 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1477 return $this->inDnsBlacklist( $ip, $urls );
1481 * Whether the given IP is in a given DNS blacklist.
1483 * @param string $ip IP to check
1484 * @param string|array $bases of Strings: URL of the DNS blacklist
1485 * @return bool True if blacklisted.
1487 public function inDnsBlacklist( $ip, $bases ) {
1488 wfProfileIn( __METHOD__
);
1491 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1492 if ( IP
::isIPv4( $ip ) ) {
1493 // Reverse IP, bug 21255
1494 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1496 foreach ( (array)$bases as $base ) {
1498 // If we have an access key, use that too (ProjectHoneypot, etc.)
1499 if ( is_array( $base ) ) {
1500 if ( count( $base ) >= 2 ) {
1501 // Access key is 1, base URL is 0
1502 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1504 $host = "$ipReversed.{$base[0]}";
1507 $host = "$ipReversed.$base";
1511 $ipList = gethostbynamel( $host );
1514 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1518 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1523 wfProfileOut( __METHOD__
);
1528 * Check if an IP address is in the local proxy list
1534 public static function isLocallyBlockedProxy( $ip ) {
1535 global $wgProxyList;
1537 if ( !$wgProxyList ) {
1540 wfProfileIn( __METHOD__
);
1542 if ( !is_array( $wgProxyList ) ) {
1543 // Load from the specified file
1544 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1547 if ( !is_array( $wgProxyList ) ) {
1549 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1551 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1552 // Old-style flipped proxy list
1557 wfProfileOut( __METHOD__
);
1562 * Is this user subject to rate limiting?
1564 * @return bool True if rate limited
1566 public function isPingLimitable() {
1567 global $wgRateLimitsExcludedIPs;
1568 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1569 // No other good way currently to disable rate limits
1570 // for specific IPs. :P
1571 // But this is a crappy hack and should die.
1574 return !$this->isAllowed( 'noratelimit' );
1578 * Primitive rate limits: enforce maximum actions per time period
1579 * to put a brake on flooding.
1581 * @note When using a shared cache like memcached, IP-address
1582 * last-hit counters will be shared across wikis.
1584 * @param string $action Action to enforce; 'edit' if unspecified
1585 * @param integer $incrBy Positive amount to increment counter by [defaults to 1]
1586 * @return bool True if a rate limiter was tripped
1588 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1589 // Call the 'PingLimiter' hook
1591 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1595 global $wgRateLimits;
1596 if ( !isset( $wgRateLimits[$action] ) ) {
1600 // Some groups shouldn't trigger the ping limiter, ever
1601 if ( !$this->isPingLimitable() ) {
1606 wfProfileIn( __METHOD__
);
1608 $limits = $wgRateLimits[$action];
1610 $id = $this->getId();
1613 if ( isset( $limits['anon'] ) && $id == 0 ) {
1614 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1617 if ( isset( $limits['user'] ) && $id != 0 ) {
1618 $userLimit = $limits['user'];
1620 if ( $this->isNewbie() ) {
1621 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1622 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1624 if ( isset( $limits['ip'] ) ) {
1625 $ip = $this->getRequest()->getIP();
1626 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1628 if ( isset( $limits['subnet'] ) ) {
1629 $ip = $this->getRequest()->getIP();
1632 if ( IP
::isIPv6( $ip ) ) {
1633 $parts = IP
::parseRange( "$ip/64" );
1634 $subnet = $parts[0];
1635 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1637 $subnet = $matches[1];
1639 if ( $subnet !== false ) {
1640 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1644 // Check for group-specific permissions
1645 // If more than one group applies, use the group with the highest limit
1646 foreach ( $this->getGroups() as $group ) {
1647 if ( isset( $limits[$group] ) ) {
1648 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1649 $userLimit = $limits[$group];
1653 // Set the user limit key
1654 if ( $userLimit !== false ) {
1655 list( $max, $period ) = $userLimit;
1656 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1657 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1661 foreach ( $keys as $key => $limit ) {
1662 list( $max, $period ) = $limit;
1663 $summary = "(limit $max in {$period}s)";
1664 $count = $wgMemc->get( $key );
1667 if ( $count >= $max ) {
1668 wfDebugLog( 'ratelimit', $this->getName() . " tripped! $key at $count $summary");
1671 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1674 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1675 if ( $incrBy > 0 ) {
1676 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1679 if ( $incrBy > 0 ) {
1680 $wgMemc->incr( $key, $incrBy );
1684 wfProfileOut( __METHOD__
);
1689 * Check if user is blocked
1691 * @param bool $bFromSlave Whether to check the slave database instead of the master
1692 * @return bool True if blocked, false otherwise
1694 public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1695 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1699 * Get the block affecting the user, or null if the user is not blocked
1701 * @param bool $bFromSlave Whether to check the slave database instead of the master
1702 * @return Block|null
1704 public function getBlock( $bFromSlave = true ) {
1705 $this->getBlockedStatus( $bFromSlave );
1706 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1710 * Check if user is blocked from editing a particular article
1712 * @param Title $title Title to check
1713 * @param bool $bFromSlave whether to check the slave database instead of the master
1716 public function isBlockedFrom( $title, $bFromSlave = false ) {
1717 global $wgBlockAllowsUTEdit;
1718 wfProfileIn( __METHOD__
);
1720 $blocked = $this->isBlocked( $bFromSlave );
1721 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1722 // If a user's name is suppressed, they cannot make edits anywhere
1723 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1724 && $title->getNamespace() == NS_USER_TALK
) {
1726 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1729 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1731 wfProfileOut( __METHOD__
);
1736 * If user is blocked, return the name of the user who placed the block
1737 * @return string Name of blocker
1739 public function blockedBy() {
1740 $this->getBlockedStatus();
1741 return $this->mBlockedby
;
1745 * If user is blocked, return the specified reason for the block
1746 * @return string Blocking reason
1748 public function blockedFor() {
1749 $this->getBlockedStatus();
1750 return $this->mBlockreason
;
1754 * If user is blocked, return the ID for the block
1755 * @return int Block ID
1757 public function getBlockId() {
1758 $this->getBlockedStatus();
1759 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1763 * Check if user is blocked on all wikis.
1764 * Do not use for actual edit permission checks!
1765 * This is intended for quick UI checks.
1767 * @param string $ip IP address, uses current client if none given
1768 * @return bool True if blocked, false otherwise
1770 public function isBlockedGlobally( $ip = '' ) {
1771 if ( $this->mBlockedGlobally
!== null ) {
1772 return $this->mBlockedGlobally
;
1774 // User is already an IP?
1775 if ( IP
::isIPAddress( $this->getName() ) ) {
1776 $ip = $this->getName();
1778 $ip = $this->getRequest()->getIP();
1781 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1782 $this->mBlockedGlobally
= (bool)$blocked;
1783 return $this->mBlockedGlobally
;
1787 * Check if user account is locked
1789 * @return bool True if locked, false otherwise
1791 public function isLocked() {
1792 if ( $this->mLocked
!== null ) {
1793 return $this->mLocked
;
1796 StubObject
::unstub( $wgAuth );
1797 $authUser = $wgAuth->getUserInstance( $this );
1798 $this->mLocked
= (bool)$authUser->isLocked();
1799 return $this->mLocked
;
1803 * Check if user account is hidden
1805 * @return bool True if hidden, false otherwise
1807 public function isHidden() {
1808 if ( $this->mHideName
!== null ) {
1809 return $this->mHideName
;
1811 $this->getBlockedStatus();
1812 if ( !$this->mHideName
) {
1814 StubObject
::unstub( $wgAuth );
1815 $authUser = $wgAuth->getUserInstance( $this );
1816 $this->mHideName
= (bool)$authUser->isHidden();
1818 return $this->mHideName
;
1822 * Get the user's ID.
1823 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1825 public function getId() {
1826 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1827 // Special case, we know the user is anonymous
1829 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1830 // Don't load if this was initialized from an ID
1837 * Set the user and reload all fields according to a given ID
1838 * @param int $v User ID to reload
1840 public function setId( $v ) {
1842 $this->clearInstanceCache( 'id' );
1846 * Get the user name, or the IP of an anonymous user
1847 * @return string User's name or IP address
1849 public function getName() {
1850 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1851 // Special case optimisation
1852 return $this->mName
;
1855 if ( $this->mName
=== false ) {
1857 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1859 return $this->mName
;
1864 * Set the user name.
1866 * This does not reload fields from the database according to the given
1867 * name. Rather, it is used to create a temporary "nonexistent user" for
1868 * later addition to the database. It can also be used to set the IP
1869 * address for an anonymous user to something other than the current
1872 * @note User::newFromName() has roughly the same function, when the named user
1874 * @param string $str New user name to set
1876 public function setName( $str ) {
1878 $this->mName
= $str;
1882 * Get the user's name escaped by underscores.
1883 * @return string Username escaped by underscores.
1885 public function getTitleKey() {
1886 return str_replace( ' ', '_', $this->getName() );
1890 * Check if the user has new messages.
1891 * @return bool True if the user has new messages
1893 public function getNewtalk() {
1896 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1897 if ( $this->mNewtalk
=== -1 ) {
1898 $this->mNewtalk
= false; # reset talk page status
1900 // Check memcached separately for anons, who have no
1901 // entire User object stored in there.
1902 if ( !$this->mId
) {
1903 global $wgDisableAnonTalk;
1904 if ( $wgDisableAnonTalk ) {
1905 // Anon newtalk disabled by configuration.
1906 $this->mNewtalk
= false;
1909 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1910 $newtalk = $wgMemc->get( $key );
1911 if ( strval( $newtalk ) !== '' ) {
1912 $this->mNewtalk
= (bool)$newtalk;
1914 // Since we are caching this, make sure it is up to date by getting it
1916 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1917 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1921 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1925 return (bool)$this->mNewtalk
;
1929 * Return the data needed to construct links for new talk page message
1930 * alerts. If there are new messages, this will return an associative array
1931 * with the following data:
1932 * wiki: The database name of the wiki
1933 * link: Root-relative link to the user's talk page
1934 * rev: The last talk page revision that the user has seen or null. This
1935 * is useful for building diff links.
1936 * If there are no new messages, it returns an empty array.
1937 * @note This function was designed to accomodate multiple talk pages, but
1938 * currently only returns a single link and revision.
1941 public function getNewMessageLinks() {
1943 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
1945 } elseif ( !$this->getNewtalk() ) {
1948 $utp = $this->getTalkPage();
1949 $dbr = wfGetDB( DB_SLAVE
);
1950 // Get the "last viewed rev" timestamp from the oldest message notification
1951 $timestamp = $dbr->selectField( 'user_newtalk',
1952 'MIN(user_last_timestamp)',
1953 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
1955 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
1956 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
1960 * Get the revision ID for the last talk page revision viewed by the talk
1962 * @return int|null Revision ID or null
1964 public function getNewMessageRevisionId() {
1965 $newMessageRevisionId = null;
1966 $newMessageLinks = $this->getNewMessageLinks();
1967 if ( $newMessageLinks ) {
1968 // Note: getNewMessageLinks() never returns more than a single link
1969 // and it is always for the same wiki, but we double-check here in
1970 // case that changes some time in the future.
1971 if ( count( $newMessageLinks ) === 1
1972 && $newMessageLinks[0]['wiki'] === wfWikiID()
1973 && $newMessageLinks[0]['rev']
1975 $newMessageRevision = $newMessageLinks[0]['rev'];
1976 $newMessageRevisionId = $newMessageRevision->getId();
1979 return $newMessageRevisionId;
1983 * Internal uncached check for new messages
1986 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1987 * @param string|int $id User's IP address for anonymous users, User ID otherwise
1988 * @param bool $fromMaster true to fetch from the master, false for a slave
1989 * @return bool True if the user has new messages
1991 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
1992 if ( $fromMaster ) {
1993 $db = wfGetDB( DB_MASTER
);
1995 $db = wfGetDB( DB_SLAVE
);
1997 $ok = $db->selectField( 'user_newtalk', $field,
1998 array( $field => $id ), __METHOD__
);
1999 return $ok !== false;
2003 * Add or update the new messages flag
2004 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2005 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2006 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null.
2007 * @return bool True if successful, false otherwise
2009 protected function updateNewtalk( $field, $id, $curRev = null ) {
2010 // Get timestamp of the talk page revision prior to the current one
2011 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2012 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2013 // Mark the user as having new messages since this revision
2014 $dbw = wfGetDB( DB_MASTER
);
2015 $dbw->insert( 'user_newtalk',
2016 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2019 if ( $dbw->affectedRows() ) {
2020 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2023 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2029 * Clear the new messages flag for the given user
2030 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2031 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2032 * @return bool True if successful, false otherwise
2034 protected function deleteNewtalk( $field, $id ) {
2035 $dbw = wfGetDB( DB_MASTER
);
2036 $dbw->delete( 'user_newtalk',
2037 array( $field => $id ),
2039 if ( $dbw->affectedRows() ) {
2040 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2043 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2049 * Update the 'You have new messages!' status.
2050 * @param bool $val Whether the user has new messages
2051 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null or !$val.
2053 public function setNewtalk( $val, $curRev = null ) {
2054 if ( wfReadOnly() ) {
2059 $this->mNewtalk
= $val;
2061 if ( $this->isAnon() ) {
2063 $id = $this->getName();
2066 $id = $this->getId();
2071 $changed = $this->updateNewtalk( $field, $id, $curRev );
2073 $changed = $this->deleteNewtalk( $field, $id );
2076 if ( $this->isAnon() ) {
2077 // Anons have a separate memcached space, since
2078 // user records aren't kept for them.
2079 $key = wfMemcKey( 'newtalk', 'ip', $id );
2080 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
2083 $this->invalidateCache();
2088 * Generate a current or new-future timestamp to be stored in the
2089 * user_touched field when we update things.
2090 * @return string Timestamp in TS_MW format
2092 private static function newTouchedTimestamp() {
2093 global $wgClockSkewFudge;
2094 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2098 * Clear user data from memcached.
2099 * Use after applying fun updates to the database; caller's
2100 * responsibility to update user_touched if appropriate.
2102 * Called implicitly from invalidateCache() and saveSettings().
2104 private function clearSharedCache() {
2108 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
2113 * Immediately touch the user data cache for this account.
2114 * Updates user_touched field, and removes account data from memcached
2115 * for reload on the next hit.
2117 public function invalidateCache() {
2118 if ( wfReadOnly() ) {
2123 $this->mTouched
= self
::newTouchedTimestamp();
2125 $dbw = wfGetDB( DB_MASTER
);
2126 $userid = $this->mId
;
2127 $touched = $this->mTouched
;
2128 $method = __METHOD__
;
2129 $dbw->onTransactionIdle( function() use ( $dbw, $userid, $touched, $method ) {
2130 // Prevent contention slams by checking user_touched first
2131 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2132 $needsPurge = $dbw->selectField( 'user', '1',
2133 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2134 if ( $needsPurge ) {
2135 $dbw->update( 'user',
2136 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2137 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2142 $this->clearSharedCache();
2147 * Validate the cache for this account.
2148 * @param string $timestamp A timestamp in TS_MW format
2151 public function validateCache( $timestamp ) {
2153 return ( $timestamp >= $this->mTouched
);
2157 * Get the user touched timestamp
2158 * @return string timestamp
2160 public function getTouched() {
2162 return $this->mTouched
;
2166 * Set the password and reset the random token.
2167 * Calls through to authentication plugin if necessary;
2168 * will have no effect if the auth plugin refuses to
2169 * pass the change through or if the legal password
2172 * As a special case, setting the password to null
2173 * wipes it, so the account cannot be logged in until
2174 * a new password is set, for instance via e-mail.
2176 * @param string $str New password to set
2177 * @throws PasswordError on failure
2181 public function setPassword( $str ) {
2184 if ( $str !== null ) {
2185 if ( !$wgAuth->allowPasswordChange() ) {
2186 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2189 if ( !$this->isValidPassword( $str ) ) {
2190 global $wgMinimalPasswordLength;
2191 $valid = $this->getPasswordValidity( $str );
2192 if ( is_array( $valid ) ) {
2193 $message = array_shift( $valid );
2197 $params = array( $wgMinimalPasswordLength );
2199 throw new PasswordError( wfMessage( $message, $params )->text() );
2203 if ( !$wgAuth->setPassword( $this, $str ) ) {
2204 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2207 $this->setInternalPassword( $str );
2213 * Set the password and reset the random token unconditionally.
2215 * @param string|null $str New password to set or null to set an invalid
2216 * password hash meaning that the user will not be able to log in
2217 * through the web interface.
2219 public function setInternalPassword( $str ) {
2223 if ( $str === null ) {
2224 // Save an invalid hash...
2225 $this->mPassword
= '';
2227 $this->mPassword
= self
::crypt( $str );
2229 $this->mNewpassword
= '';
2230 $this->mNewpassTime
= null;
2234 * Get the user's current token.
2235 * @param bool $forceCreation Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility)
2236 * @return string Token
2238 public function getToken( $forceCreation = true ) {
2240 if ( !$this->mToken
&& $forceCreation ) {
2243 return $this->mToken
;
2247 * Set the random token (used for persistent authentication)
2248 * Called from loadDefaults() among other places.
2250 * @param string|bool $token If specified, set the token to this value
2252 public function setToken( $token = false ) {
2255 $this->mToken
= MWCryptRand
::generateHex( USER_TOKEN_LENGTH
);
2257 $this->mToken
= $token;
2262 * Set the password for a password reminder or new account email
2264 * @param $str New password to set or null to set an invalid
2265 * password hash meaning that the user will not be able to use it
2266 * @param bool $throttle If true, reset the throttle timestamp to the present
2268 public function setNewpassword( $str, $throttle = true ) {
2271 if ( $str === null ) {
2272 $this->mNewpassword
= '';
2273 $this->mNewpassTime
= null;
2275 $this->mNewpassword
= self
::crypt( $str );
2277 $this->mNewpassTime
= wfTimestampNow();
2283 * Has password reminder email been sent within the last
2284 * $wgPasswordReminderResendTime hours?
2287 public function isPasswordReminderThrottled() {
2288 global $wgPasswordReminderResendTime;
2290 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2293 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2294 return time() < $expiry;
2298 * Get the user's e-mail address
2299 * @return string User's email address
2301 public function getEmail() {
2303 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
2304 return $this->mEmail
;
2308 * Get the timestamp of the user's e-mail authentication
2309 * @return string TS_MW timestamp
2311 public function getEmailAuthenticationTimestamp() {
2313 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2314 return $this->mEmailAuthenticated
;
2318 * Set the user's e-mail address
2319 * @param string $str New e-mail address
2321 public function setEmail( $str ) {
2323 if ( $str == $this->mEmail
) {
2326 $this->mEmail
= $str;
2327 $this->invalidateEmail();
2328 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
2332 * Set the user's e-mail address and a confirmation mail if needed.
2335 * @param string $str New e-mail address
2338 public function setEmailWithConfirmation( $str ) {
2339 global $wgEnableEmail, $wgEmailAuthentication;
2341 if ( !$wgEnableEmail ) {
2342 return Status
::newFatal( 'emaildisabled' );
2345 $oldaddr = $this->getEmail();
2346 if ( $str === $oldaddr ) {
2347 return Status
::newGood( true );
2350 $this->setEmail( $str );
2352 if ( $str !== '' && $wgEmailAuthentication ) {
2353 // Send a confirmation request to the new address if needed
2354 $type = $oldaddr != '' ?
'changed' : 'set';
2355 $result = $this->sendConfirmationMail( $type );
2356 if ( $result->isGood() ) {
2357 // Say the the caller that a confirmation mail has been sent
2358 $result->value
= 'eauth';
2361 $result = Status
::newGood( true );
2368 * Get the user's real name
2369 * @return string User's real name
2371 public function getRealName() {
2372 if ( !$this->isItemLoaded( 'realname' ) ) {
2376 return $this->mRealName
;
2380 * Set the user's real name
2381 * @param string $str New real name
2383 public function setRealName( $str ) {
2385 $this->mRealName
= $str;
2389 * Get the user's current setting for a given option.
2391 * @param string $oname The option to check
2392 * @param string $defaultOverride A default value returned if the option does not exist
2393 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2394 * @return string User's current value for the option
2395 * @see getBoolOption()
2396 * @see getIntOption()
2398 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2399 global $wgHiddenPrefs;
2400 $this->loadOptions();
2402 # We want 'disabled' preferences to always behave as the default value for
2403 # users, even if they have set the option explicitly in their settings (ie they
2404 # set it, and then it was disabled removing their ability to change it). But
2405 # we don't want to erase the preferences in the database in case the preference
2406 # is re-enabled again. So don't touch $mOptions, just override the returned value
2407 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2408 return self
::getDefaultOption( $oname );
2411 if ( array_key_exists( $oname, $this->mOptions
) ) {
2412 return $this->mOptions
[$oname];
2414 return $defaultOverride;
2419 * Get all user's options
2423 public function getOptions() {
2424 global $wgHiddenPrefs;
2425 $this->loadOptions();
2426 $options = $this->mOptions
;
2428 # We want 'disabled' preferences to always behave as the default value for
2429 # users, even if they have set the option explicitly in their settings (ie they
2430 # set it, and then it was disabled removing their ability to change it). But
2431 # we don't want to erase the preferences in the database in case the preference
2432 # is re-enabled again. So don't touch $mOptions, just override the returned value
2433 foreach ( $wgHiddenPrefs as $pref ) {
2434 $default = self
::getDefaultOption( $pref );
2435 if ( $default !== null ) {
2436 $options[$pref] = $default;
2444 * Get the user's current setting for a given option, as a boolean value.
2446 * @param string $oname The option to check
2447 * @return bool User's current value for the option
2450 public function getBoolOption( $oname ) {
2451 return (bool)$this->getOption( $oname );
2455 * Get the user's current setting for a given option, as an integer value.
2457 * @param string $oname The option to check
2458 * @param int $defaultOverride A default value returned if the option does not exist
2459 * @return int User's current value for the option
2462 public function getIntOption( $oname, $defaultOverride = 0 ) {
2463 $val = $this->getOption( $oname );
2465 $val = $defaultOverride;
2467 return intval( $val );
2471 * Set the given option for a user.
2473 * @param string $oname The option to set
2474 * @param mixed $val New value to set
2476 public function setOption( $oname, $val ) {
2477 $this->loadOptions();
2479 // Explicitly NULL values should refer to defaults
2480 if ( is_null( $val ) ) {
2481 $val = self
::getDefaultOption( $oname );
2484 $this->mOptions
[$oname] = $val;
2488 * Get a token stored in the preferences (like the watchlist one),
2489 * resetting it if it's empty (and saving changes).
2491 * @param string $oname The option name to retrieve the token from
2492 * @return string|bool User's current value for the option, or false if this option is disabled.
2493 * @see resetTokenFromOption()
2496 public function getTokenFromOption( $oname ) {
2497 global $wgHiddenPrefs;
2498 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2502 $token = $this->getOption( $oname );
2504 $token = $this->resetTokenFromOption( $oname );
2505 $this->saveSettings();
2511 * Reset a token stored in the preferences (like the watchlist one).
2512 * *Does not* save user's preferences (similarly to setOption()).
2514 * @param string $oname The option name to reset the token in
2515 * @return string|bool New token value, or false if this option is disabled.
2516 * @see getTokenFromOption()
2519 public function resetTokenFromOption( $oname ) {
2520 global $wgHiddenPrefs;
2521 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2525 $token = MWCryptRand
::generateHex( 40 );
2526 $this->setOption( $oname, $token );
2531 * Return a list of the types of user options currently returned by
2532 * User::getOptionKinds().
2534 * Currently, the option kinds are:
2535 * - 'registered' - preferences which are registered in core MediaWiki or
2536 * by extensions using the UserGetDefaultOptions hook.
2537 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2538 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2539 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2540 * be used by user scripts.
2541 * - 'special' - "preferences" that are not accessible via User::getOptions
2542 * or User::setOptions.
2543 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2544 * These are usually legacy options, removed in newer versions.
2546 * The API (and possibly others) use this function to determine the possible
2547 * option types for validation purposes, so make sure to update this when a
2548 * new option kind is added.
2550 * @see User::getOptionKinds
2551 * @return array Option kinds
2553 public static function listOptionKinds() {
2556 'registered-multiselect',
2557 'registered-checkmatrix',
2565 * Return an associative array mapping preferences keys to the kind of a preference they're
2566 * used for. Different kinds are handled differently when setting or reading preferences.
2568 * See User::listOptionKinds for the list of valid option types that can be provided.
2570 * @see User::listOptionKinds
2571 * @param $context IContextSource
2572 * @param array $options assoc. array with options keys to check as keys. Defaults to $this->mOptions.
2573 * @return array the key => kind mapping data
2575 public function getOptionKinds( IContextSource
$context, $options = null ) {
2576 $this->loadOptions();
2577 if ( $options === null ) {
2578 $options = $this->mOptions
;
2581 $prefs = Preferences
::getPreferences( $this, $context );
2584 // Pull out the "special" options, so they don't get converted as
2585 // multiselect or checkmatrix.
2586 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2587 foreach ( $specialOptions as $name => $value ) {
2588 unset( $prefs[$name] );
2591 // Multiselect and checkmatrix options are stored in the database with
2592 // one key per option, each having a boolean value. Extract those keys.
2593 $multiselectOptions = array();
2594 foreach ( $prefs as $name => $info ) {
2595 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2596 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2597 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2598 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2600 foreach ( $opts as $value ) {
2601 $multiselectOptions["$prefix$value"] = true;
2604 unset( $prefs[$name] );
2607 $checkmatrixOptions = array();
2608 foreach ( $prefs as $name => $info ) {
2609 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2610 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2611 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2612 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2613 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2615 foreach ( $columns as $column ) {
2616 foreach ( $rows as $row ) {
2617 $checkmatrixOptions["$prefix-$column-$row"] = true;
2621 unset( $prefs[$name] );
2625 // $value is ignored
2626 foreach ( $options as $key => $value ) {
2627 if ( isset( $prefs[$key] ) ) {
2628 $mapping[$key] = 'registered';
2629 } elseif ( isset( $multiselectOptions[$key] ) ) {
2630 $mapping[$key] = 'registered-multiselect';
2631 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2632 $mapping[$key] = 'registered-checkmatrix';
2633 } elseif ( isset( $specialOptions[$key] ) ) {
2634 $mapping[$key] = 'special';
2635 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2636 $mapping[$key] = 'userjs';
2638 $mapping[$key] = 'unused';
2646 * Reset certain (or all) options to the site defaults
2648 * The optional parameter determines which kinds of preferences will be reset.
2649 * Supported values are everything that can be reported by getOptionKinds()
2650 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2652 * @param array|string $resetKinds which kinds of preferences to reset. Defaults to
2653 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2654 * for backwards-compatibility.
2655 * @param $context IContextSource|null context source used when $resetKinds
2656 * does not contain 'all', passed to getOptionKinds().
2657 * Defaults to RequestContext::getMain() when null.
2659 public function resetOptions(
2660 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2661 IContextSource
$context = null
2664 $defaultOptions = self
::getDefaultOptions();
2666 if ( !is_array( $resetKinds ) ) {
2667 $resetKinds = array( $resetKinds );
2670 if ( in_array( 'all', $resetKinds ) ) {
2671 $newOptions = $defaultOptions;
2673 if ( $context === null ) {
2674 $context = RequestContext
::getMain();
2677 $optionKinds = $this->getOptionKinds( $context );
2678 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2679 $newOptions = array();
2681 // Use default values for the options that should be deleted, and
2682 // copy old values for the ones that shouldn't.
2683 foreach ( $this->mOptions
as $key => $value ) {
2684 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2685 if ( array_key_exists( $key, $defaultOptions ) ) {
2686 $newOptions[$key] = $defaultOptions[$key];
2689 $newOptions[$key] = $value;
2694 $this->mOptions
= $newOptions;
2695 $this->mOptionsLoaded
= true;
2699 * Get the user's preferred date format.
2700 * @return string User's preferred date format
2702 public function getDatePreference() {
2703 // Important migration for old data rows
2704 if ( is_null( $this->mDatePreference
) ) {
2706 $value = $this->getOption( 'date' );
2707 $map = $wgLang->getDatePreferenceMigrationMap();
2708 if ( isset( $map[$value] ) ) {
2709 $value = $map[$value];
2711 $this->mDatePreference
= $value;
2713 return $this->mDatePreference
;
2717 * Determine based on the wiki configuration and the user's options,
2718 * whether this user must be over HTTPS no matter what.
2722 public function requiresHTTPS() {
2723 global $wgSecureLogin;
2724 if ( !$wgSecureLogin ) {
2727 $https = $this->getBoolOption( 'prefershttps' );
2728 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2730 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2737 * Get the user preferred stub threshold
2741 public function getStubThreshold() {
2742 global $wgMaxArticleSize; # Maximum article size, in Kb
2743 $threshold = $this->getIntOption( 'stubthreshold' );
2744 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2745 // If they have set an impossible value, disable the preference
2746 // so we can use the parser cache again.
2753 * Get the permissions this user has.
2754 * @return Array of String permission names
2756 public function getRights() {
2757 if ( is_null( $this->mRights
) ) {
2758 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2759 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2760 // Force reindexation of rights when a hook has unset one of them
2761 $this->mRights
= array_values( array_unique( $this->mRights
) );
2763 return $this->mRights
;
2767 * Get the list of explicit group memberships this user has.
2768 * The implicit * and user groups are not included.
2769 * @return Array of String internal group names
2771 public function getGroups() {
2773 $this->loadGroups();
2774 return $this->mGroups
;
2778 * Get the list of implicit group memberships this user has.
2779 * This includes all explicit groups, plus 'user' if logged in,
2780 * '*' for all accounts, and autopromoted groups
2781 * @param bool $recache Whether to avoid the cache
2782 * @return Array of String internal group names
2784 public function getEffectiveGroups( $recache = false ) {
2785 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2786 wfProfileIn( __METHOD__
);
2787 $this->mEffectiveGroups
= array_unique( array_merge(
2788 $this->getGroups(), // explicit groups
2789 $this->getAutomaticGroups( $recache ) // implicit groups
2791 // Hook for additional groups
2792 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2793 // Force reindexation of groups when a hook has unset one of them
2794 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
2795 wfProfileOut( __METHOD__
);
2797 return $this->mEffectiveGroups
;
2801 * Get the list of implicit group memberships this user has.
2802 * This includes 'user' if logged in, '*' for all accounts,
2803 * and autopromoted groups
2804 * @param bool $recache Whether to avoid the cache
2805 * @return Array of String internal group names
2807 public function getAutomaticGroups( $recache = false ) {
2808 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
2809 wfProfileIn( __METHOD__
);
2810 $this->mImplicitGroups
= array( '*' );
2811 if ( $this->getId() ) {
2812 $this->mImplicitGroups
[] = 'user';
2814 $this->mImplicitGroups
= array_unique( array_merge(
2815 $this->mImplicitGroups
,
2816 Autopromote
::getAutopromoteGroups( $this )
2820 // Assure data consistency with rights/groups,
2821 // as getEffectiveGroups() depends on this function
2822 $this->mEffectiveGroups
= null;
2824 wfProfileOut( __METHOD__
);
2826 return $this->mImplicitGroups
;
2830 * Returns the groups the user has belonged to.
2832 * The user may still belong to the returned groups. Compare with getGroups().
2834 * The function will not return groups the user had belonged to before MW 1.17
2836 * @return array Names of the groups the user has belonged to.
2838 public function getFormerGroups() {
2839 if ( is_null( $this->mFormerGroups
) ) {
2840 $dbr = wfGetDB( DB_MASTER
);
2841 $res = $dbr->select( 'user_former_groups',
2842 array( 'ufg_group' ),
2843 array( 'ufg_user' => $this->mId
),
2845 $this->mFormerGroups
= array();
2846 foreach ( $res as $row ) {
2847 $this->mFormerGroups
[] = $row->ufg_group
;
2850 return $this->mFormerGroups
;
2854 * Get the user's edit count.
2855 * @return int, null for anonymous users
2857 public function getEditCount() {
2858 if ( !$this->getId() ) {
2862 if ( !isset( $this->mEditCount
) ) {
2863 /* Populate the count, if it has not been populated yet */
2864 wfProfileIn( __METHOD__
);
2865 $dbr = wfGetDB( DB_SLAVE
);
2866 // check if the user_editcount field has been initialized
2867 $count = $dbr->selectField(
2868 'user', 'user_editcount',
2869 array( 'user_id' => $this->mId
),
2873 if ( $count === null ) {
2874 // it has not been initialized. do so.
2875 $count = $this->initEditCount();
2877 $this->mEditCount
= $count;
2878 wfProfileOut( __METHOD__
);
2880 return (int)$this->mEditCount
;
2884 * Add the user to the given group.
2885 * This takes immediate effect.
2886 * @param string $group Name of the group to add
2888 public function addGroup( $group ) {
2889 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2890 $dbw = wfGetDB( DB_MASTER
);
2891 if ( $this->getId() ) {
2892 $dbw->insert( 'user_groups',
2894 'ug_user' => $this->getID(),
2895 'ug_group' => $group,
2898 array( 'IGNORE' ) );
2901 $this->loadGroups();
2902 $this->mGroups
[] = $group;
2903 // In case loadGroups was not called before, we now have the right twice.
2904 // Get rid of the duplicate.
2905 $this->mGroups
= array_unique( $this->mGroups
);
2907 // Refresh the groups caches, and clear the rights cache so it will be
2908 // refreshed on the next call to $this->getRights().
2909 $this->getEffectiveGroups( true );
2910 $this->mRights
= null;
2912 $this->invalidateCache();
2916 * Remove the user from the given group.
2917 * This takes immediate effect.
2918 * @param string $group Name of the group to remove
2920 public function removeGroup( $group ) {
2922 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2923 $dbw = wfGetDB( DB_MASTER
);
2924 $dbw->delete( 'user_groups',
2926 'ug_user' => $this->getID(),
2927 'ug_group' => $group,
2929 // Remember that the user was in this group
2930 $dbw->insert( 'user_former_groups',
2932 'ufg_user' => $this->getID(),
2933 'ufg_group' => $group,
2936 array( 'IGNORE' ) );
2938 $this->loadGroups();
2939 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2941 // Refresh the groups caches, and clear the rights cache so it will be
2942 // refreshed on the next call to $this->getRights().
2943 $this->getEffectiveGroups( true );
2944 $this->mRights
= null;
2946 $this->invalidateCache();
2950 * Get whether the user is logged in
2953 public function isLoggedIn() {
2954 return $this->getID() != 0;
2958 * Get whether the user is anonymous
2961 public function isAnon() {
2962 return !$this->isLoggedIn();
2966 * Check if user is allowed to access a feature / make an action
2968 * @internal param \String $varargs permissions to test
2969 * @return boolean: True if user is allowed to perform *any* of the given actions
2973 public function isAllowedAny( /*...*/ ) {
2974 $permissions = func_get_args();
2975 foreach ( $permissions as $permission ) {
2976 if ( $this->isAllowed( $permission ) ) {
2985 * @internal param $varargs string
2986 * @return bool True if the user is allowed to perform *all* of the given actions
2988 public function isAllowedAll( /*...*/ ) {
2989 $permissions = func_get_args();
2990 foreach ( $permissions as $permission ) {
2991 if ( !$this->isAllowed( $permission ) ) {
2999 * Internal mechanics of testing a permission
3000 * @param string $action
3003 public function isAllowed( $action = '' ) {
3004 if ( $action === '' ) {
3005 return true; // In the spirit of DWIM
3007 // Patrolling may not be enabled
3008 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3009 global $wgUseRCPatrol, $wgUseNPPatrol;
3010 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3014 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3015 // by misconfiguration: 0 == 'foo'
3016 return in_array( $action, $this->getRights(), true );
3020 * Check whether to enable recent changes patrol features for this user
3021 * @return boolean: True or false
3023 public function useRCPatrol() {
3024 global $wgUseRCPatrol;
3025 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3029 * Check whether to enable new pages patrol features for this user
3030 * @return bool True or false
3032 public function useNPPatrol() {
3033 global $wgUseRCPatrol, $wgUseNPPatrol;
3035 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3036 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3041 * Get the WebRequest object to use with this object
3043 * @return WebRequest
3045 public function getRequest() {
3046 if ( $this->mRequest
) {
3047 return $this->mRequest
;
3055 * Get the current skin, loading it if required
3056 * @return Skin The current skin
3057 * @todo FIXME: Need to check the old failback system [AV]
3058 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3060 public function getSkin() {
3061 wfDeprecated( __METHOD__
, '1.18' );
3062 return RequestContext
::getMain()->getSkin();
3066 * Get a WatchedItem for this user and $title.
3068 * @since 1.22 $checkRights parameter added
3069 * @param $title Title
3070 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3071 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3072 * @return WatchedItem
3074 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3075 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3077 if ( isset( $this->mWatchedItems
[$key] ) ) {
3078 return $this->mWatchedItems
[$key];
3081 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3082 $this->mWatchedItems
= array();
3085 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3086 return $this->mWatchedItems
[$key];
3090 * Check the watched status of an article.
3091 * @since 1.22 $checkRights parameter added
3092 * @param $title Title of the article to look at
3093 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3094 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3097 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3098 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3103 * @since 1.22 $checkRights parameter added
3104 * @param $title Title of the article to look at
3105 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3106 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3108 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3109 $this->getWatchedItem( $title, $checkRights )->addWatch();
3110 $this->invalidateCache();
3114 * Stop watching an article.
3115 * @since 1.22 $checkRights parameter added
3116 * @param $title Title of the article to look at
3117 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3118 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3120 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3121 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3122 $this->invalidateCache();
3126 * Clear the user's notification timestamp for the given title.
3127 * If e-notif e-mails are on, they will receive notification mails on
3128 * the next change of the page if it's watched etc.
3129 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3130 * @param $title Title of the article to look at
3131 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3133 public function clearNotification( &$title, $oldid = 0 ) {
3134 global $wgUseEnotif, $wgShowUpdatedMarker;
3136 // Do nothing if the database is locked to writes
3137 if ( wfReadOnly() ) {
3141 // Do nothing if not allowed to edit the watchlist
3142 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3146 // If we're working on user's talk page, we should update the talk page message indicator
3147 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3148 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3152 $nextid = $oldid ?
$title->getNextRevisionID( $oldid ) : null;
3154 if ( !$oldid ||
!$nextid ) {
3155 // If we're looking at the latest revision, we should definitely clear it
3156 $this->setNewtalk( false );
3158 // Otherwise we should update its revision, if it's present
3159 if ( $this->getNewtalk() ) {
3160 // Naturally the other one won't clear by itself
3161 $this->setNewtalk( false );
3162 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3167 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3171 if ( $this->isAnon() ) {
3172 // Nothing else to do...
3176 // Only update the timestamp if the page is being watched.
3177 // The query to find out if it is watched is cached both in memcached and per-invocation,
3178 // and when it does have to be executed, it can be on a slave
3179 // If this is the user's newtalk page, we always update the timestamp
3181 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3185 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3189 * Resets all of the given user's page-change notification timestamps.
3190 * If e-notif e-mails are on, they will receive notification mails on
3191 * the next change of any watched page.
3192 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3194 public function clearAllNotifications() {
3195 if ( wfReadOnly() ) {
3199 // Do nothing if not allowed to edit the watchlist
3200 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3204 global $wgUseEnotif, $wgShowUpdatedMarker;
3205 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3206 $this->setNewtalk( false );
3209 $id = $this->getId();
3211 $dbw = wfGetDB( DB_MASTER
);
3212 $dbw->update( 'watchlist',
3213 array( /* SET */ 'wl_notificationtimestamp' => null ),
3214 array( /* WHERE */ 'wl_user' => $id ),
3217 // We also need to clear here the "you have new message" notification for the own user_talk page;
3218 // it's cleared one page view later in WikiPage::doViewUpdates().
3223 * Set this user's options from an encoded string
3224 * @param string $str Encoded options to import
3226 * @deprecated in 1.19 due to removal of user_options from the user table
3228 private function decodeOptions( $str ) {
3229 wfDeprecated( __METHOD__
, '1.19' );
3234 $this->mOptionsLoaded
= true;
3235 $this->mOptionOverrides
= array();
3237 // If an option is not set in $str, use the default value
3238 $this->mOptions
= self
::getDefaultOptions();
3240 $a = explode( "\n", $str );
3241 foreach ( $a as $s ) {
3243 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
3244 $this->mOptions
[$m[1]] = $m[2];
3245 $this->mOptionOverrides
[$m[1]] = $m[2];
3251 * Set a cookie on the user's client. Wrapper for
3252 * WebResponse::setCookie
3253 * @param string $name Name of the cookie to set
3254 * @param string $value Value to set
3255 * @param int $exp Expiration time, as a UNIX time value;
3256 * if 0 or not specified, use the default $wgCookieExpiration
3257 * @param bool $secure
3258 * true: Force setting the secure attribute when setting the cookie
3259 * false: Force NOT setting the secure attribute when setting the cookie
3260 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3261 * @param array $params Array of options sent passed to WebResponse::setcookie()
3263 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3264 $params['secure'] = $secure;
3265 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3269 * Clear a cookie on the user's client
3270 * @param string $name Name of the cookie to clear
3271 * @param bool $secure
3272 * true: Force setting the secure attribute when setting the cookie
3273 * false: Force NOT setting the secure attribute when setting the cookie
3274 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3275 * @param array $params Array of options sent passed to WebResponse::setcookie()
3277 protected function clearCookie( $name, $secure = null, $params = array() ) {
3278 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3282 * Set the default cookies for this session on the user's client.
3284 * @param $request WebRequest object to use; $wgRequest will be used if null
3286 * @param bool $secure Whether to force secure/insecure cookies or use default
3288 public function setCookies( $request = null, $secure = null ) {
3289 if ( $request === null ) {
3290 $request = $this->getRequest();
3294 if ( 0 == $this->mId
) {
3297 if ( !$this->mToken
) {
3298 // When token is empty or NULL generate a new one and then save it to the database
3299 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3300 // Simply by setting every cell in the user_token column to NULL and letting them be
3301 // regenerated as users log back into the wiki.
3303 $this->saveSettings();
3306 'wsUserID' => $this->mId
,
3307 'wsToken' => $this->mToken
,
3308 'wsUserName' => $this->getName()
3311 'UserID' => $this->mId
,
3312 'UserName' => $this->getName(),
3314 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
3315 $cookies['Token'] = $this->mToken
;
3317 $cookies['Token'] = false;
3320 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3322 foreach ( $session as $name => $value ) {
3323 $request->setSessionData( $name, $value );
3325 foreach ( $cookies as $name => $value ) {
3326 if ( $value === false ) {
3327 $this->clearCookie( $name );
3329 $this->setCookie( $name, $value, 0, $secure );
3334 * If wpStickHTTPS was selected, also set an insecure cookie that
3335 * will cause the site to redirect the user to HTTPS, if they access
3336 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3337 * as the one set by centralauth (bug 53538). Also set it to session, or
3338 * standard time setting, based on if rememberme was set.
3340 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3342 if ( ( 1 == $this->getOption( 'rememberpassword' ) ) ) {
3343 $time = 0; // set to $wgCookieExpiration
3350 array( 'prefix' => '' ) // no prefix
3356 * Log this user out.
3358 public function logout() {
3359 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3365 * Clear the user's cookies and session, and reset the instance cache.
3368 public function doLogout() {
3369 $this->clearInstanceCache( 'defaults' );
3371 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3373 $this->clearCookie( 'UserID' );
3374 $this->clearCookie( 'Token' );
3375 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3377 // Remember when user logged out, to prevent seeing cached pages
3378 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3382 * Save this user's settings into the database.
3383 * @todo Only rarely do all these fields need to be set!
3385 public function saveSettings() {
3389 if ( wfReadOnly() ) {
3392 if ( 0 == $this->mId
) {
3396 $this->mTouched
= self
::newTouchedTimestamp();
3397 if ( !$wgAuth->allowSetLocalPassword() ) {
3398 $this->mPassword
= '';
3401 $dbw = wfGetDB( DB_MASTER
);
3402 $dbw->update( 'user',
3404 'user_name' => $this->mName
,
3405 'user_password' => $this->mPassword
,
3406 'user_newpassword' => $this->mNewpassword
,
3407 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3408 'user_real_name' => $this->mRealName
,
3409 'user_email' => $this->mEmail
,
3410 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3411 'user_touched' => $dbw->timestamp( $this->mTouched
),
3412 'user_token' => strval( $this->mToken
),
3413 'user_email_token' => $this->mEmailToken
,
3414 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3415 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires
),
3416 ), array( /* WHERE */
3417 'user_id' => $this->mId
3421 $this->saveOptions();
3423 wfRunHooks( 'UserSaveSettings', array( $this ) );
3424 $this->clearSharedCache();
3425 $this->getUserPage()->invalidateCache();
3429 * If only this user's username is known, and it exists, return the user ID.
3432 public function idForName() {
3433 $s = trim( $this->getName() );
3438 $dbr = wfGetDB( DB_SLAVE
);
3439 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
3440 if ( $id === false ) {
3447 * Add a user to the database, return the user object
3449 * @param string $name Username to add
3450 * @param array $params of Strings Non-default parameters to save to the database as user_* fields:
3451 * - password The user's password hash. Password logins will be disabled if this is omitted.
3452 * - newpassword Hash for a temporary password that has been mailed to the user
3453 * - email The user's email address
3454 * - email_authenticated The email authentication timestamp
3455 * - real_name The user's real name
3456 * - options An associative array of non-default options
3457 * - token Random authentication token. Do not set.
3458 * - registration Registration timestamp. Do not set.
3460 * @return User object, or null if the username already exists
3462 public static function createNew( $name, $params = array() ) {
3465 $user->setToken(); // init token
3466 if ( isset( $params['options'] ) ) {
3467 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3468 unset( $params['options'] );
3470 $dbw = wfGetDB( DB_MASTER
);
3471 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3474 'user_id' => $seqVal,
3475 'user_name' => $name,
3476 'user_password' => $user->mPassword
,
3477 'user_newpassword' => $user->mNewpassword
,
3478 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3479 'user_email' => $user->mEmail
,
3480 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3481 'user_real_name' => $user->mRealName
,
3482 'user_token' => strval( $user->mToken
),
3483 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3484 'user_editcount' => 0,
3485 'user_touched' => $dbw->timestamp( self
::newTouchedTimestamp() ),
3487 foreach ( $params as $name => $value ) {
3488 $fields["user_$name"] = $value;
3490 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3491 if ( $dbw->affectedRows() ) {
3492 $newUser = User
::newFromId( $dbw->insertId() );
3500 * Add this existing user object to the database. If the user already
3501 * exists, a fatal status object is returned, and the user object is
3502 * initialised with the data from the database.
3504 * Previously, this function generated a DB error due to a key conflict
3505 * if the user already existed. Many extension callers use this function
3506 * in code along the lines of:
3508 * $user = User::newFromName( $name );
3509 * if ( !$user->isLoggedIn() ) {
3510 * $user->addToDatabase();
3512 * // do something with $user...
3514 * However, this was vulnerable to a race condition (bug 16020). By
3515 * initialising the user object if the user exists, we aim to support this
3516 * calling sequence as far as possible.
3518 * Note that if the user exists, this function will acquire a write lock,
3519 * so it is still advisable to make the call conditional on isLoggedIn(),
3520 * and to commit the transaction after calling.
3522 * @throws MWException
3525 public function addToDatabase() {
3527 if ( !$this->mToken
) {
3528 $this->setToken(); // init token
3531 $this->mTouched
= self
::newTouchedTimestamp();
3533 $dbw = wfGetDB( DB_MASTER
);
3534 $inWrite = $dbw->writesOrCallbacksPending();
3535 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3536 $dbw->insert( 'user',
3538 'user_id' => $seqVal,
3539 'user_name' => $this->mName
,
3540 'user_password' => $this->mPassword
,
3541 'user_newpassword' => $this->mNewpassword
,
3542 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3543 'user_email' => $this->mEmail
,
3544 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3545 'user_real_name' => $this->mRealName
,
3546 'user_token' => strval( $this->mToken
),
3547 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3548 'user_editcount' => 0,
3549 'user_touched' => $dbw->timestamp( $this->mTouched
),
3553 if ( !$dbw->affectedRows() ) {
3555 // XXX: Get out of REPEATABLE-READ so the SELECT below works.
3556 // Often this case happens early in views before any writes.
3557 // This shows up at least with CentralAuth.
3558 $dbw->commit( __METHOD__
, 'flush' );
3560 $this->mId
= $dbw->selectField( 'user', 'user_id',
3561 array( 'user_name' => $this->mName
), __METHOD__
);
3564 if ( $this->loadFromDatabase() ) {
3569 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3570 "to insert user '{$this->mName}' row, but it was not present in select!" );
3572 return Status
::newFatal( 'userexists' );
3574 $this->mId
= $dbw->insertId();
3576 // Clear instance cache other than user table data, which is already accurate
3577 $this->clearInstanceCache();
3579 $this->saveOptions();
3580 return Status
::newGood();
3584 * If this user is logged-in and blocked,
3585 * block any IP address they've successfully logged in from.
3586 * @return bool A block was spread
3588 public function spreadAnyEditBlock() {
3589 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3590 return $this->spreadBlock();
3596 * If this (non-anonymous) user is blocked,
3597 * block the IP address they've successfully logged in from.
3598 * @return bool A block was spread
3600 protected function spreadBlock() {
3601 wfDebug( __METHOD__
. "()\n" );
3603 if ( $this->mId
== 0 ) {
3607 $userblock = Block
::newFromTarget( $this->getName() );
3608 if ( !$userblock ) {
3612 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3616 * Get whether the user is explicitly blocked from account creation.
3617 * @return bool|Block
3619 public function isBlockedFromCreateAccount() {
3620 $this->getBlockedStatus();
3621 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3622 return $this->mBlock
;
3625 # bug 13611: if the IP address the user is trying to create an account from is
3626 # blocked with createaccount disabled, prevent new account creation there even
3627 # when the user is logged in
3628 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3629 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3631 return $this->mBlockedFromCreateAccount
instanceof Block
&& $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3632 ?
$this->mBlockedFromCreateAccount
3637 * Get whether the user is blocked from using Special:Emailuser.
3640 public function isBlockedFromEmailuser() {
3641 $this->getBlockedStatus();
3642 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3646 * Get whether the user is allowed to create an account.
3649 public function isAllowedToCreateAccount() {
3650 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3654 * Get this user's personal page title.
3656 * @return Title: User's personal page title
3658 public function getUserPage() {
3659 return Title
::makeTitle( NS_USER
, $this->getName() );
3663 * Get this user's talk page title.
3665 * @return Title: User's talk page title
3667 public function getTalkPage() {
3668 $title = $this->getUserPage();
3669 return $title->getTalkPage();
3673 * Determine whether the user is a newbie. Newbies are either
3674 * anonymous IPs, or the most recently created accounts.
3677 public function isNewbie() {
3678 return !$this->isAllowed( 'autoconfirmed' );
3682 * Check to see if the given clear-text password is one of the accepted passwords
3683 * @param string $password user password.
3684 * @return boolean: True if the given password is correct, otherwise False.
3686 public function checkPassword( $password ) {
3687 global $wgAuth, $wgLegacyEncoding;
3690 // Even though we stop people from creating passwords that
3691 // are shorter than this, doesn't mean people wont be able
3692 // to. Certain authentication plugins do NOT want to save
3693 // domain passwords in a mysql database, so we should
3694 // check this (in case $wgAuth->strict() is false).
3695 if ( !$this->isValidPassword( $password ) ) {
3699 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3701 } elseif ( $wgAuth->strict() ) {
3702 // Auth plugin doesn't allow local authentication
3704 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3705 // Auth plugin doesn't allow local authentication for this user name
3708 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
3710 } elseif ( $wgLegacyEncoding ) {
3711 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3712 // Check for this with iconv
3713 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3714 if ( $cp1252Password != $password
3715 && self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
)
3724 * Check if the given clear-text password matches the temporary password
3725 * sent by e-mail for password reset operations.
3727 * @param $plaintext string
3729 * @return boolean: True if matches, false otherwise
3731 public function checkTemporaryPassword( $plaintext ) {
3732 global $wgNewPasswordExpiry;
3735 if ( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
3736 if ( is_null( $this->mNewpassTime
) ) {
3739 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3740 return ( time() < $expiry );
3747 * Alias for getEditToken.
3748 * @deprecated since 1.19, use getEditToken instead.
3750 * @param string|array $salt of Strings Optional function-specific data for hashing
3751 * @param $request WebRequest object to use or null to use $wgRequest
3752 * @return string The new edit token
3754 public function editToken( $salt = '', $request = null ) {
3755 wfDeprecated( __METHOD__
, '1.19' );
3756 return $this->getEditToken( $salt, $request );
3760 * Initialize (if necessary) and return a session token value
3761 * which can be used in edit forms to show that the user's
3762 * login credentials aren't being hijacked with a foreign form
3767 * @param string|array $salt of Strings Optional function-specific data for hashing
3768 * @param $request WebRequest object to use or null to use $wgRequest
3769 * @return string The new edit token
3771 public function getEditToken( $salt = '', $request = null ) {
3772 if ( $request == null ) {
3773 $request = $this->getRequest();
3776 if ( $this->isAnon() ) {
3777 return EDIT_TOKEN_SUFFIX
;
3779 $token = $request->getSessionData( 'wsEditToken' );
3780 if ( $token === null ) {
3781 $token = MWCryptRand
::generateHex( 32 );
3782 $request->setSessionData( 'wsEditToken', $token );
3784 if ( is_array( $salt ) ) {
3785 $salt = implode( '|', $salt );
3787 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
3792 * Generate a looking random token for various uses.
3794 * @return string The new random token
3795 * @deprecated since 1.20: Use MWCryptRand for secure purposes or wfRandomString for pseudo-randomness
3797 public static function generateToken() {
3798 return MWCryptRand
::generateHex( 32 );
3802 * Check given value against the token value stored in the session.
3803 * A match should confirm that the form was submitted from the
3804 * user's own login session, not a form submission from a third-party
3807 * @param string $val Input value to compare
3808 * @param string $salt Optional function-specific data for hashing
3809 * @param WebRequest $request Object to use or null to use $wgRequest
3810 * @return boolean: Whether the token matches
3812 public function matchEditToken( $val, $salt = '', $request = null ) {
3813 $sessionToken = $this->getEditToken( $salt, $request );
3814 if ( $val != $sessionToken ) {
3815 wfDebug( "User::matchEditToken: broken session data\n" );
3817 return $val == $sessionToken;
3821 * Check given value against the token value stored in the session,
3822 * ignoring the suffix.
3824 * @param string $val Input value to compare
3825 * @param string $salt Optional function-specific data for hashing
3826 * @param WebRequest $request object to use or null to use $wgRequest
3827 * @return boolean: Whether the token matches
3829 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3830 $sessionToken = $this->getEditToken( $salt, $request );
3831 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3835 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3836 * mail to the user's given address.
3838 * @param string $type message to send, either "created", "changed" or "set"
3839 * @return Status object
3841 public function sendConfirmationMail( $type = 'created' ) {
3843 $expiration = null; // gets passed-by-ref and defined in next line.
3844 $token = $this->confirmationToken( $expiration );
3845 $url = $this->confirmationTokenUrl( $token );
3846 $invalidateURL = $this->invalidationTokenUrl( $token );
3847 $this->saveSettings();
3849 if ( $type == 'created' ||
$type === false ) {
3850 $message = 'confirmemail_body';
3851 } elseif ( $type === true ) {
3852 $message = 'confirmemail_body_changed';
3854 // Messages: confirmemail_body_changed, confirmemail_body_set
3855 $message = 'confirmemail_body_' . $type;
3858 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3859 wfMessage( $message,
3860 $this->getRequest()->getIP(),
3863 $wgLang->timeanddate( $expiration, false ),
3865 $wgLang->date( $expiration, false ),
3866 $wgLang->time( $expiration, false ) )->text() );
3870 * Send an e-mail to this user's account. Does not check for
3871 * confirmed status or validity.
3873 * @param string $subject Message subject
3874 * @param string $body Message body
3875 * @param string $from Optional From address; if unspecified, default $wgPasswordSender will be used
3876 * @param string $replyto Reply-To address
3879 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3880 if ( is_null( $from ) ) {
3881 global $wgPasswordSender;
3882 $sender = new MailAddress( $wgPasswordSender,
3883 wfMessage( 'emailsender' )->inContentLanguage()->text() );
3885 $sender = new MailAddress( $from );
3888 $to = new MailAddress( $this );
3889 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
3893 * Generate, store, and return a new e-mail confirmation code.
3894 * A hash (unsalted, since it's used as a key) is stored.
3896 * @note Call saveSettings() after calling this function to commit
3897 * this change to the database.
3899 * @param &$expiration \mixed Accepts the expiration time
3900 * @return string New token
3902 protected function confirmationToken( &$expiration ) {
3903 global $wgUserEmailConfirmationTokenExpiry;
3905 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
3906 $expiration = wfTimestamp( TS_MW
, $expires );
3908 $token = MWCryptRand
::generateHex( 32 );
3909 $hash = md5( $token );
3910 $this->mEmailToken
= $hash;
3911 $this->mEmailTokenExpires
= $expiration;
3916 * Return a URL the user can use to confirm their email address.
3917 * @param string $token Accepts the email confirmation token
3918 * @return string New token URL
3920 protected function confirmationTokenUrl( $token ) {
3921 return $this->getTokenUrl( 'ConfirmEmail', $token );
3925 * Return a URL the user can use to invalidate their email address.
3926 * @param string $token Accepts the email confirmation token
3927 * @return string New token URL
3929 protected function invalidationTokenUrl( $token ) {
3930 return $this->getTokenUrl( 'InvalidateEmail', $token );
3934 * Internal function to format the e-mail validation/invalidation URLs.
3935 * This uses a quickie hack to use the
3936 * hardcoded English names of the Special: pages, for ASCII safety.
3938 * @note Since these URLs get dropped directly into emails, using the
3939 * short English names avoids insanely long URL-encoded links, which
3940 * also sometimes can get corrupted in some browsers/mailers
3941 * (bug 6957 with Gmail and Internet Explorer).
3943 * @param string $page Special page
3944 * @param string $token Token
3945 * @return string Formatted URL
3947 protected function getTokenUrl( $page, $token ) {
3948 // Hack to bypass localization of 'Special:'
3949 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
3950 return $title->getCanonicalURL();
3954 * Mark the e-mail address confirmed.
3956 * @note Call saveSettings() after calling this function to commit the change.
3960 public function confirmEmail() {
3961 // Check if it's already confirmed, so we don't touch the database
3962 // and fire the ConfirmEmailComplete hook on redundant confirmations.
3963 if ( !$this->isEmailConfirmed() ) {
3964 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3965 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3971 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3972 * address if it was already confirmed.
3974 * @note Call saveSettings() after calling this function to commit the change.
3975 * @return bool Returns true
3977 public function invalidateEmail() {
3979 $this->mEmailToken
= null;
3980 $this->mEmailTokenExpires
= null;
3981 $this->setEmailAuthenticationTimestamp( null );
3982 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3987 * Set the e-mail authentication timestamp.
3988 * @param string $timestamp TS_MW timestamp
3990 public function setEmailAuthenticationTimestamp( $timestamp ) {
3992 $this->mEmailAuthenticated
= $timestamp;
3993 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
3997 * Is this user allowed to send e-mails within limits of current
3998 * site configuration?
4001 public function canSendEmail() {
4002 global $wgEnableEmail, $wgEnableUserEmail;
4003 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4006 $canSend = $this->isEmailConfirmed();
4007 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4012 * Is this user allowed to receive e-mails within limits of current
4013 * site configuration?
4016 public function canReceiveEmail() {
4017 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4021 * Is this user's e-mail address valid-looking and confirmed within
4022 * limits of the current site configuration?
4024 * @note If $wgEmailAuthentication is on, this may require the user to have
4025 * confirmed their address by returning a code or using a password
4026 * sent to the address from the wiki.
4030 public function isEmailConfirmed() {
4031 global $wgEmailAuthentication;
4034 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4035 if ( $this->isAnon() ) {
4038 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4041 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4051 * Check whether there is an outstanding request for e-mail confirmation.
4054 public function isEmailConfirmationPending() {
4055 global $wgEmailAuthentication;
4056 return $wgEmailAuthentication &&
4057 !$this->isEmailConfirmed() &&
4058 $this->mEmailToken
&&
4059 $this->mEmailTokenExpires
> wfTimestamp();
4063 * Get the timestamp of account creation.
4065 * @return string|bool|null Timestamp of account creation, false for
4066 * non-existent/anonymous user accounts, or null if existing account
4067 * but information is not in database.
4069 public function getRegistration() {
4070 if ( $this->isAnon() ) {
4074 return $this->mRegistration
;
4078 * Get the timestamp of the first edit
4080 * @return string|bool Timestamp of first edit, or false for
4081 * non-existent/anonymous user accounts.
4083 public function getFirstEditTimestamp() {
4084 if ( $this->getId() == 0 ) {
4085 return false; // anons
4087 $dbr = wfGetDB( DB_SLAVE
);
4088 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4089 array( 'rev_user' => $this->getId() ),
4091 array( 'ORDER BY' => 'rev_timestamp ASC' )
4094 return false; // no edits
4096 return wfTimestamp( TS_MW
, $time );
4100 * Get the permissions associated with a given list of groups
4102 * @param array $groups of Strings List of internal group names
4103 * @return Array of Strings List of permission key names for given groups combined
4105 public static function getGroupPermissions( $groups ) {
4106 global $wgGroupPermissions, $wgRevokePermissions;
4108 // grant every granted permission first
4109 foreach ( $groups as $group ) {
4110 if ( isset( $wgGroupPermissions[$group] ) ) {
4111 $rights = array_merge( $rights,
4112 // array_filter removes empty items
4113 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4116 // now revoke the revoked permissions
4117 foreach ( $groups as $group ) {
4118 if ( isset( $wgRevokePermissions[$group] ) ) {
4119 $rights = array_diff( $rights,
4120 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4123 return array_unique( $rights );
4127 * Get all the groups who have a given permission
4129 * @param string $role Role to check
4130 * @return Array of Strings List of internal group names with the given permission
4132 public static function getGroupsWithPermission( $role ) {
4133 global $wgGroupPermissions;
4134 $allowedGroups = array();
4135 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4136 if ( self
::groupHasPermission( $group, $role ) ) {
4137 $allowedGroups[] = $group;
4140 return $allowedGroups;
4144 * Check, if the given group has the given permission
4146 * If you're wanting to check whether all users have a permission, use
4147 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4151 * @param string $group Group to check
4152 * @param string $role Role to check
4155 public static function groupHasPermission( $group, $role ) {
4156 global $wgGroupPermissions, $wgRevokePermissions;
4157 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4158 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4162 * Check if all users have the given permission
4165 * @param string $right Right to check
4168 public static function isEveryoneAllowed( $right ) {
4169 global $wgGroupPermissions, $wgRevokePermissions;
4170 static $cache = array();
4172 // Use the cached results, except in unit tests which rely on
4173 // being able change the permission mid-request
4174 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4175 return $cache[$right];
4178 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4179 $cache[$right] = false;
4183 // If it's revoked anywhere, then everyone doesn't have it
4184 foreach ( $wgRevokePermissions as $rights ) {
4185 if ( isset( $rights[$right] ) && $rights[$right] ) {
4186 $cache[$right] = false;
4191 // Allow extensions (e.g. OAuth) to say false
4192 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4193 $cache[$right] = false;
4197 $cache[$right] = true;
4202 * Get the localized descriptive name for a group, if it exists
4204 * @param string $group Internal group name
4205 * @return string Localized descriptive group name
4207 public static function getGroupName( $group ) {
4208 $msg = wfMessage( "group-$group" );
4209 return $msg->isBlank() ?
$group : $msg->text();
4213 * Get the localized descriptive name for a member of a group, if it exists
4215 * @param string $group Internal group name
4216 * @param string $username Username for gender (since 1.19)
4217 * @return string Localized name for group member
4219 public static function getGroupMember( $group, $username = '#' ) {
4220 $msg = wfMessage( "group-$group-member", $username );
4221 return $msg->isBlank() ?
$group : $msg->text();
4225 * Return the set of defined explicit groups.
4226 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4227 * are not included, as they are defined automatically, not in the database.
4228 * @return Array of internal group names
4230 public static function getAllGroups() {
4231 global $wgGroupPermissions, $wgRevokePermissions;
4233 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4234 self
::getImplicitGroups()
4239 * Get a list of all available permissions.
4240 * @return Array of permission names
4242 public static function getAllRights() {
4243 if ( self
::$mAllRights === false ) {
4244 global $wgAvailableRights;
4245 if ( count( $wgAvailableRights ) ) {
4246 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4248 self
::$mAllRights = self
::$mCoreRights;
4250 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
4252 return self
::$mAllRights;
4256 * Get a list of implicit groups
4257 * @return Array of Strings Array of internal group names
4259 public static function getImplicitGroups() {
4260 global $wgImplicitGroups;
4261 $groups = $wgImplicitGroups;
4262 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
4267 * Get the title of a page describing a particular group
4269 * @param string $group Internal group name
4270 * @return Title|bool Title of the page if it exists, false otherwise
4272 public static function getGroupPage( $group ) {
4273 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4274 if ( $msg->exists() ) {
4275 $title = Title
::newFromText( $msg->text() );
4276 if ( is_object( $title ) ) {
4284 * Create a link to the group in HTML, if available;
4285 * else return the group name.
4287 * @param string $group Internal name of the group
4288 * @param string $text The text of the link
4289 * @return string HTML link to the group
4291 public static function makeGroupLinkHTML( $group, $text = '' ) {
4292 if ( $text == '' ) {
4293 $text = self
::getGroupName( $group );
4295 $title = self
::getGroupPage( $group );
4297 return Linker
::link( $title, htmlspecialchars( $text ) );
4304 * Create a link to the group in Wikitext, if available;
4305 * else return the group name.
4307 * @param string $group Internal name of the group
4308 * @param string $text The text of the link
4309 * @return string Wikilink to the group
4311 public static function makeGroupLinkWiki( $group, $text = '' ) {
4312 if ( $text == '' ) {
4313 $text = self
::getGroupName( $group );
4315 $title = self
::getGroupPage( $group );
4317 $page = $title->getPrefixedText();
4318 return "[[$page|$text]]";
4325 * Returns an array of the groups that a particular group can add/remove.
4327 * @param string $group the group to check for whether it can add/remove
4328 * @return Array array( 'add' => array( addablegroups ),
4329 * 'remove' => array( removablegroups ),
4330 * 'add-self' => array( addablegroups to self),
4331 * 'remove-self' => array( removable groups from self) )
4333 public static function changeableByGroup( $group ) {
4334 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4336 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
4337 if ( empty( $wgAddGroups[$group] ) ) {
4338 // Don't add anything to $groups
4339 } elseif ( $wgAddGroups[$group] === true ) {
4340 // You get everything
4341 $groups['add'] = self
::getAllGroups();
4342 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4343 $groups['add'] = $wgAddGroups[$group];
4346 // Same thing for remove
4347 if ( empty( $wgRemoveGroups[$group] ) ) {
4348 } elseif ( $wgRemoveGroups[$group] === true ) {
4349 $groups['remove'] = self
::getAllGroups();
4350 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4351 $groups['remove'] = $wgRemoveGroups[$group];
4354 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4355 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4356 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4357 if ( is_int( $key ) ) {
4358 $wgGroupsAddToSelf['user'][] = $value;
4363 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4364 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4365 if ( is_int( $key ) ) {
4366 $wgGroupsRemoveFromSelf['user'][] = $value;
4371 // Now figure out what groups the user can add to him/herself
4372 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4373 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4374 // No idea WHY this would be used, but it's there
4375 $groups['add-self'] = User
::getAllGroups();
4376 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4377 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4380 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4381 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4382 $groups['remove-self'] = User
::getAllGroups();
4383 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4384 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4391 * Returns an array of groups that this user can add and remove
4392 * @return Array array( 'add' => array( addablegroups ),
4393 * 'remove' => array( removablegroups ),
4394 * 'add-self' => array( addablegroups to self),
4395 * 'remove-self' => array( removable groups from self) )
4397 public function changeableGroups() {
4398 if ( $this->isAllowed( 'userrights' ) ) {
4399 // This group gives the right to modify everything (reverse-
4400 // compatibility with old "userrights lets you change
4402 // Using array_merge to make the groups reindexed
4403 $all = array_merge( User
::getAllGroups() );
4407 'add-self' => array(),
4408 'remove-self' => array()
4412 // Okay, it's not so simple, we will have to go through the arrays
4415 'remove' => array(),
4416 'add-self' => array(),
4417 'remove-self' => array()
4419 $addergroups = $this->getEffectiveGroups();
4421 foreach ( $addergroups as $addergroup ) {
4422 $groups = array_merge_recursive(
4423 $groups, $this->changeableByGroup( $addergroup )
4425 $groups['add'] = array_unique( $groups['add'] );
4426 $groups['remove'] = array_unique( $groups['remove'] );
4427 $groups['add-self'] = array_unique( $groups['add-self'] );
4428 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4434 * Increment the user's edit-count field.
4435 * Will have no effect for anonymous users.
4437 public function incEditCount() {
4438 if ( !$this->isAnon() ) {
4439 $dbw = wfGetDB( DB_MASTER
);
4442 array( 'user_editcount=user_editcount+1' ),
4443 array( 'user_id' => $this->getId() ),
4447 // Lazy initialization check...
4448 if ( $dbw->affectedRows() == 0 ) {
4449 // Now here's a goddamn hack...
4450 $dbr = wfGetDB( DB_SLAVE
);
4451 if ( $dbr !== $dbw ) {
4452 // If we actually have a slave server, the count is
4453 // at least one behind because the current transaction
4454 // has not been committed and replicated.
4455 $this->initEditCount( 1 );
4457 // But if DB_SLAVE is selecting the master, then the
4458 // count we just read includes the revision that was
4459 // just added in the working transaction.
4460 $this->initEditCount();
4464 // edit count in user cache too
4465 $this->invalidateCache();
4469 * Initialize user_editcount from data out of the revision table
4471 * @param $add Integer Edits to add to the count from the revision table
4472 * @return integer Number of edits
4474 protected function initEditCount( $add = 0 ) {
4475 // Pull from a slave to be less cruel to servers
4476 // Accuracy isn't the point anyway here
4477 $dbr = wfGetDB( DB_SLAVE
);
4478 $count = (int)$dbr->selectField(
4481 array( 'rev_user' => $this->getId() ),
4484 $count = $count +
$add;
4486 $dbw = wfGetDB( DB_MASTER
);
4489 array( 'user_editcount' => $count ),
4490 array( 'user_id' => $this->getId() ),
4498 * Get the description of a given right
4500 * @param string $right Right to query
4501 * @return string Localized description of the right
4503 public static function getRightDescription( $right ) {
4504 $key = "right-$right";
4505 $msg = wfMessage( $key );
4506 return $msg->isBlank() ?
$right : $msg->text();
4510 * Make an old-style password hash
4512 * @param string $password Plain-text password
4513 * @param string $userId User ID
4514 * @return string Password hash
4516 public static function oldCrypt( $password, $userId ) {
4517 global $wgPasswordSalt;
4518 if ( $wgPasswordSalt ) {
4519 return md5( $userId . '-' . md5( $password ) );
4521 return md5( $password );
4526 * Make a new-style password hash
4528 * @param string $password Plain-text password
4529 * @param bool|string $salt Optional salt, may be random or the user ID.
4530 * If unspecified or false, will generate one automatically
4531 * @return string Password hash
4533 public static function crypt( $password, $salt = false ) {
4534 global $wgPasswordSalt;
4537 if ( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4541 if ( $wgPasswordSalt ) {
4542 if ( $salt === false ) {
4543 $salt = MWCryptRand
::generateHex( 8 );
4545 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4547 return ':A:' . md5( $password );
4552 * Compare a password hash with a plain-text password. Requires the user
4553 * ID if there's a chance that the hash is an old-style hash.
4555 * @param string $hash Password hash
4556 * @param string $password Plain-text password to compare
4557 * @param string|bool $userId User ID for old-style password salt
4561 public static function comparePasswords( $hash, $password, $userId = false ) {
4562 $type = substr( $hash, 0, 3 );
4565 if ( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4569 if ( $type == ':A:' ) {
4571 return md5( $password ) === substr( $hash, 3 );
4572 } elseif ( $type == ':B:' ) {
4574 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4575 return md5( $salt . '-' . md5( $password ) ) === $realHash;
4578 return self
::oldCrypt( $password, $userId ) === $hash;
4583 * Add a newuser log entry for this user.
4584 * Before 1.19 the return value was always true.
4586 * @param string|bool $action account creation type.
4587 * - String, one of the following values:
4588 * - 'create' for an anonymous user creating an account for himself.
4589 * This will force the action's performer to be the created user itself,
4590 * no matter the value of $wgUser
4591 * - 'create2' for a logged in user creating an account for someone else
4592 * - 'byemail' when the created user will receive its password by e-mail
4593 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4594 * - Boolean means whether the account was created by e-mail (deprecated):
4595 * - true will be converted to 'byemail'
4596 * - false will be converted to 'create' if this object is the same as
4597 * $wgUser and to 'create2' otherwise
4599 * @param string $reason user supplied reason
4601 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4603 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4604 global $wgUser, $wgNewUserLog;
4605 if ( empty( $wgNewUserLog ) ) {
4606 return true; // disabled
4609 if ( $action === true ) {
4610 $action = 'byemail';
4611 } elseif ( $action === false ) {
4612 if ( $this->getName() == $wgUser->getName() ) {
4615 $action = 'create2';
4619 if ( $action === 'create' ||
$action === 'autocreate' ) {
4622 $performer = $wgUser;
4625 $logEntry = new ManualLogEntry( 'newusers', $action );
4626 $logEntry->setPerformer( $performer );
4627 $logEntry->setTarget( $this->getUserPage() );
4628 $logEntry->setComment( $reason );
4629 $logEntry->setParameters( array(
4630 '4::userid' => $this->getId(),
4632 $logid = $logEntry->insert();
4634 if ( $action !== 'autocreate' ) {
4635 $logEntry->publish( $logid );
4642 * Add an autocreate newuser log entry for this user
4643 * Used by things like CentralAuth and perhaps other authplugins.
4644 * Consider calling addNewUserLogEntry() directly instead.
4648 public function addNewUserLogEntryAutoCreate() {
4649 $this->addNewUserLogEntry( 'autocreate' );
4655 * Load the user options either from cache, the database or an array
4657 * @param array $data Rows for the current user out of the user_properties table
4659 protected function loadOptions( $data = null ) {
4664 if ( $this->mOptionsLoaded
) {
4668 $this->mOptions
= self
::getDefaultOptions();
4670 if ( !$this->getId() ) {
4671 // For unlogged-in users, load language/variant options from request.
4672 // There's no need to do it for logged-in users: they can set preferences,
4673 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4674 // so don't override user's choice (especially when the user chooses site default).
4675 $variant = $wgContLang->getDefaultVariant();
4676 $this->mOptions
['variant'] = $variant;
4677 $this->mOptions
['language'] = $variant;
4678 $this->mOptionsLoaded
= true;
4682 // Maybe load from the object
4683 if ( !is_null( $this->mOptionOverrides
) ) {
4684 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4685 foreach ( $this->mOptionOverrides
as $key => $value ) {
4686 $this->mOptions
[$key] = $value;
4689 if ( !is_array( $data ) ) {
4690 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4691 // Load from database
4692 $dbr = wfGetDB( DB_SLAVE
);
4694 $res = $dbr->select(
4696 array( 'up_property', 'up_value' ),
4697 array( 'up_user' => $this->getId() ),
4701 $this->mOptionOverrides
= array();
4703 foreach ( $res as $row ) {
4704 $data[$row->up_property
] = $row->up_value
;
4707 foreach ( $data as $property => $value ) {
4708 $this->mOptionOverrides
[$property] = $value;
4709 $this->mOptions
[$property] = $value;
4713 $this->mOptionsLoaded
= true;
4715 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
4721 protected function saveOptions() {
4722 $this->loadOptions();
4724 // Not using getOptions(), to keep hidden preferences in database
4725 $saveOptions = $this->mOptions
;
4727 // Allow hooks to abort, for instance to save to a global profile.
4728 // Reset options to default state before saving.
4729 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4733 $userId = $this->getId();
4734 $insert_rows = array();
4735 foreach ( $saveOptions as $key => $value ) {
4736 // Don't bother storing default values
4737 $defaultOption = self
::getDefaultOption( $key );
4738 if ( ( is_null( $defaultOption ) &&
4739 !( $value === false ||
is_null( $value ) ) ) ||
4740 $value != $defaultOption
4742 $insert_rows[] = array(
4743 'up_user' => $userId,
4744 'up_property' => $key,
4745 'up_value' => $value,
4750 $dbw = wfGetDB( DB_MASTER
);
4751 // Find and delete any prior preference rows...
4752 $res = $dbw->select( 'user_properties',
4753 array( 'up_property' ), array( 'up_user' => $userId ), __METHOD__
);
4754 $priorKeys = array();
4755 foreach ( $res as $row ) {
4756 $priorKeys[] = $row->up_property
;
4758 if ( count( $priorKeys ) ) {
4759 // Do the DELETE by PRIMARY KEY for prior rows. A very large portion of
4760 // calls to this function are for setting 'rememberpassword' for new accounts.
4761 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4762 // causes gap locks on [max user ID,+infinity) which causes high contention since
4763 // updates will pile up on each other as they are for higher (newer) user IDs.
4764 $dbw->delete( 'user_properties',
4765 array( 'up_user' => $userId, 'up_property' => $priorKeys ), __METHOD__
);
4767 // Insert the new preference rows
4768 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
4772 * Provide an array of HTML5 attributes to put on an input element
4773 * intended for the user to enter a new password. This may include
4774 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4776 * Do *not* use this when asking the user to enter his current password!
4777 * Regardless of configuration, users may have invalid passwords for whatever
4778 * reason (e.g., they were set before requirements were tightened up).
4779 * Only use it when asking for a new password, like on account creation or
4782 * Obviously, you still need to do server-side checking.
4784 * NOTE: A combination of bugs in various browsers means that this function
4785 * actually just returns array() unconditionally at the moment. May as
4786 * well keep it around for when the browser bugs get fixed, though.
4788 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4790 * @return array Array of HTML attributes suitable for feeding to
4791 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4792 * That will get confused by the boolean attribute syntax used.)
4794 public static function passwordChangeInputAttribs() {
4795 global $wgMinimalPasswordLength;
4797 if ( $wgMinimalPasswordLength == 0 ) {
4801 # Note that the pattern requirement will always be satisfied if the
4802 # input is empty, so we need required in all cases.
4804 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4805 # if e-mail confirmation is being used. Since HTML5 input validation
4806 # is b0rked anyway in some browsers, just return nothing. When it's
4807 # re-enabled, fix this code to not output required for e-mail
4809 #$ret = array( 'required' );
4812 # We can't actually do this right now, because Opera 9.6 will print out
4813 # the entered password visibly in its error message! When other
4814 # browsers add support for this attribute, or Opera fixes its support,
4815 # we can add support with a version check to avoid doing this on Opera
4816 # versions where it will be a problem. Reported to Opera as
4817 # DSK-262266, but they don't have a public bug tracker for us to follow.
4819 if ( $wgMinimalPasswordLength > 1 ) {
4820 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4821 $ret['title'] = wfMessage( 'passwordtooshort' )
4822 ->numParams( $wgMinimalPasswordLength )->text();
4830 * Return the list of user fields that should be selected to create
4831 * a new user object.
4834 public static function selectFields() {
4841 'user_newpass_time',
4845 'user_email_authenticated',
4847 'user_email_token_expires',
4848 'user_password_expires',
4849 'user_registration',
4855 * Factory function for fatal permission-denied errors
4858 * @param string $permission User right required
4861 static function newFatalPermissionDeniedStatus( $permission ) {
4864 $groups = array_map(
4865 array( 'User', 'makeGroupLinkWiki' ),
4866 User
::getGroupsWithPermission( $permission )
4870 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4872 return Status
::newFatal( 'badaccess-group0' );