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(
127 'editusercssjs', #deprecated
139 'move-rootuserpages',
143 'override-export-depth',
166 'userrights-interwiki',
170 * String Cached results of getAllRights()
172 static $mAllRights = false;
174 /** @name Cache variables */
176 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
177 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
178 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mEditCount,
179 $mGroups, $mOptionOverrides;
183 * Bool Whether the cache variables have been loaded.
189 * Array with already loaded items or true if all items have been loaded.
191 private $mLoadedItems = array();
195 * String Initialization data source if mLoadedItems!==true. May be one of:
196 * - 'defaults' anonymous user initialised from class defaults
197 * - 'name' initialise from mName
198 * - 'id' initialise from mId
199 * - 'session' log in from cookies or session if possible
201 * Use the User::newFrom*() family of functions to set this.
206 * Lazy-initialized variables, invalidated with clearInstanceCache
208 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mRights,
209 $mBlockreason, $mEffectiveGroups, $mImplicitGroups, $mFormerGroups, $mBlockedGlobally,
210 $mLocked, $mHideName, $mOptions;
230 private $mBlockedFromCreateAccount = false;
235 private $mWatchedItems = array();
237 static $idCacheByName = array();
240 * Lightweight constructor for an anonymous user.
241 * Use the User::newFrom* factory functions for other kinds of users.
245 * @see newFromConfirmationCode()
246 * @see newFromSession()
249 function __construct() {
250 $this->clearInstanceCache( 'defaults' );
256 function __toString(){
257 return $this->getName();
261 * Load the user table data for this object from the source given by mFrom.
263 public function load() {
264 if ( $this->mLoadedItems
=== true ) {
267 wfProfileIn( __METHOD__
);
269 # Set it now to avoid infinite recursion in accessors
270 $this->mLoadedItems
= true;
272 switch ( $this->mFrom
) {
274 $this->loadDefaults();
277 $this->mId
= self
::idFromName( $this->mName
);
279 # Nonexistent user placeholder object
280 $this->loadDefaults( $this->mName
);
289 $this->loadFromSession();
290 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
293 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
295 wfProfileOut( __METHOD__
);
299 * Load user table data, given mId has already been set.
300 * @return Bool false if the ID does not exist, true otherwise
302 public function loadFromId() {
304 if ( $this->mId
== 0 ) {
305 $this->loadDefaults();
310 $key = wfMemcKey( 'user', 'id', $this->mId
);
311 $data = $wgMemc->get( $key );
312 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
313 # Object is expired, load from DB
318 wfDebug( "User: cache miss for user {$this->mId}\n" );
320 if ( !$this->loadFromDatabase() ) {
321 # Can't load from ID, user is anonymous
324 $this->saveToCache();
326 wfDebug( "User: got user {$this->mId} from cache\n" );
328 foreach ( self
::$mCacheVars as $name ) {
329 $this->$name = $data[$name];
336 * Save user data to the shared cache
338 public function saveToCache() {
341 $this->loadOptions();
342 if ( $this->isAnon() ) {
343 // Anonymous users are uncached
347 foreach ( self
::$mCacheVars as $name ) {
348 $data[$name] = $this->$name;
350 $data['mVersion'] = MW_USER_VERSION
;
351 $key = wfMemcKey( 'user', 'id', $this->mId
);
353 $wgMemc->set( $key, $data );
356 /** @name newFrom*() static factory methods */
360 * Static factory method for creation from username.
362 * This is slightly less efficient than newFromId(), so use newFromId() if
363 * you have both an ID and a name handy.
365 * @param $name String Username, validated by Title::newFromText()
366 * @param $validate String|Bool Validate username. Takes the same parameters as
367 * User::getCanonicalName(), except that true is accepted as an alias
368 * for 'valid', for BC.
370 * @return User object, or false if the username is invalid
371 * (e.g. if it contains illegal characters or is an IP address). If the
372 * username is not present in the database, the result will be a user object
373 * with a name, zero user ID and default settings.
375 public static function newFromName( $name, $validate = 'valid' ) {
376 if ( $validate === true ) {
379 $name = self
::getCanonicalName( $name, $validate );
380 if ( $name === false ) {
383 # Create unloaded user object
387 $u->setItemLoaded( 'name' );
393 * Static factory method for creation from a given user ID.
395 * @param $id Int Valid user ID
396 * @return User The corresponding User object
398 public static function newFromId( $id ) {
402 $u->setItemLoaded( 'id' );
407 * Factory method to fetch whichever user has a given email confirmation code.
408 * This code is generated when an account is created or its e-mail address
411 * If the code is invalid or has expired, returns NULL.
413 * @param $code String Confirmation code
414 * @return User object, or null
416 public static function newFromConfirmationCode( $code ) {
417 $dbr = wfGetDB( DB_SLAVE
);
418 $id = $dbr->selectField( 'user', 'user_id', array(
419 'user_email_token' => md5( $code ),
420 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
422 if( $id !== false ) {
423 return User
::newFromId( $id );
430 * Create a new user object using data from session or cookies. If the
431 * login credentials are invalid, the result is an anonymous user.
433 * @param $request WebRequest object to use; $wgRequest will be used if
435 * @return User object
437 public static function newFromSession( WebRequest
$request = null ) {
439 $user->mFrom
= 'session';
440 $user->mRequest
= $request;
445 * Create a new user object from a user row.
446 * The row should have the following fields from the user table in it:
447 * - either user_name or user_id to load further data if needed (or both)
449 * - all other fields (email, password, etc.)
450 * It is useless to provide the remaining fields if either user_id,
451 * user_name and user_real_name are not provided because the whole row
452 * will be loaded once more from the database when accessing them.
454 * @param $row Array A row from the user table
457 public static function newFromRow( $row ) {
459 $user->loadFromRow( $row );
466 * Get the username corresponding to a given user ID
467 * @param $id Int User ID
468 * @return String|bool The corresponding username
470 public static function whoIs( $id ) {
471 $dbr = wfGetDB( DB_SLAVE
);
472 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), __METHOD__
);
476 * Get the real name of a user given their user ID
478 * @param $id Int User ID
479 * @return String|bool The corresponding user's real name
481 public static function whoIsReal( $id ) {
482 $dbr = wfGetDB( DB_SLAVE
);
483 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
487 * Get database id given a user name
488 * @param $name String Username
489 * @return Int|Null The corresponding user's ID, or null if user is nonexistent
491 public static function idFromName( $name ) {
492 $nt = Title
::makeTitleSafe( NS_USER
, $name );
493 if( is_null( $nt ) ) {
498 if ( isset( self
::$idCacheByName[$name] ) ) {
499 return self
::$idCacheByName[$name];
502 $dbr = wfGetDB( DB_SLAVE
);
503 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
505 if ( $s === false ) {
508 $result = $s->user_id
;
511 self
::$idCacheByName[$name] = $result;
513 if ( count( self
::$idCacheByName ) > 1000 ) {
514 self
::$idCacheByName = array();
521 * Reset the cache used in idFromName(). For use in tests.
523 public static function resetIdByNameCache() {
524 self
::$idCacheByName = array();
528 * Does the string match an anonymous IPv4 address?
530 * This function exists for username validation, in order to reject
531 * usernames which are similar in form to IP addresses. Strings such
532 * as 300.300.300.300 will return true because it looks like an IP
533 * address, despite not being strictly valid.
535 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
536 * address because the usemod software would "cloak" anonymous IP
537 * addresses like this, if we allowed accounts like this to be created
538 * new users could get the old edits of these anonymous users.
540 * @param $name String to match
543 public static function isIP( $name ) {
544 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP
::isIPv6($name);
548 * Is the input a valid username?
550 * Checks if the input is a valid username, we don't want an empty string,
551 * an IP address, anything that containins slashes (would mess up subpages),
552 * is longer than the maximum allowed username size or doesn't begin with
555 * @param $name String to match
558 public static function isValidUserName( $name ) {
559 global $wgContLang, $wgMaxNameChars;
562 || User
::isIP( $name )
563 ||
strpos( $name, '/' ) !== false
564 ||
strlen( $name ) > $wgMaxNameChars
565 ||
$name != $wgContLang->ucfirst( $name ) ) {
566 wfDebugLog( 'username', __METHOD__
.
567 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
572 // Ensure that the name can't be misresolved as a different title,
573 // such as with extra namespace keys at the start.
574 $parsed = Title
::newFromText( $name );
575 if( is_null( $parsed )
576 ||
$parsed->getNamespace()
577 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
578 wfDebugLog( 'username', __METHOD__
.
579 ": '$name' invalid due to ambiguous prefixes" );
583 // Check an additional blacklist of troublemaker characters.
584 // Should these be merged into the title char list?
585 $unicodeBlacklist = '/[' .
586 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
587 '\x{00a0}' . # non-breaking space
588 '\x{2000}-\x{200f}' . # various whitespace
589 '\x{2028}-\x{202f}' . # breaks and control chars
590 '\x{3000}' . # ideographic space
591 '\x{e000}-\x{f8ff}' . # private use
593 if( preg_match( $unicodeBlacklist, $name ) ) {
594 wfDebugLog( 'username', __METHOD__
.
595 ": '$name' invalid due to blacklisted characters" );
603 * Usernames which fail to pass this function will be blocked
604 * from user login and new account registrations, but may be used
605 * internally by batch processes.
607 * If an account already exists in this form, login will be blocked
608 * by a failure to pass this function.
610 * @param $name String to match
613 public static function isUsableName( $name ) {
614 global $wgReservedUsernames;
615 // Must be a valid username, obviously ;)
616 if ( !self
::isValidUserName( $name ) ) {
620 static $reservedUsernames = false;
621 if ( !$reservedUsernames ) {
622 $reservedUsernames = $wgReservedUsernames;
623 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
626 // Certain names may be reserved for batch processes.
627 foreach ( $reservedUsernames as $reserved ) {
628 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
629 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
631 if ( $reserved == $name ) {
639 * Usernames which fail to pass this function will be blocked
640 * from new account registrations, but may be used internally
641 * either by batch processes or by user accounts which have
642 * already been created.
644 * Additional blacklisting may be added here rather than in
645 * isValidUserName() to avoid disrupting existing accounts.
647 * @param $name String to match
650 public static function isCreatableName( $name ) {
651 global $wgInvalidUsernameCharacters;
653 // Ensure that the username isn't longer than 235 bytes, so that
654 // (at least for the builtin skins) user javascript and css files
655 // will work. (bug 23080)
656 if( strlen( $name ) > 235 ) {
657 wfDebugLog( 'username', __METHOD__
.
658 ": '$name' invalid due to length" );
662 // Preg yells if you try to give it an empty string
663 if( $wgInvalidUsernameCharacters !== '' ) {
664 if( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
665 wfDebugLog( 'username', __METHOD__
.
666 ": '$name' invalid due to wgInvalidUsernameCharacters" );
671 return self
::isUsableName( $name );
675 * Is the input a valid password for this user?
677 * @param $password String Desired password
680 public function isValidPassword( $password ) {
681 //simple boolean wrapper for getPasswordValidity
682 return $this->getPasswordValidity( $password ) === true;
686 * Given unvalidated password input, return error message on failure.
688 * @param $password String Desired password
689 * @return mixed: true on success, string or array of error message on failure
691 public function getPasswordValidity( $password ) {
692 global $wgMinimalPasswordLength, $wgContLang;
694 static $blockedLogins = array(
695 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
696 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
699 $result = false; //init $result to false for the internal checks
701 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
704 if ( $result === false ) {
705 if( strlen( $password ) < $wgMinimalPasswordLength ) {
706 return 'passwordtooshort';
707 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
708 return 'password-name-match';
709 } elseif ( isset( $blockedLogins[ $this->getName() ] ) && $password == $blockedLogins[ $this->getName() ] ) {
710 return 'password-login-forbidden';
712 //it seems weird returning true here, but this is because of the
713 //initialization of $result to false above. If the hook is never run or it
714 //doesn't modify $result, then we will likely get down into this if with
718 } elseif( $result === true ) {
721 return $result; //the isValidPassword hook set a string $result and returned true
726 * Does a string look like an e-mail address?
728 * This validates an email address using an HTML5 specification found at:
729 * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
730 * Which as of 2011-01-24 says:
732 * A valid e-mail address is a string that matches the ABNF production
733 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
734 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
737 * This function is an implementation of the specification as requested in
740 * Client-side forms will use the same standard validation rules via JS or
741 * HTML 5 validation; additional restrictions can be enforced server-side
742 * by extensions via the 'isValidEmailAddr' hook.
744 * Note that this validation doesn't 100% match RFC 2822, but is believed
745 * to be liberal enough for wide use. Some invalid addresses will still
746 * pass validation here.
748 * @param $addr String E-mail address
750 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
752 public static function isValidEmailAddr( $addr ) {
753 wfDeprecated( __METHOD__
, '1.18' );
754 return Sanitizer
::validateEmail( $addr );
758 * Given unvalidated user input, return a canonical username, or false if
759 * the username is invalid.
760 * @param $name String User input
761 * @param $validate String|Bool type of validation to use:
762 * - false No validation
763 * - 'valid' Valid for batch processes
764 * - 'usable' Valid for batch processes and login
765 * - 'creatable' Valid for batch processes, login and account creation
767 * @return bool|string
769 public static function getCanonicalName( $name, $validate = 'valid' ) {
770 # Force usernames to capital
772 $name = $wgContLang->ucfirst( $name );
774 # Reject names containing '#'; these will be cleaned up
775 # with title normalisation, but then it's too late to
777 if( strpos( $name, '#' ) !== false )
780 # Clean up name according to title rules
781 $t = ( $validate === 'valid' ) ?
782 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
783 # Check for invalid titles
784 if( is_null( $t ) ) {
788 # Reject various classes of invalid names
790 $name = $wgAuth->getCanonicalName( $t->getText() );
792 switch ( $validate ) {
796 if ( !User
::isValidUserName( $name ) ) {
801 if ( !User
::isUsableName( $name ) ) {
806 if ( !User
::isCreatableName( $name ) ) {
811 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
817 * Count the number of edits of a user
818 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
820 * @param $uid Int User ID to check
821 * @return Int the user's edit count
823 public static function edits( $uid ) {
824 wfProfileIn( __METHOD__
);
825 $dbr = wfGetDB( DB_SLAVE
);
826 // check if the user_editcount field has been initialized
827 $field = $dbr->selectField(
828 'user', 'user_editcount',
829 array( 'user_id' => $uid ),
833 if( $field === null ) { // it has not been initialized. do so.
834 $dbw = wfGetDB( DB_MASTER
);
835 $count = $dbr->selectField(
836 'revision', 'count(*)',
837 array( 'rev_user' => $uid ),
842 array( 'user_editcount' => $count ),
843 array( 'user_id' => $uid ),
849 wfProfileOut( __METHOD__
);
854 * Return a random password.
856 * @return String new random password
858 public static function randomPassword() {
859 global $wgMinimalPasswordLength;
860 // Decide the final password length based on our min password length, stopping at a minimum of 10 chars
861 $length = max( 10, $wgMinimalPasswordLength );
862 // Multiply by 1.25 to get the number of hex characters we need
863 $length = $length * 1.25;
864 // Generate random hex chars
865 $hex = MWCryptRand
::generateHex( $length );
866 // Convert from base 16 to base 32 to get a proper password like string
867 return wfBaseConvert( $hex, 16, 32 );
871 * Set cached properties to default.
873 * @note This no longer clears uncached lazy-initialised properties;
874 * the constructor does that instead.
876 * @param $name string
878 public function loadDefaults( $name = false ) {
879 wfProfileIn( __METHOD__
);
882 $this->mName
= $name;
883 $this->mRealName
= '';
884 $this->mPassword
= $this->mNewpassword
= '';
885 $this->mNewpassTime
= null;
887 $this->mOptionOverrides
= null;
888 $this->mOptionsLoaded
= false;
890 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
891 if( $loggedOut !== null ) {
892 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
894 $this->mTouched
= '0'; # Allow any pages to be cached
897 $this->mToken
= null; // Don't run cryptographic functions till we need a token
898 $this->mEmailAuthenticated
= null;
899 $this->mEmailToken
= '';
900 $this->mEmailTokenExpires
= null;
901 $this->mRegistration
= wfTimestamp( TS_MW
);
902 $this->mGroups
= array();
904 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
906 wfProfileOut( __METHOD__
);
910 * Return whether an item has been loaded.
912 * @param $item String: item to check. Current possibilities:
916 * @param $all String: 'all' to check if the whole object has been loaded
917 * or any other string to check if only the item is available (e.g.
921 public function isItemLoaded( $item, $all = 'all' ) {
922 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
923 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
927 * Set that an item has been loaded
929 * @param $item String
931 private function setItemLoaded( $item ) {
932 if ( is_array( $this->mLoadedItems
) ) {
933 $this->mLoadedItems
[$item] = true;
938 * Load user data from the session or login cookie. If there are no valid
939 * credentials, initialises the user as an anonymous user.
940 * @return Bool True if the user is logged in, false otherwise.
942 private function loadFromSession() {
943 global $wgExternalAuthType, $wgAutocreatePolicy;
946 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
947 if ( $result !== null ) {
951 if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
952 $extUser = ExternalUser
::newFromCookie();
954 # TODO: Automatically create the user here (or probably a bit
955 # lower down, in fact)
959 $request = $this->getRequest();
961 $cookieId = $request->getCookie( 'UserID' );
962 $sessId = $request->getSessionData( 'wsUserID' );
964 if ( $cookieId !== null ) {
965 $sId = intval( $cookieId );
966 if( $sessId !== null && $cookieId != $sessId ) {
967 $this->loadDefaults(); // Possible collision!
968 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
969 cookie user ID ($sId) don't match!" );
972 $request->setSessionData( 'wsUserID', $sId );
973 } elseif ( $sessId !== null && $sessId != 0 ) {
976 $this->loadDefaults();
980 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
981 $sName = $request->getSessionData( 'wsUserName' );
982 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
983 $sName = $request->getCookie( 'UserName' );
984 $request->setSessionData( 'wsUserName', $sName );
986 $this->loadDefaults();
990 $proposedUser = User
::newFromId( $sId );
991 if ( !$proposedUser->isLoggedIn() ) {
993 $this->loadDefaults();
997 global $wgBlockDisablesLogin;
998 if( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
999 # User blocked and we've disabled blocked user logins
1000 $this->loadDefaults();
1004 if ( $request->getSessionData( 'wsToken' ) ) {
1005 $passwordCorrect = $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' );
1007 } elseif ( $request->getCookie( 'Token' ) ) {
1008 $passwordCorrect = $proposedUser->getToken( false ) === $request->getCookie( 'Token' );
1011 # No session or persistent login cookie
1012 $this->loadDefaults();
1016 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1017 $this->loadFromUserObject( $proposedUser );
1018 $request->setSessionData( 'wsToken', $this->mToken
);
1019 wfDebug( "User: logged in from $from\n" );
1022 # Invalid credentials
1023 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1024 $this->loadDefaults();
1030 * Load user and user_group data from the database.
1031 * $this->mId must be set, this is how the user is identified.
1033 * @return Bool True if the user exists, false if the user is anonymous
1035 public function loadFromDatabase() {
1037 $this->mId
= intval( $this->mId
);
1039 /** Anonymous user */
1041 $this->loadDefaults();
1045 $dbr = wfGetDB( DB_MASTER
);
1046 $s = $dbr->selectRow( 'user', self
::selectFields(), array( 'user_id' => $this->mId
), __METHOD__
);
1048 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1050 if ( $s !== false ) {
1051 # Initialise user table data
1052 $this->loadFromRow( $s );
1053 $this->mGroups
= null; // deferred
1054 $this->getEditCount(); // revalidation for nulls
1059 $this->loadDefaults();
1065 * Initialize this object from a row from the user table.
1067 * @param $row Array Row from the user table to load.
1069 public function loadFromRow( $row ) {
1072 $this->mGroups
= null; // deferred
1074 if ( isset( $row->user_name
) ) {
1075 $this->mName
= $row->user_name
;
1076 $this->mFrom
= 'name';
1077 $this->setItemLoaded( 'name' );
1082 if ( isset( $row->user_real_name
) ) {
1083 $this->mRealName
= $row->user_real_name
;
1084 $this->setItemLoaded( 'realname' );
1089 if ( isset( $row->user_id
) ) {
1090 $this->mId
= intval( $row->user_id
);
1091 $this->mFrom
= 'id';
1092 $this->setItemLoaded( 'id' );
1097 if ( isset( $row->user_editcount
) ) {
1098 $this->mEditCount
= $row->user_editcount
;
1103 if ( isset( $row->user_password
) ) {
1104 $this->mPassword
= $row->user_password
;
1105 $this->mNewpassword
= $row->user_newpassword
;
1106 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1107 $this->mEmail
= $row->user_email
;
1108 if ( isset( $row->user_options
) ) {
1109 $this->decodeOptions( $row->user_options
);
1111 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1112 $this->mToken
= $row->user_token
;
1113 if ( $this->mToken
== '' ) {
1114 $this->mToken
= null;
1116 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1117 $this->mEmailToken
= $row->user_email_token
;
1118 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1119 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1125 $this->mLoadedItems
= true;
1130 * Load the data for this user object from another user object.
1134 protected function loadFromUserObject( $user ) {
1136 $user->loadGroups();
1137 $user->loadOptions();
1138 foreach ( self
::$mCacheVars as $var ) {
1139 $this->$var = $user->$var;
1144 * Load the groups from the database if they aren't already loaded.
1146 private function loadGroups() {
1147 if ( is_null( $this->mGroups
) ) {
1148 $dbr = wfGetDB( DB_MASTER
);
1149 $res = $dbr->select( 'user_groups',
1150 array( 'ug_group' ),
1151 array( 'ug_user' => $this->mId
),
1153 $this->mGroups
= array();
1154 foreach ( $res as $row ) {
1155 $this->mGroups
[] = $row->ug_group
;
1161 * Add the user to the group if he/she meets given criteria.
1163 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1164 * possible to remove manually via Special:UserRights. In such case it
1165 * will not be re-added automatically. The user will also not lose the
1166 * group if they no longer meet the criteria.
1168 * @param $event String key in $wgAutopromoteOnce (each one has groups/criteria)
1170 * @return array Array of groups the user has been promoted to.
1172 * @see $wgAutopromoteOnce
1174 public function addAutopromoteOnceGroups( $event ) {
1175 global $wgAutopromoteOnceLogInRC;
1177 $toPromote = array();
1178 if ( $this->getId() ) {
1179 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1180 if ( count( $toPromote ) ) {
1181 $oldGroups = $this->getGroups(); // previous groups
1182 foreach ( $toPromote as $group ) {
1183 $this->addGroup( $group );
1185 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1187 $log = new LogPage( 'rights', $wgAutopromoteOnceLogInRC /* in RC? */ );
1188 $log->addEntry( 'autopromote',
1189 $this->getUserPage(),
1191 // These group names are "list to texted"-ed in class LogPage.
1192 array( implode( ', ', $oldGroups ), implode( ', ', $newGroups ) )
1200 * Clear various cached data stored in this object.
1201 * @param $reloadFrom bool|String Reload user and user_groups table data from a
1202 * given source. May be "name", "id", "defaults", "session", or false for
1205 public function clearInstanceCache( $reloadFrom = false ) {
1206 $this->mNewtalk
= -1;
1207 $this->mDatePreference
= null;
1208 $this->mBlockedby
= -1; # Unset
1209 $this->mHash
= false;
1210 $this->mRights
= null;
1211 $this->mEffectiveGroups
= null;
1212 $this->mImplicitGroups
= null;
1213 $this->mOptions
= null;
1215 if ( $reloadFrom ) {
1216 $this->mLoadedItems
= array();
1217 $this->mFrom
= $reloadFrom;
1222 * Combine the language default options with any site-specific options
1223 * and add the default language variants.
1225 * @return Array of String options
1227 public static function getDefaultOptions() {
1228 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1230 $defOpt = $wgDefaultUserOptions;
1231 # default language setting
1232 $variant = $wgContLang->getDefaultVariant();
1233 $defOpt['variant'] = $variant;
1234 $defOpt['language'] = $variant;
1235 foreach( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1236 $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1238 $defOpt['skin'] = $wgDefaultSkin;
1240 // FIXME: Ideally we'd cache the results of this function so the hook is only run once,
1241 // but that breaks the parser tests because they rely on being able to change $wgContLang
1242 // mid-request and see that change reflected in the return value of this function.
1243 // Which is insane and would never happen during normal MW operation, but is also not
1244 // likely to get fixed unless and until we context-ify everything.
1245 // See also https://www.mediawiki.org/wiki/Special:Code/MediaWiki/101488#c25275
1246 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1252 * Get a given default option value.
1254 * @param $opt String Name of option to retrieve
1255 * @return String Default option value
1257 public static function getDefaultOption( $opt ) {
1258 $defOpts = self
::getDefaultOptions();
1259 if( isset( $defOpts[$opt] ) ) {
1260 return $defOpts[$opt];
1268 * Get blocking information
1269 * @param $bFromSlave Bool Whether to check the slave database first. To
1270 * improve performance, non-critical checks are done
1271 * against slaves. Check when actually saving should be
1272 * done against master.
1274 private function getBlockedStatus( $bFromSlave = true ) {
1275 global $wgProxyWhitelist, $wgUser;
1277 if ( -1 != $this->mBlockedby
) {
1281 wfProfileIn( __METHOD__
);
1282 wfDebug( __METHOD__
.": checking...\n" );
1284 // Initialize data...
1285 // Otherwise something ends up stomping on $this->mBlockedby when
1286 // things get lazy-loaded later, causing false positive block hits
1287 // due to -1 !== 0. Probably session-related... Nothing should be
1288 // overwriting mBlockedby, surely?
1291 # We only need to worry about passing the IP address to the Block generator if the
1292 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1293 # know which IP address they're actually coming from
1294 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1295 $ip = $this->getRequest()->getIP();
1301 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1304 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1305 && !in_array( $ip, $wgProxyWhitelist ) )
1308 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1310 $block->setBlocker( wfMsg( 'proxyblocker' ) );
1311 $block->mReason
= wfMsg( 'proxyblockreason' );
1312 $block->setTarget( $ip );
1313 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1315 $block->setBlocker( wfMsg( 'sorbs' ) );
1316 $block->mReason
= wfMsg( 'sorbsreason' );
1317 $block->setTarget( $ip );
1321 if ( $block instanceof Block
) {
1322 wfDebug( __METHOD__
. ": Found block.\n" );
1323 $this->mBlock
= $block;
1324 $this->mBlockedby
= $block->getByName();
1325 $this->mBlockreason
= $block->mReason
;
1326 $this->mHideName
= $block->mHideName
;
1327 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1329 $this->mBlockedby
= '';
1330 $this->mHideName
= 0;
1331 $this->mAllowUsertalk
= false;
1335 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1337 wfProfileOut( __METHOD__
);
1341 * Whether the given IP is in a DNS blacklist.
1343 * @param $ip String IP to check
1344 * @param $checkWhitelist Bool: whether to check the whitelist first
1345 * @return Bool True if blacklisted.
1347 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1348 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1349 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1351 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
1354 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
1357 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1358 return $this->inDnsBlacklist( $ip, $urls );
1362 * Whether the given IP is in a given DNS blacklist.
1364 * @param $ip String IP to check
1365 * @param $bases String|Array of Strings: URL of the DNS blacklist
1366 * @return Bool True if blacklisted.
1368 public function inDnsBlacklist( $ip, $bases ) {
1369 wfProfileIn( __METHOD__
);
1372 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1373 if( IP
::isIPv4( $ip ) ) {
1374 # Reverse IP, bug 21255
1375 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1377 foreach( (array)$bases as $base ) {
1379 # If we have an access key, use that too (ProjectHoneypot, etc.)
1380 if( is_array( $base ) ) {
1381 if( count( $base ) >= 2 ) {
1382 # Access key is 1, base URL is 0
1383 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1385 $host = "$ipReversed.{$base[0]}";
1388 $host = "$ipReversed.$base";
1392 $ipList = gethostbynamel( $host );
1395 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1399 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base.\n" );
1404 wfProfileOut( __METHOD__
);
1409 * Check if an IP address is in the local proxy list
1415 public static function isLocallyBlockedProxy( $ip ) {
1416 global $wgProxyList;
1418 if ( !$wgProxyList ) {
1421 wfProfileIn( __METHOD__
);
1423 if ( !is_array( $wgProxyList ) ) {
1424 # Load from the specified file
1425 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1428 if ( !is_array( $wgProxyList ) ) {
1430 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1432 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1433 # Old-style flipped proxy list
1438 wfProfileOut( __METHOD__
);
1443 * Is this user subject to rate limiting?
1445 * @return Bool True if rate limited
1447 public function isPingLimitable() {
1448 global $wgRateLimitsExcludedIPs;
1449 if( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1450 // No other good way currently to disable rate limits
1451 // for specific IPs. :P
1452 // But this is a crappy hack and should die.
1455 return !$this->isAllowed('noratelimit');
1459 * Primitive rate limits: enforce maximum actions per time period
1460 * to put a brake on flooding.
1462 * @note When using a shared cache like memcached, IP-address
1463 * last-hit counters will be shared across wikis.
1465 * @param $action String Action to enforce; 'edit' if unspecified
1466 * @return Bool True if a rate limiter was tripped
1468 public function pingLimiter( $action = 'edit' ) {
1469 # Call the 'PingLimiter' hook
1471 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1475 global $wgRateLimits;
1476 if( !isset( $wgRateLimits[$action] ) ) {
1480 # Some groups shouldn't trigger the ping limiter, ever
1481 if( !$this->isPingLimitable() )
1484 global $wgMemc, $wgRateLimitLog;
1485 wfProfileIn( __METHOD__
);
1487 $limits = $wgRateLimits[$action];
1489 $id = $this->getId();
1490 $ip = $this->getRequest()->getIP();
1493 if( isset( $limits['anon'] ) && $id == 0 ) {
1494 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1497 if( isset( $limits['user'] ) && $id != 0 ) {
1498 $userLimit = $limits['user'];
1500 if( $this->isNewbie() ) {
1501 if( isset( $limits['newbie'] ) && $id != 0 ) {
1502 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1504 if( isset( $limits['ip'] ) ) {
1505 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1508 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1509 $subnet = $matches[1];
1510 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1513 // Check for group-specific permissions
1514 // If more than one group applies, use the group with the highest limit
1515 foreach ( $this->getGroups() as $group ) {
1516 if ( isset( $limits[$group] ) ) {
1517 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1518 $userLimit = $limits[$group];
1522 // Set the user limit key
1523 if ( $userLimit !== false ) {
1524 wfDebug( __METHOD__
. ": effective user limit: $userLimit\n" );
1525 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1529 foreach( $keys as $key => $limit ) {
1530 list( $max, $period ) = $limit;
1531 $summary = "(limit $max in {$period}s)";
1532 $count = $wgMemc->get( $key );
1535 if( $count >= $max ) {
1536 wfDebug( __METHOD__
. ": tripped! $key at $count $summary\n" );
1537 if( $wgRateLimitLog ) {
1538 wfSuppressWarnings();
1539 file_put_contents( $wgRateLimitLog, wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", FILE_APPEND
);
1540 wfRestoreWarnings();
1544 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1547 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1548 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1550 $wgMemc->incr( $key );
1553 wfProfileOut( __METHOD__
);
1558 * Check if user is blocked
1560 * @param $bFromSlave Bool Whether to check the slave database instead of the master
1561 * @return Bool True if blocked, false otherwise
1563 public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1564 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1568 * Get the block affecting the user, or null if the user is not blocked
1570 * @param $bFromSlave Bool Whether to check the slave database instead of the master
1571 * @return Block|null
1573 public function getBlock( $bFromSlave = true ){
1574 $this->getBlockedStatus( $bFromSlave );
1575 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1579 * Check if user is blocked from editing a particular article
1581 * @param $title Title to check
1582 * @param $bFromSlave Bool whether to check the slave database instead of the master
1585 function isBlockedFrom( $title, $bFromSlave = false ) {
1586 global $wgBlockAllowsUTEdit;
1587 wfProfileIn( __METHOD__
);
1589 $blocked = $this->isBlocked( $bFromSlave );
1590 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1591 # If a user's name is suppressed, they cannot make edits anywhere
1592 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1593 $title->getNamespace() == NS_USER_TALK
) {
1595 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1598 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1600 wfProfileOut( __METHOD__
);
1605 * If user is blocked, return the name of the user who placed the block
1606 * @return String name of blocker
1608 public function blockedBy() {
1609 $this->getBlockedStatus();
1610 return $this->mBlockedby
;
1614 * If user is blocked, return the specified reason for the block
1615 * @return String Blocking reason
1617 public function blockedFor() {
1618 $this->getBlockedStatus();
1619 return $this->mBlockreason
;
1623 * If user is blocked, return the ID for the block
1624 * @return Int Block ID
1626 public function getBlockId() {
1627 $this->getBlockedStatus();
1628 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1632 * Check if user is blocked on all wikis.
1633 * Do not use for actual edit permission checks!
1634 * This is intented for quick UI checks.
1636 * @param $ip String IP address, uses current client if none given
1637 * @return Bool True if blocked, false otherwise
1639 public function isBlockedGlobally( $ip = '' ) {
1640 if( $this->mBlockedGlobally
!== null ) {
1641 return $this->mBlockedGlobally
;
1643 // User is already an IP?
1644 if( IP
::isIPAddress( $this->getName() ) ) {
1645 $ip = $this->getName();
1647 $ip = $this->getRequest()->getIP();
1650 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1651 $this->mBlockedGlobally
= (bool)$blocked;
1652 return $this->mBlockedGlobally
;
1656 * Check if user account is locked
1658 * @return Bool True if locked, false otherwise
1660 public function isLocked() {
1661 if( $this->mLocked
!== null ) {
1662 return $this->mLocked
;
1665 $authUser = $wgAuth->getUserInstance( $this );
1666 $this->mLocked
= (bool)$authUser->isLocked();
1667 return $this->mLocked
;
1671 * Check if user account is hidden
1673 * @return Bool True if hidden, false otherwise
1675 public function isHidden() {
1676 if( $this->mHideName
!== null ) {
1677 return $this->mHideName
;
1679 $this->getBlockedStatus();
1680 if( !$this->mHideName
) {
1682 $authUser = $wgAuth->getUserInstance( $this );
1683 $this->mHideName
= (bool)$authUser->isHidden();
1685 return $this->mHideName
;
1689 * Get the user's ID.
1690 * @return Int The user's ID; 0 if the user is anonymous or nonexistent
1692 public function getId() {
1693 if( $this->mId
=== null && $this->mName
!== null
1694 && User
::isIP( $this->mName
) ) {
1695 // Special case, we know the user is anonymous
1697 } elseif( !$this->isItemLoaded( 'id' ) ) {
1698 // Don't load if this was initialized from an ID
1705 * Set the user and reload all fields according to a given ID
1706 * @param $v Int User ID to reload
1708 public function setId( $v ) {
1710 $this->clearInstanceCache( 'id' );
1714 * Get the user name, or the IP of an anonymous user
1715 * @return String User's name or IP address
1717 public function getName() {
1718 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1719 # Special case optimisation
1720 return $this->mName
;
1723 if ( $this->mName
=== false ) {
1725 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1727 return $this->mName
;
1732 * Set the user name.
1734 * This does not reload fields from the database according to the given
1735 * name. Rather, it is used to create a temporary "nonexistent user" for
1736 * later addition to the database. It can also be used to set the IP
1737 * address for an anonymous user to something other than the current
1740 * @note User::newFromName() has rougly the same function, when the named user
1742 * @param $str String New user name to set
1744 public function setName( $str ) {
1746 $this->mName
= $str;
1750 * Get the user's name escaped by underscores.
1751 * @return String Username escaped by underscores.
1753 public function getTitleKey() {
1754 return str_replace( ' ', '_', $this->getName() );
1758 * Check if the user has new messages.
1759 * @return Bool True if the user has new messages
1761 public function getNewtalk() {
1764 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1765 if( $this->mNewtalk
=== -1 ) {
1766 $this->mNewtalk
= false; # reset talk page status
1768 # Check memcached separately for anons, who have no
1769 # entire User object stored in there.
1772 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1773 $newtalk = $wgMemc->get( $key );
1774 if( strval( $newtalk ) !== '' ) {
1775 $this->mNewtalk
= (bool)$newtalk;
1777 // Since we are caching this, make sure it is up to date by getting it
1779 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1780 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1783 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1787 return (bool)$this->mNewtalk
;
1791 * Return the talk page(s) this user has new messages on.
1792 * @return Array of String page URLs
1794 public function getNewMessageLinks() {
1796 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
1798 } elseif( !$this->getNewtalk() ) {
1801 $utp = $this->getTalkPage();
1802 $dbr = wfGetDB( DB_SLAVE
);
1803 // Get the "last viewed rev" timestamp from the oldest message notification
1804 $timestamp = $dbr->selectField( 'user_newtalk',
1805 'MIN(user_last_timestamp)',
1806 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
1808 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
1809 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
1813 * Internal uncached check for new messages
1816 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1817 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1818 * @param $fromMaster Bool true to fetch from the master, false for a slave
1819 * @return Bool True if the user has new messages
1821 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
1822 if ( $fromMaster ) {
1823 $db = wfGetDB( DB_MASTER
);
1825 $db = wfGetDB( DB_SLAVE
);
1827 $ok = $db->selectField( 'user_newtalk', $field,
1828 array( $field => $id ), __METHOD__
);
1829 return $ok !== false;
1833 * Add or update the new messages flag
1834 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1835 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1836 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null.
1837 * @return Bool True if successful, false otherwise
1839 protected function updateNewtalk( $field, $id, $curRev = null ) {
1840 // Get timestamp of the talk page revision prior to the current one
1841 $prevRev = $curRev ?
$curRev->getPrevious() : false;
1842 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
1843 // Mark the user as having new messages since this revision
1844 $dbw = wfGetDB( DB_MASTER
);
1845 $dbw->insert( 'user_newtalk',
1846 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
1849 if ( $dbw->affectedRows() ) {
1850 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
1853 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
1859 * Clear the new messages flag for the given user
1860 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1861 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1862 * @return Bool True if successful, false otherwise
1864 protected function deleteNewtalk( $field, $id ) {
1865 $dbw = wfGetDB( DB_MASTER
);
1866 $dbw->delete( 'user_newtalk',
1867 array( $field => $id ),
1869 if ( $dbw->affectedRows() ) {
1870 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
1873 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
1879 * Update the 'You have new messages!' status.
1880 * @param $val Bool Whether the user has new messages
1881 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null or !$val.
1883 public function setNewtalk( $val, $curRev = null ) {
1884 if( wfReadOnly() ) {
1889 $this->mNewtalk
= $val;
1891 if( $this->isAnon() ) {
1893 $id = $this->getName();
1896 $id = $this->getId();
1901 $changed = $this->updateNewtalk( $field, $id, $curRev );
1903 $changed = $this->deleteNewtalk( $field, $id );
1906 if( $this->isAnon() ) {
1907 // Anons have a separate memcached space, since
1908 // user records aren't kept for them.
1909 $key = wfMemcKey( 'newtalk', 'ip', $id );
1910 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1913 $this->invalidateCache();
1918 * Generate a current or new-future timestamp to be stored in the
1919 * user_touched field when we update things.
1920 * @return String Timestamp in TS_MW format
1922 private static function newTouchedTimestamp() {
1923 global $wgClockSkewFudge;
1924 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1928 * Clear user data from memcached.
1929 * Use after applying fun updates to the database; caller's
1930 * responsibility to update user_touched if appropriate.
1932 * Called implicitly from invalidateCache() and saveSettings().
1934 private function clearSharedCache() {
1938 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1943 * Immediately touch the user data cache for this account.
1944 * Updates user_touched field, and removes account data from memcached
1945 * for reload on the next hit.
1947 public function invalidateCache() {
1948 if( wfReadOnly() ) {
1953 $this->mTouched
= self
::newTouchedTimestamp();
1955 $dbw = wfGetDB( DB_MASTER
);
1957 // Prevent contention slams by checking user_touched first
1958 $now = $dbw->timestamp( $this->mTouched
);
1959 $needsPurge = $dbw->selectField( 'user', '1',
1960 array( 'user_id' => $this->mId
, 'user_touched < ' . $dbw->addQuotes( $now ) )
1962 if ( $needsPurge ) {
1963 $dbw->update( 'user',
1964 array( 'user_touched' => $now ),
1965 array( 'user_id' => $this->mId
, 'user_touched < ' . $dbw->addQuotes( $now ) ),
1970 $this->clearSharedCache();
1975 * Validate the cache for this account.
1976 * @param $timestamp String A timestamp in TS_MW format
1980 public function validateCache( $timestamp ) {
1982 return ( $timestamp >= $this->mTouched
);
1986 * Get the user touched timestamp
1987 * @return String timestamp
1989 public function getTouched() {
1991 return $this->mTouched
;
1995 * Set the password and reset the random token.
1996 * Calls through to authentication plugin if necessary;
1997 * will have no effect if the auth plugin refuses to
1998 * pass the change through or if the legal password
2001 * As a special case, setting the password to null
2002 * wipes it, so the account cannot be logged in until
2003 * a new password is set, for instance via e-mail.
2005 * @param $str String New password to set
2006 * @throws PasswordError on failure
2010 public function setPassword( $str ) {
2013 if( $str !== null ) {
2014 if( !$wgAuth->allowPasswordChange() ) {
2015 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
2018 if( !$this->isValidPassword( $str ) ) {
2019 global $wgMinimalPasswordLength;
2020 $valid = $this->getPasswordValidity( $str );
2021 if ( is_array( $valid ) ) {
2022 $message = array_shift( $valid );
2026 $params = array( $wgMinimalPasswordLength );
2028 throw new PasswordError( wfMsgExt( $message, array( 'parsemag' ), $params ) );
2032 if( !$wgAuth->setPassword( $this, $str ) ) {
2033 throw new PasswordError( wfMsg( 'externaldberror' ) );
2036 $this->setInternalPassword( $str );
2042 * Set the password and reset the random token unconditionally.
2044 * @param $str String New password to set
2046 public function setInternalPassword( $str ) {
2050 if( $str === null ) {
2051 // Save an invalid hash...
2052 $this->mPassword
= '';
2054 $this->mPassword
= self
::crypt( $str );
2056 $this->mNewpassword
= '';
2057 $this->mNewpassTime
= null;
2061 * Get the user's current token.
2062 * @param $forceCreation Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility)
2063 * @return String Token
2065 public function getToken( $forceCreation = true ) {
2067 if ( !$this->mToken
&& $forceCreation ) {
2070 return $this->mToken
;
2074 * Set the random token (used for persistent authentication)
2075 * Called from loadDefaults() among other places.
2077 * @param $token String|bool If specified, set the token to this value
2079 public function setToken( $token = false ) {
2082 $this->mToken
= MWCryptRand
::generateHex( USER_TOKEN_LENGTH
);
2084 $this->mToken
= $token;
2089 * Set the password for a password reminder or new account email
2091 * @param $str String New password to set
2092 * @param $throttle Bool If true, reset the throttle timestamp to the present
2094 public function setNewpassword( $str, $throttle = true ) {
2096 $this->mNewpassword
= self
::crypt( $str );
2098 $this->mNewpassTime
= wfTimestampNow();
2103 * Has password reminder email been sent within the last
2104 * $wgPasswordReminderResendTime hours?
2107 public function isPasswordReminderThrottled() {
2108 global $wgPasswordReminderResendTime;
2110 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2113 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2114 return time() < $expiry;
2118 * Get the user's e-mail address
2119 * @return String User's email address
2121 public function getEmail() {
2123 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
2124 return $this->mEmail
;
2128 * Get the timestamp of the user's e-mail authentication
2129 * @return String TS_MW timestamp
2131 public function getEmailAuthenticationTimestamp() {
2133 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2134 return $this->mEmailAuthenticated
;
2138 * Set the user's e-mail address
2139 * @param $str String New e-mail address
2141 public function setEmail( $str ) {
2143 if( $str == $this->mEmail
) {
2146 $this->mEmail
= $str;
2147 $this->invalidateEmail();
2148 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
2152 * Set the user's e-mail address and a confirmation mail if needed.
2155 * @param $str String New e-mail address
2158 public function setEmailWithConfirmation( $str ) {
2159 global $wgEnableEmail, $wgEmailAuthentication;
2161 if ( !$wgEnableEmail ) {
2162 return Status
::newFatal( 'emaildisabled' );
2165 $oldaddr = $this->getEmail();
2166 if ( $str === $oldaddr ) {
2167 return Status
::newGood( true );
2170 $this->setEmail( $str );
2172 if ( $str !== '' && $wgEmailAuthentication ) {
2173 # Send a confirmation request to the new address if needed
2174 $type = $oldaddr != '' ?
'changed' : 'set';
2175 $result = $this->sendConfirmationMail( $type );
2176 if ( $result->isGood() ) {
2177 # Say the the caller that a confirmation mail has been sent
2178 $result->value
= 'eauth';
2181 $result = Status
::newGood( true );
2188 * Get the user's real name
2189 * @return String User's real name
2191 public function getRealName() {
2192 if ( !$this->isItemLoaded( 'realname' ) ) {
2196 return $this->mRealName
;
2200 * Set the user's real name
2201 * @param $str String New real name
2203 public function setRealName( $str ) {
2205 $this->mRealName
= $str;
2209 * Get the user's current setting for a given option.
2211 * @param $oname String The option to check
2212 * @param $defaultOverride String A default value returned if the option does not exist
2213 * @param $ignoreHidden Bool = whether to ignore the effects of $wgHiddenPrefs
2214 * @return String User's current value for the option
2215 * @see getBoolOption()
2216 * @see getIntOption()
2218 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2219 global $wgHiddenPrefs;
2220 $this->loadOptions();
2222 if ( is_null( $this->mOptions
) ) {
2223 if($defaultOverride != '') {
2224 return $defaultOverride;
2226 $this->mOptions
= User
::getDefaultOptions();
2229 # We want 'disabled' preferences to always behave as the default value for
2230 # users, even if they have set the option explicitly in their settings (ie they
2231 # set it, and then it was disabled removing their ability to change it). But
2232 # we don't want to erase the preferences in the database in case the preference
2233 # is re-enabled again. So don't touch $mOptions, just override the returned value
2234 if( in_array( $oname, $wgHiddenPrefs ) && !$ignoreHidden ){
2235 return self
::getDefaultOption( $oname );
2238 if ( array_key_exists( $oname, $this->mOptions
) ) {
2239 return $this->mOptions
[$oname];
2241 return $defaultOverride;
2246 * Get all user's options
2250 public function getOptions() {
2251 global $wgHiddenPrefs;
2252 $this->loadOptions();
2253 $options = $this->mOptions
;
2255 # We want 'disabled' preferences to always behave as the default value for
2256 # users, even if they have set the option explicitly in their settings (ie they
2257 # set it, and then it was disabled removing their ability to change it). But
2258 # we don't want to erase the preferences in the database in case the preference
2259 # is re-enabled again. So don't touch $mOptions, just override the returned value
2260 foreach( $wgHiddenPrefs as $pref ){
2261 $default = self
::getDefaultOption( $pref );
2262 if( $default !== null ){
2263 $options[$pref] = $default;
2271 * Get the user's current setting for a given option, as a boolean value.
2273 * @param $oname String The option to check
2274 * @return Bool User's current value for the option
2277 public function getBoolOption( $oname ) {
2278 return (bool)$this->getOption( $oname );
2282 * Get the user's current setting for a given option, as a boolean value.
2284 * @param $oname String The option to check
2285 * @param $defaultOverride Int A default value returned if the option does not exist
2286 * @return Int User's current value for the option
2289 public function getIntOption( $oname, $defaultOverride=0 ) {
2290 $val = $this->getOption( $oname );
2292 $val = $defaultOverride;
2294 return intval( $val );
2298 * Set the given option for a user.
2300 * @param $oname String The option to set
2301 * @param $val mixed New value to set
2303 public function setOption( $oname, $val ) {
2305 $this->loadOptions();
2307 // Explicitly NULL values should refer to defaults
2308 if( is_null( $val ) ) {
2309 $defaultOption = self
::getDefaultOption( $oname );
2310 if( !is_null( $defaultOption ) ) {
2311 $val = $defaultOption;
2315 $this->mOptions
[$oname] = $val;
2319 * Reset all options to the site defaults
2321 public function resetOptions() {
2324 $this->mOptions
= self
::getDefaultOptions();
2325 $this->mOptionsLoaded
= true;
2329 * Get the user's preferred date format.
2330 * @return String User's preferred date format
2332 public function getDatePreference() {
2333 // Important migration for old data rows
2334 if ( is_null( $this->mDatePreference
) ) {
2336 $value = $this->getOption( 'date' );
2337 $map = $wgLang->getDatePreferenceMigrationMap();
2338 if ( isset( $map[$value] ) ) {
2339 $value = $map[$value];
2341 $this->mDatePreference
= $value;
2343 return $this->mDatePreference
;
2347 * Get the user preferred stub threshold
2351 public function getStubThreshold() {
2352 global $wgMaxArticleSize; # Maximum article size, in Kb
2353 $threshold = intval( $this->getOption( 'stubthreshold' ) );
2354 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2355 # If they have set an impossible value, disable the preference
2356 # so we can use the parser cache again.
2363 * Get the permissions this user has.
2364 * @return Array of String permission names
2366 public function getRights() {
2367 if ( is_null( $this->mRights
) ) {
2368 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2369 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2370 // Force reindexation of rights when a hook has unset one of them
2371 $this->mRights
= array_values( $this->mRights
);
2373 return $this->mRights
;
2377 * Get the list of explicit group memberships this user has.
2378 * The implicit * and user groups are not included.
2379 * @return Array of String internal group names
2381 public function getGroups() {
2383 $this->loadGroups();
2384 return $this->mGroups
;
2388 * Get the list of implicit group memberships this user has.
2389 * This includes all explicit groups, plus 'user' if logged in,
2390 * '*' for all accounts, and autopromoted groups
2391 * @param $recache Bool Whether to avoid the cache
2392 * @return Array of String internal group names
2394 public function getEffectiveGroups( $recache = false ) {
2395 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2396 wfProfileIn( __METHOD__
);
2397 $this->mEffectiveGroups
= array_unique( array_merge(
2398 $this->getGroups(), // explicit groups
2399 $this->getAutomaticGroups( $recache ) // implicit groups
2401 # Hook for additional groups
2402 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2403 wfProfileOut( __METHOD__
);
2405 return $this->mEffectiveGroups
;
2409 * Get the list of implicit group memberships this user has.
2410 * This includes 'user' if logged in, '*' for all accounts,
2411 * and autopromoted groups
2412 * @param $recache Bool Whether to avoid the cache
2413 * @return Array of String internal group names
2415 public function getAutomaticGroups( $recache = false ) {
2416 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
2417 wfProfileIn( __METHOD__
);
2418 $this->mImplicitGroups
= array( '*' );
2419 if ( $this->getId() ) {
2420 $this->mImplicitGroups
[] = 'user';
2422 $this->mImplicitGroups
= array_unique( array_merge(
2423 $this->mImplicitGroups
,
2424 Autopromote
::getAutopromoteGroups( $this )
2428 # Assure data consistency with rights/groups,
2429 # as getEffectiveGroups() depends on this function
2430 $this->mEffectiveGroups
= null;
2432 wfProfileOut( __METHOD__
);
2434 return $this->mImplicitGroups
;
2438 * Returns the groups the user has belonged to.
2440 * The user may still belong to the returned groups. Compare with getGroups().
2442 * The function will not return groups the user had belonged to before MW 1.17
2444 * @return array Names of the groups the user has belonged to.
2446 public function getFormerGroups() {
2447 if( is_null( $this->mFormerGroups
) ) {
2448 $dbr = wfGetDB( DB_MASTER
);
2449 $res = $dbr->select( 'user_former_groups',
2450 array( 'ufg_group' ),
2451 array( 'ufg_user' => $this->mId
),
2453 $this->mFormerGroups
= array();
2454 foreach( $res as $row ) {
2455 $this->mFormerGroups
[] = $row->ufg_group
;
2458 return $this->mFormerGroups
;
2462 * Get the user's edit count.
2465 public function getEditCount() {
2466 if( $this->getId() ) {
2467 if ( !isset( $this->mEditCount
) ) {
2468 /* Populate the count, if it has not been populated yet */
2469 $this->mEditCount
= User
::edits( $this->mId
);
2471 return $this->mEditCount
;
2479 * Add the user to the given group.
2480 * This takes immediate effect.
2481 * @param $group String Name of the group to add
2483 public function addGroup( $group ) {
2484 if( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2485 $dbw = wfGetDB( DB_MASTER
);
2486 if( $this->getId() ) {
2487 $dbw->insert( 'user_groups',
2489 'ug_user' => $this->getID(),
2490 'ug_group' => $group,
2493 array( 'IGNORE' ) );
2496 $this->loadGroups();
2497 $this->mGroups
[] = $group;
2498 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2500 $this->invalidateCache();
2504 * Remove the user from the given group.
2505 * This takes immediate effect.
2506 * @param $group String Name of the group to remove
2508 public function removeGroup( $group ) {
2510 if( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2511 $dbw = wfGetDB( DB_MASTER
);
2512 $dbw->delete( 'user_groups',
2514 'ug_user' => $this->getID(),
2515 'ug_group' => $group,
2517 // Remember that the user was in this group
2518 $dbw->insert( 'user_former_groups',
2520 'ufg_user' => $this->getID(),
2521 'ufg_group' => $group,
2524 array( 'IGNORE' ) );
2526 $this->loadGroups();
2527 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2528 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2530 $this->invalidateCache();
2534 * Get whether the user is logged in
2537 public function isLoggedIn() {
2538 return $this->getID() != 0;
2542 * Get whether the user is anonymous
2545 public function isAnon() {
2546 return !$this->isLoggedIn();
2550 * Check if user is allowed to access a feature / make an action
2552 * @internal param \String $varargs permissions to test
2553 * @return Boolean: True if user is allowed to perform *any* of the given actions
2557 public function isAllowedAny( /*...*/ ){
2558 $permissions = func_get_args();
2559 foreach( $permissions as $permission ){
2560 if( $this->isAllowed( $permission ) ){
2569 * @internal param $varargs string
2570 * @return bool True if the user is allowed to perform *all* of the given actions
2572 public function isAllowedAll( /*...*/ ){
2573 $permissions = func_get_args();
2574 foreach( $permissions as $permission ){
2575 if( !$this->isAllowed( $permission ) ){
2583 * Internal mechanics of testing a permission
2584 * @param $action String
2587 public function isAllowed( $action = '' ) {
2588 if ( $action === '' ) {
2589 return true; // In the spirit of DWIM
2591 # Patrolling may not be enabled
2592 if( $action === 'patrol' ||
$action === 'autopatrol' ) {
2593 global $wgUseRCPatrol, $wgUseNPPatrol;
2594 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2597 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2598 # by misconfiguration: 0 == 'foo'
2599 return in_array( $action, $this->getRights(), true );
2603 * Check whether to enable recent changes patrol features for this user
2604 * @return Boolean: True or false
2606 public function useRCPatrol() {
2607 global $wgUseRCPatrol;
2608 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
2612 * Check whether to enable new pages patrol features for this user
2613 * @return Bool True or false
2615 public function useNPPatrol() {
2616 global $wgUseRCPatrol, $wgUseNPPatrol;
2617 return( ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) ) );
2621 * Get the WebRequest object to use with this object
2623 * @return WebRequest
2625 public function getRequest() {
2626 if ( $this->mRequest
) {
2627 return $this->mRequest
;
2635 * Get the current skin, loading it if required
2636 * @return Skin The current skin
2637 * @todo FIXME: Need to check the old failback system [AV]
2638 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
2640 public function getSkin() {
2641 wfDeprecated( __METHOD__
, '1.18' );
2642 return RequestContext
::getMain()->getSkin();
2646 * Get a WatchedItem for this user and $title.
2648 * @param $title Title
2649 * @return WatchedItem
2651 public function getWatchedItem( $title ) {
2652 $key = $title->getNamespace() . ':' . $title->getDBkey();
2654 if ( isset( $this->mWatchedItems
[$key] ) ) {
2655 return $this->mWatchedItems
[$key];
2658 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
2659 $this->mWatchedItems
= array();
2662 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title );
2663 return $this->mWatchedItems
[$key];
2667 * Check the watched status of an article.
2668 * @param $title Title of the article to look at
2671 public function isWatched( $title ) {
2672 return $this->getWatchedItem( $title )->isWatched();
2677 * @param $title Title of the article to look at
2679 public function addWatch( $title ) {
2680 $this->getWatchedItem( $title )->addWatch();
2681 $this->invalidateCache();
2685 * Stop watching an article.
2686 * @param $title Title of the article to look at
2688 public function removeWatch( $title ) {
2689 $this->getWatchedItem( $title )->removeWatch();
2690 $this->invalidateCache();
2694 * Clear the user's notification timestamp for the given title.
2695 * If e-notif e-mails are on, they will receive notification mails on
2696 * the next change of the page if it's watched etc.
2697 * @param $title Title of the article to look at
2699 public function clearNotification( &$title ) {
2700 global $wgUseEnotif, $wgShowUpdatedMarker;
2702 # Do nothing if the database is locked to writes
2703 if( wfReadOnly() ) {
2707 if( $title->getNamespace() == NS_USER_TALK
&&
2708 $title->getText() == $this->getName() ) {
2709 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2711 $this->setNewtalk( false );
2714 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2718 if( $this->isAnon() ) {
2719 // Nothing else to do...
2723 // Only update the timestamp if the page is being watched.
2724 // The query to find out if it is watched is cached both in memcached and per-invocation,
2725 // and when it does have to be executed, it can be on a slave
2726 // If this is the user's newtalk page, we always update the timestamp
2728 if ( $title->getNamespace() == NS_USER_TALK
&&
2729 $title->getText() == $this->getName() )
2734 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force );
2738 * Resets all of the given user's page-change notification timestamps.
2739 * If e-notif e-mails are on, they will receive notification mails on
2740 * the next change of any watched page.
2742 public function clearAllNotifications() {
2743 global $wgUseEnotif, $wgShowUpdatedMarker;
2744 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2745 $this->setNewtalk( false );
2748 $id = $this->getId();
2750 $dbw = wfGetDB( DB_MASTER
);
2751 $dbw->update( 'watchlist',
2753 'wl_notificationtimestamp' => null
2754 ), array( /* WHERE */
2758 # We also need to clear here the "you have new message" notification for the own user_talk page
2759 # This is cleared one page view later in Article::viewUpdates();
2764 * Set this user's options from an encoded string
2765 * @param $str String Encoded options to import
2767 * @deprecated in 1.19 due to removal of user_options from the user table
2769 private function decodeOptions( $str ) {
2770 wfDeprecated( __METHOD__
, '1.19' );
2774 $this->mOptionsLoaded
= true;
2775 $this->mOptionOverrides
= array();
2777 // If an option is not set in $str, use the default value
2778 $this->mOptions
= self
::getDefaultOptions();
2780 $a = explode( "\n", $str );
2781 foreach ( $a as $s ) {
2783 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2784 $this->mOptions
[$m[1]] = $m[2];
2785 $this->mOptionOverrides
[$m[1]] = $m[2];
2791 * Set a cookie on the user's client. Wrapper for
2792 * WebResponse::setCookie
2793 * @param $name String Name of the cookie to set
2794 * @param $value String Value to set
2795 * @param $exp Int Expiration time, as a UNIX time value;
2796 * if 0 or not specified, use the default $wgCookieExpiration
2798 protected function setCookie( $name, $value, $exp = 0 ) {
2799 $this->getRequest()->response()->setcookie( $name, $value, $exp );
2803 * Clear a cookie on the user's client
2804 * @param $name String Name of the cookie to clear
2806 protected function clearCookie( $name ) {
2807 $this->setCookie( $name, '', time() - 86400 );
2811 * Set the default cookies for this session on the user's client.
2813 * @param $request WebRequest object to use; $wgRequest will be used if null
2816 public function setCookies( $request = null ) {
2817 if ( $request === null ) {
2818 $request = $this->getRequest();
2822 if ( 0 == $this->mId
) return;
2823 if ( !$this->mToken
) {
2824 // When token is empty or NULL generate a new one and then save it to the database
2825 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
2826 // Simply by setting every cell in the user_token column to NULL and letting them be
2827 // regenerated as users log back into the wiki.
2829 $this->saveSettings();
2832 'wsUserID' => $this->mId
,
2833 'wsToken' => $this->mToken
,
2834 'wsUserName' => $this->getName()
2837 'UserID' => $this->mId
,
2838 'UserName' => $this->getName(),
2840 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2841 $cookies['Token'] = $this->mToken
;
2843 $cookies['Token'] = false;
2846 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2848 foreach ( $session as $name => $value ) {
2849 $request->setSessionData( $name, $value );
2851 foreach ( $cookies as $name => $value ) {
2852 if ( $value === false ) {
2853 $this->clearCookie( $name );
2855 $this->setCookie( $name, $value );
2861 * Log this user out.
2863 public function logout() {
2864 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
2870 * Clear the user's cookies and session, and reset the instance cache.
2873 public function doLogout() {
2874 $this->clearInstanceCache( 'defaults' );
2876 $this->getRequest()->setSessionData( 'wsUserID', 0 );
2878 $this->clearCookie( 'UserID' );
2879 $this->clearCookie( 'Token' );
2881 # Remember when user logged out, to prevent seeing cached pages
2882 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2886 * Save this user's settings into the database.
2887 * @todo Only rarely do all these fields need to be set!
2889 public function saveSettings() {
2891 if ( wfReadOnly() ) { return; }
2892 if ( 0 == $this->mId
) { return; }
2894 $this->mTouched
= self
::newTouchedTimestamp();
2896 $dbw = wfGetDB( DB_MASTER
);
2897 $dbw->update( 'user',
2899 'user_name' => $this->mName
,
2900 'user_password' => $this->mPassword
,
2901 'user_newpassword' => $this->mNewpassword
,
2902 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2903 'user_real_name' => $this->mRealName
,
2904 'user_email' => $this->mEmail
,
2905 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2906 'user_touched' => $dbw->timestamp( $this->mTouched
),
2907 'user_token' => strval( $this->mToken
),
2908 'user_email_token' => $this->mEmailToken
,
2909 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2910 ), array( /* WHERE */
2911 'user_id' => $this->mId
2915 $this->saveOptions();
2917 wfRunHooks( 'UserSaveSettings', array( $this ) );
2918 $this->clearSharedCache();
2919 $this->getUserPage()->invalidateCache();
2923 * If only this user's username is known, and it exists, return the user ID.
2926 public function idForName() {
2927 $s = trim( $this->getName() );
2928 if ( $s === '' ) return 0;
2930 $dbr = wfGetDB( DB_SLAVE
);
2931 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2932 if ( $id === false ) {
2939 * Add a user to the database, return the user object
2941 * @param $name String Username to add
2942 * @param $params Array of Strings Non-default parameters to save to the database as user_* fields:
2943 * - password The user's password hash. Password logins will be disabled if this is omitted.
2944 * - newpassword Hash for a temporary password that has been mailed to the user
2945 * - email The user's email address
2946 * - email_authenticated The email authentication timestamp
2947 * - real_name The user's real name
2948 * - options An associative array of non-default options
2949 * - token Random authentication token. Do not set.
2950 * - registration Registration timestamp. Do not set.
2952 * @return User object, or null if the username already exists
2954 public static function createNew( $name, $params = array() ) {
2957 if ( isset( $params['options'] ) ) {
2958 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
2959 unset( $params['options'] );
2961 $dbw = wfGetDB( DB_MASTER
);
2962 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2965 'user_id' => $seqVal,
2966 'user_name' => $name,
2967 'user_password' => $user->mPassword
,
2968 'user_newpassword' => $user->mNewpassword
,
2969 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
2970 'user_email' => $user->mEmail
,
2971 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2972 'user_real_name' => $user->mRealName
,
2973 'user_token' => strval( $user->mToken
),
2974 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2975 'user_editcount' => 0,
2976 'user_touched' => $dbw->timestamp( self
::newTouchedTimestamp() ),
2978 foreach ( $params as $name => $value ) {
2979 $fields["user_$name"] = $value;
2981 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2982 if ( $dbw->affectedRows() ) {
2983 $newUser = User
::newFromId( $dbw->insertId() );
2991 * Add this existing user object to the database
2993 public function addToDatabase() {
2996 $this->mTouched
= self
::newTouchedTimestamp();
2998 $dbw = wfGetDB( DB_MASTER
);
2999 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3000 $dbw->insert( 'user',
3002 'user_id' => $seqVal,
3003 'user_name' => $this->mName
,
3004 'user_password' => $this->mPassword
,
3005 'user_newpassword' => $this->mNewpassword
,
3006 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3007 'user_email' => $this->mEmail
,
3008 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3009 'user_real_name' => $this->mRealName
,
3010 'user_token' => strval( $this->mToken
),
3011 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3012 'user_editcount' => 0,
3013 'user_touched' => $dbw->timestamp( $this->mTouched
),
3016 $this->mId
= $dbw->insertId();
3018 // Clear instance cache other than user table data, which is already accurate
3019 $this->clearInstanceCache();
3021 $this->saveOptions();
3025 * If this user is logged-in and blocked,
3026 * block any IP address they've successfully logged in from.
3027 * @return bool A block was spread
3029 public function spreadAnyEditBlock() {
3030 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3031 return $this->spreadBlock();
3037 * If this (non-anonymous) user is blocked,
3038 * block the IP address they've successfully logged in from.
3039 * @return bool A block was spread
3041 protected function spreadBlock() {
3042 wfDebug( __METHOD__
. "()\n" );
3044 if ( $this->mId
== 0 ) {
3048 $userblock = Block
::newFromTarget( $this->getName() );
3049 if ( !$userblock ) {
3053 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3057 * Generate a string which will be different for any combination of
3058 * user options which would produce different parser output.
3059 * This will be used as part of the hash key for the parser cache,
3060 * so users with the same options can share the same cached data
3063 * Extensions which require it should install 'PageRenderingHash' hook,
3064 * which will give them a chance to modify this key based on their own
3067 * @deprecated since 1.17 use the ParserOptions object to get the relevant options
3068 * @return String Page rendering hash
3070 public function getPageRenderingHash() {
3071 wfDeprecated( __METHOD__
, '1.17' );
3073 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
3075 return $this->mHash
;
3078 // stubthreshold is only included below for completeness,
3079 // since it disables the parser cache, its value will always
3080 // be 0 when this function is called by parsercache.
3082 $confstr = $this->getOption( 'math' );
3083 $confstr .= '!' . $this->getStubThreshold();
3084 if ( $wgUseDynamicDates ) { # This is wrong (bug 24714)
3085 $confstr .= '!' . $this->getDatePreference();
3087 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ?
'1' : '' );
3088 $confstr .= '!' . $wgLang->getCode();
3089 $confstr .= '!' . $this->getOption( 'thumbsize' );
3090 // add in language specific options, if any
3091 $extra = $wgContLang->getExtraHashOptions();
3094 // Since the skin could be overloading link(), it should be
3095 // included here but in practice, none of our skins do that.
3097 $confstr .= $wgRenderHashAppend;
3099 // Give a chance for extensions to modify the hash, if they have
3100 // extra options or other effects on the parser cache.
3101 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
3103 // Make it a valid memcached key fragment
3104 $confstr = str_replace( ' ', '_', $confstr );
3105 $this->mHash
= $confstr;
3110 * Get whether the user is explicitly blocked from account creation.
3111 * @return Bool|Block
3113 public function isBlockedFromCreateAccount() {
3114 $this->getBlockedStatus();
3115 if( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ){
3116 return $this->mBlock
;
3119 # bug 13611: if the IP address the user is trying to create an account from is
3120 # blocked with createaccount disabled, prevent new account creation there even
3121 # when the user is logged in
3122 if( $this->mBlockedFromCreateAccount
=== false ){
3123 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3125 return $this->mBlockedFromCreateAccount
instanceof Block
&& $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3126 ?
$this->mBlockedFromCreateAccount
3131 * Get whether the user is blocked from using Special:Emailuser.
3134 public function isBlockedFromEmailuser() {
3135 $this->getBlockedStatus();
3136 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3140 * Get whether the user is allowed to create an account.
3143 function isAllowedToCreateAccount() {
3144 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3148 * Get this user's personal page title.
3150 * @return Title: User's personal page title
3152 public function getUserPage() {
3153 return Title
::makeTitle( NS_USER
, $this->getName() );
3157 * Get this user's talk page title.
3159 * @return Title: User's talk page title
3161 public function getTalkPage() {
3162 $title = $this->getUserPage();
3163 return $title->getTalkPage();
3167 * Determine whether the user is a newbie. Newbies are either
3168 * anonymous IPs, or the most recently created accounts.
3171 public function isNewbie() {
3172 return !$this->isAllowed( 'autoconfirmed' );
3176 * Check to see if the given clear-text password is one of the accepted passwords
3177 * @param $password String: user password.
3178 * @return Boolean: True if the given password is correct, otherwise False.
3180 public function checkPassword( $password ) {
3181 global $wgAuth, $wgLegacyEncoding;
3184 // Even though we stop people from creating passwords that
3185 // are shorter than this, doesn't mean people wont be able
3186 // to. Certain authentication plugins do NOT want to save
3187 // domain passwords in a mysql database, so we should
3188 // check this (in case $wgAuth->strict() is false).
3189 if( !$this->isValidPassword( $password ) ) {
3193 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
3195 } elseif( $wgAuth->strict() ) {
3196 /* Auth plugin doesn't allow local authentication */
3198 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
3199 /* Auth plugin doesn't allow local authentication for this user name */
3202 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
3204 } elseif ( $wgLegacyEncoding ) {
3205 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3206 # Check for this with iconv
3207 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3208 if ( $cp1252Password != $password &&
3209 self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) )
3218 * Check if the given clear-text password matches the temporary password
3219 * sent by e-mail for password reset operations.
3221 * @param $plaintext string
3223 * @return Boolean: True if matches, false otherwise
3225 public function checkTemporaryPassword( $plaintext ) {
3226 global $wgNewPasswordExpiry;
3229 if( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
3230 if ( is_null( $this->mNewpassTime
) ) {
3233 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3234 return ( time() < $expiry );
3241 * Alias for getEditToken.
3242 * @deprecated since 1.19, use getEditToken instead.
3244 * @param $salt String|Array of Strings Optional function-specific data for hashing
3245 * @param $request WebRequest object to use or null to use $wgRequest
3246 * @return String The new edit token
3248 public function editToken( $salt = '', $request = null ) {
3249 wfDeprecated( __METHOD__
, '1.19' );
3250 return $this->getEditToken( $salt, $request );
3254 * Initialize (if necessary) and return a session token value
3255 * which can be used in edit forms to show that the user's
3256 * login credentials aren't being hijacked with a foreign form
3261 * @param $salt String|Array of Strings Optional function-specific data for hashing
3262 * @param $request WebRequest object to use or null to use $wgRequest
3263 * @return String The new edit token
3265 public function getEditToken( $salt = '', $request = null ) {
3266 if ( $request == null ) {
3267 $request = $this->getRequest();
3270 if ( $this->isAnon() ) {
3271 return EDIT_TOKEN_SUFFIX
;
3273 $token = $request->getSessionData( 'wsEditToken' );
3274 if ( $token === null ) {
3275 $token = MWCryptRand
::generateHex( 32 );
3276 $request->setSessionData( 'wsEditToken', $token );
3278 if( is_array( $salt ) ) {
3279 $salt = implode( '|', $salt );
3281 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
3286 * Generate a looking random token for various uses.
3288 * @param $salt String Optional salt value
3289 * @return String The new random token
3290 * @deprecated since 1.20; Use MWCryptRand for secure purposes or wfRandomString for pesudo-randomness
3292 public static function generateToken( $salt = '' ) {
3293 return MWCryptRand
::generateHex( 32 );
3297 * Check given value against the token value stored in the session.
3298 * A match should confirm that the form was submitted from the
3299 * user's own login session, not a form submission from a third-party
3302 * @param $val String Input value to compare
3303 * @param $salt String Optional function-specific data for hashing
3304 * @param $request WebRequest object to use or null to use $wgRequest
3305 * @return Boolean: Whether the token matches
3307 public function matchEditToken( $val, $salt = '', $request = null ) {
3308 $sessionToken = $this->getEditToken( $salt, $request );
3309 if ( $val != $sessionToken ) {
3310 wfDebug( "User::matchEditToken: broken session data\n" );
3312 return $val == $sessionToken;
3316 * Check given value against the token value stored in the session,
3317 * ignoring the suffix.
3319 * @param $val String Input value to compare
3320 * @param $salt String Optional function-specific data for hashing
3321 * @param $request WebRequest object to use or null to use $wgRequest
3322 * @return Boolean: Whether the token matches
3324 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3325 $sessionToken = $this->getEditToken( $salt, $request );
3326 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3330 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3331 * mail to the user's given address.
3333 * @param $type String: message to send, either "created", "changed" or "set"
3334 * @return Status object
3336 public function sendConfirmationMail( $type = 'created' ) {
3338 $expiration = null; // gets passed-by-ref and defined in next line.
3339 $token = $this->confirmationToken( $expiration );
3340 $url = $this->confirmationTokenUrl( $token );
3341 $invalidateURL = $this->invalidationTokenUrl( $token );
3342 $this->saveSettings();
3344 if ( $type == 'created' ||
$type === false ) {
3345 $message = 'confirmemail_body';
3346 } elseif ( $type === true ) {
3347 $message = 'confirmemail_body_changed';
3349 $message = 'confirmemail_body_' . $type;
3352 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
3354 $this->getRequest()->getIP(),
3357 $wgLang->timeanddate( $expiration, false ),
3359 $wgLang->date( $expiration, false ),
3360 $wgLang->time( $expiration, false ) ) );
3364 * Send an e-mail to this user's account. Does not check for
3365 * confirmed status or validity.
3367 * @param $subject String Message subject
3368 * @param $body String Message body
3369 * @param $from String Optional From address; if unspecified, default $wgPasswordSender will be used
3370 * @param $replyto String Reply-To address
3373 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3374 if( is_null( $from ) ) {
3375 global $wgPasswordSender, $wgPasswordSenderName;
3376 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
3378 $sender = new MailAddress( $from );
3381 $to = new MailAddress( $this );
3382 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
3386 * Generate, store, and return a new e-mail confirmation code.
3387 * A hash (unsalted, since it's used as a key) is stored.
3389 * @note Call saveSettings() after calling this function to commit
3390 * this change to the database.
3392 * @param &$expiration \mixed Accepts the expiration time
3393 * @return String New token
3395 private function confirmationToken( &$expiration ) {
3396 global $wgUserEmailConfirmationTokenExpiry;
3398 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
3399 $expiration = wfTimestamp( TS_MW
, $expires );
3401 $token = MWCryptRand
::generateHex( 32 );
3402 $hash = md5( $token );
3403 $this->mEmailToken
= $hash;
3404 $this->mEmailTokenExpires
= $expiration;
3409 * Return a URL the user can use to confirm their email address.
3410 * @param $token String Accepts the email confirmation token
3411 * @return String New token URL
3413 private function confirmationTokenUrl( $token ) {
3414 return $this->getTokenUrl( 'ConfirmEmail', $token );
3418 * Return a URL the user can use to invalidate their email address.
3419 * @param $token String Accepts the email confirmation token
3420 * @return String New token URL
3422 private function invalidationTokenUrl( $token ) {
3423 return $this->getTokenUrl( 'InvalidateEmail', $token );
3427 * Internal function to format the e-mail validation/invalidation URLs.
3428 * This uses a quickie hack to use the
3429 * hardcoded English names of the Special: pages, for ASCII safety.
3431 * @note Since these URLs get dropped directly into emails, using the
3432 * short English names avoids insanely long URL-encoded links, which
3433 * also sometimes can get corrupted in some browsers/mailers
3434 * (bug 6957 with Gmail and Internet Explorer).
3436 * @param $page String Special page
3437 * @param $token String Token
3438 * @return String Formatted URL
3440 protected function getTokenUrl( $page, $token ) {
3441 // Hack to bypass localization of 'Special:'
3442 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
3443 return $title->getCanonicalUrl();
3447 * Mark the e-mail address confirmed.
3449 * @note Call saveSettings() after calling this function to commit the change.
3453 public function confirmEmail() {
3454 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3455 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3460 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3461 * address if it was already confirmed.
3463 * @note Call saveSettings() after calling this function to commit the change.
3464 * @return bool Returns true
3466 function invalidateEmail() {
3468 $this->mEmailToken
= null;
3469 $this->mEmailTokenExpires
= null;
3470 $this->setEmailAuthenticationTimestamp( null );
3471 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3476 * Set the e-mail authentication timestamp.
3477 * @param $timestamp String TS_MW timestamp
3479 function setEmailAuthenticationTimestamp( $timestamp ) {
3481 $this->mEmailAuthenticated
= $timestamp;
3482 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
3486 * Is this user allowed to send e-mails within limits of current
3487 * site configuration?
3490 public function canSendEmail() {
3491 global $wgEnableEmail, $wgEnableUserEmail;
3492 if( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
3495 $canSend = $this->isEmailConfirmed();
3496 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3501 * Is this user allowed to receive e-mails within limits of current
3502 * site configuration?
3505 public function canReceiveEmail() {
3506 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3510 * Is this user's e-mail address valid-looking and confirmed within
3511 * limits of the current site configuration?
3513 * @note If $wgEmailAuthentication is on, this may require the user to have
3514 * confirmed their address by returning a code or using a password
3515 * sent to the address from the wiki.
3519 public function isEmailConfirmed() {
3520 global $wgEmailAuthentication;
3523 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3524 if( $this->isAnon() ) {
3527 if( !Sanitizer
::validateEmail( $this->mEmail
) ) {
3530 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
3540 * Check whether there is an outstanding request for e-mail confirmation.
3543 public function isEmailConfirmationPending() {
3544 global $wgEmailAuthentication;
3545 return $wgEmailAuthentication &&
3546 !$this->isEmailConfirmed() &&
3547 $this->mEmailToken
&&
3548 $this->mEmailTokenExpires
> wfTimestamp();
3552 * Get the timestamp of account creation.
3554 * @return String|Bool Timestamp of account creation, or false for
3555 * non-existent/anonymous user accounts.
3557 public function getRegistration() {
3558 if ( $this->isAnon() ) {
3562 return $this->mRegistration
;
3566 * Get the timestamp of the first edit
3568 * @return String|Bool Timestamp of first edit, or false for
3569 * non-existent/anonymous user accounts.
3571 public function getFirstEditTimestamp() {
3572 if( $this->getId() == 0 ) {
3573 return false; // anons
3575 $dbr = wfGetDB( DB_SLAVE
);
3576 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3577 array( 'rev_user' => $this->getId() ),
3579 array( 'ORDER BY' => 'rev_timestamp ASC' )
3582 return false; // no edits
3584 return wfTimestamp( TS_MW
, $time );
3588 * Get the permissions associated with a given list of groups
3590 * @param $groups Array of Strings List of internal group names
3591 * @return Array of Strings List of permission key names for given groups combined
3593 public static function getGroupPermissions( $groups ) {
3594 global $wgGroupPermissions, $wgRevokePermissions;
3596 // grant every granted permission first
3597 foreach( $groups as $group ) {
3598 if( isset( $wgGroupPermissions[$group] ) ) {
3599 $rights = array_merge( $rights,
3600 // array_filter removes empty items
3601 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3604 // now revoke the revoked permissions
3605 foreach( $groups as $group ) {
3606 if( isset( $wgRevokePermissions[$group] ) ) {
3607 $rights = array_diff( $rights,
3608 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3611 return array_unique( $rights );
3615 * Get all the groups who have a given permission
3617 * @param $role String Role to check
3618 * @return Array of Strings List of internal group names with the given permission
3620 public static function getGroupsWithPermission( $role ) {
3621 global $wgGroupPermissions;
3622 $allowedGroups = array();
3623 foreach ( $wgGroupPermissions as $group => $rights ) {
3624 if ( isset( $rights[$role] ) && $rights[$role] ) {
3625 $allowedGroups[] = $group;
3628 return $allowedGroups;
3632 * Get the localized descriptive name for a group, if it exists
3634 * @param $group String Internal group name
3635 * @return String Localized descriptive group name
3637 public static function getGroupName( $group ) {
3638 $msg = wfMessage( "group-$group" );
3639 return $msg->isBlank() ?
$group : $msg->text();
3643 * Get the localized descriptive name for a member of a group, if it exists
3645 * @param $group String Internal group name
3646 * @param $username String Username for gender (since 1.19)
3647 * @return String Localized name for group member
3649 public static function getGroupMember( $group, $username = '#' ) {
3650 $msg = wfMessage( "group-$group-member", $username );
3651 return $msg->isBlank() ?
$group : $msg->text();
3655 * Return the set of defined explicit groups.
3656 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3657 * are not included, as they are defined automatically, not in the database.
3658 * @return Array of internal group names
3660 public static function getAllGroups() {
3661 global $wgGroupPermissions, $wgRevokePermissions;
3663 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3664 self
::getImplicitGroups()
3669 * Get a list of all available permissions.
3670 * @return Array of permission names
3672 public static function getAllRights() {
3673 if ( self
::$mAllRights === false ) {
3674 global $wgAvailableRights;
3675 if ( count( $wgAvailableRights ) ) {
3676 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3678 self
::$mAllRights = self
::$mCoreRights;
3680 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3682 return self
::$mAllRights;
3686 * Get a list of implicit groups
3687 * @return Array of Strings Array of internal group names
3689 public static function getImplicitGroups() {
3690 global $wgImplicitGroups;
3691 $groups = $wgImplicitGroups;
3692 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3697 * Get the title of a page describing a particular group
3699 * @param $group String Internal group name
3700 * @return Title|Bool Title of the page if it exists, false otherwise
3702 public static function getGroupPage( $group ) {
3703 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
3704 if( $msg->exists() ) {
3705 $title = Title
::newFromText( $msg->text() );
3706 if( is_object( $title ) )
3713 * Create a link to the group in HTML, if available;
3714 * else return the group name.
3716 * @param $group String Internal name of the group
3717 * @param $text String The text of the link
3718 * @return String HTML link to the group
3720 public static function makeGroupLinkHTML( $group, $text = '' ) {
3722 $text = self
::getGroupName( $group );
3724 $title = self
::getGroupPage( $group );
3726 return Linker
::link( $title, htmlspecialchars( $text ) );
3733 * Create a link to the group in Wikitext, if available;
3734 * else return the group name.
3736 * @param $group String Internal name of the group
3737 * @param $text String The text of the link
3738 * @return String Wikilink to the group
3740 public static function makeGroupLinkWiki( $group, $text = '' ) {
3742 $text = self
::getGroupName( $group );
3744 $title = self
::getGroupPage( $group );
3746 $page = $title->getPrefixedText();
3747 return "[[$page|$text]]";
3754 * Returns an array of the groups that a particular group can add/remove.
3756 * @param $group String: the group to check for whether it can add/remove
3757 * @return Array array( 'add' => array( addablegroups ),
3758 * 'remove' => array( removablegroups ),
3759 * 'add-self' => array( addablegroups to self),
3760 * 'remove-self' => array( removable groups from self) )
3762 public static function changeableByGroup( $group ) {
3763 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
3765 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
3766 if( empty( $wgAddGroups[$group] ) ) {
3767 // Don't add anything to $groups
3768 } elseif( $wgAddGroups[$group] === true ) {
3769 // You get everything
3770 $groups['add'] = self
::getAllGroups();
3771 } elseif( is_array( $wgAddGroups[$group] ) ) {
3772 $groups['add'] = $wgAddGroups[$group];
3775 // Same thing for remove
3776 if( empty( $wgRemoveGroups[$group] ) ) {
3777 } elseif( $wgRemoveGroups[$group] === true ) {
3778 $groups['remove'] = self
::getAllGroups();
3779 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
3780 $groups['remove'] = $wgRemoveGroups[$group];
3783 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
3784 if( empty( $wgGroupsAddToSelf['user']) ||
$wgGroupsAddToSelf['user'] !== true ) {
3785 foreach( $wgGroupsAddToSelf as $key => $value ) {
3786 if( is_int( $key ) ) {
3787 $wgGroupsAddToSelf['user'][] = $value;
3792 if( empty( $wgGroupsRemoveFromSelf['user']) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
3793 foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
3794 if( is_int( $key ) ) {
3795 $wgGroupsRemoveFromSelf['user'][] = $value;
3800 // Now figure out what groups the user can add to him/herself
3801 if( empty( $wgGroupsAddToSelf[$group] ) ) {
3802 } elseif( $wgGroupsAddToSelf[$group] === true ) {
3803 // No idea WHY this would be used, but it's there
3804 $groups['add-self'] = User
::getAllGroups();
3805 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
3806 $groups['add-self'] = $wgGroupsAddToSelf[$group];
3809 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
3810 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
3811 $groups['remove-self'] = User
::getAllGroups();
3812 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
3813 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
3820 * Returns an array of groups that this user can add and remove
3821 * @return Array array( 'add' => array( addablegroups ),
3822 * 'remove' => array( removablegroups ),
3823 * 'add-self' => array( addablegroups to self),
3824 * 'remove-self' => array( removable groups from self) )
3826 public function changeableGroups() {
3827 if( $this->isAllowed( 'userrights' ) ) {
3828 // This group gives the right to modify everything (reverse-
3829 // compatibility with old "userrights lets you change
3831 // Using array_merge to make the groups reindexed
3832 $all = array_merge( User
::getAllGroups() );
3836 'add-self' => array(),
3837 'remove-self' => array()
3841 // Okay, it's not so simple, we will have to go through the arrays
3844 'remove' => array(),
3845 'add-self' => array(),
3846 'remove-self' => array()
3848 $addergroups = $this->getEffectiveGroups();
3850 foreach( $addergroups as $addergroup ) {
3851 $groups = array_merge_recursive(
3852 $groups, $this->changeableByGroup( $addergroup )
3854 $groups['add'] = array_unique( $groups['add'] );
3855 $groups['remove'] = array_unique( $groups['remove'] );
3856 $groups['add-self'] = array_unique( $groups['add-self'] );
3857 $groups['remove-self'] = array_unique( $groups['remove-self'] );
3863 * Increment the user's edit-count field.
3864 * Will have no effect for anonymous users.
3866 public function incEditCount() {
3867 if( !$this->isAnon() ) {
3868 $dbw = wfGetDB( DB_MASTER
);
3869 $dbw->update( 'user',
3870 array( 'user_editcount=user_editcount+1' ),
3871 array( 'user_id' => $this->getId() ),
3874 // Lazy initialization check...
3875 if( $dbw->affectedRows() == 0 ) {
3876 // Pull from a slave to be less cruel to servers
3877 // Accuracy isn't the point anyway here
3878 $dbr = wfGetDB( DB_SLAVE
);
3879 $count = $dbr->selectField( 'revision',
3881 array( 'rev_user' => $this->getId() ),
3884 // Now here's a goddamn hack...
3885 if( $dbr !== $dbw ) {
3886 // If we actually have a slave server, the count is
3887 // at least one behind because the current transaction
3888 // has not been committed and replicated.
3891 // But if DB_SLAVE is selecting the master, then the
3892 // count we just read includes the revision that was
3893 // just added in the working transaction.
3896 $dbw->update( 'user',
3897 array( 'user_editcount' => $count ),
3898 array( 'user_id' => $this->getId() ),
3902 // edit count in user cache too
3903 $this->invalidateCache();
3907 * Get the description of a given right
3909 * @param $right String Right to query
3910 * @return String Localized description of the right
3912 public static function getRightDescription( $right ) {
3913 $key = "right-$right";
3914 $msg = wfMessage( $key );
3915 return $msg->isBlank() ?
$right : $msg->text();
3919 * Make an old-style password hash
3921 * @param $password String Plain-text password
3922 * @param $userId String User ID
3923 * @return String Password hash
3925 public static function oldCrypt( $password, $userId ) {
3926 global $wgPasswordSalt;
3927 if ( $wgPasswordSalt ) {
3928 return md5( $userId . '-' . md5( $password ) );
3930 return md5( $password );
3935 * Make a new-style password hash
3937 * @param $password String Plain-text password
3938 * @param bool|string $salt Optional salt, may be random or the user ID.
3940 * If unspecified or false, will generate one automatically
3941 * @return String Password hash
3943 public static function crypt( $password, $salt = false ) {
3944 global $wgPasswordSalt;
3947 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3951 if( $wgPasswordSalt ) {
3952 if ( $salt === false ) {
3953 $salt = MWCryptRand
::generateHex( 8 );
3955 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3957 return ':A:' . md5( $password );
3962 * Compare a password hash with a plain-text password. Requires the user
3963 * ID if there's a chance that the hash is an old-style hash.
3965 * @param $hash String Password hash
3966 * @param $password String Plain-text password to compare
3967 * @param $userId String|bool User ID for old-style password salt
3971 public static function comparePasswords( $hash, $password, $userId = false ) {
3972 $type = substr( $hash, 0, 3 );
3975 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3979 if ( $type == ':A:' ) {
3981 return md5( $password ) === substr( $hash, 3 );
3982 } elseif ( $type == ':B:' ) {
3984 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3985 return md5( $salt.'-'.md5( $password ) ) === $realHash;
3988 return self
::oldCrypt( $password, $userId ) === $hash;
3993 * Add a newuser log entry for this user. Before 1.19 the return value was always true.
3995 * @param $byEmail Boolean: account made by email?
3996 * @param $reason String: user supplied reason
3998 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4000 public function addNewUserLogEntry( $byEmail = false, $reason = '' ) {
4001 global $wgUser, $wgContLang, $wgNewUserLog;
4002 if( empty( $wgNewUserLog ) ) {
4003 return true; // disabled
4006 if( $this->getName() == $wgUser->getName() ) {
4009 $action = 'create2';
4011 if ( $reason === '' ) {
4012 $reason = wfMsgForContent( 'newuserlog-byemail' );
4014 $reason = $wgContLang->commaList( array(
4015 $reason, wfMsgForContent( 'newuserlog-byemail' ) ) );
4019 $log = new LogPage( 'newusers' );
4020 return (int)$log->addEntry(
4022 $this->getUserPage(),
4024 array( $this->getId() )
4029 * Add an autocreate newuser log entry for this user
4030 * Used by things like CentralAuth and perhaps other authplugins.
4034 public function addNewUserLogEntryAutoCreate() {
4035 global $wgNewUserLog;
4036 if( !$wgNewUserLog ) {
4037 return true; // disabled
4039 $log = new LogPage( 'newusers', false );
4040 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ), $this );
4047 protected function loadOptions() {
4049 if ( $this->mOptionsLoaded ||
!$this->getId() )
4052 $this->mOptions
= self
::getDefaultOptions();
4054 // Maybe load from the object
4055 if ( !is_null( $this->mOptionOverrides
) ) {
4056 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4057 foreach( $this->mOptionOverrides
as $key => $value ) {
4058 $this->mOptions
[$key] = $value;
4061 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4062 // Load from database
4063 $dbr = wfGetDB( DB_SLAVE
);
4065 $res = $dbr->select(
4067 array( 'up_property', 'up_value' ),
4068 array( 'up_user' => $this->getId() ),
4072 $this->mOptionOverrides
= array();
4073 foreach ( $res as $row ) {
4074 $this->mOptionOverrides
[$row->up_property
] = $row->up_value
;
4075 $this->mOptions
[$row->up_property
] = $row->up_value
;
4079 $this->mOptionsLoaded
= true;
4081 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
4087 protected function saveOptions() {
4088 global $wgAllowPrefChange;
4090 $this->loadOptions();
4092 // Not using getOptions(), to keep hidden preferences in database
4093 $saveOptions = $this->mOptions
;
4095 // Allow hooks to abort, for instance to save to a global profile.
4096 // Reset options to default state before saving.
4097 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4101 $extuser = ExternalUser
::newFromUser( $this );
4102 $userId = $this->getId();
4103 $insert_rows = array();
4104 foreach( $saveOptions as $key => $value ) {
4105 # Don't bother storing default values
4106 $defaultOption = self
::getDefaultOption( $key );
4107 if ( ( is_null( $defaultOption ) &&
4108 !( $value === false ||
is_null( $value ) ) ) ||
4109 $value != $defaultOption ) {
4110 $insert_rows[] = array(
4111 'up_user' => $userId,
4112 'up_property' => $key,
4113 'up_value' => $value,
4116 if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
4117 switch ( $wgAllowPrefChange[$key] ) {
4123 $extuser->setPref( $key, $value );
4128 $dbw = wfGetDB( DB_MASTER
);
4129 $dbw->delete( 'user_properties', array( 'up_user' => $userId ), __METHOD__
);
4130 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
);
4134 * Provide an array of HTML5 attributes to put on an input element
4135 * intended for the user to enter a new password. This may include
4136 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4138 * Do *not* use this when asking the user to enter his current password!
4139 * Regardless of configuration, users may have invalid passwords for whatever
4140 * reason (e.g., they were set before requirements were tightened up).
4141 * Only use it when asking for a new password, like on account creation or
4144 * Obviously, you still need to do server-side checking.
4146 * NOTE: A combination of bugs in various browsers means that this function
4147 * actually just returns array() unconditionally at the moment. May as
4148 * well keep it around for when the browser bugs get fixed, though.
4150 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4152 * @return array Array of HTML attributes suitable for feeding to
4153 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4154 * That will potentially output invalid XHTML 1.0 Transitional, and will
4155 * get confused by the boolean attribute syntax used.)
4157 public static function passwordChangeInputAttribs() {
4158 global $wgMinimalPasswordLength;
4160 if ( $wgMinimalPasswordLength == 0 ) {
4164 # Note that the pattern requirement will always be satisfied if the
4165 # input is empty, so we need required in all cases.
4167 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4168 # if e-mail confirmation is being used. Since HTML5 input validation
4169 # is b0rked anyway in some browsers, just return nothing. When it's
4170 # re-enabled, fix this code to not output required for e-mail
4172 #$ret = array( 'required' );
4175 # We can't actually do this right now, because Opera 9.6 will print out
4176 # the entered password visibly in its error message! When other
4177 # browsers add support for this attribute, or Opera fixes its support,
4178 # we can add support with a version check to avoid doing this on Opera
4179 # versions where it will be a problem. Reported to Opera as
4180 # DSK-262266, but they don't have a public bug tracker for us to follow.
4182 if ( $wgMinimalPasswordLength > 1 ) {
4183 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4184 $ret['title'] = wfMsgExt( 'passwordtooshort', 'parsemag',
4185 $wgMinimalPasswordLength );
4193 * Return the list of user fields that should be selected to create
4194 * a new user object.
4197 public static function selectFields() {
4204 'user_newpass_time',
4208 'user_email_authenticated',
4210 'user_email_token_expires',
4211 'user_registration',