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', 8 );
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',
97 // user_properties table
102 * Array of Strings Core rights.
103 * Each of these should have a corresponding message of the form
107 static $mCoreRights = array(
130 'editusercssjs', #deprecated
142 'move-rootuserpages',
146 'override-export-depth',
169 'userrights-interwiki',
174 * String Cached results of getAllRights()
176 static $mAllRights = false;
178 /** @name Cache variables */
180 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
181 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
182 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mEditCount,
183 $mGroups, $mOptionOverrides;
187 * Bool Whether the cache variables have been loaded.
193 * Array with already loaded items or true if all items have been loaded.
195 private $mLoadedItems = array();
199 * String Initialization data source if mLoadedItems!==true. May be one of:
200 * - 'defaults' anonymous user initialised from class defaults
201 * - 'name' initialise from mName
202 * - 'id' initialise from mId
203 * - 'session' log in from cookies or session if possible
205 * Use the User::newFrom*() family of functions to set this.
210 * Lazy-initialized variables, invalidated with clearInstanceCache
212 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mRights,
213 $mBlockreason, $mEffectiveGroups, $mImplicitGroups, $mFormerGroups, $mBlockedGlobally,
214 $mLocked, $mHideName, $mOptions;
234 private $mBlockedFromCreateAccount = false;
239 private $mWatchedItems = array();
241 static $idCacheByName = array();
244 * Lightweight constructor for an anonymous user.
245 * Use the User::newFrom* factory functions for other kinds of users.
249 * @see newFromConfirmationCode()
250 * @see newFromSession()
253 function __construct() {
254 $this->clearInstanceCache( 'defaults' );
260 function __toString() {
261 return $this->getName();
265 * Load the user table data for this object from the source given by mFrom.
267 public function load() {
268 if ( $this->mLoadedItems
=== true ) {
271 wfProfileIn( __METHOD__
);
273 // Set it now to avoid infinite recursion in accessors
274 $this->mLoadedItems
= true;
276 switch ( $this->mFrom
) {
278 $this->loadDefaults();
281 $this->mId
= self
::idFromName( $this->mName
);
283 // Nonexistent user placeholder object
284 $this->loadDefaults( $this->mName
);
293 if ( !$this->loadFromSession() ) {
294 // Loading from session failed. Load defaults.
295 $this->loadDefaults();
297 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
300 wfProfileOut( __METHOD__
);
301 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
303 wfProfileOut( __METHOD__
);
307 * Load user table data, given mId has already been set.
308 * @return bool false if the ID does not exist, true otherwise
310 public function loadFromId() {
312 if ( $this->mId
== 0 ) {
313 $this->loadDefaults();
318 $key = wfMemcKey( 'user', 'id', $this->mId
);
319 $data = $wgMemc->get( $key );
320 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
321 // Object is expired, load from DB
326 wfDebug( "User: cache miss for user {$this->mId}\n" );
328 if ( !$this->loadFromDatabase() ) {
329 // Can't load from ID, user is anonymous
332 $this->saveToCache();
334 wfDebug( "User: got user {$this->mId} from cache\n" );
335 // Restore from cache
336 foreach ( self
::$mCacheVars as $name ) {
337 $this->$name = $data[$name];
341 $this->mLoadedItems
= true;
347 * Save user data to the shared cache
349 public function saveToCache() {
352 $this->loadOptions();
353 if ( $this->isAnon() ) {
354 // Anonymous users are uncached
358 foreach ( self
::$mCacheVars as $name ) {
359 $data[$name] = $this->$name;
361 $data['mVersion'] = MW_USER_VERSION
;
362 $key = wfMemcKey( 'user', 'id', $this->mId
);
364 $wgMemc->set( $key, $data );
367 /** @name newFrom*() static factory methods */
371 * Static factory method for creation from username.
373 * This is slightly less efficient than newFromId(), so use newFromId() if
374 * you have both an ID and a name handy.
376 * @param string $name Username, validated by Title::newFromText()
377 * @param string|bool $validate Validate username. Takes the same parameters as
378 * User::getCanonicalName(), except that true is accepted as an alias
379 * for 'valid', for BC.
381 * @return User|bool User object, or false if the username is invalid
382 * (e.g. if it contains illegal characters or is an IP address). If the
383 * username is not present in the database, the result will be a user object
384 * with a name, zero user ID and default settings.
386 public static function newFromName( $name, $validate = 'valid' ) {
387 if ( $validate === true ) {
390 $name = self
::getCanonicalName( $name, $validate );
391 if ( $name === false ) {
394 // Create unloaded user object
398 $u->setItemLoaded( 'name' );
404 * Static factory method for creation from a given user ID.
406 * @param int $id Valid user ID
407 * @return User The corresponding User object
409 public static function newFromId( $id ) {
413 $u->setItemLoaded( 'id' );
418 * Factory method to fetch whichever user has a given email confirmation code.
419 * This code is generated when an account is created or its e-mail address
422 * If the code is invalid or has expired, returns NULL.
424 * @param string $code Confirmation code
427 public static function newFromConfirmationCode( $code ) {
428 $dbr = wfGetDB( DB_SLAVE
);
429 $id = $dbr->selectField( 'user', 'user_id', array(
430 'user_email_token' => md5( $code ),
431 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
433 if ( $id !== false ) {
434 return User
::newFromId( $id );
441 * Create a new user object using data from session or cookies. If the
442 * login credentials are invalid, the result is an anonymous user.
444 * @param WebRequest $request Object to use; $wgRequest will be used if omitted.
445 * @return User object
447 public static function newFromSession( WebRequest
$request = null ) {
449 $user->mFrom
= 'session';
450 $user->mRequest
= $request;
455 * Create a new user object from a user row.
456 * The row should have the following fields from the user table in it:
457 * - either user_name or user_id to load further data if needed (or both)
459 * - all other fields (email, password, etc.)
460 * It is useless to provide the remaining fields if either user_id,
461 * user_name and user_real_name are not provided because the whole row
462 * will be loaded once more from the database when accessing them.
464 * @param array $row A row from the user table
465 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
468 public static function newFromRow( $row, $data = null ) {
470 $user->loadFromRow( $row, $data );
477 * Get the username corresponding to a given user ID
478 * @param int $id User ID
479 * @return string|bool The corresponding username
481 public static function whoIs( $id ) {
482 return UserCache
::singleton()->getProp( $id, 'name' );
486 * Get the real name of a user given their user ID
488 * @param int $id User ID
489 * @return string|bool The corresponding user's real name
491 public static function whoIsReal( $id ) {
492 return UserCache
::singleton()->getProp( $id, 'real_name' );
496 * Get database id given a user name
497 * @param string $name Username
498 * @return int|null The corresponding user's ID, or null if user is nonexistent
500 public static function idFromName( $name ) {
501 $nt = Title
::makeTitleSafe( NS_USER
, $name );
502 if ( is_null( $nt ) ) {
507 if ( isset( self
::$idCacheByName[$name] ) ) {
508 return self
::$idCacheByName[$name];
511 $dbr = wfGetDB( DB_SLAVE
);
512 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
514 if ( $s === false ) {
517 $result = $s->user_id
;
520 self
::$idCacheByName[$name] = $result;
522 if ( count( self
::$idCacheByName ) > 1000 ) {
523 self
::$idCacheByName = array();
530 * Reset the cache used in idFromName(). For use in tests.
532 public static function resetIdByNameCache() {
533 self
::$idCacheByName = array();
537 * Does the string match an anonymous IPv4 address?
539 * This function exists for username validation, in order to reject
540 * usernames which are similar in form to IP addresses. Strings such
541 * as 300.300.300.300 will return true because it looks like an IP
542 * address, despite not being strictly valid.
544 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
545 * address because the usemod software would "cloak" anonymous IP
546 * addresses like this, if we allowed accounts like this to be created
547 * new users could get the old edits of these anonymous users.
549 * @param string $name Name to match
552 public static function isIP( $name ) {
553 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name ) || IP
::isIPv6( $name );
557 * Is the input a valid username?
559 * Checks if the input is a valid username, we don't want an empty string,
560 * an IP address, anything that contains slashes (would mess up subpages),
561 * is longer than the maximum allowed username size or doesn't begin with
564 * @param string $name Name to match
567 public static function isValidUserName( $name ) {
568 global $wgContLang, $wgMaxNameChars;
571 || User
::isIP( $name )
572 ||
strpos( $name, '/' ) !== false
573 ||
strlen( $name ) > $wgMaxNameChars
574 ||
$name != $wgContLang->ucfirst( $name ) ) {
575 wfDebugLog( 'username', __METHOD__
.
576 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
580 // Ensure that the name can't be misresolved as a different title,
581 // such as with extra namespace keys at the start.
582 $parsed = Title
::newFromText( $name );
583 if ( is_null( $parsed )
584 ||
$parsed->getNamespace()
585 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
586 wfDebugLog( 'username', __METHOD__
.
587 ": '$name' invalid due to ambiguous prefixes" );
591 // Check an additional blacklist of troublemaker characters.
592 // Should these be merged into the title char list?
593 $unicodeBlacklist = '/[' .
594 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
595 '\x{00a0}' . # non-breaking space
596 '\x{2000}-\x{200f}' . # various whitespace
597 '\x{2028}-\x{202f}' . # breaks and control chars
598 '\x{3000}' . # ideographic space
599 '\x{e000}-\x{f8ff}' . # private use
601 if ( preg_match( $unicodeBlacklist, $name ) ) {
602 wfDebugLog( 'username', __METHOD__
.
603 ": '$name' invalid due to blacklisted characters" );
611 * Usernames which fail to pass this function will be blocked
612 * from user login and new account registrations, but may be used
613 * internally by batch processes.
615 * If an account already exists in this form, login will be blocked
616 * by a failure to pass this function.
618 * @param string $name Name to match
621 public static function isUsableName( $name ) {
622 global $wgReservedUsernames;
623 // Must be a valid username, obviously ;)
624 if ( !self
::isValidUserName( $name ) ) {
628 static $reservedUsernames = false;
629 if ( !$reservedUsernames ) {
630 $reservedUsernames = $wgReservedUsernames;
631 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
634 // Certain names may be reserved for batch processes.
635 foreach ( $reservedUsernames as $reserved ) {
636 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
637 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
639 if ( $reserved == $name ) {
647 * Usernames which fail to pass this function will be blocked
648 * from new account registrations, but may be used internally
649 * either by batch processes or by user accounts which have
650 * already been created.
652 * Additional blacklisting may be added here rather than in
653 * isValidUserName() to avoid disrupting existing accounts.
655 * @param string $name to match
658 public static function isCreatableName( $name ) {
659 global $wgInvalidUsernameCharacters;
661 // Ensure that the username isn't longer than 235 bytes, so that
662 // (at least for the builtin skins) user javascript and css files
663 // will work. (bug 23080)
664 if ( strlen( $name ) > 235 ) {
665 wfDebugLog( 'username', __METHOD__
.
666 ": '$name' invalid due to length" );
670 // Preg yells if you try to give it an empty string
671 if ( $wgInvalidUsernameCharacters !== '' ) {
672 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
673 wfDebugLog( 'username', __METHOD__
.
674 ": '$name' invalid due to wgInvalidUsernameCharacters" );
679 return self
::isUsableName( $name );
683 * Is the input a valid password for this user?
685 * @param string $password Desired password
688 public function isValidPassword( $password ) {
689 //simple boolean wrapper for getPasswordValidity
690 return $this->getPasswordValidity( $password ) === true;
694 * Given unvalidated password input, return error message on failure.
696 * @param string $password Desired password
697 * @return mixed: true on success, string or array of error message on failure
699 public function getPasswordValidity( $password ) {
700 global $wgMinimalPasswordLength, $wgContLang;
702 static $blockedLogins = array(
703 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
704 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
707 $result = false; //init $result to false for the internal checks
709 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
713 if ( $result === false ) {
714 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
715 return 'passwordtooshort';
716 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
717 return 'password-name-match';
718 } elseif ( isset( $blockedLogins[$this->getName()] ) && $password == $blockedLogins[$this->getName()] ) {
719 return 'password-login-forbidden';
721 //it seems weird returning true here, but this is because of the
722 //initialization of $result to false above. If the hook is never run or it
723 //doesn't modify $result, then we will likely get down into this if with
727 } elseif ( $result === true ) {
730 return $result; //the isValidPassword hook set a string $result and returned true
735 * Does a string look like an e-mail address?
737 * This validates an email address using an HTML5 specification found at:
738 * http://www.whatwg.org/html/states-of-the-type-attribute.html#valid-e-mail-address
739 * Which as of 2011-01-24 says:
741 * A valid e-mail address is a string that matches the ABNF production
742 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
743 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
746 * This function is an implementation of the specification as requested in
749 * Client-side forms will use the same standard validation rules via JS or
750 * HTML 5 validation; additional restrictions can be enforced server-side
751 * by extensions via the 'isValidEmailAddr' hook.
753 * Note that this validation doesn't 100% match RFC 2822, but is believed
754 * to be liberal enough for wide use. Some invalid addresses will still
755 * pass validation here.
757 * @param string $addr E-mail address
759 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
761 public static function isValidEmailAddr( $addr ) {
762 wfDeprecated( __METHOD__
, '1.18' );
763 return Sanitizer
::validateEmail( $addr );
767 * Given unvalidated user input, return a canonical username, or false if
768 * the username is invalid.
769 * @param string $name User input
770 * @param string|bool $validate type of validation to use:
771 * - false No validation
772 * - 'valid' Valid for batch processes
773 * - 'usable' Valid for batch processes and login
774 * - 'creatable' Valid for batch processes, login and account creation
776 * @throws MWException
777 * @return bool|string
779 public static function getCanonicalName( $name, $validate = 'valid' ) {
780 // Force usernames to capital
782 $name = $wgContLang->ucfirst( $name );
784 # Reject names containing '#'; these will be cleaned up
785 # with title normalisation, but then it's too late to
787 if ( strpos( $name, '#' ) !== false ) {
791 // Clean up name according to title rules
792 $t = ( $validate === 'valid' ) ?
793 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
794 // Check for invalid titles
795 if ( is_null( $t ) ) {
799 // Reject various classes of invalid names
801 $name = $wgAuth->getCanonicalName( $t->getText() );
803 switch ( $validate ) {
807 if ( !User
::isValidUserName( $name ) ) {
812 if ( !User
::isUsableName( $name ) ) {
817 if ( !User
::isCreatableName( $name ) ) {
822 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
828 * Count the number of edits of a user
830 * @param int $uid User ID to check
831 * @return int The user's edit count
833 * @deprecated since 1.21 in favour of User::getEditCount
835 public static function edits( $uid ) {
836 wfDeprecated( __METHOD__
, '1.21' );
837 $user = self
::newFromId( $uid );
838 return $user->getEditCount();
842 * Return a random password.
844 * @return string New random password
846 public static function randomPassword() {
847 global $wgMinimalPasswordLength;
848 // Decide the final password length based on our min password length, stopping at a minimum of 10 chars
849 $length = max( 10, $wgMinimalPasswordLength );
850 // Multiply by 1.25 to get the number of hex characters we need
851 $length = $length * 1.25;
852 // Generate random hex chars
853 $hex = MWCryptRand
::generateHex( $length );
854 // Convert from base 16 to base 32 to get a proper password like string
855 return wfBaseConvert( $hex, 16, 32 );
859 * Set cached properties to default.
861 * @note This no longer clears uncached lazy-initialised properties;
862 * the constructor does that instead.
864 * @param $name string|bool
866 public function loadDefaults( $name = false ) {
867 wfProfileIn( __METHOD__
);
870 $this->mName
= $name;
871 $this->mRealName
= '';
872 $this->mPassword
= $this->mNewpassword
= '';
873 $this->mNewpassTime
= null;
875 $this->mOptionOverrides
= null;
876 $this->mOptionsLoaded
= false;
878 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
879 if ( $loggedOut !== null ) {
880 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
882 $this->mTouched
= '1'; # Allow any pages to be cached
885 $this->mToken
= null; // Don't run cryptographic functions till we need a token
886 $this->mEmailAuthenticated
= null;
887 $this->mEmailToken
= '';
888 $this->mEmailTokenExpires
= null;
889 $this->mRegistration
= wfTimestamp( TS_MW
);
890 $this->mGroups
= array();
892 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
894 wfProfileOut( __METHOD__
);
898 * Return whether an item has been loaded.
900 * @param string $item item to check. Current possibilities:
904 * @param string $all 'all' to check if the whole object has been loaded
905 * or any other string to check if only the item is available (e.g.
909 public function isItemLoaded( $item, $all = 'all' ) {
910 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
911 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
915 * Set that an item has been loaded
917 * @param string $item
919 protected function setItemLoaded( $item ) {
920 if ( is_array( $this->mLoadedItems
) ) {
921 $this->mLoadedItems
[$item] = true;
926 * Load user data from the session or login cookie.
927 * @return bool True if the user is logged in, false otherwise.
929 private function loadFromSession() {
931 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
932 if ( $result !== null ) {
936 $request = $this->getRequest();
938 $cookieId = $request->getCookie( 'UserID' );
939 $sessId = $request->getSessionData( 'wsUserID' );
941 if ( $cookieId !== null ) {
942 $sId = intval( $cookieId );
943 if ( $sessId !== null && $cookieId != $sessId ) {
944 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
945 cookie user ID ($sId) don't match!" );
948 $request->setSessionData( 'wsUserID', $sId );
949 } elseif ( $sessId !== null && $sessId != 0 ) {
955 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
956 $sName = $request->getSessionData( 'wsUserName' );
957 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
958 $sName = $request->getCookie( 'UserName' );
959 $request->setSessionData( 'wsUserName', $sName );
964 $proposedUser = User
::newFromId( $sId );
965 if ( !$proposedUser->isLoggedIn() ) {
970 global $wgBlockDisablesLogin;
971 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
972 // User blocked and we've disabled blocked user logins
976 if ( $request->getSessionData( 'wsToken' ) ) {
977 $passwordCorrect = ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
979 } elseif ( $request->getCookie( 'Token' ) ) {
980 # Get the token from DB/cache and clean it up to remove garbage padding.
981 # This deals with historical problems with bugs and the default column value.
982 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
983 $passwordCorrect = ( strlen( $token ) && $token === $request->getCookie( 'Token' ) );
986 // No session or persistent login cookie
990 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
991 $this->loadFromUserObject( $proposedUser );
992 $request->setSessionData( 'wsToken', $this->mToken
);
993 wfDebug( "User: logged in from $from\n" );
996 // Invalid credentials
997 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1003 * Load user and user_group data from the database.
1004 * $this->mId must be set, this is how the user is identified.
1006 * @return bool True if the user exists, false if the user is anonymous
1008 public function loadFromDatabase() {
1010 $this->mId
= intval( $this->mId
);
1013 if ( !$this->mId
) {
1014 $this->loadDefaults();
1018 $dbr = wfGetDB( DB_MASTER
);
1019 $s = $dbr->selectRow( 'user', self
::selectFields(), array( 'user_id' => $this->mId
), __METHOD__
);
1021 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1023 if ( $s !== false ) {
1024 // Initialise user table data
1025 $this->loadFromRow( $s );
1026 $this->mGroups
= null; // deferred
1027 $this->getEditCount(); // revalidation for nulls
1032 $this->loadDefaults();
1038 * Initialize this object from a row from the user table.
1040 * @param array $row Row from the user table to load.
1041 * @param array $data Further user data to load into the object
1043 * user_groups Array with groups out of the user_groups table
1044 * user_properties Array with properties out of the user_properties table
1046 public function loadFromRow( $row, $data = null ) {
1049 $this->mGroups
= null; // deferred
1051 if ( isset( $row->user_name
) ) {
1052 $this->mName
= $row->user_name
;
1053 $this->mFrom
= 'name';
1054 $this->setItemLoaded( 'name' );
1059 if ( isset( $row->user_real_name
) ) {
1060 $this->mRealName
= $row->user_real_name
;
1061 $this->setItemLoaded( 'realname' );
1066 if ( isset( $row->user_id
) ) {
1067 $this->mId
= intval( $row->user_id
);
1068 $this->mFrom
= 'id';
1069 $this->setItemLoaded( 'id' );
1074 if ( isset( $row->user_editcount
) ) {
1075 $this->mEditCount
= $row->user_editcount
;
1080 if ( isset( $row->user_password
) ) {
1081 $this->mPassword
= $row->user_password
;
1082 $this->mNewpassword
= $row->user_newpassword
;
1083 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1084 $this->mEmail
= $row->user_email
;
1085 if ( isset( $row->user_options
) ) {
1086 $this->decodeOptions( $row->user_options
);
1088 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1089 $this->mToken
= $row->user_token
;
1090 if ( $this->mToken
== '' ) {
1091 $this->mToken
= null;
1093 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1094 $this->mEmailToken
= $row->user_email_token
;
1095 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1096 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1102 $this->mLoadedItems
= true;
1105 if ( is_array( $data ) ) {
1106 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1107 $this->mGroups
= $data['user_groups'];
1109 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1110 $this->loadOptions( $data['user_properties'] );
1116 * Load the data for this user object from another user object.
1120 protected function loadFromUserObject( $user ) {
1122 $user->loadGroups();
1123 $user->loadOptions();
1124 foreach ( self
::$mCacheVars as $var ) {
1125 $this->$var = $user->$var;
1130 * Load the groups from the database if they aren't already loaded.
1132 private function loadGroups() {
1133 if ( is_null( $this->mGroups
) ) {
1134 $dbr = wfGetDB( DB_MASTER
);
1135 $res = $dbr->select( 'user_groups',
1136 array( 'ug_group' ),
1137 array( 'ug_user' => $this->mId
),
1139 $this->mGroups
= array();
1140 foreach ( $res as $row ) {
1141 $this->mGroups
[] = $row->ug_group
;
1147 * Add the user to the group if he/she meets given criteria.
1149 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1150 * possible to remove manually via Special:UserRights. In such case it
1151 * will not be re-added automatically. The user will also not lose the
1152 * group if they no longer meet the criteria.
1154 * @param string $event key in $wgAutopromoteOnce (each one has groups/criteria)
1156 * @return array Array of groups the user has been promoted to.
1158 * @see $wgAutopromoteOnce
1160 public function addAutopromoteOnceGroups( $event ) {
1161 global $wgAutopromoteOnceLogInRC;
1163 $toPromote = array();
1164 if ( $this->getId() ) {
1165 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1166 if ( count( $toPromote ) ) {
1167 $oldGroups = $this->getGroups(); // previous groups
1168 foreach ( $toPromote as $group ) {
1169 $this->addGroup( $group );
1171 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1173 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1174 $logEntry->setPerformer( $this );
1175 $logEntry->setTarget( $this->getUserPage() );
1176 $logEntry->setParameters( array(
1177 '4::oldgroups' => $oldGroups,
1178 '5::newgroups' => $newGroups,
1180 $logid = $logEntry->insert();
1181 if ( $wgAutopromoteOnceLogInRC ) {
1182 $logEntry->publish( $logid );
1190 * Clear various cached data stored in this object. The cache of the user table
1191 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1193 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1194 * given source. May be "name", "id", "defaults", "session", or false for
1197 public function clearInstanceCache( $reloadFrom = false ) {
1198 $this->mNewtalk
= -1;
1199 $this->mDatePreference
= null;
1200 $this->mBlockedby
= -1; # Unset
1201 $this->mHash
= false;
1202 $this->mRights
= null;
1203 $this->mEffectiveGroups
= null;
1204 $this->mImplicitGroups
= null;
1205 $this->mGroups
= null;
1206 $this->mOptions
= null;
1207 $this->mOptionsLoaded
= false;
1208 $this->mEditCount
= null;
1210 if ( $reloadFrom ) {
1211 $this->mLoadedItems
= array();
1212 $this->mFrom
= $reloadFrom;
1217 * Combine the language default options with any site-specific options
1218 * and add the default language variants.
1220 * @return Array of String options
1222 public static function getDefaultOptions() {
1223 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1225 static $defOpt = null;
1226 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1227 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1228 // mid-request and see that change reflected in the return value of this function.
1229 // Which is insane and would never happen during normal MW operation
1233 $defOpt = $wgDefaultUserOptions;
1234 // Default language setting
1235 $defOpt['language'] = $defOpt['variant'] = $wgContLang->getCode();
1236 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1237 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1239 $defOpt['skin'] = $wgDefaultSkin;
1241 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1247 * Get a given default option value.
1249 * @param string $opt Name of option to retrieve
1250 * @return string Default option value
1252 public static function getDefaultOption( $opt ) {
1253 $defOpts = self
::getDefaultOptions();
1254 if ( isset( $defOpts[$opt] ) ) {
1255 return $defOpts[$opt];
1262 * Get blocking information
1263 * @param bool $bFromSlave Whether to check the slave database first. To
1264 * improve performance, non-critical checks are done
1265 * against slaves. Check when actually saving should be
1266 * done against master.
1268 private function getBlockedStatus( $bFromSlave = true ) {
1269 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1271 if ( -1 != $this->mBlockedby
) {
1275 wfProfileIn( __METHOD__
);
1276 wfDebug( __METHOD__
. ": checking...\n" );
1278 // Initialize data...
1279 // Otherwise something ends up stomping on $this->mBlockedby when
1280 // things get lazy-loaded later, causing false positive block hits
1281 // due to -1 !== 0. Probably session-related... Nothing should be
1282 // overwriting mBlockedby, surely?
1285 # We only need to worry about passing the IP address to the Block generator if the
1286 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1287 # know which IP address they're actually coming from
1288 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1289 $ip = $this->getRequest()->getIP();
1295 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1298 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1299 && !in_array( $ip, $wgProxyWhitelist ) )
1302 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1304 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1305 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1306 $block->setTarget( $ip );
1307 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1309 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1310 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1311 $block->setTarget( $ip );
1315 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1316 if ( !$block instanceof Block
1317 && $wgApplyIpBlocksToXff
1319 && !$this->isAllowed( 'proxyunbannable' )
1320 && !in_array( $ip, $wgProxyWhitelist )
1322 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1323 $xff = array_map( 'trim', explode( ',', $xff ) );
1324 $xff = array_diff( $xff, array( $ip ) );
1325 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1326 $block = Block
::chooseBlock( $xffblocks, $xff );
1327 if ( $block instanceof Block
) {
1328 # Mangle the reason to alert the user that the block
1329 # originated from matching the X-Forwarded-For header.
1330 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1334 if ( $block instanceof Block
) {
1335 wfDebug( __METHOD__
. ": Found block.\n" );
1336 $this->mBlock
= $block;
1337 $this->mBlockedby
= $block->getByName();
1338 $this->mBlockreason
= $block->mReason
;
1339 $this->mHideName
= $block->mHideName
;
1340 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1342 $this->mBlockedby
= '';
1343 $this->mHideName
= 0;
1344 $this->mAllowUsertalk
= false;
1348 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1350 wfProfileOut( __METHOD__
);
1354 * Whether the given IP is in a DNS blacklist.
1356 * @param string $ip IP to check
1357 * @param bool $checkWhitelist whether to check the whitelist first
1358 * @return bool True if blacklisted.
1360 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1361 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1362 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1364 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs ) {
1368 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1372 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1373 return $this->inDnsBlacklist( $ip, $urls );
1377 * Whether the given IP is in a given DNS blacklist.
1379 * @param string $ip IP to check
1380 * @param string|array $bases of Strings: URL of the DNS blacklist
1381 * @return bool True if blacklisted.
1383 public function inDnsBlacklist( $ip, $bases ) {
1384 wfProfileIn( __METHOD__
);
1387 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1388 if ( IP
::isIPv4( $ip ) ) {
1389 // Reverse IP, bug 21255
1390 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1392 foreach ( (array)$bases as $base ) {
1394 // If we have an access key, use that too (ProjectHoneypot, etc.)
1395 if ( is_array( $base ) ) {
1396 if ( count( $base ) >= 2 ) {
1397 // Access key is 1, base URL is 0
1398 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1400 $host = "$ipReversed.{$base[0]}";
1403 $host = "$ipReversed.$base";
1407 $ipList = gethostbynamel( $host );
1410 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1414 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base.\n" );
1419 wfProfileOut( __METHOD__
);
1424 * Check if an IP address is in the local proxy list
1430 public static function isLocallyBlockedProxy( $ip ) {
1431 global $wgProxyList;
1433 if ( !$wgProxyList ) {
1436 wfProfileIn( __METHOD__
);
1438 if ( !is_array( $wgProxyList ) ) {
1439 // Load from the specified file
1440 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1443 if ( !is_array( $wgProxyList ) ) {
1445 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1447 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1448 // Old-style flipped proxy list
1453 wfProfileOut( __METHOD__
);
1458 * Is this user subject to rate limiting?
1460 * @return bool True if rate limited
1462 public function isPingLimitable() {
1463 global $wgRateLimitsExcludedIPs;
1464 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1465 // No other good way currently to disable rate limits
1466 // for specific IPs. :P
1467 // But this is a crappy hack and should die.
1470 return !$this->isAllowed( 'noratelimit' );
1474 * Primitive rate limits: enforce maximum actions per time period
1475 * to put a brake on flooding.
1477 * @note When using a shared cache like memcached, IP-address
1478 * last-hit counters will be shared across wikis.
1480 * @param string $action Action to enforce; 'edit' if unspecified
1481 * @return bool True if a rate limiter was tripped
1483 public function pingLimiter( $action = 'edit' ) {
1484 // Call the 'PingLimiter' hook
1486 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result ) ) ) {
1490 global $wgRateLimits;
1491 if ( !isset( $wgRateLimits[$action] ) ) {
1495 // Some groups shouldn't trigger the ping limiter, ever
1496 if ( !$this->isPingLimitable() ) {
1500 global $wgMemc, $wgRateLimitLog;
1501 wfProfileIn( __METHOD__
);
1503 $limits = $wgRateLimits[$action];
1505 $id = $this->getId();
1508 if ( isset( $limits['anon'] ) && $id == 0 ) {
1509 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1512 if ( isset( $limits['user'] ) && $id != 0 ) {
1513 $userLimit = $limits['user'];
1515 if ( $this->isNewbie() ) {
1516 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1517 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1519 if ( isset( $limits['ip'] ) ) {
1520 $ip = $this->getRequest()->getIP();
1521 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1523 if ( isset( $limits['subnet'] ) ) {
1524 $ip = $this->getRequest()->getIP();
1527 if ( IP
::isIPv6( $ip ) ) {
1528 $parts = IP
::parseRange( "$ip/64" );
1529 $subnet = $parts[0];
1530 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1532 $subnet = $matches[1];
1534 if ( $subnet !== false ) {
1535 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1539 // Check for group-specific permissions
1540 // If more than one group applies, use the group with the highest limit
1541 foreach ( $this->getGroups() as $group ) {
1542 if ( isset( $limits[$group] ) ) {
1543 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1544 $userLimit = $limits[$group];
1548 // Set the user limit key
1549 if ( $userLimit !== false ) {
1550 list( $max, $period ) = $userLimit;
1551 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1552 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1556 foreach ( $keys as $key => $limit ) {
1557 list( $max, $period ) = $limit;
1558 $summary = "(limit $max in {$period}s)";
1559 $count = $wgMemc->get( $key );
1562 if ( $count >= $max ) {
1563 wfDebug( __METHOD__
. ": tripped! $key at $count $summary\n" );
1564 if ( $wgRateLimitLog ) {
1565 wfSuppressWarnings();
1566 file_put_contents( $wgRateLimitLog, wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", FILE_APPEND
);
1567 wfRestoreWarnings();
1571 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1574 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1575 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1577 $wgMemc->incr( $key );
1580 wfProfileOut( __METHOD__
);
1585 * Check if user is blocked
1587 * @param bool $bFromSlave Whether to check the slave database instead of the master
1588 * @return bool True if blocked, false otherwise
1590 public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1591 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1595 * Get the block affecting the user, or null if the user is not blocked
1597 * @param bool $bFromSlave Whether to check the slave database instead of the master
1598 * @return Block|null
1600 public function getBlock( $bFromSlave = true ) {
1601 $this->getBlockedStatus( $bFromSlave );
1602 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1606 * Check if user is blocked from editing a particular article
1608 * @param Title $title Title to check
1609 * @param bool $bFromSlave whether to check the slave database instead of the master
1612 function isBlockedFrom( $title, $bFromSlave = false ) {
1613 global $wgBlockAllowsUTEdit;
1614 wfProfileIn( __METHOD__
);
1616 $blocked = $this->isBlocked( $bFromSlave );
1617 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1618 // If a user's name is suppressed, they cannot make edits anywhere
1619 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1620 $title->getNamespace() == NS_USER_TALK
) {
1622 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1625 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1627 wfProfileOut( __METHOD__
);
1632 * If user is blocked, return the name of the user who placed the block
1633 * @return string Name of blocker
1635 public function blockedBy() {
1636 $this->getBlockedStatus();
1637 return $this->mBlockedby
;
1641 * If user is blocked, return the specified reason for the block
1642 * @return string Blocking reason
1644 public function blockedFor() {
1645 $this->getBlockedStatus();
1646 return $this->mBlockreason
;
1650 * If user is blocked, return the ID for the block
1651 * @return int Block ID
1653 public function getBlockId() {
1654 $this->getBlockedStatus();
1655 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1659 * Check if user is blocked on all wikis.
1660 * Do not use for actual edit permission checks!
1661 * This is intended for quick UI checks.
1663 * @param string $ip IP address, uses current client if none given
1664 * @return bool True if blocked, false otherwise
1666 public function isBlockedGlobally( $ip = '' ) {
1667 if ( $this->mBlockedGlobally
!== null ) {
1668 return $this->mBlockedGlobally
;
1670 // User is already an IP?
1671 if ( IP
::isIPAddress( $this->getName() ) ) {
1672 $ip = $this->getName();
1674 $ip = $this->getRequest()->getIP();
1677 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1678 $this->mBlockedGlobally
= (bool)$blocked;
1679 return $this->mBlockedGlobally
;
1683 * Check if user account is locked
1685 * @return bool True if locked, false otherwise
1687 public function isLocked() {
1688 if ( $this->mLocked
!== null ) {
1689 return $this->mLocked
;
1692 $authUser = $wgAuth->getUserInstance( $this );
1693 $this->mLocked
= (bool)$authUser->isLocked();
1694 return $this->mLocked
;
1698 * Check if user account is hidden
1700 * @return bool True if hidden, false otherwise
1702 public function isHidden() {
1703 if ( $this->mHideName
!== null ) {
1704 return $this->mHideName
;
1706 $this->getBlockedStatus();
1707 if ( !$this->mHideName
) {
1709 $authUser = $wgAuth->getUserInstance( $this );
1710 $this->mHideName
= (bool)$authUser->isHidden();
1712 return $this->mHideName
;
1716 * Get the user's ID.
1717 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1719 public function getId() {
1720 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1721 // Special case, we know the user is anonymous
1723 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1724 // Don't load if this was initialized from an ID
1731 * Set the user and reload all fields according to a given ID
1732 * @param int $v User ID to reload
1734 public function setId( $v ) {
1736 $this->clearInstanceCache( 'id' );
1740 * Get the user name, or the IP of an anonymous user
1741 * @return string User's name or IP address
1743 public function getName() {
1744 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1745 // Special case optimisation
1746 return $this->mName
;
1749 if ( $this->mName
=== false ) {
1751 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1753 return $this->mName
;
1758 * Set the user name.
1760 * This does not reload fields from the database according to the given
1761 * name. Rather, it is used to create a temporary "nonexistent user" for
1762 * later addition to the database. It can also be used to set the IP
1763 * address for an anonymous user to something other than the current
1766 * @note User::newFromName() has roughly the same function, when the named user
1768 * @param string $str New user name to set
1770 public function setName( $str ) {
1772 $this->mName
= $str;
1776 * Get the user's name escaped by underscores.
1777 * @return string Username escaped by underscores.
1779 public function getTitleKey() {
1780 return str_replace( ' ', '_', $this->getName() );
1784 * Check if the user has new messages.
1785 * @return bool True if the user has new messages
1787 public function getNewtalk() {
1790 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1791 if ( $this->mNewtalk
=== -1 ) {
1792 $this->mNewtalk
= false; # reset talk page status
1794 // Check memcached separately for anons, who have no
1795 // entire User object stored in there.
1796 if ( !$this->mId
) {
1797 global $wgDisableAnonTalk;
1798 if ( $wgDisableAnonTalk ) {
1799 // Anon newtalk disabled by configuration.
1800 $this->mNewtalk
= false;
1803 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1804 $newtalk = $wgMemc->get( $key );
1805 if ( strval( $newtalk ) !== '' ) {
1806 $this->mNewtalk
= (bool)$newtalk;
1808 // Since we are caching this, make sure it is up to date by getting it
1810 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1811 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1815 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1819 return (bool)$this->mNewtalk
;
1823 * Return the revision and link for the oldest new talk page message for
1825 * @note This function was designed to accomodate multiple talk pages, but
1826 * currently only returns a single link and revision.
1829 public function getNewMessageLinks() {
1831 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
1833 } elseif ( !$this->getNewtalk() ) {
1836 $utp = $this->getTalkPage();
1837 $dbr = wfGetDB( DB_SLAVE
);
1838 // Get the "last viewed rev" timestamp from the oldest message notification
1839 $timestamp = $dbr->selectField( 'user_newtalk',
1840 'MIN(user_last_timestamp)',
1841 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
1843 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
1844 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
1848 * Get the revision ID for the oldest new talk page message for this user
1849 * @return int|null Revision id or null if there are no new messages
1851 public function getNewMessageRevisionId() {
1852 $newMessageRevisionId = null;
1853 $newMessageLinks = $this->getNewMessageLinks();
1854 if ( $newMessageLinks ) {
1855 // Note: getNewMessageLinks() never returns more than a single link
1856 // and it is always for the same wiki, but we double-check here in
1857 // case that changes some time in the future.
1858 if ( count( $newMessageLinks ) === 1
1859 && $newMessageLinks[0]['wiki'] === wfWikiID()
1860 && $newMessageLinks[0]['rev']
1862 $newMessageRevision = $newMessageLinks[0]['rev'];
1863 $newMessageRevisionId = $newMessageRevision->getId();
1866 return $newMessageRevisionId;
1870 * Internal uncached check for new messages
1873 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1874 * @param string|int $id User's IP address for anonymous users, User ID otherwise
1875 * @param bool $fromMaster true to fetch from the master, false for a slave
1876 * @return bool True if the user has new messages
1878 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
1879 if ( $fromMaster ) {
1880 $db = wfGetDB( DB_MASTER
);
1882 $db = wfGetDB( DB_SLAVE
);
1884 $ok = $db->selectField( 'user_newtalk', $field,
1885 array( $field => $id ), __METHOD__
);
1886 return $ok !== false;
1890 * Add or update the new messages flag
1891 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1892 * @param string|int $id User's IP address for anonymous users, User ID otherwise
1893 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null.
1894 * @return bool True if successful, false otherwise
1896 protected function updateNewtalk( $field, $id, $curRev = null ) {
1897 // Get timestamp of the talk page revision prior to the current one
1898 $prevRev = $curRev ?
$curRev->getPrevious() : false;
1899 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
1900 // Mark the user as having new messages since this revision
1901 $dbw = wfGetDB( DB_MASTER
);
1902 $dbw->insert( 'user_newtalk',
1903 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
1906 if ( $dbw->affectedRows() ) {
1907 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
1910 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
1916 * Clear the new messages flag for the given user
1917 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1918 * @param string|int $id User's IP address for anonymous users, User ID otherwise
1919 * @return bool True if successful, false otherwise
1921 protected function deleteNewtalk( $field, $id ) {
1922 $dbw = wfGetDB( DB_MASTER
);
1923 $dbw->delete( 'user_newtalk',
1924 array( $field => $id ),
1926 if ( $dbw->affectedRows() ) {
1927 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
1930 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
1936 * Update the 'You have new messages!' status.
1937 * @param bool $val Whether the user has new messages
1938 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null or !$val.
1940 public function setNewtalk( $val, $curRev = null ) {
1941 if ( wfReadOnly() ) {
1946 $this->mNewtalk
= $val;
1948 if ( $this->isAnon() ) {
1950 $id = $this->getName();
1953 $id = $this->getId();
1958 $changed = $this->updateNewtalk( $field, $id, $curRev );
1960 $changed = $this->deleteNewtalk( $field, $id );
1963 if ( $this->isAnon() ) {
1964 // Anons have a separate memcached space, since
1965 // user records aren't kept for them.
1966 $key = wfMemcKey( 'newtalk', 'ip', $id );
1967 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1970 $this->invalidateCache();
1975 * Generate a current or new-future timestamp to be stored in the
1976 * user_touched field when we update things.
1977 * @return string Timestamp in TS_MW format
1979 private static function newTouchedTimestamp() {
1980 global $wgClockSkewFudge;
1981 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1985 * Clear user data from memcached.
1986 * Use after applying fun updates to the database; caller's
1987 * responsibility to update user_touched if appropriate.
1989 * Called implicitly from invalidateCache() and saveSettings().
1991 private function clearSharedCache() {
1995 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
2000 * Immediately touch the user data cache for this account.
2001 * Updates user_touched field, and removes account data from memcached
2002 * for reload on the next hit.
2004 public function invalidateCache() {
2005 if ( wfReadOnly() ) {
2010 $this->mTouched
= self
::newTouchedTimestamp();
2012 $dbw = wfGetDB( DB_MASTER
);
2013 $userid = $this->mId
;
2014 $touched = $this->mTouched
;
2015 $method = __METHOD__
;
2016 $dbw->onTransactionIdle( function() use ( $dbw, $userid, $touched, $method ) {
2017 // Prevent contention slams by checking user_touched first
2018 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2019 $needsPurge = $dbw->selectField( 'user', '1',
2020 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2021 if ( $needsPurge ) {
2022 $dbw->update( 'user',
2023 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2024 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2029 $this->clearSharedCache();
2034 * Validate the cache for this account.
2035 * @param string $timestamp A timestamp in TS_MW format
2038 public function validateCache( $timestamp ) {
2040 return ( $timestamp >= $this->mTouched
);
2044 * Get the user touched timestamp
2045 * @return string timestamp
2047 public function getTouched() {
2049 return $this->mTouched
;
2053 * Set the password and reset the random token.
2054 * Calls through to authentication plugin if necessary;
2055 * will have no effect if the auth plugin refuses to
2056 * pass the change through or if the legal password
2059 * As a special case, setting the password to null
2060 * wipes it, so the account cannot be logged in until
2061 * a new password is set, for instance via e-mail.
2063 * @param string $str New password to set
2064 * @throws PasswordError on failure
2068 public function setPassword( $str ) {
2071 if ( $str !== null ) {
2072 if ( !$wgAuth->allowPasswordChange() ) {
2073 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2076 if ( !$this->isValidPassword( $str ) ) {
2077 global $wgMinimalPasswordLength;
2078 $valid = $this->getPasswordValidity( $str );
2079 if ( is_array( $valid ) ) {
2080 $message = array_shift( $valid );
2084 $params = array( $wgMinimalPasswordLength );
2086 throw new PasswordError( wfMessage( $message, $params )->text() );
2090 if ( !$wgAuth->setPassword( $this, $str ) ) {
2091 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2094 $this->setInternalPassword( $str );
2100 * Set the password and reset the random token unconditionally.
2102 * @param string|null $str New password to set or null to set an invalid
2103 * password hash meaning that the user will not be able to log in
2104 * through the web interface.
2106 public function setInternalPassword( $str ) {
2110 if ( $str === null ) {
2111 // Save an invalid hash...
2112 $this->mPassword
= '';
2114 $this->mPassword
= self
::crypt( $str );
2116 $this->mNewpassword
= '';
2117 $this->mNewpassTime
= null;
2121 * Get the user's current token.
2122 * @param bool $forceCreation Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility)
2123 * @return string Token
2125 public function getToken( $forceCreation = true ) {
2127 if ( !$this->mToken
&& $forceCreation ) {
2130 return $this->mToken
;
2134 * Set the random token (used for persistent authentication)
2135 * Called from loadDefaults() among other places.
2137 * @param string|bool $token If specified, set the token to this value
2139 public function setToken( $token = false ) {
2142 $this->mToken
= MWCryptRand
::generateHex( USER_TOKEN_LENGTH
);
2144 $this->mToken
= $token;
2149 * Set the password for a password reminder or new account email
2151 * @param string $str New password to set
2152 * @param bool $throttle If true, reset the throttle timestamp to the present
2154 public function setNewpassword( $str, $throttle = true ) {
2156 $this->mNewpassword
= self
::crypt( $str );
2158 $this->mNewpassTime
= wfTimestampNow();
2163 * Has password reminder email been sent within the last
2164 * $wgPasswordReminderResendTime hours?
2167 public function isPasswordReminderThrottled() {
2168 global $wgPasswordReminderResendTime;
2170 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2173 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2174 return time() < $expiry;
2178 * Get the user's e-mail address
2179 * @return string User's email address
2181 public function getEmail() {
2183 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
2184 return $this->mEmail
;
2188 * Get the timestamp of the user's e-mail authentication
2189 * @return string TS_MW timestamp
2191 public function getEmailAuthenticationTimestamp() {
2193 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2194 return $this->mEmailAuthenticated
;
2198 * Set the user's e-mail address
2199 * @param string $str New e-mail address
2201 public function setEmail( $str ) {
2203 if ( $str == $this->mEmail
) {
2206 $this->mEmail
= $str;
2207 $this->invalidateEmail();
2208 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
2212 * Set the user's e-mail address and a confirmation mail if needed.
2215 * @param string $str New e-mail address
2218 public function setEmailWithConfirmation( $str ) {
2219 global $wgEnableEmail, $wgEmailAuthentication;
2221 if ( !$wgEnableEmail ) {
2222 return Status
::newFatal( 'emaildisabled' );
2225 $oldaddr = $this->getEmail();
2226 if ( $str === $oldaddr ) {
2227 return Status
::newGood( true );
2230 $this->setEmail( $str );
2232 if ( $str !== '' && $wgEmailAuthentication ) {
2233 // Send a confirmation request to the new address if needed
2234 $type = $oldaddr != '' ?
'changed' : 'set';
2235 $result = $this->sendConfirmationMail( $type );
2236 if ( $result->isGood() ) {
2237 // Say the the caller that a confirmation mail has been sent
2238 $result->value
= 'eauth';
2241 $result = Status
::newGood( true );
2248 * Get the user's real name
2249 * @return string User's real name
2251 public function getRealName() {
2252 if ( !$this->isItemLoaded( 'realname' ) ) {
2256 return $this->mRealName
;
2260 * Set the user's real name
2261 * @param string $str New real name
2263 public function setRealName( $str ) {
2265 $this->mRealName
= $str;
2269 * Get the user's current setting for a given option.
2271 * @param string $oname The option to check
2272 * @param string $defaultOverride A default value returned if the option does not exist
2273 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2274 * @return string User's current value for the option
2275 * @see getBoolOption()
2276 * @see getIntOption()
2278 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2279 global $wgHiddenPrefs;
2280 $this->loadOptions();
2282 # We want 'disabled' preferences to always behave as the default value for
2283 # users, even if they have set the option explicitly in their settings (ie they
2284 # set it, and then it was disabled removing their ability to change it). But
2285 # we don't want to erase the preferences in the database in case the preference
2286 # is re-enabled again. So don't touch $mOptions, just override the returned value
2287 if ( in_array( $oname, $wgHiddenPrefs ) && !$ignoreHidden ) {
2288 return self
::getDefaultOption( $oname );
2291 if ( array_key_exists( $oname, $this->mOptions
) ) {
2292 return $this->mOptions
[$oname];
2294 return $defaultOverride;
2299 * Get all user's options
2303 public function getOptions() {
2304 global $wgHiddenPrefs;
2305 $this->loadOptions();
2306 $options = $this->mOptions
;
2308 # We want 'disabled' preferences to always behave as the default value for
2309 # users, even if they have set the option explicitly in their settings (ie they
2310 # set it, and then it was disabled removing their ability to change it). But
2311 # we don't want to erase the preferences in the database in case the preference
2312 # is re-enabled again. So don't touch $mOptions, just override the returned value
2313 foreach ( $wgHiddenPrefs as $pref ) {
2314 $default = self
::getDefaultOption( $pref );
2315 if ( $default !== null ) {
2316 $options[$pref] = $default;
2324 * Get the user's current setting for a given option, as a boolean value.
2326 * @param string $oname The option to check
2327 * @return bool User's current value for the option
2330 public function getBoolOption( $oname ) {
2331 return (bool)$this->getOption( $oname );
2335 * Get the user's current setting for a given option, as a boolean value.
2337 * @param string $oname The option to check
2338 * @param int $defaultOverride A default value returned if the option does not exist
2339 * @return int User's current value for the option
2342 public function getIntOption( $oname, $defaultOverride = 0 ) {
2343 $val = $this->getOption( $oname );
2345 $val = $defaultOverride;
2347 return intval( $val );
2351 * Set the given option for a user.
2353 * @param string $oname The option to set
2354 * @param mixed $val New value to set
2356 public function setOption( $oname, $val ) {
2357 $this->loadOptions();
2359 // Explicitly NULL values should refer to defaults
2360 if ( is_null( $val ) ) {
2361 $val = self
::getDefaultOption( $oname );
2364 $this->mOptions
[$oname] = $val;
2368 * Return a list of the types of user options currently returned by
2369 * User::getOptionKinds().
2371 * Currently, the option kinds are:
2372 * - 'registered' - preferences which are registered in core MediaWiki or
2373 * by extensions using the UserGetDefaultOptions hook.
2374 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2375 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2376 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2377 * be used by user scripts.
2378 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2379 * These are usually legacy options, removed in newer versions.
2381 * The API (and possibly others) use this function to determine the possible
2382 * option types for validation purposes, so make sure to update this when a
2383 * new option kind is added.
2385 * @see User::getOptionKinds
2386 * @return array Option kinds
2388 public static function listOptionKinds() {
2391 'registered-multiselect',
2392 'registered-checkmatrix',
2399 * Return an associative array mapping preferences keys to the kind of a preference they're
2400 * used for. Different kinds are handled differently when setting or reading preferences.
2402 * See User::listOptionKinds for the list of valid option types that can be provided.
2404 * @see User::listOptionKinds
2405 * @param $context IContextSource
2406 * @param array $options assoc. array with options keys to check as keys. Defaults to $this->mOptions.
2407 * @return array the key => kind mapping data
2409 public function getOptionKinds( IContextSource
$context, $options = null ) {
2410 $this->loadOptions();
2411 if ( $options === null ) {
2412 $options = $this->mOptions
;
2415 $prefs = Preferences
::getPreferences( $this, $context );
2418 // Multiselect and checkmatrix options are stored in the database with
2419 // one key per option, each having a boolean value. Extract those keys.
2420 $multiselectOptions = array();
2421 foreach ( $prefs as $name => $info ) {
2422 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2423 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2424 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2425 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2427 foreach ( $opts as $value ) {
2428 $multiselectOptions["$prefix$value"] = true;
2431 unset( $prefs[$name] );
2434 $checkmatrixOptions = array();
2435 foreach ( $prefs as $name => $info ) {
2436 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2437 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2438 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2439 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2440 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2442 foreach ( $columns as $column ) {
2443 foreach ( $rows as $row ) {
2444 $checkmatrixOptions["$prefix-$column-$row"] = true;
2448 unset( $prefs[$name] );
2452 // $value is ignored
2453 foreach ( $options as $key => $value ) {
2454 if ( isset( $prefs[$key] ) ) {
2455 $mapping[$key] = 'registered';
2456 } elseif ( isset( $multiselectOptions[$key] ) ) {
2457 $mapping[$key] = 'registered-multiselect';
2458 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2459 $mapping[$key] = 'registered-checkmatrix';
2460 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2461 $mapping[$key] = 'userjs';
2463 $mapping[$key] = 'unused';
2471 * Reset certain (or all) options to the site defaults
2473 * The optional parameter determines which kinds of preferences will be reset.
2474 * Supported values are everything that can be reported by getOptionKinds()
2475 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2477 * @param array|string $resetKinds which kinds of preferences to reset. Defaults to
2478 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2479 * for backwards-compatibility.
2480 * @param $context IContextSource|null context source used when $resetKinds
2481 * does not contain 'all', passed to getOptionKinds().
2482 * Defaults to RequestContext::getMain() when null.
2484 public function resetOptions(
2485 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2486 IContextSource
$context = null
2489 $defaultOptions = self
::getDefaultOptions();
2491 if ( !is_array( $resetKinds ) ) {
2492 $resetKinds = array( $resetKinds );
2495 if ( in_array( 'all', $resetKinds ) ) {
2496 $newOptions = $defaultOptions;
2498 if ( $context === null ) {
2499 $context = RequestContext
::getMain();
2502 $optionKinds = $this->getOptionKinds( $context );
2503 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2504 $newOptions = array();
2506 // Use default values for the options that should be deleted, and
2507 // copy old values for the ones that shouldn't.
2508 foreach ( $this->mOptions
as $key => $value ) {
2509 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2510 if ( array_key_exists( $key, $defaultOptions ) ) {
2511 $newOptions[$key] = $defaultOptions[$key];
2514 $newOptions[$key] = $value;
2519 $this->mOptions
= $newOptions;
2520 $this->mOptionsLoaded
= true;
2524 * Get the user's preferred date format.
2525 * @return string User's preferred date format
2527 public function getDatePreference() {
2528 // Important migration for old data rows
2529 if ( is_null( $this->mDatePreference
) ) {
2531 $value = $this->getOption( 'date' );
2532 $map = $wgLang->getDatePreferenceMigrationMap();
2533 if ( isset( $map[$value] ) ) {
2534 $value = $map[$value];
2536 $this->mDatePreference
= $value;
2538 return $this->mDatePreference
;
2542 * Get the user preferred stub threshold
2546 public function getStubThreshold() {
2547 global $wgMaxArticleSize; # Maximum article size, in Kb
2548 $threshold = $this->getIntOption( 'stubthreshold' );
2549 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2550 // If they have set an impossible value, disable the preference
2551 // so we can use the parser cache again.
2558 * Get the permissions this user has.
2559 * @return Array of String permission names
2561 public function getRights() {
2562 if ( is_null( $this->mRights
) ) {
2563 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2564 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2565 // Force reindexation of rights when a hook has unset one of them
2566 $this->mRights
= array_values( array_unique( $this->mRights
) );
2568 return $this->mRights
;
2572 * Get the list of explicit group memberships this user has.
2573 * The implicit * and user groups are not included.
2574 * @return Array of String internal group names
2576 public function getGroups() {
2578 $this->loadGroups();
2579 return $this->mGroups
;
2583 * Get the list of implicit group memberships this user has.
2584 * This includes all explicit groups, plus 'user' if logged in,
2585 * '*' for all accounts, and autopromoted groups
2586 * @param bool $recache Whether to avoid the cache
2587 * @return Array of String internal group names
2589 public function getEffectiveGroups( $recache = false ) {
2590 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2591 wfProfileIn( __METHOD__
);
2592 $this->mEffectiveGroups
= array_unique( array_merge(
2593 $this->getGroups(), // explicit groups
2594 $this->getAutomaticGroups( $recache ) // implicit groups
2596 // Hook for additional groups
2597 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2598 // Force reindexation of groups when a hook has unset one of them
2599 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
2600 wfProfileOut( __METHOD__
);
2602 return $this->mEffectiveGroups
;
2606 * Get the list of implicit group memberships this user has.
2607 * This includes 'user' if logged in, '*' for all accounts,
2608 * and autopromoted groups
2609 * @param bool $recache Whether to avoid the cache
2610 * @return Array of String internal group names
2612 public function getAutomaticGroups( $recache = false ) {
2613 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
2614 wfProfileIn( __METHOD__
);
2615 $this->mImplicitGroups
= array( '*' );
2616 if ( $this->getId() ) {
2617 $this->mImplicitGroups
[] = 'user';
2619 $this->mImplicitGroups
= array_unique( array_merge(
2620 $this->mImplicitGroups
,
2621 Autopromote
::getAutopromoteGroups( $this )
2625 // Assure data consistency with rights/groups,
2626 // as getEffectiveGroups() depends on this function
2627 $this->mEffectiveGroups
= null;
2629 wfProfileOut( __METHOD__
);
2631 return $this->mImplicitGroups
;
2635 * Returns the groups the user has belonged to.
2637 * The user may still belong to the returned groups. Compare with getGroups().
2639 * The function will not return groups the user had belonged to before MW 1.17
2641 * @return array Names of the groups the user has belonged to.
2643 public function getFormerGroups() {
2644 if ( is_null( $this->mFormerGroups
) ) {
2645 $dbr = wfGetDB( DB_MASTER
);
2646 $res = $dbr->select( 'user_former_groups',
2647 array( 'ufg_group' ),
2648 array( 'ufg_user' => $this->mId
),
2650 $this->mFormerGroups
= array();
2651 foreach ( $res as $row ) {
2652 $this->mFormerGroups
[] = $row->ufg_group
;
2655 return $this->mFormerGroups
;
2659 * Get the user's edit count.
2662 public function getEditCount() {
2663 if ( !$this->getId() ) {
2667 if ( !isset( $this->mEditCount
) ) {
2668 /* Populate the count, if it has not been populated yet */
2669 wfProfileIn( __METHOD__
);
2670 $dbr = wfGetDB( DB_SLAVE
);
2671 // check if the user_editcount field has been initialized
2672 $count = $dbr->selectField(
2673 'user', 'user_editcount',
2674 array( 'user_id' => $this->mId
),
2678 if ( $count === null ) {
2679 // it has not been initialized. do so.
2680 $count = $this->initEditCount();
2682 $this->mEditCount
= intval( $count );
2683 wfProfileOut( __METHOD__
);
2685 return $this->mEditCount
;
2689 * Add the user to the given group.
2690 * This takes immediate effect.
2691 * @param string $group Name of the group to add
2693 public function addGroup( $group ) {
2694 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2695 $dbw = wfGetDB( DB_MASTER
);
2696 if ( $this->getId() ) {
2697 $dbw->insert( 'user_groups',
2699 'ug_user' => $this->getID(),
2700 'ug_group' => $group,
2703 array( 'IGNORE' ) );
2706 $this->loadGroups();
2707 $this->mGroups
[] = $group;
2708 // In case loadGroups was not called before, we now have the right twice.
2709 // Get rid of the duplicate.
2710 $this->mGroups
= array_unique( $this->mGroups
);
2711 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2713 $this->invalidateCache();
2717 * Remove the user from the given group.
2718 * This takes immediate effect.
2719 * @param string $group Name of the group to remove
2721 public function removeGroup( $group ) {
2723 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2724 $dbw = wfGetDB( DB_MASTER
);
2725 $dbw->delete( 'user_groups',
2727 'ug_user' => $this->getID(),
2728 'ug_group' => $group,
2730 // Remember that the user was in this group
2731 $dbw->insert( 'user_former_groups',
2733 'ufg_user' => $this->getID(),
2734 'ufg_group' => $group,
2737 array( 'IGNORE' ) );
2739 $this->loadGroups();
2740 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2741 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2743 $this->invalidateCache();
2747 * Get whether the user is logged in
2750 public function isLoggedIn() {
2751 return $this->getID() != 0;
2755 * Get whether the user is anonymous
2758 public function isAnon() {
2759 return !$this->isLoggedIn();
2763 * Check if user is allowed to access a feature / make an action
2765 * @internal param \String $varargs permissions to test
2766 * @return boolean: True if user is allowed to perform *any* of the given actions
2770 public function isAllowedAny( /*...*/ ) {
2771 $permissions = func_get_args();
2772 foreach ( $permissions as $permission ) {
2773 if ( $this->isAllowed( $permission ) ) {
2782 * @internal param $varargs string
2783 * @return bool True if the user is allowed to perform *all* of the given actions
2785 public function isAllowedAll( /*...*/ ) {
2786 $permissions = func_get_args();
2787 foreach ( $permissions as $permission ) {
2788 if ( !$this->isAllowed( $permission ) ) {
2796 * Internal mechanics of testing a permission
2797 * @param string $action
2800 public function isAllowed( $action = '' ) {
2801 if ( $action === '' ) {
2802 return true; // In the spirit of DWIM
2804 // Patrolling may not be enabled
2805 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
2806 global $wgUseRCPatrol, $wgUseNPPatrol;
2807 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
2811 // Use strict parameter to avoid matching numeric 0 accidentally inserted
2812 // by misconfiguration: 0 == 'foo'
2813 return in_array( $action, $this->getRights(), true );
2817 * Check whether to enable recent changes patrol features for this user
2818 * @return boolean: True or false
2820 public function useRCPatrol() {
2821 global $wgUseRCPatrol;
2822 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
2826 * Check whether to enable new pages patrol features for this user
2827 * @return bool True or false
2829 public function useNPPatrol() {
2830 global $wgUseRCPatrol, $wgUseNPPatrol;
2832 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
2833 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
2838 * Get the WebRequest object to use with this object
2840 * @return WebRequest
2842 public function getRequest() {
2843 if ( $this->mRequest
) {
2844 return $this->mRequest
;
2852 * Get the current skin, loading it if required
2853 * @return Skin The current skin
2854 * @todo FIXME: Need to check the old failback system [AV]
2855 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
2857 public function getSkin() {
2858 wfDeprecated( __METHOD__
, '1.18' );
2859 return RequestContext
::getMain()->getSkin();
2863 * Get a WatchedItem for this user and $title.
2865 * @since 1.22 $checkRights parameter added
2866 * @param $title Title
2867 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
2868 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
2869 * @return WatchedItem
2871 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
2872 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
2874 if ( isset( $this->mWatchedItems
[$key] ) ) {
2875 return $this->mWatchedItems
[$key];
2878 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
2879 $this->mWatchedItems
= array();
2882 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
2883 return $this->mWatchedItems
[$key];
2887 * Check the watched status of an article.
2888 * @since 1.22 $checkRights parameter added
2889 * @param $title Title of the article to look at
2890 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
2891 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
2894 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
2895 return $this->getWatchedItem( $title, $checkRights )->isWatched();
2900 * @since 1.22 $checkRights parameter added
2901 * @param $title Title of the article to look at
2902 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
2903 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
2905 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
2906 $this->getWatchedItem( $title, $checkRights )->addWatch();
2907 $this->invalidateCache();
2911 * Stop watching an article.
2912 * @since 1.22 $checkRights parameter added
2913 * @param $title Title of the article to look at
2914 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
2915 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
2917 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
2918 $this->getWatchedItem( $title, $checkRights )->removeWatch();
2919 $this->invalidateCache();
2923 * Clear the user's notification timestamp for the given title.
2924 * If e-notif e-mails are on, they will receive notification mails on
2925 * the next change of the page if it's watched etc.
2926 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
2927 * @param $title Title of the article to look at
2929 public function clearNotification( &$title ) {
2930 global $wgUseEnotif, $wgShowUpdatedMarker;
2932 // Do nothing if the database is locked to writes
2933 if ( wfReadOnly() ) {
2937 // Do nothing if not allowed to edit the watchlist
2938 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
2942 if ( $title->getNamespace() == NS_USER_TALK
&&
2943 $title->getText() == $this->getName() ) {
2944 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) ) {
2947 $this->setNewtalk( false );
2950 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2954 if ( $this->isAnon() ) {
2955 // Nothing else to do...
2959 // Only update the timestamp if the page is being watched.
2960 // The query to find out if it is watched is cached both in memcached and per-invocation,
2961 // and when it does have to be executed, it can be on a slave
2962 // If this is the user's newtalk page, we always update the timestamp
2964 if ( $title->getNamespace() == NS_USER_TALK
&&
2965 $title->getText() == $this->getName() )
2970 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force );
2974 * Resets all of the given user's page-change notification timestamps.
2975 * If e-notif e-mails are on, they will receive notification mails on
2976 * the next change of any watched page.
2977 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
2979 public function clearAllNotifications() {
2980 if ( wfReadOnly() ) {
2984 // Do nothing if not allowed to edit the watchlist
2985 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
2989 global $wgUseEnotif, $wgShowUpdatedMarker;
2990 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2991 $this->setNewtalk( false );
2994 $id = $this->getId();
2996 $dbw = wfGetDB( DB_MASTER
);
2997 $dbw->update( 'watchlist',
2999 'wl_notificationtimestamp' => null
3000 ), array( /* WHERE */
3004 # We also need to clear here the "you have new message" notification for the own user_talk page
3005 # This is cleared one page view later in Article::viewUpdates();
3010 * Set this user's options from an encoded string
3011 * @param string $str Encoded options to import
3013 * @deprecated in 1.19 due to removal of user_options from the user table
3015 private function decodeOptions( $str ) {
3016 wfDeprecated( __METHOD__
, '1.19' );
3021 $this->mOptionsLoaded
= true;
3022 $this->mOptionOverrides
= array();
3024 // If an option is not set in $str, use the default value
3025 $this->mOptions
= self
::getDefaultOptions();
3027 $a = explode( "\n", $str );
3028 foreach ( $a as $s ) {
3030 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
3031 $this->mOptions
[$m[1]] = $m[2];
3032 $this->mOptionOverrides
[$m[1]] = $m[2];
3038 * Set a cookie on the user's client. Wrapper for
3039 * WebResponse::setCookie
3040 * @param string $name Name of the cookie to set
3041 * @param string $value Value to set
3042 * @param int $exp Expiration time, as a UNIX time value;
3043 * if 0 or not specified, use the default $wgCookieExpiration
3044 * @param bool $secure
3045 * true: Force setting the secure attribute when setting the cookie
3046 * false: Force NOT setting the secure attribute when setting the cookie
3047 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3049 protected function setCookie( $name, $value, $exp = 0, $secure = null ) {
3050 $this->getRequest()->response()->setcookie( $name, $value, $exp, null, null, $secure );
3054 * Clear a cookie on the user's client
3055 * @param string $name Name of the cookie to clear
3057 protected function clearCookie( $name ) {
3058 $this->setCookie( $name, '', time() - 86400 );
3062 * Set the default cookies for this session on the user's client.
3064 * @param $request WebRequest object to use; $wgRequest will be used if null
3066 * @param bool $secure Whether to force secure/insecure cookies or use default
3068 public function setCookies( $request = null, $secure = null ) {
3069 if ( $request === null ) {
3070 $request = $this->getRequest();
3074 if ( 0 == $this->mId
) {
3077 if ( !$this->mToken
) {
3078 // When token is empty or NULL generate a new one and then save it to the database
3079 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3080 // Simply by setting every cell in the user_token column to NULL and letting them be
3081 // regenerated as users log back into the wiki.
3083 $this->saveSettings();
3086 'wsUserID' => $this->mId
,
3087 'wsToken' => $this->mToken
,
3088 'wsUserName' => $this->getName()
3091 'UserID' => $this->mId
,
3092 'UserName' => $this->getName(),
3094 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
3095 $cookies['Token'] = $this->mToken
;
3097 $cookies['Token'] = false;
3100 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3102 foreach ( $session as $name => $value ) {
3103 $request->setSessionData( $name, $value );
3105 foreach ( $cookies as $name => $value ) {
3106 if ( $value === false ) {
3107 $this->clearCookie( $name );
3109 $this->setCookie( $name, $value, 0, $secure );
3114 * If wpStickHTTPS was selected, also set an insecure cookie that
3115 * will cause the site to redirect the user to HTTPS, if they access
3116 * it over HTTP. Bug 29898.
3118 if ( $request->getCheck( 'wpStickHTTPS' ) ) {
3119 $this->setCookie( 'forceHTTPS', 'true', time() +
2592000, false ); //30 days
3124 * Log this user out.
3126 public function logout() {
3127 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3133 * Clear the user's cookies and session, and reset the instance cache.
3136 public function doLogout() {
3137 $this->clearInstanceCache( 'defaults' );
3139 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3141 $this->clearCookie( 'UserID' );
3142 $this->clearCookie( 'Token' );
3143 $this->clearCookie( 'forceHTTPS' );
3145 // Remember when user logged out, to prevent seeing cached pages
3146 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
3150 * Save this user's settings into the database.
3151 * @todo Only rarely do all these fields need to be set!
3153 public function saveSettings() {
3157 if ( wfReadOnly() ) {
3160 if ( 0 == $this->mId
) {
3164 $this->mTouched
= self
::newTouchedTimestamp();
3165 if ( !$wgAuth->allowSetLocalPassword() ) {
3166 $this->mPassword
= '';
3169 $dbw = wfGetDB( DB_MASTER
);
3170 $dbw->update( 'user',
3172 'user_name' => $this->mName
,
3173 'user_password' => $this->mPassword
,
3174 'user_newpassword' => $this->mNewpassword
,
3175 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3176 'user_real_name' => $this->mRealName
,
3177 'user_email' => $this->mEmail
,
3178 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3179 'user_touched' => $dbw->timestamp( $this->mTouched
),
3180 'user_token' => strval( $this->mToken
),
3181 'user_email_token' => $this->mEmailToken
,
3182 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3183 ), array( /* WHERE */
3184 'user_id' => $this->mId
3188 $this->saveOptions();
3190 wfRunHooks( 'UserSaveSettings', array( $this ) );
3191 $this->clearSharedCache();
3192 $this->getUserPage()->invalidateCache();
3196 * If only this user's username is known, and it exists, return the user ID.
3199 public function idForName() {
3200 $s = trim( $this->getName() );
3205 $dbr = wfGetDB( DB_SLAVE
);
3206 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
3207 if ( $id === false ) {
3214 * Add a user to the database, return the user object
3216 * @param string $name Username to add
3217 * @param array $params of Strings Non-default parameters to save to the database as user_* fields:
3218 * - password The user's password hash. Password logins will be disabled if this is omitted.
3219 * - newpassword Hash for a temporary password that has been mailed to the user
3220 * - email The user's email address
3221 * - email_authenticated The email authentication timestamp
3222 * - real_name The user's real name
3223 * - options An associative array of non-default options
3224 * - token Random authentication token. Do not set.
3225 * - registration Registration timestamp. Do not set.
3227 * @return User object, or null if the username already exists
3229 public static function createNew( $name, $params = array() ) {
3232 $user->setToken(); // init token
3233 if ( isset( $params['options'] ) ) {
3234 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3235 unset( $params['options'] );
3237 $dbw = wfGetDB( DB_MASTER
);
3238 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3241 'user_id' => $seqVal,
3242 'user_name' => $name,
3243 'user_password' => $user->mPassword
,
3244 'user_newpassword' => $user->mNewpassword
,
3245 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3246 'user_email' => $user->mEmail
,
3247 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3248 'user_real_name' => $user->mRealName
,
3249 'user_token' => strval( $user->mToken
),
3250 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3251 'user_editcount' => 0,
3252 'user_touched' => $dbw->timestamp( self
::newTouchedTimestamp() ),
3254 foreach ( $params as $name => $value ) {
3255 $fields["user_$name"] = $value;
3257 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3258 if ( $dbw->affectedRows() ) {
3259 $newUser = User
::newFromId( $dbw->insertId() );
3267 * Add this existing user object to the database. If the user already
3268 * exists, a fatal status object is returned, and the user object is
3269 * initialised with the data from the database.
3271 * Previously, this function generated a DB error due to a key conflict
3272 * if the user already existed. Many extension callers use this function
3273 * in code along the lines of:
3275 * $user = User::newFromName( $name );
3276 * if ( !$user->isLoggedIn() ) {
3277 * $user->addToDatabase();
3279 * // do something with $user...
3281 * However, this was vulnerable to a race condition (bug 16020). By
3282 * initialising the user object if the user exists, we aim to support this
3283 * calling sequence as far as possible.
3285 * Note that if the user exists, this function will acquire a write lock,
3286 * so it is still advisable to make the call conditional on isLoggedIn(),
3287 * and to commit the transaction after calling.
3289 * @throws MWException
3292 public function addToDatabase() {
3294 if ( !$this->mToken
) {
3295 $this->setToken(); // init token
3298 $this->mTouched
= self
::newTouchedTimestamp();
3300 $dbw = wfGetDB( DB_MASTER
);
3301 $inWrite = $dbw->writesOrCallbacksPending();
3302 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3303 $dbw->insert( 'user',
3305 'user_id' => $seqVal,
3306 'user_name' => $this->mName
,
3307 'user_password' => $this->mPassword
,
3308 'user_newpassword' => $this->mNewpassword
,
3309 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3310 'user_email' => $this->mEmail
,
3311 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3312 'user_real_name' => $this->mRealName
,
3313 'user_token' => strval( $this->mToken
),
3314 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3315 'user_editcount' => 0,
3316 'user_touched' => $dbw->timestamp( $this->mTouched
),
3320 if ( !$dbw->affectedRows() ) {
3322 // XXX: Get out of REPEATABLE-READ so the SELECT below works.
3323 // Often this case happens early in views before any writes.
3324 // This shows up at least with CentralAuth.
3325 $dbw->commit( __METHOD__
, 'flush' );
3327 $this->mId
= $dbw->selectField( 'user', 'user_id',
3328 array( 'user_name' => $this->mName
), __METHOD__
);
3331 if ( $this->loadFromDatabase() ) {
3336 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3337 "to insert user '{$this->mName}' row, but it was not present in select!" );
3339 return Status
::newFatal( 'userexists' );
3341 $this->mId
= $dbw->insertId();
3343 // Clear instance cache other than user table data, which is already accurate
3344 $this->clearInstanceCache();
3346 $this->saveOptions();
3347 return Status
::newGood();
3351 * If this user is logged-in and blocked,
3352 * block any IP address they've successfully logged in from.
3353 * @return bool A block was spread
3355 public function spreadAnyEditBlock() {
3356 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3357 return $this->spreadBlock();
3363 * If this (non-anonymous) user is blocked,
3364 * block the IP address they've successfully logged in from.
3365 * @return bool A block was spread
3367 protected function spreadBlock() {
3368 wfDebug( __METHOD__
. "()\n" );
3370 if ( $this->mId
== 0 ) {
3374 $userblock = Block
::newFromTarget( $this->getName() );
3375 if ( !$userblock ) {
3379 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3383 * Generate a string which will be different for any combination of
3384 * user options which would produce different parser output.
3385 * This will be used as part of the hash key for the parser cache,
3386 * so users with the same options can share the same cached data
3389 * Extensions which require it should install 'PageRenderingHash' hook,
3390 * which will give them a chance to modify this key based on their own
3393 * @deprecated since 1.17 use the ParserOptions object to get the relevant options
3394 * @return string Page rendering hash
3396 public function getPageRenderingHash() {
3397 wfDeprecated( __METHOD__
, '1.17' );
3399 global $wgRenderHashAppend, $wgLang, $wgContLang;
3400 if ( $this->mHash
) {
3401 return $this->mHash
;
3404 // stubthreshold is only included below for completeness,
3405 // since it disables the parser cache, its value will always
3406 // be 0 when this function is called by parsercache.
3408 $confstr = $this->getOption( 'math' );
3409 $confstr .= '!' . $this->getStubThreshold();
3410 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ?
'1' : '' );
3411 $confstr .= '!' . $wgLang->getCode();
3412 $confstr .= '!' . $this->getOption( 'thumbsize' );
3413 // add in language specific options, if any
3414 $extra = $wgContLang->getExtraHashOptions();
3417 // Since the skin could be overloading link(), it should be
3418 // included here but in practice, none of our skins do that.
3420 $confstr .= $wgRenderHashAppend;
3422 // Give a chance for extensions to modify the hash, if they have
3423 // extra options or other effects on the parser cache.
3424 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
3426 // Make it a valid memcached key fragment
3427 $confstr = str_replace( ' ', '_', $confstr );
3428 $this->mHash
= $confstr;
3433 * Get whether the user is explicitly blocked from account creation.
3434 * @return bool|Block
3436 public function isBlockedFromCreateAccount() {
3437 $this->getBlockedStatus();
3438 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3439 return $this->mBlock
;
3442 # bug 13611: if the IP address the user is trying to create an account from is
3443 # blocked with createaccount disabled, prevent new account creation there even
3444 # when the user is logged in
3445 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3446 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3448 return $this->mBlockedFromCreateAccount
instanceof Block
&& $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3449 ?
$this->mBlockedFromCreateAccount
3454 * Get whether the user is blocked from using Special:Emailuser.
3457 public function isBlockedFromEmailuser() {
3458 $this->getBlockedStatus();
3459 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3463 * Get whether the user is allowed to create an account.
3466 function isAllowedToCreateAccount() {
3467 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3471 * Get this user's personal page title.
3473 * @return Title: User's personal page title
3475 public function getUserPage() {
3476 return Title
::makeTitle( NS_USER
, $this->getName() );
3480 * Get this user's talk page title.
3482 * @return Title: User's talk page title
3484 public function getTalkPage() {
3485 $title = $this->getUserPage();
3486 return $title->getTalkPage();
3490 * Determine whether the user is a newbie. Newbies are either
3491 * anonymous IPs, or the most recently created accounts.
3494 public function isNewbie() {
3495 return !$this->isAllowed( 'autoconfirmed' );
3499 * Check to see if the given clear-text password is one of the accepted passwords
3500 * @param string $password user password.
3501 * @return boolean: True if the given password is correct, otherwise False.
3503 public function checkPassword( $password ) {
3504 global $wgAuth, $wgLegacyEncoding;
3507 // Even though we stop people from creating passwords that
3508 // are shorter than this, doesn't mean people wont be able
3509 // to. Certain authentication plugins do NOT want to save
3510 // domain passwords in a mysql database, so we should
3511 // check this (in case $wgAuth->strict() is false).
3512 if ( !$this->isValidPassword( $password ) ) {
3516 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3518 } elseif ( $wgAuth->strict() ) {
3519 // Auth plugin doesn't allow local authentication
3521 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3522 // Auth plugin doesn't allow local authentication for this user name
3525 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
3527 } elseif ( $wgLegacyEncoding ) {
3528 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3529 // Check for this with iconv
3530 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3531 if ( $cp1252Password != $password &&
3532 self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) )
3541 * Check if the given clear-text password matches the temporary password
3542 * sent by e-mail for password reset operations.
3544 * @param $plaintext string
3546 * @return boolean: True if matches, false otherwise
3548 public function checkTemporaryPassword( $plaintext ) {
3549 global $wgNewPasswordExpiry;
3552 if ( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
3553 if ( is_null( $this->mNewpassTime
) ) {
3556 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3557 return ( time() < $expiry );
3564 * Alias for getEditToken.
3565 * @deprecated since 1.19, use getEditToken instead.
3567 * @param string|array $salt of Strings Optional function-specific data for hashing
3568 * @param $request WebRequest object to use or null to use $wgRequest
3569 * @return string The new edit token
3571 public function editToken( $salt = '', $request = null ) {
3572 wfDeprecated( __METHOD__
, '1.19' );
3573 return $this->getEditToken( $salt, $request );
3577 * Initialize (if necessary) and return a session token value
3578 * which can be used in edit forms to show that the user's
3579 * login credentials aren't being hijacked with a foreign form
3584 * @param string|array $salt of Strings Optional function-specific data for hashing
3585 * @param $request WebRequest object to use or null to use $wgRequest
3586 * @return string The new edit token
3588 public function getEditToken( $salt = '', $request = null ) {
3589 if ( $request == null ) {
3590 $request = $this->getRequest();
3593 if ( $this->isAnon() ) {
3594 return EDIT_TOKEN_SUFFIX
;
3596 $token = $request->getSessionData( 'wsEditToken' );
3597 if ( $token === null ) {
3598 $token = MWCryptRand
::generateHex( 32 );
3599 $request->setSessionData( 'wsEditToken', $token );
3601 if ( is_array( $salt ) ) {
3602 $salt = implode( '|', $salt );
3604 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
3609 * Generate a looking random token for various uses.
3611 * @return string The new random token
3612 * @deprecated since 1.20: Use MWCryptRand for secure purposes or wfRandomString for pseudo-randomness
3614 public static function generateToken() {
3615 return MWCryptRand
::generateHex( 32 );
3619 * Check given value against the token value stored in the session.
3620 * A match should confirm that the form was submitted from the
3621 * user's own login session, not a form submission from a third-party
3624 * @param string $val Input value to compare
3625 * @param string $salt Optional function-specific data for hashing
3626 * @param WebRequest $request Object to use or null to use $wgRequest
3627 * @return boolean: Whether the token matches
3629 public function matchEditToken( $val, $salt = '', $request = null ) {
3630 $sessionToken = $this->getEditToken( $salt, $request );
3631 if ( $val != $sessionToken ) {
3632 wfDebug( "User::matchEditToken: broken session data\n" );
3634 return $val == $sessionToken;
3638 * Check given value against the token value stored in the session,
3639 * ignoring the suffix.
3641 * @param string $val Input value to compare
3642 * @param string $salt Optional function-specific data for hashing
3643 * @param WebRequest $request object to use or null to use $wgRequest
3644 * @return boolean: Whether the token matches
3646 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3647 $sessionToken = $this->getEditToken( $salt, $request );
3648 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3652 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3653 * mail to the user's given address.
3655 * @param string $type message to send, either "created", "changed" or "set"
3656 * @return Status object
3658 public function sendConfirmationMail( $type = 'created' ) {
3660 $expiration = null; // gets passed-by-ref and defined in next line.
3661 $token = $this->confirmationToken( $expiration );
3662 $url = $this->confirmationTokenUrl( $token );
3663 $invalidateURL = $this->invalidationTokenUrl( $token );
3664 $this->saveSettings();
3666 if ( $type == 'created' ||
$type === false ) {
3667 $message = 'confirmemail_body';
3668 } elseif ( $type === true ) {
3669 $message = 'confirmemail_body_changed';
3671 $message = 'confirmemail_body_' . $type;
3674 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3675 wfMessage( $message,
3676 $this->getRequest()->getIP(),
3679 $wgLang->timeanddate( $expiration, false ),
3681 $wgLang->date( $expiration, false ),
3682 $wgLang->time( $expiration, false ) )->text() );
3686 * Send an e-mail to this user's account. Does not check for
3687 * confirmed status or validity.
3689 * @param string $subject Message subject
3690 * @param string $body Message body
3691 * @param string $from Optional From address; if unspecified, default $wgPasswordSender will be used
3692 * @param string $replyto Reply-To address
3695 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3696 if ( is_null( $from ) ) {
3697 global $wgPasswordSender, $wgPasswordSenderName;
3698 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
3700 $sender = new MailAddress( $from );
3703 $to = new MailAddress( $this );
3704 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
3708 * Generate, store, and return a new e-mail confirmation code.
3709 * A hash (unsalted, since it's used as a key) is stored.
3711 * @note Call saveSettings() after calling this function to commit
3712 * this change to the database.
3714 * @param &$expiration \mixed Accepts the expiration time
3715 * @return string New token
3717 protected function confirmationToken( &$expiration ) {
3718 global $wgUserEmailConfirmationTokenExpiry;
3720 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
3721 $expiration = wfTimestamp( TS_MW
, $expires );
3723 $token = MWCryptRand
::generateHex( 32 );
3724 $hash = md5( $token );
3725 $this->mEmailToken
= $hash;
3726 $this->mEmailTokenExpires
= $expiration;
3731 * Return a URL the user can use to confirm their email address.
3732 * @param string $token Accepts the email confirmation token
3733 * @return string New token URL
3735 protected function confirmationTokenUrl( $token ) {
3736 return $this->getTokenUrl( 'ConfirmEmail', $token );
3740 * Return a URL the user can use to invalidate their email address.
3741 * @param string $token Accepts the email confirmation token
3742 * @return string New token URL
3744 protected function invalidationTokenUrl( $token ) {
3745 return $this->getTokenUrl( 'InvalidateEmail', $token );
3749 * Internal function to format the e-mail validation/invalidation URLs.
3750 * This uses a quickie hack to use the
3751 * hardcoded English names of the Special: pages, for ASCII safety.
3753 * @note Since these URLs get dropped directly into emails, using the
3754 * short English names avoids insanely long URL-encoded links, which
3755 * also sometimes can get corrupted in some browsers/mailers
3756 * (bug 6957 with Gmail and Internet Explorer).
3758 * @param string $page Special page
3759 * @param string $token Token
3760 * @return string Formatted URL
3762 protected function getTokenUrl( $page, $token ) {
3763 // Hack to bypass localization of 'Special:'
3764 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
3765 return $title->getCanonicalURL();
3769 * Mark the e-mail address confirmed.
3771 * @note Call saveSettings() after calling this function to commit the change.
3775 public function confirmEmail() {
3776 // Check if it's already confirmed, so we don't touch the database
3777 // and fire the ConfirmEmailComplete hook on redundant confirmations.
3778 if ( !$this->isEmailConfirmed() ) {
3779 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3780 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3786 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3787 * address if it was already confirmed.
3789 * @note Call saveSettings() after calling this function to commit the change.
3790 * @return bool Returns true
3792 function invalidateEmail() {
3794 $this->mEmailToken
= null;
3795 $this->mEmailTokenExpires
= null;
3796 $this->setEmailAuthenticationTimestamp( null );
3797 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3802 * Set the e-mail authentication timestamp.
3803 * @param string $timestamp TS_MW timestamp
3805 function setEmailAuthenticationTimestamp( $timestamp ) {
3807 $this->mEmailAuthenticated
= $timestamp;
3808 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
3812 * Is this user allowed to send e-mails within limits of current
3813 * site configuration?
3816 public function canSendEmail() {
3817 global $wgEnableEmail, $wgEnableUserEmail;
3818 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
3821 $canSend = $this->isEmailConfirmed();
3822 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3827 * Is this user allowed to receive e-mails within limits of current
3828 * site configuration?
3831 public function canReceiveEmail() {
3832 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3836 * Is this user's e-mail address valid-looking and confirmed within
3837 * limits of the current site configuration?
3839 * @note If $wgEmailAuthentication is on, this may require the user to have
3840 * confirmed their address by returning a code or using a password
3841 * sent to the address from the wiki.
3845 public function isEmailConfirmed() {
3846 global $wgEmailAuthentication;
3849 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3850 if ( $this->isAnon() ) {
3853 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
3856 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
3866 * Check whether there is an outstanding request for e-mail confirmation.
3869 public function isEmailConfirmationPending() {
3870 global $wgEmailAuthentication;
3871 return $wgEmailAuthentication &&
3872 !$this->isEmailConfirmed() &&
3873 $this->mEmailToken
&&
3874 $this->mEmailTokenExpires
> wfTimestamp();
3878 * Get the timestamp of account creation.
3880 * @return string|bool|null Timestamp of account creation, false for
3881 * non-existent/anonymous user accounts, or null if existing account
3882 * but information is not in database.
3884 public function getRegistration() {
3885 if ( $this->isAnon() ) {
3889 return $this->mRegistration
;
3893 * Get the timestamp of the first edit
3895 * @return string|bool Timestamp of first edit, or false for
3896 * non-existent/anonymous user accounts.
3898 public function getFirstEditTimestamp() {
3899 if ( $this->getId() == 0 ) {
3900 return false; // anons
3902 $dbr = wfGetDB( DB_SLAVE
);
3903 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3904 array( 'rev_user' => $this->getId() ),
3906 array( 'ORDER BY' => 'rev_timestamp ASC' )
3909 return false; // no edits
3911 return wfTimestamp( TS_MW
, $time );
3915 * Get the permissions associated with a given list of groups
3917 * @param array $groups of Strings List of internal group names
3918 * @return Array of Strings List of permission key names for given groups combined
3920 public static function getGroupPermissions( $groups ) {
3921 global $wgGroupPermissions, $wgRevokePermissions;
3923 // grant every granted permission first
3924 foreach ( $groups as $group ) {
3925 if ( isset( $wgGroupPermissions[$group] ) ) {
3926 $rights = array_merge( $rights,
3927 // array_filter removes empty items
3928 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3931 // now revoke the revoked permissions
3932 foreach ( $groups as $group ) {
3933 if ( isset( $wgRevokePermissions[$group] ) ) {
3934 $rights = array_diff( $rights,
3935 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3938 return array_unique( $rights );
3942 * Get all the groups who have a given permission
3944 * @param string $role Role to check
3945 * @return Array of Strings List of internal group names with the given permission
3947 public static function getGroupsWithPermission( $role ) {
3948 global $wgGroupPermissions;
3949 $allowedGroups = array();
3950 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
3951 if ( self
::groupHasPermission( $group, $role ) ) {
3952 $allowedGroups[] = $group;
3955 return $allowedGroups;
3959 * Check, if the given group has the given permission
3962 * @param string $group Group to check
3963 * @param string $role Role to check
3966 public static function groupHasPermission( $group, $role ) {
3967 global $wgGroupPermissions, $wgRevokePermissions;
3968 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
3969 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
3973 * Get the localized descriptive name for a group, if it exists
3975 * @param string $group Internal group name
3976 * @return string Localized descriptive group name
3978 public static function getGroupName( $group ) {
3979 $msg = wfMessage( "group-$group" );
3980 return $msg->isBlank() ?
$group : $msg->text();
3984 * Get the localized descriptive name for a member of a group, if it exists
3986 * @param string $group Internal group name
3987 * @param string $username Username for gender (since 1.19)
3988 * @return string Localized name for group member
3990 public static function getGroupMember( $group, $username = '#' ) {
3991 $msg = wfMessage( "group-$group-member", $username );
3992 return $msg->isBlank() ?
$group : $msg->text();
3996 * Return the set of defined explicit groups.
3997 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3998 * are not included, as they are defined automatically, not in the database.
3999 * @return Array of internal group names
4001 public static function getAllGroups() {
4002 global $wgGroupPermissions, $wgRevokePermissions;
4004 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4005 self
::getImplicitGroups()
4010 * Get a list of all available permissions.
4011 * @return Array of permission names
4013 public static function getAllRights() {
4014 if ( self
::$mAllRights === false ) {
4015 global $wgAvailableRights;
4016 if ( count( $wgAvailableRights ) ) {
4017 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4019 self
::$mAllRights = self
::$mCoreRights;
4021 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
4023 return self
::$mAllRights;
4027 * Get a list of implicit groups
4028 * @return Array of Strings Array of internal group names
4030 public static function getImplicitGroups() {
4031 global $wgImplicitGroups;
4032 $groups = $wgImplicitGroups;
4033 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
4038 * Get the title of a page describing a particular group
4040 * @param string $group Internal group name
4041 * @return Title|bool Title of the page if it exists, false otherwise
4043 public static function getGroupPage( $group ) {
4044 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4045 if ( $msg->exists() ) {
4046 $title = Title
::newFromText( $msg->text() );
4047 if ( is_object( $title ) ) {
4055 * Create a link to the group in HTML, if available;
4056 * else return the group name.
4058 * @param string $group Internal name of the group
4059 * @param string $text The text of the link
4060 * @return string HTML link to the group
4062 public static function makeGroupLinkHTML( $group, $text = '' ) {
4063 if ( $text == '' ) {
4064 $text = self
::getGroupName( $group );
4066 $title = self
::getGroupPage( $group );
4068 return Linker
::link( $title, htmlspecialchars( $text ) );
4075 * Create a link to the group in Wikitext, if available;
4076 * else return the group name.
4078 * @param string $group Internal name of the group
4079 * @param string $text The text of the link
4080 * @return string Wikilink to the group
4082 public static function makeGroupLinkWiki( $group, $text = '' ) {
4083 if ( $text == '' ) {
4084 $text = self
::getGroupName( $group );
4086 $title = self
::getGroupPage( $group );
4088 $page = $title->getPrefixedText();
4089 return "[[$page|$text]]";
4096 * Returns an array of the groups that a particular group can add/remove.
4098 * @param string $group the group to check for whether it can add/remove
4099 * @return Array array( 'add' => array( addablegroups ),
4100 * 'remove' => array( removablegroups ),
4101 * 'add-self' => array( addablegroups to self),
4102 * 'remove-self' => array( removable groups from self) )
4104 public static function changeableByGroup( $group ) {
4105 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4107 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
4108 if ( empty( $wgAddGroups[$group] ) ) {
4109 // Don't add anything to $groups
4110 } elseif ( $wgAddGroups[$group] === true ) {
4111 // You get everything
4112 $groups['add'] = self
::getAllGroups();
4113 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4114 $groups['add'] = $wgAddGroups[$group];
4117 // Same thing for remove
4118 if ( empty( $wgRemoveGroups[$group] ) ) {
4119 } elseif ( $wgRemoveGroups[$group] === true ) {
4120 $groups['remove'] = self
::getAllGroups();
4121 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4122 $groups['remove'] = $wgRemoveGroups[$group];
4125 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4126 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4127 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4128 if ( is_int( $key ) ) {
4129 $wgGroupsAddToSelf['user'][] = $value;
4134 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4135 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4136 if ( is_int( $key ) ) {
4137 $wgGroupsRemoveFromSelf['user'][] = $value;
4142 // Now figure out what groups the user can add to him/herself
4143 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4144 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4145 // No idea WHY this would be used, but it's there
4146 $groups['add-self'] = User
::getAllGroups();
4147 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4148 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4151 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4152 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4153 $groups['remove-self'] = User
::getAllGroups();
4154 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4155 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4162 * Returns an array of groups that this user can add and remove
4163 * @return Array array( 'add' => array( addablegroups ),
4164 * 'remove' => array( removablegroups ),
4165 * 'add-self' => array( addablegroups to self),
4166 * 'remove-self' => array( removable groups from self) )
4168 public function changeableGroups() {
4169 if ( $this->isAllowed( 'userrights' ) ) {
4170 // This group gives the right to modify everything (reverse-
4171 // compatibility with old "userrights lets you change
4173 // Using array_merge to make the groups reindexed
4174 $all = array_merge( User
::getAllGroups() );
4178 'add-self' => array(),
4179 'remove-self' => array()
4183 // Okay, it's not so simple, we will have to go through the arrays
4186 'remove' => array(),
4187 'add-self' => array(),
4188 'remove-self' => array()
4190 $addergroups = $this->getEffectiveGroups();
4192 foreach ( $addergroups as $addergroup ) {
4193 $groups = array_merge_recursive(
4194 $groups, $this->changeableByGroup( $addergroup )
4196 $groups['add'] = array_unique( $groups['add'] );
4197 $groups['remove'] = array_unique( $groups['remove'] );
4198 $groups['add-self'] = array_unique( $groups['add-self'] );
4199 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4205 * Increment the user's edit-count field.
4206 * Will have no effect for anonymous users.
4208 public function incEditCount() {
4209 if ( !$this->isAnon() ) {
4210 $dbw = wfGetDB( DB_MASTER
);
4213 array( 'user_editcount=user_editcount+1' ),
4214 array( 'user_id' => $this->getId() ),
4218 // Lazy initialization check...
4219 if ( $dbw->affectedRows() == 0 ) {
4220 // Now here's a goddamn hack...
4221 $dbr = wfGetDB( DB_SLAVE
);
4222 if ( $dbr !== $dbw ) {
4223 // If we actually have a slave server, the count is
4224 // at least one behind because the current transaction
4225 // has not been committed and replicated.
4226 $this->initEditCount( 1 );
4228 // But if DB_SLAVE is selecting the master, then the
4229 // count we just read includes the revision that was
4230 // just added in the working transaction.
4231 $this->initEditCount();
4235 // edit count in user cache too
4236 $this->invalidateCache();
4240 * Initialize user_editcount from data out of the revision table
4242 * @param $add Integer Edits to add to the count from the revision table
4243 * @return integer Number of edits
4245 protected function initEditCount( $add = 0 ) {
4246 // Pull from a slave to be less cruel to servers
4247 // Accuracy isn't the point anyway here
4248 $dbr = wfGetDB( DB_SLAVE
);
4249 $count = (int) $dbr->selectField(
4252 array( 'rev_user' => $this->getId() ),
4255 $count = $count +
$add;
4257 $dbw = wfGetDB( DB_MASTER
);
4260 array( 'user_editcount' => $count ),
4261 array( 'user_id' => $this->getId() ),
4269 * Get the description of a given right
4271 * @param string $right Right to query
4272 * @return string Localized description of the right
4274 public static function getRightDescription( $right ) {
4275 $key = "right-$right";
4276 $msg = wfMessage( $key );
4277 return $msg->isBlank() ?
$right : $msg->text();
4281 * Make an old-style password hash
4283 * @param string $password Plain-text password
4284 * @param string $userId User ID
4285 * @return string Password hash
4287 public static function oldCrypt( $password, $userId ) {
4288 global $wgPasswordSalt;
4289 if ( $wgPasswordSalt ) {
4290 return md5( $userId . '-' . md5( $password ) );
4292 return md5( $password );
4297 * Make a new-style password hash
4299 * @param string $password Plain-text password
4300 * @param bool|string $salt Optional salt, may be random or the user ID.
4301 * If unspecified or false, will generate one automatically
4302 * @return string Password hash
4304 public static function crypt( $password, $salt = false ) {
4305 global $wgPasswordSalt;
4308 if ( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4312 if ( $wgPasswordSalt ) {
4313 if ( $salt === false ) {
4314 $salt = MWCryptRand
::generateHex( 8 );
4316 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4318 return ':A:' . md5( $password );
4323 * Compare a password hash with a plain-text password. Requires the user
4324 * ID if there's a chance that the hash is an old-style hash.
4326 * @param string $hash Password hash
4327 * @param string $password Plain-text password to compare
4328 * @param string|bool $userId User ID for old-style password salt
4332 public static function comparePasswords( $hash, $password, $userId = false ) {
4333 $type = substr( $hash, 0, 3 );
4336 if ( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4340 if ( $type == ':A:' ) {
4342 return md5( $password ) === substr( $hash, 3 );
4343 } elseif ( $type == ':B:' ) {
4345 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4346 return md5( $salt . '-' . md5( $password ) ) === $realHash;
4349 return self
::oldCrypt( $password, $userId ) === $hash;
4354 * Add a newuser log entry for this user.
4355 * Before 1.19 the return value was always true.
4357 * @param string|bool $action account creation type.
4358 * - String, one of the following values:
4359 * - 'create' for an anonymous user creating an account for himself.
4360 * This will force the action's performer to be the created user itself,
4361 * no matter the value of $wgUser
4362 * - 'create2' for a logged in user creating an account for someone else
4363 * - 'byemail' when the created user will receive its password by e-mail
4364 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4365 * - Boolean means whether the account was created by e-mail (deprecated):
4366 * - true will be converted to 'byemail'
4367 * - false will be converted to 'create' if this object is the same as
4368 * $wgUser and to 'create2' otherwise
4370 * @param string $reason user supplied reason
4372 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4374 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4375 global $wgUser, $wgNewUserLog;
4376 if ( empty( $wgNewUserLog ) ) {
4377 return true; // disabled
4380 if ( $action === true ) {
4381 $action = 'byemail';
4382 } elseif ( $action === false ) {
4383 if ( $this->getName() == $wgUser->getName() ) {
4386 $action = 'create2';
4390 if ( $action === 'create' ||
$action === 'autocreate' ) {
4393 $performer = $wgUser;
4396 $logEntry = new ManualLogEntry( 'newusers', $action );
4397 $logEntry->setPerformer( $performer );
4398 $logEntry->setTarget( $this->getUserPage() );
4399 $logEntry->setComment( $reason );
4400 $logEntry->setParameters( array(
4401 '4::userid' => $this->getId(),
4403 $logid = $logEntry->insert();
4405 if ( $action !== 'autocreate' ) {
4406 $logEntry->publish( $logid );
4413 * Add an autocreate newuser log entry for this user
4414 * Used by things like CentralAuth and perhaps other authplugins.
4415 * Consider calling addNewUserLogEntry() directly instead.
4419 public function addNewUserLogEntryAutoCreate() {
4420 $this->addNewUserLogEntry( 'autocreate' );
4426 * Load the user options either from cache, the database or an array
4428 * @param array $data Rows for the current user out of the user_properties table
4430 protected function loadOptions( $data = null ) {
4435 if ( $this->mOptionsLoaded
) {
4439 $this->mOptions
= self
::getDefaultOptions();
4441 if ( !$this->getId() ) {
4442 // For unlogged-in users, load language/variant options from request.
4443 // There's no need to do it for logged-in users: they can set preferences,
4444 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4445 // so don't override user's choice (especially when the user chooses site default).
4446 $variant = $wgContLang->getDefaultVariant();
4447 $this->mOptions
['variant'] = $variant;
4448 $this->mOptions
['language'] = $variant;
4449 $this->mOptionsLoaded
= true;
4453 // Maybe load from the object
4454 if ( !is_null( $this->mOptionOverrides
) ) {
4455 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4456 foreach ( $this->mOptionOverrides
as $key => $value ) {
4457 $this->mOptions
[$key] = $value;
4460 if ( !is_array( $data ) ) {
4461 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4462 // Load from database
4463 $dbr = wfGetDB( DB_SLAVE
);
4465 $res = $dbr->select(
4467 array( 'up_property', 'up_value' ),
4468 array( 'up_user' => $this->getId() ),
4472 $this->mOptionOverrides
= array();
4474 foreach ( $res as $row ) {
4475 $data[$row->up_property
] = $row->up_value
;
4478 foreach ( $data as $property => $value ) {
4479 $this->mOptionOverrides
[$property] = $value;
4480 $this->mOptions
[$property] = $value;
4484 $this->mOptionsLoaded
= true;
4486 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
4492 protected function saveOptions() {
4493 $this->loadOptions();
4495 // Not using getOptions(), to keep hidden preferences in database
4496 $saveOptions = $this->mOptions
;
4498 // Allow hooks to abort, for instance to save to a global profile.
4499 // Reset options to default state before saving.
4500 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4504 $userId = $this->getId();
4505 $insert_rows = array();
4506 foreach ( $saveOptions as $key => $value ) {
4507 // Don't bother storing default values
4508 $defaultOption = self
::getDefaultOption( $key );
4509 if ( ( is_null( $defaultOption ) &&
4510 !( $value === false ||
is_null( $value ) ) ) ||
4511 $value != $defaultOption ) {
4512 $insert_rows[] = array(
4513 'up_user' => $userId,
4514 'up_property' => $key,
4515 'up_value' => $value,
4520 $dbw = wfGetDB( DB_MASTER
);
4521 $hasRows = $dbw->selectField( 'user_properties', '1',
4522 array( 'up_user' => $userId ), __METHOD__
);
4525 // Only do this delete if there is something there. A very large portion of
4526 // calls to this function are for setting 'rememberpassword' for new accounts.
4527 // Doing this delete for new accounts with no rows in the table rougly causes
4528 // gap locks on [max user ID,+infinity) which causes high contention since many
4529 // updates will pile up on each other since they are for higher (newer) user IDs.
4530 $dbw->delete( 'user_properties', array( 'up_user' => $userId ), __METHOD__
);
4532 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
4536 * Provide an array of HTML5 attributes to put on an input element
4537 * intended for the user to enter a new password. This may include
4538 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4540 * Do *not* use this when asking the user to enter his current password!
4541 * Regardless of configuration, users may have invalid passwords for whatever
4542 * reason (e.g., they were set before requirements were tightened up).
4543 * Only use it when asking for a new password, like on account creation or
4546 * Obviously, you still need to do server-side checking.
4548 * NOTE: A combination of bugs in various browsers means that this function
4549 * actually just returns array() unconditionally at the moment. May as
4550 * well keep it around for when the browser bugs get fixed, though.
4552 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4554 * @return array Array of HTML attributes suitable for feeding to
4555 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4556 * That will get confused by the boolean attribute syntax used.)
4558 public static function passwordChangeInputAttribs() {
4559 global $wgMinimalPasswordLength;
4561 if ( $wgMinimalPasswordLength == 0 ) {
4565 # Note that the pattern requirement will always be satisfied if the
4566 # input is empty, so we need required in all cases.
4568 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4569 # if e-mail confirmation is being used. Since HTML5 input validation
4570 # is b0rked anyway in some browsers, just return nothing. When it's
4571 # re-enabled, fix this code to not output required for e-mail
4573 #$ret = array( 'required' );
4576 # We can't actually do this right now, because Opera 9.6 will print out
4577 # the entered password visibly in its error message! When other
4578 # browsers add support for this attribute, or Opera fixes its support,
4579 # we can add support with a version check to avoid doing this on Opera
4580 # versions where it will be a problem. Reported to Opera as
4581 # DSK-262266, but they don't have a public bug tracker for us to follow.
4583 if ( $wgMinimalPasswordLength > 1 ) {
4584 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4585 $ret['title'] = wfMessage( 'passwordtooshort' )
4586 ->numParams( $wgMinimalPasswordLength )->text();
4594 * Return the list of user fields that should be selected to create
4595 * a new user object.
4598 public static function selectFields() {
4605 'user_newpass_time',
4609 'user_email_authenticated',
4611 'user_email_token_expires',
4612 'user_registration',
4618 * Factory function for fatal permission-denied errors
4621 * @param string $permission User right required
4624 static function newFatalPermissionDeniedStatus( $permission ) {
4627 $groups = array_map(
4628 array( 'User', 'makeGroupLinkWiki' ),
4629 User
::getGroupsWithPermission( $permission )
4633 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4635 return Status
::newFatal( 'badaccess-group0' );