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(
126 'editusercssjs', #deprecated
138 'move-rootuserpages',
142 'override-export-depth',
165 'userrights-interwiki',
169 * String Cached results of getAllRights()
171 static $mAllRights = false;
173 /** @name Cache variables */
175 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
176 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
177 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mEditCount,
178 $mGroups, $mOptionOverrides;
182 * Bool Whether the cache variables have been loaded.
188 * Array with already loaded items or true if all items have been loaded.
190 private $mLoadedItems = array();
194 * String Initialization data source if mLoadedItems!==true. May be one of:
195 * - 'defaults' anonymous user initialised from class defaults
196 * - 'name' initialise from mName
197 * - 'id' initialise from mId
198 * - 'session' log in from cookies or session if possible
200 * Use the User::newFrom*() family of functions to set this.
205 * Lazy-initialized variables, invalidated with clearInstanceCache
207 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mRights,
208 $mBlockreason, $mEffectiveGroups, $mImplicitGroups, $mFormerGroups, $mBlockedGlobally,
209 $mLocked, $mHideName, $mOptions;
229 private $mBlockedFromCreateAccount = false;
234 private $mWatchedItems = array();
236 static $idCacheByName = array();
239 * Lightweight constructor for an anonymous user.
240 * Use the User::newFrom* factory functions for other kinds of users.
244 * @see newFromConfirmationCode()
245 * @see newFromSession()
248 function __construct() {
249 $this->clearInstanceCache( 'defaults' );
255 function __toString(){
256 return $this->getName();
260 * Load the user table data for this object from the source given by mFrom.
262 public function load() {
263 if ( $this->mLoadedItems
=== true ) {
266 wfProfileIn( __METHOD__
);
268 # Set it now to avoid infinite recursion in accessors
269 $this->mLoadedItems
= true;
271 switch ( $this->mFrom
) {
273 $this->loadDefaults();
276 $this->mId
= self
::idFromName( $this->mName
);
278 # Nonexistent user placeholder object
279 $this->loadDefaults( $this->mName
);
288 $this->loadFromSession();
289 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
292 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
294 wfProfileOut( __METHOD__
);
298 * Load user table data, given mId has already been set.
299 * @return Bool false if the ID does not exist, true otherwise
301 public function loadFromId() {
303 if ( $this->mId
== 0 ) {
304 $this->loadDefaults();
309 $key = wfMemcKey( 'user', 'id', $this->mId
);
310 $data = $wgMemc->get( $key );
311 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
312 # Object is expired, load from DB
317 wfDebug( "User: cache miss for user {$this->mId}\n" );
319 if ( !$this->loadFromDatabase() ) {
320 # Can't load from ID, user is anonymous
323 $this->saveToCache();
325 wfDebug( "User: got user {$this->mId} from cache\n" );
327 foreach ( self
::$mCacheVars as $name ) {
328 $this->$name = $data[$name];
335 * Save user data to the shared cache
337 public function saveToCache() {
340 $this->loadOptions();
341 if ( $this->isAnon() ) {
342 // Anonymous users are uncached
346 foreach ( self
::$mCacheVars as $name ) {
347 $data[$name] = $this->$name;
349 $data['mVersion'] = MW_USER_VERSION
;
350 $key = wfMemcKey( 'user', 'id', $this->mId
);
352 $wgMemc->set( $key, $data );
355 /** @name newFrom*() static factory methods */
359 * Static factory method for creation from username.
361 * This is slightly less efficient than newFromId(), so use newFromId() if
362 * you have both an ID and a name handy.
364 * @param $name String Username, validated by Title::newFromText()
365 * @param $validate String|Bool Validate username. Takes the same parameters as
366 * User::getCanonicalName(), except that true is accepted as an alias
367 * for 'valid', for BC.
369 * @return User object, or false if the username is invalid
370 * (e.g. if it contains illegal characters or is an IP address). If the
371 * username is not present in the database, the result will be a user object
372 * with a name, zero user ID and default settings.
374 public static function newFromName( $name, $validate = 'valid' ) {
375 if ( $validate === true ) {
378 $name = self
::getCanonicalName( $name, $validate );
379 if ( $name === false ) {
382 # Create unloaded user object
386 $u->setItemLoaded( 'name' );
392 * Static factory method for creation from a given user ID.
394 * @param $id Int Valid user ID
395 * @return User The corresponding User object
397 public static function newFromId( $id ) {
401 $u->setItemLoaded( 'id' );
406 * Factory method to fetch whichever user has a given email confirmation code.
407 * This code is generated when an account is created or its e-mail address
410 * If the code is invalid or has expired, returns NULL.
412 * @param $code String Confirmation code
413 * @return User object, or null
415 public static function newFromConfirmationCode( $code ) {
416 $dbr = wfGetDB( DB_SLAVE
);
417 $id = $dbr->selectField( 'user', 'user_id', array(
418 'user_email_token' => md5( $code ),
419 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
421 if( $id !== false ) {
422 return User
::newFromId( $id );
429 * Create a new user object using data from session or cookies. If the
430 * login credentials are invalid, the result is an anonymous user.
432 * @param $request WebRequest object to use; $wgRequest will be used if
434 * @return User object
436 public static function newFromSession( WebRequest
$request = null ) {
438 $user->mFrom
= 'session';
439 $user->mRequest
= $request;
444 * Create a new user object from a user row.
445 * The row should have the following fields from the user table in it:
446 * - either user_name or user_id to load further data if needed (or both)
448 * - all other fields (email, password, etc.)
449 * It is useless to provide the remaining fields if either user_id,
450 * user_name and user_real_name are not provided because the whole row
451 * will be loaded once more from the database when accessing them.
453 * @param $row Array A row from the user table
456 public static function newFromRow( $row ) {
458 $user->loadFromRow( $row );
465 * Get the username corresponding to a given user ID
466 * @param $id Int User ID
467 * @return String|bool The corresponding username
469 public static function whoIs( $id ) {
470 $dbr = wfGetDB( DB_SLAVE
);
471 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), __METHOD__
);
475 * Get the real name of a user given their user ID
477 * @param $id Int User ID
478 * @return String|bool The corresponding user's real name
480 public static function whoIsReal( $id ) {
481 $dbr = wfGetDB( DB_SLAVE
);
482 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
486 * Get database id given a user name
487 * @param $name String Username
488 * @return Int|Null The corresponding user's ID, or null if user is nonexistent
490 public static function idFromName( $name ) {
491 $nt = Title
::makeTitleSafe( NS_USER
, $name );
492 if( is_null( $nt ) ) {
497 if ( isset( self
::$idCacheByName[$name] ) ) {
498 return self
::$idCacheByName[$name];
501 $dbr = wfGetDB( DB_SLAVE
);
502 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
504 if ( $s === false ) {
507 $result = $s->user_id
;
510 self
::$idCacheByName[$name] = $result;
512 if ( count( self
::$idCacheByName ) > 1000 ) {
513 self
::$idCacheByName = array();
520 * Reset the cache used in idFromName(). For use in tests.
522 public static function resetIdByNameCache() {
523 self
::$idCacheByName = array();
527 * Does the string match an anonymous IPv4 address?
529 * This function exists for username validation, in order to reject
530 * usernames which are similar in form to IP addresses. Strings such
531 * as 300.300.300.300 will return true because it looks like an IP
532 * address, despite not being strictly valid.
534 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
535 * address because the usemod software would "cloak" anonymous IP
536 * addresses like this, if we allowed accounts like this to be created
537 * new users could get the old edits of these anonymous users.
539 * @param $name String to match
542 public static function isIP( $name ) {
543 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP
::isIPv6($name);
547 * Is the input a valid username?
549 * Checks if the input is a valid username, we don't want an empty string,
550 * an IP address, anything that containins slashes (would mess up subpages),
551 * is longer than the maximum allowed username size or doesn't begin with
554 * @param $name String to match
557 public static function isValidUserName( $name ) {
558 global $wgContLang, $wgMaxNameChars;
561 || User
::isIP( $name )
562 ||
strpos( $name, '/' ) !== false
563 ||
strlen( $name ) > $wgMaxNameChars
564 ||
$name != $wgContLang->ucfirst( $name ) ) {
565 wfDebugLog( 'username', __METHOD__
.
566 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
571 // Ensure that the name can't be misresolved as a different title,
572 // such as with extra namespace keys at the start.
573 $parsed = Title
::newFromText( $name );
574 if( is_null( $parsed )
575 ||
$parsed->getNamespace()
576 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
577 wfDebugLog( 'username', __METHOD__
.
578 ": '$name' invalid due to ambiguous prefixes" );
582 // Check an additional blacklist of troublemaker characters.
583 // Should these be merged into the title char list?
584 $unicodeBlacklist = '/[' .
585 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
586 '\x{00a0}' . # non-breaking space
587 '\x{2000}-\x{200f}' . # various whitespace
588 '\x{2028}-\x{202f}' . # breaks and control chars
589 '\x{3000}' . # ideographic space
590 '\x{e000}-\x{f8ff}' . # private use
592 if( preg_match( $unicodeBlacklist, $name ) ) {
593 wfDebugLog( 'username', __METHOD__
.
594 ": '$name' invalid due to blacklisted characters" );
602 * Usernames which fail to pass this function will be blocked
603 * from user login and new account registrations, but may be used
604 * internally by batch processes.
606 * If an account already exists in this form, login will be blocked
607 * by a failure to pass this function.
609 * @param $name String to match
612 public static function isUsableName( $name ) {
613 global $wgReservedUsernames;
614 // Must be a valid username, obviously ;)
615 if ( !self
::isValidUserName( $name ) ) {
619 static $reservedUsernames = false;
620 if ( !$reservedUsernames ) {
621 $reservedUsernames = $wgReservedUsernames;
622 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
625 // Certain names may be reserved for batch processes.
626 foreach ( $reservedUsernames as $reserved ) {
627 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
628 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
630 if ( $reserved == $name ) {
638 * Usernames which fail to pass this function will be blocked
639 * from new account registrations, but may be used internally
640 * either by batch processes or by user accounts which have
641 * already been created.
643 * Additional blacklisting may be added here rather than in
644 * isValidUserName() to avoid disrupting existing accounts.
646 * @param $name String to match
649 public static function isCreatableName( $name ) {
650 global $wgInvalidUsernameCharacters;
652 // Ensure that the username isn't longer than 235 bytes, so that
653 // (at least for the builtin skins) user javascript and css files
654 // will work. (bug 23080)
655 if( strlen( $name ) > 235 ) {
656 wfDebugLog( 'username', __METHOD__
.
657 ": '$name' invalid due to length" );
661 // Preg yells if you try to give it an empty string
662 if( $wgInvalidUsernameCharacters !== '' ) {
663 if( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
664 wfDebugLog( 'username', __METHOD__
.
665 ": '$name' invalid due to wgInvalidUsernameCharacters" );
670 return self
::isUsableName( $name );
674 * Is the input a valid password for this user?
676 * @param $password String Desired password
679 public function isValidPassword( $password ) {
680 //simple boolean wrapper for getPasswordValidity
681 return $this->getPasswordValidity( $password ) === true;
685 * Given unvalidated password input, return error message on failure.
687 * @param $password String Desired password
688 * @return mixed: true on success, string or array of error message on failure
690 public function getPasswordValidity( $password ) {
691 global $wgMinimalPasswordLength, $wgContLang;
693 static $blockedLogins = array(
694 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
695 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
698 $result = false; //init $result to false for the internal checks
700 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
703 if ( $result === false ) {
704 if( strlen( $password ) < $wgMinimalPasswordLength ) {
705 return 'passwordtooshort';
706 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
707 return 'password-name-match';
708 } elseif ( isset( $blockedLogins[ $this->getName() ] ) && $password == $blockedLogins[ $this->getName() ] ) {
709 return 'password-login-forbidden';
711 //it seems weird returning true here, but this is because of the
712 //initialization of $result to false above. If the hook is never run or it
713 //doesn't modify $result, then we will likely get down into this if with
717 } elseif( $result === true ) {
720 return $result; //the isValidPassword hook set a string $result and returned true
725 * Does a string look like an e-mail address?
727 * This validates an email address using an HTML5 specification found at:
728 * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
729 * Which as of 2011-01-24 says:
731 * A valid e-mail address is a string that matches the ABNF production
732 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
733 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
736 * This function is an implementation of the specification as requested in
739 * Client-side forms will use the same standard validation rules via JS or
740 * HTML 5 validation; additional restrictions can be enforced server-side
741 * by extensions via the 'isValidEmailAddr' hook.
743 * Note that this validation doesn't 100% match RFC 2822, but is believed
744 * to be liberal enough for wide use. Some invalid addresses will still
745 * pass validation here.
747 * @param $addr String E-mail address
749 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
751 public static function isValidEmailAddr( $addr ) {
752 wfDeprecated( __METHOD__
, '1.18' );
753 return Sanitizer
::validateEmail( $addr );
757 * Given unvalidated user input, return a canonical username, or false if
758 * the username is invalid.
759 * @param $name String User input
760 * @param $validate String|Bool type of validation to use:
761 * - false No validation
762 * - 'valid' Valid for batch processes
763 * - 'usable' Valid for batch processes and login
764 * - 'creatable' Valid for batch processes, login and account creation
766 * @return bool|string
768 public static function getCanonicalName( $name, $validate = 'valid' ) {
769 # Force usernames to capital
771 $name = $wgContLang->ucfirst( $name );
773 # Reject names containing '#'; these will be cleaned up
774 # with title normalisation, but then it's too late to
776 if( strpos( $name, '#' ) !== false )
779 # Clean up name according to title rules
780 $t = ( $validate === 'valid' ) ?
781 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
782 # Check for invalid titles
783 if( is_null( $t ) ) {
787 # Reject various classes of invalid names
789 $name = $wgAuth->getCanonicalName( $t->getText() );
791 switch ( $validate ) {
795 if ( !User
::isValidUserName( $name ) ) {
800 if ( !User
::isUsableName( $name ) ) {
805 if ( !User
::isCreatableName( $name ) ) {
810 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
816 * Count the number of edits of a user
817 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
819 * @param $uid Int User ID to check
820 * @return Int the user's edit count
822 public static function edits( $uid ) {
823 wfProfileIn( __METHOD__
);
824 $dbr = wfGetDB( DB_SLAVE
);
825 // check if the user_editcount field has been initialized
826 $field = $dbr->selectField(
827 'user', 'user_editcount',
828 array( 'user_id' => $uid ),
832 if( $field === null ) { // it has not been initialized. do so.
833 $dbw = wfGetDB( DB_MASTER
);
834 $count = $dbr->selectField(
835 'revision', 'count(*)',
836 array( 'rev_user' => $uid ),
841 array( 'user_editcount' => $count ),
842 array( 'user_id' => $uid ),
848 wfProfileOut( __METHOD__
);
853 * Return a random password.
855 * @return String new random password
857 public static function randomPassword() {
858 global $wgMinimalPasswordLength;
859 // Decide the final password length based on our min password length, stopping at a minimum of 10 chars
860 $length = max( 10, $wgMinimalPasswordLength );
861 // Multiply by 1.25 to get the number of hex characters we need
862 $length = $length * 1.25;
863 // Generate random hex chars
864 $hex = MWCryptRand
::generateHex( $length );
865 // Convert from base 16 to base 32 to get a proper password like string
866 return wfBaseConvert( $hex, 16, 32 );
870 * Set cached properties to default.
872 * @note This no longer clears uncached lazy-initialised properties;
873 * the constructor does that instead.
875 * @param $name string
877 public function loadDefaults( $name = false ) {
878 wfProfileIn( __METHOD__
);
881 $this->mName
= $name;
882 $this->mRealName
= '';
883 $this->mPassword
= $this->mNewpassword
= '';
884 $this->mNewpassTime
= null;
886 $this->mOptionOverrides
= null;
887 $this->mOptionsLoaded
= false;
889 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
890 if( $loggedOut !== null ) {
891 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
893 $this->mTouched
= '0'; # Allow any pages to be cached
896 $this->mToken
= null; // Don't run cryptographic functions till we need a token
897 $this->mEmailAuthenticated
= null;
898 $this->mEmailToken
= '';
899 $this->mEmailTokenExpires
= null;
900 $this->mRegistration
= wfTimestamp( TS_MW
);
901 $this->mGroups
= array();
903 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
905 wfProfileOut( __METHOD__
);
909 * Return whether an item has been loaded.
911 * @param $item String: item to check. Current possibilities:
915 * @param $all String: 'all' to check if the whole object has been loaded
916 * or any other string to check if only the item is available (e.g.
920 public function isItemLoaded( $item, $all = 'all' ) {
921 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
922 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
926 * Set that an item has been loaded
928 * @param $item String
930 private function setItemLoaded( $item ) {
931 if ( is_array( $this->mLoadedItems
) ) {
932 $this->mLoadedItems
[$item] = true;
937 * Load user data from the session or login cookie. If there are no valid
938 * credentials, initialises the user as an anonymous user.
939 * @return Bool True if the user is logged in, false otherwise.
941 private function loadFromSession() {
942 global $wgExternalAuthType, $wgAutocreatePolicy;
945 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
946 if ( $result !== null ) {
950 if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
951 $extUser = ExternalUser
::newFromCookie();
953 # TODO: Automatically create the user here (or probably a bit
954 # lower down, in fact)
958 $request = $this->getRequest();
960 $cookieId = $request->getCookie( 'UserID' );
961 $sessId = $request->getSessionData( 'wsUserID' );
963 if ( $cookieId !== null ) {
964 $sId = intval( $cookieId );
965 if( $sessId !== null && $cookieId != $sessId ) {
966 $this->loadDefaults(); // Possible collision!
967 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
968 cookie user ID ($sId) don't match!" );
971 $request->setSessionData( 'wsUserID', $sId );
972 } elseif ( $sessId !== null && $sessId != 0 ) {
975 $this->loadDefaults();
979 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
980 $sName = $request->getSessionData( 'wsUserName' );
981 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
982 $sName = $request->getCookie( 'UserName' );
983 $request->setSessionData( 'wsUserName', $sName );
985 $this->loadDefaults();
989 $proposedUser = User
::newFromId( $sId );
990 if ( !$proposedUser->isLoggedIn() ) {
992 $this->loadDefaults();
996 global $wgBlockDisablesLogin;
997 if( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
998 # User blocked and we've disabled blocked user logins
999 $this->loadDefaults();
1003 if ( $request->getSessionData( 'wsToken' ) ) {
1004 $passwordCorrect = $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' );
1006 } elseif ( $request->getCookie( 'Token' ) ) {
1007 $passwordCorrect = $proposedUser->getToken( false ) === $request->getCookie( 'Token' );
1010 # No session or persistent login cookie
1011 $this->loadDefaults();
1015 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1016 $this->loadFromUserObject( $proposedUser );
1017 $request->setSessionData( 'wsToken', $this->mToken
);
1018 wfDebug( "User: logged in from $from\n" );
1021 # Invalid credentials
1022 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1023 $this->loadDefaults();
1029 * Load user and user_group data from the database.
1030 * $this->mId must be set, this is how the user is identified.
1032 * @return Bool True if the user exists, false if the user is anonymous
1034 public function loadFromDatabase() {
1036 $this->mId
= intval( $this->mId
);
1038 /** Anonymous user */
1040 $this->loadDefaults();
1044 $dbr = wfGetDB( DB_MASTER
);
1045 $s = $dbr->selectRow( 'user', self
::selectFields(), array( 'user_id' => $this->mId
), __METHOD__
);
1047 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1049 if ( $s !== false ) {
1050 # Initialise user table data
1051 $this->loadFromRow( $s );
1052 $this->mGroups
= null; // deferred
1053 $this->getEditCount(); // revalidation for nulls
1058 $this->loadDefaults();
1064 * Initialize this object from a row from the user table.
1066 * @param $row Array Row from the user table to load.
1068 public function loadFromRow( $row ) {
1071 $this->mGroups
= null; // deferred
1073 if ( isset( $row->user_name
) ) {
1074 $this->mName
= $row->user_name
;
1075 $this->mFrom
= 'name';
1076 $this->setItemLoaded( 'name' );
1081 if ( isset( $row->user_real_name
) ) {
1082 $this->mRealName
= $row->user_real_name
;
1083 $this->setItemLoaded( 'realname' );
1088 if ( isset( $row->user_id
) ) {
1089 $this->mId
= intval( $row->user_id
);
1090 $this->mFrom
= 'id';
1091 $this->setItemLoaded( 'id' );
1096 if ( isset( $row->user_editcount
) ) {
1097 $this->mEditCount
= $row->user_editcount
;
1102 if ( isset( $row->user_password
) ) {
1103 $this->mPassword
= $row->user_password
;
1104 $this->mNewpassword
= $row->user_newpassword
;
1105 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1106 $this->mEmail
= $row->user_email
;
1107 if ( isset( $row->user_options
) ) {
1108 $this->decodeOptions( $row->user_options
);
1110 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1111 $this->mToken
= $row->user_token
;
1112 if ( $this->mToken
== '' ) {
1113 $this->mToken
= null;
1115 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1116 $this->mEmailToken
= $row->user_email_token
;
1117 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1118 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1124 $this->mLoadedItems
= true;
1129 * Load the data for this user object from another user object.
1133 protected function loadFromUserObject( $user ) {
1135 $user->loadGroups();
1136 $user->loadOptions();
1137 foreach ( self
::$mCacheVars as $var ) {
1138 $this->$var = $user->$var;
1143 * Load the groups from the database if they aren't already loaded.
1145 private function loadGroups() {
1146 if ( is_null( $this->mGroups
) ) {
1147 $dbr = wfGetDB( DB_MASTER
);
1148 $res = $dbr->select( 'user_groups',
1149 array( 'ug_group' ),
1150 array( 'ug_user' => $this->mId
),
1152 $this->mGroups
= array();
1153 foreach ( $res as $row ) {
1154 $this->mGroups
[] = $row->ug_group
;
1160 * Add the user to the group if he/she meets given criteria.
1162 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1163 * possible to remove manually via Special:UserRights. In such case it
1164 * will not be re-added automatically. The user will also not lose the
1165 * group if they no longer meet the criteria.
1167 * @param $event String key in $wgAutopromoteOnce (each one has groups/criteria)
1169 * @return array Array of groups the user has been promoted to.
1171 * @see $wgAutopromoteOnce
1173 public function addAutopromoteOnceGroups( $event ) {
1174 global $wgAutopromoteOnceLogInRC;
1176 $toPromote = array();
1177 if ( $this->getId() ) {
1178 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1179 if ( count( $toPromote ) ) {
1180 $oldGroups = $this->getGroups(); // previous groups
1181 foreach ( $toPromote as $group ) {
1182 $this->addGroup( $group );
1184 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1186 $log = new LogPage( 'rights', $wgAutopromoteOnceLogInRC /* in RC? */ );
1187 $log->addEntry( 'autopromote',
1188 $this->getUserPage(),
1190 // These group names are "list to texted"-ed in class LogPage.
1191 array( implode( ', ', $oldGroups ), implode( ', ', $newGroups ) )
1199 * Clear various cached data stored in this object.
1200 * @param $reloadFrom bool|String Reload user and user_groups table data from a
1201 * given source. May be "name", "id", "defaults", "session", or false for
1204 public function clearInstanceCache( $reloadFrom = false ) {
1205 $this->mNewtalk
= -1;
1206 $this->mDatePreference
= null;
1207 $this->mBlockedby
= -1; # Unset
1208 $this->mHash
= false;
1209 $this->mRights
= null;
1210 $this->mEffectiveGroups
= null;
1211 $this->mImplicitGroups
= null;
1212 $this->mOptions
= null;
1214 if ( $reloadFrom ) {
1215 $this->mLoadedItems
= array();
1216 $this->mFrom
= $reloadFrom;
1221 * Combine the language default options with any site-specific options
1222 * and add the default language variants.
1224 * @return Array of String options
1226 public static function getDefaultOptions() {
1227 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1229 $defOpt = $wgDefaultUserOptions;
1230 # default language setting
1231 $variant = $wgContLang->getDefaultVariant();
1232 $defOpt['variant'] = $variant;
1233 $defOpt['language'] = $variant;
1234 foreach( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1235 $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1237 $defOpt['skin'] = $wgDefaultSkin;
1239 // FIXME: Ideally we'd cache the results of this function so the hook is only run once,
1240 // but that breaks the parser tests because they rely on being able to change $wgContLang
1241 // mid-request and see that change reflected in the return value of this function.
1242 // Which is insane and would never happen during normal MW operation, but is also not
1243 // likely to get fixed unless and until we context-ify everything.
1244 // See also https://www.mediawiki.org/wiki/Special:Code/MediaWiki/101488#c25275
1245 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1251 * Get a given default option value.
1253 * @param $opt String Name of option to retrieve
1254 * @return String Default option value
1256 public static function getDefaultOption( $opt ) {
1257 $defOpts = self
::getDefaultOptions();
1258 if( isset( $defOpts[$opt] ) ) {
1259 return $defOpts[$opt];
1267 * Get blocking information
1268 * @param $bFromSlave Bool Whether to check the slave database first. To
1269 * improve performance, non-critical checks are done
1270 * against slaves. Check when actually saving should be
1271 * done against master.
1273 private function getBlockedStatus( $bFromSlave = true ) {
1274 global $wgProxyWhitelist, $wgUser;
1276 if ( -1 != $this->mBlockedby
) {
1280 wfProfileIn( __METHOD__
);
1281 wfDebug( __METHOD__
.": checking...\n" );
1283 // Initialize data...
1284 // Otherwise something ends up stomping on $this->mBlockedby when
1285 // things get lazy-loaded later, causing false positive block hits
1286 // due to -1 !== 0. Probably session-related... Nothing should be
1287 // overwriting mBlockedby, surely?
1290 # We only need to worry about passing the IP address to the Block generator if the
1291 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1292 # know which IP address they're actually coming from
1293 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1294 $ip = $this->getRequest()->getIP();
1300 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1303 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1304 && !in_array( $ip, $wgProxyWhitelist ) )
1307 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1309 $block->setBlocker( wfMsg( 'proxyblocker' ) );
1310 $block->mReason
= wfMsg( 'proxyblockreason' );
1311 $block->setTarget( $ip );
1312 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1314 $block->setBlocker( wfMsg( 'sorbs' ) );
1315 $block->mReason
= wfMsg( 'sorbsreason' );
1316 $block->setTarget( $ip );
1320 if ( $block instanceof Block
) {
1321 wfDebug( __METHOD__
. ": Found block.\n" );
1322 $this->mBlock
= $block;
1323 $this->mBlockedby
= $block->getByName();
1324 $this->mBlockreason
= $block->mReason
;
1325 $this->mHideName
= $block->mHideName
;
1326 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1328 $this->mBlockedby
= '';
1329 $this->mHideName
= 0;
1330 $this->mAllowUsertalk
= false;
1334 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1336 wfProfileOut( __METHOD__
);
1340 * Whether the given IP is in a DNS blacklist.
1342 * @param $ip String IP to check
1343 * @param $checkWhitelist Bool: whether to check the whitelist first
1344 * @return Bool True if blacklisted.
1346 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1347 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1348 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1350 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
1353 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
1356 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1357 return $this->inDnsBlacklist( $ip, $urls );
1361 * Whether the given IP is in a given DNS blacklist.
1363 * @param $ip String IP to check
1364 * @param $bases String|Array of Strings: URL of the DNS blacklist
1365 * @return Bool True if blacklisted.
1367 public function inDnsBlacklist( $ip, $bases ) {
1368 wfProfileIn( __METHOD__
);
1371 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1372 if( IP
::isIPv4( $ip ) ) {
1373 # Reverse IP, bug 21255
1374 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1376 foreach( (array)$bases as $base ) {
1378 # If we have an access key, use that too (ProjectHoneypot, etc.)
1379 if( is_array( $base ) ) {
1380 if( count( $base ) >= 2 ) {
1381 # Access key is 1, base URL is 0
1382 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1384 $host = "$ipReversed.{$base[0]}";
1387 $host = "$ipReversed.$base";
1391 $ipList = gethostbynamel( $host );
1394 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1398 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base.\n" );
1403 wfProfileOut( __METHOD__
);
1408 * Check if an IP address is in the local proxy list
1414 public static function isLocallyBlockedProxy( $ip ) {
1415 global $wgProxyList;
1417 if ( !$wgProxyList ) {
1420 wfProfileIn( __METHOD__
);
1422 if ( !is_array( $wgProxyList ) ) {
1423 # Load from the specified file
1424 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1427 if ( !is_array( $wgProxyList ) ) {
1429 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1431 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1432 # Old-style flipped proxy list
1437 wfProfileOut( __METHOD__
);
1442 * Is this user subject to rate limiting?
1444 * @return Bool True if rate limited
1446 public function isPingLimitable() {
1447 global $wgRateLimitsExcludedIPs;
1448 if( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1449 // No other good way currently to disable rate limits
1450 // for specific IPs. :P
1451 // But this is a crappy hack and should die.
1454 return !$this->isAllowed('noratelimit');
1458 * Primitive rate limits: enforce maximum actions per time period
1459 * to put a brake on flooding.
1461 * @note When using a shared cache like memcached, IP-address
1462 * last-hit counters will be shared across wikis.
1464 * @param $action String Action to enforce; 'edit' if unspecified
1465 * @return Bool True if a rate limiter was tripped
1467 public function pingLimiter( $action = 'edit' ) {
1468 # Call the 'PingLimiter' hook
1470 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1474 global $wgRateLimits;
1475 if( !isset( $wgRateLimits[$action] ) ) {
1479 # Some groups shouldn't trigger the ping limiter, ever
1480 if( !$this->isPingLimitable() )
1483 global $wgMemc, $wgRateLimitLog;
1484 wfProfileIn( __METHOD__
);
1486 $limits = $wgRateLimits[$action];
1488 $id = $this->getId();
1489 $ip = $this->getRequest()->getIP();
1492 if( isset( $limits['anon'] ) && $id == 0 ) {
1493 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1496 if( isset( $limits['user'] ) && $id != 0 ) {
1497 $userLimit = $limits['user'];
1499 if( $this->isNewbie() ) {
1500 if( isset( $limits['newbie'] ) && $id != 0 ) {
1501 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1503 if( isset( $limits['ip'] ) ) {
1504 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1507 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1508 $subnet = $matches[1];
1509 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1512 // Check for group-specific permissions
1513 // If more than one group applies, use the group with the highest limit
1514 foreach ( $this->getGroups() as $group ) {
1515 if ( isset( $limits[$group] ) ) {
1516 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1517 $userLimit = $limits[$group];
1521 // Set the user limit key
1522 if ( $userLimit !== false ) {
1523 wfDebug( __METHOD__
. ": effective user limit: $userLimit\n" );
1524 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1528 foreach( $keys as $key => $limit ) {
1529 list( $max, $period ) = $limit;
1530 $summary = "(limit $max in {$period}s)";
1531 $count = $wgMemc->get( $key );
1534 if( $count >= $max ) {
1535 wfDebug( __METHOD__
. ": tripped! $key at $count $summary\n" );
1536 if( $wgRateLimitLog ) {
1537 wfSuppressWarnings();
1538 file_put_contents( $wgRateLimitLog, wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", FILE_APPEND
);
1539 wfRestoreWarnings();
1543 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1546 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1547 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1549 $wgMemc->incr( $key );
1552 wfProfileOut( __METHOD__
);
1557 * Check if user is blocked
1559 * @param $bFromSlave Bool Whether to check the slave database instead of the master
1560 * @return Bool True if blocked, false otherwise
1562 public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1563 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1567 * Get the block affecting the user, or null if the user is not blocked
1569 * @param $bFromSlave Bool Whether to check the slave database instead of the master
1570 * @return Block|null
1572 public function getBlock( $bFromSlave = true ){
1573 $this->getBlockedStatus( $bFromSlave );
1574 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1578 * Check if user is blocked from editing a particular article
1580 * @param $title Title to check
1581 * @param $bFromSlave Bool whether to check the slave database instead of the master
1584 function isBlockedFrom( $title, $bFromSlave = false ) {
1585 global $wgBlockAllowsUTEdit;
1586 wfProfileIn( __METHOD__
);
1588 $blocked = $this->isBlocked( $bFromSlave );
1589 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1590 # If a user's name is suppressed, they cannot make edits anywhere
1591 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1592 $title->getNamespace() == NS_USER_TALK
) {
1594 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1597 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1599 wfProfileOut( __METHOD__
);
1604 * If user is blocked, return the name of the user who placed the block
1605 * @return String name of blocker
1607 public function blockedBy() {
1608 $this->getBlockedStatus();
1609 return $this->mBlockedby
;
1613 * If user is blocked, return the specified reason for the block
1614 * @return String Blocking reason
1616 public function blockedFor() {
1617 $this->getBlockedStatus();
1618 return $this->mBlockreason
;
1622 * If user is blocked, return the ID for the block
1623 * @return Int Block ID
1625 public function getBlockId() {
1626 $this->getBlockedStatus();
1627 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1631 * Check if user is blocked on all wikis.
1632 * Do not use for actual edit permission checks!
1633 * This is intented for quick UI checks.
1635 * @param $ip String IP address, uses current client if none given
1636 * @return Bool True if blocked, false otherwise
1638 public function isBlockedGlobally( $ip = '' ) {
1639 if( $this->mBlockedGlobally
!== null ) {
1640 return $this->mBlockedGlobally
;
1642 // User is already an IP?
1643 if( IP
::isIPAddress( $this->getName() ) ) {
1644 $ip = $this->getName();
1646 $ip = $this->getRequest()->getIP();
1649 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1650 $this->mBlockedGlobally
= (bool)$blocked;
1651 return $this->mBlockedGlobally
;
1655 * Check if user account is locked
1657 * @return Bool True if locked, false otherwise
1659 public function isLocked() {
1660 if( $this->mLocked
!== null ) {
1661 return $this->mLocked
;
1664 $authUser = $wgAuth->getUserInstance( $this );
1665 $this->mLocked
= (bool)$authUser->isLocked();
1666 return $this->mLocked
;
1670 * Check if user account is hidden
1672 * @return Bool True if hidden, false otherwise
1674 public function isHidden() {
1675 if( $this->mHideName
!== null ) {
1676 return $this->mHideName
;
1678 $this->getBlockedStatus();
1679 if( !$this->mHideName
) {
1681 $authUser = $wgAuth->getUserInstance( $this );
1682 $this->mHideName
= (bool)$authUser->isHidden();
1684 return $this->mHideName
;
1688 * Get the user's ID.
1689 * @return Int The user's ID; 0 if the user is anonymous or nonexistent
1691 public function getId() {
1692 if( $this->mId
=== null && $this->mName
!== null
1693 && User
::isIP( $this->mName
) ) {
1694 // Special case, we know the user is anonymous
1696 } elseif( !$this->isItemLoaded( 'id' ) ) {
1697 // Don't load if this was initialized from an ID
1704 * Set the user and reload all fields according to a given ID
1705 * @param $v Int User ID to reload
1707 public function setId( $v ) {
1709 $this->clearInstanceCache( 'id' );
1713 * Get the user name, or the IP of an anonymous user
1714 * @return String User's name or IP address
1716 public function getName() {
1717 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1718 # Special case optimisation
1719 return $this->mName
;
1722 if ( $this->mName
=== false ) {
1724 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1726 return $this->mName
;
1731 * Set the user name.
1733 * This does not reload fields from the database according to the given
1734 * name. Rather, it is used to create a temporary "nonexistent user" for
1735 * later addition to the database. It can also be used to set the IP
1736 * address for an anonymous user to something other than the current
1739 * @note User::newFromName() has rougly the same function, when the named user
1741 * @param $str String New user name to set
1743 public function setName( $str ) {
1745 $this->mName
= $str;
1749 * Get the user's name escaped by underscores.
1750 * @return String Username escaped by underscores.
1752 public function getTitleKey() {
1753 return str_replace( ' ', '_', $this->getName() );
1757 * Check if the user has new messages.
1758 * @return Bool True if the user has new messages
1760 public function getNewtalk() {
1763 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1764 if( $this->mNewtalk
=== -1 ) {
1765 $this->mNewtalk
= false; # reset talk page status
1767 # Check memcached separately for anons, who have no
1768 # entire User object stored in there.
1771 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1772 $newtalk = $wgMemc->get( $key );
1773 if( strval( $newtalk ) !== '' ) {
1774 $this->mNewtalk
= (bool)$newtalk;
1776 // Since we are caching this, make sure it is up to date by getting it
1778 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1779 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1782 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1786 return (bool)$this->mNewtalk
;
1790 * Return the talk page(s) this user has new messages on.
1791 * @return Array of String page URLs
1793 public function getNewMessageLinks() {
1795 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
1797 } elseif( !$this->getNewtalk() ) {
1800 $utp = $this->getTalkPage();
1801 $dbr = wfGetDB( DB_SLAVE
);
1802 // Get the "last viewed rev" timestamp from the oldest message notification
1803 $timestamp = $dbr->selectField( 'user_newtalk',
1804 'MIN(user_last_timestamp)',
1805 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
1807 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
1808 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
1812 * Internal uncached check for new messages
1815 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1816 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1817 * @param $fromMaster Bool true to fetch from the master, false for a slave
1818 * @return Bool True if the user has new messages
1820 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
1821 if ( $fromMaster ) {
1822 $db = wfGetDB( DB_MASTER
);
1824 $db = wfGetDB( DB_SLAVE
);
1826 $ok = $db->selectField( 'user_newtalk', $field,
1827 array( $field => $id ), __METHOD__
);
1828 return $ok !== false;
1832 * Add or update the new messages flag
1833 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1834 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1835 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null.
1836 * @return Bool True if successful, false otherwise
1838 protected function updateNewtalk( $field, $id, $curRev = null ) {
1839 // Get timestamp of the talk page revision prior to the current one
1840 $prevRev = $curRev ?
$curRev->getPrevious() : false;
1841 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
1842 // Mark the user as having new messages since this revision
1843 $dbw = wfGetDB( DB_MASTER
);
1844 $dbw->insert( 'user_newtalk',
1845 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
1848 if ( $dbw->affectedRows() ) {
1849 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
1852 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
1858 * Clear the new messages flag for the given user
1859 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1860 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1861 * @return Bool True if successful, false otherwise
1863 protected function deleteNewtalk( $field, $id ) {
1864 $dbw = wfGetDB( DB_MASTER
);
1865 $dbw->delete( 'user_newtalk',
1866 array( $field => $id ),
1868 if ( $dbw->affectedRows() ) {
1869 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
1872 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
1878 * Update the 'You have new messages!' status.
1879 * @param $val Bool Whether the user has new messages
1880 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null or !$val.
1882 public function setNewtalk( $val, $curRev = null ) {
1883 if( wfReadOnly() ) {
1888 $this->mNewtalk
= $val;
1890 if( $this->isAnon() ) {
1892 $id = $this->getName();
1895 $id = $this->getId();
1900 $changed = $this->updateNewtalk( $field, $id, $curRev );
1902 $changed = $this->deleteNewtalk( $field, $id );
1905 if( $this->isAnon() ) {
1906 // Anons have a separate memcached space, since
1907 // user records aren't kept for them.
1908 $key = wfMemcKey( 'newtalk', 'ip', $id );
1909 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1912 $this->invalidateCache();
1917 * Generate a current or new-future timestamp to be stored in the
1918 * user_touched field when we update things.
1919 * @return String Timestamp in TS_MW format
1921 private static function newTouchedTimestamp() {
1922 global $wgClockSkewFudge;
1923 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1927 * Clear user data from memcached.
1928 * Use after applying fun updates to the database; caller's
1929 * responsibility to update user_touched if appropriate.
1931 * Called implicitly from invalidateCache() and saveSettings().
1933 private function clearSharedCache() {
1937 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1942 * Immediately touch the user data cache for this account.
1943 * Updates user_touched field, and removes account data from memcached
1944 * for reload on the next hit.
1946 public function invalidateCache() {
1947 if( wfReadOnly() ) {
1952 $this->mTouched
= self
::newTouchedTimestamp();
1954 $dbw = wfGetDB( DB_MASTER
);
1956 // Prevent contention slams by checking user_touched first
1957 $now = $dbw->timestamp( $this->mTouched
);
1958 $needsPurge = $dbw->selectField( 'user', '1',
1959 array( 'user_id' => $this->mId
, 'user_touched < ' . $dbw->addQuotes( $now ) )
1961 if ( $needsPurge ) {
1962 $dbw->update( 'user',
1963 array( 'user_touched' => $now ),
1964 array( 'user_id' => $this->mId
, 'user_touched < ' . $dbw->addQuotes( $now ) ),
1969 $this->clearSharedCache();
1974 * Validate the cache for this account.
1975 * @param $timestamp String A timestamp in TS_MW format
1979 public function validateCache( $timestamp ) {
1981 return ( $timestamp >= $this->mTouched
);
1985 * Get the user touched timestamp
1986 * @return String timestamp
1988 public function getTouched() {
1990 return $this->mTouched
;
1994 * Set the password and reset the random token.
1995 * Calls through to authentication plugin if necessary;
1996 * will have no effect if the auth plugin refuses to
1997 * pass the change through or if the legal password
2000 * As a special case, setting the password to null
2001 * wipes it, so the account cannot be logged in until
2002 * a new password is set, for instance via e-mail.
2004 * @param $str String New password to set
2005 * @throws PasswordError on failure
2009 public function setPassword( $str ) {
2012 if( $str !== null ) {
2013 if( !$wgAuth->allowPasswordChange() ) {
2014 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
2017 if( !$this->isValidPassword( $str ) ) {
2018 global $wgMinimalPasswordLength;
2019 $valid = $this->getPasswordValidity( $str );
2020 if ( is_array( $valid ) ) {
2021 $message = array_shift( $valid );
2025 $params = array( $wgMinimalPasswordLength );
2027 throw new PasswordError( wfMsgExt( $message, array( 'parsemag' ), $params ) );
2031 if( !$wgAuth->setPassword( $this, $str ) ) {
2032 throw new PasswordError( wfMsg( 'externaldberror' ) );
2035 $this->setInternalPassword( $str );
2041 * Set the password and reset the random token unconditionally.
2043 * @param $str String New password to set
2045 public function setInternalPassword( $str ) {
2049 if( $str === null ) {
2050 // Save an invalid hash...
2051 $this->mPassword
= '';
2053 $this->mPassword
= self
::crypt( $str );
2055 $this->mNewpassword
= '';
2056 $this->mNewpassTime
= null;
2060 * Get the user's current token.
2061 * @param $forceCreation Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility)
2062 * @return String Token
2064 public function getToken( $forceCreation = true ) {
2066 if ( !$this->mToken
&& $forceCreation ) {
2069 return $this->mToken
;
2073 * Set the random token (used for persistent authentication)
2074 * Called from loadDefaults() among other places.
2076 * @param $token String|bool If specified, set the token to this value
2078 public function setToken( $token = false ) {
2081 $this->mToken
= MWCryptRand
::generateHex( USER_TOKEN_LENGTH
);
2083 $this->mToken
= $token;
2088 * Set the password for a password reminder or new account email
2090 * @param $str String New password to set
2091 * @param $throttle Bool If true, reset the throttle timestamp to the present
2093 public function setNewpassword( $str, $throttle = true ) {
2095 $this->mNewpassword
= self
::crypt( $str );
2097 $this->mNewpassTime
= wfTimestampNow();
2102 * Has password reminder email been sent within the last
2103 * $wgPasswordReminderResendTime hours?
2106 public function isPasswordReminderThrottled() {
2107 global $wgPasswordReminderResendTime;
2109 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2112 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2113 return time() < $expiry;
2117 * Get the user's e-mail address
2118 * @return String User's email address
2120 public function getEmail() {
2122 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
2123 return $this->mEmail
;
2127 * Get the timestamp of the user's e-mail authentication
2128 * @return String TS_MW timestamp
2130 public function getEmailAuthenticationTimestamp() {
2132 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2133 return $this->mEmailAuthenticated
;
2137 * Set the user's e-mail address
2138 * @param $str String New e-mail address
2140 public function setEmail( $str ) {
2142 if( $str == $this->mEmail
) {
2145 $this->mEmail
= $str;
2146 $this->invalidateEmail();
2147 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
2151 * Set the user's e-mail address and a confirmation mail if needed.
2154 * @param $str String New e-mail address
2157 public function setEmailWithConfirmation( $str ) {
2158 global $wgEnableEmail, $wgEmailAuthentication;
2160 if ( !$wgEnableEmail ) {
2161 return Status
::newFatal( 'emaildisabled' );
2164 $oldaddr = $this->getEmail();
2165 if ( $str === $oldaddr ) {
2166 return Status
::newGood( true );
2169 $this->setEmail( $str );
2171 if ( $str !== '' && $wgEmailAuthentication ) {
2172 # Send a confirmation request to the new address if needed
2173 $type = $oldaddr != '' ?
'changed' : 'set';
2174 $result = $this->sendConfirmationMail( $type );
2175 if ( $result->isGood() ) {
2176 # Say the the caller that a confirmation mail has been sent
2177 $result->value
= 'eauth';
2180 $result = Status
::newGood( true );
2187 * Get the user's real name
2188 * @return String User's real name
2190 public function getRealName() {
2191 if ( !$this->isItemLoaded( 'realname' ) ) {
2195 return $this->mRealName
;
2199 * Set the user's real name
2200 * @param $str String New real name
2202 public function setRealName( $str ) {
2204 $this->mRealName
= $str;
2208 * Get the user's current setting for a given option.
2210 * @param $oname String The option to check
2211 * @param $defaultOverride String A default value returned if the option does not exist
2212 * @param $ignoreHidden Bool = whether to ignore the effects of $wgHiddenPrefs
2213 * @return String User's current value for the option
2214 * @see getBoolOption()
2215 * @see getIntOption()
2217 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2218 global $wgHiddenPrefs;
2219 $this->loadOptions();
2221 if ( is_null( $this->mOptions
) ) {
2222 if($defaultOverride != '') {
2223 return $defaultOverride;
2225 $this->mOptions
= User
::getDefaultOptions();
2228 # We want 'disabled' preferences to always behave as the default value for
2229 # users, even if they have set the option explicitly in their settings (ie they
2230 # set it, and then it was disabled removing their ability to change it). But
2231 # we don't want to erase the preferences in the database in case the preference
2232 # is re-enabled again. So don't touch $mOptions, just override the returned value
2233 if( in_array( $oname, $wgHiddenPrefs ) && !$ignoreHidden ){
2234 return self
::getDefaultOption( $oname );
2237 if ( array_key_exists( $oname, $this->mOptions
) ) {
2238 return $this->mOptions
[$oname];
2240 return $defaultOverride;
2245 * Get all user's options
2249 public function getOptions() {
2250 global $wgHiddenPrefs;
2251 $this->loadOptions();
2252 $options = $this->mOptions
;
2254 # We want 'disabled' preferences to always behave as the default value for
2255 # users, even if they have set the option explicitly in their settings (ie they
2256 # set it, and then it was disabled removing their ability to change it). But
2257 # we don't want to erase the preferences in the database in case the preference
2258 # is re-enabled again. So don't touch $mOptions, just override the returned value
2259 foreach( $wgHiddenPrefs as $pref ){
2260 $default = self
::getDefaultOption( $pref );
2261 if( $default !== null ){
2262 $options[$pref] = $default;
2270 * Get the user's current setting for a given option, as a boolean value.
2272 * @param $oname String The option to check
2273 * @return Bool User's current value for the option
2276 public function getBoolOption( $oname ) {
2277 return (bool)$this->getOption( $oname );
2281 * Get the user's current setting for a given option, as a boolean value.
2283 * @param $oname String The option to check
2284 * @param $defaultOverride Int A default value returned if the option does not exist
2285 * @return Int User's current value for the option
2288 public function getIntOption( $oname, $defaultOverride=0 ) {
2289 $val = $this->getOption( $oname );
2291 $val = $defaultOverride;
2293 return intval( $val );
2297 * Set the given option for a user.
2299 * @param $oname String The option to set
2300 * @param $val mixed New value to set
2302 public function setOption( $oname, $val ) {
2304 $this->loadOptions();
2306 // Explicitly NULL values should refer to defaults
2307 if( is_null( $val ) ) {
2308 $defaultOption = self
::getDefaultOption( $oname );
2309 if( !is_null( $defaultOption ) ) {
2310 $val = $defaultOption;
2314 $this->mOptions
[$oname] = $val;
2318 * Reset all options to the site defaults
2320 public function resetOptions() {
2323 $this->mOptions
= self
::getDefaultOptions();
2324 $this->mOptionsLoaded
= true;
2328 * Get the user's preferred date format.
2329 * @return String User's preferred date format
2331 public function getDatePreference() {
2332 // Important migration for old data rows
2333 if ( is_null( $this->mDatePreference
) ) {
2335 $value = $this->getOption( 'date' );
2336 $map = $wgLang->getDatePreferenceMigrationMap();
2337 if ( isset( $map[$value] ) ) {
2338 $value = $map[$value];
2340 $this->mDatePreference
= $value;
2342 return $this->mDatePreference
;
2346 * Get the user preferred stub threshold
2350 public function getStubThreshold() {
2351 global $wgMaxArticleSize; # Maximum article size, in Kb
2352 $threshold = intval( $this->getOption( 'stubthreshold' ) );
2353 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2354 # If they have set an impossible value, disable the preference
2355 # so we can use the parser cache again.
2362 * Get the permissions this user has.
2363 * @return Array of String permission names
2365 public function getRights() {
2366 if ( is_null( $this->mRights
) ) {
2367 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2368 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2369 // Force reindexation of rights when a hook has unset one of them
2370 $this->mRights
= array_values( $this->mRights
);
2372 return $this->mRights
;
2376 * Get the list of explicit group memberships this user has.
2377 * The implicit * and user groups are not included.
2378 * @return Array of String internal group names
2380 public function getGroups() {
2382 $this->loadGroups();
2383 return $this->mGroups
;
2387 * Get the list of implicit group memberships this user has.
2388 * This includes all explicit groups, plus 'user' if logged in,
2389 * '*' for all accounts, and autopromoted groups
2390 * @param $recache Bool Whether to avoid the cache
2391 * @return Array of String internal group names
2393 public function getEffectiveGroups( $recache = false ) {
2394 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2395 wfProfileIn( __METHOD__
);
2396 $this->mEffectiveGroups
= array_unique( array_merge(
2397 $this->getGroups(), // explicit groups
2398 $this->getAutomaticGroups( $recache ) // implicit groups
2400 # Hook for additional groups
2401 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2402 wfProfileOut( __METHOD__
);
2404 return $this->mEffectiveGroups
;
2408 * Get the list of implicit group memberships this user has.
2409 * This includes 'user' if logged in, '*' for all accounts,
2410 * and autopromoted groups
2411 * @param $recache Bool Whether to avoid the cache
2412 * @return Array of String internal group names
2414 public function getAutomaticGroups( $recache = false ) {
2415 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
2416 wfProfileIn( __METHOD__
);
2417 $this->mImplicitGroups
= array( '*' );
2418 if ( $this->getId() ) {
2419 $this->mImplicitGroups
[] = 'user';
2421 $this->mImplicitGroups
= array_unique( array_merge(
2422 $this->mImplicitGroups
,
2423 Autopromote
::getAutopromoteGroups( $this )
2427 # Assure data consistency with rights/groups,
2428 # as getEffectiveGroups() depends on this function
2429 $this->mEffectiveGroups
= null;
2431 wfProfileOut( __METHOD__
);
2433 return $this->mImplicitGroups
;
2437 * Returns the groups the user has belonged to.
2439 * The user may still belong to the returned groups. Compare with getGroups().
2441 * The function will not return groups the user had belonged to before MW 1.17
2443 * @return array Names of the groups the user has belonged to.
2445 public function getFormerGroups() {
2446 if( is_null( $this->mFormerGroups
) ) {
2447 $dbr = wfGetDB( DB_MASTER
);
2448 $res = $dbr->select( 'user_former_groups',
2449 array( 'ufg_group' ),
2450 array( 'ufg_user' => $this->mId
),
2452 $this->mFormerGroups
= array();
2453 foreach( $res as $row ) {
2454 $this->mFormerGroups
[] = $row->ufg_group
;
2457 return $this->mFormerGroups
;
2461 * Get the user's edit count.
2464 public function getEditCount() {
2465 if( $this->getId() ) {
2466 if ( !isset( $this->mEditCount
) ) {
2467 /* Populate the count, if it has not been populated yet */
2468 $this->mEditCount
= User
::edits( $this->mId
);
2470 return $this->mEditCount
;
2478 * Add the user to the given group.
2479 * This takes immediate effect.
2480 * @param $group String Name of the group to add
2482 public function addGroup( $group ) {
2483 if( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2484 $dbw = wfGetDB( DB_MASTER
);
2485 if( $this->getId() ) {
2486 $dbw->insert( 'user_groups',
2488 'ug_user' => $this->getID(),
2489 'ug_group' => $group,
2492 array( 'IGNORE' ) );
2495 $this->loadGroups();
2496 $this->mGroups
[] = $group;
2497 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2499 $this->invalidateCache();
2503 * Remove the user from the given group.
2504 * This takes immediate effect.
2505 * @param $group String Name of the group to remove
2507 public function removeGroup( $group ) {
2509 if( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2510 $dbw = wfGetDB( DB_MASTER
);
2511 $dbw->delete( 'user_groups',
2513 'ug_user' => $this->getID(),
2514 'ug_group' => $group,
2516 // Remember that the user was in this group
2517 $dbw->insert( 'user_former_groups',
2519 'ufg_user' => $this->getID(),
2520 'ufg_group' => $group,
2523 array( 'IGNORE' ) );
2525 $this->loadGroups();
2526 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2527 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2529 $this->invalidateCache();
2533 * Get whether the user is logged in
2536 public function isLoggedIn() {
2537 return $this->getID() != 0;
2541 * Get whether the user is anonymous
2544 public function isAnon() {
2545 return !$this->isLoggedIn();
2549 * Check if user is allowed to access a feature / make an action
2551 * @internal param \String $varargs permissions to test
2552 * @return Boolean: True if user is allowed to perform *any* of the given actions
2556 public function isAllowedAny( /*...*/ ){
2557 $permissions = func_get_args();
2558 foreach( $permissions as $permission ){
2559 if( $this->isAllowed( $permission ) ){
2568 * @internal param $varargs string
2569 * @return bool True if the user is allowed to perform *all* of the given actions
2571 public function isAllowedAll( /*...*/ ){
2572 $permissions = func_get_args();
2573 foreach( $permissions as $permission ){
2574 if( !$this->isAllowed( $permission ) ){
2582 * Internal mechanics of testing a permission
2583 * @param $action String
2586 public function isAllowed( $action = '' ) {
2587 if ( $action === '' ) {
2588 return true; // In the spirit of DWIM
2590 # Patrolling may not be enabled
2591 if( $action === 'patrol' ||
$action === 'autopatrol' ) {
2592 global $wgUseRCPatrol, $wgUseNPPatrol;
2593 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2596 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2597 # by misconfiguration: 0 == 'foo'
2598 return in_array( $action, $this->getRights(), true );
2602 * Check whether to enable recent changes patrol features for this user
2603 * @return Boolean: True or false
2605 public function useRCPatrol() {
2606 global $wgUseRCPatrol;
2607 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
2611 * Check whether to enable new pages patrol features for this user
2612 * @return Bool True or false
2614 public function useNPPatrol() {
2615 global $wgUseRCPatrol, $wgUseNPPatrol;
2616 return( ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) ) );
2620 * Get the WebRequest object to use with this object
2622 * @return WebRequest
2624 public function getRequest() {
2625 if ( $this->mRequest
) {
2626 return $this->mRequest
;
2634 * Get the current skin, loading it if required
2635 * @return Skin The current skin
2636 * @todo FIXME: Need to check the old failback system [AV]
2637 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
2639 public function getSkin() {
2640 wfDeprecated( __METHOD__
, '1.18' );
2641 return RequestContext
::getMain()->getSkin();
2645 * Get a WatchedItem for this user and $title.
2647 * @param $title Title
2648 * @return WatchedItem
2650 public function getWatchedItem( $title ) {
2651 $key = $title->getNamespace() . ':' . $title->getDBkey();
2653 if ( isset( $this->mWatchedItems
[$key] ) ) {
2654 return $this->mWatchedItems
[$key];
2657 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
2658 $this->mWatchedItems
= array();
2661 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title );
2662 return $this->mWatchedItems
[$key];
2666 * Check the watched status of an article.
2667 * @param $title Title of the article to look at
2670 public function isWatched( $title ) {
2671 return $this->getWatchedItem( $title )->isWatched();
2676 * @param $title Title of the article to look at
2678 public function addWatch( $title ) {
2679 $this->getWatchedItem( $title )->addWatch();
2680 $this->invalidateCache();
2684 * Stop watching an article.
2685 * @param $title Title of the article to look at
2687 public function removeWatch( $title ) {
2688 $this->getWatchedItem( $title )->removeWatch();
2689 $this->invalidateCache();
2693 * Clear the user's notification timestamp for the given title.
2694 * If e-notif e-mails are on, they will receive notification mails on
2695 * the next change of the page if it's watched etc.
2696 * @param $title Title of the article to look at
2698 public function clearNotification( &$title ) {
2699 global $wgUseEnotif, $wgShowUpdatedMarker;
2701 # Do nothing if the database is locked to writes
2702 if( wfReadOnly() ) {
2706 if( $title->getNamespace() == NS_USER_TALK
&&
2707 $title->getText() == $this->getName() ) {
2708 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2710 $this->setNewtalk( false );
2713 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2717 if( $this->isAnon() ) {
2718 // Nothing else to do...
2722 // Only update the timestamp if the page is being watched.
2723 // The query to find out if it is watched is cached both in memcached and per-invocation,
2724 // and when it does have to be executed, it can be on a slave
2725 // If this is the user's newtalk page, we always update the timestamp
2727 if ( $title->getNamespace() == NS_USER_TALK
&&
2728 $title->getText() == $this->getName() )
2733 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force );
2737 * Resets all of the given user's page-change notification timestamps.
2738 * If e-notif e-mails are on, they will receive notification mails on
2739 * the next change of any watched page.
2741 public function clearAllNotifications() {
2742 global $wgUseEnotif, $wgShowUpdatedMarker;
2743 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2744 $this->setNewtalk( false );
2747 $id = $this->getId();
2749 $dbw = wfGetDB( DB_MASTER
);
2750 $dbw->update( 'watchlist',
2752 'wl_notificationtimestamp' => null
2753 ), array( /* WHERE */
2757 # We also need to clear here the "you have new message" notification for the own user_talk page
2758 # This is cleared one page view later in Article::viewUpdates();
2763 * Set this user's options from an encoded string
2764 * @param $str String Encoded options to import
2766 * @deprecated in 1.19 due to removal of user_options from the user table
2768 private function decodeOptions( $str ) {
2769 wfDeprecated( __METHOD__
, '1.19' );
2773 $this->mOptionsLoaded
= true;
2774 $this->mOptionOverrides
= array();
2776 // If an option is not set in $str, use the default value
2777 $this->mOptions
= self
::getDefaultOptions();
2779 $a = explode( "\n", $str );
2780 foreach ( $a as $s ) {
2782 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2783 $this->mOptions
[$m[1]] = $m[2];
2784 $this->mOptionOverrides
[$m[1]] = $m[2];
2790 * Set a cookie on the user's client. Wrapper for
2791 * WebResponse::setCookie
2792 * @param $name String Name of the cookie to set
2793 * @param $value String Value to set
2794 * @param $exp Int Expiration time, as a UNIX time value;
2795 * if 0 or not specified, use the default $wgCookieExpiration
2797 protected function setCookie( $name, $value, $exp = 0 ) {
2798 $this->getRequest()->response()->setcookie( $name, $value, $exp );
2802 * Clear a cookie on the user's client
2803 * @param $name String Name of the cookie to clear
2805 protected function clearCookie( $name ) {
2806 $this->setCookie( $name, '', time() - 86400 );
2810 * Set the default cookies for this session on the user's client.
2812 * @param $request WebRequest object to use; $wgRequest will be used if null
2815 public function setCookies( $request = null ) {
2816 if ( $request === null ) {
2817 $request = $this->getRequest();
2821 if ( 0 == $this->mId
) return;
2822 if ( !$this->mToken
) {
2823 // When token is empty or NULL generate a new one and then save it to the database
2824 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
2825 // Simply by setting every cell in the user_token column to NULL and letting them be
2826 // regenerated as users log back into the wiki.
2828 $this->saveSettings();
2831 'wsUserID' => $this->mId
,
2832 'wsToken' => $this->mToken
,
2833 'wsUserName' => $this->getName()
2836 'UserID' => $this->mId
,
2837 'UserName' => $this->getName(),
2839 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2840 $cookies['Token'] = $this->mToken
;
2842 $cookies['Token'] = false;
2845 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2847 foreach ( $session as $name => $value ) {
2848 $request->setSessionData( $name, $value );
2850 foreach ( $cookies as $name => $value ) {
2851 if ( $value === false ) {
2852 $this->clearCookie( $name );
2854 $this->setCookie( $name, $value );
2860 * Log this user out.
2862 public function logout() {
2863 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
2869 * Clear the user's cookies and session, and reset the instance cache.
2872 public function doLogout() {
2873 $this->clearInstanceCache( 'defaults' );
2875 $this->getRequest()->setSessionData( 'wsUserID', 0 );
2877 $this->clearCookie( 'UserID' );
2878 $this->clearCookie( 'Token' );
2880 # Remember when user logged out, to prevent seeing cached pages
2881 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2885 * Save this user's settings into the database.
2886 * @todo Only rarely do all these fields need to be set!
2888 public function saveSettings() {
2890 if ( wfReadOnly() ) { return; }
2891 if ( 0 == $this->mId
) { return; }
2893 $this->mTouched
= self
::newTouchedTimestamp();
2895 $dbw = wfGetDB( DB_MASTER
);
2896 $dbw->update( 'user',
2898 'user_name' => $this->mName
,
2899 'user_password' => $this->mPassword
,
2900 'user_newpassword' => $this->mNewpassword
,
2901 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2902 'user_real_name' => $this->mRealName
,
2903 'user_email' => $this->mEmail
,
2904 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2905 'user_touched' => $dbw->timestamp( $this->mTouched
),
2906 'user_token' => strval( $this->mToken
),
2907 'user_email_token' => $this->mEmailToken
,
2908 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2909 ), array( /* WHERE */
2910 'user_id' => $this->mId
2914 $this->saveOptions();
2916 wfRunHooks( 'UserSaveSettings', array( $this ) );
2917 $this->clearSharedCache();
2918 $this->getUserPage()->invalidateCache();
2922 * If only this user's username is known, and it exists, return the user ID.
2925 public function idForName() {
2926 $s = trim( $this->getName() );
2927 if ( $s === '' ) return 0;
2929 $dbr = wfGetDB( DB_SLAVE
);
2930 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2931 if ( $id === false ) {
2938 * Add a user to the database, return the user object
2940 * @param $name String Username to add
2941 * @param $params Array of Strings Non-default parameters to save to the database as user_* fields:
2942 * - password The user's password hash. Password logins will be disabled if this is omitted.
2943 * - newpassword Hash for a temporary password that has been mailed to the user
2944 * - email The user's email address
2945 * - email_authenticated The email authentication timestamp
2946 * - real_name The user's real name
2947 * - options An associative array of non-default options
2948 * - token Random authentication token. Do not set.
2949 * - registration Registration timestamp. Do not set.
2951 * @return User object, or null if the username already exists
2953 public static function createNew( $name, $params = array() ) {
2956 if ( isset( $params['options'] ) ) {
2957 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
2958 unset( $params['options'] );
2960 $dbw = wfGetDB( DB_MASTER
);
2961 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2964 'user_id' => $seqVal,
2965 'user_name' => $name,
2966 'user_password' => $user->mPassword
,
2967 'user_newpassword' => $user->mNewpassword
,
2968 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
2969 'user_email' => $user->mEmail
,
2970 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2971 'user_real_name' => $user->mRealName
,
2972 'user_token' => strval( $user->mToken
),
2973 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2974 'user_editcount' => 0,
2975 'user_touched' => $dbw->timestamp( self
::newTouchedTimestamp() ),
2977 foreach ( $params as $name => $value ) {
2978 $fields["user_$name"] = $value;
2980 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2981 if ( $dbw->affectedRows() ) {
2982 $newUser = User
::newFromId( $dbw->insertId() );
2990 * Add this existing user object to the database
2992 public function addToDatabase() {
2995 $this->mTouched
= self
::newTouchedTimestamp();
2997 $dbw = wfGetDB( DB_MASTER
);
2998 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2999 $dbw->insert( 'user',
3001 'user_id' => $seqVal,
3002 'user_name' => $this->mName
,
3003 'user_password' => $this->mPassword
,
3004 'user_newpassword' => $this->mNewpassword
,
3005 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3006 'user_email' => $this->mEmail
,
3007 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3008 'user_real_name' => $this->mRealName
,
3009 'user_token' => strval( $this->mToken
),
3010 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3011 'user_editcount' => 0,
3012 'user_touched' => $dbw->timestamp( $this->mTouched
),
3015 $this->mId
= $dbw->insertId();
3017 // Clear instance cache other than user table data, which is already accurate
3018 $this->clearInstanceCache();
3020 $this->saveOptions();
3024 * If this user is logged-in and blocked,
3025 * block any IP address they've successfully logged in from.
3026 * @return bool A block was spread
3028 public function spreadAnyEditBlock() {
3029 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3030 return $this->spreadBlock();
3036 * If this (non-anonymous) user is blocked,
3037 * block the IP address they've successfully logged in from.
3038 * @return bool A block was spread
3040 protected function spreadBlock() {
3041 wfDebug( __METHOD__
. "()\n" );
3043 if ( $this->mId
== 0 ) {
3047 $userblock = Block
::newFromTarget( $this->getName() );
3048 if ( !$userblock ) {
3052 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3056 * Generate a string which will be different for any combination of
3057 * user options which would produce different parser output.
3058 * This will be used as part of the hash key for the parser cache,
3059 * so users with the same options can share the same cached data
3062 * Extensions which require it should install 'PageRenderingHash' hook,
3063 * which will give them a chance to modify this key based on their own
3066 * @deprecated since 1.17 use the ParserOptions object to get the relevant options
3067 * @return String Page rendering hash
3069 public function getPageRenderingHash() {
3070 wfDeprecated( __METHOD__
, '1.17' );
3072 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
3074 return $this->mHash
;
3077 // stubthreshold is only included below for completeness,
3078 // since it disables the parser cache, its value will always
3079 // be 0 when this function is called by parsercache.
3081 $confstr = $this->getOption( 'math' );
3082 $confstr .= '!' . $this->getStubThreshold();
3083 if ( $wgUseDynamicDates ) { # This is wrong (bug 24714)
3084 $confstr .= '!' . $this->getDatePreference();
3086 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ?
'1' : '' );
3087 $confstr .= '!' . $wgLang->getCode();
3088 $confstr .= '!' . $this->getOption( 'thumbsize' );
3089 // add in language specific options, if any
3090 $extra = $wgContLang->getExtraHashOptions();
3093 // Since the skin could be overloading link(), it should be
3094 // included here but in practice, none of our skins do that.
3096 $confstr .= $wgRenderHashAppend;
3098 // Give a chance for extensions to modify the hash, if they have
3099 // extra options or other effects on the parser cache.
3100 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
3102 // Make it a valid memcached key fragment
3103 $confstr = str_replace( ' ', '_', $confstr );
3104 $this->mHash
= $confstr;
3109 * Get whether the user is explicitly blocked from account creation.
3110 * @return Bool|Block
3112 public function isBlockedFromCreateAccount() {
3113 $this->getBlockedStatus();
3114 if( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ){
3115 return $this->mBlock
;
3118 # bug 13611: if the IP address the user is trying to create an account from is
3119 # blocked with createaccount disabled, prevent new account creation there even
3120 # when the user is logged in
3121 if( $this->mBlockedFromCreateAccount
=== false ){
3122 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3124 return $this->mBlockedFromCreateAccount
instanceof Block
&& $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3125 ?
$this->mBlockedFromCreateAccount
3130 * Get whether the user is blocked from using Special:Emailuser.
3133 public function isBlockedFromEmailuser() {
3134 $this->getBlockedStatus();
3135 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3139 * Get whether the user is allowed to create an account.
3142 function isAllowedToCreateAccount() {
3143 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3147 * Get this user's personal page title.
3149 * @return Title: User's personal page title
3151 public function getUserPage() {
3152 return Title
::makeTitle( NS_USER
, $this->getName() );
3156 * Get this user's talk page title.
3158 * @return Title: User's talk page title
3160 public function getTalkPage() {
3161 $title = $this->getUserPage();
3162 return $title->getTalkPage();
3166 * Determine whether the user is a newbie. Newbies are either
3167 * anonymous IPs, or the most recently created accounts.
3170 public function isNewbie() {
3171 return !$this->isAllowed( 'autoconfirmed' );
3175 * Check to see if the given clear-text password is one of the accepted passwords
3176 * @param $password String: user password.
3177 * @return Boolean: True if the given password is correct, otherwise False.
3179 public function checkPassword( $password ) {
3180 global $wgAuth, $wgLegacyEncoding;
3183 // Even though we stop people from creating passwords that
3184 // are shorter than this, doesn't mean people wont be able
3185 // to. Certain authentication plugins do NOT want to save
3186 // domain passwords in a mysql database, so we should
3187 // check this (in case $wgAuth->strict() is false).
3188 if( !$this->isValidPassword( $password ) ) {
3192 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
3194 } elseif( $wgAuth->strict() ) {
3195 /* Auth plugin doesn't allow local authentication */
3197 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
3198 /* Auth plugin doesn't allow local authentication for this user name */
3201 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
3203 } elseif ( $wgLegacyEncoding ) {
3204 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3205 # Check for this with iconv
3206 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3207 if ( $cp1252Password != $password &&
3208 self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) )
3217 * Check if the given clear-text password matches the temporary password
3218 * sent by e-mail for password reset operations.
3220 * @param $plaintext string
3222 * @return Boolean: True if matches, false otherwise
3224 public function checkTemporaryPassword( $plaintext ) {
3225 global $wgNewPasswordExpiry;
3228 if( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
3229 if ( is_null( $this->mNewpassTime
) ) {
3232 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3233 return ( time() < $expiry );
3240 * Alias for getEditToken.
3241 * @deprecated since 1.19, use getEditToken instead.
3243 * @param $salt String|Array of Strings Optional function-specific data for hashing
3244 * @param $request WebRequest object to use or null to use $wgRequest
3245 * @return String The new edit token
3247 public function editToken( $salt = '', $request = null ) {
3248 wfDeprecated( __METHOD__
, '1.19' );
3249 return $this->getEditToken( $salt, $request );
3253 * Initialize (if necessary) and return a session token value
3254 * which can be used in edit forms to show that the user's
3255 * login credentials aren't being hijacked with a foreign form
3260 * @param $salt String|Array of Strings Optional function-specific data for hashing
3261 * @param $request WebRequest object to use or null to use $wgRequest
3262 * @return String The new edit token
3264 public function getEditToken( $salt = '', $request = null ) {
3265 if ( $request == null ) {
3266 $request = $this->getRequest();
3269 if ( $this->isAnon() ) {
3270 return EDIT_TOKEN_SUFFIX
;
3272 $token = $request->getSessionData( 'wsEditToken' );
3273 if ( $token === null ) {
3274 $token = MWCryptRand
::generateHex( 32 );
3275 $request->setSessionData( 'wsEditToken', $token );
3277 if( is_array( $salt ) ) {
3278 $salt = implode( '|', $salt );
3280 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
3285 * Generate a looking random token for various uses.
3287 * @param $salt String Optional salt value
3288 * @return String The new random token
3289 * @deprecated since 1.20; Use MWCryptRand for secure purposes or wfRandomString for pesudo-randomness
3291 public static function generateToken( $salt = '' ) {
3292 return MWCryptRand
::generateHex( 32 );
3296 * Check given value against the token value stored in the session.
3297 * A match should confirm that the form was submitted from the
3298 * user's own login session, not a form submission from a third-party
3301 * @param $val String Input value to compare
3302 * @param $salt String Optional function-specific data for hashing
3303 * @param $request WebRequest object to use or null to use $wgRequest
3304 * @return Boolean: Whether the token matches
3306 public function matchEditToken( $val, $salt = '', $request = null ) {
3307 $sessionToken = $this->getEditToken( $salt, $request );
3308 if ( $val != $sessionToken ) {
3309 wfDebug( "User::matchEditToken: broken session data\n" );
3311 return $val == $sessionToken;
3315 * Check given value against the token value stored in the session,
3316 * ignoring the suffix.
3318 * @param $val String Input value to compare
3319 * @param $salt String Optional function-specific data for hashing
3320 * @param $request WebRequest object to use or null to use $wgRequest
3321 * @return Boolean: Whether the token matches
3323 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3324 $sessionToken = $this->getEditToken( $salt, $request );
3325 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3329 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3330 * mail to the user's given address.
3332 * @param $type String: message to send, either "created", "changed" or "set"
3333 * @return Status object
3335 public function sendConfirmationMail( $type = 'created' ) {
3337 $expiration = null; // gets passed-by-ref and defined in next line.
3338 $token = $this->confirmationToken( $expiration );
3339 $url = $this->confirmationTokenUrl( $token );
3340 $invalidateURL = $this->invalidationTokenUrl( $token );
3341 $this->saveSettings();
3343 if ( $type == 'created' ||
$type === false ) {
3344 $message = 'confirmemail_body';
3345 } elseif ( $type === true ) {
3346 $message = 'confirmemail_body_changed';
3348 $message = 'confirmemail_body_' . $type;
3351 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
3353 $this->getRequest()->getIP(),
3356 $wgLang->timeanddate( $expiration, false ),
3358 $wgLang->date( $expiration, false ),
3359 $wgLang->time( $expiration, false ) ) );
3363 * Send an e-mail to this user's account. Does not check for
3364 * confirmed status or validity.
3366 * @param $subject String Message subject
3367 * @param $body String Message body
3368 * @param $from String Optional From address; if unspecified, default $wgPasswordSender will be used
3369 * @param $replyto String Reply-To address
3372 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3373 if( is_null( $from ) ) {
3374 global $wgPasswordSender, $wgPasswordSenderName;
3375 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
3377 $sender = new MailAddress( $from );
3380 $to = new MailAddress( $this );
3381 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
3385 * Generate, store, and return a new e-mail confirmation code.
3386 * A hash (unsalted, since it's used as a key) is stored.
3388 * @note Call saveSettings() after calling this function to commit
3389 * this change to the database.
3391 * @param &$expiration \mixed Accepts the expiration time
3392 * @return String New token
3394 private function confirmationToken( &$expiration ) {
3395 global $wgUserEmailConfirmationTokenExpiry;
3397 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
3398 $expiration = wfTimestamp( TS_MW
, $expires );
3400 $token = MWCryptRand
::generateHex( 32 );
3401 $hash = md5( $token );
3402 $this->mEmailToken
= $hash;
3403 $this->mEmailTokenExpires
= $expiration;
3408 * Return a URL the user can use to confirm their email address.
3409 * @param $token String Accepts the email confirmation token
3410 * @return String New token URL
3412 private function confirmationTokenUrl( $token ) {
3413 return $this->getTokenUrl( 'ConfirmEmail', $token );
3417 * Return a URL the user can use to invalidate their email address.
3418 * @param $token String Accepts the email confirmation token
3419 * @return String New token URL
3421 private function invalidationTokenUrl( $token ) {
3422 return $this->getTokenUrl( 'InvalidateEmail', $token );
3426 * Internal function to format the e-mail validation/invalidation URLs.
3427 * This uses a quickie hack to use the
3428 * hardcoded English names of the Special: pages, for ASCII safety.
3430 * @note Since these URLs get dropped directly into emails, using the
3431 * short English names avoids insanely long URL-encoded links, which
3432 * also sometimes can get corrupted in some browsers/mailers
3433 * (bug 6957 with Gmail and Internet Explorer).
3435 * @param $page String Special page
3436 * @param $token String Token
3437 * @return String Formatted URL
3439 protected function getTokenUrl( $page, $token ) {
3440 // Hack to bypass localization of 'Special:'
3441 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
3442 return $title->getCanonicalUrl();
3446 * Mark the e-mail address confirmed.
3448 * @note Call saveSettings() after calling this function to commit the change.
3452 public function confirmEmail() {
3453 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3454 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3459 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3460 * address if it was already confirmed.
3462 * @note Call saveSettings() after calling this function to commit the change.
3463 * @return bool Returns true
3465 function invalidateEmail() {
3467 $this->mEmailToken
= null;
3468 $this->mEmailTokenExpires
= null;
3469 $this->setEmailAuthenticationTimestamp( null );
3470 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3475 * Set the e-mail authentication timestamp.
3476 * @param $timestamp String TS_MW timestamp
3478 function setEmailAuthenticationTimestamp( $timestamp ) {
3480 $this->mEmailAuthenticated
= $timestamp;
3481 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
3485 * Is this user allowed to send e-mails within limits of current
3486 * site configuration?
3489 public function canSendEmail() {
3490 global $wgEnableEmail, $wgEnableUserEmail;
3491 if( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
3494 $canSend = $this->isEmailConfirmed();
3495 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3500 * Is this user allowed to receive e-mails within limits of current
3501 * site configuration?
3504 public function canReceiveEmail() {
3505 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3509 * Is this user's e-mail address valid-looking and confirmed within
3510 * limits of the current site configuration?
3512 * @note If $wgEmailAuthentication is on, this may require the user to have
3513 * confirmed their address by returning a code or using a password
3514 * sent to the address from the wiki.
3518 public function isEmailConfirmed() {
3519 global $wgEmailAuthentication;
3522 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3523 if( $this->isAnon() ) {
3526 if( !Sanitizer
::validateEmail( $this->mEmail
) ) {
3529 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
3539 * Check whether there is an outstanding request for e-mail confirmation.
3542 public function isEmailConfirmationPending() {
3543 global $wgEmailAuthentication;
3544 return $wgEmailAuthentication &&
3545 !$this->isEmailConfirmed() &&
3546 $this->mEmailToken
&&
3547 $this->mEmailTokenExpires
> wfTimestamp();
3551 * Get the timestamp of account creation.
3553 * @return String|Bool Timestamp of account creation, or false for
3554 * non-existent/anonymous user accounts.
3556 public function getRegistration() {
3557 if ( $this->isAnon() ) {
3561 return $this->mRegistration
;
3565 * Get the timestamp of the first edit
3567 * @return String|Bool Timestamp of first edit, or false for
3568 * non-existent/anonymous user accounts.
3570 public function getFirstEditTimestamp() {
3571 if( $this->getId() == 0 ) {
3572 return false; // anons
3574 $dbr = wfGetDB( DB_SLAVE
);
3575 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3576 array( 'rev_user' => $this->getId() ),
3578 array( 'ORDER BY' => 'rev_timestamp ASC' )
3581 return false; // no edits
3583 return wfTimestamp( TS_MW
, $time );
3587 * Get the permissions associated with a given list of groups
3589 * @param $groups Array of Strings List of internal group names
3590 * @return Array of Strings List of permission key names for given groups combined
3592 public static function getGroupPermissions( $groups ) {
3593 global $wgGroupPermissions, $wgRevokePermissions;
3595 // grant every granted permission first
3596 foreach( $groups as $group ) {
3597 if( isset( $wgGroupPermissions[$group] ) ) {
3598 $rights = array_merge( $rights,
3599 // array_filter removes empty items
3600 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3603 // now revoke the revoked permissions
3604 foreach( $groups as $group ) {
3605 if( isset( $wgRevokePermissions[$group] ) ) {
3606 $rights = array_diff( $rights,
3607 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3610 return array_unique( $rights );
3614 * Get all the groups who have a given permission
3616 * @param $role String Role to check
3617 * @return Array of Strings List of internal group names with the given permission
3619 public static function getGroupsWithPermission( $role ) {
3620 global $wgGroupPermissions;
3621 $allowedGroups = array();
3622 foreach ( $wgGroupPermissions as $group => $rights ) {
3623 if ( isset( $rights[$role] ) && $rights[$role] ) {
3624 $allowedGroups[] = $group;
3627 return $allowedGroups;
3631 * Get the localized descriptive name for a group, if it exists
3633 * @param $group String Internal group name
3634 * @return String Localized descriptive group name
3636 public static function getGroupName( $group ) {
3637 $msg = wfMessage( "group-$group" );
3638 return $msg->isBlank() ?
$group : $msg->text();
3642 * Get the localized descriptive name for a member of a group, if it exists
3644 * @param $group String Internal group name
3645 * @param $username String Username for gender (since 1.19)
3646 * @return String Localized name for group member
3648 public static function getGroupMember( $group, $username = '#' ) {
3649 $msg = wfMessage( "group-$group-member", $username );
3650 return $msg->isBlank() ?
$group : $msg->text();
3654 * Return the set of defined explicit groups.
3655 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3656 * are not included, as they are defined automatically, not in the database.
3657 * @return Array of internal group names
3659 public static function getAllGroups() {
3660 global $wgGroupPermissions, $wgRevokePermissions;
3662 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3663 self
::getImplicitGroups()
3668 * Get a list of all available permissions.
3669 * @return Array of permission names
3671 public static function getAllRights() {
3672 if ( self
::$mAllRights === false ) {
3673 global $wgAvailableRights;
3674 if ( count( $wgAvailableRights ) ) {
3675 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3677 self
::$mAllRights = self
::$mCoreRights;
3679 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3681 return self
::$mAllRights;
3685 * Get a list of implicit groups
3686 * @return Array of Strings Array of internal group names
3688 public static function getImplicitGroups() {
3689 global $wgImplicitGroups;
3690 $groups = $wgImplicitGroups;
3691 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3696 * Get the title of a page describing a particular group
3698 * @param $group String Internal group name
3699 * @return Title|Bool Title of the page if it exists, false otherwise
3701 public static function getGroupPage( $group ) {
3702 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
3703 if( $msg->exists() ) {
3704 $title = Title
::newFromText( $msg->text() );
3705 if( is_object( $title ) )
3712 * Create a link to the group in HTML, if available;
3713 * else return the group name.
3715 * @param $group String Internal name of the group
3716 * @param $text String The text of the link
3717 * @return String HTML link to the group
3719 public static function makeGroupLinkHTML( $group, $text = '' ) {
3721 $text = self
::getGroupName( $group );
3723 $title = self
::getGroupPage( $group );
3725 return Linker
::link( $title, htmlspecialchars( $text ) );
3732 * Create a link to the group in Wikitext, if available;
3733 * else return the group name.
3735 * @param $group String Internal name of the group
3736 * @param $text String The text of the link
3737 * @return String Wikilink to the group
3739 public static function makeGroupLinkWiki( $group, $text = '' ) {
3741 $text = self
::getGroupName( $group );
3743 $title = self
::getGroupPage( $group );
3745 $page = $title->getPrefixedText();
3746 return "[[$page|$text]]";
3753 * Returns an array of the groups that a particular group can add/remove.
3755 * @param $group String: the group to check for whether it can add/remove
3756 * @return Array array( 'add' => array( addablegroups ),
3757 * 'remove' => array( removablegroups ),
3758 * 'add-self' => array( addablegroups to self),
3759 * 'remove-self' => array( removable groups from self) )
3761 public static function changeableByGroup( $group ) {
3762 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
3764 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
3765 if( empty( $wgAddGroups[$group] ) ) {
3766 // Don't add anything to $groups
3767 } elseif( $wgAddGroups[$group] === true ) {
3768 // You get everything
3769 $groups['add'] = self
::getAllGroups();
3770 } elseif( is_array( $wgAddGroups[$group] ) ) {
3771 $groups['add'] = $wgAddGroups[$group];
3774 // Same thing for remove
3775 if( empty( $wgRemoveGroups[$group] ) ) {
3776 } elseif( $wgRemoveGroups[$group] === true ) {
3777 $groups['remove'] = self
::getAllGroups();
3778 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
3779 $groups['remove'] = $wgRemoveGroups[$group];
3782 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
3783 if( empty( $wgGroupsAddToSelf['user']) ||
$wgGroupsAddToSelf['user'] !== true ) {
3784 foreach( $wgGroupsAddToSelf as $key => $value ) {
3785 if( is_int( $key ) ) {
3786 $wgGroupsAddToSelf['user'][] = $value;
3791 if( empty( $wgGroupsRemoveFromSelf['user']) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
3792 foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
3793 if( is_int( $key ) ) {
3794 $wgGroupsRemoveFromSelf['user'][] = $value;
3799 // Now figure out what groups the user can add to him/herself
3800 if( empty( $wgGroupsAddToSelf[$group] ) ) {
3801 } elseif( $wgGroupsAddToSelf[$group] === true ) {
3802 // No idea WHY this would be used, but it's there
3803 $groups['add-self'] = User
::getAllGroups();
3804 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
3805 $groups['add-self'] = $wgGroupsAddToSelf[$group];
3808 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
3809 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
3810 $groups['remove-self'] = User
::getAllGroups();
3811 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
3812 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
3819 * Returns an array of groups that this user can add and remove
3820 * @return Array array( 'add' => array( addablegroups ),
3821 * 'remove' => array( removablegroups ),
3822 * 'add-self' => array( addablegroups to self),
3823 * 'remove-self' => array( removable groups from self) )
3825 public function changeableGroups() {
3826 if( $this->isAllowed( 'userrights' ) ) {
3827 // This group gives the right to modify everything (reverse-
3828 // compatibility with old "userrights lets you change
3830 // Using array_merge to make the groups reindexed
3831 $all = array_merge( User
::getAllGroups() );
3835 'add-self' => array(),
3836 'remove-self' => array()
3840 // Okay, it's not so simple, we will have to go through the arrays
3843 'remove' => array(),
3844 'add-self' => array(),
3845 'remove-self' => array()
3847 $addergroups = $this->getEffectiveGroups();
3849 foreach( $addergroups as $addergroup ) {
3850 $groups = array_merge_recursive(
3851 $groups, $this->changeableByGroup( $addergroup )
3853 $groups['add'] = array_unique( $groups['add'] );
3854 $groups['remove'] = array_unique( $groups['remove'] );
3855 $groups['add-self'] = array_unique( $groups['add-self'] );
3856 $groups['remove-self'] = array_unique( $groups['remove-self'] );
3862 * Increment the user's edit-count field.
3863 * Will have no effect for anonymous users.
3865 public function incEditCount() {
3866 if( !$this->isAnon() ) {
3867 $dbw = wfGetDB( DB_MASTER
);
3868 $dbw->update( 'user',
3869 array( 'user_editcount=user_editcount+1' ),
3870 array( 'user_id' => $this->getId() ),
3873 // Lazy initialization check...
3874 if( $dbw->affectedRows() == 0 ) {
3875 // Pull from a slave to be less cruel to servers
3876 // Accuracy isn't the point anyway here
3877 $dbr = wfGetDB( DB_SLAVE
);
3878 $count = $dbr->selectField( 'revision',
3880 array( 'rev_user' => $this->getId() ),
3883 // Now here's a goddamn hack...
3884 if( $dbr !== $dbw ) {
3885 // If we actually have a slave server, the count is
3886 // at least one behind because the current transaction
3887 // has not been committed and replicated.
3890 // But if DB_SLAVE is selecting the master, then the
3891 // count we just read includes the revision that was
3892 // just added in the working transaction.
3895 $dbw->update( 'user',
3896 array( 'user_editcount' => $count ),
3897 array( 'user_id' => $this->getId() ),
3901 // edit count in user cache too
3902 $this->invalidateCache();
3906 * Get the description of a given right
3908 * @param $right String Right to query
3909 * @return String Localized description of the right
3911 public static function getRightDescription( $right ) {
3912 $key = "right-$right";
3913 $msg = wfMessage( $key );
3914 return $msg->isBlank() ?
$right : $msg->text();
3918 * Make an old-style password hash
3920 * @param $password String Plain-text password
3921 * @param $userId String User ID
3922 * @return String Password hash
3924 public static function oldCrypt( $password, $userId ) {
3925 global $wgPasswordSalt;
3926 if ( $wgPasswordSalt ) {
3927 return md5( $userId . '-' . md5( $password ) );
3929 return md5( $password );
3934 * Make a new-style password hash
3936 * @param $password String Plain-text password
3937 * @param bool|string $salt Optional salt, may be random or the user ID.
3939 * If unspecified or false, will generate one automatically
3940 * @return String Password hash
3942 public static function crypt( $password, $salt = false ) {
3943 global $wgPasswordSalt;
3946 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3950 if( $wgPasswordSalt ) {
3951 if ( $salt === false ) {
3952 $salt = MWCryptRand
::generateHex( 8 );
3954 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3956 return ':A:' . md5( $password );
3961 * Compare a password hash with a plain-text password. Requires the user
3962 * ID if there's a chance that the hash is an old-style hash.
3964 * @param $hash String Password hash
3965 * @param $password String Plain-text password to compare
3966 * @param $userId String|bool User ID for old-style password salt
3970 public static function comparePasswords( $hash, $password, $userId = false ) {
3971 $type = substr( $hash, 0, 3 );
3974 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3978 if ( $type == ':A:' ) {
3980 return md5( $password ) === substr( $hash, 3 );
3981 } elseif ( $type == ':B:' ) {
3983 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3984 return md5( $salt.'-'.md5( $password ) ) === $realHash;
3987 return self
::oldCrypt( $password, $userId ) === $hash;
3992 * Add a newuser log entry for this user. Before 1.19 the return value was always true.
3994 * @param $byEmail Boolean: account made by email?
3995 * @param $reason String: user supplied reason
3997 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
3999 public function addNewUserLogEntry( $byEmail = false, $reason = '' ) {
4000 global $wgUser, $wgContLang, $wgNewUserLog;
4001 if( empty( $wgNewUserLog ) ) {
4002 return true; // disabled
4005 if( $this->getName() == $wgUser->getName() ) {
4008 $action = 'create2';
4010 if ( $reason === '' ) {
4011 $reason = wfMsgForContent( 'newuserlog-byemail' );
4013 $reason = $wgContLang->commaList( array(
4014 $reason, wfMsgForContent( 'newuserlog-byemail' ) ) );
4018 $log = new LogPage( 'newusers' );
4019 return (int)$log->addEntry(
4021 $this->getUserPage(),
4023 array( $this->getId() )
4028 * Add an autocreate newuser log entry for this user
4029 * Used by things like CentralAuth and perhaps other authplugins.
4033 public function addNewUserLogEntryAutoCreate() {
4034 global $wgNewUserLog;
4035 if( !$wgNewUserLog ) {
4036 return true; // disabled
4038 $log = new LogPage( 'newusers', false );
4039 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ), $this );
4046 protected function loadOptions() {
4048 if ( $this->mOptionsLoaded ||
!$this->getId() )
4051 $this->mOptions
= self
::getDefaultOptions();
4053 // Maybe load from the object
4054 if ( !is_null( $this->mOptionOverrides
) ) {
4055 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4056 foreach( $this->mOptionOverrides
as $key => $value ) {
4057 $this->mOptions
[$key] = $value;
4060 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4061 // Load from database
4062 $dbr = wfGetDB( DB_SLAVE
);
4064 $res = $dbr->select(
4066 array( 'up_property', 'up_value' ),
4067 array( 'up_user' => $this->getId() ),
4071 $this->mOptionOverrides
= array();
4072 foreach ( $res as $row ) {
4073 $this->mOptionOverrides
[$row->up_property
] = $row->up_value
;
4074 $this->mOptions
[$row->up_property
] = $row->up_value
;
4078 $this->mOptionsLoaded
= true;
4080 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
4086 protected function saveOptions() {
4087 global $wgAllowPrefChange;
4089 $this->loadOptions();
4091 // Not using getOptions(), to keep hidden preferences in database
4092 $saveOptions = $this->mOptions
;
4094 // Allow hooks to abort, for instance to save to a global profile.
4095 // Reset options to default state before saving.
4096 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4100 $extuser = ExternalUser
::newFromUser( $this );
4101 $userId = $this->getId();
4102 $insert_rows = array();
4103 foreach( $saveOptions as $key => $value ) {
4104 # Don't bother storing default values
4105 $defaultOption = self
::getDefaultOption( $key );
4106 if ( ( is_null( $defaultOption ) &&
4107 !( $value === false ||
is_null( $value ) ) ) ||
4108 $value != $defaultOption ) {
4109 $insert_rows[] = array(
4110 'up_user' => $userId,
4111 'up_property' => $key,
4112 'up_value' => $value,
4115 if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
4116 switch ( $wgAllowPrefChange[$key] ) {
4122 $extuser->setPref( $key, $value );
4127 $dbw = wfGetDB( DB_MASTER
);
4128 $dbw->delete( 'user_properties', array( 'up_user' => $userId ), __METHOD__
);
4129 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
);
4133 * Provide an array of HTML5 attributes to put on an input element
4134 * intended for the user to enter a new password. This may include
4135 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4137 * Do *not* use this when asking the user to enter his current password!
4138 * Regardless of configuration, users may have invalid passwords for whatever
4139 * reason (e.g., they were set before requirements were tightened up).
4140 * Only use it when asking for a new password, like on account creation or
4143 * Obviously, you still need to do server-side checking.
4145 * NOTE: A combination of bugs in various browsers means that this function
4146 * actually just returns array() unconditionally at the moment. May as
4147 * well keep it around for when the browser bugs get fixed, though.
4149 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4151 * @return array Array of HTML attributes suitable for feeding to
4152 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4153 * That will potentially output invalid XHTML 1.0 Transitional, and will
4154 * get confused by the boolean attribute syntax used.)
4156 public static function passwordChangeInputAttribs() {
4157 global $wgMinimalPasswordLength;
4159 if ( $wgMinimalPasswordLength == 0 ) {
4163 # Note that the pattern requirement will always be satisfied if the
4164 # input is empty, so we need required in all cases.
4166 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4167 # if e-mail confirmation is being used. Since HTML5 input validation
4168 # is b0rked anyway in some browsers, just return nothing. When it's
4169 # re-enabled, fix this code to not output required for e-mail
4171 #$ret = array( 'required' );
4174 # We can't actually do this right now, because Opera 9.6 will print out
4175 # the entered password visibly in its error message! When other
4176 # browsers add support for this attribute, or Opera fixes its support,
4177 # we can add support with a version check to avoid doing this on Opera
4178 # versions where it will be a problem. Reported to Opera as
4179 # DSK-262266, but they don't have a public bug tracker for us to follow.
4181 if ( $wgMinimalPasswordLength > 1 ) {
4182 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4183 $ret['title'] = wfMsgExt( 'passwordtooshort', 'parsemag',
4184 $wgMinimalPasswordLength );
4192 * Return the list of user fields that should be selected to create
4193 * a new user object.
4196 public static function selectFields() {
4203 'user_newpass_time',
4207 'user_email_authenticated',
4209 'user_email_token_expires',
4210 'user_registration',