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() {
925 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
926 if ( $result !== null ) {
930 $request = $this->getRequest();
932 $cookieId = $request->getCookie( 'UserID' );
933 $sessId = $request->getSessionData( 'wsUserID' );
935 if ( $cookieId !== null ) {
936 $sId = intval( $cookieId );
937 if( $sessId !== null && $cookieId != $sessId ) {
938 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
939 cookie user ID ($sId) don't match!" );
942 $request->setSessionData( 'wsUserID', $sId );
943 } elseif ( $sessId !== null && $sessId != 0 ) {
949 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
950 $sName = $request->getSessionData( 'wsUserName' );
951 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
952 $sName = $request->getCookie( 'UserName' );
953 $request->setSessionData( 'wsUserName', $sName );
958 $proposedUser = User
::newFromId( $sId );
959 if ( !$proposedUser->isLoggedIn() ) {
964 global $wgBlockDisablesLogin;
965 if( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
966 # User blocked and we've disabled blocked user logins
970 if ( $request->getSessionData( 'wsToken' ) ) {
971 $passwordCorrect = ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
973 } elseif ( $request->getCookie( 'Token' ) ) {
974 # Get the token from DB/cache and clean it up to remove garbage padding.
975 # This deals with historical problems with bugs and the default column value.
976 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
977 $passwordCorrect = ( strlen( $token ) && $token === $request->getCookie( 'Token' ) );
980 # No session or persistent login cookie
984 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
985 $this->loadFromUserObject( $proposedUser );
986 $request->setSessionData( 'wsToken', $this->mToken
);
987 wfDebug( "User: logged in from $from\n" );
990 # Invalid credentials
991 wfDebug( "User: can't log in from $from, invalid credentials\n" );
997 * Load user and user_group data from the database.
998 * $this->mId must be set, this is how the user is identified.
1000 * @return Bool True if the user exists, false if the user is anonymous
1002 public function loadFromDatabase() {
1004 $this->mId
= intval( $this->mId
);
1006 /** Anonymous user */
1008 $this->loadDefaults();
1012 $dbr = wfGetDB( DB_MASTER
);
1013 $s = $dbr->selectRow( 'user', self
::selectFields(), array( 'user_id' => $this->mId
), __METHOD__
);
1015 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1017 if ( $s !== false ) {
1018 # Initialise user table data
1019 $this->loadFromRow( $s );
1020 $this->mGroups
= null; // deferred
1021 $this->getEditCount(); // revalidation for nulls
1026 $this->loadDefaults();
1032 * Initialize this object from a row from the user table.
1034 * @param array $row Row from the user table to load.
1035 * @param array $data Further user data to load into the object
1037 * user_groups Array with groups out of the user_groups table
1038 * user_properties Array with properties out of the user_properties table
1040 public function loadFromRow( $row, $data = null ) {
1043 $this->mGroups
= null; // deferred
1045 if ( isset( $row->user_name
) ) {
1046 $this->mName
= $row->user_name
;
1047 $this->mFrom
= 'name';
1048 $this->setItemLoaded( 'name' );
1053 if ( isset( $row->user_real_name
) ) {
1054 $this->mRealName
= $row->user_real_name
;
1055 $this->setItemLoaded( 'realname' );
1060 if ( isset( $row->user_id
) ) {
1061 $this->mId
= intval( $row->user_id
);
1062 $this->mFrom
= 'id';
1063 $this->setItemLoaded( 'id' );
1068 if ( isset( $row->user_editcount
) ) {
1069 $this->mEditCount
= $row->user_editcount
;
1074 if ( isset( $row->user_password
) ) {
1075 $this->mPassword
= $row->user_password
;
1076 $this->mNewpassword
= $row->user_newpassword
;
1077 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1078 $this->mEmail
= $row->user_email
;
1079 if ( isset( $row->user_options
) ) {
1080 $this->decodeOptions( $row->user_options
);
1082 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1083 $this->mToken
= $row->user_token
;
1084 if ( $this->mToken
== '' ) {
1085 $this->mToken
= null;
1087 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1088 $this->mEmailToken
= $row->user_email_token
;
1089 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1090 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1096 $this->mLoadedItems
= true;
1099 if ( is_array( $data ) ) {
1100 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1101 $this->mGroups
= $data['user_groups'];
1103 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1104 $this->loadOptions( $data['user_properties'] );
1110 * Load the data for this user object from another user object.
1114 protected function loadFromUserObject( $user ) {
1116 $user->loadGroups();
1117 $user->loadOptions();
1118 foreach ( self
::$mCacheVars as $var ) {
1119 $this->$var = $user->$var;
1124 * Load the groups from the database if they aren't already loaded.
1126 private function loadGroups() {
1127 if ( is_null( $this->mGroups
) ) {
1128 $dbr = wfGetDB( DB_MASTER
);
1129 $res = $dbr->select( 'user_groups',
1130 array( 'ug_group' ),
1131 array( 'ug_user' => $this->mId
),
1133 $this->mGroups
= array();
1134 foreach ( $res as $row ) {
1135 $this->mGroups
[] = $row->ug_group
;
1141 * Add the user to the group if he/she meets given criteria.
1143 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1144 * possible to remove manually via Special:UserRights. In such case it
1145 * will not be re-added automatically. The user will also not lose the
1146 * group if they no longer meet the criteria.
1148 * @param string $event key in $wgAutopromoteOnce (each one has groups/criteria)
1150 * @return array Array of groups the user has been promoted to.
1152 * @see $wgAutopromoteOnce
1154 public function addAutopromoteOnceGroups( $event ) {
1155 global $wgAutopromoteOnceLogInRC;
1157 $toPromote = array();
1158 if ( $this->getId() ) {
1159 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1160 if ( count( $toPromote ) ) {
1161 $oldGroups = $this->getGroups(); // previous groups
1162 foreach ( $toPromote as $group ) {
1163 $this->addGroup( $group );
1165 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1167 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1168 $logEntry->setPerformer( $this );
1169 $logEntry->setTarget( $this->getUserPage() );
1170 $logEntry->setParameters( array(
1171 '4::oldgroups' => $oldGroups,
1172 '5::newgroups' => $newGroups,
1174 $logid = $logEntry->insert();
1175 if ( $wgAutopromoteOnceLogInRC ) {
1176 $logEntry->publish( $logid );
1184 * Clear various cached data stored in this object. The cache of the user table
1185 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1187 * @param bool|String $reloadFrom Reload user and user_groups table data from a
1188 * given source. May be "name", "id", "defaults", "session", or false for
1191 public function clearInstanceCache( $reloadFrom = false ) {
1192 $this->mNewtalk
= -1;
1193 $this->mDatePreference
= null;
1194 $this->mBlockedby
= -1; # Unset
1195 $this->mHash
= false;
1196 $this->mRights
= null;
1197 $this->mEffectiveGroups
= null;
1198 $this->mImplicitGroups
= null;
1199 $this->mGroups
= null;
1200 $this->mOptions
= null;
1201 $this->mOptionsLoaded
= false;
1202 $this->mEditCount
= null;
1204 if ( $reloadFrom ) {
1205 $this->mLoadedItems
= array();
1206 $this->mFrom
= $reloadFrom;
1211 * Combine the language default options with any site-specific options
1212 * and add the default language variants.
1214 * @return Array of String options
1216 public static function getDefaultOptions() {
1217 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1219 static $defOpt = null;
1220 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1221 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1222 // mid-request and see that change reflected in the return value of this function.
1223 // Which is insane and would never happen during normal MW operation
1227 $defOpt = $wgDefaultUserOptions;
1228 # default language setting
1229 $defOpt['variant'] = $wgContLang->getCode();
1230 $defOpt['language'] = $wgContLang->getCode();
1231 foreach( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1232 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1234 $defOpt['skin'] = $wgDefaultSkin;
1236 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1242 * Get a given default option value.
1244 * @param string $opt Name of option to retrieve
1245 * @return String Default option value
1247 public static function getDefaultOption( $opt ) {
1248 $defOpts = self
::getDefaultOptions();
1249 if( isset( $defOpts[$opt] ) ) {
1250 return $defOpts[$opt];
1257 * Get blocking information
1258 * @param bool $bFromSlave Whether to check the slave database first. To
1259 * improve performance, non-critical checks are done
1260 * against slaves. Check when actually saving should be
1261 * done against master.
1263 private function getBlockedStatus( $bFromSlave = true ) {
1264 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1266 if ( -1 != $this->mBlockedby
) {
1270 wfProfileIn( __METHOD__
);
1271 wfDebug( __METHOD__
. ": checking...\n" );
1273 // Initialize data...
1274 // Otherwise something ends up stomping on $this->mBlockedby when
1275 // things get lazy-loaded later, causing false positive block hits
1276 // due to -1 !== 0. Probably session-related... Nothing should be
1277 // overwriting mBlockedby, surely?
1280 # We only need to worry about passing the IP address to the Block generator if the
1281 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1282 # know which IP address they're actually coming from
1283 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1284 $ip = $this->getRequest()->getIP();
1290 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1293 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1294 && !in_array( $ip, $wgProxyWhitelist ) )
1297 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1299 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1300 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1301 $block->setTarget( $ip );
1302 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1304 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1305 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1306 $block->setTarget( $ip );
1310 # (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1311 if ( !$block instanceof Block
1312 && $wgApplyIpBlocksToXff
1314 && !$this->isAllowed( 'proxyunbannable' )
1315 && !in_array( $ip, $wgProxyWhitelist )
1317 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1318 $xff = array_map( 'trim', explode( ',', $xff ) );
1319 $xff = array_diff( $xff, array( $ip ) );
1320 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1321 $block = Block
::chooseBlock( $xffblocks, $xff );
1322 if ( $block instanceof Block
) {
1323 # Mangle the reason to alert the user that the block
1324 # originated from matching the X-Forwarded-For header.
1325 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1329 if ( $block instanceof Block
) {
1330 wfDebug( __METHOD__
. ": Found block.\n" );
1331 $this->mBlock
= $block;
1332 $this->mBlockedby
= $block->getByName();
1333 $this->mBlockreason
= $block->mReason
;
1334 $this->mHideName
= $block->mHideName
;
1335 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1337 $this->mBlockedby
= '';
1338 $this->mHideName
= 0;
1339 $this->mAllowUsertalk
= false;
1343 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1345 wfProfileOut( __METHOD__
);
1349 * Whether the given IP is in a DNS blacklist.
1351 * @param string $ip IP to check
1352 * @param bool $checkWhitelist whether to check the whitelist first
1353 * @return Bool True if blacklisted.
1355 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1356 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1357 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1359 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
1362 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
1365 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1366 return $this->inDnsBlacklist( $ip, $urls );
1370 * Whether the given IP is in a given DNS blacklist.
1372 * @param string $ip IP to check
1373 * @param string|array $bases of Strings: URL of the DNS blacklist
1374 * @return Bool True if blacklisted.
1376 public function inDnsBlacklist( $ip, $bases ) {
1377 wfProfileIn( __METHOD__
);
1380 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1381 if( IP
::isIPv4( $ip ) ) {
1382 # Reverse IP, bug 21255
1383 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1385 foreach( (array)$bases as $base ) {
1387 # If we have an access key, use that too (ProjectHoneypot, etc.)
1388 if( is_array( $base ) ) {
1389 if( count( $base ) >= 2 ) {
1390 # Access key is 1, base URL is 0
1391 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1393 $host = "$ipReversed.{$base[0]}";
1396 $host = "$ipReversed.$base";
1400 $ipList = gethostbynamel( $host );
1403 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1407 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base.\n" );
1412 wfProfileOut( __METHOD__
);
1417 * Check if an IP address is in the local proxy list
1423 public static function isLocallyBlockedProxy( $ip ) {
1424 global $wgProxyList;
1426 if ( !$wgProxyList ) {
1429 wfProfileIn( __METHOD__
);
1431 if ( !is_array( $wgProxyList ) ) {
1432 # Load from the specified file
1433 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1436 if ( !is_array( $wgProxyList ) ) {
1438 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1440 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1441 # Old-style flipped proxy list
1446 wfProfileOut( __METHOD__
);
1451 * Is this user subject to rate limiting?
1453 * @return Bool True if rate limited
1455 public function isPingLimitable() {
1456 global $wgRateLimitsExcludedIPs;
1457 if( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1458 // No other good way currently to disable rate limits
1459 // for specific IPs. :P
1460 // But this is a crappy hack and should die.
1463 return !$this->isAllowed( 'noratelimit' );
1467 * Primitive rate limits: enforce maximum actions per time period
1468 * to put a brake on flooding.
1470 * @note When using a shared cache like memcached, IP-address
1471 * last-hit counters will be shared across wikis.
1473 * @param string $action Action to enforce; 'edit' if unspecified
1474 * @return Bool True if a rate limiter was tripped
1476 public function pingLimiter( $action = 'edit' ) {
1477 # Call the 'PingLimiter' hook
1479 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result ) ) ) {
1483 global $wgRateLimits;
1484 if( !isset( $wgRateLimits[$action] ) ) {
1488 # Some groups shouldn't trigger the ping limiter, ever
1489 if( !$this->isPingLimitable() )
1492 global $wgMemc, $wgRateLimitLog;
1493 wfProfileIn( __METHOD__
);
1495 $limits = $wgRateLimits[$action];
1497 $id = $this->getId();
1498 $ip = $this->getRequest()->getIP();
1501 if( isset( $limits['anon'] ) && $id == 0 ) {
1502 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1505 if( isset( $limits['user'] ) && $id != 0 ) {
1506 $userLimit = $limits['user'];
1508 if( $this->isNewbie() ) {
1509 if( isset( $limits['newbie'] ) && $id != 0 ) {
1510 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1512 if( isset( $limits['ip'] ) ) {
1513 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1516 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1517 $subnet = $matches[1];
1518 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1521 // Check for group-specific permissions
1522 // If more than one group applies, use the group with the highest limit
1523 foreach ( $this->getGroups() as $group ) {
1524 if ( isset( $limits[$group] ) ) {
1525 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1526 $userLimit = $limits[$group];
1530 // Set the user limit key
1531 if ( $userLimit !== false ) {
1532 wfDebug( __METHOD__
. ": effective user limit: $userLimit\n" );
1533 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1537 foreach( $keys as $key => $limit ) {
1538 list( $max, $period ) = $limit;
1539 $summary = "(limit $max in {$period}s)";
1540 $count = $wgMemc->get( $key );
1543 if( $count >= $max ) {
1544 wfDebug( __METHOD__
. ": tripped! $key at $count $summary\n" );
1545 if( $wgRateLimitLog ) {
1546 wfSuppressWarnings();
1547 file_put_contents( $wgRateLimitLog, wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", FILE_APPEND
);
1548 wfRestoreWarnings();
1552 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1555 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1556 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1558 $wgMemc->incr( $key );
1561 wfProfileOut( __METHOD__
);
1566 * Check if user is blocked
1568 * @param bool $bFromSlave Whether to check the slave database instead of the master
1569 * @return Bool True if blocked, false otherwise
1571 public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1572 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1576 * Get the block affecting the user, or null if the user is not blocked
1578 * @param bool $bFromSlave Whether to check the slave database instead of the master
1579 * @return Block|null
1581 public function getBlock( $bFromSlave = true ) {
1582 $this->getBlockedStatus( $bFromSlave );
1583 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1587 * Check if user is blocked from editing a particular article
1589 * @param $title Title to check
1590 * @param bool $bFromSlave whether to check the slave database instead of the master
1593 function isBlockedFrom( $title, $bFromSlave = false ) {
1594 global $wgBlockAllowsUTEdit;
1595 wfProfileIn( __METHOD__
);
1597 $blocked = $this->isBlocked( $bFromSlave );
1598 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1599 # If a user's name is suppressed, they cannot make edits anywhere
1600 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1601 $title->getNamespace() == NS_USER_TALK
) {
1603 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1606 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1608 wfProfileOut( __METHOD__
);
1613 * If user is blocked, return the name of the user who placed the block
1614 * @return String name of blocker
1616 public function blockedBy() {
1617 $this->getBlockedStatus();
1618 return $this->mBlockedby
;
1622 * If user is blocked, return the specified reason for the block
1623 * @return String Blocking reason
1625 public function blockedFor() {
1626 $this->getBlockedStatus();
1627 return $this->mBlockreason
;
1631 * If user is blocked, return the ID for the block
1632 * @return Int Block ID
1634 public function getBlockId() {
1635 $this->getBlockedStatus();
1636 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1640 * Check if user is blocked on all wikis.
1641 * Do not use for actual edit permission checks!
1642 * This is intended for quick UI checks.
1644 * @param string $ip IP address, uses current client if none given
1645 * @return Bool True if blocked, false otherwise
1647 public function isBlockedGlobally( $ip = '' ) {
1648 if( $this->mBlockedGlobally
!== null ) {
1649 return $this->mBlockedGlobally
;
1651 // User is already an IP?
1652 if( IP
::isIPAddress( $this->getName() ) ) {
1653 $ip = $this->getName();
1655 $ip = $this->getRequest()->getIP();
1658 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1659 $this->mBlockedGlobally
= (bool)$blocked;
1660 return $this->mBlockedGlobally
;
1664 * Check if user account is locked
1666 * @return Bool True if locked, false otherwise
1668 public function isLocked() {
1669 if( $this->mLocked
!== null ) {
1670 return $this->mLocked
;
1673 $authUser = $wgAuth->getUserInstance( $this );
1674 $this->mLocked
= (bool)$authUser->isLocked();
1675 return $this->mLocked
;
1679 * Check if user account is hidden
1681 * @return Bool True if hidden, false otherwise
1683 public function isHidden() {
1684 if( $this->mHideName
!== null ) {
1685 return $this->mHideName
;
1687 $this->getBlockedStatus();
1688 if( !$this->mHideName
) {
1690 $authUser = $wgAuth->getUserInstance( $this );
1691 $this->mHideName
= (bool)$authUser->isHidden();
1693 return $this->mHideName
;
1697 * Get the user's ID.
1698 * @return Int The user's ID; 0 if the user is anonymous or nonexistent
1700 public function getId() {
1701 if( $this->mId
=== null && $this->mName
!== null
1702 && User
::isIP( $this->mName
) ) {
1703 // Special case, we know the user is anonymous
1705 } elseif( !$this->isItemLoaded( 'id' ) ) {
1706 // Don't load if this was initialized from an ID
1713 * Set the user and reload all fields according to a given ID
1714 * @param int $v User ID to reload
1716 public function setId( $v ) {
1718 $this->clearInstanceCache( 'id' );
1722 * Get the user name, or the IP of an anonymous user
1723 * @return String User's name or IP address
1725 public function getName() {
1726 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1727 # Special case optimisation
1728 return $this->mName
;
1731 if ( $this->mName
=== false ) {
1733 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1735 return $this->mName
;
1740 * Set the user name.
1742 * This does not reload fields from the database according to the given
1743 * name. Rather, it is used to create a temporary "nonexistent user" for
1744 * later addition to the database. It can also be used to set the IP
1745 * address for an anonymous user to something other than the current
1748 * @note User::newFromName() has roughly the same function, when the named user
1750 * @param string $str New user name to set
1752 public function setName( $str ) {
1754 $this->mName
= $str;
1758 * Get the user's name escaped by underscores.
1759 * @return String Username escaped by underscores.
1761 public function getTitleKey() {
1762 return str_replace( ' ', '_', $this->getName() );
1766 * Check if the user has new messages.
1767 * @return Bool True if the user has new messages
1769 public function getNewtalk() {
1772 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1773 if( $this->mNewtalk
=== -1 ) {
1774 $this->mNewtalk
= false; # reset talk page status
1776 # Check memcached separately for anons, who have no
1777 # entire User object stored in there.
1779 global $wgDisableAnonTalk;
1780 if( $wgDisableAnonTalk ) {
1781 // Anon newtalk disabled by configuration.
1782 $this->mNewtalk
= false;
1785 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1786 $newtalk = $wgMemc->get( $key );
1787 if( strval( $newtalk ) !== '' ) {
1788 $this->mNewtalk
= (bool)$newtalk;
1790 // Since we are caching this, make sure it is up to date by getting it
1792 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1793 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1797 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1801 return (bool)$this->mNewtalk
;
1805 * Return the talk page(s) this user has new messages on.
1806 * @return Array of String page URLs
1808 public function getNewMessageLinks() {
1810 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
1812 } elseif( !$this->getNewtalk() ) {
1815 $utp = $this->getTalkPage();
1816 $dbr = wfGetDB( DB_SLAVE
);
1817 // Get the "last viewed rev" timestamp from the oldest message notification
1818 $timestamp = $dbr->selectField( 'user_newtalk',
1819 'MIN(user_last_timestamp)',
1820 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
1822 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
1823 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
1827 * Internal uncached check for new messages
1830 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1831 * @param string|Int $id User's IP address for anonymous users, User ID otherwise
1832 * @param bool $fromMaster true to fetch from the master, false for a slave
1833 * @return Bool True if the user has new messages
1835 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
1836 if ( $fromMaster ) {
1837 $db = wfGetDB( DB_MASTER
);
1839 $db = wfGetDB( DB_SLAVE
);
1841 $ok = $db->selectField( 'user_newtalk', $field,
1842 array( $field => $id ), __METHOD__
);
1843 return $ok !== false;
1847 * Add or update the new messages flag
1848 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1849 * @param string|Int $id User's IP address for anonymous users, User ID otherwise
1850 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null.
1851 * @return Bool True if successful, false otherwise
1853 protected function updateNewtalk( $field, $id, $curRev = null ) {
1854 // Get timestamp of the talk page revision prior to the current one
1855 $prevRev = $curRev ?
$curRev->getPrevious() : false;
1856 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
1857 // Mark the user as having new messages since this revision
1858 $dbw = wfGetDB( DB_MASTER
);
1859 $dbw->insert( 'user_newtalk',
1860 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
1863 if ( $dbw->affectedRows() ) {
1864 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
1867 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
1873 * Clear the new messages flag for the given user
1874 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1875 * @param string|Int $id User's IP address for anonymous users, User ID otherwise
1876 * @return Bool True if successful, false otherwise
1878 protected function deleteNewtalk( $field, $id ) {
1879 $dbw = wfGetDB( DB_MASTER
);
1880 $dbw->delete( 'user_newtalk',
1881 array( $field => $id ),
1883 if ( $dbw->affectedRows() ) {
1884 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
1887 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
1893 * Update the 'You have new messages!' status.
1894 * @param bool $val Whether the user has new messages
1895 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null or !$val.
1897 public function setNewtalk( $val, $curRev = null ) {
1898 if( wfReadOnly() ) {
1903 $this->mNewtalk
= $val;
1905 if( $this->isAnon() ) {
1907 $id = $this->getName();
1910 $id = $this->getId();
1915 $changed = $this->updateNewtalk( $field, $id, $curRev );
1917 $changed = $this->deleteNewtalk( $field, $id );
1920 if( $this->isAnon() ) {
1921 // Anons have a separate memcached space, since
1922 // user records aren't kept for them.
1923 $key = wfMemcKey( 'newtalk', 'ip', $id );
1924 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1927 $this->invalidateCache();
1932 * Generate a current or new-future timestamp to be stored in the
1933 * user_touched field when we update things.
1934 * @return String Timestamp in TS_MW format
1936 private static function newTouchedTimestamp() {
1937 global $wgClockSkewFudge;
1938 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1942 * Clear user data from memcached.
1943 * Use after applying fun updates to the database; caller's
1944 * responsibility to update user_touched if appropriate.
1946 * Called implicitly from invalidateCache() and saveSettings().
1948 private function clearSharedCache() {
1952 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1957 * Immediately touch the user data cache for this account.
1958 * Updates user_touched field, and removes account data from memcached
1959 * for reload on the next hit.
1961 public function invalidateCache() {
1962 if ( wfReadOnly() ) {
1967 $this->mTouched
= self
::newTouchedTimestamp();
1969 $dbw = wfGetDB( DB_MASTER
);
1970 $userid = $this->mId
;
1971 $touched = $this->mTouched
;
1972 $dbw->onTransactionIdle( function() use ( $dbw, $userid, $touched ) {
1973 // Prevent contention slams by checking user_touched first
1974 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
1975 $needsPurge = $dbw->selectField( 'user', '1',
1976 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
1977 if ( $needsPurge ) {
1978 $dbw->update( 'user',
1979 array( 'user_touched' => $dbw->timestamp( $touched ) ),
1980 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
1985 $this->clearSharedCache();
1990 * Validate the cache for this account.
1991 * @param string $timestamp A timestamp in TS_MW format
1995 public function validateCache( $timestamp ) {
1997 return ( $timestamp >= $this->mTouched
);
2001 * Get the user touched timestamp
2002 * @return String timestamp
2004 public function getTouched() {
2006 return $this->mTouched
;
2010 * Set the password and reset the random token.
2011 * Calls through to authentication plugin if necessary;
2012 * will have no effect if the auth plugin refuses to
2013 * pass the change through or if the legal password
2016 * As a special case, setting the password to null
2017 * wipes it, so the account cannot be logged in until
2018 * a new password is set, for instance via e-mail.
2020 * @param string $str New password to set
2021 * @throws PasswordError on failure
2025 public function setPassword( $str ) {
2028 if( $str !== null ) {
2029 if( !$wgAuth->allowPasswordChange() ) {
2030 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2033 if( !$this->isValidPassword( $str ) ) {
2034 global $wgMinimalPasswordLength;
2035 $valid = $this->getPasswordValidity( $str );
2036 if ( is_array( $valid ) ) {
2037 $message = array_shift( $valid );
2041 $params = array( $wgMinimalPasswordLength );
2043 throw new PasswordError( wfMessage( $message, $params )->text() );
2047 if( !$wgAuth->setPassword( $this, $str ) ) {
2048 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2051 $this->setInternalPassword( $str );
2057 * Set the password and reset the random token unconditionally.
2059 * @param string|null $str New password to set or null to set an invalid
2060 * password hash meaning that the user will not be able to log in
2061 * through the web interface.
2063 public function setInternalPassword( $str ) {
2067 if( $str === null ) {
2068 // Save an invalid hash...
2069 $this->mPassword
= '';
2071 $this->mPassword
= self
::crypt( $str );
2073 $this->mNewpassword
= '';
2074 $this->mNewpassTime
= null;
2078 * Get the user's current token.
2079 * @param bool $forceCreation Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility)
2080 * @return String Token
2082 public function getToken( $forceCreation = true ) {
2084 if ( !$this->mToken
&& $forceCreation ) {
2087 return $this->mToken
;
2091 * Set the random token (used for persistent authentication)
2092 * Called from loadDefaults() among other places.
2094 * @param string|bool $token If specified, set the token to this value
2096 public function setToken( $token = false ) {
2099 $this->mToken
= MWCryptRand
::generateHex( USER_TOKEN_LENGTH
);
2101 $this->mToken
= $token;
2106 * Set the password for a password reminder or new account email
2108 * @param string $str New password to set
2109 * @param bool $throttle If true, reset the throttle timestamp to the present
2111 public function setNewpassword( $str, $throttle = true ) {
2113 $this->mNewpassword
= self
::crypt( $str );
2115 $this->mNewpassTime
= wfTimestampNow();
2120 * Has password reminder email been sent within the last
2121 * $wgPasswordReminderResendTime hours?
2124 public function isPasswordReminderThrottled() {
2125 global $wgPasswordReminderResendTime;
2127 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2130 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2131 return time() < $expiry;
2135 * Get the user's e-mail address
2136 * @return String User's email address
2138 public function getEmail() {
2140 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
2141 return $this->mEmail
;
2145 * Get the timestamp of the user's e-mail authentication
2146 * @return String TS_MW timestamp
2148 public function getEmailAuthenticationTimestamp() {
2150 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2151 return $this->mEmailAuthenticated
;
2155 * Set the user's e-mail address
2156 * @param string $str New e-mail address
2158 public function setEmail( $str ) {
2160 if( $str == $this->mEmail
) {
2163 $this->mEmail
= $str;
2164 $this->invalidateEmail();
2165 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
2169 * Set the user's e-mail address and a confirmation mail if needed.
2172 * @param string $str New e-mail address
2175 public function setEmailWithConfirmation( $str ) {
2176 global $wgEnableEmail, $wgEmailAuthentication;
2178 if ( !$wgEnableEmail ) {
2179 return Status
::newFatal( 'emaildisabled' );
2182 $oldaddr = $this->getEmail();
2183 if ( $str === $oldaddr ) {
2184 return Status
::newGood( true );
2187 $this->setEmail( $str );
2189 if ( $str !== '' && $wgEmailAuthentication ) {
2190 # Send a confirmation request to the new address if needed
2191 $type = $oldaddr != '' ?
'changed' : 'set';
2192 $result = $this->sendConfirmationMail( $type );
2193 if ( $result->isGood() ) {
2194 # Say the the caller that a confirmation mail has been sent
2195 $result->value
= 'eauth';
2198 $result = Status
::newGood( true );
2205 * Get the user's real name
2206 * @return String User's real name
2208 public function getRealName() {
2209 if ( !$this->isItemLoaded( 'realname' ) ) {
2213 return $this->mRealName
;
2217 * Set the user's real name
2218 * @param string $str New real name
2220 public function setRealName( $str ) {
2222 $this->mRealName
= $str;
2226 * Get the user's current setting for a given option.
2228 * @param string $oname The option to check
2229 * @param string $defaultOverride A default value returned if the option does not exist
2230 * @param bool $ignoreHidden = whether to ignore the effects of $wgHiddenPrefs
2231 * @return String User's current value for the option
2232 * @see getBoolOption()
2233 * @see getIntOption()
2235 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2236 global $wgHiddenPrefs;
2237 $this->loadOptions();
2239 # We want 'disabled' preferences to always behave as the default value for
2240 # users, even if they have set the option explicitly in their settings (ie they
2241 # set it, and then it was disabled removing their ability to change it). But
2242 # we don't want to erase the preferences in the database in case the preference
2243 # is re-enabled again. So don't touch $mOptions, just override the returned value
2244 if( in_array( $oname, $wgHiddenPrefs ) && !$ignoreHidden ) {
2245 return self
::getDefaultOption( $oname );
2248 if ( array_key_exists( $oname, $this->mOptions
) ) {
2249 return $this->mOptions
[$oname];
2251 return $defaultOverride;
2256 * Get all user's options
2260 public function getOptions() {
2261 global $wgHiddenPrefs;
2262 $this->loadOptions();
2263 $options = $this->mOptions
;
2265 # We want 'disabled' preferences to always behave as the default value for
2266 # users, even if they have set the option explicitly in their settings (ie they
2267 # set it, and then it was disabled removing their ability to change it). But
2268 # we don't want to erase the preferences in the database in case the preference
2269 # is re-enabled again. So don't touch $mOptions, just override the returned value
2270 foreach( $wgHiddenPrefs as $pref ) {
2271 $default = self
::getDefaultOption( $pref );
2272 if( $default !== null ) {
2273 $options[$pref] = $default;
2281 * Get the user's current setting for a given option, as a boolean value.
2283 * @param string $oname The option to check
2284 * @return Bool User's current value for the option
2287 public function getBoolOption( $oname ) {
2288 return (bool)$this->getOption( $oname );
2292 * Get the user's current setting for a given option, as a boolean value.
2294 * @param string $oname The option to check
2295 * @param int $defaultOverride A default value returned if the option does not exist
2296 * @return Int User's current value for the option
2299 public function getIntOption( $oname, $defaultOverride = 0 ) {
2300 $val = $this->getOption( $oname );
2302 $val = $defaultOverride;
2304 return intval( $val );
2308 * Set the given option for a user.
2310 * @param string $oname The option to set
2311 * @param $val mixed New value to set
2313 public function setOption( $oname, $val ) {
2314 $this->loadOptions();
2316 // Explicitly NULL values should refer to defaults
2317 if( is_null( $val ) ) {
2318 $val = self
::getDefaultOption( $oname );
2321 $this->mOptions
[$oname] = $val;
2325 * Return a list of the types of user options currently returned by
2326 * User::getOptionKinds().
2328 * Currently, the option kinds are:
2329 * - 'registered' - preferences which are registered in core MediaWiki or
2330 * by extensions using the UserGetDefaultOptions hook.
2331 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2332 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2333 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2334 * be used by user scripts.
2335 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2336 * These are usually legacy options, removed in newer versions.
2338 * The API (and possibly others) use this function to determine the possible
2339 * option types for validation purposes, so make sure to update this when a
2340 * new option kind is added.
2342 * @see User::getOptionKinds
2343 * @return array Option kinds
2345 public static function listOptionKinds() {
2348 'registered-multiselect',
2349 'registered-checkmatrix',
2356 * Return an associative array mapping preferences keys to the kind of a preference they're
2357 * used for. Different kinds are handled differently when setting or reading preferences.
2359 * See User::listOptionKinds for the list of valid option types that can be provided.
2361 * @see User::listOptionKinds
2362 * @param $context IContextSource
2363 * @param array $options assoc. array with options keys to check as keys. Defaults to $this->mOptions.
2364 * @return array the key => kind mapping data
2366 public function getOptionKinds( IContextSource
$context, $options = null ) {
2367 $this->loadOptions();
2368 if ( $options === null ) {
2369 $options = $this->mOptions
;
2372 $prefs = Preferences
::getPreferences( $this, $context );
2375 // Multiselect and checkmatrix options are stored in the database with
2376 // one key per option, each having a boolean value. Extract those keys.
2377 $multiselectOptions = array();
2378 foreach ( $prefs as $name => $info ) {
2379 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2380 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2381 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2382 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2384 foreach ( $opts as $value ) {
2385 $multiselectOptions["$prefix$value"] = true;
2388 unset( $prefs[$name] );
2391 $checkmatrixOptions = array();
2392 foreach ( $prefs as $name => $info ) {
2393 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2394 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2395 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2396 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2397 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2399 foreach ( $columns as $column ) {
2400 foreach ( $rows as $row ) {
2401 $checkmatrixOptions["$prefix-$column-$row"] = true;
2405 unset( $prefs[$name] );
2409 // $value is ignored
2410 foreach ( $options as $key => $value ) {
2411 if ( isset( $prefs[$key] ) ) {
2412 $mapping[$key] = 'registered';
2413 } elseif( isset( $multiselectOptions[$key] ) ) {
2414 $mapping[$key] = 'registered-multiselect';
2415 } elseif( isset( $checkmatrixOptions[$key] ) ) {
2416 $mapping[$key] = 'registered-checkmatrix';
2417 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2418 $mapping[$key] = 'userjs';
2420 $mapping[$key] = 'unused';
2428 * Reset certain (or all) options to the site defaults
2430 * The optional parameter determines which kinds of preferences will be reset.
2431 * Supported values are everything that can be reported by getOptionKinds()
2432 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2434 * @param array|string $resetKinds which kinds of preferences to reset. Defaults to
2435 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2436 * for backwards-compatibility.
2437 * @param $context IContextSource|null context source used when $resetKinds
2438 * does not contain 'all', passed to getOptionKinds().
2439 * Defaults to RequestContext::getMain() when null.
2441 public function resetOptions(
2442 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2443 IContextSource
$context = null
2446 $defaultOptions = self
::getDefaultOptions();
2448 if ( !is_array( $resetKinds ) ) {
2449 $resetKinds = array( $resetKinds );
2452 if ( in_array( 'all', $resetKinds ) ) {
2453 $newOptions = $defaultOptions;
2455 if ( $context === null ) {
2456 $context = RequestContext
::getMain();
2459 $optionKinds = $this->getOptionKinds( $context );
2460 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2461 $newOptions = array();
2463 // Use default values for the options that should be deleted, and
2464 // copy old values for the ones that shouldn't.
2465 foreach ( $this->mOptions
as $key => $value ) {
2466 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2467 if ( array_key_exists( $key, $defaultOptions ) ) {
2468 $newOptions[$key] = $defaultOptions[$key];
2471 $newOptions[$key] = $value;
2476 $this->mOptions
= $newOptions;
2477 $this->mOptionsLoaded
= true;
2481 * Get the user's preferred date format.
2482 * @return String User's preferred date format
2484 public function getDatePreference() {
2485 // Important migration for old data rows
2486 if ( is_null( $this->mDatePreference
) ) {
2488 $value = $this->getOption( 'date' );
2489 $map = $wgLang->getDatePreferenceMigrationMap();
2490 if ( isset( $map[$value] ) ) {
2491 $value = $map[$value];
2493 $this->mDatePreference
= $value;
2495 return $this->mDatePreference
;
2499 * Get the user preferred stub threshold
2503 public function getStubThreshold() {
2504 global $wgMaxArticleSize; # Maximum article size, in Kb
2505 $threshold = $this->getIntOption( 'stubthreshold' );
2506 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2507 # If they have set an impossible value, disable the preference
2508 # so we can use the parser cache again.
2515 * Get the permissions this user has.
2516 * @return Array of String permission names
2518 public function getRights() {
2519 if ( is_null( $this->mRights
) ) {
2520 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2521 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2522 // Force reindexation of rights when a hook has unset one of them
2523 $this->mRights
= array_values( array_unique( $this->mRights
) );
2525 return $this->mRights
;
2529 * Get the list of explicit group memberships this user has.
2530 * The implicit * and user groups are not included.
2531 * @return Array of String internal group names
2533 public function getGroups() {
2535 $this->loadGroups();
2536 return $this->mGroups
;
2540 * Get the list of implicit group memberships this user has.
2541 * This includes all explicit groups, plus 'user' if logged in,
2542 * '*' for all accounts, and autopromoted groups
2543 * @param bool $recache Whether to avoid the cache
2544 * @return Array of String internal group names
2546 public function getEffectiveGroups( $recache = false ) {
2547 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2548 wfProfileIn( __METHOD__
);
2549 $this->mEffectiveGroups
= array_unique( array_merge(
2550 $this->getGroups(), // explicit groups
2551 $this->getAutomaticGroups( $recache ) // implicit groups
2553 # Hook for additional groups
2554 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2555 // Force reindexation of groups when a hook has unset one of them
2556 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
2557 wfProfileOut( __METHOD__
);
2559 return $this->mEffectiveGroups
;
2563 * Get the list of implicit group memberships this user has.
2564 * This includes 'user' if logged in, '*' for all accounts,
2565 * and autopromoted groups
2566 * @param bool $recache Whether to avoid the cache
2567 * @return Array of String internal group names
2569 public function getAutomaticGroups( $recache = false ) {
2570 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
2571 wfProfileIn( __METHOD__
);
2572 $this->mImplicitGroups
= array( '*' );
2573 if ( $this->getId() ) {
2574 $this->mImplicitGroups
[] = 'user';
2576 $this->mImplicitGroups
= array_unique( array_merge(
2577 $this->mImplicitGroups
,
2578 Autopromote
::getAutopromoteGroups( $this )
2582 # Assure data consistency with rights/groups,
2583 # as getEffectiveGroups() depends on this function
2584 $this->mEffectiveGroups
= null;
2586 wfProfileOut( __METHOD__
);
2588 return $this->mImplicitGroups
;
2592 * Returns the groups the user has belonged to.
2594 * The user may still belong to the returned groups. Compare with getGroups().
2596 * The function will not return groups the user had belonged to before MW 1.17
2598 * @return array Names of the groups the user has belonged to.
2600 public function getFormerGroups() {
2601 if( is_null( $this->mFormerGroups
) ) {
2602 $dbr = wfGetDB( DB_MASTER
);
2603 $res = $dbr->select( 'user_former_groups',
2604 array( 'ufg_group' ),
2605 array( 'ufg_user' => $this->mId
),
2607 $this->mFormerGroups
= array();
2608 foreach( $res as $row ) {
2609 $this->mFormerGroups
[] = $row->ufg_group
;
2612 return $this->mFormerGroups
;
2616 * Get the user's edit count.
2619 public function getEditCount() {
2620 if ( !$this->getId() ) {
2624 if ( !isset( $this->mEditCount
) ) {
2625 /* Populate the count, if it has not been populated yet */
2626 wfProfileIn( __METHOD__
);
2627 $dbr = wfGetDB( DB_SLAVE
);
2628 // check if the user_editcount field has been initialized
2629 $count = $dbr->selectField(
2630 'user', 'user_editcount',
2631 array( 'user_id' => $this->mId
),
2635 if( $count === null ) {
2636 // it has not been initialized. do so.
2637 $count = $this->initEditCount();
2639 $this->mEditCount
= intval( $count );
2640 wfProfileOut( __METHOD__
);
2642 return $this->mEditCount
;
2646 * Add the user to the given group.
2647 * This takes immediate effect.
2648 * @param string $group Name of the group to add
2650 public function addGroup( $group ) {
2651 if( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2652 $dbw = wfGetDB( DB_MASTER
);
2653 if( $this->getId() ) {
2654 $dbw->insert( 'user_groups',
2656 'ug_user' => $this->getID(),
2657 'ug_group' => $group,
2660 array( 'IGNORE' ) );
2663 $this->loadGroups();
2664 $this->mGroups
[] = $group;
2665 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2667 $this->invalidateCache();
2671 * Remove the user from the given group.
2672 * This takes immediate effect.
2673 * @param string $group Name of the group to remove
2675 public function removeGroup( $group ) {
2677 if( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2678 $dbw = wfGetDB( DB_MASTER
);
2679 $dbw->delete( 'user_groups',
2681 'ug_user' => $this->getID(),
2682 'ug_group' => $group,
2684 // Remember that the user was in this group
2685 $dbw->insert( 'user_former_groups',
2687 'ufg_user' => $this->getID(),
2688 'ufg_group' => $group,
2691 array( 'IGNORE' ) );
2693 $this->loadGroups();
2694 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2695 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2697 $this->invalidateCache();
2701 * Get whether the user is logged in
2704 public function isLoggedIn() {
2705 return $this->getID() != 0;
2709 * Get whether the user is anonymous
2712 public function isAnon() {
2713 return !$this->isLoggedIn();
2717 * Check if user is allowed to access a feature / make an action
2719 * @internal param \String $varargs permissions to test
2720 * @return Boolean: True if user is allowed to perform *any* of the given actions
2724 public function isAllowedAny( /*...*/ ) {
2725 $permissions = func_get_args();
2726 foreach( $permissions as $permission ) {
2727 if( $this->isAllowed( $permission ) ) {
2736 * @internal param $varargs string
2737 * @return bool True if the user is allowed to perform *all* of the given actions
2739 public function isAllowedAll( /*...*/ ) {
2740 $permissions = func_get_args();
2741 foreach( $permissions as $permission ) {
2742 if( !$this->isAllowed( $permission ) ) {
2750 * Internal mechanics of testing a permission
2751 * @param $action String
2754 public function isAllowed( $action = '' ) {
2755 if ( $action === '' ) {
2756 return true; // In the spirit of DWIM
2758 # Patrolling may not be enabled
2759 if( $action === 'patrol' ||
$action === 'autopatrol' ) {
2760 global $wgUseRCPatrol, $wgUseNPPatrol;
2761 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2764 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2765 # by misconfiguration: 0 == 'foo'
2766 return in_array( $action, $this->getRights(), true );
2770 * Check whether to enable recent changes patrol features for this user
2771 * @return Boolean: True or false
2773 public function useRCPatrol() {
2774 global $wgUseRCPatrol;
2775 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
2779 * Check whether to enable new pages patrol features for this user
2780 * @return Bool True or false
2782 public function useNPPatrol() {
2783 global $wgUseRCPatrol, $wgUseNPPatrol;
2784 return( ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) ) );
2788 * Get the WebRequest object to use with this object
2790 * @return WebRequest
2792 public function getRequest() {
2793 if ( $this->mRequest
) {
2794 return $this->mRequest
;
2802 * Get the current skin, loading it if required
2803 * @return Skin The current skin
2804 * @todo FIXME: Need to check the old failback system [AV]
2805 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
2807 public function getSkin() {
2808 wfDeprecated( __METHOD__
, '1.18' );
2809 return RequestContext
::getMain()->getSkin();
2813 * Get a WatchedItem for this user and $title.
2815 * @param $title Title
2816 * @return WatchedItem
2818 public function getWatchedItem( $title ) {
2819 $key = $title->getNamespace() . ':' . $title->getDBkey();
2821 if ( isset( $this->mWatchedItems
[$key] ) ) {
2822 return $this->mWatchedItems
[$key];
2825 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
2826 $this->mWatchedItems
= array();
2829 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title );
2830 return $this->mWatchedItems
[$key];
2834 * Check the watched status of an article.
2835 * @param $title Title of the article to look at
2838 public function isWatched( $title ) {
2839 return $this->getWatchedItem( $title )->isWatched();
2844 * @param $title Title of the article to look at
2846 public function addWatch( $title ) {
2847 $this->getWatchedItem( $title )->addWatch();
2848 $this->invalidateCache();
2852 * Stop watching an article.
2853 * @param $title Title of the article to look at
2855 public function removeWatch( $title ) {
2856 $this->getWatchedItem( $title )->removeWatch();
2857 $this->invalidateCache();
2861 * Clear the user's notification timestamp for the given title.
2862 * If e-notif e-mails are on, they will receive notification mails on
2863 * the next change of the page if it's watched etc.
2864 * @param $title Title of the article to look at
2866 public function clearNotification( &$title ) {
2867 global $wgUseEnotif, $wgShowUpdatedMarker;
2869 # Do nothing if the database is locked to writes
2870 if( wfReadOnly() ) {
2874 if( $title->getNamespace() == NS_USER_TALK
&&
2875 $title->getText() == $this->getName() ) {
2876 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2878 $this->setNewtalk( false );
2881 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2885 if( $this->isAnon() ) {
2886 // Nothing else to do...
2890 // Only update the timestamp if the page is being watched.
2891 // The query to find out if it is watched is cached both in memcached and per-invocation,
2892 // and when it does have to be executed, it can be on a slave
2893 // If this is the user's newtalk page, we always update the timestamp
2895 if ( $title->getNamespace() == NS_USER_TALK
&&
2896 $title->getText() == $this->getName() )
2901 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force );
2905 * Resets all of the given user's page-change notification timestamps.
2906 * If e-notif e-mails are on, they will receive notification mails on
2907 * the next change of any watched page.
2909 public function clearAllNotifications() {
2910 if ( wfReadOnly() ) {
2914 global $wgUseEnotif, $wgShowUpdatedMarker;
2915 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2916 $this->setNewtalk( false );
2919 $id = $this->getId();
2921 $dbw = wfGetDB( DB_MASTER
);
2922 $dbw->update( 'watchlist',
2924 'wl_notificationtimestamp' => null
2925 ), array( /* WHERE */
2929 # We also need to clear here the "you have new message" notification for the own user_talk page
2930 # This is cleared one page view later in Article::viewUpdates();
2935 * Set this user's options from an encoded string
2936 * @param string $str Encoded options to import
2938 * @deprecated in 1.19 due to removal of user_options from the user table
2940 private function decodeOptions( $str ) {
2941 wfDeprecated( __METHOD__
, '1.19' );
2945 $this->mOptionsLoaded
= true;
2946 $this->mOptionOverrides
= array();
2948 // If an option is not set in $str, use the default value
2949 $this->mOptions
= self
::getDefaultOptions();
2951 $a = explode( "\n", $str );
2952 foreach ( $a as $s ) {
2954 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2955 $this->mOptions
[$m[1]] = $m[2];
2956 $this->mOptionOverrides
[$m[1]] = $m[2];
2962 * Set a cookie on the user's client. Wrapper for
2963 * WebResponse::setCookie
2964 * @param string $name Name of the cookie to set
2965 * @param string $value Value to set
2966 * @param int $exp Expiration time, as a UNIX time value;
2967 * if 0 or not specified, use the default $wgCookieExpiration
2968 * @param $secure Bool
2969 * true: Force setting the secure attribute when setting the cookie
2970 * false: Force NOT setting the secure attribute when setting the cookie
2971 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
2973 protected function setCookie( $name, $value, $exp = 0, $secure = null ) {
2974 $this->getRequest()->response()->setcookie( $name, $value, $exp, null, null, $secure );
2978 * Clear a cookie on the user's client
2979 * @param string $name Name of the cookie to clear
2981 protected function clearCookie( $name ) {
2982 $this->setCookie( $name, '', time() - 86400 );
2986 * Set the default cookies for this session on the user's client.
2988 * @param $request WebRequest object to use; $wgRequest will be used if null
2990 * @param bool $secure Whether to force secure/insecure cookies or use default
2992 public function setCookies( $request = null, $secure = null ) {
2993 if ( $request === null ) {
2994 $request = $this->getRequest();
2998 if ( 0 == $this->mId
) {
3001 if ( !$this->mToken
) {
3002 // When token is empty or NULL generate a new one and then save it to the database
3003 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3004 // Simply by setting every cell in the user_token column to NULL and letting them be
3005 // regenerated as users log back into the wiki.
3007 $this->saveSettings();
3010 'wsUserID' => $this->mId
,
3011 'wsToken' => $this->mToken
,
3012 'wsUserName' => $this->getName()
3015 'UserID' => $this->mId
,
3016 'UserName' => $this->getName(),
3018 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
3019 $cookies['Token'] = $this->mToken
;
3021 $cookies['Token'] = false;
3024 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3026 foreach ( $session as $name => $value ) {
3027 $request->setSessionData( $name, $value );
3029 foreach ( $cookies as $name => $value ) {
3030 if ( $value === false ) {
3031 $this->clearCookie( $name );
3033 $this->setCookie( $name, $value, 0, $secure );
3038 * If wpStickHTTPS was selected, also set an insecure cookie that
3039 * will cause the site to redirect the user to HTTPS, if they access
3040 * it over HTTP. Bug 29898.
3042 if ( $request->getCheck( 'wpStickHTTPS' ) ) {
3043 $this->setCookie( 'forceHTTPS', 'true', time() +
2592000, false ); //30 days
3048 * Log this user out.
3050 public function logout() {
3051 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3057 * Clear the user's cookies and session, and reset the instance cache.
3060 public function doLogout() {
3061 $this->clearInstanceCache( 'defaults' );
3063 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3065 $this->clearCookie( 'UserID' );
3066 $this->clearCookie( 'Token' );
3067 $this->clearCookie( 'forceHTTPS' );
3069 # Remember when user logged out, to prevent seeing cached pages
3070 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
3074 * Save this user's settings into the database.
3075 * @todo Only rarely do all these fields need to be set!
3077 public function saveSettings() {
3081 if ( wfReadOnly() ) { return; }
3082 if ( 0 == $this->mId
) { return; }
3084 $this->mTouched
= self
::newTouchedTimestamp();
3085 if ( !$wgAuth->allowSetLocalPassword() ) {
3086 $this->mPassword
= '';
3089 $dbw = wfGetDB( DB_MASTER
);
3090 $dbw->update( 'user',
3092 'user_name' => $this->mName
,
3093 'user_password' => $this->mPassword
,
3094 'user_newpassword' => $this->mNewpassword
,
3095 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3096 'user_real_name' => $this->mRealName
,
3097 'user_email' => $this->mEmail
,
3098 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3099 'user_touched' => $dbw->timestamp( $this->mTouched
),
3100 'user_token' => strval( $this->mToken
),
3101 'user_email_token' => $this->mEmailToken
,
3102 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3103 ), array( /* WHERE */
3104 'user_id' => $this->mId
3108 $this->saveOptions();
3110 wfRunHooks( 'UserSaveSettings', array( $this ) );
3111 $this->clearSharedCache();
3112 $this->getUserPage()->invalidateCache();
3116 * If only this user's username is known, and it exists, return the user ID.
3119 public function idForName() {
3120 $s = trim( $this->getName() );
3121 if ( $s === '' ) return 0;
3123 $dbr = wfGetDB( DB_SLAVE
);
3124 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
3125 if ( $id === false ) {
3132 * Add a user to the database, return the user object
3134 * @param string $name Username to add
3135 * @param array $params of Strings Non-default parameters to save to the database as user_* fields:
3136 * - password The user's password hash. Password logins will be disabled if this is omitted.
3137 * - newpassword Hash for a temporary password that has been mailed to the user
3138 * - email The user's email address
3139 * - email_authenticated The email authentication timestamp
3140 * - real_name The user's real name
3141 * - options An associative array of non-default options
3142 * - token Random authentication token. Do not set.
3143 * - registration Registration timestamp. Do not set.
3145 * @return User object, or null if the username already exists
3147 public static function createNew( $name, $params = array() ) {
3150 $user->setToken(); // init token
3151 if ( isset( $params['options'] ) ) {
3152 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3153 unset( $params['options'] );
3155 $dbw = wfGetDB( DB_MASTER
);
3156 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3159 'user_id' => $seqVal,
3160 'user_name' => $name,
3161 'user_password' => $user->mPassword
,
3162 'user_newpassword' => $user->mNewpassword
,
3163 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3164 'user_email' => $user->mEmail
,
3165 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3166 'user_real_name' => $user->mRealName
,
3167 'user_token' => strval( $user->mToken
),
3168 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3169 'user_editcount' => 0,
3170 'user_touched' => $dbw->timestamp( self
::newTouchedTimestamp() ),
3172 foreach ( $params as $name => $value ) {
3173 $fields["user_$name"] = $value;
3175 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3176 if ( $dbw->affectedRows() ) {
3177 $newUser = User
::newFromId( $dbw->insertId() );
3185 * Add this existing user object to the database. If the user already
3186 * exists, a fatal status object is returned, and the user object is
3187 * initialised with the data from the database.
3189 * Previously, this function generated a DB error due to a key conflict
3190 * if the user already existed. Many extension callers use this function
3191 * in code along the lines of:
3193 * $user = User::newFromName( $name );
3194 * if ( !$user->isLoggedIn() ) {
3195 * $user->addToDatabase();
3197 * // do something with $user...
3199 * However, this was vulnerable to a race condition (bug 16020). By
3200 * initialising the user object if the user exists, we aim to support this
3201 * calling sequence as far as possible.
3203 * Note that if the user exists, this function will acquire a write lock,
3204 * so it is still advisable to make the call conditional on isLoggedIn(),
3205 * and to commit the transaction after calling.
3207 * @throws MWException
3210 public function addToDatabase() {
3212 if ( !$this->mToken
) {
3213 $this->setToken(); // init token
3216 $this->mTouched
= self
::newTouchedTimestamp();
3218 $dbw = wfGetDB( DB_MASTER
);
3219 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3220 $dbw->insert( 'user',
3222 'user_id' => $seqVal,
3223 'user_name' => $this->mName
,
3224 'user_password' => $this->mPassword
,
3225 'user_newpassword' => $this->mNewpassword
,
3226 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3227 'user_email' => $this->mEmail
,
3228 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3229 'user_real_name' => $this->mRealName
,
3230 'user_token' => strval( $this->mToken
),
3231 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3232 'user_editcount' => 0,
3233 'user_touched' => $dbw->timestamp( $this->mTouched
),
3237 if ( !$dbw->affectedRows() ) {
3238 $this->mId
= $dbw->selectField( 'user', 'user_id',
3239 array( 'user_name' => $this->mName
), __METHOD__
);
3242 if ( $this->loadFromDatabase() ) {
3247 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3248 "to insert a user row, but then it doesn't exist when we select it!" );
3250 return Status
::newFatal( 'userexists' );
3252 $this->mId
= $dbw->insertId();
3254 // Clear instance cache other than user table data, which is already accurate
3255 $this->clearInstanceCache();
3257 $this->saveOptions();
3258 return Status
::newGood();
3262 * If this user is logged-in and blocked,
3263 * block any IP address they've successfully logged in from.
3264 * @return bool A block was spread
3266 public function spreadAnyEditBlock() {
3267 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3268 return $this->spreadBlock();
3274 * If this (non-anonymous) user is blocked,
3275 * block the IP address they've successfully logged in from.
3276 * @return bool A block was spread
3278 protected function spreadBlock() {
3279 wfDebug( __METHOD__
. "()\n" );
3281 if ( $this->mId
== 0 ) {
3285 $userblock = Block
::newFromTarget( $this->getName() );
3286 if ( !$userblock ) {
3290 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3294 * Generate a string which will be different for any combination of
3295 * user options which would produce different parser output.
3296 * This will be used as part of the hash key for the parser cache,
3297 * so users with the same options can share the same cached data
3300 * Extensions which require it should install 'PageRenderingHash' hook,
3301 * which will give them a chance to modify this key based on their own
3304 * @deprecated since 1.17 use the ParserOptions object to get the relevant options
3305 * @return String Page rendering hash
3307 public function getPageRenderingHash() {
3308 wfDeprecated( __METHOD__
, '1.17' );
3310 global $wgRenderHashAppend, $wgLang, $wgContLang;
3311 if( $this->mHash
) {
3312 return $this->mHash
;
3315 // stubthreshold is only included below for completeness,
3316 // since it disables the parser cache, its value will always
3317 // be 0 when this function is called by parsercache.
3319 $confstr = $this->getOption( 'math' );
3320 $confstr .= '!' . $this->getStubThreshold();
3321 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ?
'1' : '' );
3322 $confstr .= '!' . $wgLang->getCode();
3323 $confstr .= '!' . $this->getOption( 'thumbsize' );
3324 // add in language specific options, if any
3325 $extra = $wgContLang->getExtraHashOptions();
3328 // Since the skin could be overloading link(), it should be
3329 // included here but in practice, none of our skins do that.
3331 $confstr .= $wgRenderHashAppend;
3333 // Give a chance for extensions to modify the hash, if they have
3334 // extra options or other effects on the parser cache.
3335 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
3337 // Make it a valid memcached key fragment
3338 $confstr = str_replace( ' ', '_', $confstr );
3339 $this->mHash
= $confstr;
3344 * Get whether the user is explicitly blocked from account creation.
3345 * @return Bool|Block
3347 public function isBlockedFromCreateAccount() {
3348 $this->getBlockedStatus();
3349 if( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3350 return $this->mBlock
;
3353 # bug 13611: if the IP address the user is trying to create an account from is
3354 # blocked with createaccount disabled, prevent new account creation there even
3355 # when the user is logged in
3356 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3357 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3359 return $this->mBlockedFromCreateAccount
instanceof Block
&& $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3360 ?
$this->mBlockedFromCreateAccount
3365 * Get whether the user is blocked from using Special:Emailuser.
3368 public function isBlockedFromEmailuser() {
3369 $this->getBlockedStatus();
3370 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3374 * Get whether the user is allowed to create an account.
3377 function isAllowedToCreateAccount() {
3378 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3382 * Get this user's personal page title.
3384 * @return Title: User's personal page title
3386 public function getUserPage() {
3387 return Title
::makeTitle( NS_USER
, $this->getName() );
3391 * Get this user's talk page title.
3393 * @return Title: User's talk page title
3395 public function getTalkPage() {
3396 $title = $this->getUserPage();
3397 return $title->getTalkPage();
3401 * Determine whether the user is a newbie. Newbies are either
3402 * anonymous IPs, or the most recently created accounts.
3405 public function isNewbie() {
3406 return !$this->isAllowed( 'autoconfirmed' );
3410 * Check to see if the given clear-text password is one of the accepted passwords
3411 * @param string $password user password.
3412 * @return Boolean: True if the given password is correct, otherwise False.
3414 public function checkPassword( $password ) {
3415 global $wgAuth, $wgLegacyEncoding;
3418 // Even though we stop people from creating passwords that
3419 // are shorter than this, doesn't mean people wont be able
3420 // to. Certain authentication plugins do NOT want to save
3421 // domain passwords in a mysql database, so we should
3422 // check this (in case $wgAuth->strict() is false).
3423 if( !$this->isValidPassword( $password ) ) {
3427 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
3429 } elseif( $wgAuth->strict() ) {
3430 /* Auth plugin doesn't allow local authentication */
3432 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
3433 /* Auth plugin doesn't allow local authentication for this user name */
3436 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
3438 } elseif ( $wgLegacyEncoding ) {
3439 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3440 # Check for this with iconv
3441 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3442 if ( $cp1252Password != $password &&
3443 self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) )
3452 * Check if the given clear-text password matches the temporary password
3453 * sent by e-mail for password reset operations.
3455 * @param $plaintext string
3457 * @return Boolean: True if matches, false otherwise
3459 public function checkTemporaryPassword( $plaintext ) {
3460 global $wgNewPasswordExpiry;
3463 if( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
3464 if ( is_null( $this->mNewpassTime
) ) {
3467 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3468 return ( time() < $expiry );
3475 * Alias for getEditToken.
3476 * @deprecated since 1.19, use getEditToken instead.
3478 * @param string|array $salt of Strings Optional function-specific data for hashing
3479 * @param $request WebRequest object to use or null to use $wgRequest
3480 * @return String The new edit token
3482 public function editToken( $salt = '', $request = null ) {
3483 wfDeprecated( __METHOD__
, '1.19' );
3484 return $this->getEditToken( $salt, $request );
3488 * Initialize (if necessary) and return a session token value
3489 * which can be used in edit forms to show that the user's
3490 * login credentials aren't being hijacked with a foreign form
3495 * @param string|array $salt of Strings Optional function-specific data for hashing
3496 * @param $request WebRequest object to use or null to use $wgRequest
3497 * @return String The new edit token
3499 public function getEditToken( $salt = '', $request = null ) {
3500 if ( $request == null ) {
3501 $request = $this->getRequest();
3504 if ( $this->isAnon() ) {
3505 return EDIT_TOKEN_SUFFIX
;
3507 $token = $request->getSessionData( 'wsEditToken' );
3508 if ( $token === null ) {
3509 $token = MWCryptRand
::generateHex( 32 );
3510 $request->setSessionData( 'wsEditToken', $token );
3512 if( is_array( $salt ) ) {
3513 $salt = implode( '|', $salt );
3515 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
3520 * Generate a looking random token for various uses.
3522 * @return String The new random token
3523 * @deprecated since 1.20; Use MWCryptRand for secure purposes or wfRandomString for pseudo-randomness
3525 public static function generateToken() {
3526 return MWCryptRand
::generateHex( 32 );
3530 * Check given value against the token value stored in the session.
3531 * A match should confirm that the form was submitted from the
3532 * user's own login session, not a form submission from a third-party
3535 * @param string $val Input value to compare
3536 * @param string $salt Optional function-specific data for hashing
3537 * @param $request WebRequest object to use or null to use $wgRequest
3538 * @return Boolean: Whether the token matches
3540 public function matchEditToken( $val, $salt = '', $request = null ) {
3541 $sessionToken = $this->getEditToken( $salt, $request );
3542 if ( $val != $sessionToken ) {
3543 wfDebug( "User::matchEditToken: broken session data\n" );
3545 return $val == $sessionToken;
3549 * Check given value against the token value stored in the session,
3550 * ignoring the suffix.
3552 * @param string $val Input value to compare
3553 * @param string $salt Optional function-specific data for hashing
3554 * @param $request WebRequest object to use or null to use $wgRequest
3555 * @return Boolean: Whether the token matches
3557 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3558 $sessionToken = $this->getEditToken( $salt, $request );
3559 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3563 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3564 * mail to the user's given address.
3566 * @param string $type message to send, either "created", "changed" or "set"
3567 * @return Status object
3569 public function sendConfirmationMail( $type = 'created' ) {
3571 $expiration = null; // gets passed-by-ref and defined in next line.
3572 $token = $this->confirmationToken( $expiration );
3573 $url = $this->confirmationTokenUrl( $token );
3574 $invalidateURL = $this->invalidationTokenUrl( $token );
3575 $this->saveSettings();
3577 if ( $type == 'created' ||
$type === false ) {
3578 $message = 'confirmemail_body';
3579 } elseif ( $type === true ) {
3580 $message = 'confirmemail_body_changed';
3582 $message = 'confirmemail_body_' . $type;
3585 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3586 wfMessage( $message,
3587 $this->getRequest()->getIP(),
3590 $wgLang->timeanddate( $expiration, false ),
3592 $wgLang->date( $expiration, false ),
3593 $wgLang->time( $expiration, false ) )->text() );
3597 * Send an e-mail to this user's account. Does not check for
3598 * confirmed status or validity.
3600 * @param string $subject Message subject
3601 * @param string $body Message body
3602 * @param string $from Optional From address; if unspecified, default $wgPasswordSender will be used
3603 * @param string $replyto Reply-To address
3606 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3607 if( is_null( $from ) ) {
3608 global $wgPasswordSender, $wgPasswordSenderName;
3609 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
3611 $sender = new MailAddress( $from );
3614 $to = new MailAddress( $this );
3615 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
3619 * Generate, store, and return a new e-mail confirmation code.
3620 * A hash (unsalted, since it's used as a key) is stored.
3622 * @note Call saveSettings() after calling this function to commit
3623 * this change to the database.
3625 * @param &$expiration \mixed Accepts the expiration time
3626 * @return String New token
3628 private function confirmationToken( &$expiration ) {
3629 global $wgUserEmailConfirmationTokenExpiry;
3631 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
3632 $expiration = wfTimestamp( TS_MW
, $expires );
3634 $token = MWCryptRand
::generateHex( 32 );
3635 $hash = md5( $token );
3636 $this->mEmailToken
= $hash;
3637 $this->mEmailTokenExpires
= $expiration;
3642 * Return a URL the user can use to confirm their email address.
3643 * @param string $token Accepts the email confirmation token
3644 * @return String New token URL
3646 private function confirmationTokenUrl( $token ) {
3647 return $this->getTokenUrl( 'ConfirmEmail', $token );
3651 * Return a URL the user can use to invalidate their email address.
3652 * @param string $token Accepts the email confirmation token
3653 * @return String New token URL
3655 private function invalidationTokenUrl( $token ) {
3656 return $this->getTokenUrl( 'InvalidateEmail', $token );
3660 * Internal function to format the e-mail validation/invalidation URLs.
3661 * This uses a quickie hack to use the
3662 * hardcoded English names of the Special: pages, for ASCII safety.
3664 * @note Since these URLs get dropped directly into emails, using the
3665 * short English names avoids insanely long URL-encoded links, which
3666 * also sometimes can get corrupted in some browsers/mailers
3667 * (bug 6957 with Gmail and Internet Explorer).
3669 * @param string $page Special page
3670 * @param string $token Token
3671 * @return String Formatted URL
3673 protected function getTokenUrl( $page, $token ) {
3674 // Hack to bypass localization of 'Special:'
3675 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
3676 return $title->getCanonicalURL();
3680 * Mark the e-mail address confirmed.
3682 * @note Call saveSettings() after calling this function to commit the change.
3686 public function confirmEmail() {
3687 // Check if it's already confirmed, so we don't touch the database
3688 // and fire the ConfirmEmailComplete hook on redundant confirmations.
3689 if ( !$this->isEmailConfirmed() ) {
3690 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3691 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3697 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3698 * address if it was already confirmed.
3700 * @note Call saveSettings() after calling this function to commit the change.
3701 * @return bool Returns true
3703 function invalidateEmail() {
3705 $this->mEmailToken
= null;
3706 $this->mEmailTokenExpires
= null;
3707 $this->setEmailAuthenticationTimestamp( null );
3708 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3713 * Set the e-mail authentication timestamp.
3714 * @param string $timestamp TS_MW timestamp
3716 function setEmailAuthenticationTimestamp( $timestamp ) {
3718 $this->mEmailAuthenticated
= $timestamp;
3719 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
3723 * Is this user allowed to send e-mails within limits of current
3724 * site configuration?
3727 public function canSendEmail() {
3728 global $wgEnableEmail, $wgEnableUserEmail;
3729 if( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
3732 $canSend = $this->isEmailConfirmed();
3733 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3738 * Is this user allowed to receive e-mails within limits of current
3739 * site configuration?
3742 public function canReceiveEmail() {
3743 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3747 * Is this user's e-mail address valid-looking and confirmed within
3748 * limits of the current site configuration?
3750 * @note If $wgEmailAuthentication is on, this may require the user to have
3751 * confirmed their address by returning a code or using a password
3752 * sent to the address from the wiki.
3756 public function isEmailConfirmed() {
3757 global $wgEmailAuthentication;
3760 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3761 if( $this->isAnon() ) {
3764 if( !Sanitizer
::validateEmail( $this->mEmail
) ) {
3767 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
3777 * Check whether there is an outstanding request for e-mail confirmation.
3780 public function isEmailConfirmationPending() {
3781 global $wgEmailAuthentication;
3782 return $wgEmailAuthentication &&
3783 !$this->isEmailConfirmed() &&
3784 $this->mEmailToken
&&
3785 $this->mEmailTokenExpires
> wfTimestamp();
3789 * Get the timestamp of account creation.
3791 * @return String|Bool|Null Timestamp of account creation, false for
3792 * non-existent/anonymous user accounts, or null if existing account
3793 * but information is not in database.
3795 public function getRegistration() {
3796 if ( $this->isAnon() ) {
3800 return $this->mRegistration
;
3804 * Get the timestamp of the first edit
3806 * @return String|Bool Timestamp of first edit, or false for
3807 * non-existent/anonymous user accounts.
3809 public function getFirstEditTimestamp() {
3810 if( $this->getId() == 0 ) {
3811 return false; // anons
3813 $dbr = wfGetDB( DB_SLAVE
);
3814 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3815 array( 'rev_user' => $this->getId() ),
3817 array( 'ORDER BY' => 'rev_timestamp ASC' )
3820 return false; // no edits
3822 return wfTimestamp( TS_MW
, $time );
3826 * Get the permissions associated with a given list of groups
3828 * @param array $groups of Strings List of internal group names
3829 * @return Array of Strings List of permission key names for given groups combined
3831 public static function getGroupPermissions( $groups ) {
3832 global $wgGroupPermissions, $wgRevokePermissions;
3834 // grant every granted permission first
3835 foreach( $groups as $group ) {
3836 if( isset( $wgGroupPermissions[$group] ) ) {
3837 $rights = array_merge( $rights,
3838 // array_filter removes empty items
3839 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3842 // now revoke the revoked permissions
3843 foreach( $groups as $group ) {
3844 if( isset( $wgRevokePermissions[$group] ) ) {
3845 $rights = array_diff( $rights,
3846 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3849 return array_unique( $rights );
3853 * Get all the groups who have a given permission
3855 * @param string $role Role to check
3856 * @return Array of Strings List of internal group names with the given permission
3858 public static function getGroupsWithPermission( $role ) {
3859 global $wgGroupPermissions;
3860 $allowedGroups = array();
3861 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
3862 if ( self
::groupHasPermission( $group, $role ) ) {
3863 $allowedGroups[] = $group;
3866 return $allowedGroups;
3870 * Check, if the given group has the given permission
3873 * @param string $group Group to check
3874 * @param string $role Role to check
3877 public static function groupHasPermission( $group, $role ) {
3878 global $wgGroupPermissions, $wgRevokePermissions;
3879 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
3880 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
3884 * Get the localized descriptive name for a group, if it exists
3886 * @param string $group Internal group name
3887 * @return String Localized descriptive group name
3889 public static function getGroupName( $group ) {
3890 $msg = wfMessage( "group-$group" );
3891 return $msg->isBlank() ?
$group : $msg->text();
3895 * Get the localized descriptive name for a member of a group, if it exists
3897 * @param string $group Internal group name
3898 * @param string $username Username for gender (since 1.19)
3899 * @return String Localized name for group member
3901 public static function getGroupMember( $group, $username = '#' ) {
3902 $msg = wfMessage( "group-$group-member", $username );
3903 return $msg->isBlank() ?
$group : $msg->text();
3907 * Return the set of defined explicit groups.
3908 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3909 * are not included, as they are defined automatically, not in the database.
3910 * @return Array of internal group names
3912 public static function getAllGroups() {
3913 global $wgGroupPermissions, $wgRevokePermissions;
3915 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3916 self
::getImplicitGroups()
3921 * Get a list of all available permissions.
3922 * @return Array of permission names
3924 public static function getAllRights() {
3925 if ( self
::$mAllRights === false ) {
3926 global $wgAvailableRights;
3927 if ( count( $wgAvailableRights ) ) {
3928 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3930 self
::$mAllRights = self
::$mCoreRights;
3932 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3934 return self
::$mAllRights;
3938 * Get a list of implicit groups
3939 * @return Array of Strings Array of internal group names
3941 public static function getImplicitGroups() {
3942 global $wgImplicitGroups;
3943 $groups = $wgImplicitGroups;
3944 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3949 * Get the title of a page describing a particular group
3951 * @param string $group Internal group name
3952 * @return Title|Bool Title of the page if it exists, false otherwise
3954 public static function getGroupPage( $group ) {
3955 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
3956 if( $msg->exists() ) {
3957 $title = Title
::newFromText( $msg->text() );
3958 if( is_object( $title ) )
3965 * Create a link to the group in HTML, if available;
3966 * else return the group name.
3968 * @param string $group Internal name of the group
3969 * @param string $text The text of the link
3970 * @return String HTML link to the group
3972 public static function makeGroupLinkHTML( $group, $text = '' ) {
3974 $text = self
::getGroupName( $group );
3976 $title = self
::getGroupPage( $group );
3978 return Linker
::link( $title, htmlspecialchars( $text ) );
3985 * Create a link to the group in Wikitext, if available;
3986 * else return the group name.
3988 * @param string $group Internal name of the group
3989 * @param string $text The text of the link
3990 * @return String Wikilink to the group
3992 public static function makeGroupLinkWiki( $group, $text = '' ) {
3994 $text = self
::getGroupName( $group );
3996 $title = self
::getGroupPage( $group );
3998 $page = $title->getPrefixedText();
3999 return "[[$page|$text]]";
4006 * Returns an array of the groups that a particular group can add/remove.
4008 * @param string $group the group to check for whether it can add/remove
4009 * @return Array array( 'add' => array( addablegroups ),
4010 * 'remove' => array( removablegroups ),
4011 * 'add-self' => array( addablegroups to self),
4012 * 'remove-self' => array( removable groups from self) )
4014 public static function changeableByGroup( $group ) {
4015 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4017 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
4018 if( empty( $wgAddGroups[$group] ) ) {
4019 // Don't add anything to $groups
4020 } elseif( $wgAddGroups[$group] === true ) {
4021 // You get everything
4022 $groups['add'] = self
::getAllGroups();
4023 } elseif( is_array( $wgAddGroups[$group] ) ) {
4024 $groups['add'] = $wgAddGroups[$group];
4027 // Same thing for remove
4028 if( empty( $wgRemoveGroups[$group] ) ) {
4029 } elseif( $wgRemoveGroups[$group] === true ) {
4030 $groups['remove'] = self
::getAllGroups();
4031 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
4032 $groups['remove'] = $wgRemoveGroups[$group];
4035 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4036 if( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4037 foreach( $wgGroupsAddToSelf as $key => $value ) {
4038 if( is_int( $key ) ) {
4039 $wgGroupsAddToSelf['user'][] = $value;
4044 if( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4045 foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
4046 if( is_int( $key ) ) {
4047 $wgGroupsRemoveFromSelf['user'][] = $value;
4052 // Now figure out what groups the user can add to him/herself
4053 if( empty( $wgGroupsAddToSelf[$group] ) ) {
4054 } elseif( $wgGroupsAddToSelf[$group] === true ) {
4055 // No idea WHY this would be used, but it's there
4056 $groups['add-self'] = User
::getAllGroups();
4057 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
4058 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4061 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4062 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
4063 $groups['remove-self'] = User
::getAllGroups();
4064 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4065 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4072 * Returns an array of groups that this user can add and remove
4073 * @return Array array( 'add' => array( addablegroups ),
4074 * 'remove' => array( removablegroups ),
4075 * 'add-self' => array( addablegroups to self),
4076 * 'remove-self' => array( removable groups from self) )
4078 public function changeableGroups() {
4079 if( $this->isAllowed( 'userrights' ) ) {
4080 // This group gives the right to modify everything (reverse-
4081 // compatibility with old "userrights lets you change
4083 // Using array_merge to make the groups reindexed
4084 $all = array_merge( User
::getAllGroups() );
4088 'add-self' => array(),
4089 'remove-self' => array()
4093 // Okay, it's not so simple, we will have to go through the arrays
4096 'remove' => array(),
4097 'add-self' => array(),
4098 'remove-self' => array()
4100 $addergroups = $this->getEffectiveGroups();
4102 foreach( $addergroups as $addergroup ) {
4103 $groups = array_merge_recursive(
4104 $groups, $this->changeableByGroup( $addergroup )
4106 $groups['add'] = array_unique( $groups['add'] );
4107 $groups['remove'] = array_unique( $groups['remove'] );
4108 $groups['add-self'] = array_unique( $groups['add-self'] );
4109 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4115 * Increment the user's edit-count field.
4116 * Will have no effect for anonymous users.
4118 public function incEditCount() {
4119 if( !$this->isAnon() ) {
4120 $dbw = wfGetDB( DB_MASTER
);
4123 array( 'user_editcount=user_editcount+1' ),
4124 array( 'user_id' => $this->getId() ),
4128 // Lazy initialization check...
4129 if( $dbw->affectedRows() == 0 ) {
4130 // Now here's a goddamn hack...
4131 $dbr = wfGetDB( DB_SLAVE
);
4132 if( $dbr !== $dbw ) {
4133 // If we actually have a slave server, the count is
4134 // at least one behind because the current transaction
4135 // has not been committed and replicated.
4136 $this->initEditCount( 1 );
4138 // But if DB_SLAVE is selecting the master, then the
4139 // count we just read includes the revision that was
4140 // just added in the working transaction.
4141 $this->initEditCount();
4145 // edit count in user cache too
4146 $this->invalidateCache();
4150 * Initialize user_editcount from data out of the revision table
4152 * @param $add Integer Edits to add to the count from the revision table
4153 * @return Integer Number of edits
4155 protected function initEditCount( $add = 0 ) {
4156 // Pull from a slave to be less cruel to servers
4157 // Accuracy isn't the point anyway here
4158 $dbr = wfGetDB( DB_SLAVE
);
4159 $count = (int) $dbr->selectField(
4162 array( 'rev_user' => $this->getId() ),
4165 $count = $count +
$add;
4167 $dbw = wfGetDB( DB_MASTER
);
4170 array( 'user_editcount' => $count ),
4171 array( 'user_id' => $this->getId() ),
4179 * Get the description of a given right
4181 * @param string $right Right to query
4182 * @return String Localized description of the right
4184 public static function getRightDescription( $right ) {
4185 $key = "right-$right";
4186 $msg = wfMessage( $key );
4187 return $msg->isBlank() ?
$right : $msg->text();
4191 * Make an old-style password hash
4193 * @param string $password Plain-text password
4194 * @param string $userId User ID
4195 * @return String Password hash
4197 public static function oldCrypt( $password, $userId ) {
4198 global $wgPasswordSalt;
4199 if ( $wgPasswordSalt ) {
4200 return md5( $userId . '-' . md5( $password ) );
4202 return md5( $password );
4207 * Make a new-style password hash
4209 * @param string $password Plain-text password
4210 * @param bool|string $salt Optional salt, may be random or the user ID.
4212 * If unspecified or false, will generate one automatically
4213 * @return String Password hash
4215 public static function crypt( $password, $salt = false ) {
4216 global $wgPasswordSalt;
4219 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4223 if( $wgPasswordSalt ) {
4224 if ( $salt === false ) {
4225 $salt = MWCryptRand
::generateHex( 8 );
4227 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4229 return ':A:' . md5( $password );
4234 * Compare a password hash with a plain-text password. Requires the user
4235 * ID if there's a chance that the hash is an old-style hash.
4237 * @param string $hash Password hash
4238 * @param string $password Plain-text password to compare
4239 * @param string|bool $userId User ID for old-style password salt
4243 public static function comparePasswords( $hash, $password, $userId = false ) {
4244 $type = substr( $hash, 0, 3 );
4247 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4251 if ( $type == ':A:' ) {
4253 return md5( $password ) === substr( $hash, 3 );
4254 } elseif ( $type == ':B:' ) {
4256 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4257 return md5( $salt . '-' . md5( $password ) ) === $realHash;
4260 return self
::oldCrypt( $password, $userId ) === $hash;
4265 * Add a newuser log entry for this user.
4266 * Before 1.19 the return value was always true.
4268 * @param string|bool $action account creation type.
4269 * - String, one of the following values:
4270 * - 'create' for an anonymous user creating an account for himself.
4271 * This will force the action's performer to be the created user itself,
4272 * no matter the value of $wgUser
4273 * - 'create2' for a logged in user creating an account for someone else
4274 * - 'byemail' when the created user will receive its password by e-mail
4275 * - Boolean means whether the account was created by e-mail (deprecated):
4276 * - true will be converted to 'byemail'
4277 * - false will be converted to 'create' if this object is the same as
4278 * $wgUser and to 'create2' otherwise
4280 * @param string $reason user supplied reason
4282 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4284 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4285 global $wgUser, $wgNewUserLog;
4286 if( empty( $wgNewUserLog ) ) {
4287 return true; // disabled
4290 if ( $action === true ) {
4291 $action = 'byemail';
4292 } elseif ( $action === false ) {
4293 if ( $this->getName() == $wgUser->getName() ) {
4296 $action = 'create2';
4300 if ( $action === 'create' ||
$action === 'autocreate' ) {
4303 $performer = $wgUser;
4306 $logEntry = new ManualLogEntry( 'newusers', $action );
4307 $logEntry->setPerformer( $performer );
4308 $logEntry->setTarget( $this->getUserPage() );
4309 $logEntry->setComment( $reason );
4310 $logEntry->setParameters( array(
4311 '4::userid' => $this->getId(),
4313 $logid = $logEntry->insert();
4315 if ( $action !== 'autocreate' ) {
4316 $logEntry->publish( $logid );
4323 * Add an autocreate newuser log entry for this user
4324 * Used by things like CentralAuth and perhaps other authplugins.
4325 * Consider calling addNewUserLogEntry() directly instead.
4329 public function addNewUserLogEntryAutoCreate() {
4330 $this->addNewUserLogEntry( 'autocreate' );
4336 * Load the user options either from cache, the database or an array
4338 * @param array $data Rows for the current user out of the user_properties table
4340 protected function loadOptions( $data = null ) {
4345 if ( $this->mOptionsLoaded
) {
4349 $this->mOptions
= self
::getDefaultOptions();
4351 if ( !$this->getId() ) {
4352 // For unlogged-in users, load language/variant options from request.
4353 // There's no need to do it for logged-in users: they can set preferences,
4354 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4355 // so don't override user's choice (especially when the user chooses site default).
4356 $variant = $wgContLang->getDefaultVariant();
4357 $this->mOptions
['variant'] = $variant;
4358 $this->mOptions
['language'] = $variant;
4359 $this->mOptionsLoaded
= true;
4363 // Maybe load from the object
4364 if ( !is_null( $this->mOptionOverrides
) ) {
4365 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4366 foreach( $this->mOptionOverrides
as $key => $value ) {
4367 $this->mOptions
[$key] = $value;
4370 if( !is_array( $data ) ) {
4371 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4372 // Load from database
4373 $dbr = wfGetDB( DB_SLAVE
);
4375 $res = $dbr->select(
4377 array( 'up_property', 'up_value' ),
4378 array( 'up_user' => $this->getId() ),
4382 $this->mOptionOverrides
= array();
4384 foreach ( $res as $row ) {
4385 $data[$row->up_property
] = $row->up_value
;
4388 foreach ( $data as $property => $value ) {
4389 $this->mOptionOverrides
[$property] = $value;
4390 $this->mOptions
[$property] = $value;
4394 $this->mOptionsLoaded
= true;
4396 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
4402 protected function saveOptions() {
4403 $this->loadOptions();
4405 // Not using getOptions(), to keep hidden preferences in database
4406 $saveOptions = $this->mOptions
;
4408 // Allow hooks to abort, for instance to save to a global profile.
4409 // Reset options to default state before saving.
4410 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4414 $userId = $this->getId();
4415 $insert_rows = array();
4416 foreach( $saveOptions as $key => $value ) {
4417 # Don't bother storing default values
4418 $defaultOption = self
::getDefaultOption( $key );
4419 if ( ( is_null( $defaultOption ) &&
4420 !( $value === false ||
is_null( $value ) ) ) ||
4421 $value != $defaultOption ) {
4422 $insert_rows[] = array(
4423 'up_user' => $userId,
4424 'up_property' => $key,
4425 'up_value' => $value,
4430 $dbw = wfGetDB( DB_MASTER
);
4431 $hasRows = $dbw->selectField( 'user_properties', '1',
4432 array( 'up_user' => $userId ), __METHOD__
);
4435 // Only do this delete if there is something there. A very large portion of
4436 // calls to this function are for setting 'rememberpassword' for new accounts.
4437 // Doing this delete for new accounts with no rows in the table rougly causes
4438 // gap locks on [max user ID,+infinity) which causes high contention since many
4439 // updates will pile up on each other since they are for higher (newer) user IDs.
4440 $dbw->delete( 'user_properties', array( 'up_user' => $userId ), __METHOD__
);
4442 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
4446 * Provide an array of HTML5 attributes to put on an input element
4447 * intended for the user to enter a new password. This may include
4448 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4450 * Do *not* use this when asking the user to enter his current password!
4451 * Regardless of configuration, users may have invalid passwords for whatever
4452 * reason (e.g., they were set before requirements were tightened up).
4453 * Only use it when asking for a new password, like on account creation or
4456 * Obviously, you still need to do server-side checking.
4458 * NOTE: A combination of bugs in various browsers means that this function
4459 * actually just returns array() unconditionally at the moment. May as
4460 * well keep it around for when the browser bugs get fixed, though.
4462 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4464 * @return array Array of HTML attributes suitable for feeding to
4465 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4466 * That will potentially output invalid XHTML 1.0 Transitional, and will
4467 * get confused by the boolean attribute syntax used.)
4469 public static function passwordChangeInputAttribs() {
4470 global $wgMinimalPasswordLength;
4472 if ( $wgMinimalPasswordLength == 0 ) {
4476 # Note that the pattern requirement will always be satisfied if the
4477 # input is empty, so we need required in all cases.
4479 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4480 # if e-mail confirmation is being used. Since HTML5 input validation
4481 # is b0rked anyway in some browsers, just return nothing. When it's
4482 # re-enabled, fix this code to not output required for e-mail
4484 #$ret = array( 'required' );
4487 # We can't actually do this right now, because Opera 9.6 will print out
4488 # the entered password visibly in its error message! When other
4489 # browsers add support for this attribute, or Opera fixes its support,
4490 # we can add support with a version check to avoid doing this on Opera
4491 # versions where it will be a problem. Reported to Opera as
4492 # DSK-262266, but they don't have a public bug tracker for us to follow.
4494 if ( $wgMinimalPasswordLength > 1 ) {
4495 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4496 $ret['title'] = wfMessage( 'passwordtooshort' )
4497 ->numParams( $wgMinimalPasswordLength )->text();
4505 * Return the list of user fields that should be selected to create
4506 * a new user object.
4509 public static function selectFields() {
4516 'user_newpass_time',
4520 'user_email_authenticated',
4522 'user_email_token_expires',
4523 'user_registration',