3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Int Number of characters in user_token field.
27 define( 'USER_TOKEN_LENGTH', 32 );
30 * Int Serialized record version.
33 define( 'MW_USER_VERSION', 8 );
36 * String Some punctuation to prevent editing from broken text-mangling proxies.
39 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
42 * Thrown by User::setPassword() on error.
45 class PasswordError
extends MWException
{
50 * The User object encapsulates all of the user-specific settings (user_id,
51 * name, rights, password, email address, options, last login time). Client
52 * classes use the getXXX() functions to access these fields. These functions
53 * do all the work of determining whether the user is logged in,
54 * whether the requested option can be satisfied from cookies or
55 * whether a database query is needed. Most of the settings needed
56 * for rendering normal pages are set in the cookie to minimize use
61 * Global constants made accessible as class constants so that autoloader
64 const USER_TOKEN_LENGTH
= USER_TOKEN_LENGTH
;
65 const MW_USER_VERSION
= MW_USER_VERSION
;
66 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
69 * Maximum items in $mWatchedItems
71 const MAX_WATCHED_ITEMS_CACHE
= 100;
74 * Array of Strings List of member variables which are saved to the
75 * shared cache (memcached). Any operation which changes the
76 * corresponding database fields must call a cache-clearing function.
79 static $mCacheVars = array(
90 'mEmailAuthenticated',
97 // user_properties table
102 * Array of Strings Core rights.
103 * Each of these should have a corresponding message of the form
107 static $mCoreRights = array(
127 'editusercssjs', #deprecated
139 'move-rootuserpages',
143 'override-export-depth',
166 'userrights-interwiki',
170 * String Cached results of getAllRights()
172 static $mAllRights = false;
174 /** @name Cache variables */
176 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
177 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
178 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mEditCount,
179 $mGroups, $mOptionOverrides;
183 * Bool Whether the cache variables have been loaded.
189 * Array with already loaded items or true if all items have been loaded.
191 private $mLoadedItems = array();
195 * String Initialization data source if mLoadedItems!==true. May be one of:
196 * - 'defaults' anonymous user initialised from class defaults
197 * - 'name' initialise from mName
198 * - 'id' initialise from mId
199 * - 'session' log in from cookies or session if possible
201 * Use the User::newFrom*() family of functions to set this.
206 * Lazy-initialized variables, invalidated with clearInstanceCache
208 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mRights,
209 $mBlockreason, $mEffectiveGroups, $mImplicitGroups, $mFormerGroups, $mBlockedGlobally,
210 $mLocked, $mHideName, $mOptions;
230 private $mBlockedFromCreateAccount = false;
235 private $mWatchedItems = array();
237 static $idCacheByName = array();
240 * Lightweight constructor for an anonymous user.
241 * Use the User::newFrom* factory functions for other kinds of users.
245 * @see newFromConfirmationCode()
246 * @see newFromSession()
249 function __construct() {
250 $this->clearInstanceCache( 'defaults' );
256 function __toString() {
257 return $this->getName();
261 * Load the user table data for this object from the source given by mFrom.
263 public function load() {
264 if ( $this->mLoadedItems
=== true ) {
267 wfProfileIn( __METHOD__
);
269 # Set it now to avoid infinite recursion in accessors
270 $this->mLoadedItems
= true;
272 switch ( $this->mFrom
) {
274 $this->loadDefaults();
277 $this->mId
= self
::idFromName( $this->mName
);
279 # Nonexistent user placeholder object
280 $this->loadDefaults( $this->mName
);
289 if( !$this->loadFromSession() ) {
290 // Loading from session failed. Load defaults.
291 $this->loadDefaults();
293 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
296 wfProfileOut( __METHOD__
);
297 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
299 wfProfileOut( __METHOD__
);
303 * Load user table data, given mId has already been set.
304 * @return Bool false if the ID does not exist, true otherwise
306 public function loadFromId() {
308 if ( $this->mId
== 0 ) {
309 $this->loadDefaults();
314 $key = wfMemcKey( 'user', 'id', $this->mId
);
315 $data = $wgMemc->get( $key );
316 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
317 # Object is expired, load from DB
322 wfDebug( "User: cache miss for user {$this->mId}\n" );
324 if ( !$this->loadFromDatabase() ) {
325 # Can't load from ID, user is anonymous
328 $this->saveToCache();
330 wfDebug( "User: got user {$this->mId} from cache\n" );
332 foreach ( self
::$mCacheVars as $name ) {
333 $this->$name = $data[$name];
337 $this->mLoadedItems
= true;
343 * Save user data to the shared cache
345 public function saveToCache() {
348 $this->loadOptions();
349 if ( $this->isAnon() ) {
350 // Anonymous users are uncached
354 foreach ( self
::$mCacheVars as $name ) {
355 $data[$name] = $this->$name;
357 $data['mVersion'] = MW_USER_VERSION
;
358 $key = wfMemcKey( 'user', 'id', $this->mId
);
360 $wgMemc->set( $key, $data );
363 /** @name newFrom*() static factory methods */
367 * Static factory method for creation from username.
369 * This is slightly less efficient than newFromId(), so use newFromId() if
370 * you have both an ID and a name handy.
372 * @param string $name Username, validated by Title::newFromText()
373 * @param string|Bool $validate Validate username. Takes the same parameters as
374 * User::getCanonicalName(), except that true is accepted as an alias
375 * for 'valid', for BC.
377 * @return User|bool User object, or false if the username is invalid
378 * (e.g. if it contains illegal characters or is an IP address). If the
379 * username is not present in the database, the result will be a user object
380 * with a name, zero user ID and default settings.
382 public static function newFromName( $name, $validate = 'valid' ) {
383 if ( $validate === true ) {
386 $name = self
::getCanonicalName( $name, $validate );
387 if ( $name === false ) {
390 # Create unloaded user object
394 $u->setItemLoaded( 'name' );
400 * Static factory method for creation from a given user ID.
402 * @param int $id Valid user ID
403 * @return User The corresponding User object
405 public static function newFromId( $id ) {
409 $u->setItemLoaded( 'id' );
414 * Factory method to fetch whichever user has a given email confirmation code.
415 * This code is generated when an account is created or its e-mail address
418 * If the code is invalid or has expired, returns NULL.
420 * @param string $code Confirmation code
421 * @return User object, or null
423 public static function newFromConfirmationCode( $code ) {
424 $dbr = wfGetDB( DB_SLAVE
);
425 $id = $dbr->selectField( 'user', 'user_id', array(
426 'user_email_token' => md5( $code ),
427 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
429 if( $id !== false ) {
430 return User
::newFromId( $id );
437 * Create a new user object using data from session or cookies. If the
438 * login credentials are invalid, the result is an anonymous user.
440 * @param $request WebRequest object to use; $wgRequest will be used if omitted.
441 * @return User object
443 public static function newFromSession( WebRequest
$request = null ) {
445 $user->mFrom
= 'session';
446 $user->mRequest
= $request;
451 * Create a new user object from a user row.
452 * The row should have the following fields from the user table in it:
453 * - either user_name or user_id to load further data if needed (or both)
455 * - all other fields (email, password, etc.)
456 * It is useless to provide the remaining fields if either user_id,
457 * user_name and user_real_name are not provided because the whole row
458 * will be loaded once more from the database when accessing them.
460 * @param array $row A row from the user table
461 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
464 public static function newFromRow( $row, $data = null ) {
466 $user->loadFromRow( $row, $data );
473 * Get the username corresponding to a given user ID
474 * @param int $id User ID
475 * @return String|bool The corresponding username
477 public static function whoIs( $id ) {
478 return UserCache
::singleton()->getProp( $id, 'name' );
482 * Get the real name of a user given their user ID
484 * @param int $id User ID
485 * @return String|bool The corresponding user's real name
487 public static function whoIsReal( $id ) {
488 return UserCache
::singleton()->getProp( $id, 'real_name' );
492 * Get database id given a user name
493 * @param string $name Username
494 * @return Int|Null The corresponding user's ID, or null if user is nonexistent
496 public static function idFromName( $name ) {
497 $nt = Title
::makeTitleSafe( NS_USER
, $name );
498 if( is_null( $nt ) ) {
503 if ( isset( self
::$idCacheByName[$name] ) ) {
504 return self
::$idCacheByName[$name];
507 $dbr = wfGetDB( DB_SLAVE
);
508 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
510 if ( $s === false ) {
513 $result = $s->user_id
;
516 self
::$idCacheByName[$name] = $result;
518 if ( count( self
::$idCacheByName ) > 1000 ) {
519 self
::$idCacheByName = array();
526 * Reset the cache used in idFromName(). For use in tests.
528 public static function resetIdByNameCache() {
529 self
::$idCacheByName = array();
533 * Does the string match an anonymous IPv4 address?
535 * This function exists for username validation, in order to reject
536 * usernames which are similar in form to IP addresses. Strings such
537 * as 300.300.300.300 will return true because it looks like an IP
538 * address, despite not being strictly valid.
540 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
541 * address because the usemod software would "cloak" anonymous IP
542 * addresses like this, if we allowed accounts like this to be created
543 * new users could get the old edits of these anonymous users.
545 * @param string $name to match
548 public static function isIP( $name ) {
549 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name ) || IP
::isIPv6( $name );
553 * Is the input a valid username?
555 * Checks if the input is a valid username, we don't want an empty string,
556 * an IP address, anything that contains slashes (would mess up subpages),
557 * is longer than the maximum allowed username size or doesn't begin with
560 * @param string $name to match
563 public static function isValidUserName( $name ) {
564 global $wgContLang, $wgMaxNameChars;
567 || User
::isIP( $name )
568 ||
strpos( $name, '/' ) !== false
569 ||
strlen( $name ) > $wgMaxNameChars
570 ||
$name != $wgContLang->ucfirst( $name ) ) {
571 wfDebugLog( 'username', __METHOD__
.
572 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
576 // Ensure that the name can't be misresolved as a different title,
577 // such as with extra namespace keys at the start.
578 $parsed = Title
::newFromText( $name );
579 if( is_null( $parsed )
580 ||
$parsed->getNamespace()
581 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
582 wfDebugLog( 'username', __METHOD__
.
583 ": '$name' invalid due to ambiguous prefixes" );
587 // Check an additional blacklist of troublemaker characters.
588 // Should these be merged into the title char list?
589 $unicodeBlacklist = '/[' .
590 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
591 '\x{00a0}' . # non-breaking space
592 '\x{2000}-\x{200f}' . # various whitespace
593 '\x{2028}-\x{202f}' . # breaks and control chars
594 '\x{3000}' . # ideographic space
595 '\x{e000}-\x{f8ff}' . # private use
597 if( preg_match( $unicodeBlacklist, $name ) ) {
598 wfDebugLog( 'username', __METHOD__
.
599 ": '$name' invalid due to blacklisted characters" );
607 * Usernames which fail to pass this function will be blocked
608 * from user login and new account registrations, but may be used
609 * internally by batch processes.
611 * If an account already exists in this form, login will be blocked
612 * by a failure to pass this function.
614 * @param string $name to match
617 public static function isUsableName( $name ) {
618 global $wgReservedUsernames;
619 // Must be a valid username, obviously ;)
620 if ( !self
::isValidUserName( $name ) ) {
624 static $reservedUsernames = false;
625 if ( !$reservedUsernames ) {
626 $reservedUsernames = $wgReservedUsernames;
627 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
630 // Certain names may be reserved for batch processes.
631 foreach ( $reservedUsernames as $reserved ) {
632 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
633 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
635 if ( $reserved == $name ) {
643 * Usernames which fail to pass this function will be blocked
644 * from new account registrations, but may be used internally
645 * either by batch processes or by user accounts which have
646 * already been created.
648 * Additional blacklisting may be added here rather than in
649 * isValidUserName() to avoid disrupting existing accounts.
651 * @param string $name to match
654 public static function isCreatableName( $name ) {
655 global $wgInvalidUsernameCharacters;
657 // Ensure that the username isn't longer than 235 bytes, so that
658 // (at least for the builtin skins) user javascript and css files
659 // will work. (bug 23080)
660 if( strlen( $name ) > 235 ) {
661 wfDebugLog( 'username', __METHOD__
.
662 ": '$name' invalid due to length" );
666 // Preg yells if you try to give it an empty string
667 if( $wgInvalidUsernameCharacters !== '' ) {
668 if( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
669 wfDebugLog( 'username', __METHOD__
.
670 ": '$name' invalid due to wgInvalidUsernameCharacters" );
675 return self
::isUsableName( $name );
679 * Is the input a valid password for this user?
681 * @param string $password Desired password
684 public function isValidPassword( $password ) {
685 //simple boolean wrapper for getPasswordValidity
686 return $this->getPasswordValidity( $password ) === true;
690 * Given unvalidated password input, return error message on failure.
692 * @param string $password Desired password
693 * @return mixed: true on success, string or array of error message on failure
695 public function getPasswordValidity( $password ) {
696 global $wgMinimalPasswordLength, $wgContLang;
698 static $blockedLogins = array(
699 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
700 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
703 $result = false; //init $result to false for the internal checks
705 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
708 if ( $result === false ) {
709 if( strlen( $password ) < $wgMinimalPasswordLength ) {
710 return 'passwordtooshort';
711 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
712 return 'password-name-match';
713 } elseif ( isset( $blockedLogins[$this->getName()] ) && $password == $blockedLogins[$this->getName()] ) {
714 return 'password-login-forbidden';
716 //it seems weird returning true here, but this is because of the
717 //initialization of $result to false above. If the hook is never run or it
718 //doesn't modify $result, then we will likely get down into this if with
722 } elseif( $result === true ) {
725 return $result; //the isValidPassword hook set a string $result and returned true
730 * Does a string look like an e-mail address?
732 * This validates an email address using an HTML5 specification found at:
733 * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
734 * Which as of 2011-01-24 says:
736 * A valid e-mail address is a string that matches the ABNF production
737 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
738 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
741 * This function is an implementation of the specification as requested in
744 * Client-side forms will use the same standard validation rules via JS or
745 * HTML 5 validation; additional restrictions can be enforced server-side
746 * by extensions via the 'isValidEmailAddr' hook.
748 * Note that this validation doesn't 100% match RFC 2822, but is believed
749 * to be liberal enough for wide use. Some invalid addresses will still
750 * pass validation here.
752 * @param string $addr E-mail address
754 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
756 public static function isValidEmailAddr( $addr ) {
757 wfDeprecated( __METHOD__
, '1.18' );
758 return Sanitizer
::validateEmail( $addr );
762 * Given unvalidated user input, return a canonical username, or false if
763 * the username is invalid.
764 * @param string $name User input
765 * @param string|Bool $validate type of validation to use:
766 * - false No validation
767 * - 'valid' Valid for batch processes
768 * - 'usable' Valid for batch processes and login
769 * - 'creatable' Valid for batch processes, login and account creation
771 * @throws MWException
772 * @return bool|string
774 public static function getCanonicalName( $name, $validate = 'valid' ) {
775 # Force usernames to capital
777 $name = $wgContLang->ucfirst( $name );
779 # Reject names containing '#'; these will be cleaned up
780 # with title normalisation, but then it's too late to
782 if( strpos( $name, '#' ) !== false )
785 # Clean up name according to title rules
786 $t = ( $validate === 'valid' ) ?
787 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
788 # Check for invalid titles
789 if( is_null( $t ) ) {
793 # Reject various classes of invalid names
795 $name = $wgAuth->getCanonicalName( $t->getText() );
797 switch ( $validate ) {
801 if ( !User
::isValidUserName( $name ) ) {
806 if ( !User
::isUsableName( $name ) ) {
811 if ( !User
::isCreatableName( $name ) ) {
816 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
822 * Count the number of edits of a user
824 * @param int $uid User ID to check
825 * @return Int the user's edit count
827 * @deprecated since 1.21 in favour of User::getEditCount
829 public static function edits( $uid ) {
830 wfDeprecated( __METHOD__
, '1.21' );
831 $user = self
::newFromId( $uid );
832 return $user->getEditCount();
836 * Return a random password.
838 * @return String new random password
840 public static function randomPassword() {
841 global $wgMinimalPasswordLength;
842 // Decide the final password length based on our min password length, stopping at a minimum of 10 chars
843 $length = max( 10, $wgMinimalPasswordLength );
844 // Multiply by 1.25 to get the number of hex characters we need
845 $length = $length * 1.25;
846 // Generate random hex chars
847 $hex = MWCryptRand
::generateHex( $length );
848 // Convert from base 16 to base 32 to get a proper password like string
849 return wfBaseConvert( $hex, 16, 32 );
853 * Set cached properties to default.
855 * @note This no longer clears uncached lazy-initialised properties;
856 * the constructor does that instead.
858 * @param $name string|bool
860 public function loadDefaults( $name = false ) {
861 wfProfileIn( __METHOD__
);
864 $this->mName
= $name;
865 $this->mRealName
= '';
866 $this->mPassword
= $this->mNewpassword
= '';
867 $this->mNewpassTime
= null;
869 $this->mOptionOverrides
= null;
870 $this->mOptionsLoaded
= false;
872 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
873 if( $loggedOut !== null ) {
874 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
876 $this->mTouched
= '1'; # Allow any pages to be cached
879 $this->mToken
= null; // Don't run cryptographic functions till we need a token
880 $this->mEmailAuthenticated
= null;
881 $this->mEmailToken
= '';
882 $this->mEmailTokenExpires
= null;
883 $this->mRegistration
= wfTimestamp( TS_MW
);
884 $this->mGroups
= array();
886 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
888 wfProfileOut( __METHOD__
);
892 * Return whether an item has been loaded.
894 * @param string $item item to check. Current possibilities:
898 * @param string $all 'all' to check if the whole object has been loaded
899 * or any other string to check if only the item is available (e.g.
903 public function isItemLoaded( $item, $all = 'all' ) {
904 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
905 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
909 * Set that an item has been loaded
911 * @param $item String
913 private function setItemLoaded( $item ) {
914 if ( is_array( $this->mLoadedItems
) ) {
915 $this->mLoadedItems
[$item] = true;
920 * Load user data from the session or login cookie.
921 * @return Bool True if the user is logged in, false otherwise.
923 private function loadFromSession() {
924 global $wgExternalAuthType, $wgAutocreatePolicy;
927 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
928 if ( $result !== null ) {
932 if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
933 $extUser = ExternalUser
::newFromCookie();
935 # TODO: Automatically create the user here (or probably a bit
936 # lower down, in fact)
940 $request = $this->getRequest();
942 $cookieId = $request->getCookie( 'UserID' );
943 $sessId = $request->getSessionData( 'wsUserID' );
945 if ( $cookieId !== null ) {
946 $sId = intval( $cookieId );
947 if( $sessId !== null && $cookieId != $sessId ) {
948 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
949 cookie user ID ($sId) don't match!" );
952 $request->setSessionData( 'wsUserID', $sId );
953 } elseif ( $sessId !== null && $sessId != 0 ) {
959 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
960 $sName = $request->getSessionData( 'wsUserName' );
961 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
962 $sName = $request->getCookie( 'UserName' );
963 $request->setSessionData( 'wsUserName', $sName );
968 $proposedUser = User
::newFromId( $sId );
969 if ( !$proposedUser->isLoggedIn() ) {
974 global $wgBlockDisablesLogin;
975 if( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
976 # User blocked and we've disabled blocked user logins
980 if ( $request->getSessionData( 'wsToken' ) ) {
981 $passwordCorrect = ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
983 } elseif ( $request->getCookie( 'Token' ) ) {
984 # Get the token from DB/cache and clean it up to remove garbage padding.
985 # This deals with historical problems with bugs and the default column value.
986 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
987 $passwordCorrect = ( strlen( $token ) && $token === $request->getCookie( 'Token' ) );
990 # No session or persistent login cookie
994 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
995 $this->loadFromUserObject( $proposedUser );
996 $request->setSessionData( 'wsToken', $this->mToken
);
997 wfDebug( "User: logged in from $from\n" );
1000 # Invalid credentials
1001 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1007 * Load user and user_group data from the database.
1008 * $this->mId must be set, this is how the user is identified.
1010 * @return Bool True if the user exists, false if the user is anonymous
1012 public function loadFromDatabase() {
1014 $this->mId
= intval( $this->mId
);
1016 /** Anonymous user */
1018 $this->loadDefaults();
1022 $dbr = wfGetDB( DB_MASTER
);
1023 $s = $dbr->selectRow( 'user', self
::selectFields(), array( 'user_id' => $this->mId
), __METHOD__
);
1025 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1027 if ( $s !== false ) {
1028 # Initialise user table data
1029 $this->loadFromRow( $s );
1030 $this->mGroups
= null; // deferred
1031 $this->getEditCount(); // revalidation for nulls
1036 $this->loadDefaults();
1042 * Initialize this object from a row from the user table.
1044 * @param array $row Row from the user table to load.
1045 * @param array $data Further user data to load into the object
1047 * user_groups Array with groups out of the user_groups table
1048 * user_properties Array with properties out of the user_properties table
1050 public function loadFromRow( $row, $data = null ) {
1053 $this->mGroups
= null; // deferred
1055 if ( isset( $row->user_name
) ) {
1056 $this->mName
= $row->user_name
;
1057 $this->mFrom
= 'name';
1058 $this->setItemLoaded( 'name' );
1063 if ( isset( $row->user_real_name
) ) {
1064 $this->mRealName
= $row->user_real_name
;
1065 $this->setItemLoaded( 'realname' );
1070 if ( isset( $row->user_id
) ) {
1071 $this->mId
= intval( $row->user_id
);
1072 $this->mFrom
= 'id';
1073 $this->setItemLoaded( 'id' );
1078 if ( isset( $row->user_editcount
) ) {
1079 $this->mEditCount
= $row->user_editcount
;
1084 if ( isset( $row->user_password
) ) {
1085 $this->mPassword
= $row->user_password
;
1086 $this->mNewpassword
= $row->user_newpassword
;
1087 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1088 $this->mEmail
= $row->user_email
;
1089 if ( isset( $row->user_options
) ) {
1090 $this->decodeOptions( $row->user_options
);
1092 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1093 $this->mToken
= $row->user_token
;
1094 if ( $this->mToken
== '' ) {
1095 $this->mToken
= null;
1097 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1098 $this->mEmailToken
= $row->user_email_token
;
1099 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1100 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1106 $this->mLoadedItems
= true;
1109 if ( is_array( $data ) ) {
1110 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1111 $this->mGroups
= $data['user_groups'];
1113 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1114 $this->loadOptions( $data['user_properties'] );
1120 * Load the data for this user object from another user object.
1124 protected function loadFromUserObject( $user ) {
1126 $user->loadGroups();
1127 $user->loadOptions();
1128 foreach ( self
::$mCacheVars as $var ) {
1129 $this->$var = $user->$var;
1134 * Load the groups from the database if they aren't already loaded.
1136 private function loadGroups() {
1137 if ( is_null( $this->mGroups
) ) {
1138 $dbr = wfGetDB( DB_MASTER
);
1139 $res = $dbr->select( 'user_groups',
1140 array( 'ug_group' ),
1141 array( 'ug_user' => $this->mId
),
1143 $this->mGroups
= array();
1144 foreach ( $res as $row ) {
1145 $this->mGroups
[] = $row->ug_group
;
1151 * Add the user to the group if he/she meets given criteria.
1153 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1154 * possible to remove manually via Special:UserRights. In such case it
1155 * will not be re-added automatically. The user will also not lose the
1156 * group if they no longer meet the criteria.
1158 * @param string $event key in $wgAutopromoteOnce (each one has groups/criteria)
1160 * @return array Array of groups the user has been promoted to.
1162 * @see $wgAutopromoteOnce
1164 public function addAutopromoteOnceGroups( $event ) {
1165 global $wgAutopromoteOnceLogInRC;
1167 $toPromote = array();
1168 if ( $this->getId() ) {
1169 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1170 if ( count( $toPromote ) ) {
1171 $oldGroups = $this->getGroups(); // previous groups
1172 foreach ( $toPromote as $group ) {
1173 $this->addGroup( $group );
1175 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1177 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1178 $logEntry->setPerformer( $this );
1179 $logEntry->setTarget( $this->getUserPage() );
1180 $logEntry->setParameters( array(
1181 '4::oldgroups' => $oldGroups,
1182 '5::newgroups' => $newGroups,
1184 $logid = $logEntry->insert();
1185 if ( $wgAutopromoteOnceLogInRC ) {
1186 $logEntry->publish( $logid );
1194 * Clear various cached data stored in this object. The cache of the user table
1195 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1197 * @param bool|String $reloadFrom Reload user and user_groups table data from a
1198 * given source. May be "name", "id", "defaults", "session", or false for
1201 public function clearInstanceCache( $reloadFrom = false ) {
1202 $this->mNewtalk
= -1;
1203 $this->mDatePreference
= null;
1204 $this->mBlockedby
= -1; # Unset
1205 $this->mHash
= false;
1206 $this->mRights
= null;
1207 $this->mEffectiveGroups
= null;
1208 $this->mImplicitGroups
= null;
1209 $this->mGroups
= null;
1210 $this->mOptions
= null;
1211 $this->mOptionsLoaded
= false;
1212 $this->mEditCount
= 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 static $defOpt = null;
1230 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1231 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1232 // mid-request and see that change reflected in the return value of this function.
1233 // Which is insane and would never happen during normal MW operation
1237 $defOpt = $wgDefaultUserOptions;
1238 # default language setting
1239 $defOpt['variant'] = $wgContLang->getCode();
1240 $defOpt['language'] = $wgContLang->getCode();
1241 foreach( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1242 $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1244 $defOpt['skin'] = $wgDefaultSkin;
1246 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1252 * Get a given default option value.
1254 * @param string $opt Name of option to retrieve
1255 * @return String Default option value
1257 public static function getDefaultOption( $opt ) {
1258 $defOpts = self
::getDefaultOptions();
1259 if( isset( $defOpts[$opt] ) ) {
1260 return $defOpts[$opt];
1267 * Get blocking information
1268 * @param bool $bFromSlave 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( wfMessage( 'proxyblocker' )->text() );
1310 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1311 $block->setTarget( $ip );
1312 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1314 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1315 $block->mReason
= wfMessage( 'sorbsreason' )->text();
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 string $ip IP to check
1343 * @param bool $checkWhitelist 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 string $ip IP to check
1364 * @param string|array $bases 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 string $action 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 bool $bFromSlave 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 bool $bFromSlave 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 bool $bFromSlave 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 intended for quick UI checks.
1635 * @param string $ip 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 int $v 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 roughly the same function, when the named user
1741 * @param string $str 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.
1770 global $wgDisableAnonTalk;
1771 if( $wgDisableAnonTalk ) {
1772 // Anon newtalk disabled by configuration.
1773 $this->mNewtalk
= false;
1776 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1777 $newtalk = $wgMemc->get( $key );
1778 if( strval( $newtalk ) !== '' ) {
1779 $this->mNewtalk
= (bool)$newtalk;
1781 // Since we are caching this, make sure it is up to date by getting it
1783 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1784 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1788 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1792 return (bool)$this->mNewtalk
;
1796 * Return the talk page(s) this user has new messages on.
1797 * @return Array of String page URLs
1799 public function getNewMessageLinks() {
1801 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
1803 } elseif( !$this->getNewtalk() ) {
1806 $utp = $this->getTalkPage();
1807 $dbr = wfGetDB( DB_SLAVE
);
1808 // Get the "last viewed rev" timestamp from the oldest message notification
1809 $timestamp = $dbr->selectField( 'user_newtalk',
1810 'MIN(user_last_timestamp)',
1811 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
1813 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
1814 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
1818 * Internal uncached check for new messages
1821 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1822 * @param string|Int $id User's IP address for anonymous users, User ID otherwise
1823 * @param bool $fromMaster true to fetch from the master, false for a slave
1824 * @return Bool True if the user has new messages
1826 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
1827 if ( $fromMaster ) {
1828 $db = wfGetDB( DB_MASTER
);
1830 $db = wfGetDB( DB_SLAVE
);
1832 $ok = $db->selectField( 'user_newtalk', $field,
1833 array( $field => $id ), __METHOD__
);
1834 return $ok !== false;
1838 * Add or update the new messages flag
1839 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1840 * @param string|Int $id User's IP address for anonymous users, User ID otherwise
1841 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null.
1842 * @return Bool True if successful, false otherwise
1844 protected function updateNewtalk( $field, $id, $curRev = null ) {
1845 // Get timestamp of the talk page revision prior to the current one
1846 $prevRev = $curRev ?
$curRev->getPrevious() : false;
1847 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
1848 // Mark the user as having new messages since this revision
1849 $dbw = wfGetDB( DB_MASTER
);
1850 $dbw->insert( 'user_newtalk',
1851 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
1854 if ( $dbw->affectedRows() ) {
1855 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
1858 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
1864 * Clear the new messages flag for the given user
1865 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1866 * @param string|Int $id User's IP address for anonymous users, User ID otherwise
1867 * @return Bool True if successful, false otherwise
1869 protected function deleteNewtalk( $field, $id ) {
1870 $dbw = wfGetDB( DB_MASTER
);
1871 $dbw->delete( 'user_newtalk',
1872 array( $field => $id ),
1874 if ( $dbw->affectedRows() ) {
1875 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
1878 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
1884 * Update the 'You have new messages!' status.
1885 * @param bool $val Whether the user has new messages
1886 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null or !$val.
1888 public function setNewtalk( $val, $curRev = null ) {
1889 if( wfReadOnly() ) {
1894 $this->mNewtalk
= $val;
1896 if( $this->isAnon() ) {
1898 $id = $this->getName();
1901 $id = $this->getId();
1906 $changed = $this->updateNewtalk( $field, $id, $curRev );
1908 $changed = $this->deleteNewtalk( $field, $id );
1911 if( $this->isAnon() ) {
1912 // Anons have a separate memcached space, since
1913 // user records aren't kept for them.
1914 $key = wfMemcKey( 'newtalk', 'ip', $id );
1915 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1918 $this->invalidateCache();
1923 * Generate a current or new-future timestamp to be stored in the
1924 * user_touched field when we update things.
1925 * @return String Timestamp in TS_MW format
1927 private static function newTouchedTimestamp() {
1928 global $wgClockSkewFudge;
1929 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1933 * Clear user data from memcached.
1934 * Use after applying fun updates to the database; caller's
1935 * responsibility to update user_touched if appropriate.
1937 * Called implicitly from invalidateCache() and saveSettings().
1939 private function clearSharedCache() {
1943 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1948 * Immediately touch the user data cache for this account.
1949 * Updates user_touched field, and removes account data from memcached
1950 * for reload on the next hit.
1952 public function invalidateCache() {
1953 if( wfReadOnly() ) {
1958 $this->mTouched
= self
::newTouchedTimestamp();
1960 $dbw = wfGetDB( DB_MASTER
);
1962 // Prevent contention slams by checking user_touched first
1963 $now = $dbw->timestamp( $this->mTouched
);
1964 $needsPurge = $dbw->selectField( 'user', '1',
1965 array( 'user_id' => $this->mId
, 'user_touched < ' . $dbw->addQuotes( $now ) )
1967 if ( $needsPurge ) {
1968 $dbw->update( 'user',
1969 array( 'user_touched' => $now ),
1970 array( 'user_id' => $this->mId
, 'user_touched < ' . $dbw->addQuotes( $now ) ),
1975 $this->clearSharedCache();
1980 * Validate the cache for this account.
1981 * @param string $timestamp A timestamp in TS_MW format
1985 public function validateCache( $timestamp ) {
1987 return ( $timestamp >= $this->mTouched
);
1991 * Get the user touched timestamp
1992 * @return String timestamp
1994 public function getTouched() {
1996 return $this->mTouched
;
2000 * Set the password and reset the random token.
2001 * Calls through to authentication plugin if necessary;
2002 * will have no effect if the auth plugin refuses to
2003 * pass the change through or if the legal password
2006 * As a special case, setting the password to null
2007 * wipes it, so the account cannot be logged in until
2008 * a new password is set, for instance via e-mail.
2010 * @param string $str New password to set
2011 * @throws PasswordError on failure
2015 public function setPassword( $str ) {
2018 if( $str !== null ) {
2019 if( !$wgAuth->allowPasswordChange() ) {
2020 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2023 if( !$this->isValidPassword( $str ) ) {
2024 global $wgMinimalPasswordLength;
2025 $valid = $this->getPasswordValidity( $str );
2026 if ( is_array( $valid ) ) {
2027 $message = array_shift( $valid );
2031 $params = array( $wgMinimalPasswordLength );
2033 throw new PasswordError( wfMessage( $message, $params )->text() );
2037 if( !$wgAuth->setPassword( $this, $str ) ) {
2038 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2041 $this->setInternalPassword( $str );
2047 * Set the password and reset the random token unconditionally.
2049 * @param string|null $str New password to set or null to set an invalid
2050 * password hash meaning that the user will not be able to log in
2051 * through the web interface.
2053 public function setInternalPassword( $str ) {
2057 if( $str === null ) {
2058 // Save an invalid hash...
2059 $this->mPassword
= '';
2061 $this->mPassword
= self
::crypt( $str );
2063 $this->mNewpassword
= '';
2064 $this->mNewpassTime
= null;
2068 * Get the user's current token.
2069 * @param bool $forceCreation Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility)
2070 * @return String Token
2072 public function getToken( $forceCreation = true ) {
2074 if ( !$this->mToken
&& $forceCreation ) {
2077 return $this->mToken
;
2081 * Set the random token (used for persistent authentication)
2082 * Called from loadDefaults() among other places.
2084 * @param string|bool $token If specified, set the token to this value
2086 public function setToken( $token = false ) {
2089 $this->mToken
= MWCryptRand
::generateHex( USER_TOKEN_LENGTH
);
2091 $this->mToken
= $token;
2096 * Set the password for a password reminder or new account email
2098 * @param string $str New password to set
2099 * @param bool $throttle If true, reset the throttle timestamp to the present
2101 public function setNewpassword( $str, $throttle = true ) {
2103 $this->mNewpassword
= self
::crypt( $str );
2105 $this->mNewpassTime
= wfTimestampNow();
2110 * Has password reminder email been sent within the last
2111 * $wgPasswordReminderResendTime hours?
2114 public function isPasswordReminderThrottled() {
2115 global $wgPasswordReminderResendTime;
2117 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2120 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2121 return time() < $expiry;
2125 * Get the user's e-mail address
2126 * @return String User's email address
2128 public function getEmail() {
2130 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
2131 return $this->mEmail
;
2135 * Get the timestamp of the user's e-mail authentication
2136 * @return String TS_MW timestamp
2138 public function getEmailAuthenticationTimestamp() {
2140 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2141 return $this->mEmailAuthenticated
;
2145 * Set the user's e-mail address
2146 * @param string $str New e-mail address
2148 public function setEmail( $str ) {
2150 if( $str == $this->mEmail
) {
2153 $this->mEmail
= $str;
2154 $this->invalidateEmail();
2155 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
2159 * Set the user's e-mail address and a confirmation mail if needed.
2162 * @param string $str New e-mail address
2165 public function setEmailWithConfirmation( $str ) {
2166 global $wgEnableEmail, $wgEmailAuthentication;
2168 if ( !$wgEnableEmail ) {
2169 return Status
::newFatal( 'emaildisabled' );
2172 $oldaddr = $this->getEmail();
2173 if ( $str === $oldaddr ) {
2174 return Status
::newGood( true );
2177 $this->setEmail( $str );
2179 if ( $str !== '' && $wgEmailAuthentication ) {
2180 # Send a confirmation request to the new address if needed
2181 $type = $oldaddr != '' ?
'changed' : 'set';
2182 $result = $this->sendConfirmationMail( $type );
2183 if ( $result->isGood() ) {
2184 # Say the the caller that a confirmation mail has been sent
2185 $result->value
= 'eauth';
2188 $result = Status
::newGood( true );
2195 * Get the user's real name
2196 * @return String User's real name
2198 public function getRealName() {
2199 if ( !$this->isItemLoaded( 'realname' ) ) {
2203 return $this->mRealName
;
2207 * Set the user's real name
2208 * @param string $str New real name
2210 public function setRealName( $str ) {
2212 $this->mRealName
= $str;
2216 * Get the user's current setting for a given option.
2218 * @param string $oname The option to check
2219 * @param string $defaultOverride A default value returned if the option does not exist
2220 * @param bool $ignoreHidden = whether to ignore the effects of $wgHiddenPrefs
2221 * @return String User's current value for the option
2222 * @see getBoolOption()
2223 * @see getIntOption()
2225 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2226 global $wgHiddenPrefs;
2227 $this->loadOptions();
2229 # We want 'disabled' preferences to always behave as the default value for
2230 # users, even if they have set the option explicitly in their settings (ie they
2231 # set it, and then it was disabled removing their ability to change it). But
2232 # we don't want to erase the preferences in the database in case the preference
2233 # is re-enabled again. So don't touch $mOptions, just override the returned value
2234 if( in_array( $oname, $wgHiddenPrefs ) && !$ignoreHidden ) {
2235 return self
::getDefaultOption( $oname );
2238 if ( array_key_exists( $oname, $this->mOptions
) ) {
2239 return $this->mOptions
[$oname];
2241 return $defaultOverride;
2246 * Get all user's options
2250 public function getOptions() {
2251 global $wgHiddenPrefs;
2252 $this->loadOptions();
2253 $options = $this->mOptions
;
2255 # We want 'disabled' preferences to always behave as the default value for
2256 # users, even if they have set the option explicitly in their settings (ie they
2257 # set it, and then it was disabled removing their ability to change it). But
2258 # we don't want to erase the preferences in the database in case the preference
2259 # is re-enabled again. So don't touch $mOptions, just override the returned value
2260 foreach( $wgHiddenPrefs as $pref ) {
2261 $default = self
::getDefaultOption( $pref );
2262 if( $default !== null ) {
2263 $options[$pref] = $default;
2271 * Get the user's current setting for a given option, as a boolean value.
2273 * @param string $oname The option to check
2274 * @return Bool User's current value for the option
2277 public function getBoolOption( $oname ) {
2278 return (bool)$this->getOption( $oname );
2282 * Get the user's current setting for a given option, as a boolean value.
2284 * @param string $oname The option to check
2285 * @param int $defaultOverride A default value returned if the option does not exist
2286 * @return Int User's current value for the option
2289 public function getIntOption( $oname, $defaultOverride = 0 ) {
2290 $val = $this->getOption( $oname );
2292 $val = $defaultOverride;
2294 return intval( $val );
2298 * Set the given option for a user.
2300 * @param string $oname The option to set
2301 * @param $val mixed New value to set
2303 public function setOption( $oname, $val ) {
2304 $this->loadOptions();
2306 // Explicitly NULL values should refer to defaults
2307 if( is_null( $val ) ) {
2308 $val = self
::getDefaultOption( $oname );
2311 $this->mOptions
[$oname] = $val;
2315 * Return a list of the types of user options currently returned by
2316 * User::getOptionKinds().
2318 * Currently, the option kinds are:
2319 * - 'registered' - preferences which are registered in core MediaWiki or
2320 * by extensions using the UserGetDefaultOptions hook.
2321 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2322 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2323 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2324 * be used by user scripts.
2325 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2326 * These are usually legacy options, removed in newer versions.
2328 * The API (and possibly others) use this function to determine the possible
2329 * option types for validation purposes, so make sure to update this when a
2330 * new option kind is added.
2332 * @see User::getOptionKinds
2333 * @return array Option kinds
2335 public static function listOptionKinds() {
2338 'registered-multiselect',
2339 'registered-checkmatrix',
2346 * Return an associative array mapping preferences keys to the kind of a preference they're
2347 * used for. Different kinds are handled differently when setting or reading preferences.
2349 * See User::listOptionKinds for the list of valid option types that can be provided.
2351 * @see User::listOptionKinds
2352 * @param $context IContextSource
2353 * @param array $options assoc. array with options keys to check as keys. Defaults to $this->mOptions.
2354 * @return array the key => kind mapping data
2356 public function getOptionKinds( IContextSource
$context, $options = null ) {
2357 $this->loadOptions();
2358 if ( $options === null ) {
2359 $options = $this->mOptions
;
2362 $prefs = Preferences
::getPreferences( $this, $context );
2365 // Multiselect and checkmatrix options are stored in the database with
2366 // one key per option, each having a boolean value. Extract those keys.
2367 $multiselectOptions = array();
2368 foreach ( $prefs as $name => $info ) {
2369 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2370 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2371 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2372 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2374 foreach ( $opts as $value ) {
2375 $multiselectOptions["$prefix$value"] = true;
2378 unset( $prefs[$name] );
2381 $checkmatrixOptions = array();
2382 foreach ( $prefs as $name => $info ) {
2383 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2384 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2385 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2386 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2387 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2389 foreach ( $columns as $column ) {
2390 foreach ( $rows as $row ) {
2391 $checkmatrixOptions["$prefix-$column-$row"] = true;
2395 unset( $prefs[$name] );
2399 // $value is ignored
2400 foreach ( $options as $key => $value ) {
2401 if ( isset( $prefs[$key] ) ) {
2402 $mapping[$key] = 'registered';
2403 } elseif( isset( $multiselectOptions[$key] ) ) {
2404 $mapping[$key] = 'registered-multiselect';
2405 } elseif( isset( $checkmatrixOptions[$key] ) ) {
2406 $mapping[$key] = 'registered-checkmatrix';
2407 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2408 $mapping[$key] = 'userjs';
2410 $mapping[$key] = 'unused';
2418 * Reset certain (or all) options to the site defaults
2420 * The optional parameter determines which kinds of preferences will be reset.
2421 * Supported values are everything that can be reported by getOptionKinds()
2422 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2424 * @param array|string $resetKinds which kinds of preferences to reset. Defaults to
2425 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2426 * for backwards-compatibility.
2427 * @param $context IContextSource|null context source used when $resetKinds
2428 * does not contain 'all', passed to getOptionKinds().
2429 * Defaults to RequestContext::getMain() when null.
2431 public function resetOptions(
2432 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2433 IContextSource
$context = null
2436 $defaultOptions = self
::getDefaultOptions();
2438 if ( !is_array( $resetKinds ) ) {
2439 $resetKinds = array( $resetKinds );
2442 if ( in_array( 'all', $resetKinds ) ) {
2443 $newOptions = $defaultOptions;
2445 if ( $context === null ) {
2446 $context = RequestContext
::getMain();
2449 $optionKinds = $this->getOptionKinds( $context );
2450 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2451 $newOptions = array();
2453 // Use default values for the options that should be deleted, and
2454 // copy old values for the ones that shouldn't.
2455 foreach ( $this->mOptions
as $key => $value ) {
2456 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2457 if ( array_key_exists( $key, $defaultOptions ) ) {
2458 $newOptions[$key] = $defaultOptions[$key];
2461 $newOptions[$key] = $value;
2466 $this->mOptions
= $newOptions;
2467 $this->mOptionsLoaded
= true;
2471 * Get the user's preferred date format.
2472 * @return String User's preferred date format
2474 public function getDatePreference() {
2475 // Important migration for old data rows
2476 if ( is_null( $this->mDatePreference
) ) {
2478 $value = $this->getOption( 'date' );
2479 $map = $wgLang->getDatePreferenceMigrationMap();
2480 if ( isset( $map[$value] ) ) {
2481 $value = $map[$value];
2483 $this->mDatePreference
= $value;
2485 return $this->mDatePreference
;
2489 * Get the user preferred stub threshold
2493 public function getStubThreshold() {
2494 global $wgMaxArticleSize; # Maximum article size, in Kb
2495 $threshold = $this->getIntOption( 'stubthreshold' );
2496 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2497 # If they have set an impossible value, disable the preference
2498 # so we can use the parser cache again.
2505 * Get the permissions this user has.
2506 * @return Array of String permission names
2508 public function getRights() {
2509 if ( is_null( $this->mRights
) ) {
2510 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2511 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2512 // Force reindexation of rights when a hook has unset one of them
2513 $this->mRights
= array_values( array_unique( $this->mRights
) );
2515 return $this->mRights
;
2519 * Get the list of explicit group memberships this user has.
2520 * The implicit * and user groups are not included.
2521 * @return Array of String internal group names
2523 public function getGroups() {
2525 $this->loadGroups();
2526 return $this->mGroups
;
2530 * Get the list of implicit group memberships this user has.
2531 * This includes all explicit groups, plus 'user' if logged in,
2532 * '*' for all accounts, and autopromoted groups
2533 * @param bool $recache Whether to avoid the cache
2534 * @return Array of String internal group names
2536 public function getEffectiveGroups( $recache = false ) {
2537 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2538 wfProfileIn( __METHOD__
);
2539 $this->mEffectiveGroups
= array_unique( array_merge(
2540 $this->getGroups(), // explicit groups
2541 $this->getAutomaticGroups( $recache ) // implicit groups
2543 # Hook for additional groups
2544 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2545 // Force reindexation of groups when a hook has unset one of them
2546 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
2547 wfProfileOut( __METHOD__
);
2549 return $this->mEffectiveGroups
;
2553 * Get the list of implicit group memberships this user has.
2554 * This includes 'user' if logged in, '*' for all accounts,
2555 * and autopromoted groups
2556 * @param bool $recache Whether to avoid the cache
2557 * @return Array of String internal group names
2559 public function getAutomaticGroups( $recache = false ) {
2560 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
2561 wfProfileIn( __METHOD__
);
2562 $this->mImplicitGroups
= array( '*' );
2563 if ( $this->getId() ) {
2564 $this->mImplicitGroups
[] = 'user';
2566 $this->mImplicitGroups
= array_unique( array_merge(
2567 $this->mImplicitGroups
,
2568 Autopromote
::getAutopromoteGroups( $this )
2572 # Assure data consistency with rights/groups,
2573 # as getEffectiveGroups() depends on this function
2574 $this->mEffectiveGroups
= null;
2576 wfProfileOut( __METHOD__
);
2578 return $this->mImplicitGroups
;
2582 * Returns the groups the user has belonged to.
2584 * The user may still belong to the returned groups. Compare with getGroups().
2586 * The function will not return groups the user had belonged to before MW 1.17
2588 * @return array Names of the groups the user has belonged to.
2590 public function getFormerGroups() {
2591 if( is_null( $this->mFormerGroups
) ) {
2592 $dbr = wfGetDB( DB_MASTER
);
2593 $res = $dbr->select( 'user_former_groups',
2594 array( 'ufg_group' ),
2595 array( 'ufg_user' => $this->mId
),
2597 $this->mFormerGroups
= array();
2598 foreach( $res as $row ) {
2599 $this->mFormerGroups
[] = $row->ufg_group
;
2602 return $this->mFormerGroups
;
2606 * Get the user's edit count.
2609 public function getEditCount() {
2610 if ( !$this->getId() ) {
2614 if ( !isset( $this->mEditCount
) ) {
2615 /* Populate the count, if it has not been populated yet */
2616 wfProfileIn( __METHOD__
);
2617 $dbr = wfGetDB( DB_SLAVE
);
2618 // check if the user_editcount field has been initialized
2619 $count = $dbr->selectField(
2620 'user', 'user_editcount',
2621 array( 'user_id' => $this->mId
),
2625 if( $count === null ) {
2626 // it has not been initialized. do so.
2627 $count = $this->initEditCount();
2629 $this->mEditCount
= intval( $count );
2630 wfProfileOut( __METHOD__
);
2632 return $this->mEditCount
;
2636 * Add the user to the given group.
2637 * This takes immediate effect.
2638 * @param string $group Name of the group to add
2640 public function addGroup( $group ) {
2641 if( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2642 $dbw = wfGetDB( DB_MASTER
);
2643 if( $this->getId() ) {
2644 $dbw->insert( 'user_groups',
2646 'ug_user' => $this->getID(),
2647 'ug_group' => $group,
2650 array( 'IGNORE' ) );
2653 $this->loadGroups();
2654 $this->mGroups
[] = $group;
2655 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2657 $this->invalidateCache();
2661 * Remove the user from the given group.
2662 * This takes immediate effect.
2663 * @param string $group Name of the group to remove
2665 public function removeGroup( $group ) {
2667 if( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2668 $dbw = wfGetDB( DB_MASTER
);
2669 $dbw->delete( 'user_groups',
2671 'ug_user' => $this->getID(),
2672 'ug_group' => $group,
2674 // Remember that the user was in this group
2675 $dbw->insert( 'user_former_groups',
2677 'ufg_user' => $this->getID(),
2678 'ufg_group' => $group,
2681 array( 'IGNORE' ) );
2683 $this->loadGroups();
2684 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2685 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2687 $this->invalidateCache();
2691 * Get whether the user is logged in
2694 public function isLoggedIn() {
2695 return $this->getID() != 0;
2699 * Get whether the user is anonymous
2702 public function isAnon() {
2703 return !$this->isLoggedIn();
2707 * Check if user is allowed to access a feature / make an action
2709 * @internal param \String $varargs permissions to test
2710 * @return Boolean: True if user is allowed to perform *any* of the given actions
2714 public function isAllowedAny( /*...*/ ) {
2715 $permissions = func_get_args();
2716 foreach( $permissions as $permission ) {
2717 if( $this->isAllowed( $permission ) ) {
2726 * @internal param $varargs string
2727 * @return bool True if the user is allowed to perform *all* of the given actions
2729 public function isAllowedAll( /*...*/ ) {
2730 $permissions = func_get_args();
2731 foreach( $permissions as $permission ) {
2732 if( !$this->isAllowed( $permission ) ) {
2740 * Internal mechanics of testing a permission
2741 * @param $action String
2744 public function isAllowed( $action = '' ) {
2745 if ( $action === '' ) {
2746 return true; // In the spirit of DWIM
2748 # Patrolling may not be enabled
2749 if( $action === 'patrol' ||
$action === 'autopatrol' ) {
2750 global $wgUseRCPatrol, $wgUseNPPatrol;
2751 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2754 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2755 # by misconfiguration: 0 == 'foo'
2756 return in_array( $action, $this->getRights(), true );
2760 * Check whether to enable recent changes patrol features for this user
2761 * @return Boolean: True or false
2763 public function useRCPatrol() {
2764 global $wgUseRCPatrol;
2765 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
2769 * Check whether to enable new pages patrol features for this user
2770 * @return Bool True or false
2772 public function useNPPatrol() {
2773 global $wgUseRCPatrol, $wgUseNPPatrol;
2774 return( ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) ) );
2778 * Get the WebRequest object to use with this object
2780 * @return WebRequest
2782 public function getRequest() {
2783 if ( $this->mRequest
) {
2784 return $this->mRequest
;
2792 * Get the current skin, loading it if required
2793 * @return Skin The current skin
2794 * @todo FIXME: Need to check the old failback system [AV]
2795 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
2797 public function getSkin() {
2798 wfDeprecated( __METHOD__
, '1.18' );
2799 return RequestContext
::getMain()->getSkin();
2803 * Get a WatchedItem for this user and $title.
2805 * @param $title Title
2806 * @return WatchedItem
2808 public function getWatchedItem( $title ) {
2809 $key = $title->getNamespace() . ':' . $title->getDBkey();
2811 if ( isset( $this->mWatchedItems
[$key] ) ) {
2812 return $this->mWatchedItems
[$key];
2815 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
2816 $this->mWatchedItems
= array();
2819 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title );
2820 return $this->mWatchedItems
[$key];
2824 * Check the watched status of an article.
2825 * @param $title Title of the article to look at
2828 public function isWatched( $title ) {
2829 return $this->getWatchedItem( $title )->isWatched();
2834 * @param $title Title of the article to look at
2836 public function addWatch( $title ) {
2837 $this->getWatchedItem( $title )->addWatch();
2838 $this->invalidateCache();
2842 * Stop watching an article.
2843 * @param $title Title of the article to look at
2845 public function removeWatch( $title ) {
2846 $this->getWatchedItem( $title )->removeWatch();
2847 $this->invalidateCache();
2851 * Clear the user's notification timestamp for the given title.
2852 * If e-notif e-mails are on, they will receive notification mails on
2853 * the next change of the page if it's watched etc.
2854 * @param $title Title of the article to look at
2856 public function clearNotification( &$title ) {
2857 global $wgUseEnotif, $wgShowUpdatedMarker;
2859 # Do nothing if the database is locked to writes
2860 if( wfReadOnly() ) {
2864 if( $title->getNamespace() == NS_USER_TALK
&&
2865 $title->getText() == $this->getName() ) {
2866 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2868 $this->setNewtalk( false );
2871 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2875 if( $this->isAnon() ) {
2876 // Nothing else to do...
2880 // Only update the timestamp if the page is being watched.
2881 // The query to find out if it is watched is cached both in memcached and per-invocation,
2882 // and when it does have to be executed, it can be on a slave
2883 // If this is the user's newtalk page, we always update the timestamp
2885 if ( $title->getNamespace() == NS_USER_TALK
&&
2886 $title->getText() == $this->getName() )
2891 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force );
2895 * Resets all of the given user's page-change notification timestamps.
2896 * If e-notif e-mails are on, they will receive notification mails on
2897 * the next change of any watched page.
2899 public function clearAllNotifications() {
2900 if ( wfReadOnly() ) {
2904 global $wgUseEnotif, $wgShowUpdatedMarker;
2905 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2906 $this->setNewtalk( false );
2909 $id = $this->getId();
2911 $dbw = wfGetDB( DB_MASTER
);
2912 $dbw->update( 'watchlist',
2914 'wl_notificationtimestamp' => null
2915 ), array( /* WHERE */
2919 # We also need to clear here the "you have new message" notification for the own user_talk page
2920 # This is cleared one page view later in Article::viewUpdates();
2925 * Set this user's options from an encoded string
2926 * @param string $str Encoded options to import
2928 * @deprecated in 1.19 due to removal of user_options from the user table
2930 private function decodeOptions( $str ) {
2931 wfDeprecated( __METHOD__
, '1.19' );
2935 $this->mOptionsLoaded
= true;
2936 $this->mOptionOverrides
= array();
2938 // If an option is not set in $str, use the default value
2939 $this->mOptions
= self
::getDefaultOptions();
2941 $a = explode( "\n", $str );
2942 foreach ( $a as $s ) {
2944 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2945 $this->mOptions
[$m[1]] = $m[2];
2946 $this->mOptionOverrides
[$m[1]] = $m[2];
2952 * Set a cookie on the user's client. Wrapper for
2953 * WebResponse::setCookie
2954 * @param string $name Name of the cookie to set
2955 * @param string $value Value to set
2956 * @param int $exp Expiration time, as a UNIX time value;
2957 * if 0 or not specified, use the default $wgCookieExpiration
2958 * @param $secure Bool
2959 * true: Force setting the secure attribute when setting the cookie
2960 * false: Force NOT setting the secure attribute when setting the cookie
2961 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
2963 protected function setCookie( $name, $value, $exp = 0, $secure = null ) {
2964 $this->getRequest()->response()->setcookie( $name, $value, $exp, null, null, $secure );
2968 * Clear a cookie on the user's client
2969 * @param string $name Name of the cookie to clear
2971 protected function clearCookie( $name ) {
2972 $this->setCookie( $name, '', time() - 86400 );
2976 * Set the default cookies for this session on the user's client.
2978 * @param $request WebRequest object to use; $wgRequest will be used if null
2980 * @param bool $secure Whether to force secure/insecure cookies or use default
2982 public function setCookies( $request = null, $secure = null ) {
2983 if ( $request === null ) {
2984 $request = $this->getRequest();
2988 if ( 0 == $this->mId
) {
2991 if ( !$this->mToken
) {
2992 // When token is empty or NULL generate a new one and then save it to the database
2993 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
2994 // Simply by setting every cell in the user_token column to NULL and letting them be
2995 // regenerated as users log back into the wiki.
2997 $this->saveSettings();
3000 'wsUserID' => $this->mId
,
3001 'wsToken' => $this->mToken
,
3002 'wsUserName' => $this->getName()
3005 'UserID' => $this->mId
,
3006 'UserName' => $this->getName(),
3008 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
3009 $cookies['Token'] = $this->mToken
;
3011 $cookies['Token'] = false;
3014 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3016 foreach ( $session as $name => $value ) {
3017 $request->setSessionData( $name, $value );
3019 foreach ( $cookies as $name => $value ) {
3020 if ( $value === false ) {
3021 $this->clearCookie( $name );
3023 $this->setCookie( $name, $value, 0, $secure );
3028 * If wpStickHTTPS was selected, also set an insecure cookie that
3029 * will cause the site to redirect the user to HTTPS, if they access
3030 * it over HTTP. Bug 29898.
3032 if ( $request->getCheck( 'wpStickHTTPS' ) ) {
3033 $this->setCookie( 'forceHTTPS', 'true', time() +
2592000, false ); //30 days
3038 * Log this user out.
3040 public function logout() {
3041 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3047 * Clear the user's cookies and session, and reset the instance cache.
3050 public function doLogout() {
3051 $this->clearInstanceCache( 'defaults' );
3053 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3055 $this->clearCookie( 'UserID' );
3056 $this->clearCookie( 'Token' );
3057 $this->clearCookie( 'forceHTTPS' );
3059 # Remember when user logged out, to prevent seeing cached pages
3060 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
3064 * Save this user's settings into the database.
3065 * @todo Only rarely do all these fields need to be set!
3067 public function saveSettings() {
3071 if ( wfReadOnly() ) { return; }
3072 if ( 0 == $this->mId
) { return; }
3074 $this->mTouched
= self
::newTouchedTimestamp();
3075 if ( !$wgAuth->allowSetLocalPassword() ) {
3076 $this->mPassword
= '';
3079 $dbw = wfGetDB( DB_MASTER
);
3080 $dbw->update( 'user',
3082 'user_name' => $this->mName
,
3083 'user_password' => $this->mPassword
,
3084 'user_newpassword' => $this->mNewpassword
,
3085 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3086 'user_real_name' => $this->mRealName
,
3087 'user_email' => $this->mEmail
,
3088 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3089 'user_touched' => $dbw->timestamp( $this->mTouched
),
3090 'user_token' => strval( $this->mToken
),
3091 'user_email_token' => $this->mEmailToken
,
3092 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3093 ), array( /* WHERE */
3094 'user_id' => $this->mId
3098 $this->saveOptions();
3100 wfRunHooks( 'UserSaveSettings', array( $this ) );
3101 $this->clearSharedCache();
3102 $this->getUserPage()->invalidateCache();
3106 * If only this user's username is known, and it exists, return the user ID.
3109 public function idForName() {
3110 $s = trim( $this->getName() );
3111 if ( $s === '' ) return 0;
3113 $dbr = wfGetDB( DB_SLAVE
);
3114 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
3115 if ( $id === false ) {
3122 * Add a user to the database, return the user object
3124 * @param string $name Username to add
3125 * @param array $params of Strings Non-default parameters to save to the database as user_* fields:
3126 * - password The user's password hash. Password logins will be disabled if this is omitted.
3127 * - newpassword Hash for a temporary password that has been mailed to the user
3128 * - email The user's email address
3129 * - email_authenticated The email authentication timestamp
3130 * - real_name The user's real name
3131 * - options An associative array of non-default options
3132 * - token Random authentication token. Do not set.
3133 * - registration Registration timestamp. Do not set.
3135 * @return User object, or null if the username already exists
3137 public static function createNew( $name, $params = array() ) {
3140 $user->setToken(); // init token
3141 if ( isset( $params['options'] ) ) {
3142 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3143 unset( $params['options'] );
3145 $dbw = wfGetDB( DB_MASTER
);
3146 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3149 'user_id' => $seqVal,
3150 'user_name' => $name,
3151 'user_password' => $user->mPassword
,
3152 'user_newpassword' => $user->mNewpassword
,
3153 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3154 'user_email' => $user->mEmail
,
3155 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3156 'user_real_name' => $user->mRealName
,
3157 'user_token' => strval( $user->mToken
),
3158 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3159 'user_editcount' => 0,
3160 'user_touched' => $dbw->timestamp( self
::newTouchedTimestamp() ),
3162 foreach ( $params as $name => $value ) {
3163 $fields["user_$name"] = $value;
3165 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3166 if ( $dbw->affectedRows() ) {
3167 $newUser = User
::newFromId( $dbw->insertId() );
3175 * Add this existing user object to the database. If the user already
3176 * exists, a fatal status object is returned, and the user object is
3177 * initialised with the data from the database.
3179 * Previously, this function generated a DB error due to a key conflict
3180 * if the user already existed. Many extension callers use this function
3181 * in code along the lines of:
3183 * $user = User::newFromName( $name );
3184 * if ( !$user->isLoggedIn() ) {
3185 * $user->addToDatabase();
3187 * // do something with $user...
3189 * However, this was vulnerable to a race condition (bug 16020). By
3190 * initialising the user object if the user exists, we aim to support this
3191 * calling sequence as far as possible.
3193 * Note that if the user exists, this function will acquire a write lock,
3194 * so it is still advisable to make the call conditional on isLoggedIn(),
3195 * and to commit the transaction after calling.
3197 * @throws MWException
3200 public function addToDatabase() {
3202 if ( !$this->mToken
) {
3203 $this->setToken(); // init token
3206 $this->mTouched
= self
::newTouchedTimestamp();
3208 $dbw = wfGetDB( DB_MASTER
);
3209 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3210 $dbw->insert( 'user',
3212 'user_id' => $seqVal,
3213 'user_name' => $this->mName
,
3214 'user_password' => $this->mPassword
,
3215 'user_newpassword' => $this->mNewpassword
,
3216 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3217 'user_email' => $this->mEmail
,
3218 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3219 'user_real_name' => $this->mRealName
,
3220 'user_token' => strval( $this->mToken
),
3221 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3222 'user_editcount' => 0,
3223 'user_touched' => $dbw->timestamp( $this->mTouched
),
3227 if ( !$dbw->affectedRows() ) {
3228 $this->mId
= $dbw->selectField( 'user', 'user_id',
3229 array( 'user_name' => $this->mName
), __METHOD__
);
3232 if ( $this->loadFromDatabase() ) {
3237 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3238 "to insert a user row, but then it doesn't exist when we select it!" );
3240 return Status
::newFatal( 'userexists' );
3242 $this->mId
= $dbw->insertId();
3244 // Clear instance cache other than user table data, which is already accurate
3245 $this->clearInstanceCache();
3247 $this->saveOptions();
3248 return Status
::newGood();
3252 * If this user is logged-in and blocked,
3253 * block any IP address they've successfully logged in from.
3254 * @return bool A block was spread
3256 public function spreadAnyEditBlock() {
3257 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3258 return $this->spreadBlock();
3264 * If this (non-anonymous) user is blocked,
3265 * block the IP address they've successfully logged in from.
3266 * @return bool A block was spread
3268 protected function spreadBlock() {
3269 wfDebug( __METHOD__
. "()\n" );
3271 if ( $this->mId
== 0 ) {
3275 $userblock = Block
::newFromTarget( $this->getName() );
3276 if ( !$userblock ) {
3280 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3284 * Generate a string which will be different for any combination of
3285 * user options which would produce different parser output.
3286 * This will be used as part of the hash key for the parser cache,
3287 * so users with the same options can share the same cached data
3290 * Extensions which require it should install 'PageRenderingHash' hook,
3291 * which will give them a chance to modify this key based on their own
3294 * @deprecated since 1.17 use the ParserOptions object to get the relevant options
3295 * @return String Page rendering hash
3297 public function getPageRenderingHash() {
3298 wfDeprecated( __METHOD__
, '1.17' );
3300 global $wgRenderHashAppend, $wgLang, $wgContLang;
3301 if( $this->mHash
) {
3302 return $this->mHash
;
3305 // stubthreshold is only included below for completeness,
3306 // since it disables the parser cache, its value will always
3307 // be 0 when this function is called by parsercache.
3309 $confstr = $this->getOption( 'math' );
3310 $confstr .= '!' . $this->getStubThreshold();
3311 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ?
'1' : '' );
3312 $confstr .= '!' . $wgLang->getCode();
3313 $confstr .= '!' . $this->getOption( 'thumbsize' );
3314 // add in language specific options, if any
3315 $extra = $wgContLang->getExtraHashOptions();
3318 // Since the skin could be overloading link(), it should be
3319 // included here but in practice, none of our skins do that.
3321 $confstr .= $wgRenderHashAppend;
3323 // Give a chance for extensions to modify the hash, if they have
3324 // extra options or other effects on the parser cache.
3325 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
3327 // Make it a valid memcached key fragment
3328 $confstr = str_replace( ' ', '_', $confstr );
3329 $this->mHash
= $confstr;
3334 * Get whether the user is explicitly blocked from account creation.
3335 * @return Bool|Block
3337 public function isBlockedFromCreateAccount() {
3338 $this->getBlockedStatus();
3339 if( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3340 return $this->mBlock
;
3343 # bug 13611: if the IP address the user is trying to create an account from is
3344 # blocked with createaccount disabled, prevent new account creation there even
3345 # when the user is logged in
3346 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3347 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3349 return $this->mBlockedFromCreateAccount
instanceof Block
&& $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3350 ?
$this->mBlockedFromCreateAccount
3355 * Get whether the user is blocked from using Special:Emailuser.
3358 public function isBlockedFromEmailuser() {
3359 $this->getBlockedStatus();
3360 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3364 * Get whether the user is allowed to create an account.
3367 function isAllowedToCreateAccount() {
3368 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3372 * Get this user's personal page title.
3374 * @return Title: User's personal page title
3376 public function getUserPage() {
3377 return Title
::makeTitle( NS_USER
, $this->getName() );
3381 * Get this user's talk page title.
3383 * @return Title: User's talk page title
3385 public function getTalkPage() {
3386 $title = $this->getUserPage();
3387 return $title->getTalkPage();
3391 * Determine whether the user is a newbie. Newbies are either
3392 * anonymous IPs, or the most recently created accounts.
3395 public function isNewbie() {
3396 return !$this->isAllowed( 'autoconfirmed' );
3400 * Check to see if the given clear-text password is one of the accepted passwords
3401 * @param string $password user password.
3402 * @return Boolean: True if the given password is correct, otherwise False.
3404 public function checkPassword( $password ) {
3405 global $wgAuth, $wgLegacyEncoding;
3408 // Even though we stop people from creating passwords that
3409 // are shorter than this, doesn't mean people wont be able
3410 // to. Certain authentication plugins do NOT want to save
3411 // domain passwords in a mysql database, so we should
3412 // check this (in case $wgAuth->strict() is false).
3413 if( !$this->isValidPassword( $password ) ) {
3417 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
3419 } elseif( $wgAuth->strict() ) {
3420 /* Auth plugin doesn't allow local authentication */
3422 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
3423 /* Auth plugin doesn't allow local authentication for this user name */
3426 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
3428 } elseif ( $wgLegacyEncoding ) {
3429 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3430 # Check for this with iconv
3431 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3432 if ( $cp1252Password != $password &&
3433 self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) )
3442 * Check if the given clear-text password matches the temporary password
3443 * sent by e-mail for password reset operations.
3445 * @param $plaintext string
3447 * @return Boolean: True if matches, false otherwise
3449 public function checkTemporaryPassword( $plaintext ) {
3450 global $wgNewPasswordExpiry;
3453 if( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
3454 if ( is_null( $this->mNewpassTime
) ) {
3457 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3458 return ( time() < $expiry );
3465 * Alias for getEditToken.
3466 * @deprecated since 1.19, use getEditToken instead.
3468 * @param string|array $salt of Strings Optional function-specific data for hashing
3469 * @param $request WebRequest object to use or null to use $wgRequest
3470 * @return String The new edit token
3472 public function editToken( $salt = '', $request = null ) {
3473 wfDeprecated( __METHOD__
, '1.19' );
3474 return $this->getEditToken( $salt, $request );
3478 * Initialize (if necessary) and return a session token value
3479 * which can be used in edit forms to show that the user's
3480 * login credentials aren't being hijacked with a foreign form
3485 * @param string|array $salt of Strings Optional function-specific data for hashing
3486 * @param $request WebRequest object to use or null to use $wgRequest
3487 * @return String The new edit token
3489 public function getEditToken( $salt = '', $request = null ) {
3490 if ( $request == null ) {
3491 $request = $this->getRequest();
3494 if ( $this->isAnon() ) {
3495 return EDIT_TOKEN_SUFFIX
;
3497 $token = $request->getSessionData( 'wsEditToken' );
3498 if ( $token === null ) {
3499 $token = MWCryptRand
::generateHex( 32 );
3500 $request->setSessionData( 'wsEditToken', $token );
3502 if( is_array( $salt ) ) {
3503 $salt = implode( '|', $salt );
3505 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
3510 * Generate a looking random token for various uses.
3512 * @return String The new random token
3513 * @deprecated since 1.20; Use MWCryptRand for secure purposes or wfRandomString for pseudo-randomness
3515 public static function generateToken() {
3516 return MWCryptRand
::generateHex( 32 );
3520 * Check given value against the token value stored in the session.
3521 * A match should confirm that the form was submitted from the
3522 * user's own login session, not a form submission from a third-party
3525 * @param string $val Input value to compare
3526 * @param string $salt Optional function-specific data for hashing
3527 * @param $request WebRequest object to use or null to use $wgRequest
3528 * @return Boolean: Whether the token matches
3530 public function matchEditToken( $val, $salt = '', $request = null ) {
3531 $sessionToken = $this->getEditToken( $salt, $request );
3532 if ( $val != $sessionToken ) {
3533 wfDebug( "User::matchEditToken: broken session data\n" );
3535 return $val == $sessionToken;
3539 * Check given value against the token value stored in the session,
3540 * ignoring the suffix.
3542 * @param string $val Input value to compare
3543 * @param string $salt Optional function-specific data for hashing
3544 * @param $request WebRequest object to use or null to use $wgRequest
3545 * @return Boolean: Whether the token matches
3547 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3548 $sessionToken = $this->getEditToken( $salt, $request );
3549 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3553 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3554 * mail to the user's given address.
3556 * @param string $type message to send, either "created", "changed" or "set"
3557 * @return Status object
3559 public function sendConfirmationMail( $type = 'created' ) {
3561 $expiration = null; // gets passed-by-ref and defined in next line.
3562 $token = $this->confirmationToken( $expiration );
3563 $url = $this->confirmationTokenUrl( $token );
3564 $invalidateURL = $this->invalidationTokenUrl( $token );
3565 $this->saveSettings();
3567 if ( $type == 'created' ||
$type === false ) {
3568 $message = 'confirmemail_body';
3569 } elseif ( $type === true ) {
3570 $message = 'confirmemail_body_changed';
3572 $message = 'confirmemail_body_' . $type;
3575 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3576 wfMessage( $message,
3577 $this->getRequest()->getIP(),
3580 $wgLang->timeanddate( $expiration, false ),
3582 $wgLang->date( $expiration, false ),
3583 $wgLang->time( $expiration, false ) )->text() );
3587 * Send an e-mail to this user's account. Does not check for
3588 * confirmed status or validity.
3590 * @param string $subject Message subject
3591 * @param string $body Message body
3592 * @param string $from Optional From address; if unspecified, default $wgPasswordSender will be used
3593 * @param string $replyto Reply-To address
3596 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3597 if( is_null( $from ) ) {
3598 global $wgPasswordSender, $wgPasswordSenderName;
3599 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
3601 $sender = new MailAddress( $from );
3604 $to = new MailAddress( $this );
3605 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
3609 * Generate, store, and return a new e-mail confirmation code.
3610 * A hash (unsalted, since it's used as a key) is stored.
3612 * @note Call saveSettings() after calling this function to commit
3613 * this change to the database.
3615 * @param &$expiration \mixed Accepts the expiration time
3616 * @return String New token
3618 private function confirmationToken( &$expiration ) {
3619 global $wgUserEmailConfirmationTokenExpiry;
3621 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
3622 $expiration = wfTimestamp( TS_MW
, $expires );
3624 $token = MWCryptRand
::generateHex( 32 );
3625 $hash = md5( $token );
3626 $this->mEmailToken
= $hash;
3627 $this->mEmailTokenExpires
= $expiration;
3632 * Return a URL the user can use to confirm their email address.
3633 * @param string $token Accepts the email confirmation token
3634 * @return String New token URL
3636 private function confirmationTokenUrl( $token ) {
3637 return $this->getTokenUrl( 'ConfirmEmail', $token );
3641 * Return a URL the user can use to invalidate their email address.
3642 * @param string $token Accepts the email confirmation token
3643 * @return String New token URL
3645 private function invalidationTokenUrl( $token ) {
3646 return $this->getTokenUrl( 'InvalidateEmail', $token );
3650 * Internal function to format the e-mail validation/invalidation URLs.
3651 * This uses a quickie hack to use the
3652 * hardcoded English names of the Special: pages, for ASCII safety.
3654 * @note Since these URLs get dropped directly into emails, using the
3655 * short English names avoids insanely long URL-encoded links, which
3656 * also sometimes can get corrupted in some browsers/mailers
3657 * (bug 6957 with Gmail and Internet Explorer).
3659 * @param string $page Special page
3660 * @param string $token Token
3661 * @return String Formatted URL
3663 protected function getTokenUrl( $page, $token ) {
3664 // Hack to bypass localization of 'Special:'
3665 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
3666 return $title->getCanonicalURL();
3670 * Mark the e-mail address confirmed.
3672 * @note Call saveSettings() after calling this function to commit the change.
3676 public function confirmEmail() {
3677 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3678 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3683 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3684 * address if it was already confirmed.
3686 * @note Call saveSettings() after calling this function to commit the change.
3687 * @return bool Returns true
3689 function invalidateEmail() {
3691 $this->mEmailToken
= null;
3692 $this->mEmailTokenExpires
= null;
3693 $this->setEmailAuthenticationTimestamp( null );
3694 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3699 * Set the e-mail authentication timestamp.
3700 * @param string $timestamp TS_MW timestamp
3702 function setEmailAuthenticationTimestamp( $timestamp ) {
3704 $this->mEmailAuthenticated
= $timestamp;
3705 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
3709 * Is this user allowed to send e-mails within limits of current
3710 * site configuration?
3713 public function canSendEmail() {
3714 global $wgEnableEmail, $wgEnableUserEmail;
3715 if( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
3718 $canSend = $this->isEmailConfirmed();
3719 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3724 * Is this user allowed to receive e-mails within limits of current
3725 * site configuration?
3728 public function canReceiveEmail() {
3729 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3733 * Is this user's e-mail address valid-looking and confirmed within
3734 * limits of the current site configuration?
3736 * @note If $wgEmailAuthentication is on, this may require the user to have
3737 * confirmed their address by returning a code or using a password
3738 * sent to the address from the wiki.
3742 public function isEmailConfirmed() {
3743 global $wgEmailAuthentication;
3746 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3747 if( $this->isAnon() ) {
3750 if( !Sanitizer
::validateEmail( $this->mEmail
) ) {
3753 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
3763 * Check whether there is an outstanding request for e-mail confirmation.
3766 public function isEmailConfirmationPending() {
3767 global $wgEmailAuthentication;
3768 return $wgEmailAuthentication &&
3769 !$this->isEmailConfirmed() &&
3770 $this->mEmailToken
&&
3771 $this->mEmailTokenExpires
> wfTimestamp();
3775 * Get the timestamp of account creation.
3777 * @return String|Bool|Null Timestamp of account creation, false for
3778 * non-existent/anonymous user accounts, or null if existing account
3779 * but information is not in database.
3781 public function getRegistration() {
3782 if ( $this->isAnon() ) {
3786 return $this->mRegistration
;
3790 * Get the timestamp of the first edit
3792 * @return String|Bool Timestamp of first edit, or false for
3793 * non-existent/anonymous user accounts.
3795 public function getFirstEditTimestamp() {
3796 if( $this->getId() == 0 ) {
3797 return false; // anons
3799 $dbr = wfGetDB( DB_SLAVE
);
3800 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3801 array( 'rev_user' => $this->getId() ),
3803 array( 'ORDER BY' => 'rev_timestamp ASC' )
3806 return false; // no edits
3808 return wfTimestamp( TS_MW
, $time );
3812 * Get the permissions associated with a given list of groups
3814 * @param array $groups of Strings List of internal group names
3815 * @return Array of Strings List of permission key names for given groups combined
3817 public static function getGroupPermissions( $groups ) {
3818 global $wgGroupPermissions, $wgRevokePermissions;
3820 // grant every granted permission first
3821 foreach( $groups as $group ) {
3822 if( isset( $wgGroupPermissions[$group] ) ) {
3823 $rights = array_merge( $rights,
3824 // array_filter removes empty items
3825 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3828 // now revoke the revoked permissions
3829 foreach( $groups as $group ) {
3830 if( isset( $wgRevokePermissions[$group] ) ) {
3831 $rights = array_diff( $rights,
3832 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3835 return array_unique( $rights );
3839 * Get all the groups who have a given permission
3841 * @param string $role Role to check
3842 * @return Array of Strings List of internal group names with the given permission
3844 public static function getGroupsWithPermission( $role ) {
3845 global $wgGroupPermissions;
3846 $allowedGroups = array();
3847 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
3848 if ( self
::groupHasPermission( $group, $role ) ) {
3849 $allowedGroups[] = $group;
3852 return $allowedGroups;
3856 * Check, if the given group has the given permission
3858 * @param string $group Group to check
3859 * @param string $role Role to check
3862 public static function groupHasPermission( $group, $role ) {
3863 global $wgGroupPermissions, $wgRevokePermissions;
3864 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
3865 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
3869 * Get the localized descriptive name for a group, if it exists
3871 * @param string $group Internal group name
3872 * @return String Localized descriptive group name
3874 public static function getGroupName( $group ) {
3875 $msg = wfMessage( "group-$group" );
3876 return $msg->isBlank() ?
$group : $msg->text();
3880 * Get the localized descriptive name for a member of a group, if it exists
3882 * @param string $group Internal group name
3883 * @param string $username Username for gender (since 1.19)
3884 * @return String Localized name for group member
3886 public static function getGroupMember( $group, $username = '#' ) {
3887 $msg = wfMessage( "group-$group-member", $username );
3888 return $msg->isBlank() ?
$group : $msg->text();
3892 * Return the set of defined explicit groups.
3893 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3894 * are not included, as they are defined automatically, not in the database.
3895 * @return Array of internal group names
3897 public static function getAllGroups() {
3898 global $wgGroupPermissions, $wgRevokePermissions;
3900 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3901 self
::getImplicitGroups()
3906 * Get a list of all available permissions.
3907 * @return Array of permission names
3909 public static function getAllRights() {
3910 if ( self
::$mAllRights === false ) {
3911 global $wgAvailableRights;
3912 if ( count( $wgAvailableRights ) ) {
3913 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3915 self
::$mAllRights = self
::$mCoreRights;
3917 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3919 return self
::$mAllRights;
3923 * Get a list of implicit groups
3924 * @return Array of Strings Array of internal group names
3926 public static function getImplicitGroups() {
3927 global $wgImplicitGroups;
3928 $groups = $wgImplicitGroups;
3929 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3934 * Get the title of a page describing a particular group
3936 * @param string $group Internal group name
3937 * @return Title|Bool Title of the page if it exists, false otherwise
3939 public static function getGroupPage( $group ) {
3940 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
3941 if( $msg->exists() ) {
3942 $title = Title
::newFromText( $msg->text() );
3943 if( is_object( $title ) )
3950 * Create a link to the group in HTML, if available;
3951 * else return the group name.
3953 * @param string $group Internal name of the group
3954 * @param string $text The text of the link
3955 * @return String HTML link to the group
3957 public static function makeGroupLinkHTML( $group, $text = '' ) {
3959 $text = self
::getGroupName( $group );
3961 $title = self
::getGroupPage( $group );
3963 return Linker
::link( $title, htmlspecialchars( $text ) );
3970 * Create a link to the group in Wikitext, if available;
3971 * else return the group name.
3973 * @param string $group Internal name of the group
3974 * @param string $text The text of the link
3975 * @return String Wikilink to the group
3977 public static function makeGroupLinkWiki( $group, $text = '' ) {
3979 $text = self
::getGroupName( $group );
3981 $title = self
::getGroupPage( $group );
3983 $page = $title->getPrefixedText();
3984 return "[[$page|$text]]";
3991 * Returns an array of the groups that a particular group can add/remove.
3993 * @param string $group the group to check for whether it can add/remove
3994 * @return Array array( 'add' => array( addablegroups ),
3995 * 'remove' => array( removablegroups ),
3996 * 'add-self' => array( addablegroups to self),
3997 * 'remove-self' => array( removable groups from self) )
3999 public static function changeableByGroup( $group ) {
4000 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4002 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
4003 if( empty( $wgAddGroups[$group] ) ) {
4004 // Don't add anything to $groups
4005 } elseif( $wgAddGroups[$group] === true ) {
4006 // You get everything
4007 $groups['add'] = self
::getAllGroups();
4008 } elseif( is_array( $wgAddGroups[$group] ) ) {
4009 $groups['add'] = $wgAddGroups[$group];
4012 // Same thing for remove
4013 if( empty( $wgRemoveGroups[$group] ) ) {
4014 } elseif( $wgRemoveGroups[$group] === true ) {
4015 $groups['remove'] = self
::getAllGroups();
4016 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
4017 $groups['remove'] = $wgRemoveGroups[$group];
4020 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4021 if( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4022 foreach( $wgGroupsAddToSelf as $key => $value ) {
4023 if( is_int( $key ) ) {
4024 $wgGroupsAddToSelf['user'][] = $value;
4029 if( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4030 foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
4031 if( is_int( $key ) ) {
4032 $wgGroupsRemoveFromSelf['user'][] = $value;
4037 // Now figure out what groups the user can add to him/herself
4038 if( empty( $wgGroupsAddToSelf[$group] ) ) {
4039 } elseif( $wgGroupsAddToSelf[$group] === true ) {
4040 // No idea WHY this would be used, but it's there
4041 $groups['add-self'] = User
::getAllGroups();
4042 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
4043 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4046 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4047 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
4048 $groups['remove-self'] = User
::getAllGroups();
4049 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4050 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4057 * Returns an array of groups that this user can add and remove
4058 * @return Array array( 'add' => array( addablegroups ),
4059 * 'remove' => array( removablegroups ),
4060 * 'add-self' => array( addablegroups to self),
4061 * 'remove-self' => array( removable groups from self) )
4063 public function changeableGroups() {
4064 if( $this->isAllowed( 'userrights' ) ) {
4065 // This group gives the right to modify everything (reverse-
4066 // compatibility with old "userrights lets you change
4068 // Using array_merge to make the groups reindexed
4069 $all = array_merge( User
::getAllGroups() );
4073 'add-self' => array(),
4074 'remove-self' => array()
4078 // Okay, it's not so simple, we will have to go through the arrays
4081 'remove' => array(),
4082 'add-self' => array(),
4083 'remove-self' => array()
4085 $addergroups = $this->getEffectiveGroups();
4087 foreach( $addergroups as $addergroup ) {
4088 $groups = array_merge_recursive(
4089 $groups, $this->changeableByGroup( $addergroup )
4091 $groups['add'] = array_unique( $groups['add'] );
4092 $groups['remove'] = array_unique( $groups['remove'] );
4093 $groups['add-self'] = array_unique( $groups['add-self'] );
4094 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4100 * Increment the user's edit-count field.
4101 * Will have no effect for anonymous users.
4103 public function incEditCount() {
4104 if( !$this->isAnon() ) {
4105 $dbw = wfGetDB( DB_MASTER
);
4108 array( 'user_editcount=user_editcount+1' ),
4109 array( 'user_id' => $this->getId() ),
4113 // Lazy initialization check...
4114 if( $dbw->affectedRows() == 0 ) {
4115 // Now here's a goddamn hack...
4116 $dbr = wfGetDB( DB_SLAVE
);
4117 if( $dbr !== $dbw ) {
4118 // If we actually have a slave server, the count is
4119 // at least one behind because the current transaction
4120 // has not been committed and replicated.
4121 $this->initEditCount( 1 );
4123 // But if DB_SLAVE is selecting the master, then the
4124 // count we just read includes the revision that was
4125 // just added in the working transaction.
4126 $this->initEditCount();
4130 // edit count in user cache too
4131 $this->invalidateCache();
4135 * Initialize user_editcount from data out of the revision table
4137 * @param $add Integer Edits to add to the count from the revision table
4138 * @return Integer Number of edits
4140 protected function initEditCount( $add = 0 ) {
4141 // Pull from a slave to be less cruel to servers
4142 // Accuracy isn't the point anyway here
4143 $dbr = wfGetDB( DB_SLAVE
);
4144 $count = (int) $dbr->selectField(
4147 array( 'rev_user' => $this->getId() ),
4150 $count = $count +
$add;
4152 $dbw = wfGetDB( DB_MASTER
);
4155 array( 'user_editcount' => $count ),
4156 array( 'user_id' => $this->getId() ),
4164 * Get the description of a given right
4166 * @param string $right Right to query
4167 * @return String Localized description of the right
4169 public static function getRightDescription( $right ) {
4170 $key = "right-$right";
4171 $msg = wfMessage( $key );
4172 return $msg->isBlank() ?
$right : $msg->text();
4176 * Make an old-style password hash
4178 * @param string $password Plain-text password
4179 * @param string $userId User ID
4180 * @return String Password hash
4182 public static function oldCrypt( $password, $userId ) {
4183 global $wgPasswordSalt;
4184 if ( $wgPasswordSalt ) {
4185 return md5( $userId . '-' . md5( $password ) );
4187 return md5( $password );
4192 * Make a new-style password hash
4194 * @param string $password Plain-text password
4195 * @param bool|string $salt Optional salt, may be random or the user ID.
4197 * If unspecified or false, will generate one automatically
4198 * @return String Password hash
4200 public static function crypt( $password, $salt = false ) {
4201 global $wgPasswordSalt;
4204 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4208 if( $wgPasswordSalt ) {
4209 if ( $salt === false ) {
4210 $salt = MWCryptRand
::generateHex( 8 );
4212 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4214 return ':A:' . md5( $password );
4219 * Compare a password hash with a plain-text password. Requires the user
4220 * ID if there's a chance that the hash is an old-style hash.
4222 * @param string $hash Password hash
4223 * @param string $password Plain-text password to compare
4224 * @param string|bool $userId User ID for old-style password salt
4228 public static function comparePasswords( $hash, $password, $userId = false ) {
4229 $type = substr( $hash, 0, 3 );
4232 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4236 if ( $type == ':A:' ) {
4238 return md5( $password ) === substr( $hash, 3 );
4239 } elseif ( $type == ':B:' ) {
4241 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4242 return md5( $salt.'-'.md5( $password ) ) === $realHash;
4245 return self
::oldCrypt( $password, $userId ) === $hash;
4250 * Add a newuser log entry for this user.
4251 * Before 1.19 the return value was always true.
4253 * @param string|bool $action account creation type.
4254 * - String, one of the following values:
4255 * - 'create' for an anonymous user creating an account for himself.
4256 * This will force the action's performer to be the created user itself,
4257 * no matter the value of $wgUser
4258 * - 'create2' for a logged in user creating an account for someone else
4259 * - 'byemail' when the created user will receive its password by e-mail
4260 * - Boolean means whether the account was created by e-mail (deprecated):
4261 * - true will be converted to 'byemail'
4262 * - false will be converted to 'create' if this object is the same as
4263 * $wgUser and to 'create2' otherwise
4265 * @param string $reason user supplied reason
4267 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4269 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4270 global $wgUser, $wgNewUserLog;
4271 if( empty( $wgNewUserLog ) ) {
4272 return true; // disabled
4275 if ( $action === true ) {
4276 $action = 'byemail';
4277 } elseif ( $action === false ) {
4278 if ( $this->getName() == $wgUser->getName() ) {
4281 $action = 'create2';
4285 if ( $action === 'create' ||
$action === 'autocreate' ) {
4288 $performer = $wgUser;
4291 $logEntry = new ManualLogEntry( 'newusers', $action );
4292 $logEntry->setPerformer( $performer );
4293 $logEntry->setTarget( $this->getUserPage() );
4294 $logEntry->setComment( $reason );
4295 $logEntry->setParameters( array(
4296 '4::userid' => $this->getId(),
4298 $logid = $logEntry->insert();
4300 if ( $action !== 'autocreate' ) {
4301 $logEntry->publish( $logid );
4308 * Add an autocreate newuser log entry for this user
4309 * Used by things like CentralAuth and perhaps other authplugins.
4310 * Consider calling addNewUserLogEntry() directly instead.
4314 public function addNewUserLogEntryAutoCreate() {
4315 $this->addNewUserLogEntry( 'autocreate' );
4321 * Load the user options either from cache, the database or an array
4323 * @param array $data Rows for the current user out of the user_properties table
4325 protected function loadOptions( $data = null ) {
4330 if ( $this->mOptionsLoaded
) {
4334 $this->mOptions
= self
::getDefaultOptions();
4336 if ( !$this->getId() ) {
4337 // For unlogged-in users, load language/variant options from request.
4338 // There's no need to do it for logged-in users: they can set preferences,
4339 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4340 // so don't override user's choice (especially when the user chooses site default).
4341 $variant = $wgContLang->getDefaultVariant();
4342 $this->mOptions
['variant'] = $variant;
4343 $this->mOptions
['language'] = $variant;
4344 $this->mOptionsLoaded
= true;
4348 // Maybe load from the object
4349 if ( !is_null( $this->mOptionOverrides
) ) {
4350 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4351 foreach( $this->mOptionOverrides
as $key => $value ) {
4352 $this->mOptions
[$key] = $value;
4355 if( !is_array( $data ) ) {
4356 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4357 // Load from database
4358 $dbr = wfGetDB( DB_SLAVE
);
4360 $res = $dbr->select(
4362 array( 'up_property', 'up_value' ),
4363 array( 'up_user' => $this->getId() ),
4367 $this->mOptionOverrides
= array();
4369 foreach ( $res as $row ) {
4370 $data[$row->up_property
] = $row->up_value
;
4373 foreach ( $data as $property => $value ) {
4374 $this->mOptionOverrides
[$property] = $value;
4375 $this->mOptions
[$property] = $value;
4379 $this->mOptionsLoaded
= true;
4381 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
4387 protected function saveOptions() {
4388 global $wgAllowPrefChange;
4390 $this->loadOptions();
4392 // Not using getOptions(), to keep hidden preferences in database
4393 $saveOptions = $this->mOptions
;
4395 // Allow hooks to abort, for instance to save to a global profile.
4396 // Reset options to default state before saving.
4397 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4401 $extuser = ExternalUser
::newFromUser( $this );
4402 $userId = $this->getId();
4403 $insert_rows = array();
4404 foreach( $saveOptions as $key => $value ) {
4405 # Don't bother storing default values
4406 $defaultOption = self
::getDefaultOption( $key );
4407 if ( ( is_null( $defaultOption ) &&
4408 !( $value === false ||
is_null( $value ) ) ) ||
4409 $value != $defaultOption ) {
4410 $insert_rows[] = array(
4411 'up_user' => $userId,
4412 'up_property' => $key,
4413 'up_value' => $value,
4416 if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
4417 switch ( $wgAllowPrefChange[$key] ) {
4423 $extuser->setPref( $key, $value );
4428 $dbw = wfGetDB( DB_MASTER
);
4429 $dbw->delete( 'user_properties', array( 'up_user' => $userId ), __METHOD__
);
4430 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
);
4434 * Provide an array of HTML5 attributes to put on an input element
4435 * intended for the user to enter a new password. This may include
4436 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4438 * Do *not* use this when asking the user to enter his current password!
4439 * Regardless of configuration, users may have invalid passwords for whatever
4440 * reason (e.g., they were set before requirements were tightened up).
4441 * Only use it when asking for a new password, like on account creation or
4444 * Obviously, you still need to do server-side checking.
4446 * NOTE: A combination of bugs in various browsers means that this function
4447 * actually just returns array() unconditionally at the moment. May as
4448 * well keep it around for when the browser bugs get fixed, though.
4450 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4452 * @return array Array of HTML attributes suitable for feeding to
4453 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4454 * That will potentially output invalid XHTML 1.0 Transitional, and will
4455 * get confused by the boolean attribute syntax used.)
4457 public static function passwordChangeInputAttribs() {
4458 global $wgMinimalPasswordLength;
4460 if ( $wgMinimalPasswordLength == 0 ) {
4464 # Note that the pattern requirement will always be satisfied if the
4465 # input is empty, so we need required in all cases.
4467 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4468 # if e-mail confirmation is being used. Since HTML5 input validation
4469 # is b0rked anyway in some browsers, just return nothing. When it's
4470 # re-enabled, fix this code to not output required for e-mail
4472 #$ret = array( 'required' );
4475 # We can't actually do this right now, because Opera 9.6 will print out
4476 # the entered password visibly in its error message! When other
4477 # browsers add support for this attribute, or Opera fixes its support,
4478 # we can add support with a version check to avoid doing this on Opera
4479 # versions where it will be a problem. Reported to Opera as
4480 # DSK-262266, but they don't have a public bug tracker for us to follow.
4482 if ( $wgMinimalPasswordLength > 1 ) {
4483 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4484 $ret['title'] = wfMessage( 'passwordtooshort' )
4485 ->numParams( $wgMinimalPasswordLength )->text();
4493 * Return the list of user fields that should be selected to create
4494 * a new user object.
4497 public static function selectFields() {
4504 'user_newpass_time',
4508 'user_email_authenticated',
4510 'user_email_token_expires',
4511 'user_registration',