3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Int Number of characters in user_token field.
27 define( 'USER_TOKEN_LENGTH', 32 );
30 * Int Serialized record version.
33 define( 'MW_USER_VERSION', 8 );
36 * String Some punctuation to prevent editing from broken text-mangling proxies.
39 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
42 * Thrown by User::setPassword() on error.
45 class PasswordError
extends MWException
{
50 * The User object encapsulates all of the user-specific settings (user_id,
51 * name, rights, password, email address, options, last login time). Client
52 * classes use the getXXX() functions to access these fields. These functions
53 * do all the work of determining whether the user is logged in,
54 * whether the requested option can be satisfied from cookies or
55 * whether a database query is needed. Most of the settings needed
56 * for rendering normal pages are set in the cookie to minimize use
61 * Global constants made accessible as class constants so that autoloader
64 const USER_TOKEN_LENGTH
= USER_TOKEN_LENGTH
;
65 const MW_USER_VERSION
= MW_USER_VERSION
;
66 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
69 * Maximum items in $mWatchedItems
71 const MAX_WATCHED_ITEMS_CACHE
= 100;
74 * Array of Strings List of member variables which are saved to the
75 * shared cache (memcached). Any operation which changes the
76 * corresponding database fields must call a cache-clearing function.
79 static $mCacheVars = array(
90 'mEmailAuthenticated',
97 // user_properties table
102 * Array of Strings Core rights.
103 * Each of these should have a corresponding message of the form
107 static $mCoreRights = array(
127 'editusercssjs', #deprecated
139 'move-rootuserpages',
143 'override-export-depth',
166 'userrights-interwiki',
170 * String Cached results of getAllRights()
172 static $mAllRights = false;
174 /** @name Cache variables */
176 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
177 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
178 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mEditCount,
179 $mGroups, $mOptionOverrides;
183 * Bool Whether the cache variables have been loaded.
189 * Array with already loaded items or true if all items have been loaded.
191 private $mLoadedItems = array();
195 * String Initialization data source if mLoadedItems!==true. May be one of:
196 * - 'defaults' anonymous user initialised from class defaults
197 * - 'name' initialise from mName
198 * - 'id' initialise from mId
199 * - 'session' log in from cookies or session if possible
201 * Use the User::newFrom*() family of functions to set this.
206 * Lazy-initialized variables, invalidated with clearInstanceCache
208 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mRights,
209 $mBlockreason, $mEffectiveGroups, $mImplicitGroups, $mFormerGroups, $mBlockedGlobally,
210 $mLocked, $mHideName, $mOptions;
230 private $mBlockedFromCreateAccount = false;
235 private $mWatchedItems = array();
237 static $idCacheByName = array();
240 * Lightweight constructor for an anonymous user.
241 * Use the User::newFrom* factory functions for other kinds of users.
245 * @see newFromConfirmationCode()
246 * @see newFromSession()
249 function __construct() {
250 $this->clearInstanceCache( 'defaults' );
256 function __toString() {
257 return $this->getName();
261 * Load the user table data for this object from the source given by mFrom.
263 public function load() {
264 if ( $this->mLoadedItems
=== true ) {
267 wfProfileIn( __METHOD__
);
269 # Set it now to avoid infinite recursion in accessors
270 $this->mLoadedItems
= true;
272 switch ( $this->mFrom
) {
274 $this->loadDefaults();
277 $this->mId
= self
::idFromName( $this->mName
);
279 # Nonexistent user placeholder object
280 $this->loadDefaults( $this->mName
);
289 if( !$this->loadFromSession() ) {
290 // Loading from session failed. Load defaults.
291 $this->loadDefaults();
293 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
296 wfProfileOut( __METHOD__
);
297 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
299 wfProfileOut( __METHOD__
);
303 * Load user table data, given mId has already been set.
304 * @return Bool false if the ID does not exist, true otherwise
306 public function loadFromId() {
308 if ( $this->mId
== 0 ) {
309 $this->loadDefaults();
314 $key = wfMemcKey( 'user', 'id', $this->mId
);
315 $data = $wgMemc->get( $key );
316 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
317 # Object is expired, load from DB
322 wfDebug( "User: cache miss for user {$this->mId}\n" );
324 if ( !$this->loadFromDatabase() ) {
325 # Can't load from ID, user is anonymous
328 $this->saveToCache();
330 wfDebug( "User: got user {$this->mId} from cache\n" );
332 foreach ( self
::$mCacheVars as $name ) {
333 $this->$name = $data[$name];
337 $this->mLoadedItems
= true;
343 * Save user data to the shared cache
345 public function saveToCache() {
348 $this->loadOptions();
349 if ( $this->isAnon() ) {
350 // Anonymous users are uncached
354 foreach ( self
::$mCacheVars as $name ) {
355 $data[$name] = $this->$name;
357 $data['mVersion'] = MW_USER_VERSION
;
358 $key = wfMemcKey( 'user', 'id', $this->mId
);
360 $wgMemc->set( $key, $data );
363 /** @name newFrom*() static factory methods */
367 * Static factory method for creation from username.
369 * This is slightly less efficient than newFromId(), so use newFromId() if
370 * you have both an ID and a name handy.
372 * @param string $name Username, validated by Title::newFromText()
373 * @param string|Bool $validate Validate username. Takes the same parameters as
374 * User::getCanonicalName(), except that true is accepted as an alias
375 * for 'valid', for BC.
377 * @return User|bool User object, or false if the username is invalid
378 * (e.g. if it contains illegal characters or is an IP address). If the
379 * username is not present in the database, the result will be a user object
380 * with a name, zero user ID and default settings.
382 public static function newFromName( $name, $validate = 'valid' ) {
383 if ( $validate === true ) {
386 $name = self
::getCanonicalName( $name, $validate );
387 if ( $name === false ) {
390 # Create unloaded user object
394 $u->setItemLoaded( 'name' );
400 * Static factory method for creation from a given user ID.
402 * @param int $id Valid user ID
403 * @return User The corresponding User object
405 public static function newFromId( $id ) {
409 $u->setItemLoaded( 'id' );
414 * Factory method to fetch whichever user has a given email confirmation code.
415 * This code is generated when an account is created or its e-mail address
418 * If the code is invalid or has expired, returns NULL.
420 * @param string $code Confirmation code
421 * @return User object, or null
423 public static function newFromConfirmationCode( $code ) {
424 $dbr = wfGetDB( DB_SLAVE
);
425 $id = $dbr->selectField( 'user', 'user_id', array(
426 'user_email_token' => md5( $code ),
427 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
429 if( $id !== false ) {
430 return User
::newFromId( $id );
437 * Create a new user object using data from session or cookies. If the
438 * login credentials are invalid, the result is an anonymous user.
440 * @param $request WebRequest object to use; $wgRequest will be used if omitted.
441 * @return User object
443 public static function newFromSession( WebRequest
$request = null ) {
445 $user->mFrom
= 'session';
446 $user->mRequest
= $request;
451 * Create a new user object from a user row.
452 * The row should have the following fields from the user table in it:
453 * - either user_name or user_id to load further data if needed (or both)
455 * - all other fields (email, password, etc.)
456 * It is useless to provide the remaining fields if either user_id,
457 * user_name and user_real_name are not provided because the whole row
458 * will be loaded once more from the database when accessing them.
460 * @param array $row A row from the user table
461 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
464 public static function newFromRow( $row, $data = null ) {
466 $user->loadFromRow( $row, $data );
473 * Get the username corresponding to a given user ID
474 * @param int $id User ID
475 * @return String|bool The corresponding username
477 public static function whoIs( $id ) {
478 return UserCache
::singleton()->getProp( $id, 'name' );
482 * Get the real name of a user given their user ID
484 * @param int $id User ID
485 * @return String|bool The corresponding user's real name
487 public static function whoIsReal( $id ) {
488 return UserCache
::singleton()->getProp( $id, 'real_name' );
492 * Get database id given a user name
493 * @param string $name Username
494 * @return Int|Null The corresponding user's ID, or null if user is nonexistent
496 public static function idFromName( $name ) {
497 $nt = Title
::makeTitleSafe( NS_USER
, $name );
498 if( is_null( $nt ) ) {
503 if ( isset( self
::$idCacheByName[$name] ) ) {
504 return self
::$idCacheByName[$name];
507 $dbr = wfGetDB( DB_SLAVE
);
508 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
510 if ( $s === false ) {
513 $result = $s->user_id
;
516 self
::$idCacheByName[$name] = $result;
518 if ( count( self
::$idCacheByName ) > 1000 ) {
519 self
::$idCacheByName = array();
526 * Reset the cache used in idFromName(). For use in tests.
528 public static function resetIdByNameCache() {
529 self
::$idCacheByName = array();
533 * Does the string match an anonymous IPv4 address?
535 * This function exists for username validation, in order to reject
536 * usernames which are similar in form to IP addresses. Strings such
537 * as 300.300.300.300 will return true because it looks like an IP
538 * address, despite not being strictly valid.
540 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
541 * address because the usemod software would "cloak" anonymous IP
542 * addresses like this, if we allowed accounts like this to be created
543 * new users could get the old edits of these anonymous users.
545 * @param string $name to match
548 public static function isIP( $name ) {
549 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name ) || IP
::isIPv6( $name );
553 * Is the input a valid username?
555 * Checks if the input is a valid username, we don't want an empty string,
556 * an IP address, anything that contains slashes (would mess up subpages),
557 * is longer than the maximum allowed username size or doesn't begin with
560 * @param string $name to match
563 public static function isValidUserName( $name ) {
564 global $wgContLang, $wgMaxNameChars;
567 || User
::isIP( $name )
568 ||
strpos( $name, '/' ) !== false
569 ||
strlen( $name ) > $wgMaxNameChars
570 ||
$name != $wgContLang->ucfirst( $name ) ) {
571 wfDebugLog( 'username', __METHOD__
.
572 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
576 // Ensure that the name can't be misresolved as a different title,
577 // such as with extra namespace keys at the start.
578 $parsed = Title
::newFromText( $name );
579 if( is_null( $parsed )
580 ||
$parsed->getNamespace()
581 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
582 wfDebugLog( 'username', __METHOD__
.
583 ": '$name' invalid due to ambiguous prefixes" );
587 // Check an additional blacklist of troublemaker characters.
588 // Should these be merged into the title char list?
589 $unicodeBlacklist = '/[' .
590 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
591 '\x{00a0}' . # non-breaking space
592 '\x{2000}-\x{200f}' . # various whitespace
593 '\x{2028}-\x{202f}' . # breaks and control chars
594 '\x{3000}' . # ideographic space
595 '\x{e000}-\x{f8ff}' . # private use
597 if( preg_match( $unicodeBlacklist, $name ) ) {
598 wfDebugLog( 'username', __METHOD__
.
599 ": '$name' invalid due to blacklisted characters" );
607 * Usernames which fail to pass this function will be blocked
608 * from user login and new account registrations, but may be used
609 * internally by batch processes.
611 * If an account already exists in this form, login will be blocked
612 * by a failure to pass this function.
614 * @param string $name to match
617 public static function isUsableName( $name ) {
618 global $wgReservedUsernames;
619 // Must be a valid username, obviously ;)
620 if ( !self
::isValidUserName( $name ) ) {
624 static $reservedUsernames = false;
625 if ( !$reservedUsernames ) {
626 $reservedUsernames = $wgReservedUsernames;
627 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
630 // Certain names may be reserved for batch processes.
631 foreach ( $reservedUsernames as $reserved ) {
632 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
633 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
635 if ( $reserved == $name ) {
643 * Usernames which fail to pass this function will be blocked
644 * from new account registrations, but may be used internally
645 * either by batch processes or by user accounts which have
646 * already been created.
648 * Additional blacklisting may be added here rather than in
649 * isValidUserName() to avoid disrupting existing accounts.
651 * @param string $name to match
654 public static function isCreatableName( $name ) {
655 global $wgInvalidUsernameCharacters;
657 // Ensure that the username isn't longer than 235 bytes, so that
658 // (at least for the builtin skins) user javascript and css files
659 // will work. (bug 23080)
660 if( strlen( $name ) > 235 ) {
661 wfDebugLog( 'username', __METHOD__
.
662 ": '$name' invalid due to length" );
666 // Preg yells if you try to give it an empty string
667 if( $wgInvalidUsernameCharacters !== '' ) {
668 if( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
669 wfDebugLog( 'username', __METHOD__
.
670 ": '$name' invalid due to wgInvalidUsernameCharacters" );
675 return self
::isUsableName( $name );
679 * Is the input a valid password for this user?
681 * @param string $password Desired password
684 public function isValidPassword( $password ) {
685 //simple boolean wrapper for getPasswordValidity
686 return $this->getPasswordValidity( $password ) === true;
690 * Given unvalidated password input, return error message on failure.
692 * @param string $password Desired password
693 * @return mixed: true on success, string or array of error message on failure
695 public function getPasswordValidity( $password ) {
696 global $wgMinimalPasswordLength, $wgContLang;
698 static $blockedLogins = array(
699 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
700 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
703 $result = false; //init $result to false for the internal checks
705 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
708 if ( $result === false ) {
709 if( strlen( $password ) < $wgMinimalPasswordLength ) {
710 return 'passwordtooshort';
711 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
712 return 'password-name-match';
713 } elseif ( isset( $blockedLogins[$this->getName()] ) && $password == $blockedLogins[$this->getName()] ) {
714 return 'password-login-forbidden';
716 //it seems weird returning true here, but this is because of the
717 //initialization of $result to false above. If the hook is never run or it
718 //doesn't modify $result, then we will likely get down into this if with
722 } elseif( $result === true ) {
725 return $result; //the isValidPassword hook set a string $result and returned true
730 * Does a string look like an e-mail address?
732 * This validates an email address using an HTML5 specification found at:
733 * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
734 * Which as of 2011-01-24 says:
736 * A valid e-mail address is a string that matches the ABNF production
737 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
738 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
741 * This function is an implementation of the specification as requested in
744 * Client-side forms will use the same standard validation rules via JS or
745 * HTML 5 validation; additional restrictions can be enforced server-side
746 * by extensions via the 'isValidEmailAddr' hook.
748 * Note that this validation doesn't 100% match RFC 2822, but is believed
749 * to be liberal enough for wide use. Some invalid addresses will still
750 * pass validation here.
752 * @param string $addr E-mail address
754 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
756 public static function isValidEmailAddr( $addr ) {
757 wfDeprecated( __METHOD__
, '1.18' );
758 return Sanitizer
::validateEmail( $addr );
762 * Given unvalidated user input, return a canonical username, or false if
763 * the username is invalid.
764 * @param string $name User input
765 * @param string|Bool $validate type of validation to use:
766 * - false No validation
767 * - 'valid' Valid for batch processes
768 * - 'usable' Valid for batch processes and login
769 * - 'creatable' Valid for batch processes, login and account creation
771 * @throws MWException
772 * @return bool|string
774 public static function getCanonicalName( $name, $validate = 'valid' ) {
775 # Force usernames to capital
777 $name = $wgContLang->ucfirst( $name );
779 # Reject names containing '#'; these will be cleaned up
780 # with title normalisation, but then it's too late to
782 if( strpos( $name, '#' ) !== false )
785 # Clean up name according to title rules
786 $t = ( $validate === 'valid' ) ?
787 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
788 # Check for invalid titles
789 if( is_null( $t ) ) {
793 # Reject various classes of invalid names
795 $name = $wgAuth->getCanonicalName( $t->getText() );
797 switch ( $validate ) {
801 if ( !User
::isValidUserName( $name ) ) {
806 if ( !User
::isUsableName( $name ) ) {
811 if ( !User
::isCreatableName( $name ) ) {
816 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
822 * Count the number of edits of a user
824 * @param int $uid User ID to check
825 * @return Int the user's edit count
827 * @deprecated since 1.21 in favour of User::getEditCount
829 public static function edits( $uid ) {
830 wfDeprecated( __METHOD__
, '1.21' );
831 $user = self
::newFromId( $uid );
832 return $user->getEditCount();
836 * Return a random password.
838 * @return String new random password
840 public static function randomPassword() {
841 global $wgMinimalPasswordLength;
842 // Decide the final password length based on our min password length, stopping at a minimum of 10 chars
843 $length = max( 10, $wgMinimalPasswordLength );
844 // Multiply by 1.25 to get the number of hex characters we need
845 $length = $length * 1.25;
846 // Generate random hex chars
847 $hex = MWCryptRand
::generateHex( $length );
848 // Convert from base 16 to base 32 to get a proper password like string
849 return wfBaseConvert( $hex, 16, 32 );
853 * Set cached properties to default.
855 * @note This no longer clears uncached lazy-initialised properties;
856 * the constructor does that instead.
858 * @param $name string|bool
860 public function loadDefaults( $name = false ) {
861 wfProfileIn( __METHOD__
);
864 $this->mName
= $name;
865 $this->mRealName
= '';
866 $this->mPassword
= $this->mNewpassword
= '';
867 $this->mNewpassTime
= null;
869 $this->mOptionOverrides
= null;
870 $this->mOptionsLoaded
= false;
872 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
873 if( $loggedOut !== null ) {
874 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
876 $this->mTouched
= '1'; # Allow any pages to be cached
879 $this->mToken
= null; // Don't run cryptographic functions till we need a token
880 $this->mEmailAuthenticated
= null;
881 $this->mEmailToken
= '';
882 $this->mEmailTokenExpires
= null;
883 $this->mRegistration
= wfTimestamp( TS_MW
);
884 $this->mGroups
= array();
886 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
888 wfProfileOut( __METHOD__
);
892 * Return whether an item has been loaded.
894 * @param string $item item to check. Current possibilities:
898 * @param string $all 'all' to check if the whole object has been loaded
899 * or any other string to check if only the item is available (e.g.
903 public function isItemLoaded( $item, $all = 'all' ) {
904 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
905 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
909 * Set that an item has been loaded
911 * @param $item String
913 private function setItemLoaded( $item ) {
914 if ( is_array( $this->mLoadedItems
) ) {
915 $this->mLoadedItems
[$item] = true;
920 * Load user data from the session or login cookie.
921 * @return Bool True if the user is logged in, false otherwise.
923 private function loadFromSession() {
924 global $wgExternalAuthType, $wgAutocreatePolicy;
927 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
928 if ( $result !== null ) {
932 if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
933 $extUser = ExternalUser
::newFromCookie();
935 # TODO: Automatically create the user here (or probably a bit
936 # lower down, in fact)
940 $request = $this->getRequest();
942 $cookieId = $request->getCookie( 'UserID' );
943 $sessId = $request->getSessionData( 'wsUserID' );
945 if ( $cookieId !== null ) {
946 $sId = intval( $cookieId );
947 if( $sessId !== null && $cookieId != $sessId ) {
948 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
949 cookie user ID ($sId) don't match!" );
952 $request->setSessionData( 'wsUserID', $sId );
953 } elseif ( $sessId !== null && $sessId != 0 ) {
959 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
960 $sName = $request->getSessionData( 'wsUserName' );
961 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
962 $sName = $request->getCookie( 'UserName' );
963 $request->setSessionData( 'wsUserName', $sName );
968 $proposedUser = User
::newFromId( $sId );
969 if ( !$proposedUser->isLoggedIn() ) {
974 global $wgBlockDisablesLogin;
975 if( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
976 # User blocked and we've disabled blocked user logins
980 if ( $request->getSessionData( 'wsToken' ) ) {
981 $passwordCorrect = ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
983 } elseif ( $request->getCookie( 'Token' ) ) {
984 # Get the token from DB/cache and clean it up to remove garbage padding.
985 # This deals with historical problems with bugs and the default column value.
986 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
987 $passwordCorrect = ( strlen( $token ) && $token === $request->getCookie( 'Token' ) );
990 # No session or persistent login cookie
994 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
995 $this->loadFromUserObject( $proposedUser );
996 $request->setSessionData( 'wsToken', $this->mToken
);
997 wfDebug( "User: logged in from $from\n" );
1000 # Invalid credentials
1001 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1007 * Load user and user_group data from the database.
1008 * $this->mId must be set, this is how the user is identified.
1010 * @return Bool True if the user exists, false if the user is anonymous
1012 public function loadFromDatabase() {
1014 $this->mId
= intval( $this->mId
);
1016 /** Anonymous user */
1018 $this->loadDefaults();
1022 $dbr = wfGetDB( DB_MASTER
);
1023 $s = $dbr->selectRow( 'user', self
::selectFields(), array( 'user_id' => $this->mId
), __METHOD__
);
1025 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1027 if ( $s !== false ) {
1028 # Initialise user table data
1029 $this->loadFromRow( $s );
1030 $this->mGroups
= null; // deferred
1031 $this->getEditCount(); // revalidation for nulls
1036 $this->loadDefaults();
1042 * Initialize this object from a row from the user table.
1044 * @param array $row Row from the user table to load.
1045 * @param array $data Further user data to load into the object
1047 * user_groups Array with groups out of the user_groups table
1048 * user_properties Array with properties out of the user_properties table
1050 public function loadFromRow( $row, $data = null ) {
1053 $this->mGroups
= null; // deferred
1055 if ( isset( $row->user_name
) ) {
1056 $this->mName
= $row->user_name
;
1057 $this->mFrom
= 'name';
1058 $this->setItemLoaded( 'name' );
1063 if ( isset( $row->user_real_name
) ) {
1064 $this->mRealName
= $row->user_real_name
;
1065 $this->setItemLoaded( 'realname' );
1070 if ( isset( $row->user_id
) ) {
1071 $this->mId
= intval( $row->user_id
);
1072 $this->mFrom
= 'id';
1073 $this->setItemLoaded( 'id' );
1078 if ( isset( $row->user_editcount
) ) {
1079 $this->mEditCount
= $row->user_editcount
;
1084 if ( isset( $row->user_password
) ) {
1085 $this->mPassword
= $row->user_password
;
1086 $this->mNewpassword
= $row->user_newpassword
;
1087 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1088 $this->mEmail
= $row->user_email
;
1089 if ( isset( $row->user_options
) ) {
1090 $this->decodeOptions( $row->user_options
);
1092 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1093 $this->mToken
= $row->user_token
;
1094 if ( $this->mToken
== '' ) {
1095 $this->mToken
= null;
1097 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1098 $this->mEmailToken
= $row->user_email_token
;
1099 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1100 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1106 $this->mLoadedItems
= true;
1109 if ( is_array( $data ) ) {
1110 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1111 $this->mGroups
= $data['user_groups'];
1113 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1114 $this->loadOptions( $data['user_properties'] );
1120 * Load the data for this user object from another user object.
1124 protected function loadFromUserObject( $user ) {
1126 $user->loadGroups();
1127 $user->loadOptions();
1128 foreach ( self
::$mCacheVars as $var ) {
1129 $this->$var = $user->$var;
1134 * Load the groups from the database if they aren't already loaded.
1136 private function loadGroups() {
1137 if ( is_null( $this->mGroups
) ) {
1138 $dbr = wfGetDB( DB_MASTER
);
1139 $res = $dbr->select( 'user_groups',
1140 array( 'ug_group' ),
1141 array( 'ug_user' => $this->mId
),
1143 $this->mGroups
= array();
1144 foreach ( $res as $row ) {
1145 $this->mGroups
[] = $row->ug_group
;
1151 * Add the user to the group if he/she meets given criteria.
1153 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1154 * possible to remove manually via Special:UserRights. In such case it
1155 * will not be re-added automatically. The user will also not lose the
1156 * group if they no longer meet the criteria.
1158 * @param string $event key in $wgAutopromoteOnce (each one has groups/criteria)
1160 * @return array Array of groups the user has been promoted to.
1162 * @see $wgAutopromoteOnce
1164 public function addAutopromoteOnceGroups( $event ) {
1165 global $wgAutopromoteOnceLogInRC;
1167 $toPromote = array();
1168 if ( $this->getId() ) {
1169 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1170 if ( count( $toPromote ) ) {
1171 $oldGroups = $this->getGroups(); // previous groups
1172 foreach ( $toPromote as $group ) {
1173 $this->addGroup( $group );
1175 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1177 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1178 $logEntry->setPerformer( $this );
1179 $logEntry->setTarget( $this->getUserPage() );
1180 $logEntry->setParameters( array(
1181 '4::oldgroups' => $oldGroups,
1182 '5::newgroups' => $newGroups,
1184 $logid = $logEntry->insert();
1185 if ( $wgAutopromoteOnceLogInRC ) {
1186 $logEntry->publish( $logid );
1194 * Clear various cached data stored in this object. The cache of the user table
1195 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1197 * @param bool|String $reloadFrom Reload user and user_groups table data from a
1198 * given source. May be "name", "id", "defaults", "session", or false for
1201 public function clearInstanceCache( $reloadFrom = false ) {
1202 $this->mNewtalk
= -1;
1203 $this->mDatePreference
= null;
1204 $this->mBlockedby
= -1; # Unset
1205 $this->mHash
= false;
1206 $this->mRights
= null;
1207 $this->mEffectiveGroups
= null;
1208 $this->mImplicitGroups
= null;
1209 $this->mGroups
= null;
1210 $this->mOptions
= null;
1211 $this->mOptionsLoaded
= false;
1212 $this->mEditCount
= null;
1214 if ( $reloadFrom ) {
1215 $this->mLoadedItems
= array();
1216 $this->mFrom
= $reloadFrom;
1221 * Combine the language default options with any site-specific options
1222 * and add the default language variants.
1224 * @return Array of String options
1226 public static function getDefaultOptions() {
1227 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1229 static $defOpt = null;
1230 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1231 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1232 // mid-request and see that change reflected in the return value of this function.
1233 // Which is insane and would never happen during normal MW operation
1237 $defOpt = $wgDefaultUserOptions;
1238 # default language setting
1239 $defOpt['variant'] = $wgContLang->getCode();
1240 $defOpt['language'] = $wgContLang->getCode();
1241 foreach( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1242 $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1244 $defOpt['skin'] = $wgDefaultSkin;
1246 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1252 * Get a given default option value.
1254 * @param string $opt Name of option to retrieve
1255 * @return String Default option value
1257 public static function getDefaultOption( $opt ) {
1258 $defOpts = self
::getDefaultOptions();
1259 if( isset( $defOpts[$opt] ) ) {
1260 return $defOpts[$opt];
1267 * Get blocking information
1268 * @param bool $bFromSlave Whether to check the slave database first. To
1269 * improve performance, non-critical checks are done
1270 * against slaves. Check when actually saving should be
1271 * done against master.
1273 private function getBlockedStatus( $bFromSlave = true ) {
1274 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1276 if ( -1 != $this->mBlockedby
) {
1280 wfProfileIn( __METHOD__
);
1281 wfDebug( __METHOD__
.": checking...\n" );
1283 // Initialize data...
1284 // Otherwise something ends up stomping on $this->mBlockedby when
1285 // things get lazy-loaded later, causing false positive block hits
1286 // due to -1 !== 0. Probably session-related... Nothing should be
1287 // overwriting mBlockedby, surely?
1290 # We only need to worry about passing the IP address to the Block generator if the
1291 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1292 # know which IP address they're actually coming from
1293 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1294 $ip = $this->getRequest()->getIP();
1300 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1303 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1304 && !in_array( $ip, $wgProxyWhitelist ) )
1307 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1309 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1310 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1311 $block->setTarget( $ip );
1312 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1314 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1315 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1316 $block->setTarget( $ip );
1320 # (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1321 if ( !$block instanceof Block
1322 && $wgApplyIpBlocksToXff
1324 && !$this->isAllowed( 'proxyunbannable' )
1325 && !in_array( $ip, $wgProxyWhitelist )
1327 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1328 $xff = array_map( 'trim', explode( ',', $xff ) );
1329 $xff = array_diff( $xff, array( $ip ) );
1330 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1331 $block = Block
::chooseBlock( $xffblocks, $xff );
1332 if ( $block instanceof Block
) {
1333 # Mangle the reason to alert the user that the block
1334 # originated from matching the X-Forwarded-For header.
1335 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1339 if ( $block instanceof Block
) {
1340 wfDebug( __METHOD__
. ": Found block.\n" );
1341 $this->mBlock
= $block;
1342 $this->mBlockedby
= $block->getByName();
1343 $this->mBlockreason
= $block->mReason
;
1344 $this->mHideName
= $block->mHideName
;
1345 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1347 $this->mBlockedby
= '';
1348 $this->mHideName
= 0;
1349 $this->mAllowUsertalk
= false;
1353 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1355 wfProfileOut( __METHOD__
);
1359 * Whether the given IP is in a DNS blacklist.
1361 * @param string $ip IP to check
1362 * @param bool $checkWhitelist whether to check the whitelist first
1363 * @return Bool True if blacklisted.
1365 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1366 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1367 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1369 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
1372 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
1375 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1376 return $this->inDnsBlacklist( $ip, $urls );
1380 * Whether the given IP is in a given DNS blacklist.
1382 * @param string $ip IP to check
1383 * @param string|array $bases of Strings: URL of the DNS blacklist
1384 * @return Bool True if blacklisted.
1386 public function inDnsBlacklist( $ip, $bases ) {
1387 wfProfileIn( __METHOD__
);
1390 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1391 if( IP
::isIPv4( $ip ) ) {
1392 # Reverse IP, bug 21255
1393 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1395 foreach( (array)$bases as $base ) {
1397 # If we have an access key, use that too (ProjectHoneypot, etc.)
1398 if( is_array( $base ) ) {
1399 if( count( $base ) >= 2 ) {
1400 # Access key is 1, base URL is 0
1401 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1403 $host = "$ipReversed.{$base[0]}";
1406 $host = "$ipReversed.$base";
1410 $ipList = gethostbynamel( $host );
1413 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1417 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base.\n" );
1422 wfProfileOut( __METHOD__
);
1427 * Check if an IP address is in the local proxy list
1433 public static function isLocallyBlockedProxy( $ip ) {
1434 global $wgProxyList;
1436 if ( !$wgProxyList ) {
1439 wfProfileIn( __METHOD__
);
1441 if ( !is_array( $wgProxyList ) ) {
1442 # Load from the specified file
1443 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1446 if ( !is_array( $wgProxyList ) ) {
1448 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1450 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1451 # Old-style flipped proxy list
1456 wfProfileOut( __METHOD__
);
1461 * Is this user subject to rate limiting?
1463 * @return Bool True if rate limited
1465 public function isPingLimitable() {
1466 global $wgRateLimitsExcludedIPs;
1467 if( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1468 // No other good way currently to disable rate limits
1469 // for specific IPs. :P
1470 // But this is a crappy hack and should die.
1473 return !$this->isAllowed( 'noratelimit' );
1477 * Primitive rate limits: enforce maximum actions per time period
1478 * to put a brake on flooding.
1480 * @note When using a shared cache like memcached, IP-address
1481 * last-hit counters will be shared across wikis.
1483 * @param string $action Action to enforce; 'edit' if unspecified
1484 * @return Bool True if a rate limiter was tripped
1486 public function pingLimiter( $action = 'edit' ) {
1487 # Call the 'PingLimiter' hook
1489 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result ) ) ) {
1493 global $wgRateLimits;
1494 if( !isset( $wgRateLimits[$action] ) ) {
1498 # Some groups shouldn't trigger the ping limiter, ever
1499 if( !$this->isPingLimitable() )
1502 global $wgMemc, $wgRateLimitLog;
1503 wfProfileIn( __METHOD__
);
1505 $limits = $wgRateLimits[$action];
1507 $id = $this->getId();
1508 $ip = $this->getRequest()->getIP();
1511 if( isset( $limits['anon'] ) && $id == 0 ) {
1512 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1515 if( isset( $limits['user'] ) && $id != 0 ) {
1516 $userLimit = $limits['user'];
1518 if( $this->isNewbie() ) {
1519 if( isset( $limits['newbie'] ) && $id != 0 ) {
1520 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1522 if( isset( $limits['ip'] ) ) {
1523 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1526 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1527 $subnet = $matches[1];
1528 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1531 // Check for group-specific permissions
1532 // If more than one group applies, use the group with the highest limit
1533 foreach ( $this->getGroups() as $group ) {
1534 if ( isset( $limits[$group] ) ) {
1535 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1536 $userLimit = $limits[$group];
1540 // Set the user limit key
1541 if ( $userLimit !== false ) {
1542 wfDebug( __METHOD__
. ": effective user limit: $userLimit\n" );
1543 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1547 foreach( $keys as $key => $limit ) {
1548 list( $max, $period ) = $limit;
1549 $summary = "(limit $max in {$period}s)";
1550 $count = $wgMemc->get( $key );
1553 if( $count >= $max ) {
1554 wfDebug( __METHOD__
. ": tripped! $key at $count $summary\n" );
1555 if( $wgRateLimitLog ) {
1556 wfSuppressWarnings();
1557 file_put_contents( $wgRateLimitLog, wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", FILE_APPEND
);
1558 wfRestoreWarnings();
1562 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1565 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1566 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1568 $wgMemc->incr( $key );
1571 wfProfileOut( __METHOD__
);
1576 * Check if user is blocked
1578 * @param bool $bFromSlave Whether to check the slave database instead of the master
1579 * @return Bool True if blocked, false otherwise
1581 public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1582 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1586 * Get the block affecting the user, or null if the user is not blocked
1588 * @param bool $bFromSlave Whether to check the slave database instead of the master
1589 * @return Block|null
1591 public function getBlock( $bFromSlave = true ) {
1592 $this->getBlockedStatus( $bFromSlave );
1593 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1597 * Check if user is blocked from editing a particular article
1599 * @param $title Title to check
1600 * @param bool $bFromSlave whether to check the slave database instead of the master
1603 function isBlockedFrom( $title, $bFromSlave = false ) {
1604 global $wgBlockAllowsUTEdit;
1605 wfProfileIn( __METHOD__
);
1607 $blocked = $this->isBlocked( $bFromSlave );
1608 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1609 # If a user's name is suppressed, they cannot make edits anywhere
1610 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1611 $title->getNamespace() == NS_USER_TALK
) {
1613 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1616 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1618 wfProfileOut( __METHOD__
);
1623 * If user is blocked, return the name of the user who placed the block
1624 * @return String name of blocker
1626 public function blockedBy() {
1627 $this->getBlockedStatus();
1628 return $this->mBlockedby
;
1632 * If user is blocked, return the specified reason for the block
1633 * @return String Blocking reason
1635 public function blockedFor() {
1636 $this->getBlockedStatus();
1637 return $this->mBlockreason
;
1641 * If user is blocked, return the ID for the block
1642 * @return Int Block ID
1644 public function getBlockId() {
1645 $this->getBlockedStatus();
1646 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1650 * Check if user is blocked on all wikis.
1651 * Do not use for actual edit permission checks!
1652 * This is intended for quick UI checks.
1654 * @param string $ip IP address, uses current client if none given
1655 * @return Bool True if blocked, false otherwise
1657 public function isBlockedGlobally( $ip = '' ) {
1658 if( $this->mBlockedGlobally
!== null ) {
1659 return $this->mBlockedGlobally
;
1661 // User is already an IP?
1662 if( IP
::isIPAddress( $this->getName() ) ) {
1663 $ip = $this->getName();
1665 $ip = $this->getRequest()->getIP();
1668 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1669 $this->mBlockedGlobally
= (bool)$blocked;
1670 return $this->mBlockedGlobally
;
1674 * Check if user account is locked
1676 * @return Bool True if locked, false otherwise
1678 public function isLocked() {
1679 if( $this->mLocked
!== null ) {
1680 return $this->mLocked
;
1683 $authUser = $wgAuth->getUserInstance( $this );
1684 $this->mLocked
= (bool)$authUser->isLocked();
1685 return $this->mLocked
;
1689 * Check if user account is hidden
1691 * @return Bool True if hidden, false otherwise
1693 public function isHidden() {
1694 if( $this->mHideName
!== null ) {
1695 return $this->mHideName
;
1697 $this->getBlockedStatus();
1698 if( !$this->mHideName
) {
1700 $authUser = $wgAuth->getUserInstance( $this );
1701 $this->mHideName
= (bool)$authUser->isHidden();
1703 return $this->mHideName
;
1707 * Get the user's ID.
1708 * @return Int The user's ID; 0 if the user is anonymous or nonexistent
1710 public function getId() {
1711 if( $this->mId
=== null && $this->mName
!== null
1712 && User
::isIP( $this->mName
) ) {
1713 // Special case, we know the user is anonymous
1715 } elseif( !$this->isItemLoaded( 'id' ) ) {
1716 // Don't load if this was initialized from an ID
1723 * Set the user and reload all fields according to a given ID
1724 * @param int $v User ID to reload
1726 public function setId( $v ) {
1728 $this->clearInstanceCache( 'id' );
1732 * Get the user name, or the IP of an anonymous user
1733 * @return String User's name or IP address
1735 public function getName() {
1736 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1737 # Special case optimisation
1738 return $this->mName
;
1741 if ( $this->mName
=== false ) {
1743 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1745 return $this->mName
;
1750 * Set the user name.
1752 * This does not reload fields from the database according to the given
1753 * name. Rather, it is used to create a temporary "nonexistent user" for
1754 * later addition to the database. It can also be used to set the IP
1755 * address for an anonymous user to something other than the current
1758 * @note User::newFromName() has roughly the same function, when the named user
1760 * @param string $str New user name to set
1762 public function setName( $str ) {
1764 $this->mName
= $str;
1768 * Get the user's name escaped by underscores.
1769 * @return String Username escaped by underscores.
1771 public function getTitleKey() {
1772 return str_replace( ' ', '_', $this->getName() );
1776 * Check if the user has new messages.
1777 * @return Bool True if the user has new messages
1779 public function getNewtalk() {
1782 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1783 if( $this->mNewtalk
=== -1 ) {
1784 $this->mNewtalk
= false; # reset talk page status
1786 # Check memcached separately for anons, who have no
1787 # entire User object stored in there.
1789 global $wgDisableAnonTalk;
1790 if( $wgDisableAnonTalk ) {
1791 // Anon newtalk disabled by configuration.
1792 $this->mNewtalk
= false;
1795 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1796 $newtalk = $wgMemc->get( $key );
1797 if( strval( $newtalk ) !== '' ) {
1798 $this->mNewtalk
= (bool)$newtalk;
1800 // Since we are caching this, make sure it is up to date by getting it
1802 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1803 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1807 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1811 return (bool)$this->mNewtalk
;
1815 * Return the talk page(s) this user has new messages on.
1816 * @return Array of String page URLs
1818 public function getNewMessageLinks() {
1820 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
1822 } elseif( !$this->getNewtalk() ) {
1825 $utp = $this->getTalkPage();
1826 $dbr = wfGetDB( DB_SLAVE
);
1827 // Get the "last viewed rev" timestamp from the oldest message notification
1828 $timestamp = $dbr->selectField( 'user_newtalk',
1829 'MIN(user_last_timestamp)',
1830 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
1832 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
1833 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
1837 * Internal uncached check for new messages
1840 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1841 * @param string|Int $id User's IP address for anonymous users, User ID otherwise
1842 * @param bool $fromMaster true to fetch from the master, false for a slave
1843 * @return Bool True if the user has new messages
1845 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
1846 if ( $fromMaster ) {
1847 $db = wfGetDB( DB_MASTER
);
1849 $db = wfGetDB( DB_SLAVE
);
1851 $ok = $db->selectField( 'user_newtalk', $field,
1852 array( $field => $id ), __METHOD__
);
1853 return $ok !== false;
1857 * Add or update the new messages flag
1858 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1859 * @param string|Int $id User's IP address for anonymous users, User ID otherwise
1860 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null.
1861 * @return Bool True if successful, false otherwise
1863 protected function updateNewtalk( $field, $id, $curRev = null ) {
1864 // Get timestamp of the talk page revision prior to the current one
1865 $prevRev = $curRev ?
$curRev->getPrevious() : false;
1866 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
1867 // Mark the user as having new messages since this revision
1868 $dbw = wfGetDB( DB_MASTER
);
1869 $dbw->insert( 'user_newtalk',
1870 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
1873 if ( $dbw->affectedRows() ) {
1874 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
1877 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
1883 * Clear the new messages flag for the given user
1884 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1885 * @param string|Int $id User's IP address for anonymous users, User ID otherwise
1886 * @return Bool True if successful, false otherwise
1888 protected function deleteNewtalk( $field, $id ) {
1889 $dbw = wfGetDB( DB_MASTER
);
1890 $dbw->delete( 'user_newtalk',
1891 array( $field => $id ),
1893 if ( $dbw->affectedRows() ) {
1894 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
1897 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
1903 * Update the 'You have new messages!' status.
1904 * @param bool $val Whether the user has new messages
1905 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null or !$val.
1907 public function setNewtalk( $val, $curRev = null ) {
1908 if( wfReadOnly() ) {
1913 $this->mNewtalk
= $val;
1915 if( $this->isAnon() ) {
1917 $id = $this->getName();
1920 $id = $this->getId();
1925 $changed = $this->updateNewtalk( $field, $id, $curRev );
1927 $changed = $this->deleteNewtalk( $field, $id );
1930 if( $this->isAnon() ) {
1931 // Anons have a separate memcached space, since
1932 // user records aren't kept for them.
1933 $key = wfMemcKey( 'newtalk', 'ip', $id );
1934 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1937 $this->invalidateCache();
1942 * Generate a current or new-future timestamp to be stored in the
1943 * user_touched field when we update things.
1944 * @return String Timestamp in TS_MW format
1946 private static function newTouchedTimestamp() {
1947 global $wgClockSkewFudge;
1948 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1952 * Clear user data from memcached.
1953 * Use after applying fun updates to the database; caller's
1954 * responsibility to update user_touched if appropriate.
1956 * Called implicitly from invalidateCache() and saveSettings().
1958 private function clearSharedCache() {
1962 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1967 * Immediately touch the user data cache for this account.
1968 * Updates user_touched field, and removes account data from memcached
1969 * for reload on the next hit.
1971 public function invalidateCache() {
1972 if ( wfReadOnly() ) {
1977 $this->mTouched
= self
::newTouchedTimestamp();
1979 $dbw = wfGetDB( DB_MASTER
);
1980 $userid = $this->mId
;
1981 $touched = $this->mTouched
;
1982 $dbw->onTransactionIdle( function() use ( $dbw, $userid, $touched ) {
1983 // Prevent contention slams by checking user_touched first
1984 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
1985 $needsPurge = $dbw->selectField( 'user', '1',
1986 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
1987 if ( $needsPurge ) {
1988 $dbw->update( 'user',
1989 array( 'user_touched' => $dbw->timestamp( $touched ) ),
1990 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
1995 $this->clearSharedCache();
2000 * Validate the cache for this account.
2001 * @param string $timestamp A timestamp in TS_MW format
2005 public function validateCache( $timestamp ) {
2007 return ( $timestamp >= $this->mTouched
);
2011 * Get the user touched timestamp
2012 * @return String timestamp
2014 public function getTouched() {
2016 return $this->mTouched
;
2020 * Set the password and reset the random token.
2021 * Calls through to authentication plugin if necessary;
2022 * will have no effect if the auth plugin refuses to
2023 * pass the change through or if the legal password
2026 * As a special case, setting the password to null
2027 * wipes it, so the account cannot be logged in until
2028 * a new password is set, for instance via e-mail.
2030 * @param string $str New password to set
2031 * @throws PasswordError on failure
2035 public function setPassword( $str ) {
2038 if( $str !== null ) {
2039 if( !$wgAuth->allowPasswordChange() ) {
2040 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2043 if( !$this->isValidPassword( $str ) ) {
2044 global $wgMinimalPasswordLength;
2045 $valid = $this->getPasswordValidity( $str );
2046 if ( is_array( $valid ) ) {
2047 $message = array_shift( $valid );
2051 $params = array( $wgMinimalPasswordLength );
2053 throw new PasswordError( wfMessage( $message, $params )->text() );
2057 if( !$wgAuth->setPassword( $this, $str ) ) {
2058 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2061 $this->setInternalPassword( $str );
2067 * Set the password and reset the random token unconditionally.
2069 * @param string|null $str New password to set or null to set an invalid
2070 * password hash meaning that the user will not be able to log in
2071 * through the web interface.
2073 public function setInternalPassword( $str ) {
2077 if( $str === null ) {
2078 // Save an invalid hash...
2079 $this->mPassword
= '';
2081 $this->mPassword
= self
::crypt( $str );
2083 $this->mNewpassword
= '';
2084 $this->mNewpassTime
= null;
2088 * Get the user's current token.
2089 * @param bool $forceCreation Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility)
2090 * @return String Token
2092 public function getToken( $forceCreation = true ) {
2094 if ( !$this->mToken
&& $forceCreation ) {
2097 return $this->mToken
;
2101 * Set the random token (used for persistent authentication)
2102 * Called from loadDefaults() among other places.
2104 * @param string|bool $token If specified, set the token to this value
2106 public function setToken( $token = false ) {
2109 $this->mToken
= MWCryptRand
::generateHex( USER_TOKEN_LENGTH
);
2111 $this->mToken
= $token;
2116 * Set the password for a password reminder or new account email
2118 * @param string $str New password to set
2119 * @param bool $throttle If true, reset the throttle timestamp to the present
2121 public function setNewpassword( $str, $throttle = true ) {
2123 $this->mNewpassword
= self
::crypt( $str );
2125 $this->mNewpassTime
= wfTimestampNow();
2130 * Has password reminder email been sent within the last
2131 * $wgPasswordReminderResendTime hours?
2134 public function isPasswordReminderThrottled() {
2135 global $wgPasswordReminderResendTime;
2137 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2140 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2141 return time() < $expiry;
2145 * Get the user's e-mail address
2146 * @return String User's email address
2148 public function getEmail() {
2150 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
2151 return $this->mEmail
;
2155 * Get the timestamp of the user's e-mail authentication
2156 * @return String TS_MW timestamp
2158 public function getEmailAuthenticationTimestamp() {
2160 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2161 return $this->mEmailAuthenticated
;
2165 * Set the user's e-mail address
2166 * @param string $str New e-mail address
2168 public function setEmail( $str ) {
2170 if( $str == $this->mEmail
) {
2173 $this->mEmail
= $str;
2174 $this->invalidateEmail();
2175 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
2179 * Set the user's e-mail address and a confirmation mail if needed.
2182 * @param string $str New e-mail address
2185 public function setEmailWithConfirmation( $str ) {
2186 global $wgEnableEmail, $wgEmailAuthentication;
2188 if ( !$wgEnableEmail ) {
2189 return Status
::newFatal( 'emaildisabled' );
2192 $oldaddr = $this->getEmail();
2193 if ( $str === $oldaddr ) {
2194 return Status
::newGood( true );
2197 $this->setEmail( $str );
2199 if ( $str !== '' && $wgEmailAuthentication ) {
2200 # Send a confirmation request to the new address if needed
2201 $type = $oldaddr != '' ?
'changed' : 'set';
2202 $result = $this->sendConfirmationMail( $type );
2203 if ( $result->isGood() ) {
2204 # Say the the caller that a confirmation mail has been sent
2205 $result->value
= 'eauth';
2208 $result = Status
::newGood( true );
2215 * Get the user's real name
2216 * @return String User's real name
2218 public function getRealName() {
2219 if ( !$this->isItemLoaded( 'realname' ) ) {
2223 return $this->mRealName
;
2227 * Set the user's real name
2228 * @param string $str New real name
2230 public function setRealName( $str ) {
2232 $this->mRealName
= $str;
2236 * Get the user's current setting for a given option.
2238 * @param string $oname The option to check
2239 * @param string $defaultOverride A default value returned if the option does not exist
2240 * @param bool $ignoreHidden = whether to ignore the effects of $wgHiddenPrefs
2241 * @return String User's current value for the option
2242 * @see getBoolOption()
2243 * @see getIntOption()
2245 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2246 global $wgHiddenPrefs;
2247 $this->loadOptions();
2249 # We want 'disabled' preferences to always behave as the default value for
2250 # users, even if they have set the option explicitly in their settings (ie they
2251 # set it, and then it was disabled removing their ability to change it). But
2252 # we don't want to erase the preferences in the database in case the preference
2253 # is re-enabled again. So don't touch $mOptions, just override the returned value
2254 if( in_array( $oname, $wgHiddenPrefs ) && !$ignoreHidden ) {
2255 return self
::getDefaultOption( $oname );
2258 if ( array_key_exists( $oname, $this->mOptions
) ) {
2259 return $this->mOptions
[$oname];
2261 return $defaultOverride;
2266 * Get all user's options
2270 public function getOptions() {
2271 global $wgHiddenPrefs;
2272 $this->loadOptions();
2273 $options = $this->mOptions
;
2275 # We want 'disabled' preferences to always behave as the default value for
2276 # users, even if they have set the option explicitly in their settings (ie they
2277 # set it, and then it was disabled removing their ability to change it). But
2278 # we don't want to erase the preferences in the database in case the preference
2279 # is re-enabled again. So don't touch $mOptions, just override the returned value
2280 foreach( $wgHiddenPrefs as $pref ) {
2281 $default = self
::getDefaultOption( $pref );
2282 if( $default !== null ) {
2283 $options[$pref] = $default;
2291 * Get the user's current setting for a given option, as a boolean value.
2293 * @param string $oname The option to check
2294 * @return Bool User's current value for the option
2297 public function getBoolOption( $oname ) {
2298 return (bool)$this->getOption( $oname );
2302 * Get the user's current setting for a given option, as a boolean value.
2304 * @param string $oname The option to check
2305 * @param int $defaultOverride A default value returned if the option does not exist
2306 * @return Int User's current value for the option
2309 public function getIntOption( $oname, $defaultOverride = 0 ) {
2310 $val = $this->getOption( $oname );
2312 $val = $defaultOverride;
2314 return intval( $val );
2318 * Set the given option for a user.
2320 * @param string $oname The option to set
2321 * @param $val mixed New value to set
2323 public function setOption( $oname, $val ) {
2324 $this->loadOptions();
2326 // Explicitly NULL values should refer to defaults
2327 if( is_null( $val ) ) {
2328 $val = self
::getDefaultOption( $oname );
2331 $this->mOptions
[$oname] = $val;
2335 * Return a list of the types of user options currently returned by
2336 * User::getOptionKinds().
2338 * Currently, the option kinds are:
2339 * - 'registered' - preferences which are registered in core MediaWiki or
2340 * by extensions using the UserGetDefaultOptions hook.
2341 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2342 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2343 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2344 * be used by user scripts.
2345 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2346 * These are usually legacy options, removed in newer versions.
2348 * The API (and possibly others) use this function to determine the possible
2349 * option types for validation purposes, so make sure to update this when a
2350 * new option kind is added.
2352 * @see User::getOptionKinds
2353 * @return array Option kinds
2355 public static function listOptionKinds() {
2358 'registered-multiselect',
2359 'registered-checkmatrix',
2366 * Return an associative array mapping preferences keys to the kind of a preference they're
2367 * used for. Different kinds are handled differently when setting or reading preferences.
2369 * See User::listOptionKinds for the list of valid option types that can be provided.
2371 * @see User::listOptionKinds
2372 * @param $context IContextSource
2373 * @param array $options assoc. array with options keys to check as keys. Defaults to $this->mOptions.
2374 * @return array the key => kind mapping data
2376 public function getOptionKinds( IContextSource
$context, $options = null ) {
2377 $this->loadOptions();
2378 if ( $options === null ) {
2379 $options = $this->mOptions
;
2382 $prefs = Preferences
::getPreferences( $this, $context );
2385 // Multiselect and checkmatrix options are stored in the database with
2386 // one key per option, each having a boolean value. Extract those keys.
2387 $multiselectOptions = array();
2388 foreach ( $prefs as $name => $info ) {
2389 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2390 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2391 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2392 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2394 foreach ( $opts as $value ) {
2395 $multiselectOptions["$prefix$value"] = true;
2398 unset( $prefs[$name] );
2401 $checkmatrixOptions = array();
2402 foreach ( $prefs as $name => $info ) {
2403 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2404 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2405 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2406 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2407 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2409 foreach ( $columns as $column ) {
2410 foreach ( $rows as $row ) {
2411 $checkmatrixOptions["$prefix-$column-$row"] = true;
2415 unset( $prefs[$name] );
2419 // $value is ignored
2420 foreach ( $options as $key => $value ) {
2421 if ( isset( $prefs[$key] ) ) {
2422 $mapping[$key] = 'registered';
2423 } elseif( isset( $multiselectOptions[$key] ) ) {
2424 $mapping[$key] = 'registered-multiselect';
2425 } elseif( isset( $checkmatrixOptions[$key] ) ) {
2426 $mapping[$key] = 'registered-checkmatrix';
2427 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2428 $mapping[$key] = 'userjs';
2430 $mapping[$key] = 'unused';
2438 * Reset certain (or all) options to the site defaults
2440 * The optional parameter determines which kinds of preferences will be reset.
2441 * Supported values are everything that can be reported by getOptionKinds()
2442 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2444 * @param array|string $resetKinds which kinds of preferences to reset. Defaults to
2445 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2446 * for backwards-compatibility.
2447 * @param $context IContextSource|null context source used when $resetKinds
2448 * does not contain 'all', passed to getOptionKinds().
2449 * Defaults to RequestContext::getMain() when null.
2451 public function resetOptions(
2452 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2453 IContextSource
$context = null
2456 $defaultOptions = self
::getDefaultOptions();
2458 if ( !is_array( $resetKinds ) ) {
2459 $resetKinds = array( $resetKinds );
2462 if ( in_array( 'all', $resetKinds ) ) {
2463 $newOptions = $defaultOptions;
2465 if ( $context === null ) {
2466 $context = RequestContext
::getMain();
2469 $optionKinds = $this->getOptionKinds( $context );
2470 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2471 $newOptions = array();
2473 // Use default values for the options that should be deleted, and
2474 // copy old values for the ones that shouldn't.
2475 foreach ( $this->mOptions
as $key => $value ) {
2476 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2477 if ( array_key_exists( $key, $defaultOptions ) ) {
2478 $newOptions[$key] = $defaultOptions[$key];
2481 $newOptions[$key] = $value;
2486 $this->mOptions
= $newOptions;
2487 $this->mOptionsLoaded
= true;
2491 * Get the user's preferred date format.
2492 * @return String User's preferred date format
2494 public function getDatePreference() {
2495 // Important migration for old data rows
2496 if ( is_null( $this->mDatePreference
) ) {
2498 $value = $this->getOption( 'date' );
2499 $map = $wgLang->getDatePreferenceMigrationMap();
2500 if ( isset( $map[$value] ) ) {
2501 $value = $map[$value];
2503 $this->mDatePreference
= $value;
2505 return $this->mDatePreference
;
2509 * Get the user preferred stub threshold
2513 public function getStubThreshold() {
2514 global $wgMaxArticleSize; # Maximum article size, in Kb
2515 $threshold = $this->getIntOption( 'stubthreshold' );
2516 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2517 # If they have set an impossible value, disable the preference
2518 # so we can use the parser cache again.
2525 * Get the permissions this user has.
2526 * @return Array of String permission names
2528 public function getRights() {
2529 if ( is_null( $this->mRights
) ) {
2530 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2531 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2532 // Force reindexation of rights when a hook has unset one of them
2533 $this->mRights
= array_values( array_unique( $this->mRights
) );
2535 return $this->mRights
;
2539 * Get the list of explicit group memberships this user has.
2540 * The implicit * and user groups are not included.
2541 * @return Array of String internal group names
2543 public function getGroups() {
2545 $this->loadGroups();
2546 return $this->mGroups
;
2550 * Get the list of implicit group memberships this user has.
2551 * This includes all explicit groups, plus 'user' if logged in,
2552 * '*' for all accounts, and autopromoted groups
2553 * @param bool $recache Whether to avoid the cache
2554 * @return Array of String internal group names
2556 public function getEffectiveGroups( $recache = false ) {
2557 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2558 wfProfileIn( __METHOD__
);
2559 $this->mEffectiveGroups
= array_unique( array_merge(
2560 $this->getGroups(), // explicit groups
2561 $this->getAutomaticGroups( $recache ) // implicit groups
2563 # Hook for additional groups
2564 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2565 // Force reindexation of groups when a hook has unset one of them
2566 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
2567 wfProfileOut( __METHOD__
);
2569 return $this->mEffectiveGroups
;
2573 * Get the list of implicit group memberships this user has.
2574 * This includes 'user' if logged in, '*' for all accounts,
2575 * and autopromoted groups
2576 * @param bool $recache Whether to avoid the cache
2577 * @return Array of String internal group names
2579 public function getAutomaticGroups( $recache = false ) {
2580 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
2581 wfProfileIn( __METHOD__
);
2582 $this->mImplicitGroups
= array( '*' );
2583 if ( $this->getId() ) {
2584 $this->mImplicitGroups
[] = 'user';
2586 $this->mImplicitGroups
= array_unique( array_merge(
2587 $this->mImplicitGroups
,
2588 Autopromote
::getAutopromoteGroups( $this )
2592 # Assure data consistency with rights/groups,
2593 # as getEffectiveGroups() depends on this function
2594 $this->mEffectiveGroups
= null;
2596 wfProfileOut( __METHOD__
);
2598 return $this->mImplicitGroups
;
2602 * Returns the groups the user has belonged to.
2604 * The user may still belong to the returned groups. Compare with getGroups().
2606 * The function will not return groups the user had belonged to before MW 1.17
2608 * @return array Names of the groups the user has belonged to.
2610 public function getFormerGroups() {
2611 if( is_null( $this->mFormerGroups
) ) {
2612 $dbr = wfGetDB( DB_MASTER
);
2613 $res = $dbr->select( 'user_former_groups',
2614 array( 'ufg_group' ),
2615 array( 'ufg_user' => $this->mId
),
2617 $this->mFormerGroups
= array();
2618 foreach( $res as $row ) {
2619 $this->mFormerGroups
[] = $row->ufg_group
;
2622 return $this->mFormerGroups
;
2626 * Get the user's edit count.
2629 public function getEditCount() {
2630 if ( !$this->getId() ) {
2634 if ( !isset( $this->mEditCount
) ) {
2635 /* Populate the count, if it has not been populated yet */
2636 wfProfileIn( __METHOD__
);
2637 $dbr = wfGetDB( DB_SLAVE
);
2638 // check if the user_editcount field has been initialized
2639 $count = $dbr->selectField(
2640 'user', 'user_editcount',
2641 array( 'user_id' => $this->mId
),
2645 if( $count === null ) {
2646 // it has not been initialized. do so.
2647 $count = $this->initEditCount();
2649 $this->mEditCount
= intval( $count );
2650 wfProfileOut( __METHOD__
);
2652 return $this->mEditCount
;
2656 * Add the user to the given group.
2657 * This takes immediate effect.
2658 * @param string $group Name of the group to add
2660 public function addGroup( $group ) {
2661 if( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2662 $dbw = wfGetDB( DB_MASTER
);
2663 if( $this->getId() ) {
2664 $dbw->insert( 'user_groups',
2666 'ug_user' => $this->getID(),
2667 'ug_group' => $group,
2670 array( 'IGNORE' ) );
2673 $this->loadGroups();
2674 $this->mGroups
[] = $group;
2675 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2677 $this->invalidateCache();
2681 * Remove the user from the given group.
2682 * This takes immediate effect.
2683 * @param string $group Name of the group to remove
2685 public function removeGroup( $group ) {
2687 if( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2688 $dbw = wfGetDB( DB_MASTER
);
2689 $dbw->delete( 'user_groups',
2691 'ug_user' => $this->getID(),
2692 'ug_group' => $group,
2694 // Remember that the user was in this group
2695 $dbw->insert( 'user_former_groups',
2697 'ufg_user' => $this->getID(),
2698 'ufg_group' => $group,
2701 array( 'IGNORE' ) );
2703 $this->loadGroups();
2704 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2705 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2707 $this->invalidateCache();
2711 * Get whether the user is logged in
2714 public function isLoggedIn() {
2715 return $this->getID() != 0;
2719 * Get whether the user is anonymous
2722 public function isAnon() {
2723 return !$this->isLoggedIn();
2727 * Check if user is allowed to access a feature / make an action
2729 * @internal param \String $varargs permissions to test
2730 * @return Boolean: True if user is allowed to perform *any* of the given actions
2734 public function isAllowedAny( /*...*/ ) {
2735 $permissions = func_get_args();
2736 foreach( $permissions as $permission ) {
2737 if( $this->isAllowed( $permission ) ) {
2746 * @internal param $varargs string
2747 * @return bool True if the user is allowed to perform *all* of the given actions
2749 public function isAllowedAll( /*...*/ ) {
2750 $permissions = func_get_args();
2751 foreach( $permissions as $permission ) {
2752 if( !$this->isAllowed( $permission ) ) {
2760 * Internal mechanics of testing a permission
2761 * @param $action String
2764 public function isAllowed( $action = '' ) {
2765 if ( $action === '' ) {
2766 return true; // In the spirit of DWIM
2768 # Patrolling may not be enabled
2769 if( $action === 'patrol' ||
$action === 'autopatrol' ) {
2770 global $wgUseRCPatrol, $wgUseNPPatrol;
2771 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2774 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2775 # by misconfiguration: 0 == 'foo'
2776 return in_array( $action, $this->getRights(), true );
2780 * Check whether to enable recent changes patrol features for this user
2781 * @return Boolean: True or false
2783 public function useRCPatrol() {
2784 global $wgUseRCPatrol;
2785 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
2789 * Check whether to enable new pages patrol features for this user
2790 * @return Bool True or false
2792 public function useNPPatrol() {
2793 global $wgUseRCPatrol, $wgUseNPPatrol;
2794 return( ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) ) );
2798 * Get the WebRequest object to use with this object
2800 * @return WebRequest
2802 public function getRequest() {
2803 if ( $this->mRequest
) {
2804 return $this->mRequest
;
2812 * Get the current skin, loading it if required
2813 * @return Skin The current skin
2814 * @todo FIXME: Need to check the old failback system [AV]
2815 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
2817 public function getSkin() {
2818 wfDeprecated( __METHOD__
, '1.18' );
2819 return RequestContext
::getMain()->getSkin();
2823 * Get a WatchedItem for this user and $title.
2825 * @param $title Title
2826 * @return WatchedItem
2828 public function getWatchedItem( $title ) {
2829 $key = $title->getNamespace() . ':' . $title->getDBkey();
2831 if ( isset( $this->mWatchedItems
[$key] ) ) {
2832 return $this->mWatchedItems
[$key];
2835 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
2836 $this->mWatchedItems
= array();
2839 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title );
2840 return $this->mWatchedItems
[$key];
2844 * Check the watched status of an article.
2845 * @param $title Title of the article to look at
2848 public function isWatched( $title ) {
2849 return $this->getWatchedItem( $title )->isWatched();
2854 * @param $title Title of the article to look at
2856 public function addWatch( $title ) {
2857 $this->getWatchedItem( $title )->addWatch();
2858 $this->invalidateCache();
2862 * Stop watching an article.
2863 * @param $title Title of the article to look at
2865 public function removeWatch( $title ) {
2866 $this->getWatchedItem( $title )->removeWatch();
2867 $this->invalidateCache();
2871 * Clear the user's notification timestamp for the given title.
2872 * If e-notif e-mails are on, they will receive notification mails on
2873 * the next change of the page if it's watched etc.
2874 * @param $title Title of the article to look at
2876 public function clearNotification( &$title ) {
2877 global $wgUseEnotif, $wgShowUpdatedMarker;
2879 # Do nothing if the database is locked to writes
2880 if( wfReadOnly() ) {
2884 if( $title->getNamespace() == NS_USER_TALK
&&
2885 $title->getText() == $this->getName() ) {
2886 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2888 $this->setNewtalk( false );
2891 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2895 if( $this->isAnon() ) {
2896 // Nothing else to do...
2900 // Only update the timestamp if the page is being watched.
2901 // The query to find out if it is watched is cached both in memcached and per-invocation,
2902 // and when it does have to be executed, it can be on a slave
2903 // If this is the user's newtalk page, we always update the timestamp
2905 if ( $title->getNamespace() == NS_USER_TALK
&&
2906 $title->getText() == $this->getName() )
2911 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force );
2915 * Resets all of the given user's page-change notification timestamps.
2916 * If e-notif e-mails are on, they will receive notification mails on
2917 * the next change of any watched page.
2919 public function clearAllNotifications() {
2920 if ( wfReadOnly() ) {
2924 global $wgUseEnotif, $wgShowUpdatedMarker;
2925 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2926 $this->setNewtalk( false );
2929 $id = $this->getId();
2931 $dbw = wfGetDB( DB_MASTER
);
2932 $dbw->update( 'watchlist',
2934 'wl_notificationtimestamp' => null
2935 ), array( /* WHERE */
2939 # We also need to clear here the "you have new message" notification for the own user_talk page
2940 # This is cleared one page view later in Article::viewUpdates();
2945 * Set this user's options from an encoded string
2946 * @param string $str Encoded options to import
2948 * @deprecated in 1.19 due to removal of user_options from the user table
2950 private function decodeOptions( $str ) {
2951 wfDeprecated( __METHOD__
, '1.19' );
2955 $this->mOptionsLoaded
= true;
2956 $this->mOptionOverrides
= array();
2958 // If an option is not set in $str, use the default value
2959 $this->mOptions
= self
::getDefaultOptions();
2961 $a = explode( "\n", $str );
2962 foreach ( $a as $s ) {
2964 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2965 $this->mOptions
[$m[1]] = $m[2];
2966 $this->mOptionOverrides
[$m[1]] = $m[2];
2972 * Set a cookie on the user's client. Wrapper for
2973 * WebResponse::setCookie
2974 * @param string $name Name of the cookie to set
2975 * @param string $value Value to set
2976 * @param int $exp Expiration time, as a UNIX time value;
2977 * if 0 or not specified, use the default $wgCookieExpiration
2978 * @param $secure Bool
2979 * true: Force setting the secure attribute when setting the cookie
2980 * false: Force NOT setting the secure attribute when setting the cookie
2981 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
2983 protected function setCookie( $name, $value, $exp = 0, $secure = null ) {
2984 $this->getRequest()->response()->setcookie( $name, $value, $exp, null, null, $secure );
2988 * Clear a cookie on the user's client
2989 * @param string $name Name of the cookie to clear
2991 protected function clearCookie( $name ) {
2992 $this->setCookie( $name, '', time() - 86400 );
2996 * Set the default cookies for this session on the user's client.
2998 * @param $request WebRequest object to use; $wgRequest will be used if null
3000 * @param bool $secure Whether to force secure/insecure cookies or use default
3002 public function setCookies( $request = null, $secure = null ) {
3003 if ( $request === null ) {
3004 $request = $this->getRequest();
3008 if ( 0 == $this->mId
) {
3011 if ( !$this->mToken
) {
3012 // When token is empty or NULL generate a new one and then save it to the database
3013 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3014 // Simply by setting every cell in the user_token column to NULL and letting them be
3015 // regenerated as users log back into the wiki.
3017 $this->saveSettings();
3020 'wsUserID' => $this->mId
,
3021 'wsToken' => $this->mToken
,
3022 'wsUserName' => $this->getName()
3025 'UserID' => $this->mId
,
3026 'UserName' => $this->getName(),
3028 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
3029 $cookies['Token'] = $this->mToken
;
3031 $cookies['Token'] = false;
3034 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3036 foreach ( $session as $name => $value ) {
3037 $request->setSessionData( $name, $value );
3039 foreach ( $cookies as $name => $value ) {
3040 if ( $value === false ) {
3041 $this->clearCookie( $name );
3043 $this->setCookie( $name, $value, 0, $secure );
3048 * If wpStickHTTPS was selected, also set an insecure cookie that
3049 * will cause the site to redirect the user to HTTPS, if they access
3050 * it over HTTP. Bug 29898.
3052 if ( $request->getCheck( 'wpStickHTTPS' ) ) {
3053 $this->setCookie( 'forceHTTPS', 'true', time() +
2592000, false ); //30 days
3058 * Log this user out.
3060 public function logout() {
3061 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3067 * Clear the user's cookies and session, and reset the instance cache.
3070 public function doLogout() {
3071 $this->clearInstanceCache( 'defaults' );
3073 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3075 $this->clearCookie( 'UserID' );
3076 $this->clearCookie( 'Token' );
3077 $this->clearCookie( 'forceHTTPS' );
3079 # Remember when user logged out, to prevent seeing cached pages
3080 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
3084 * Save this user's settings into the database.
3085 * @todo Only rarely do all these fields need to be set!
3087 public function saveSettings() {
3091 if ( wfReadOnly() ) { return; }
3092 if ( 0 == $this->mId
) { return; }
3094 $this->mTouched
= self
::newTouchedTimestamp();
3095 if ( !$wgAuth->allowSetLocalPassword() ) {
3096 $this->mPassword
= '';
3099 $dbw = wfGetDB( DB_MASTER
);
3100 $dbw->update( 'user',
3102 'user_name' => $this->mName
,
3103 'user_password' => $this->mPassword
,
3104 'user_newpassword' => $this->mNewpassword
,
3105 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3106 'user_real_name' => $this->mRealName
,
3107 'user_email' => $this->mEmail
,
3108 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3109 'user_touched' => $dbw->timestamp( $this->mTouched
),
3110 'user_token' => strval( $this->mToken
),
3111 'user_email_token' => $this->mEmailToken
,
3112 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3113 ), array( /* WHERE */
3114 'user_id' => $this->mId
3118 $this->saveOptions();
3120 wfRunHooks( 'UserSaveSettings', array( $this ) );
3121 $this->clearSharedCache();
3122 $this->getUserPage()->invalidateCache();
3126 * If only this user's username is known, and it exists, return the user ID.
3129 public function idForName() {
3130 $s = trim( $this->getName() );
3131 if ( $s === '' ) return 0;
3133 $dbr = wfGetDB( DB_SLAVE
);
3134 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
3135 if ( $id === false ) {
3142 * Add a user to the database, return the user object
3144 * @param string $name Username to add
3145 * @param array $params of Strings Non-default parameters to save to the database as user_* fields:
3146 * - password The user's password hash. Password logins will be disabled if this is omitted.
3147 * - newpassword Hash for a temporary password that has been mailed to the user
3148 * - email The user's email address
3149 * - email_authenticated The email authentication timestamp
3150 * - real_name The user's real name
3151 * - options An associative array of non-default options
3152 * - token Random authentication token. Do not set.
3153 * - registration Registration timestamp. Do not set.
3155 * @return User object, or null if the username already exists
3157 public static function createNew( $name, $params = array() ) {
3160 $user->setToken(); // init token
3161 if ( isset( $params['options'] ) ) {
3162 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3163 unset( $params['options'] );
3165 $dbw = wfGetDB( DB_MASTER
);
3166 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3169 'user_id' => $seqVal,
3170 'user_name' => $name,
3171 'user_password' => $user->mPassword
,
3172 'user_newpassword' => $user->mNewpassword
,
3173 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3174 'user_email' => $user->mEmail
,
3175 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3176 'user_real_name' => $user->mRealName
,
3177 'user_token' => strval( $user->mToken
),
3178 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3179 'user_editcount' => 0,
3180 'user_touched' => $dbw->timestamp( self
::newTouchedTimestamp() ),
3182 foreach ( $params as $name => $value ) {
3183 $fields["user_$name"] = $value;
3185 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3186 if ( $dbw->affectedRows() ) {
3187 $newUser = User
::newFromId( $dbw->insertId() );
3195 * Add this existing user object to the database. If the user already
3196 * exists, a fatal status object is returned, and the user object is
3197 * initialised with the data from the database.
3199 * Previously, this function generated a DB error due to a key conflict
3200 * if the user already existed. Many extension callers use this function
3201 * in code along the lines of:
3203 * $user = User::newFromName( $name );
3204 * if ( !$user->isLoggedIn() ) {
3205 * $user->addToDatabase();
3207 * // do something with $user...
3209 * However, this was vulnerable to a race condition (bug 16020). By
3210 * initialising the user object if the user exists, we aim to support this
3211 * calling sequence as far as possible.
3213 * Note that if the user exists, this function will acquire a write lock,
3214 * so it is still advisable to make the call conditional on isLoggedIn(),
3215 * and to commit the transaction after calling.
3217 * @throws MWException
3220 public function addToDatabase() {
3222 if ( !$this->mToken
) {
3223 $this->setToken(); // init token
3226 $this->mTouched
= self
::newTouchedTimestamp();
3228 $dbw = wfGetDB( DB_MASTER
);
3229 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3230 $dbw->insert( 'user',
3232 'user_id' => $seqVal,
3233 'user_name' => $this->mName
,
3234 'user_password' => $this->mPassword
,
3235 'user_newpassword' => $this->mNewpassword
,
3236 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3237 'user_email' => $this->mEmail
,
3238 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3239 'user_real_name' => $this->mRealName
,
3240 'user_token' => strval( $this->mToken
),
3241 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3242 'user_editcount' => 0,
3243 'user_touched' => $dbw->timestamp( $this->mTouched
),
3247 if ( !$dbw->affectedRows() ) {
3248 $this->mId
= $dbw->selectField( 'user', 'user_id',
3249 array( 'user_name' => $this->mName
), __METHOD__
);
3252 if ( $this->loadFromDatabase() ) {
3257 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3258 "to insert a user row, but then it doesn't exist when we select it!" );
3260 return Status
::newFatal( 'userexists' );
3262 $this->mId
= $dbw->insertId();
3264 // Clear instance cache other than user table data, which is already accurate
3265 $this->clearInstanceCache();
3267 $this->saveOptions();
3268 return Status
::newGood();
3272 * If this user is logged-in and blocked,
3273 * block any IP address they've successfully logged in from.
3274 * @return bool A block was spread
3276 public function spreadAnyEditBlock() {
3277 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3278 return $this->spreadBlock();
3284 * If this (non-anonymous) user is blocked,
3285 * block the IP address they've successfully logged in from.
3286 * @return bool A block was spread
3288 protected function spreadBlock() {
3289 wfDebug( __METHOD__
. "()\n" );
3291 if ( $this->mId
== 0 ) {
3295 $userblock = Block
::newFromTarget( $this->getName() );
3296 if ( !$userblock ) {
3300 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3304 * Generate a string which will be different for any combination of
3305 * user options which would produce different parser output.
3306 * This will be used as part of the hash key for the parser cache,
3307 * so users with the same options can share the same cached data
3310 * Extensions which require it should install 'PageRenderingHash' hook,
3311 * which will give them a chance to modify this key based on their own
3314 * @deprecated since 1.17 use the ParserOptions object to get the relevant options
3315 * @return String Page rendering hash
3317 public function getPageRenderingHash() {
3318 wfDeprecated( __METHOD__
, '1.17' );
3320 global $wgRenderHashAppend, $wgLang, $wgContLang;
3321 if( $this->mHash
) {
3322 return $this->mHash
;
3325 // stubthreshold is only included below for completeness,
3326 // since it disables the parser cache, its value will always
3327 // be 0 when this function is called by parsercache.
3329 $confstr = $this->getOption( 'math' );
3330 $confstr .= '!' . $this->getStubThreshold();
3331 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ?
'1' : '' );
3332 $confstr .= '!' . $wgLang->getCode();
3333 $confstr .= '!' . $this->getOption( 'thumbsize' );
3334 // add in language specific options, if any
3335 $extra = $wgContLang->getExtraHashOptions();
3338 // Since the skin could be overloading link(), it should be
3339 // included here but in practice, none of our skins do that.
3341 $confstr .= $wgRenderHashAppend;
3343 // Give a chance for extensions to modify the hash, if they have
3344 // extra options or other effects on the parser cache.
3345 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
3347 // Make it a valid memcached key fragment
3348 $confstr = str_replace( ' ', '_', $confstr );
3349 $this->mHash
= $confstr;
3354 * Get whether the user is explicitly blocked from account creation.
3355 * @return Bool|Block
3357 public function isBlockedFromCreateAccount() {
3358 $this->getBlockedStatus();
3359 if( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3360 return $this->mBlock
;
3363 # bug 13611: if the IP address the user is trying to create an account from is
3364 # blocked with createaccount disabled, prevent new account creation there even
3365 # when the user is logged in
3366 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3367 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3369 return $this->mBlockedFromCreateAccount
instanceof Block
&& $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3370 ?
$this->mBlockedFromCreateAccount
3375 * Get whether the user is blocked from using Special:Emailuser.
3378 public function isBlockedFromEmailuser() {
3379 $this->getBlockedStatus();
3380 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3384 * Get whether the user is allowed to create an account.
3387 function isAllowedToCreateAccount() {
3388 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3392 * Get this user's personal page title.
3394 * @return Title: User's personal page title
3396 public function getUserPage() {
3397 return Title
::makeTitle( NS_USER
, $this->getName() );
3401 * Get this user's talk page title.
3403 * @return Title: User's talk page title
3405 public function getTalkPage() {
3406 $title = $this->getUserPage();
3407 return $title->getTalkPage();
3411 * Determine whether the user is a newbie. Newbies are either
3412 * anonymous IPs, or the most recently created accounts.
3415 public function isNewbie() {
3416 return !$this->isAllowed( 'autoconfirmed' );
3420 * Check to see if the given clear-text password is one of the accepted passwords
3421 * @param string $password user password.
3422 * @return Boolean: True if the given password is correct, otherwise False.
3424 public function checkPassword( $password ) {
3425 global $wgAuth, $wgLegacyEncoding;
3428 // Even though we stop people from creating passwords that
3429 // are shorter than this, doesn't mean people wont be able
3430 // to. Certain authentication plugins do NOT want to save
3431 // domain passwords in a mysql database, so we should
3432 // check this (in case $wgAuth->strict() is false).
3433 if( !$this->isValidPassword( $password ) ) {
3437 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
3439 } elseif( $wgAuth->strict() ) {
3440 /* Auth plugin doesn't allow local authentication */
3442 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
3443 /* Auth plugin doesn't allow local authentication for this user name */
3446 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
3448 } elseif ( $wgLegacyEncoding ) {
3449 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3450 # Check for this with iconv
3451 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3452 if ( $cp1252Password != $password &&
3453 self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) )
3462 * Check if the given clear-text password matches the temporary password
3463 * sent by e-mail for password reset operations.
3465 * @param $plaintext string
3467 * @return Boolean: True if matches, false otherwise
3469 public function checkTemporaryPassword( $plaintext ) {
3470 global $wgNewPasswordExpiry;
3473 if( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
3474 if ( is_null( $this->mNewpassTime
) ) {
3477 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3478 return ( time() < $expiry );
3485 * Alias for getEditToken.
3486 * @deprecated since 1.19, use getEditToken instead.
3488 * @param string|array $salt of Strings Optional function-specific data for hashing
3489 * @param $request WebRequest object to use or null to use $wgRequest
3490 * @return String The new edit token
3492 public function editToken( $salt = '', $request = null ) {
3493 wfDeprecated( __METHOD__
, '1.19' );
3494 return $this->getEditToken( $salt, $request );
3498 * Initialize (if necessary) and return a session token value
3499 * which can be used in edit forms to show that the user's
3500 * login credentials aren't being hijacked with a foreign form
3505 * @param string|array $salt of Strings Optional function-specific data for hashing
3506 * @param $request WebRequest object to use or null to use $wgRequest
3507 * @return String The new edit token
3509 public function getEditToken( $salt = '', $request = null ) {
3510 if ( $request == null ) {
3511 $request = $this->getRequest();
3514 if ( $this->isAnon() ) {
3515 return EDIT_TOKEN_SUFFIX
;
3517 $token = $request->getSessionData( 'wsEditToken' );
3518 if ( $token === null ) {
3519 $token = MWCryptRand
::generateHex( 32 );
3520 $request->setSessionData( 'wsEditToken', $token );
3522 if( is_array( $salt ) ) {
3523 $salt = implode( '|', $salt );
3525 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
3530 * Generate a looking random token for various uses.
3532 * @return String The new random token
3533 * @deprecated since 1.20; Use MWCryptRand for secure purposes or wfRandomString for pseudo-randomness
3535 public static function generateToken() {
3536 return MWCryptRand
::generateHex( 32 );
3540 * Check given value against the token value stored in the session.
3541 * A match should confirm that the form was submitted from the
3542 * user's own login session, not a form submission from a third-party
3545 * @param string $val Input value to compare
3546 * @param string $salt Optional function-specific data for hashing
3547 * @param $request WebRequest object to use or null to use $wgRequest
3548 * @return Boolean: Whether the token matches
3550 public function matchEditToken( $val, $salt = '', $request = null ) {
3551 $sessionToken = $this->getEditToken( $salt, $request );
3552 if ( $val != $sessionToken ) {
3553 wfDebug( "User::matchEditToken: broken session data\n" );
3555 return $val == $sessionToken;
3559 * Check given value against the token value stored in the session,
3560 * ignoring the suffix.
3562 * @param string $val Input value to compare
3563 * @param string $salt Optional function-specific data for hashing
3564 * @param $request WebRequest object to use or null to use $wgRequest
3565 * @return Boolean: Whether the token matches
3567 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3568 $sessionToken = $this->getEditToken( $salt, $request );
3569 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3573 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3574 * mail to the user's given address.
3576 * @param string $type message to send, either "created", "changed" or "set"
3577 * @return Status object
3579 public function sendConfirmationMail( $type = 'created' ) {
3581 $expiration = null; // gets passed-by-ref and defined in next line.
3582 $token = $this->confirmationToken( $expiration );
3583 $url = $this->confirmationTokenUrl( $token );
3584 $invalidateURL = $this->invalidationTokenUrl( $token );
3585 $this->saveSettings();
3587 if ( $type == 'created' ||
$type === false ) {
3588 $message = 'confirmemail_body';
3589 } elseif ( $type === true ) {
3590 $message = 'confirmemail_body_changed';
3592 $message = 'confirmemail_body_' . $type;
3595 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3596 wfMessage( $message,
3597 $this->getRequest()->getIP(),
3600 $wgLang->timeanddate( $expiration, false ),
3602 $wgLang->date( $expiration, false ),
3603 $wgLang->time( $expiration, false ) )->text() );
3607 * Send an e-mail to this user's account. Does not check for
3608 * confirmed status or validity.
3610 * @param string $subject Message subject
3611 * @param string $body Message body
3612 * @param string $from Optional From address; if unspecified, default $wgPasswordSender will be used
3613 * @param string $replyto Reply-To address
3616 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3617 if( is_null( $from ) ) {
3618 global $wgPasswordSender, $wgPasswordSenderName;
3619 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
3621 $sender = new MailAddress( $from );
3624 $to = new MailAddress( $this );
3625 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
3629 * Generate, store, and return a new e-mail confirmation code.
3630 * A hash (unsalted, since it's used as a key) is stored.
3632 * @note Call saveSettings() after calling this function to commit
3633 * this change to the database.
3635 * @param &$expiration \mixed Accepts the expiration time
3636 * @return String New token
3638 private function confirmationToken( &$expiration ) {
3639 global $wgUserEmailConfirmationTokenExpiry;
3641 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
3642 $expiration = wfTimestamp( TS_MW
, $expires );
3644 $token = MWCryptRand
::generateHex( 32 );
3645 $hash = md5( $token );
3646 $this->mEmailToken
= $hash;
3647 $this->mEmailTokenExpires
= $expiration;
3652 * Return a URL the user can use to confirm their email address.
3653 * @param string $token Accepts the email confirmation token
3654 * @return String New token URL
3656 private function confirmationTokenUrl( $token ) {
3657 return $this->getTokenUrl( 'ConfirmEmail', $token );
3661 * Return a URL the user can use to invalidate their email address.
3662 * @param string $token Accepts the email confirmation token
3663 * @return String New token URL
3665 private function invalidationTokenUrl( $token ) {
3666 return $this->getTokenUrl( 'InvalidateEmail', $token );
3670 * Internal function to format the e-mail validation/invalidation URLs.
3671 * This uses a quickie hack to use the
3672 * hardcoded English names of the Special: pages, for ASCII safety.
3674 * @note Since these URLs get dropped directly into emails, using the
3675 * short English names avoids insanely long URL-encoded links, which
3676 * also sometimes can get corrupted in some browsers/mailers
3677 * (bug 6957 with Gmail and Internet Explorer).
3679 * @param string $page Special page
3680 * @param string $token Token
3681 * @return String Formatted URL
3683 protected function getTokenUrl( $page, $token ) {
3684 // Hack to bypass localization of 'Special:'
3685 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
3686 return $title->getCanonicalURL();
3690 * Mark the e-mail address confirmed.
3692 * @note Call saveSettings() after calling this function to commit the change.
3696 public function confirmEmail() {
3697 // Check if it's already confirmed, so we don't touch the database
3698 // and fire the ConfirmEmailComplete hook on redundant confirmations.
3699 if ( !$this->isEmailConfirmed() ) {
3700 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3701 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3707 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3708 * address if it was already confirmed.
3710 * @note Call saveSettings() after calling this function to commit the change.
3711 * @return bool Returns true
3713 function invalidateEmail() {
3715 $this->mEmailToken
= null;
3716 $this->mEmailTokenExpires
= null;
3717 $this->setEmailAuthenticationTimestamp( null );
3718 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3723 * Set the e-mail authentication timestamp.
3724 * @param string $timestamp TS_MW timestamp
3726 function setEmailAuthenticationTimestamp( $timestamp ) {
3728 $this->mEmailAuthenticated
= $timestamp;
3729 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
3733 * Is this user allowed to send e-mails within limits of current
3734 * site configuration?
3737 public function canSendEmail() {
3738 global $wgEnableEmail, $wgEnableUserEmail;
3739 if( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
3742 $canSend = $this->isEmailConfirmed();
3743 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3748 * Is this user allowed to receive e-mails within limits of current
3749 * site configuration?
3752 public function canReceiveEmail() {
3753 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3757 * Is this user's e-mail address valid-looking and confirmed within
3758 * limits of the current site configuration?
3760 * @note If $wgEmailAuthentication is on, this may require the user to have
3761 * confirmed their address by returning a code or using a password
3762 * sent to the address from the wiki.
3766 public function isEmailConfirmed() {
3767 global $wgEmailAuthentication;
3770 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3771 if( $this->isAnon() ) {
3774 if( !Sanitizer
::validateEmail( $this->mEmail
) ) {
3777 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
3787 * Check whether there is an outstanding request for e-mail confirmation.
3790 public function isEmailConfirmationPending() {
3791 global $wgEmailAuthentication;
3792 return $wgEmailAuthentication &&
3793 !$this->isEmailConfirmed() &&
3794 $this->mEmailToken
&&
3795 $this->mEmailTokenExpires
> wfTimestamp();
3799 * Get the timestamp of account creation.
3801 * @return String|Bool|Null Timestamp of account creation, false for
3802 * non-existent/anonymous user accounts, or null if existing account
3803 * but information is not in database.
3805 public function getRegistration() {
3806 if ( $this->isAnon() ) {
3810 return $this->mRegistration
;
3814 * Get the timestamp of the first edit
3816 * @return String|Bool Timestamp of first edit, or false for
3817 * non-existent/anonymous user accounts.
3819 public function getFirstEditTimestamp() {
3820 if( $this->getId() == 0 ) {
3821 return false; // anons
3823 $dbr = wfGetDB( DB_SLAVE
);
3824 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3825 array( 'rev_user' => $this->getId() ),
3827 array( 'ORDER BY' => 'rev_timestamp ASC' )
3830 return false; // no edits
3832 return wfTimestamp( TS_MW
, $time );
3836 * Get the permissions associated with a given list of groups
3838 * @param array $groups of Strings List of internal group names
3839 * @return Array of Strings List of permission key names for given groups combined
3841 public static function getGroupPermissions( $groups ) {
3842 global $wgGroupPermissions, $wgRevokePermissions;
3844 // grant every granted permission first
3845 foreach( $groups as $group ) {
3846 if( isset( $wgGroupPermissions[$group] ) ) {
3847 $rights = array_merge( $rights,
3848 // array_filter removes empty items
3849 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3852 // now revoke the revoked permissions
3853 foreach( $groups as $group ) {
3854 if( isset( $wgRevokePermissions[$group] ) ) {
3855 $rights = array_diff( $rights,
3856 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3859 return array_unique( $rights );
3863 * Get all the groups who have a given permission
3865 * @param string $role Role to check
3866 * @return Array of Strings List of internal group names with the given permission
3868 public static function getGroupsWithPermission( $role ) {
3869 global $wgGroupPermissions;
3870 $allowedGroups = array();
3871 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
3872 if ( self
::groupHasPermission( $group, $role ) ) {
3873 $allowedGroups[] = $group;
3876 return $allowedGroups;
3880 * Check, if the given group has the given permission
3882 * @param string $group Group to check
3883 * @param string $role Role to check
3886 public static function groupHasPermission( $group, $role ) {
3887 global $wgGroupPermissions, $wgRevokePermissions;
3888 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
3889 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
3893 * Get the localized descriptive name for a group, if it exists
3895 * @param string $group Internal group name
3896 * @return String Localized descriptive group name
3898 public static function getGroupName( $group ) {
3899 $msg = wfMessage( "group-$group" );
3900 return $msg->isBlank() ?
$group : $msg->text();
3904 * Get the localized descriptive name for a member of a group, if it exists
3906 * @param string $group Internal group name
3907 * @param string $username Username for gender (since 1.19)
3908 * @return String Localized name for group member
3910 public static function getGroupMember( $group, $username = '#' ) {
3911 $msg = wfMessage( "group-$group-member", $username );
3912 return $msg->isBlank() ?
$group : $msg->text();
3916 * Return the set of defined explicit groups.
3917 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3918 * are not included, as they are defined automatically, not in the database.
3919 * @return Array of internal group names
3921 public static function getAllGroups() {
3922 global $wgGroupPermissions, $wgRevokePermissions;
3924 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3925 self
::getImplicitGroups()
3930 * Get a list of all available permissions.
3931 * @return Array of permission names
3933 public static function getAllRights() {
3934 if ( self
::$mAllRights === false ) {
3935 global $wgAvailableRights;
3936 if ( count( $wgAvailableRights ) ) {
3937 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3939 self
::$mAllRights = self
::$mCoreRights;
3941 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3943 return self
::$mAllRights;
3947 * Get a list of implicit groups
3948 * @return Array of Strings Array of internal group names
3950 public static function getImplicitGroups() {
3951 global $wgImplicitGroups;
3952 $groups = $wgImplicitGroups;
3953 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3958 * Get the title of a page describing a particular group
3960 * @param string $group Internal group name
3961 * @return Title|Bool Title of the page if it exists, false otherwise
3963 public static function getGroupPage( $group ) {
3964 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
3965 if( $msg->exists() ) {
3966 $title = Title
::newFromText( $msg->text() );
3967 if( is_object( $title ) )
3974 * Create a link to the group in HTML, if available;
3975 * else return the group name.
3977 * @param string $group Internal name of the group
3978 * @param string $text The text of the link
3979 * @return String HTML link to the group
3981 public static function makeGroupLinkHTML( $group, $text = '' ) {
3983 $text = self
::getGroupName( $group );
3985 $title = self
::getGroupPage( $group );
3987 return Linker
::link( $title, htmlspecialchars( $text ) );
3994 * Create a link to the group in Wikitext, if available;
3995 * else return the group name.
3997 * @param string $group Internal name of the group
3998 * @param string $text The text of the link
3999 * @return String Wikilink to the group
4001 public static function makeGroupLinkWiki( $group, $text = '' ) {
4003 $text = self
::getGroupName( $group );
4005 $title = self
::getGroupPage( $group );
4007 $page = $title->getPrefixedText();
4008 return "[[$page|$text]]";
4015 * Returns an array of the groups that a particular group can add/remove.
4017 * @param string $group the group to check for whether it can add/remove
4018 * @return Array array( 'add' => array( addablegroups ),
4019 * 'remove' => array( removablegroups ),
4020 * 'add-self' => array( addablegroups to self),
4021 * 'remove-self' => array( removable groups from self) )
4023 public static function changeableByGroup( $group ) {
4024 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4026 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
4027 if( empty( $wgAddGroups[$group] ) ) {
4028 // Don't add anything to $groups
4029 } elseif( $wgAddGroups[$group] === true ) {
4030 // You get everything
4031 $groups['add'] = self
::getAllGroups();
4032 } elseif( is_array( $wgAddGroups[$group] ) ) {
4033 $groups['add'] = $wgAddGroups[$group];
4036 // Same thing for remove
4037 if( empty( $wgRemoveGroups[$group] ) ) {
4038 } elseif( $wgRemoveGroups[$group] === true ) {
4039 $groups['remove'] = self
::getAllGroups();
4040 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
4041 $groups['remove'] = $wgRemoveGroups[$group];
4044 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4045 if( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4046 foreach( $wgGroupsAddToSelf as $key => $value ) {
4047 if( is_int( $key ) ) {
4048 $wgGroupsAddToSelf['user'][] = $value;
4053 if( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4054 foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
4055 if( is_int( $key ) ) {
4056 $wgGroupsRemoveFromSelf['user'][] = $value;
4061 // Now figure out what groups the user can add to him/herself
4062 if( empty( $wgGroupsAddToSelf[$group] ) ) {
4063 } elseif( $wgGroupsAddToSelf[$group] === true ) {
4064 // No idea WHY this would be used, but it's there
4065 $groups['add-self'] = User
::getAllGroups();
4066 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
4067 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4070 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4071 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
4072 $groups['remove-self'] = User
::getAllGroups();
4073 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4074 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4081 * Returns an array of groups that this user can add and remove
4082 * @return Array array( 'add' => array( addablegroups ),
4083 * 'remove' => array( removablegroups ),
4084 * 'add-self' => array( addablegroups to self),
4085 * 'remove-self' => array( removable groups from self) )
4087 public function changeableGroups() {
4088 if( $this->isAllowed( 'userrights' ) ) {
4089 // This group gives the right to modify everything (reverse-
4090 // compatibility with old "userrights lets you change
4092 // Using array_merge to make the groups reindexed
4093 $all = array_merge( User
::getAllGroups() );
4097 'add-self' => array(),
4098 'remove-self' => array()
4102 // Okay, it's not so simple, we will have to go through the arrays
4105 'remove' => array(),
4106 'add-self' => array(),
4107 'remove-self' => array()
4109 $addergroups = $this->getEffectiveGroups();
4111 foreach( $addergroups as $addergroup ) {
4112 $groups = array_merge_recursive(
4113 $groups, $this->changeableByGroup( $addergroup )
4115 $groups['add'] = array_unique( $groups['add'] );
4116 $groups['remove'] = array_unique( $groups['remove'] );
4117 $groups['add-self'] = array_unique( $groups['add-self'] );
4118 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4124 * Increment the user's edit-count field.
4125 * Will have no effect for anonymous users.
4127 public function incEditCount() {
4128 if( !$this->isAnon() ) {
4129 $dbw = wfGetDB( DB_MASTER
);
4132 array( 'user_editcount=user_editcount+1' ),
4133 array( 'user_id' => $this->getId() ),
4137 // Lazy initialization check...
4138 if( $dbw->affectedRows() == 0 ) {
4139 // Now here's a goddamn hack...
4140 $dbr = wfGetDB( DB_SLAVE
);
4141 if( $dbr !== $dbw ) {
4142 // If we actually have a slave server, the count is
4143 // at least one behind because the current transaction
4144 // has not been committed and replicated.
4145 $this->initEditCount( 1 );
4147 // But if DB_SLAVE is selecting the master, then the
4148 // count we just read includes the revision that was
4149 // just added in the working transaction.
4150 $this->initEditCount();
4154 // edit count in user cache too
4155 $this->invalidateCache();
4159 * Initialize user_editcount from data out of the revision table
4161 * @param $add Integer Edits to add to the count from the revision table
4162 * @return Integer Number of edits
4164 protected function initEditCount( $add = 0 ) {
4165 // Pull from a slave to be less cruel to servers
4166 // Accuracy isn't the point anyway here
4167 $dbr = wfGetDB( DB_SLAVE
);
4168 $count = (int) $dbr->selectField(
4171 array( 'rev_user' => $this->getId() ),
4174 $count = $count +
$add;
4176 $dbw = wfGetDB( DB_MASTER
);
4179 array( 'user_editcount' => $count ),
4180 array( 'user_id' => $this->getId() ),
4188 * Get the description of a given right
4190 * @param string $right Right to query
4191 * @return String Localized description of the right
4193 public static function getRightDescription( $right ) {
4194 $key = "right-$right";
4195 $msg = wfMessage( $key );
4196 return $msg->isBlank() ?
$right : $msg->text();
4200 * Make an old-style password hash
4202 * @param string $password Plain-text password
4203 * @param string $userId User ID
4204 * @return String Password hash
4206 public static function oldCrypt( $password, $userId ) {
4207 global $wgPasswordSalt;
4208 if ( $wgPasswordSalt ) {
4209 return md5( $userId . '-' . md5( $password ) );
4211 return md5( $password );
4216 * Make a new-style password hash
4218 * @param string $password Plain-text password
4219 * @param bool|string $salt Optional salt, may be random or the user ID.
4221 * If unspecified or false, will generate one automatically
4222 * @return String Password hash
4224 public static function crypt( $password, $salt = false ) {
4225 global $wgPasswordSalt;
4228 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4232 if( $wgPasswordSalt ) {
4233 if ( $salt === false ) {
4234 $salt = MWCryptRand
::generateHex( 8 );
4236 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4238 return ':A:' . md5( $password );
4243 * Compare a password hash with a plain-text password. Requires the user
4244 * ID if there's a chance that the hash is an old-style hash.
4246 * @param string $hash Password hash
4247 * @param string $password Plain-text password to compare
4248 * @param string|bool $userId User ID for old-style password salt
4252 public static function comparePasswords( $hash, $password, $userId = false ) {
4253 $type = substr( $hash, 0, 3 );
4256 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4260 if ( $type == ':A:' ) {
4262 return md5( $password ) === substr( $hash, 3 );
4263 } elseif ( $type == ':B:' ) {
4265 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4266 return md5( $salt.'-'.md5( $password ) ) === $realHash;
4269 return self
::oldCrypt( $password, $userId ) === $hash;
4274 * Add a newuser log entry for this user.
4275 * Before 1.19 the return value was always true.
4277 * @param string|bool $action account creation type.
4278 * - String, one of the following values:
4279 * - 'create' for an anonymous user creating an account for himself.
4280 * This will force the action's performer to be the created user itself,
4281 * no matter the value of $wgUser
4282 * - 'create2' for a logged in user creating an account for someone else
4283 * - 'byemail' when the created user will receive its password by e-mail
4284 * - Boolean means whether the account was created by e-mail (deprecated):
4285 * - true will be converted to 'byemail'
4286 * - false will be converted to 'create' if this object is the same as
4287 * $wgUser and to 'create2' otherwise
4289 * @param string $reason user supplied reason
4291 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4293 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4294 global $wgUser, $wgNewUserLog;
4295 if( empty( $wgNewUserLog ) ) {
4296 return true; // disabled
4299 if ( $action === true ) {
4300 $action = 'byemail';
4301 } elseif ( $action === false ) {
4302 if ( $this->getName() == $wgUser->getName() ) {
4305 $action = 'create2';
4309 if ( $action === 'create' ||
$action === 'autocreate' ) {
4312 $performer = $wgUser;
4315 $logEntry = new ManualLogEntry( 'newusers', $action );
4316 $logEntry->setPerformer( $performer );
4317 $logEntry->setTarget( $this->getUserPage() );
4318 $logEntry->setComment( $reason );
4319 $logEntry->setParameters( array(
4320 '4::userid' => $this->getId(),
4322 $logid = $logEntry->insert();
4324 if ( $action !== 'autocreate' ) {
4325 $logEntry->publish( $logid );
4332 * Add an autocreate newuser log entry for this user
4333 * Used by things like CentralAuth and perhaps other authplugins.
4334 * Consider calling addNewUserLogEntry() directly instead.
4338 public function addNewUserLogEntryAutoCreate() {
4339 $this->addNewUserLogEntry( 'autocreate' );
4345 * Load the user options either from cache, the database or an array
4347 * @param array $data Rows for the current user out of the user_properties table
4349 protected function loadOptions( $data = null ) {
4354 if ( $this->mOptionsLoaded
) {
4358 $this->mOptions
= self
::getDefaultOptions();
4360 if ( !$this->getId() ) {
4361 // For unlogged-in users, load language/variant options from request.
4362 // There's no need to do it for logged-in users: they can set preferences,
4363 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4364 // so don't override user's choice (especially when the user chooses site default).
4365 $variant = $wgContLang->getDefaultVariant();
4366 $this->mOptions
['variant'] = $variant;
4367 $this->mOptions
['language'] = $variant;
4368 $this->mOptionsLoaded
= true;
4372 // Maybe load from the object
4373 if ( !is_null( $this->mOptionOverrides
) ) {
4374 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4375 foreach( $this->mOptionOverrides
as $key => $value ) {
4376 $this->mOptions
[$key] = $value;
4379 if( !is_array( $data ) ) {
4380 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4381 // Load from database
4382 $dbr = wfGetDB( DB_SLAVE
);
4384 $res = $dbr->select(
4386 array( 'up_property', 'up_value' ),
4387 array( 'up_user' => $this->getId() ),
4391 $this->mOptionOverrides
= array();
4393 foreach ( $res as $row ) {
4394 $data[$row->up_property
] = $row->up_value
;
4397 foreach ( $data as $property => $value ) {
4398 $this->mOptionOverrides
[$property] = $value;
4399 $this->mOptions
[$property] = $value;
4403 $this->mOptionsLoaded
= true;
4405 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
4411 protected function saveOptions() {
4412 global $wgAllowPrefChange;
4414 $this->loadOptions();
4416 // Not using getOptions(), to keep hidden preferences in database
4417 $saveOptions = $this->mOptions
;
4419 // Allow hooks to abort, for instance to save to a global profile.
4420 // Reset options to default state before saving.
4421 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4425 $extuser = ExternalUser
::newFromUser( $this );
4426 $userId = $this->getId();
4427 $insert_rows = array();
4428 foreach( $saveOptions as $key => $value ) {
4429 # Don't bother storing default values
4430 $defaultOption = self
::getDefaultOption( $key );
4431 if ( ( is_null( $defaultOption ) &&
4432 !( $value === false ||
is_null( $value ) ) ) ||
4433 $value != $defaultOption ) {
4434 $insert_rows[] = array(
4435 'up_user' => $userId,
4436 'up_property' => $key,
4437 'up_value' => $value,
4440 if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
4441 switch ( $wgAllowPrefChange[$key] ) {
4447 $extuser->setPref( $key, $value );
4452 $dbw = wfGetDB( DB_MASTER
);
4453 $dbw->delete( 'user_properties', array( 'up_user' => $userId ), __METHOD__
);
4454 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
);
4458 * Provide an array of HTML5 attributes to put on an input element
4459 * intended for the user to enter a new password. This may include
4460 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4462 * Do *not* use this when asking the user to enter his current password!
4463 * Regardless of configuration, users may have invalid passwords for whatever
4464 * reason (e.g., they were set before requirements were tightened up).
4465 * Only use it when asking for a new password, like on account creation or
4468 * Obviously, you still need to do server-side checking.
4470 * NOTE: A combination of bugs in various browsers means that this function
4471 * actually just returns array() unconditionally at the moment. May as
4472 * well keep it around for when the browser bugs get fixed, though.
4474 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4476 * @return array Array of HTML attributes suitable for feeding to
4477 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4478 * That will potentially output invalid XHTML 1.0 Transitional, and will
4479 * get confused by the boolean attribute syntax used.)
4481 public static function passwordChangeInputAttribs() {
4482 global $wgMinimalPasswordLength;
4484 if ( $wgMinimalPasswordLength == 0 ) {
4488 # Note that the pattern requirement will always be satisfied if the
4489 # input is empty, so we need required in all cases.
4491 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4492 # if e-mail confirmation is being used. Since HTML5 input validation
4493 # is b0rked anyway in some browsers, just return nothing. When it's
4494 # re-enabled, fix this code to not output required for e-mail
4496 #$ret = array( 'required' );
4499 # We can't actually do this right now, because Opera 9.6 will print out
4500 # the entered password visibly in its error message! When other
4501 # browsers add support for this attribute, or Opera fixes its support,
4502 # we can add support with a version check to avoid doing this on Opera
4503 # versions where it will be a problem. Reported to Opera as
4504 # DSK-262266, but they don't have a public bug tracker for us to follow.
4506 if ( $wgMinimalPasswordLength > 1 ) {
4507 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4508 $ret['title'] = wfMessage( 'passwordtooshort' )
4509 ->numParams( $wgMinimalPasswordLength )->text();
4517 * Return the list of user fields that should be selected to create
4518 * a new user object.
4521 public static function selectFields() {
4528 'user_newpass_time',
4532 'user_email_authenticated',
4534 'user_email_token_expires',
4535 'user_registration',