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 ) ) ) {
709 if ( $result === false ) {
710 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
711 return 'passwordtooshort';
712 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
713 return 'password-name-match';
714 } elseif ( isset( $blockedLogins[$this->getName()] ) && $password == $blockedLogins[$this->getName()] ) {
715 return 'password-login-forbidden';
717 //it seems weird returning true here, but this is because of the
718 //initialization of $result to false above. If the hook is never run or it
719 //doesn't modify $result, then we will likely get down into this if with
723 } elseif ( $result === true ) {
726 return $result; //the isValidPassword hook set a string $result and returned true
731 * Does a string look like an e-mail address?
733 * This validates an email address using an HTML5 specification found at:
734 * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
735 * Which as of 2011-01-24 says:
737 * A valid e-mail address is a string that matches the ABNF production
738 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
739 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
742 * This function is an implementation of the specification as requested in
745 * Client-side forms will use the same standard validation rules via JS or
746 * HTML 5 validation; additional restrictions can be enforced server-side
747 * by extensions via the 'isValidEmailAddr' hook.
749 * Note that this validation doesn't 100% match RFC 2822, but is believed
750 * to be liberal enough for wide use. Some invalid addresses will still
751 * pass validation here.
753 * @param string $addr E-mail address
755 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
757 public static function isValidEmailAddr( $addr ) {
758 wfDeprecated( __METHOD__
, '1.18' );
759 return Sanitizer
::validateEmail( $addr );
763 * Given unvalidated user input, return a canonical username, or false if
764 * the username is invalid.
765 * @param string $name User input
766 * @param string|Bool $validate type of validation to use:
767 * - false No validation
768 * - 'valid' Valid for batch processes
769 * - 'usable' Valid for batch processes and login
770 * - 'creatable' Valid for batch processes, login and account creation
772 * @throws MWException
773 * @return bool|string
775 public static function getCanonicalName( $name, $validate = 'valid' ) {
776 # Force usernames to capital
778 $name = $wgContLang->ucfirst( $name );
780 # Reject names containing '#'; these will be cleaned up
781 # with title normalisation, but then it's too late to
783 if ( strpos( $name, '#' ) !== false ) {
787 # Clean up name according to title rules
788 $t = ( $validate === 'valid' ) ?
789 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
790 # Check for invalid titles
791 if ( is_null( $t ) ) {
795 # Reject various classes of invalid names
797 $name = $wgAuth->getCanonicalName( $t->getText() );
799 switch ( $validate ) {
803 if ( !User
::isValidUserName( $name ) ) {
808 if ( !User
::isUsableName( $name ) ) {
813 if ( !User
::isCreatableName( $name ) ) {
818 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
824 * Count the number of edits of a user
826 * @param int $uid User ID to check
827 * @return Int the user's edit count
829 * @deprecated since 1.21 in favour of User::getEditCount
831 public static function edits( $uid ) {
832 wfDeprecated( __METHOD__
, '1.21' );
833 $user = self
::newFromId( $uid );
834 return $user->getEditCount();
838 * Return a random password.
840 * @return String new random password
842 public static function randomPassword() {
843 global $wgMinimalPasswordLength;
844 // Decide the final password length based on our min password length, stopping at a minimum of 10 chars
845 $length = max( 10, $wgMinimalPasswordLength );
846 // Multiply by 1.25 to get the number of hex characters we need
847 $length = $length * 1.25;
848 // Generate random hex chars
849 $hex = MWCryptRand
::generateHex( $length );
850 // Convert from base 16 to base 32 to get a proper password like string
851 return wfBaseConvert( $hex, 16, 32 );
855 * Set cached properties to default.
857 * @note This no longer clears uncached lazy-initialised properties;
858 * the constructor does that instead.
860 * @param $name string|bool
862 public function loadDefaults( $name = false ) {
863 wfProfileIn( __METHOD__
);
866 $this->mName
= $name;
867 $this->mRealName
= '';
868 $this->mPassword
= $this->mNewpassword
= '';
869 $this->mNewpassTime
= null;
871 $this->mOptionOverrides
= null;
872 $this->mOptionsLoaded
= false;
874 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
875 if ( $loggedOut !== null ) {
876 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
878 $this->mTouched
= '1'; # Allow any pages to be cached
881 $this->mToken
= null; // Don't run cryptographic functions till we need a token
882 $this->mEmailAuthenticated
= null;
883 $this->mEmailToken
= '';
884 $this->mEmailTokenExpires
= null;
885 $this->mRegistration
= wfTimestamp( TS_MW
);
886 $this->mGroups
= array();
888 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
890 wfProfileOut( __METHOD__
);
894 * Return whether an item has been loaded.
896 * @param string $item item to check. Current possibilities:
900 * @param string $all 'all' to check if the whole object has been loaded
901 * or any other string to check if only the item is available (e.g.
905 public function isItemLoaded( $item, $all = 'all' ) {
906 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
907 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
911 * Set that an item has been loaded
913 * @param $item String
915 private function setItemLoaded( $item ) {
916 if ( is_array( $this->mLoadedItems
) ) {
917 $this->mLoadedItems
[$item] = true;
922 * Load user data from the session or login cookie.
923 * @return Bool True if the user is logged in, false otherwise.
925 private function loadFromSession() {
927 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
928 if ( $result !== null ) {
932 $request = $this->getRequest();
934 $cookieId = $request->getCookie( 'UserID' );
935 $sessId = $request->getSessionData( 'wsUserID' );
937 if ( $cookieId !== null ) {
938 $sId = intval( $cookieId );
939 if ( $sessId !== null && $cookieId != $sessId ) {
940 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
941 cookie user ID ($sId) don't match!" );
944 $request->setSessionData( 'wsUserID', $sId );
945 } elseif ( $sessId !== null && $sessId != 0 ) {
951 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
952 $sName = $request->getSessionData( 'wsUserName' );
953 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
954 $sName = $request->getCookie( 'UserName' );
955 $request->setSessionData( 'wsUserName', $sName );
960 $proposedUser = User
::newFromId( $sId );
961 if ( !$proposedUser->isLoggedIn() ) {
966 global $wgBlockDisablesLogin;
967 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
968 # User blocked and we've disabled blocked user logins
972 if ( $request->getSessionData( 'wsToken' ) ) {
973 $passwordCorrect = ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
975 } elseif ( $request->getCookie( 'Token' ) ) {
976 # Get the token from DB/cache and clean it up to remove garbage padding.
977 # This deals with historical problems with bugs and the default column value.
978 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
979 $passwordCorrect = ( strlen( $token ) && $token === $request->getCookie( 'Token' ) );
982 # No session or persistent login cookie
986 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
987 $this->loadFromUserObject( $proposedUser );
988 $request->setSessionData( 'wsToken', $this->mToken
);
989 wfDebug( "User: logged in from $from\n" );
992 # Invalid credentials
993 wfDebug( "User: can't log in from $from, invalid credentials\n" );
999 * Load user and user_group data from the database.
1000 * $this->mId must be set, this is how the user is identified.
1002 * @return Bool True if the user exists, false if the user is anonymous
1004 public function loadFromDatabase() {
1006 $this->mId
= intval( $this->mId
);
1008 /** Anonymous user */
1009 if ( !$this->mId
) {
1010 $this->loadDefaults();
1014 $dbr = wfGetDB( DB_MASTER
);
1015 $s = $dbr->selectRow( 'user', self
::selectFields(), array( 'user_id' => $this->mId
), __METHOD__
);
1017 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1019 if ( $s !== false ) {
1020 # Initialise user table data
1021 $this->loadFromRow( $s );
1022 $this->mGroups
= null; // deferred
1023 $this->getEditCount(); // revalidation for nulls
1028 $this->loadDefaults();
1034 * Initialize this object from a row from the user table.
1036 * @param array $row Row from the user table to load.
1037 * @param array $data Further user data to load into the object
1039 * user_groups Array with groups out of the user_groups table
1040 * user_properties Array with properties out of the user_properties table
1042 public function loadFromRow( $row, $data = null ) {
1045 $this->mGroups
= null; // deferred
1047 if ( isset( $row->user_name
) ) {
1048 $this->mName
= $row->user_name
;
1049 $this->mFrom
= 'name';
1050 $this->setItemLoaded( 'name' );
1055 if ( isset( $row->user_real_name
) ) {
1056 $this->mRealName
= $row->user_real_name
;
1057 $this->setItemLoaded( 'realname' );
1062 if ( isset( $row->user_id
) ) {
1063 $this->mId
= intval( $row->user_id
);
1064 $this->mFrom
= 'id';
1065 $this->setItemLoaded( 'id' );
1070 if ( isset( $row->user_editcount
) ) {
1071 $this->mEditCount
= $row->user_editcount
;
1076 if ( isset( $row->user_password
) ) {
1077 $this->mPassword
= $row->user_password
;
1078 $this->mNewpassword
= $row->user_newpassword
;
1079 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1080 $this->mEmail
= $row->user_email
;
1081 if ( isset( $row->user_options
) ) {
1082 $this->decodeOptions( $row->user_options
);
1084 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1085 $this->mToken
= $row->user_token
;
1086 if ( $this->mToken
== '' ) {
1087 $this->mToken
= null;
1089 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1090 $this->mEmailToken
= $row->user_email_token
;
1091 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1092 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1098 $this->mLoadedItems
= true;
1101 if ( is_array( $data ) ) {
1102 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1103 $this->mGroups
= $data['user_groups'];
1105 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1106 $this->loadOptions( $data['user_properties'] );
1112 * Load the data for this user object from another user object.
1116 protected function loadFromUserObject( $user ) {
1118 $user->loadGroups();
1119 $user->loadOptions();
1120 foreach ( self
::$mCacheVars as $var ) {
1121 $this->$var = $user->$var;
1126 * Load the groups from the database if they aren't already loaded.
1128 private function loadGroups() {
1129 if ( is_null( $this->mGroups
) ) {
1130 $dbr = wfGetDB( DB_MASTER
);
1131 $res = $dbr->select( 'user_groups',
1132 array( 'ug_group' ),
1133 array( 'ug_user' => $this->mId
),
1135 $this->mGroups
= array();
1136 foreach ( $res as $row ) {
1137 $this->mGroups
[] = $row->ug_group
;
1143 * Add the user to the group if he/she meets given criteria.
1145 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1146 * possible to remove manually via Special:UserRights. In such case it
1147 * will not be re-added automatically. The user will also not lose the
1148 * group if they no longer meet the criteria.
1150 * @param string $event key in $wgAutopromoteOnce (each one has groups/criteria)
1152 * @return array Array of groups the user has been promoted to.
1154 * @see $wgAutopromoteOnce
1156 public function addAutopromoteOnceGroups( $event ) {
1157 global $wgAutopromoteOnceLogInRC;
1159 $toPromote = array();
1160 if ( $this->getId() ) {
1161 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1162 if ( count( $toPromote ) ) {
1163 $oldGroups = $this->getGroups(); // previous groups
1164 foreach ( $toPromote as $group ) {
1165 $this->addGroup( $group );
1167 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1169 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1170 $logEntry->setPerformer( $this );
1171 $logEntry->setTarget( $this->getUserPage() );
1172 $logEntry->setParameters( array(
1173 '4::oldgroups' => $oldGroups,
1174 '5::newgroups' => $newGroups,
1176 $logid = $logEntry->insert();
1177 if ( $wgAutopromoteOnceLogInRC ) {
1178 $logEntry->publish( $logid );
1186 * Clear various cached data stored in this object. The cache of the user table
1187 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1189 * @param bool|String $reloadFrom Reload user and user_groups table data from a
1190 * given source. May be "name", "id", "defaults", "session", or false for
1193 public function clearInstanceCache( $reloadFrom = false ) {
1194 $this->mNewtalk
= -1;
1195 $this->mDatePreference
= null;
1196 $this->mBlockedby
= -1; # Unset
1197 $this->mHash
= false;
1198 $this->mRights
= null;
1199 $this->mEffectiveGroups
= null;
1200 $this->mImplicitGroups
= null;
1201 $this->mGroups
= null;
1202 $this->mOptions
= null;
1203 $this->mOptionsLoaded
= false;
1204 $this->mEditCount
= null;
1206 if ( $reloadFrom ) {
1207 $this->mLoadedItems
= array();
1208 $this->mFrom
= $reloadFrom;
1213 * Combine the language default options with any site-specific options
1214 * and add the default language variants.
1216 * @return Array of String options
1218 public static function getDefaultOptions() {
1219 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1221 static $defOpt = null;
1222 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1223 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1224 // mid-request and see that change reflected in the return value of this function.
1225 // Which is insane and would never happen during normal MW operation
1229 $defOpt = $wgDefaultUserOptions;
1230 # default language setting
1231 $defOpt['variant'] = $wgContLang->getCode();
1232 $defOpt['language'] = $wgContLang->getCode();
1233 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1234 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1236 $defOpt['skin'] = $wgDefaultSkin;
1238 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1244 * Get a given default option value.
1246 * @param string $opt Name of option to retrieve
1247 * @return String Default option value
1249 public static function getDefaultOption( $opt ) {
1250 $defOpts = self
::getDefaultOptions();
1251 if ( isset( $defOpts[$opt] ) ) {
1252 return $defOpts[$opt];
1259 * Get blocking information
1260 * @param bool $bFromSlave Whether to check the slave database first. To
1261 * improve performance, non-critical checks are done
1262 * against slaves. Check when actually saving should be
1263 * done against master.
1265 private function getBlockedStatus( $bFromSlave = true ) {
1266 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1268 if ( -1 != $this->mBlockedby
) {
1272 wfProfileIn( __METHOD__
);
1273 wfDebug( __METHOD__
. ": checking...\n" );
1275 // Initialize data...
1276 // Otherwise something ends up stomping on $this->mBlockedby when
1277 // things get lazy-loaded later, causing false positive block hits
1278 // due to -1 !== 0. Probably session-related... Nothing should be
1279 // overwriting mBlockedby, surely?
1282 # We only need to worry about passing the IP address to the Block generator if the
1283 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1284 # know which IP address they're actually coming from
1285 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1286 $ip = $this->getRequest()->getIP();
1292 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1295 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1296 && !in_array( $ip, $wgProxyWhitelist ) )
1299 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1301 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1302 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1303 $block->setTarget( $ip );
1304 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1306 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1307 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1308 $block->setTarget( $ip );
1312 # (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1313 if ( !$block instanceof Block
1314 && $wgApplyIpBlocksToXff
1316 && !$this->isAllowed( 'proxyunbannable' )
1317 && !in_array( $ip, $wgProxyWhitelist )
1319 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1320 $xff = array_map( 'trim', explode( ',', $xff ) );
1321 $xff = array_diff( $xff, array( $ip ) );
1322 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1323 $block = Block
::chooseBlock( $xffblocks, $xff );
1324 if ( $block instanceof Block
) {
1325 # Mangle the reason to alert the user that the block
1326 # originated from matching the X-Forwarded-For header.
1327 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1331 if ( $block instanceof Block
) {
1332 wfDebug( __METHOD__
. ": Found block.\n" );
1333 $this->mBlock
= $block;
1334 $this->mBlockedby
= $block->getByName();
1335 $this->mBlockreason
= $block->mReason
;
1336 $this->mHideName
= $block->mHideName
;
1337 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1339 $this->mBlockedby
= '';
1340 $this->mHideName
= 0;
1341 $this->mAllowUsertalk
= false;
1345 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1347 wfProfileOut( __METHOD__
);
1351 * Whether the given IP is in a DNS blacklist.
1353 * @param string $ip IP to check
1354 * @param bool $checkWhitelist whether to check the whitelist first
1355 * @return Bool True if blacklisted.
1357 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1358 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1359 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1361 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs ) {
1365 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1369 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1370 return $this->inDnsBlacklist( $ip, $urls );
1374 * Whether the given IP is in a given DNS blacklist.
1376 * @param string $ip IP to check
1377 * @param string|array $bases of Strings: URL of the DNS blacklist
1378 * @return Bool True if blacklisted.
1380 public function inDnsBlacklist( $ip, $bases ) {
1381 wfProfileIn( __METHOD__
);
1384 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1385 if ( IP
::isIPv4( $ip ) ) {
1386 # Reverse IP, bug 21255
1387 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1389 foreach ( (array)$bases as $base ) {
1391 # If we have an access key, use that too (ProjectHoneypot, etc.)
1392 if ( is_array( $base ) ) {
1393 if ( count( $base ) >= 2 ) {
1394 # Access key is 1, base URL is 0
1395 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1397 $host = "$ipReversed.{$base[0]}";
1400 $host = "$ipReversed.$base";
1404 $ipList = gethostbynamel( $host );
1407 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1411 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base.\n" );
1416 wfProfileOut( __METHOD__
);
1421 * Check if an IP address is in the local proxy list
1427 public static function isLocallyBlockedProxy( $ip ) {
1428 global $wgProxyList;
1430 if ( !$wgProxyList ) {
1433 wfProfileIn( __METHOD__
);
1435 if ( !is_array( $wgProxyList ) ) {
1436 # Load from the specified file
1437 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1440 if ( !is_array( $wgProxyList ) ) {
1442 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1444 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1445 # Old-style flipped proxy list
1450 wfProfileOut( __METHOD__
);
1455 * Is this user subject to rate limiting?
1457 * @return Bool True if rate limited
1459 public function isPingLimitable() {
1460 global $wgRateLimitsExcludedIPs;
1461 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1462 // No other good way currently to disable rate limits
1463 // for specific IPs. :P
1464 // But this is a crappy hack and should die.
1467 return !$this->isAllowed( 'noratelimit' );
1471 * Primitive rate limits: enforce maximum actions per time period
1472 * to put a brake on flooding.
1474 * @note When using a shared cache like memcached, IP-address
1475 * last-hit counters will be shared across wikis.
1477 * @param string $action Action to enforce; 'edit' if unspecified
1478 * @return Bool True if a rate limiter was tripped
1480 public function pingLimiter( $action = 'edit' ) {
1481 # Call the 'PingLimiter' hook
1483 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result ) ) ) {
1487 global $wgRateLimits;
1488 if ( !isset( $wgRateLimits[$action] ) ) {
1492 # Some groups shouldn't trigger the ping limiter, ever
1493 if ( !$this->isPingLimitable() ) {
1497 global $wgMemc, $wgRateLimitLog;
1498 wfProfileIn( __METHOD__
);
1500 $limits = $wgRateLimits[$action];
1502 $id = $this->getId();
1505 if ( isset( $limits['anon'] ) && $id == 0 ) {
1506 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1509 if ( isset( $limits['user'] ) && $id != 0 ) {
1510 $userLimit = $limits['user'];
1512 if ( $this->isNewbie() ) {
1513 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1514 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1516 if ( isset( $limits['ip'] ) ) {
1517 $ip = $this->getRequest()->getIP();
1518 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1520 if ( isset( $limits['subnet'] ) ) {
1521 $ip = $this->getRequest()->getIP();
1524 if ( IP
::isIPv6( $ip ) ) {
1525 $parts = IP
::parseRange( "$ip/64" );
1526 $subnet = $parts[0];
1527 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1529 $subnet = $matches[1];
1531 if ( $subnet !== false ) {
1532 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1536 // Check for group-specific permissions
1537 // If more than one group applies, use the group with the highest limit
1538 foreach ( $this->getGroups() as $group ) {
1539 if ( isset( $limits[$group] ) ) {
1540 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1541 $userLimit = $limits[$group];
1545 // Set the user limit key
1546 if ( $userLimit !== false ) {
1547 list( $max, $period ) = $userLimit;
1548 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1549 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1553 foreach ( $keys as $key => $limit ) {
1554 list( $max, $period ) = $limit;
1555 $summary = "(limit $max in {$period}s)";
1556 $count = $wgMemc->get( $key );
1559 if ( $count >= $max ) {
1560 wfDebug( __METHOD__
. ": tripped! $key at $count $summary\n" );
1561 if ( $wgRateLimitLog ) {
1562 wfSuppressWarnings();
1563 file_put_contents( $wgRateLimitLog, wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", FILE_APPEND
);
1564 wfRestoreWarnings();
1568 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1571 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1572 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1574 $wgMemc->incr( $key );
1577 wfProfileOut( __METHOD__
);
1582 * Check if user is blocked
1584 * @param bool $bFromSlave Whether to check the slave database instead of the master
1585 * @return Bool True if blocked, false otherwise
1587 public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1588 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1592 * Get the block affecting the user, or null if the user is not blocked
1594 * @param bool $bFromSlave Whether to check the slave database instead of the master
1595 * @return Block|null
1597 public function getBlock( $bFromSlave = true ) {
1598 $this->getBlockedStatus( $bFromSlave );
1599 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1603 * Check if user is blocked from editing a particular article
1605 * @param $title Title to check
1606 * @param bool $bFromSlave whether to check the slave database instead of the master
1609 function isBlockedFrom( $title, $bFromSlave = false ) {
1610 global $wgBlockAllowsUTEdit;
1611 wfProfileIn( __METHOD__
);
1613 $blocked = $this->isBlocked( $bFromSlave );
1614 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1615 # If a user's name is suppressed, they cannot make edits anywhere
1616 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1617 $title->getNamespace() == NS_USER_TALK
) {
1619 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1622 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1624 wfProfileOut( __METHOD__
);
1629 * If user is blocked, return the name of the user who placed the block
1630 * @return String name of blocker
1632 public function blockedBy() {
1633 $this->getBlockedStatus();
1634 return $this->mBlockedby
;
1638 * If user is blocked, return the specified reason for the block
1639 * @return String Blocking reason
1641 public function blockedFor() {
1642 $this->getBlockedStatus();
1643 return $this->mBlockreason
;
1647 * If user is blocked, return the ID for the block
1648 * @return Int Block ID
1650 public function getBlockId() {
1651 $this->getBlockedStatus();
1652 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1656 * Check if user is blocked on all wikis.
1657 * Do not use for actual edit permission checks!
1658 * This is intended for quick UI checks.
1660 * @param string $ip IP address, uses current client if none given
1661 * @return Bool True if blocked, false otherwise
1663 public function isBlockedGlobally( $ip = '' ) {
1664 if ( $this->mBlockedGlobally
!== null ) {
1665 return $this->mBlockedGlobally
;
1667 // User is already an IP?
1668 if ( IP
::isIPAddress( $this->getName() ) ) {
1669 $ip = $this->getName();
1671 $ip = $this->getRequest()->getIP();
1674 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1675 $this->mBlockedGlobally
= (bool)$blocked;
1676 return $this->mBlockedGlobally
;
1680 * Check if user account is locked
1682 * @return Bool True if locked, false otherwise
1684 public function isLocked() {
1685 if ( $this->mLocked
!== null ) {
1686 return $this->mLocked
;
1689 $authUser = $wgAuth->getUserInstance( $this );
1690 $this->mLocked
= (bool)$authUser->isLocked();
1691 return $this->mLocked
;
1695 * Check if user account is hidden
1697 * @return Bool True if hidden, false otherwise
1699 public function isHidden() {
1700 if ( $this->mHideName
!== null ) {
1701 return $this->mHideName
;
1703 $this->getBlockedStatus();
1704 if ( !$this->mHideName
) {
1706 $authUser = $wgAuth->getUserInstance( $this );
1707 $this->mHideName
= (bool)$authUser->isHidden();
1709 return $this->mHideName
;
1713 * Get the user's ID.
1714 * @return Int The user's ID; 0 if the user is anonymous or nonexistent
1716 public function getId() {
1717 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1718 // Special case, we know the user is anonymous
1720 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1721 // Don't load if this was initialized from an ID
1728 * Set the user and reload all fields according to a given ID
1729 * @param int $v User ID to reload
1731 public function setId( $v ) {
1733 $this->clearInstanceCache( 'id' );
1737 * Get the user name, or the IP of an anonymous user
1738 * @return String User's name or IP address
1740 public function getName() {
1741 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1742 # Special case optimisation
1743 return $this->mName
;
1746 if ( $this->mName
=== false ) {
1748 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1750 return $this->mName
;
1755 * Set the user name.
1757 * This does not reload fields from the database according to the given
1758 * name. Rather, it is used to create a temporary "nonexistent user" for
1759 * later addition to the database. It can also be used to set the IP
1760 * address for an anonymous user to something other than the current
1763 * @note User::newFromName() has roughly the same function, when the named user
1765 * @param string $str New user name to set
1767 public function setName( $str ) {
1769 $this->mName
= $str;
1773 * Get the user's name escaped by underscores.
1774 * @return String Username escaped by underscores.
1776 public function getTitleKey() {
1777 return str_replace( ' ', '_', $this->getName() );
1781 * Check if the user has new messages.
1782 * @return Bool True if the user has new messages
1784 public function getNewtalk() {
1787 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1788 if ( $this->mNewtalk
=== -1 ) {
1789 $this->mNewtalk
= false; # reset talk page status
1791 # Check memcached separately for anons, who have no
1792 # entire User object stored in there.
1793 if ( !$this->mId
) {
1794 global $wgDisableAnonTalk;
1795 if ( $wgDisableAnonTalk ) {
1796 // Anon newtalk disabled by configuration.
1797 $this->mNewtalk
= false;
1800 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1801 $newtalk = $wgMemc->get( $key );
1802 if ( strval( $newtalk ) !== '' ) {
1803 $this->mNewtalk
= (bool)$newtalk;
1805 // Since we are caching this, make sure it is up to date by getting it
1807 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1808 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1812 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1816 return (bool)$this->mNewtalk
;
1820 * Return the revision and link for the oldest new talk page message for
1822 * Note: This function was designed to accomodate multiple talk pages, but
1823 * currently only returns a single link and revision.
1826 public function getNewMessageLinks() {
1828 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
1830 } elseif ( !$this->getNewtalk() ) {
1833 $utp = $this->getTalkPage();
1834 $dbr = wfGetDB( DB_SLAVE
);
1835 // Get the "last viewed rev" timestamp from the oldest message notification
1836 $timestamp = $dbr->selectField( 'user_newtalk',
1837 'MIN(user_last_timestamp)',
1838 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
1840 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
1841 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
1845 * Get the revision ID for the oldest new talk page message for this user
1846 * @return Integer or null if there are no new messages
1848 public function getNewMessageRevisionId() {
1849 $newMessageRevisionId = null;
1850 $newMessageLinks = $this->getNewMessageLinks();
1851 if ( $newMessageLinks ) {
1852 // Note: getNewMessageLinks() never returns more than a single link
1853 // and it is always for the same wiki, but we double-check here in
1854 // case that changes some time in the future.
1855 if ( count( $newMessageLinks ) === 1
1856 && $newMessageLinks[0]['wiki'] === wfWikiID()
1857 && $newMessageLinks[0]['rev']
1859 $newMessageRevision = $newMessageLinks[0]['rev'];
1860 $newMessageRevisionId = $newMessageRevision->getId();
1863 return $newMessageRevisionId;
1867 * Internal uncached check for new messages
1870 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1871 * @param string|Int $id User's IP address for anonymous users, User ID otherwise
1872 * @param bool $fromMaster true to fetch from the master, false for a slave
1873 * @return Bool True if the user has new messages
1875 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
1876 if ( $fromMaster ) {
1877 $db = wfGetDB( DB_MASTER
);
1879 $db = wfGetDB( DB_SLAVE
);
1881 $ok = $db->selectField( 'user_newtalk', $field,
1882 array( $field => $id ), __METHOD__
);
1883 return $ok !== false;
1887 * Add or update the new messages flag
1888 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1889 * @param string|Int $id User's IP address for anonymous users, User ID otherwise
1890 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null.
1891 * @return Bool True if successful, false otherwise
1893 protected function updateNewtalk( $field, $id, $curRev = null ) {
1894 // Get timestamp of the talk page revision prior to the current one
1895 $prevRev = $curRev ?
$curRev->getPrevious() : false;
1896 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
1897 // Mark the user as having new messages since this revision
1898 $dbw = wfGetDB( DB_MASTER
);
1899 $dbw->insert( 'user_newtalk',
1900 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
1903 if ( $dbw->affectedRows() ) {
1904 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
1907 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
1913 * Clear the new messages flag for the given user
1914 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1915 * @param string|Int $id User's IP address for anonymous users, User ID otherwise
1916 * @return Bool True if successful, false otherwise
1918 protected function deleteNewtalk( $field, $id ) {
1919 $dbw = wfGetDB( DB_MASTER
);
1920 $dbw->delete( 'user_newtalk',
1921 array( $field => $id ),
1923 if ( $dbw->affectedRows() ) {
1924 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
1927 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
1933 * Update the 'You have new messages!' status.
1934 * @param bool $val Whether the user has new messages
1935 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null or !$val.
1937 public function setNewtalk( $val, $curRev = null ) {
1938 if ( wfReadOnly() ) {
1943 $this->mNewtalk
= $val;
1945 if ( $this->isAnon() ) {
1947 $id = $this->getName();
1950 $id = $this->getId();
1955 $changed = $this->updateNewtalk( $field, $id, $curRev );
1957 $changed = $this->deleteNewtalk( $field, $id );
1960 if ( $this->isAnon() ) {
1961 // Anons have a separate memcached space, since
1962 // user records aren't kept for them.
1963 $key = wfMemcKey( 'newtalk', 'ip', $id );
1964 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1967 $this->invalidateCache();
1972 * Generate a current or new-future timestamp to be stored in the
1973 * user_touched field when we update things.
1974 * @return String Timestamp in TS_MW format
1976 private static function newTouchedTimestamp() {
1977 global $wgClockSkewFudge;
1978 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1982 * Clear user data from memcached.
1983 * Use after applying fun updates to the database; caller's
1984 * responsibility to update user_touched if appropriate.
1986 * Called implicitly from invalidateCache() and saveSettings().
1988 private function clearSharedCache() {
1992 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1997 * Immediately touch the user data cache for this account.
1998 * Updates user_touched field, and removes account data from memcached
1999 * for reload on the next hit.
2001 public function invalidateCache() {
2002 if ( wfReadOnly() ) {
2007 $this->mTouched
= self
::newTouchedTimestamp();
2009 $dbw = wfGetDB( DB_MASTER
);
2010 $userid = $this->mId
;
2011 $touched = $this->mTouched
;
2012 $method = __METHOD__
;
2013 $dbw->onTransactionIdle( function() use ( $dbw, $userid, $touched, $method ) {
2014 // Prevent contention slams by checking user_touched first
2015 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2016 $needsPurge = $dbw->selectField( 'user', '1',
2017 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2018 if ( $needsPurge ) {
2019 $dbw->update( 'user',
2020 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2021 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2026 $this->clearSharedCache();
2031 * Validate the cache for this account.
2032 * @param string $timestamp A timestamp in TS_MW format
2036 public function validateCache( $timestamp ) {
2038 return ( $timestamp >= $this->mTouched
);
2042 * Get the user touched timestamp
2043 * @return String timestamp
2045 public function getTouched() {
2047 return $this->mTouched
;
2051 * Set the password and reset the random token.
2052 * Calls through to authentication plugin if necessary;
2053 * will have no effect if the auth plugin refuses to
2054 * pass the change through or if the legal password
2057 * As a special case, setting the password to null
2058 * wipes it, so the account cannot be logged in until
2059 * a new password is set, for instance via e-mail.
2061 * @param string $str New password to set
2062 * @throws PasswordError on failure
2066 public function setPassword( $str ) {
2069 if ( $str !== null ) {
2070 if ( !$wgAuth->allowPasswordChange() ) {
2071 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2074 if ( !$this->isValidPassword( $str ) ) {
2075 global $wgMinimalPasswordLength;
2076 $valid = $this->getPasswordValidity( $str );
2077 if ( is_array( $valid ) ) {
2078 $message = array_shift( $valid );
2082 $params = array( $wgMinimalPasswordLength );
2084 throw new PasswordError( wfMessage( $message, $params )->text() );
2088 if ( !$wgAuth->setPassword( $this, $str ) ) {
2089 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2092 $this->setInternalPassword( $str );
2098 * Set the password and reset the random token unconditionally.
2100 * @param string|null $str New password to set or null to set an invalid
2101 * password hash meaning that the user will not be able to log in
2102 * through the web interface.
2104 public function setInternalPassword( $str ) {
2108 if ( $str === null ) {
2109 // Save an invalid hash...
2110 $this->mPassword
= '';
2112 $this->mPassword
= self
::crypt( $str );
2114 $this->mNewpassword
= '';
2115 $this->mNewpassTime
= null;
2119 * Get the user's current token.
2120 * @param bool $forceCreation Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility)
2121 * @return String Token
2123 public function getToken( $forceCreation = true ) {
2125 if ( !$this->mToken
&& $forceCreation ) {
2128 return $this->mToken
;
2132 * Set the random token (used for persistent authentication)
2133 * Called from loadDefaults() among other places.
2135 * @param string|bool $token If specified, set the token to this value
2137 public function setToken( $token = false ) {
2140 $this->mToken
= MWCryptRand
::generateHex( USER_TOKEN_LENGTH
);
2142 $this->mToken
= $token;
2147 * Set the password for a password reminder or new account email
2149 * @param string $str New password to set
2150 * @param bool $throttle If true, reset the throttle timestamp to the present
2152 public function setNewpassword( $str, $throttle = true ) {
2154 $this->mNewpassword
= self
::crypt( $str );
2156 $this->mNewpassTime
= wfTimestampNow();
2161 * Has password reminder email been sent within the last
2162 * $wgPasswordReminderResendTime hours?
2165 public function isPasswordReminderThrottled() {
2166 global $wgPasswordReminderResendTime;
2168 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2171 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2172 return time() < $expiry;
2176 * Get the user's e-mail address
2177 * @return String User's email address
2179 public function getEmail() {
2181 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
2182 return $this->mEmail
;
2186 * Get the timestamp of the user's e-mail authentication
2187 * @return String TS_MW timestamp
2189 public function getEmailAuthenticationTimestamp() {
2191 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2192 return $this->mEmailAuthenticated
;
2196 * Set the user's e-mail address
2197 * @param string $str New e-mail address
2199 public function setEmail( $str ) {
2201 if ( $str == $this->mEmail
) {
2204 $this->mEmail
= $str;
2205 $this->invalidateEmail();
2206 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
2210 * Set the user's e-mail address and a confirmation mail if needed.
2213 * @param string $str New e-mail address
2216 public function setEmailWithConfirmation( $str ) {
2217 global $wgEnableEmail, $wgEmailAuthentication;
2219 if ( !$wgEnableEmail ) {
2220 return Status
::newFatal( 'emaildisabled' );
2223 $oldaddr = $this->getEmail();
2224 if ( $str === $oldaddr ) {
2225 return Status
::newGood( true );
2228 $this->setEmail( $str );
2230 if ( $str !== '' && $wgEmailAuthentication ) {
2231 # Send a confirmation request to the new address if needed
2232 $type = $oldaddr != '' ?
'changed' : 'set';
2233 $result = $this->sendConfirmationMail( $type );
2234 if ( $result->isGood() ) {
2235 # Say the the caller that a confirmation mail has been sent
2236 $result->value
= 'eauth';
2239 $result = Status
::newGood( true );
2246 * Get the user's real name
2247 * @return String User's real name
2249 public function getRealName() {
2250 if ( !$this->isItemLoaded( 'realname' ) ) {
2254 return $this->mRealName
;
2258 * Set the user's real name
2259 * @param string $str New real name
2261 public function setRealName( $str ) {
2263 $this->mRealName
= $str;
2267 * Get the user's current setting for a given option.
2269 * @param string $oname The option to check
2270 * @param string $defaultOverride A default value returned if the option does not exist
2271 * @param bool $ignoreHidden = whether to ignore the effects of $wgHiddenPrefs
2272 * @return String User's current value for the option
2273 * @see getBoolOption()
2274 * @see getIntOption()
2276 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2277 global $wgHiddenPrefs;
2278 $this->loadOptions();
2280 # We want 'disabled' preferences to always behave as the default value for
2281 # users, even if they have set the option explicitly in their settings (ie they
2282 # set it, and then it was disabled removing their ability to change it). But
2283 # we don't want to erase the preferences in the database in case the preference
2284 # is re-enabled again. So don't touch $mOptions, just override the returned value
2285 if ( in_array( $oname, $wgHiddenPrefs ) && !$ignoreHidden ) {
2286 return self
::getDefaultOption( $oname );
2289 if ( array_key_exists( $oname, $this->mOptions
) ) {
2290 return $this->mOptions
[$oname];
2292 return $defaultOverride;
2297 * Get all user's options
2301 public function getOptions() {
2302 global $wgHiddenPrefs;
2303 $this->loadOptions();
2304 $options = $this->mOptions
;
2306 # We want 'disabled' preferences to always behave as the default value for
2307 # users, even if they have set the option explicitly in their settings (ie they
2308 # set it, and then it was disabled removing their ability to change it). But
2309 # we don't want to erase the preferences in the database in case the preference
2310 # is re-enabled again. So don't touch $mOptions, just override the returned value
2311 foreach ( $wgHiddenPrefs as $pref ) {
2312 $default = self
::getDefaultOption( $pref );
2313 if ( $default !== null ) {
2314 $options[$pref] = $default;
2322 * Get the user's current setting for a given option, as a boolean value.
2324 * @param string $oname The option to check
2325 * @return Bool User's current value for the option
2328 public function getBoolOption( $oname ) {
2329 return (bool)$this->getOption( $oname );
2333 * Get the user's current setting for a given option, as a boolean value.
2335 * @param string $oname The option to check
2336 * @param int $defaultOverride A default value returned if the option does not exist
2337 * @return Int User's current value for the option
2340 public function getIntOption( $oname, $defaultOverride = 0 ) {
2341 $val = $this->getOption( $oname );
2343 $val = $defaultOverride;
2345 return intval( $val );
2349 * Set the given option for a user.
2351 * @param string $oname The option to set
2352 * @param $val mixed New value to set
2354 public function setOption( $oname, $val ) {
2355 $this->loadOptions();
2357 // Explicitly NULL values should refer to defaults
2358 if ( is_null( $val ) ) {
2359 $val = self
::getDefaultOption( $oname );
2362 $this->mOptions
[$oname] = $val;
2366 * Return a list of the types of user options currently returned by
2367 * User::getOptionKinds().
2369 * Currently, the option kinds are:
2370 * - 'registered' - preferences which are registered in core MediaWiki or
2371 * by extensions using the UserGetDefaultOptions hook.
2372 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2373 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2374 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2375 * be used by user scripts.
2376 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2377 * These are usually legacy options, removed in newer versions.
2379 * The API (and possibly others) use this function to determine the possible
2380 * option types for validation purposes, so make sure to update this when a
2381 * new option kind is added.
2383 * @see User::getOptionKinds
2384 * @return array Option kinds
2386 public static function listOptionKinds() {
2389 'registered-multiselect',
2390 'registered-checkmatrix',
2397 * Return an associative array mapping preferences keys to the kind of a preference they're
2398 * used for. Different kinds are handled differently when setting or reading preferences.
2400 * See User::listOptionKinds for the list of valid option types that can be provided.
2402 * @see User::listOptionKinds
2403 * @param $context IContextSource
2404 * @param array $options assoc. array with options keys to check as keys. Defaults to $this->mOptions.
2405 * @return array the key => kind mapping data
2407 public function getOptionKinds( IContextSource
$context, $options = null ) {
2408 $this->loadOptions();
2409 if ( $options === null ) {
2410 $options = $this->mOptions
;
2413 $prefs = Preferences
::getPreferences( $this, $context );
2416 // Multiselect and checkmatrix options are stored in the database with
2417 // one key per option, each having a boolean value. Extract those keys.
2418 $multiselectOptions = array();
2419 foreach ( $prefs as $name => $info ) {
2420 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2421 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2422 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2423 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2425 foreach ( $opts as $value ) {
2426 $multiselectOptions["$prefix$value"] = true;
2429 unset( $prefs[$name] );
2432 $checkmatrixOptions = array();
2433 foreach ( $prefs as $name => $info ) {
2434 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2435 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2436 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2437 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2438 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2440 foreach ( $columns as $column ) {
2441 foreach ( $rows as $row ) {
2442 $checkmatrixOptions["$prefix-$column-$row"] = true;
2446 unset( $prefs[$name] );
2450 // $value is ignored
2451 foreach ( $options as $key => $value ) {
2452 if ( isset( $prefs[$key] ) ) {
2453 $mapping[$key] = 'registered';
2454 } elseif ( isset( $multiselectOptions[$key] ) ) {
2455 $mapping[$key] = 'registered-multiselect';
2456 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2457 $mapping[$key] = 'registered-checkmatrix';
2458 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2459 $mapping[$key] = 'userjs';
2461 $mapping[$key] = 'unused';
2469 * Reset certain (or all) options to the site defaults
2471 * The optional parameter determines which kinds of preferences will be reset.
2472 * Supported values are everything that can be reported by getOptionKinds()
2473 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2475 * @param array|string $resetKinds which kinds of preferences to reset. Defaults to
2476 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2477 * for backwards-compatibility.
2478 * @param $context IContextSource|null context source used when $resetKinds
2479 * does not contain 'all', passed to getOptionKinds().
2480 * Defaults to RequestContext::getMain() when null.
2482 public function resetOptions(
2483 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2484 IContextSource
$context = null
2487 $defaultOptions = self
::getDefaultOptions();
2489 if ( !is_array( $resetKinds ) ) {
2490 $resetKinds = array( $resetKinds );
2493 if ( in_array( 'all', $resetKinds ) ) {
2494 $newOptions = $defaultOptions;
2496 if ( $context === null ) {
2497 $context = RequestContext
::getMain();
2500 $optionKinds = $this->getOptionKinds( $context );
2501 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2502 $newOptions = array();
2504 // Use default values for the options that should be deleted, and
2505 // copy old values for the ones that shouldn't.
2506 foreach ( $this->mOptions
as $key => $value ) {
2507 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2508 if ( array_key_exists( $key, $defaultOptions ) ) {
2509 $newOptions[$key] = $defaultOptions[$key];
2512 $newOptions[$key] = $value;
2517 $this->mOptions
= $newOptions;
2518 $this->mOptionsLoaded
= true;
2522 * Get the user's preferred date format.
2523 * @return String User's preferred date format
2525 public function getDatePreference() {
2526 // Important migration for old data rows
2527 if ( is_null( $this->mDatePreference
) ) {
2529 $value = $this->getOption( 'date' );
2530 $map = $wgLang->getDatePreferenceMigrationMap();
2531 if ( isset( $map[$value] ) ) {
2532 $value = $map[$value];
2534 $this->mDatePreference
= $value;
2536 return $this->mDatePreference
;
2540 * Get the user preferred stub threshold
2544 public function getStubThreshold() {
2545 global $wgMaxArticleSize; # Maximum article size, in Kb
2546 $threshold = $this->getIntOption( 'stubthreshold' );
2547 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2548 # If they have set an impossible value, disable the preference
2549 # so we can use the parser cache again.
2556 * Get the permissions this user has.
2557 * @return Array of String permission names
2559 public function getRights() {
2560 if ( is_null( $this->mRights
) ) {
2561 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2562 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2563 // Force reindexation of rights when a hook has unset one of them
2564 $this->mRights
= array_values( array_unique( $this->mRights
) );
2566 return $this->mRights
;
2570 * Get the list of explicit group memberships this user has.
2571 * The implicit * and user groups are not included.
2572 * @return Array of String internal group names
2574 public function getGroups() {
2576 $this->loadGroups();
2577 return $this->mGroups
;
2581 * Get the list of implicit group memberships this user has.
2582 * This includes all explicit groups, plus 'user' if logged in,
2583 * '*' for all accounts, and autopromoted groups
2584 * @param bool $recache Whether to avoid the cache
2585 * @return Array of String internal group names
2587 public function getEffectiveGroups( $recache = false ) {
2588 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2589 wfProfileIn( __METHOD__
);
2590 $this->mEffectiveGroups
= array_unique( array_merge(
2591 $this->getGroups(), // explicit groups
2592 $this->getAutomaticGroups( $recache ) // implicit groups
2594 # Hook for additional groups
2595 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2596 // Force reindexation of groups when a hook has unset one of them
2597 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
2598 wfProfileOut( __METHOD__
);
2600 return $this->mEffectiveGroups
;
2604 * Get the list of implicit group memberships this user has.
2605 * This includes 'user' if logged in, '*' for all accounts,
2606 * and autopromoted groups
2607 * @param bool $recache Whether to avoid the cache
2608 * @return Array of String internal group names
2610 public function getAutomaticGroups( $recache = false ) {
2611 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
2612 wfProfileIn( __METHOD__
);
2613 $this->mImplicitGroups
= array( '*' );
2614 if ( $this->getId() ) {
2615 $this->mImplicitGroups
[] = 'user';
2617 $this->mImplicitGroups
= array_unique( array_merge(
2618 $this->mImplicitGroups
,
2619 Autopromote
::getAutopromoteGroups( $this )
2623 # Assure data consistency with rights/groups,
2624 # as getEffectiveGroups() depends on this function
2625 $this->mEffectiveGroups
= null;
2627 wfProfileOut( __METHOD__
);
2629 return $this->mImplicitGroups
;
2633 * Returns the groups the user has belonged to.
2635 * The user may still belong to the returned groups. Compare with getGroups().
2637 * The function will not return groups the user had belonged to before MW 1.17
2639 * @return array Names of the groups the user has belonged to.
2641 public function getFormerGroups() {
2642 if ( is_null( $this->mFormerGroups
) ) {
2643 $dbr = wfGetDB( DB_MASTER
);
2644 $res = $dbr->select( 'user_former_groups',
2645 array( 'ufg_group' ),
2646 array( 'ufg_user' => $this->mId
),
2648 $this->mFormerGroups
= array();
2649 foreach ( $res as $row ) {
2650 $this->mFormerGroups
[] = $row->ufg_group
;
2653 return $this->mFormerGroups
;
2657 * Get the user's edit count.
2660 public function getEditCount() {
2661 if ( !$this->getId() ) {
2665 if ( !isset( $this->mEditCount
) ) {
2666 /* Populate the count, if it has not been populated yet */
2667 wfProfileIn( __METHOD__
);
2668 $dbr = wfGetDB( DB_SLAVE
);
2669 // check if the user_editcount field has been initialized
2670 $count = $dbr->selectField(
2671 'user', 'user_editcount',
2672 array( 'user_id' => $this->mId
),
2676 if ( $count === null ) {
2677 // it has not been initialized. do so.
2678 $count = $this->initEditCount();
2680 $this->mEditCount
= intval( $count );
2681 wfProfileOut( __METHOD__
);
2683 return $this->mEditCount
;
2687 * Add the user to the given group.
2688 * This takes immediate effect.
2689 * @param string $group Name of the group to add
2691 public function addGroup( $group ) {
2692 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2693 $dbw = wfGetDB( DB_MASTER
);
2694 if ( $this->getId() ) {
2695 $dbw->insert( 'user_groups',
2697 'ug_user' => $this->getID(),
2698 'ug_group' => $group,
2701 array( 'IGNORE' ) );
2704 $this->loadGroups();
2705 $this->mGroups
[] = $group;
2706 // In case loadGroups was not called before, we now have the right twice.
2707 // Get rid of the duplicate.
2708 $this->mGroups
= array_unique( $this->mGroups
);
2709 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2711 $this->invalidateCache();
2715 * Remove the user from the given group.
2716 * This takes immediate effect.
2717 * @param string $group Name of the group to remove
2719 public function removeGroup( $group ) {
2721 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2722 $dbw = wfGetDB( DB_MASTER
);
2723 $dbw->delete( 'user_groups',
2725 'ug_user' => $this->getID(),
2726 'ug_group' => $group,
2728 // Remember that the user was in this group
2729 $dbw->insert( 'user_former_groups',
2731 'ufg_user' => $this->getID(),
2732 'ufg_group' => $group,
2735 array( 'IGNORE' ) );
2737 $this->loadGroups();
2738 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2739 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2741 $this->invalidateCache();
2745 * Get whether the user is logged in
2748 public function isLoggedIn() {
2749 return $this->getID() != 0;
2753 * Get whether the user is anonymous
2756 public function isAnon() {
2757 return !$this->isLoggedIn();
2761 * Check if user is allowed to access a feature / make an action
2763 * @internal param \String $varargs permissions to test
2764 * @return Boolean: True if user is allowed to perform *any* of the given actions
2768 public function isAllowedAny( /*...*/ ) {
2769 $permissions = func_get_args();
2770 foreach ( $permissions as $permission ) {
2771 if ( $this->isAllowed( $permission ) ) {
2780 * @internal param $varargs string
2781 * @return bool True if the user is allowed to perform *all* of the given actions
2783 public function isAllowedAll( /*...*/ ) {
2784 $permissions = func_get_args();
2785 foreach ( $permissions as $permission ) {
2786 if ( !$this->isAllowed( $permission ) ) {
2794 * Internal mechanics of testing a permission
2795 * @param $action String
2798 public function isAllowed( $action = '' ) {
2799 if ( $action === '' ) {
2800 return true; // In the spirit of DWIM
2802 # Patrolling may not be enabled
2803 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
2804 global $wgUseRCPatrol, $wgUseNPPatrol;
2805 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
2809 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2810 # by misconfiguration: 0 == 'foo'
2811 return in_array( $action, $this->getRights(), true );
2815 * Check whether to enable recent changes patrol features for this user
2816 * @return Boolean: True or false
2818 public function useRCPatrol() {
2819 global $wgUseRCPatrol;
2820 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
2824 * Check whether to enable new pages patrol features for this user
2825 * @return Bool True or false
2827 public function useNPPatrol() {
2828 global $wgUseRCPatrol, $wgUseNPPatrol;
2829 return ( ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) ) );
2833 * Get the WebRequest object to use with this object
2835 * @return WebRequest
2837 public function getRequest() {
2838 if ( $this->mRequest
) {
2839 return $this->mRequest
;
2847 * Get the current skin, loading it if required
2848 * @return Skin The current skin
2849 * @todo FIXME: Need to check the old failback system [AV]
2850 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
2852 public function getSkin() {
2853 wfDeprecated( __METHOD__
, '1.18' );
2854 return RequestContext
::getMain()->getSkin();
2858 * Get a WatchedItem for this user and $title.
2860 * @param $title Title
2861 * @return WatchedItem
2863 public function getWatchedItem( $title ) {
2864 $key = $title->getNamespace() . ':' . $title->getDBkey();
2866 if ( isset( $this->mWatchedItems
[$key] ) ) {
2867 return $this->mWatchedItems
[$key];
2870 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
2871 $this->mWatchedItems
= array();
2874 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title );
2875 return $this->mWatchedItems
[$key];
2879 * Check the watched status of an article.
2880 * @param $title Title of the article to look at
2883 public function isWatched( $title ) {
2884 return $this->getWatchedItem( $title )->isWatched();
2889 * @param $title Title of the article to look at
2891 public function addWatch( $title ) {
2892 $this->getWatchedItem( $title )->addWatch();
2893 $this->invalidateCache();
2897 * Stop watching an article.
2898 * @param $title Title of the article to look at
2900 public function removeWatch( $title ) {
2901 $this->getWatchedItem( $title )->removeWatch();
2902 $this->invalidateCache();
2906 * Clear the user's notification timestamp for the given title.
2907 * If e-notif e-mails are on, they will receive notification mails on
2908 * the next change of the page if it's watched etc.
2909 * @param $title Title of the article to look at
2911 public function clearNotification( &$title ) {
2912 global $wgUseEnotif, $wgShowUpdatedMarker;
2914 # Do nothing if the database is locked to writes
2915 if ( wfReadOnly() ) {
2919 if ( $title->getNamespace() == NS_USER_TALK
&&
2920 $title->getText() == $this->getName() ) {
2921 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) ) {
2924 $this->setNewtalk( false );
2927 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2931 if ( $this->isAnon() ) {
2932 // Nothing else to do...
2936 // Only update the timestamp if the page is being watched.
2937 // The query to find out if it is watched is cached both in memcached and per-invocation,
2938 // and when it does have to be executed, it can be on a slave
2939 // If this is the user's newtalk page, we always update the timestamp
2941 if ( $title->getNamespace() == NS_USER_TALK
&&
2942 $title->getText() == $this->getName() )
2947 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force );
2951 * Resets all of the given user's page-change notification timestamps.
2952 * If e-notif e-mails are on, they will receive notification mails on
2953 * the next change of any watched page.
2955 public function clearAllNotifications() {
2956 if ( wfReadOnly() ) {
2960 global $wgUseEnotif, $wgShowUpdatedMarker;
2961 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2962 $this->setNewtalk( false );
2965 $id = $this->getId();
2967 $dbw = wfGetDB( DB_MASTER
);
2968 $dbw->update( 'watchlist',
2970 'wl_notificationtimestamp' => null
2971 ), array( /* WHERE */
2975 # We also need to clear here the "you have new message" notification for the own user_talk page
2976 # This is cleared one page view later in Article::viewUpdates();
2981 * Set this user's options from an encoded string
2982 * @param string $str Encoded options to import
2984 * @deprecated in 1.19 due to removal of user_options from the user table
2986 private function decodeOptions( $str ) {
2987 wfDeprecated( __METHOD__
, '1.19' );
2992 $this->mOptionsLoaded
= true;
2993 $this->mOptionOverrides
= array();
2995 // If an option is not set in $str, use the default value
2996 $this->mOptions
= self
::getDefaultOptions();
2998 $a = explode( "\n", $str );
2999 foreach ( $a as $s ) {
3001 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
3002 $this->mOptions
[$m[1]] = $m[2];
3003 $this->mOptionOverrides
[$m[1]] = $m[2];
3009 * Set a cookie on the user's client. Wrapper for
3010 * WebResponse::setCookie
3011 * @param string $name Name of the cookie to set
3012 * @param string $value Value to set
3013 * @param int $exp Expiration time, as a UNIX time value;
3014 * if 0 or not specified, use the default $wgCookieExpiration
3015 * @param $secure Bool
3016 * true: Force setting the secure attribute when setting the cookie
3017 * false: Force NOT setting the secure attribute when setting the cookie
3018 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3020 protected function setCookie( $name, $value, $exp = 0, $secure = null ) {
3021 $this->getRequest()->response()->setcookie( $name, $value, $exp, null, null, $secure );
3025 * Clear a cookie on the user's client
3026 * @param string $name Name of the cookie to clear
3028 protected function clearCookie( $name ) {
3029 $this->setCookie( $name, '', time() - 86400 );
3033 * Set the default cookies for this session on the user's client.
3035 * @param $request WebRequest object to use; $wgRequest will be used if null
3037 * @param bool $secure Whether to force secure/insecure cookies or use default
3039 public function setCookies( $request = null, $secure = null ) {
3040 if ( $request === null ) {
3041 $request = $this->getRequest();
3045 if ( 0 == $this->mId
) {
3048 if ( !$this->mToken
) {
3049 // When token is empty or NULL generate a new one and then save it to the database
3050 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3051 // Simply by setting every cell in the user_token column to NULL and letting them be
3052 // regenerated as users log back into the wiki.
3054 $this->saveSettings();
3057 'wsUserID' => $this->mId
,
3058 'wsToken' => $this->mToken
,
3059 'wsUserName' => $this->getName()
3062 'UserID' => $this->mId
,
3063 'UserName' => $this->getName(),
3065 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
3066 $cookies['Token'] = $this->mToken
;
3068 $cookies['Token'] = false;
3071 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3073 foreach ( $session as $name => $value ) {
3074 $request->setSessionData( $name, $value );
3076 foreach ( $cookies as $name => $value ) {
3077 if ( $value === false ) {
3078 $this->clearCookie( $name );
3080 $this->setCookie( $name, $value, 0, $secure );
3085 * If wpStickHTTPS was selected, also set an insecure cookie that
3086 * will cause the site to redirect the user to HTTPS, if they access
3087 * it over HTTP. Bug 29898.
3089 if ( $request->getCheck( 'wpStickHTTPS' ) ) {
3090 $this->setCookie( 'forceHTTPS', 'true', time() +
2592000, false ); //30 days
3095 * Log this user out.
3097 public function logout() {
3098 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3104 * Clear the user's cookies and session, and reset the instance cache.
3107 public function doLogout() {
3108 $this->clearInstanceCache( 'defaults' );
3110 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3112 $this->clearCookie( 'UserID' );
3113 $this->clearCookie( 'Token' );
3114 $this->clearCookie( 'forceHTTPS' );
3116 # Remember when user logged out, to prevent seeing cached pages
3117 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
3121 * Save this user's settings into the database.
3122 * @todo Only rarely do all these fields need to be set!
3124 public function saveSettings() {
3128 if ( wfReadOnly() ) {
3131 if ( 0 == $this->mId
) {
3135 $this->mTouched
= self
::newTouchedTimestamp();
3136 if ( !$wgAuth->allowSetLocalPassword() ) {
3137 $this->mPassword
= '';
3140 $dbw = wfGetDB( DB_MASTER
);
3141 $dbw->update( 'user',
3143 'user_name' => $this->mName
,
3144 'user_password' => $this->mPassword
,
3145 'user_newpassword' => $this->mNewpassword
,
3146 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3147 'user_real_name' => $this->mRealName
,
3148 'user_email' => $this->mEmail
,
3149 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3150 'user_touched' => $dbw->timestamp( $this->mTouched
),
3151 'user_token' => strval( $this->mToken
),
3152 'user_email_token' => $this->mEmailToken
,
3153 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3154 ), array( /* WHERE */
3155 'user_id' => $this->mId
3159 $this->saveOptions();
3161 wfRunHooks( 'UserSaveSettings', array( $this ) );
3162 $this->clearSharedCache();
3163 $this->getUserPage()->invalidateCache();
3167 * If only this user's username is known, and it exists, return the user ID.
3170 public function idForName() {
3171 $s = trim( $this->getName() );
3176 $dbr = wfGetDB( DB_SLAVE
);
3177 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
3178 if ( $id === false ) {
3185 * Add a user to the database, return the user object
3187 * @param string $name Username to add
3188 * @param array $params of Strings Non-default parameters to save to the database as user_* fields:
3189 * - password The user's password hash. Password logins will be disabled if this is omitted.
3190 * - newpassword Hash for a temporary password that has been mailed to the user
3191 * - email The user's email address
3192 * - email_authenticated The email authentication timestamp
3193 * - real_name The user's real name
3194 * - options An associative array of non-default options
3195 * - token Random authentication token. Do not set.
3196 * - registration Registration timestamp. Do not set.
3198 * @return User object, or null if the username already exists
3200 public static function createNew( $name, $params = array() ) {
3203 $user->setToken(); // init token
3204 if ( isset( $params['options'] ) ) {
3205 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3206 unset( $params['options'] );
3208 $dbw = wfGetDB( DB_MASTER
);
3209 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3212 'user_id' => $seqVal,
3213 'user_name' => $name,
3214 'user_password' => $user->mPassword
,
3215 'user_newpassword' => $user->mNewpassword
,
3216 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3217 'user_email' => $user->mEmail
,
3218 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3219 'user_real_name' => $user->mRealName
,
3220 'user_token' => strval( $user->mToken
),
3221 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3222 'user_editcount' => 0,
3223 'user_touched' => $dbw->timestamp( self
::newTouchedTimestamp() ),
3225 foreach ( $params as $name => $value ) {
3226 $fields["user_$name"] = $value;
3228 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3229 if ( $dbw->affectedRows() ) {
3230 $newUser = User
::newFromId( $dbw->insertId() );
3238 * Add this existing user object to the database. If the user already
3239 * exists, a fatal status object is returned, and the user object is
3240 * initialised with the data from the database.
3242 * Previously, this function generated a DB error due to a key conflict
3243 * if the user already existed. Many extension callers use this function
3244 * in code along the lines of:
3246 * $user = User::newFromName( $name );
3247 * if ( !$user->isLoggedIn() ) {
3248 * $user->addToDatabase();
3250 * // do something with $user...
3252 * However, this was vulnerable to a race condition (bug 16020). By
3253 * initialising the user object if the user exists, we aim to support this
3254 * calling sequence as far as possible.
3256 * Note that if the user exists, this function will acquire a write lock,
3257 * so it is still advisable to make the call conditional on isLoggedIn(),
3258 * and to commit the transaction after calling.
3260 * @throws MWException
3263 public function addToDatabase() {
3265 if ( !$this->mToken
) {
3266 $this->setToken(); // init token
3269 $this->mTouched
= self
::newTouchedTimestamp();
3271 $dbw = wfGetDB( DB_MASTER
);
3272 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3273 $dbw->insert( 'user',
3275 'user_id' => $seqVal,
3276 'user_name' => $this->mName
,
3277 'user_password' => $this->mPassword
,
3278 'user_newpassword' => $this->mNewpassword
,
3279 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3280 'user_email' => $this->mEmail
,
3281 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3282 'user_real_name' => $this->mRealName
,
3283 'user_token' => strval( $this->mToken
),
3284 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3285 'user_editcount' => 0,
3286 'user_touched' => $dbw->timestamp( $this->mTouched
),
3290 if ( !$dbw->affectedRows() ) {
3291 $this->mId
= $dbw->selectField( 'user', 'user_id',
3292 array( 'user_name' => $this->mName
), __METHOD__
);
3295 if ( $this->loadFromDatabase() ) {
3300 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3301 "to insert user '{$this->mName}' row, but it was not present in select!" );
3303 return Status
::newFatal( 'userexists' );
3305 $this->mId
= $dbw->insertId();
3307 // Clear instance cache other than user table data, which is already accurate
3308 $this->clearInstanceCache();
3310 $this->saveOptions();
3311 return Status
::newGood();
3315 * If this user is logged-in and blocked,
3316 * block any IP address they've successfully logged in from.
3317 * @return bool A block was spread
3319 public function spreadAnyEditBlock() {
3320 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3321 return $this->spreadBlock();
3327 * If this (non-anonymous) user is blocked,
3328 * block the IP address they've successfully logged in from.
3329 * @return bool A block was spread
3331 protected function spreadBlock() {
3332 wfDebug( __METHOD__
. "()\n" );
3334 if ( $this->mId
== 0 ) {
3338 $userblock = Block
::newFromTarget( $this->getName() );
3339 if ( !$userblock ) {
3343 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3347 * Generate a string which will be different for any combination of
3348 * user options which would produce different parser output.
3349 * This will be used as part of the hash key for the parser cache,
3350 * so users with the same options can share the same cached data
3353 * Extensions which require it should install 'PageRenderingHash' hook,
3354 * which will give them a chance to modify this key based on their own
3357 * @deprecated since 1.17 use the ParserOptions object to get the relevant options
3358 * @return String Page rendering hash
3360 public function getPageRenderingHash() {
3361 wfDeprecated( __METHOD__
, '1.17' );
3363 global $wgRenderHashAppend, $wgLang, $wgContLang;
3364 if ( $this->mHash
) {
3365 return $this->mHash
;
3368 // stubthreshold is only included below for completeness,
3369 // since it disables the parser cache, its value will always
3370 // be 0 when this function is called by parsercache.
3372 $confstr = $this->getOption( 'math' );
3373 $confstr .= '!' . $this->getStubThreshold();
3374 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ?
'1' : '' );
3375 $confstr .= '!' . $wgLang->getCode();
3376 $confstr .= '!' . $this->getOption( 'thumbsize' );
3377 // add in language specific options, if any
3378 $extra = $wgContLang->getExtraHashOptions();
3381 // Since the skin could be overloading link(), it should be
3382 // included here but in practice, none of our skins do that.
3384 $confstr .= $wgRenderHashAppend;
3386 // Give a chance for extensions to modify the hash, if they have
3387 // extra options or other effects on the parser cache.
3388 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
3390 // Make it a valid memcached key fragment
3391 $confstr = str_replace( ' ', '_', $confstr );
3392 $this->mHash
= $confstr;
3397 * Get whether the user is explicitly blocked from account creation.
3398 * @return Bool|Block
3400 public function isBlockedFromCreateAccount() {
3401 $this->getBlockedStatus();
3402 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3403 return $this->mBlock
;
3406 # bug 13611: if the IP address the user is trying to create an account from is
3407 # blocked with createaccount disabled, prevent new account creation there even
3408 # when the user is logged in
3409 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3410 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3412 return $this->mBlockedFromCreateAccount
instanceof Block
&& $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3413 ?
$this->mBlockedFromCreateAccount
3418 * Get whether the user is blocked from using Special:Emailuser.
3421 public function isBlockedFromEmailuser() {
3422 $this->getBlockedStatus();
3423 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3427 * Get whether the user is allowed to create an account.
3430 function isAllowedToCreateAccount() {
3431 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3435 * Get this user's personal page title.
3437 * @return Title: User's personal page title
3439 public function getUserPage() {
3440 return Title
::makeTitle( NS_USER
, $this->getName() );
3444 * Get this user's talk page title.
3446 * @return Title: User's talk page title
3448 public function getTalkPage() {
3449 $title = $this->getUserPage();
3450 return $title->getTalkPage();
3454 * Determine whether the user is a newbie. Newbies are either
3455 * anonymous IPs, or the most recently created accounts.
3458 public function isNewbie() {
3459 return !$this->isAllowed( 'autoconfirmed' );
3463 * Check to see if the given clear-text password is one of the accepted passwords
3464 * @param string $password user password.
3465 * @return Boolean: True if the given password is correct, otherwise False.
3467 public function checkPassword( $password ) {
3468 global $wgAuth, $wgLegacyEncoding;
3471 // Even though we stop people from creating passwords that
3472 // are shorter than this, doesn't mean people wont be able
3473 // to. Certain authentication plugins do NOT want to save
3474 // domain passwords in a mysql database, so we should
3475 // check this (in case $wgAuth->strict() is false).
3476 if ( !$this->isValidPassword( $password ) ) {
3480 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3482 } elseif ( $wgAuth->strict() ) {
3483 /* Auth plugin doesn't allow local authentication */
3485 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3486 /* Auth plugin doesn't allow local authentication for this user name */
3489 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
3491 } elseif ( $wgLegacyEncoding ) {
3492 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3493 # Check for this with iconv
3494 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3495 if ( $cp1252Password != $password &&
3496 self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) )
3505 * Check if the given clear-text password matches the temporary password
3506 * sent by e-mail for password reset operations.
3508 * @param $plaintext string
3510 * @return Boolean: True if matches, false otherwise
3512 public function checkTemporaryPassword( $plaintext ) {
3513 global $wgNewPasswordExpiry;
3516 if ( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
3517 if ( is_null( $this->mNewpassTime
) ) {
3520 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3521 return ( time() < $expiry );
3528 * Alias for getEditToken.
3529 * @deprecated since 1.19, use getEditToken instead.
3531 * @param string|array $salt of Strings Optional function-specific data for hashing
3532 * @param $request WebRequest object to use or null to use $wgRequest
3533 * @return String The new edit token
3535 public function editToken( $salt = '', $request = null ) {
3536 wfDeprecated( __METHOD__
, '1.19' );
3537 return $this->getEditToken( $salt, $request );
3541 * Initialize (if necessary) and return a session token value
3542 * which can be used in edit forms to show that the user's
3543 * login credentials aren't being hijacked with a foreign form
3548 * @param string|array $salt of Strings Optional function-specific data for hashing
3549 * @param $request WebRequest object to use or null to use $wgRequest
3550 * @return String The new edit token
3552 public function getEditToken( $salt = '', $request = null ) {
3553 if ( $request == null ) {
3554 $request = $this->getRequest();
3557 if ( $this->isAnon() ) {
3558 return EDIT_TOKEN_SUFFIX
;
3560 $token = $request->getSessionData( 'wsEditToken' );
3561 if ( $token === null ) {
3562 $token = MWCryptRand
::generateHex( 32 );
3563 $request->setSessionData( 'wsEditToken', $token );
3565 if ( is_array( $salt ) ) {
3566 $salt = implode( '|', $salt );
3568 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
3573 * Generate a looking random token for various uses.
3575 * @return String The new random token
3576 * @deprecated since 1.20; Use MWCryptRand for secure purposes or wfRandomString for pseudo-randomness
3578 public static function generateToken() {
3579 return MWCryptRand
::generateHex( 32 );
3583 * Check given value against the token value stored in the session.
3584 * A match should confirm that the form was submitted from the
3585 * user's own login session, not a form submission from a third-party
3588 * @param string $val Input value to compare
3589 * @param string $salt Optional function-specific data for hashing
3590 * @param $request WebRequest object to use or null to use $wgRequest
3591 * @return Boolean: Whether the token matches
3593 public function matchEditToken( $val, $salt = '', $request = null ) {
3594 $sessionToken = $this->getEditToken( $salt, $request );
3595 if ( $val != $sessionToken ) {
3596 wfDebug( "User::matchEditToken: broken session data\n" );
3598 return $val == $sessionToken;
3602 * Check given value against the token value stored in the session,
3603 * ignoring the suffix.
3605 * @param string $val Input value to compare
3606 * @param string $salt Optional function-specific data for hashing
3607 * @param $request WebRequest object to use or null to use $wgRequest
3608 * @return Boolean: Whether the token matches
3610 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3611 $sessionToken = $this->getEditToken( $salt, $request );
3612 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3616 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3617 * mail to the user's given address.
3619 * @param string $type message to send, either "created", "changed" or "set"
3620 * @return Status object
3622 public function sendConfirmationMail( $type = 'created' ) {
3624 $expiration = null; // gets passed-by-ref and defined in next line.
3625 $token = $this->confirmationToken( $expiration );
3626 $url = $this->confirmationTokenUrl( $token );
3627 $invalidateURL = $this->invalidationTokenUrl( $token );
3628 $this->saveSettings();
3630 if ( $type == 'created' ||
$type === false ) {
3631 $message = 'confirmemail_body';
3632 } elseif ( $type === true ) {
3633 $message = 'confirmemail_body_changed';
3635 $message = 'confirmemail_body_' . $type;
3638 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3639 wfMessage( $message,
3640 $this->getRequest()->getIP(),
3643 $wgLang->timeanddate( $expiration, false ),
3645 $wgLang->date( $expiration, false ),
3646 $wgLang->time( $expiration, false ) )->text() );
3650 * Send an e-mail to this user's account. Does not check for
3651 * confirmed status or validity.
3653 * @param string $subject Message subject
3654 * @param string $body Message body
3655 * @param string $from Optional From address; if unspecified, default $wgPasswordSender will be used
3656 * @param string $replyto Reply-To address
3659 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3660 if ( is_null( $from ) ) {
3661 global $wgPasswordSender, $wgPasswordSenderName;
3662 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
3664 $sender = new MailAddress( $from );
3667 $to = new MailAddress( $this );
3668 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
3672 * Generate, store, and return a new e-mail confirmation code.
3673 * A hash (unsalted, since it's used as a key) is stored.
3675 * @note Call saveSettings() after calling this function to commit
3676 * this change to the database.
3678 * @param &$expiration \mixed Accepts the expiration time
3679 * @return String New token
3681 private function confirmationToken( &$expiration ) {
3682 global $wgUserEmailConfirmationTokenExpiry;
3684 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
3685 $expiration = wfTimestamp( TS_MW
, $expires );
3687 $token = MWCryptRand
::generateHex( 32 );
3688 $hash = md5( $token );
3689 $this->mEmailToken
= $hash;
3690 $this->mEmailTokenExpires
= $expiration;
3695 * Return a URL the user can use to confirm their email address.
3696 * @param string $token Accepts the email confirmation token
3697 * @return String New token URL
3699 private function confirmationTokenUrl( $token ) {
3700 return $this->getTokenUrl( 'ConfirmEmail', $token );
3704 * Return a URL the user can use to invalidate their email address.
3705 * @param string $token Accepts the email confirmation token
3706 * @return String New token URL
3708 private function invalidationTokenUrl( $token ) {
3709 return $this->getTokenUrl( 'InvalidateEmail', $token );
3713 * Internal function to format the e-mail validation/invalidation URLs.
3714 * This uses a quickie hack to use the
3715 * hardcoded English names of the Special: pages, for ASCII safety.
3717 * @note Since these URLs get dropped directly into emails, using the
3718 * short English names avoids insanely long URL-encoded links, which
3719 * also sometimes can get corrupted in some browsers/mailers
3720 * (bug 6957 with Gmail and Internet Explorer).
3722 * @param string $page Special page
3723 * @param string $token Token
3724 * @return String Formatted URL
3726 protected function getTokenUrl( $page, $token ) {
3727 // Hack to bypass localization of 'Special:'
3728 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
3729 return $title->getCanonicalURL();
3733 * Mark the e-mail address confirmed.
3735 * @note Call saveSettings() after calling this function to commit the change.
3739 public function confirmEmail() {
3740 // Check if it's already confirmed, so we don't touch the database
3741 // and fire the ConfirmEmailComplete hook on redundant confirmations.
3742 if ( !$this->isEmailConfirmed() ) {
3743 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3744 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3750 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3751 * address if it was already confirmed.
3753 * @note Call saveSettings() after calling this function to commit the change.
3754 * @return bool Returns true
3756 function invalidateEmail() {
3758 $this->mEmailToken
= null;
3759 $this->mEmailTokenExpires
= null;
3760 $this->setEmailAuthenticationTimestamp( null );
3761 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3766 * Set the e-mail authentication timestamp.
3767 * @param string $timestamp TS_MW timestamp
3769 function setEmailAuthenticationTimestamp( $timestamp ) {
3771 $this->mEmailAuthenticated
= $timestamp;
3772 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
3776 * Is this user allowed to send e-mails within limits of current
3777 * site configuration?
3780 public function canSendEmail() {
3781 global $wgEnableEmail, $wgEnableUserEmail;
3782 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
3785 $canSend = $this->isEmailConfirmed();
3786 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3791 * Is this user allowed to receive e-mails within limits of current
3792 * site configuration?
3795 public function canReceiveEmail() {
3796 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3800 * Is this user's e-mail address valid-looking and confirmed within
3801 * limits of the current site configuration?
3803 * @note If $wgEmailAuthentication is on, this may require the user to have
3804 * confirmed their address by returning a code or using a password
3805 * sent to the address from the wiki.
3809 public function isEmailConfirmed() {
3810 global $wgEmailAuthentication;
3813 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3814 if ( $this->isAnon() ) {
3817 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
3820 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
3830 * Check whether there is an outstanding request for e-mail confirmation.
3833 public function isEmailConfirmationPending() {
3834 global $wgEmailAuthentication;
3835 return $wgEmailAuthentication &&
3836 !$this->isEmailConfirmed() &&
3837 $this->mEmailToken
&&
3838 $this->mEmailTokenExpires
> wfTimestamp();
3842 * Get the timestamp of account creation.
3844 * @return String|Bool|Null Timestamp of account creation, false for
3845 * non-existent/anonymous user accounts, or null if existing account
3846 * but information is not in database.
3848 public function getRegistration() {
3849 if ( $this->isAnon() ) {
3853 return $this->mRegistration
;
3857 * Get the timestamp of the first edit
3859 * @return String|Bool Timestamp of first edit, or false for
3860 * non-existent/anonymous user accounts.
3862 public function getFirstEditTimestamp() {
3863 if ( $this->getId() == 0 ) {
3864 return false; // anons
3866 $dbr = wfGetDB( DB_SLAVE
);
3867 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3868 array( 'rev_user' => $this->getId() ),
3870 array( 'ORDER BY' => 'rev_timestamp ASC' )
3873 return false; // no edits
3875 return wfTimestamp( TS_MW
, $time );
3879 * Get the permissions associated with a given list of groups
3881 * @param array $groups of Strings List of internal group names
3882 * @return Array of Strings List of permission key names for given groups combined
3884 public static function getGroupPermissions( $groups ) {
3885 global $wgGroupPermissions, $wgRevokePermissions;
3887 // grant every granted permission first
3888 foreach ( $groups as $group ) {
3889 if ( isset( $wgGroupPermissions[$group] ) ) {
3890 $rights = array_merge( $rights,
3891 // array_filter removes empty items
3892 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3895 // now revoke the revoked permissions
3896 foreach ( $groups as $group ) {
3897 if ( isset( $wgRevokePermissions[$group] ) ) {
3898 $rights = array_diff( $rights,
3899 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3902 return array_unique( $rights );
3906 * Get all the groups who have a given permission
3908 * @param string $role Role to check
3909 * @return Array of Strings List of internal group names with the given permission
3911 public static function getGroupsWithPermission( $role ) {
3912 global $wgGroupPermissions;
3913 $allowedGroups = array();
3914 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
3915 if ( self
::groupHasPermission( $group, $role ) ) {
3916 $allowedGroups[] = $group;
3919 return $allowedGroups;
3923 * Check, if the given group has the given permission
3926 * @param string $group Group to check
3927 * @param string $role Role to check
3930 public static function groupHasPermission( $group, $role ) {
3931 global $wgGroupPermissions, $wgRevokePermissions;
3932 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
3933 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
3937 * Get the localized descriptive name for a group, if it exists
3939 * @param string $group Internal group name
3940 * @return String Localized descriptive group name
3942 public static function getGroupName( $group ) {
3943 $msg = wfMessage( "group-$group" );
3944 return $msg->isBlank() ?
$group : $msg->text();
3948 * Get the localized descriptive name for a member of a group, if it exists
3950 * @param string $group Internal group name
3951 * @param string $username Username for gender (since 1.19)
3952 * @return String Localized name for group member
3954 public static function getGroupMember( $group, $username = '#' ) {
3955 $msg = wfMessage( "group-$group-member", $username );
3956 return $msg->isBlank() ?
$group : $msg->text();
3960 * Return the set of defined explicit groups.
3961 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3962 * are not included, as they are defined automatically, not in the database.
3963 * @return Array of internal group names
3965 public static function getAllGroups() {
3966 global $wgGroupPermissions, $wgRevokePermissions;
3968 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3969 self
::getImplicitGroups()
3974 * Get a list of all available permissions.
3975 * @return Array of permission names
3977 public static function getAllRights() {
3978 if ( self
::$mAllRights === false ) {
3979 global $wgAvailableRights;
3980 if ( count( $wgAvailableRights ) ) {
3981 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3983 self
::$mAllRights = self
::$mCoreRights;
3985 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3987 return self
::$mAllRights;
3991 * Get a list of implicit groups
3992 * @return Array of Strings Array of internal group names
3994 public static function getImplicitGroups() {
3995 global $wgImplicitGroups;
3996 $groups = $wgImplicitGroups;
3997 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
4002 * Get the title of a page describing a particular group
4004 * @param string $group Internal group name
4005 * @return Title|Bool Title of the page if it exists, false otherwise
4007 public static function getGroupPage( $group ) {
4008 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4009 if ( $msg->exists() ) {
4010 $title = Title
::newFromText( $msg->text() );
4011 if ( is_object( $title ) ) {
4019 * Create a link to the group in HTML, if available;
4020 * else return the group name.
4022 * @param string $group Internal name of the group
4023 * @param string $text The text of the link
4024 * @return String HTML link to the group
4026 public static function makeGroupLinkHTML( $group, $text = '' ) {
4027 if ( $text == '' ) {
4028 $text = self
::getGroupName( $group );
4030 $title = self
::getGroupPage( $group );
4032 return Linker
::link( $title, htmlspecialchars( $text ) );
4039 * Create a link to the group in Wikitext, if available;
4040 * else return the group name.
4042 * @param string $group Internal name of the group
4043 * @param string $text The text of the link
4044 * @return String Wikilink to the group
4046 public static function makeGroupLinkWiki( $group, $text = '' ) {
4047 if ( $text == '' ) {
4048 $text = self
::getGroupName( $group );
4050 $title = self
::getGroupPage( $group );
4052 $page = $title->getPrefixedText();
4053 return "[[$page|$text]]";
4060 * Returns an array of the groups that a particular group can add/remove.
4062 * @param string $group the group to check for whether it can add/remove
4063 * @return Array array( 'add' => array( addablegroups ),
4064 * 'remove' => array( removablegroups ),
4065 * 'add-self' => array( addablegroups to self),
4066 * 'remove-self' => array( removable groups from self) )
4068 public static function changeableByGroup( $group ) {
4069 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4071 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
4072 if ( empty( $wgAddGroups[$group] ) ) {
4073 // Don't add anything to $groups
4074 } elseif ( $wgAddGroups[$group] === true ) {
4075 // You get everything
4076 $groups['add'] = self
::getAllGroups();
4077 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4078 $groups['add'] = $wgAddGroups[$group];
4081 // Same thing for remove
4082 if ( empty( $wgRemoveGroups[$group] ) ) {
4083 } elseif ( $wgRemoveGroups[$group] === true ) {
4084 $groups['remove'] = self
::getAllGroups();
4085 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4086 $groups['remove'] = $wgRemoveGroups[$group];
4089 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4090 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4091 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4092 if ( is_int( $key ) ) {
4093 $wgGroupsAddToSelf['user'][] = $value;
4098 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4099 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4100 if ( is_int( $key ) ) {
4101 $wgGroupsRemoveFromSelf['user'][] = $value;
4106 // Now figure out what groups the user can add to him/herself
4107 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4108 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4109 // No idea WHY this would be used, but it's there
4110 $groups['add-self'] = User
::getAllGroups();
4111 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4112 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4115 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4116 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4117 $groups['remove-self'] = User
::getAllGroups();
4118 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4119 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4126 * Returns an array of groups that this user can add and remove
4127 * @return Array array( 'add' => array( addablegroups ),
4128 * 'remove' => array( removablegroups ),
4129 * 'add-self' => array( addablegroups to self),
4130 * 'remove-self' => array( removable groups from self) )
4132 public function changeableGroups() {
4133 if ( $this->isAllowed( 'userrights' ) ) {
4134 // This group gives the right to modify everything (reverse-
4135 // compatibility with old "userrights lets you change
4137 // Using array_merge to make the groups reindexed
4138 $all = array_merge( User
::getAllGroups() );
4142 'add-self' => array(),
4143 'remove-self' => array()
4147 // Okay, it's not so simple, we will have to go through the arrays
4150 'remove' => array(),
4151 'add-self' => array(),
4152 'remove-self' => array()
4154 $addergroups = $this->getEffectiveGroups();
4156 foreach ( $addergroups as $addergroup ) {
4157 $groups = array_merge_recursive(
4158 $groups, $this->changeableByGroup( $addergroup )
4160 $groups['add'] = array_unique( $groups['add'] );
4161 $groups['remove'] = array_unique( $groups['remove'] );
4162 $groups['add-self'] = array_unique( $groups['add-self'] );
4163 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4169 * Increment the user's edit-count field.
4170 * Will have no effect for anonymous users.
4172 public function incEditCount() {
4173 if ( !$this->isAnon() ) {
4174 $dbw = wfGetDB( DB_MASTER
);
4177 array( 'user_editcount=user_editcount+1' ),
4178 array( 'user_id' => $this->getId() ),
4182 // Lazy initialization check...
4183 if ( $dbw->affectedRows() == 0 ) {
4184 // Now here's a goddamn hack...
4185 $dbr = wfGetDB( DB_SLAVE
);
4186 if ( $dbr !== $dbw ) {
4187 // If we actually have a slave server, the count is
4188 // at least one behind because the current transaction
4189 // has not been committed and replicated.
4190 $this->initEditCount( 1 );
4192 // But if DB_SLAVE is selecting the master, then the
4193 // count we just read includes the revision that was
4194 // just added in the working transaction.
4195 $this->initEditCount();
4199 // edit count in user cache too
4200 $this->invalidateCache();
4204 * Initialize user_editcount from data out of the revision table
4206 * @param $add Integer Edits to add to the count from the revision table
4207 * @return Integer Number of edits
4209 protected function initEditCount( $add = 0 ) {
4210 // Pull from a slave to be less cruel to servers
4211 // Accuracy isn't the point anyway here
4212 $dbr = wfGetDB( DB_SLAVE
);
4213 $count = (int) $dbr->selectField(
4216 array( 'rev_user' => $this->getId() ),
4219 $count = $count +
$add;
4221 $dbw = wfGetDB( DB_MASTER
);
4224 array( 'user_editcount' => $count ),
4225 array( 'user_id' => $this->getId() ),
4233 * Get the description of a given right
4235 * @param string $right Right to query
4236 * @return String Localized description of the right
4238 public static function getRightDescription( $right ) {
4239 $key = "right-$right";
4240 $msg = wfMessage( $key );
4241 return $msg->isBlank() ?
$right : $msg->text();
4245 * Make an old-style password hash
4247 * @param string $password Plain-text password
4248 * @param string $userId User ID
4249 * @return String Password hash
4251 public static function oldCrypt( $password, $userId ) {
4252 global $wgPasswordSalt;
4253 if ( $wgPasswordSalt ) {
4254 return md5( $userId . '-' . md5( $password ) );
4256 return md5( $password );
4261 * Make a new-style password hash
4263 * @param string $password Plain-text password
4264 * @param bool|string $salt Optional salt, may be random or the user ID.
4266 * If unspecified or false, will generate one automatically
4267 * @return String Password hash
4269 public static function crypt( $password, $salt = false ) {
4270 global $wgPasswordSalt;
4273 if ( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4277 if ( $wgPasswordSalt ) {
4278 if ( $salt === false ) {
4279 $salt = MWCryptRand
::generateHex( 8 );
4281 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4283 return ':A:' . md5( $password );
4288 * Compare a password hash with a plain-text password. Requires the user
4289 * ID if there's a chance that the hash is an old-style hash.
4291 * @param string $hash Password hash
4292 * @param string $password Plain-text password to compare
4293 * @param string|bool $userId User ID for old-style password salt
4297 public static function comparePasswords( $hash, $password, $userId = false ) {
4298 $type = substr( $hash, 0, 3 );
4301 if ( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4305 if ( $type == ':A:' ) {
4307 return md5( $password ) === substr( $hash, 3 );
4308 } elseif ( $type == ':B:' ) {
4310 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4311 return md5( $salt . '-' . md5( $password ) ) === $realHash;
4314 return self
::oldCrypt( $password, $userId ) === $hash;
4319 * Add a newuser log entry for this user.
4320 * Before 1.19 the return value was always true.
4322 * @param string|bool $action account creation type.
4323 * - String, one of the following values:
4324 * - 'create' for an anonymous user creating an account for himself.
4325 * This will force the action's performer to be the created user itself,
4326 * no matter the value of $wgUser
4327 * - 'create2' for a logged in user creating an account for someone else
4328 * - 'byemail' when the created user will receive its password by e-mail
4329 * - Boolean means whether the account was created by e-mail (deprecated):
4330 * - true will be converted to 'byemail'
4331 * - false will be converted to 'create' if this object is the same as
4332 * $wgUser and to 'create2' otherwise
4334 * @param string $reason user supplied reason
4336 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4338 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4339 global $wgUser, $wgNewUserLog;
4340 if ( empty( $wgNewUserLog ) ) {
4341 return true; // disabled
4344 if ( $action === true ) {
4345 $action = 'byemail';
4346 } elseif ( $action === false ) {
4347 if ( $this->getName() == $wgUser->getName() ) {
4350 $action = 'create2';
4354 if ( $action === 'create' ||
$action === 'autocreate' ) {
4357 $performer = $wgUser;
4360 $logEntry = new ManualLogEntry( 'newusers', $action );
4361 $logEntry->setPerformer( $performer );
4362 $logEntry->setTarget( $this->getUserPage() );
4363 $logEntry->setComment( $reason );
4364 $logEntry->setParameters( array(
4365 '4::userid' => $this->getId(),
4367 $logid = $logEntry->insert();
4369 if ( $action !== 'autocreate' ) {
4370 $logEntry->publish( $logid );
4377 * Add an autocreate newuser log entry for this user
4378 * Used by things like CentralAuth and perhaps other authplugins.
4379 * Consider calling addNewUserLogEntry() directly instead.
4383 public function addNewUserLogEntryAutoCreate() {
4384 $this->addNewUserLogEntry( 'autocreate' );
4390 * Load the user options either from cache, the database or an array
4392 * @param array $data Rows for the current user out of the user_properties table
4394 protected function loadOptions( $data = null ) {
4399 if ( $this->mOptionsLoaded
) {
4403 $this->mOptions
= self
::getDefaultOptions();
4405 if ( !$this->getId() ) {
4406 // For unlogged-in users, load language/variant options from request.
4407 // There's no need to do it for logged-in users: they can set preferences,
4408 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4409 // so don't override user's choice (especially when the user chooses site default).
4410 $variant = $wgContLang->getDefaultVariant();
4411 $this->mOptions
['variant'] = $variant;
4412 $this->mOptions
['language'] = $variant;
4413 $this->mOptionsLoaded
= true;
4417 // Maybe load from the object
4418 if ( !is_null( $this->mOptionOverrides
) ) {
4419 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4420 foreach ( $this->mOptionOverrides
as $key => $value ) {
4421 $this->mOptions
[$key] = $value;
4424 if ( !is_array( $data ) ) {
4425 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4426 // Load from database
4427 $dbr = wfGetDB( DB_SLAVE
);
4429 $res = $dbr->select(
4431 array( 'up_property', 'up_value' ),
4432 array( 'up_user' => $this->getId() ),
4436 $this->mOptionOverrides
= array();
4438 foreach ( $res as $row ) {
4439 $data[$row->up_property
] = $row->up_value
;
4442 foreach ( $data as $property => $value ) {
4443 $this->mOptionOverrides
[$property] = $value;
4444 $this->mOptions
[$property] = $value;
4448 $this->mOptionsLoaded
= true;
4450 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
4456 protected function saveOptions() {
4457 $this->loadOptions();
4459 // Not using getOptions(), to keep hidden preferences in database
4460 $saveOptions = $this->mOptions
;
4462 // Allow hooks to abort, for instance to save to a global profile.
4463 // Reset options to default state before saving.
4464 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4468 $userId = $this->getId();
4469 $insert_rows = array();
4470 foreach ( $saveOptions as $key => $value ) {
4471 # Don't bother storing default values
4472 $defaultOption = self
::getDefaultOption( $key );
4473 if ( ( is_null( $defaultOption ) &&
4474 !( $value === false ||
is_null( $value ) ) ) ||
4475 $value != $defaultOption ) {
4476 $insert_rows[] = array(
4477 'up_user' => $userId,
4478 'up_property' => $key,
4479 'up_value' => $value,
4484 $dbw = wfGetDB( DB_MASTER
);
4485 $hasRows = $dbw->selectField( 'user_properties', '1',
4486 array( 'up_user' => $userId ), __METHOD__
);
4489 // Only do this delete if there is something there. A very large portion of
4490 // calls to this function are for setting 'rememberpassword' for new accounts.
4491 // Doing this delete for new accounts with no rows in the table rougly causes
4492 // gap locks on [max user ID,+infinity) which causes high contention since many
4493 // updates will pile up on each other since they are for higher (newer) user IDs.
4494 $dbw->delete( 'user_properties', array( 'up_user' => $userId ), __METHOD__
);
4496 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
4500 * Provide an array of HTML5 attributes to put on an input element
4501 * intended for the user to enter a new password. This may include
4502 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4504 * Do *not* use this when asking the user to enter his current password!
4505 * Regardless of configuration, users may have invalid passwords for whatever
4506 * reason (e.g., they were set before requirements were tightened up).
4507 * Only use it when asking for a new password, like on account creation or
4510 * Obviously, you still need to do server-side checking.
4512 * NOTE: A combination of bugs in various browsers means that this function
4513 * actually just returns array() unconditionally at the moment. May as
4514 * well keep it around for when the browser bugs get fixed, though.
4516 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4518 * @return array Array of HTML attributes suitable for feeding to
4519 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4520 * That will potentially output invalid XHTML 1.0 Transitional, and will
4521 * get confused by the boolean attribute syntax used.)
4523 public static function passwordChangeInputAttribs() {
4524 global $wgMinimalPasswordLength;
4526 if ( $wgMinimalPasswordLength == 0 ) {
4530 # Note that the pattern requirement will always be satisfied if the
4531 # input is empty, so we need required in all cases.
4533 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4534 # if e-mail confirmation is being used. Since HTML5 input validation
4535 # is b0rked anyway in some browsers, just return nothing. When it's
4536 # re-enabled, fix this code to not output required for e-mail
4538 #$ret = array( 'required' );
4541 # We can't actually do this right now, because Opera 9.6 will print out
4542 # the entered password visibly in its error message! When other
4543 # browsers add support for this attribute, or Opera fixes its support,
4544 # we can add support with a version check to avoid doing this on Opera
4545 # versions where it will be a problem. Reported to Opera as
4546 # DSK-262266, but they don't have a public bug tracker for us to follow.
4548 if ( $wgMinimalPasswordLength > 1 ) {
4549 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4550 $ret['title'] = wfMessage( 'passwordtooshort' )
4551 ->numParams( $wgMinimalPasswordLength )->text();
4559 * Return the list of user fields that should be selected to create
4560 * a new user object.
4563 public static function selectFields() {
4570 'user_newpass_time',
4574 'user_email_authenticated',
4576 'user_email_token_expires',
4577 'user_registration',