3 * Implements the User class for the %MediaWiki software.
8 * Int Number of characters in user_token field.
11 define( 'USER_TOKEN_LENGTH', 32 );
14 * Int Serialized record version.
17 define( 'MW_USER_VERSION', 8 );
20 * String Some punctuation to prevent editing from broken text-mangling proxies.
23 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
26 * Thrown by User::setPassword() on error.
29 class PasswordError
extends MWException
{
34 * The User object encapsulates all of the user-specific settings (user_id,
35 * name, rights, password, email address, options, last login time). Client
36 * classes use the getXXX() functions to access these fields. These functions
37 * do all the work of determining whether the user is logged in,
38 * whether the requested option can be satisfied from cookies or
39 * whether a database query is needed. Most of the settings needed
40 * for rendering normal pages are set in the cookie to minimize use
45 * Global constants made accessible as class constants so that autoloader
48 const USER_TOKEN_LENGTH
= USER_TOKEN_LENGTH
;
49 const MW_USER_VERSION
= MW_USER_VERSION
;
50 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
53 * Array of Strings List of member variables which are saved to the
54 * shared cache (memcached). Any operation which changes the
55 * corresponding database fields must call a cache-clearing function.
58 static $mCacheVars = array(
69 'mEmailAuthenticated',
76 // user_properties table
81 * Array of Strings Core rights.
82 * Each of these should have a corresponding message of the form
86 static $mCoreRights = array(
105 'editusercssjs', #deprecated
117 'move-rootuserpages',
121 'override-export-depth',
142 'userrights-interwiki',
146 * String Cached results of getAllRights()
148 static $mAllRights = false;
150 /** @name Cache variables */
152 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
153 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
154 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups, $mOptionOverrides;
158 * Bool Whether the cache variables have been loaded.
162 private $mLoadedItems = array();
166 * String Initialization data source if mLoadedItems!==true. May be one of:
167 * - 'defaults' anonymous user initialised from class defaults
168 * - 'name' initialise from mName
169 * - 'id' initialise from mId
170 * - 'session' log in from cookies or session if possible
172 * Use the User::newFrom*() family of functions to set this.
177 * Lazy-initialized variables, invalidated with clearInstanceCache
179 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mRights,
180 $mBlockreason, $mEffectiveGroups, $mBlockedGlobally,
181 $mLocked, $mHideName, $mOptions;
193 static $idCacheByName = array();
196 * Lightweight constructor for an anonymous user.
197 * Use the User::newFrom* factory functions for other kinds of users.
201 * @see newFromConfirmationCode()
202 * @see newFromSession()
205 function __construct() {
206 $this->clearInstanceCache( 'defaults' );
209 function __toString(){
210 return $this->getName();
214 * Load the user table data for this object from the source given by mFrom.
217 if ( $this->mLoadedItems
=== true ) {
220 wfProfileIn( __METHOD__
);
222 # Set it now to avoid infinite recursion in accessors
223 $this->mLoadedItems
= true;
225 switch ( $this->mFrom
) {
227 $this->loadDefaults();
230 $this->mId
= self
::idFromName( $this->mName
);
232 # Nonexistent user placeholder object
233 $this->loadDefaults( $this->mName
);
242 $this->loadFromSession();
243 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
246 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
248 wfProfileOut( __METHOD__
);
252 * Load user table data, given mId has already been set.
253 * @return Bool false if the ID does not exist, true otherwise
256 function loadFromId() {
258 if ( $this->mId
== 0 ) {
259 $this->loadDefaults();
264 $key = wfMemcKey( 'user', 'id', $this->mId
);
265 $data = $wgMemc->get( $key );
266 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
267 # Object is expired, load from DB
272 wfDebug( "User: cache miss for user {$this->mId}\n" );
274 if ( !$this->loadFromDatabase() ) {
275 # Can't load from ID, user is anonymous
278 $this->saveToCache();
280 wfDebug( "User: got user {$this->mId} from cache\n" );
282 foreach ( self
::$mCacheVars as $name ) {
283 $this->$name = $data[$name];
290 * Save user data to the shared cache
292 function saveToCache() {
295 $this->loadOptions();
296 if ( $this->isAnon() ) {
297 // Anonymous users are uncached
301 foreach ( self
::$mCacheVars as $name ) {
302 $data[$name] = $this->$name;
304 $data['mVersion'] = MW_USER_VERSION
;
305 $key = wfMemcKey( 'user', 'id', $this->mId
);
307 $wgMemc->set( $key, $data );
311 /** @name newFrom*() static factory methods */
315 * Static factory method for creation from username.
317 * This is slightly less efficient than newFromId(), so use newFromId() if
318 * you have both an ID and a name handy.
320 * @param $name String Username, validated by Title::newFromText()
321 * @param $validate String|Bool Validate username. Takes the same parameters as
322 * User::getCanonicalName(), except that true is accepted as an alias
323 * for 'valid', for BC.
325 * @return User object, or false if the username is invalid
326 * (e.g. if it contains illegal characters or is an IP address). If the
327 * username is not present in the database, the result will be a user object
328 * with a name, zero user ID and default settings.
330 static function newFromName( $name, $validate = 'valid' ) {
331 if ( $validate === true ) {
334 $name = self
::getCanonicalName( $name, $validate );
335 if ( $name === false ) {
338 # Create unloaded user object
342 $u->setItemLoaded( 'name' );
348 * Static factory method for creation from a given user ID.
350 * @param $id Int Valid user ID
351 * @return User The corresponding User object
353 static function newFromId( $id ) {
357 $u->setItemLoaded( 'id' );
362 * Factory method to fetch whichever user has a given email confirmation code.
363 * This code is generated when an account is created or its e-mail address
366 * If the code is invalid or has expired, returns NULL.
368 * @param $code String Confirmation code
371 static function newFromConfirmationCode( $code ) {
372 $dbr = wfGetDB( DB_SLAVE
);
373 $id = $dbr->selectField( 'user', 'user_id', array(
374 'user_email_token' => md5( $code ),
375 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
377 if( $id !== false ) {
378 return User
::newFromId( $id );
385 * Create a new user object using data from session or cookies. If the
386 * login credentials are invalid, the result is an anonymous user.
390 static function newFromSession() {
392 $user->mFrom
= 'session';
397 * Create a new user object from a user row.
398 * The row should have the following fields from the user table in it:
399 * - either user_name or user_id to load further data if needed (or both)
401 * - all other fields (email, password, etc.)
402 * It is useless to provide the remaining fields if either user_id,
403 * user_name and user_real_name are not provided because the whole row
404 * will be loaded once more from the database when accessing them.
406 * @param $row Array A row from the user table
409 static function newFromRow( $row ) {
411 $user->loadFromRow( $row );
419 * Get the username corresponding to a given user ID
420 * @param $id Int User ID
421 * @return String The corresponding username
423 static function whoIs( $id ) {
424 $dbr = wfGetDB( DB_SLAVE
);
425 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), __METHOD__
);
429 * Get the real name of a user given their user ID
431 * @param $id Int User ID
432 * @return String The corresponding user's real name
434 static function whoIsReal( $id ) {
435 $dbr = wfGetDB( DB_SLAVE
);
436 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
440 * Get database id given a user name
441 * @param $name String Username
442 * @return Int|Null The corresponding user's ID, or null if user is nonexistent
444 static function idFromName( $name ) {
445 $nt = Title
::makeTitleSafe( NS_USER
, $name );
446 if( is_null( $nt ) ) {
451 if ( isset( self
::$idCacheByName[$name] ) ) {
452 return self
::$idCacheByName[$name];
455 $dbr = wfGetDB( DB_SLAVE
);
456 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
458 if ( $s === false ) {
461 $result = $s->user_id
;
464 self
::$idCacheByName[$name] = $result;
466 if ( count( self
::$idCacheByName ) > 1000 ) {
467 self
::$idCacheByName = array();
474 * Reset the cache used in idFromName(). For use in tests.
476 public static function resetIdByNameCache() {
477 self
::$idCacheByName = array();
481 * Does the string match an anonymous IPv4 address?
483 * This function exists for username validation, in order to reject
484 * usernames which are similar in form to IP addresses. Strings such
485 * as 300.300.300.300 will return true because it looks like an IP
486 * address, despite not being strictly valid.
488 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
489 * address because the usemod software would "cloak" anonymous IP
490 * addresses like this, if we allowed accounts like this to be created
491 * new users could get the old edits of these anonymous users.
493 * @param $name String to match
496 static function isIP( $name ) {
497 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP
::isIPv6($name);
501 * Is the input a valid username?
503 * Checks if the input is a valid username, we don't want an empty string,
504 * an IP address, anything that containins slashes (would mess up subpages),
505 * is longer than the maximum allowed username size or doesn't begin with
508 * @param $name String to match
511 static function isValidUserName( $name ) {
512 global $wgContLang, $wgMaxNameChars;
515 || User
::isIP( $name )
516 ||
strpos( $name, '/' ) !== false
517 ||
strlen( $name ) > $wgMaxNameChars
518 ||
$name != $wgContLang->ucfirst( $name ) ) {
519 wfDebugLog( 'username', __METHOD__
.
520 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
524 // Ensure that the name can't be misresolved as a different title,
525 // such as with extra namespace keys at the start.
526 $parsed = Title
::newFromText( $name );
527 if( is_null( $parsed )
528 ||
$parsed->getNamespace()
529 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
530 wfDebugLog( 'username', __METHOD__
.
531 ": '$name' invalid due to ambiguous prefixes" );
535 // Check an additional blacklist of troublemaker characters.
536 // Should these be merged into the title char list?
537 $unicodeBlacklist = '/[' .
538 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
539 '\x{00a0}' . # non-breaking space
540 '\x{2000}-\x{200f}' . # various whitespace
541 '\x{2028}-\x{202f}' . # breaks and control chars
542 '\x{3000}' . # ideographic space
543 '\x{e000}-\x{f8ff}' . # private use
545 if( preg_match( $unicodeBlacklist, $name ) ) {
546 wfDebugLog( 'username', __METHOD__
.
547 ": '$name' invalid due to blacklisted characters" );
555 * Usernames which fail to pass this function will be blocked
556 * from user login and new account registrations, but may be used
557 * internally by batch processes.
559 * If an account already exists in this form, login will be blocked
560 * by a failure to pass this function.
562 * @param $name String to match
565 static function isUsableName( $name ) {
566 global $wgReservedUsernames;
567 // Must be a valid username, obviously ;)
568 if ( !self
::isValidUserName( $name ) ) {
572 static $reservedUsernames = false;
573 if ( !$reservedUsernames ) {
574 $reservedUsernames = $wgReservedUsernames;
575 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
578 // Certain names may be reserved for batch processes.
579 foreach ( $reservedUsernames as $reserved ) {
580 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
581 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
583 if ( $reserved == $name ) {
591 * Usernames which fail to pass this function will be blocked
592 * from new account registrations, but may be used internally
593 * either by batch processes or by user accounts which have
594 * already been created.
596 * Additional blacklisting may be added here rather than in
597 * isValidUserName() to avoid disrupting existing accounts.
599 * @param $name String to match
602 static function isCreatableName( $name ) {
603 global $wgInvalidUsernameCharacters;
605 // Ensure that the username isn't longer than 235 bytes, so that
606 // (at least for the builtin skins) user javascript and css files
607 // will work. (bug 23080)
608 if( strlen( $name ) > 235 ) {
609 wfDebugLog( 'username', __METHOD__
.
610 ": '$name' invalid due to length" );
614 // Preg yells if you try to give it an empty string
615 if( $wgInvalidUsernameCharacters !== '' ) {
616 if( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
617 wfDebugLog( 'username', __METHOD__
.
618 ": '$name' invalid due to wgInvalidUsernameCharacters" );
623 return self
::isUsableName( $name );
627 * Is the input a valid password for this user?
629 * @param $password String Desired password
632 function isValidPassword( $password ) {
633 //simple boolean wrapper for getPasswordValidity
634 return $this->getPasswordValidity( $password ) === true;
638 * Given unvalidated password input, return error message on failure.
640 * @param $password String Desired password
641 * @return mixed: true on success, string or array of error message on failure
643 function getPasswordValidity( $password ) {
644 global $wgMinimalPasswordLength, $wgContLang;
646 static $blockedLogins = array(
647 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
648 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
651 $result = false; //init $result to false for the internal checks
653 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
656 if ( $result === false ) {
657 if( strlen( $password ) < $wgMinimalPasswordLength ) {
658 return 'passwordtooshort';
659 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
660 return 'password-name-match';
661 } elseif ( isset( $blockedLogins[ $this->getName() ] ) && $password == $blockedLogins[ $this->getName() ] ) {
662 return 'password-login-forbidden';
664 //it seems weird returning true here, but this is because of the
665 //initialization of $result to false above. If the hook is never run or it
666 //doesn't modify $result, then we will likely get down into this if with
670 } elseif( $result === true ) {
673 return $result; //the isValidPassword hook set a string $result and returned true
678 * Does a string look like an e-mail address?
680 * This validates an email address using an HTML5 specification found at:
681 * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
682 * Which as of 2011-01-24 says:
684 * A valid e-mail address is a string that matches the ABNF production
685 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
686 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
689 * This function is an implementation of the specification as requested in
692 * Client-side forms will use the same standard validation rules via JS or
693 * HTML 5 validation; additional restrictions can be enforced server-side
694 * by extensions via the 'isValidEmailAddr' hook.
696 * Note that this validation doesn't 100% match RFC 2822, but is believed
697 * to be liberal enough for wide use. Some invalid addresses will still
698 * pass validation here.
700 * @param $addr String E-mail address
702 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
704 public static function isValidEmailAddr( $addr ) {
705 return Sanitizer
::validateEmail( $addr );
709 * Given unvalidated user input, return a canonical username, or false if
710 * the username is invalid.
711 * @param $name String User input
712 * @param $validate String|Bool type of validation to use:
713 * - false No validation
714 * - 'valid' Valid for batch processes
715 * - 'usable' Valid for batch processes and login
716 * - 'creatable' Valid for batch processes, login and account creation
718 static function getCanonicalName( $name, $validate = 'valid' ) {
719 # Force usernames to capital
721 $name = $wgContLang->ucfirst( $name );
723 # Reject names containing '#'; these will be cleaned up
724 # with title normalisation, but then it's too late to
726 if( strpos( $name, '#' ) !== false )
729 # Clean up name according to title rules
730 $t = ( $validate === 'valid' ) ?
731 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
732 # Check for invalid titles
733 if( is_null( $t ) ) {
737 # Reject various classes of invalid names
739 $name = $wgAuth->getCanonicalName( $t->getText() );
741 switch ( $validate ) {
745 if ( !User
::isValidUserName( $name ) ) {
750 if ( !User
::isUsableName( $name ) ) {
755 if ( !User
::isCreatableName( $name ) ) {
760 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
766 * Count the number of edits of a user
767 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
769 * @param $uid Int User ID to check
770 * @return Int the user's edit count
772 static function edits( $uid ) {
773 wfProfileIn( __METHOD__
);
774 $dbr = wfGetDB( DB_SLAVE
);
775 // check if the user_editcount field has been initialized
776 $field = $dbr->selectField(
777 'user', 'user_editcount',
778 array( 'user_id' => $uid ),
782 if( $field === null ) { // it has not been initialized. do so.
783 $dbw = wfGetDB( DB_MASTER
);
784 $count = $dbr->selectField(
785 'revision', 'count(*)',
786 array( 'rev_user' => $uid ),
791 array( 'user_editcount' => $count ),
792 array( 'user_id' => $uid ),
798 wfProfileOut( __METHOD__
);
803 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
804 * @todo hash random numbers to improve security, like generateToken()
806 * @return String new random password
808 static function randomPassword() {
809 global $wgMinimalPasswordLength;
810 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
811 $l = strlen( $pwchars ) - 1;
813 $pwlength = max( 7, $wgMinimalPasswordLength );
814 $digit = mt_rand( 0, $pwlength - 1 );
816 for ( $i = 0; $i < $pwlength; $i++
) {
817 $np .= $i == $digit ?
chr( mt_rand( 48, 57 ) ) : $pwchars[ mt_rand( 0, $l ) ];
823 * Set cached properties to default.
825 * @note This no longer clears uncached lazy-initialised properties;
826 * the constructor does that instead.
829 function loadDefaults( $name = false ) {
830 wfProfileIn( __METHOD__
);
835 $this->mName
= $name;
836 $this->mRealName
= '';
837 $this->mPassword
= $this->mNewpassword
= '';
838 $this->mNewpassTime
= null;
840 $this->mOptionOverrides
= null;
841 $this->mOptionsLoaded
= false;
843 if( $wgRequest->getCookie( 'LoggedOut' ) !== null ) {
844 $this->mTouched
= wfTimestamp( TS_MW
, $wgRequest->getCookie( 'LoggedOut' ) );
846 $this->mTouched
= '0'; # Allow any pages to be cached
849 $this->setToken(); # Random
850 $this->mEmailAuthenticated
= null;
851 $this->mEmailToken
= '';
852 $this->mEmailTokenExpires
= null;
853 $this->mRegistration
= wfTimestamp( TS_MW
);
854 $this->mGroups
= array();
856 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
858 wfProfileOut( __METHOD__
);
862 * Return whether an item has been loaded.
864 * @param $item String: item to check. Current possibilities:
868 * @param $all String: 'all' to check if the whole object has been loaded
869 * or any other string to check if only the item is available (e.g.
873 public function isItemLoaded( $item, $all = 'all' ) {
874 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
875 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
879 * Set that an item has been loaded
881 * @param $item String
883 private function setItemLoaded( $item ) {
884 if ( is_array( $this->mLoadedItems
) ) {
885 $this->mLoadedItems
[$item] = true;
890 * Load user data from the session or login cookie. If there are no valid
891 * credentials, initialises the user as an anonymous user.
892 * @return Bool True if the user is logged in, false otherwise.
894 private function loadFromSession() {
895 global $wgRequest, $wgExternalAuthType, $wgAutocreatePolicy;
898 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
899 if ( $result !== null ) {
903 if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
904 $extUser = ExternalUser
::newFromCookie();
906 # TODO: Automatically create the user here (or probably a bit
907 # lower down, in fact)
911 $cookieId = $wgRequest->getCookie( 'UserID' );
912 $sessId = $wgRequest->getSessionData( 'wsUserID' );
914 if ( $cookieId !== null ) {
915 $sId = intval( $cookieId );
916 if( $sessId !== null && $cookieId != $sessId ) {
917 $this->loadDefaults(); // Possible collision!
918 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
919 cookie user ID ($sId) don't match!" );
922 $wgRequest->setSessionData( 'wsUserID', $sId );
923 } else if ( $sessId !== null && $sessId != 0 ) {
926 $this->loadDefaults();
930 if ( $wgRequest->getSessionData( 'wsUserName' ) !== null ) {
931 $sName = $wgRequest->getSessionData( 'wsUserName' );
932 } else if ( $wgRequest->getCookie( 'UserName' ) !== null ) {
933 $sName = $wgRequest->getCookie( 'UserName' );
934 $wgRequest->setSessionData( 'wsUserName', $sName );
936 $this->loadDefaults();
940 $proposedUser = User
::newFromId( $sId );
941 if ( !$proposedUser->isLoggedIn() ) {
943 $this->loadDefaults();
947 global $wgBlockDisablesLogin;
948 if( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
949 # User blocked and we've disabled blocked user logins
950 $this->loadDefaults();
954 if ( $wgRequest->getSessionData( 'wsToken' ) !== null ) {
955 $passwordCorrect = $proposedUser->getToken() === $wgRequest->getSessionData( 'wsToken' );
957 } else if ( $wgRequest->getCookie( 'Token' ) !== null ) {
958 $passwordCorrect = $proposedUser->getToken() === $wgRequest->getCookie( 'Token' );
961 # No session or persistent login cookie
962 $this->loadDefaults();
966 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
967 $this->loadFromUserObject( $proposedUser );
968 $wgRequest->setSessionData( 'wsToken', $this->mToken
);
969 wfDebug( "User: logged in from $from\n" );
972 # Invalid credentials
973 wfDebug( "User: can't log in from $from, invalid credentials\n" );
974 $this->loadDefaults();
980 * Load user and user_group data from the database.
981 * $this->mId must be set, this is how the user is identified.
983 * @return Bool True if the user exists, false if the user is anonymous
986 function loadFromDatabase() {
988 $this->mId
= intval( $this->mId
);
990 /** Anonymous user */
992 $this->loadDefaults();
996 $dbr = wfGetDB( DB_MASTER
);
997 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
999 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1001 if ( $s !== false ) {
1002 # Initialise user table data
1003 $this->loadFromRow( $s );
1004 $this->mGroups
= null; // deferred
1005 $this->getEditCount(); // revalidation for nulls
1010 $this->loadDefaults();
1016 * Initialize this object from a row from the user table.
1018 * @param $row Array Row from the user table to load.
1020 function loadFromRow( $row ) {
1023 if ( isset( $row->user_name
) ) {
1024 $this->mName
= $row->user_name
;
1025 $this->mFrom
= 'name';
1026 $this->setItemLoaded( 'name' );
1031 if ( isset( $row->user_name
) ) {
1032 $this->mRealName
= $row->user_real_name
;
1033 $this->setItemLoaded( 'realname' );
1038 if ( isset( $row->user_id
) ) {
1039 $this->mId
= intval( $row->user_id
);
1040 $this->mFrom
= 'id';
1041 $this->setItemLoaded( 'id' );
1046 if ( isset( $row->user_password
) ) {
1047 $this->mPassword
= $row->user_password
;
1048 $this->mNewpassword
= $row->user_newpassword
;
1049 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1050 $this->mEmail
= $row->user_email
;
1051 $this->decodeOptions( $row->user_options
);
1052 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
1053 $this->mToken
= $row->user_token
;
1054 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1055 $this->mEmailToken
= $row->user_email_token
;
1056 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1057 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1058 $this->mEditCount
= $row->user_editcount
;
1064 $this->mLoadedItems
= true;
1069 * Load the data for this user object from another user object.
1071 protected function loadFromUserObject( $user ) {
1073 $user->loadGroups();
1074 $user->loadOptions();
1075 foreach ( self
::$mCacheVars as $var ) {
1076 $this->$var = $user->$var;
1081 * Load the groups from the database if they aren't already loaded.
1084 function loadGroups() {
1085 if ( is_null( $this->mGroups
) ) {
1086 $dbr = wfGetDB( DB_MASTER
);
1087 $res = $dbr->select( 'user_groups',
1088 array( 'ug_group' ),
1089 array( 'ug_user' => $this->mId
),
1091 $this->mGroups
= array();
1092 foreach ( $res as $row ) {
1093 $this->mGroups
[] = $row->ug_group
;
1099 * Clear various cached data stored in this object.
1100 * @param $reloadFrom String Reload user and user_groups table data from a
1101 * given source. May be "name", "id", "defaults", "session", or false for
1104 function clearInstanceCache( $reloadFrom = false ) {
1105 $this->mNewtalk
= -1;
1106 $this->mDatePreference
= null;
1107 $this->mBlockedby
= -1; # Unset
1108 $this->mHash
= false;
1109 $this->mSkin
= null;
1110 $this->mRights
= null;
1111 $this->mEffectiveGroups
= null;
1112 $this->mOptions
= null;
1114 if ( $reloadFrom ) {
1115 $this->mLoadedItems
= array();
1116 $this->mFrom
= $reloadFrom;
1121 * Combine the language default options with any site-specific options
1122 * and add the default language variants.
1124 * @return Array of String options
1126 static function getDefaultOptions() {
1127 global $wgNamespacesToBeSearchedDefault;
1129 * Site defaults will override the global/language defaults
1131 global $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1132 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
1135 * default language setting
1137 $variant = $wgContLang->getDefaultVariant();
1138 $defOpt['variant'] = $variant;
1139 $defOpt['language'] = $variant;
1140 foreach( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1141 $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1143 $defOpt['skin'] = $wgDefaultSkin;
1149 * Get a given default option value.
1151 * @param $opt String Name of option to retrieve
1152 * @return String Default option value
1154 public static function getDefaultOption( $opt ) {
1155 $defOpts = self
::getDefaultOptions();
1156 if( isset( $defOpts[$opt] ) ) {
1157 return $defOpts[$opt];
1165 * Get blocking information
1167 * @param $bFromSlave Bool Whether to check the slave database first. To
1168 * improve performance, non-critical checks are done
1169 * against slaves. Check when actually saving should be
1170 * done against master.
1172 function getBlockedStatus( $bFromSlave = true ) {
1173 global $wgProxyWhitelist, $wgUser;
1175 if ( -1 != $this->mBlockedby
) {
1179 wfProfileIn( __METHOD__
);
1180 wfDebug( __METHOD__
.": checking...\n" );
1182 // Initialize data...
1183 // Otherwise something ends up stomping on $this->mBlockedby when
1184 // things get lazy-loaded later, causing false positive block hits
1185 // due to -1 !== 0. Probably session-related... Nothing should be
1186 // overwriting mBlockedby, surely?
1189 $this->mBlockedby
= 0;
1190 $this->mHideName
= 0;
1191 $this->mAllowUsertalk
= 0;
1193 # We only need to worry about passing the IP address to the Block generator if the
1194 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1195 # know which IP address they're actually coming from
1196 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1203 $this->mBlock
= Block
::newFromTarget( $this->getName(), $ip, !$bFromSlave );
1204 if ( $this->mBlock
instanceof Block
) {
1205 wfDebug( __METHOD__
. ": Found block.\n" );
1206 $this->mBlockedby
= $this->mBlock
->getBlocker()->getName();
1207 $this->mBlockreason
= $this->mBlock
->mReason
;
1208 $this->mHideName
= $this->mBlock
->mHideName
;
1209 $this->mAllowUsertalk
= !$this->mBlock
->prevents( 'editownusertalk' );
1210 if ( $this->isLoggedIn() && $wgUser->getID() == $this->getID() ) {
1211 $this->spreadBlock();
1216 if ( !$this->isAllowed( 'proxyunbannable' ) && !in_array( $ip, $wgProxyWhitelist ) ) {
1218 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1219 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1220 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1224 if ( !$this->mBlockedby
&& !$this->getID() ) {
1225 if ( $this->isDnsBlacklisted( $ip ) ) {
1226 $this->mBlockedby
= wfMsg( 'sorbs' );
1227 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1233 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1235 wfProfileOut( __METHOD__
);
1239 * Whether the given IP is in a DNS blacklist.
1241 * @param $ip String IP to check
1242 * @param $checkWhitelist Bool: whether to check the whitelist first
1243 * @return Bool True if blacklisted.
1245 function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1246 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1247 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1249 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
1252 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
1255 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1256 return $this->inDnsBlacklist( $ip, $urls );
1260 * Whether the given IP is in a given DNS blacklist.
1262 * @param $ip String IP to check
1263 * @param $bases String|Array of Strings: URL of the DNS blacklist
1264 * @return Bool True if blacklisted.
1266 function inDnsBlacklist( $ip, $bases ) {
1267 wfProfileIn( __METHOD__
);
1270 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1271 if( IP
::isIPv4( $ip ) ) {
1272 # Reverse IP, bug 21255
1273 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1275 foreach( (array)$bases as $base ) {
1277 $host = "$ipReversed.$base";
1280 $ipList = gethostbynamel( $host );
1283 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1287 wfDebug( "Requested $host, not found in $base.\n" );
1292 wfProfileOut( __METHOD__
);
1297 * Is this user subject to rate limiting?
1299 * @return Bool True if rate limited
1301 public function isPingLimitable() {
1302 global $wgRateLimitsExcludedGroups;
1303 global $wgRateLimitsExcludedIPs;
1304 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1305 // Deprecated, but kept for backwards-compatibility config
1308 if( in_array( wfGetIP(), $wgRateLimitsExcludedIPs ) ) {
1309 // No other good way currently to disable rate limits
1310 // for specific IPs. :P
1311 // But this is a crappy hack and should die.
1314 return !$this->isAllowed('noratelimit');
1318 * Primitive rate limits: enforce maximum actions per time period
1319 * to put a brake on flooding.
1321 * @note When using a shared cache like memcached, IP-address
1322 * last-hit counters will be shared across wikis.
1324 * @param $action String Action to enforce; 'edit' if unspecified
1325 * @return Bool True if a rate limiter was tripped
1327 function pingLimiter( $action = 'edit' ) {
1328 # Call the 'PingLimiter' hook
1330 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1334 global $wgRateLimits;
1335 if( !isset( $wgRateLimits[$action] ) ) {
1339 # Some groups shouldn't trigger the ping limiter, ever
1340 if( !$this->isPingLimitable() )
1343 global $wgMemc, $wgRateLimitLog;
1344 wfProfileIn( __METHOD__
);
1346 $limits = $wgRateLimits[$action];
1348 $id = $this->getId();
1352 if( isset( $limits['anon'] ) && $id == 0 ) {
1353 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1356 if( isset( $limits['user'] ) && $id != 0 ) {
1357 $userLimit = $limits['user'];
1359 if( $this->isNewbie() ) {
1360 if( isset( $limits['newbie'] ) && $id != 0 ) {
1361 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1363 if( isset( $limits['ip'] ) ) {
1364 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1367 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1368 $subnet = $matches[1];
1369 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1372 // Check for group-specific permissions
1373 // If more than one group applies, use the group with the highest limit
1374 foreach ( $this->getGroups() as $group ) {
1375 if ( isset( $limits[$group] ) ) {
1376 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1377 $userLimit = $limits[$group];
1381 // Set the user limit key
1382 if ( $userLimit !== false ) {
1383 wfDebug( __METHOD__
. ": effective user limit: $userLimit\n" );
1384 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1388 foreach( $keys as $key => $limit ) {
1389 list( $max, $period ) = $limit;
1390 $summary = "(limit $max in {$period}s)";
1391 $count = $wgMemc->get( $key );
1394 if( $count > $max ) {
1395 wfDebug( __METHOD__
. ": tripped! $key at $count $summary\n" );
1396 if( $wgRateLimitLog ) {
1397 @file_put_contents
( $wgRateLimitLog, wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", FILE_APPEND
);
1401 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1404 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1405 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1407 $wgMemc->incr( $key );
1410 wfProfileOut( __METHOD__
);
1415 * Check if user is blocked
1417 * @param $bFromSlave Bool Whether to check the slave database instead of the master
1418 * @return Bool True if blocked, false otherwise
1420 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1421 $this->getBlockedStatus( $bFromSlave );
1422 return $this->mBlock
instanceof Block
&& $this->mBlock
->prevents( 'edit' );
1426 * Check if user is blocked from editing a particular article
1428 * @param $title Title to check
1429 * @param $bFromSlave Bool whether to check the slave database instead of the master
1432 function isBlockedFrom( $title, $bFromSlave = false ) {
1433 global $wgBlockAllowsUTEdit;
1434 wfProfileIn( __METHOD__
);
1436 $blocked = $this->isBlocked( $bFromSlave );
1437 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1438 # If a user's name is suppressed, they cannot make edits anywhere
1439 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1440 $title->getNamespace() == NS_USER_TALK
) {
1442 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1445 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1447 wfProfileOut( __METHOD__
);
1452 * If user is blocked, return the name of the user who placed the block
1453 * @return String name of blocker
1455 function blockedBy() {
1456 $this->getBlockedStatus();
1457 return $this->mBlockedby
;
1461 * If user is blocked, return the specified reason for the block
1462 * @return String Blocking reason
1464 function blockedFor() {
1465 $this->getBlockedStatus();
1466 return $this->mBlockreason
;
1470 * If user is blocked, return the ID for the block
1471 * @return Int Block ID
1473 function getBlockId() {
1474 $this->getBlockedStatus();
1475 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1479 * Check if user is blocked on all wikis.
1480 * Do not use for actual edit permission checks!
1481 * This is intented for quick UI checks.
1483 * @param $ip String IP address, uses current client if none given
1484 * @return Bool True if blocked, false otherwise
1486 function isBlockedGlobally( $ip = '' ) {
1487 if( $this->mBlockedGlobally
!== null ) {
1488 return $this->mBlockedGlobally
;
1490 // User is already an IP?
1491 if( IP
::isIPAddress( $this->getName() ) ) {
1492 $ip = $this->getName();
1497 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1498 $this->mBlockedGlobally
= (bool)$blocked;
1499 return $this->mBlockedGlobally
;
1503 * Check if user account is locked
1505 * @return Bool True if locked, false otherwise
1507 function isLocked() {
1508 if( $this->mLocked
!== null ) {
1509 return $this->mLocked
;
1512 $authUser = $wgAuth->getUserInstance( $this );
1513 $this->mLocked
= (bool)$authUser->isLocked();
1514 return $this->mLocked
;
1518 * Check if user account is hidden
1520 * @return Bool True if hidden, false otherwise
1522 function isHidden() {
1523 if( $this->mHideName
!== null ) {
1524 return $this->mHideName
;
1526 $this->getBlockedStatus();
1527 if( !$this->mHideName
) {
1529 $authUser = $wgAuth->getUserInstance( $this );
1530 $this->mHideName
= (bool)$authUser->isHidden();
1532 return $this->mHideName
;
1536 * Get the user's ID.
1537 * @return Int The user's ID; 0 if the user is anonymous or nonexistent
1540 if( $this->mId
=== null && $this->mName
!== null
1541 && User
::isIP( $this->mName
) ) {
1542 // Special case, we know the user is anonymous
1544 } elseif( !$this->isItemLoaded( 'id' ) ) {
1545 // Don't load if this was initialized from an ID
1552 * Set the user and reload all fields according to a given ID
1553 * @param $v Int User ID to reload
1555 function setId( $v ) {
1557 $this->clearInstanceCache( 'id' );
1561 * Get the user name, or the IP of an anonymous user
1562 * @return String User's name or IP address
1564 function getName() {
1565 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1566 # Special case optimisation
1567 return $this->mName
;
1570 if ( $this->mName
=== false ) {
1572 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1574 return $this->mName
;
1579 * Set the user name.
1581 * This does not reload fields from the database according to the given
1582 * name. Rather, it is used to create a temporary "nonexistent user" for
1583 * later addition to the database. It can also be used to set the IP
1584 * address for an anonymous user to something other than the current
1587 * @note User::newFromName() has rougly the same function, when the named user
1589 * @param $str String New user name to set
1591 function setName( $str ) {
1593 $this->mName
= $str;
1597 * Get the user's name escaped by underscores.
1598 * @return String Username escaped by underscores.
1600 function getTitleKey() {
1601 return str_replace( ' ', '_', $this->getName() );
1605 * Check if the user has new messages.
1606 * @return Bool True if the user has new messages
1608 function getNewtalk() {
1611 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1612 if( $this->mNewtalk
=== -1 ) {
1613 $this->mNewtalk
= false; # reset talk page status
1615 # Check memcached separately for anons, who have no
1616 # entire User object stored in there.
1619 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1620 $newtalk = $wgMemc->get( $key );
1621 if( strval( $newtalk ) !== '' ) {
1622 $this->mNewtalk
= (bool)$newtalk;
1624 // Since we are caching this, make sure it is up to date by getting it
1626 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1627 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1630 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1634 return (bool)$this->mNewtalk
;
1638 * Return the talk page(s) this user has new messages on.
1639 * @return Array of String page URLs
1641 function getNewMessageLinks() {
1643 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) )
1646 if( !$this->getNewtalk() )
1648 $up = $this->getUserPage();
1649 $utp = $up->getTalkPage();
1650 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL() ) );
1654 * Internal uncached check for new messages
1657 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1658 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1659 * @param $fromMaster Bool true to fetch from the master, false for a slave
1660 * @return Bool True if the user has new messages
1663 function checkNewtalk( $field, $id, $fromMaster = false ) {
1664 if ( $fromMaster ) {
1665 $db = wfGetDB( DB_MASTER
);
1667 $db = wfGetDB( DB_SLAVE
);
1669 $ok = $db->selectField( 'user_newtalk', $field,
1670 array( $field => $id ), __METHOD__
);
1671 return $ok !== false;
1675 * Add or update the new messages flag
1676 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1677 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1678 * @return Bool True if successful, false otherwise
1681 function updateNewtalk( $field, $id ) {
1682 $dbw = wfGetDB( DB_MASTER
);
1683 $dbw->insert( 'user_newtalk',
1684 array( $field => $id ),
1687 if ( $dbw->affectedRows() ) {
1688 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
1691 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
1697 * Clear the new messages flag for the given user
1698 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1699 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1700 * @return Bool True if successful, false otherwise
1703 function deleteNewtalk( $field, $id ) {
1704 $dbw = wfGetDB( DB_MASTER
);
1705 $dbw->delete( 'user_newtalk',
1706 array( $field => $id ),
1708 if ( $dbw->affectedRows() ) {
1709 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
1712 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
1718 * Update the 'You have new messages!' status.
1719 * @param $val Bool Whether the user has new messages
1721 function setNewtalk( $val ) {
1722 if( wfReadOnly() ) {
1727 $this->mNewtalk
= $val;
1729 if( $this->isAnon() ) {
1731 $id = $this->getName();
1734 $id = $this->getId();
1739 $changed = $this->updateNewtalk( $field, $id );
1741 $changed = $this->deleteNewtalk( $field, $id );
1744 if( $this->isAnon() ) {
1745 // Anons have a separate memcached space, since
1746 // user records aren't kept for them.
1747 $key = wfMemcKey( 'newtalk', 'ip', $id );
1748 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1751 $this->invalidateCache( true );
1756 * Generate a current or new-future timestamp to be stored in the
1757 * user_touched field when we update things.
1758 * @return String Timestamp in TS_MW format
1760 private static function newTouchedTimestamp() {
1761 global $wgClockSkewFudge;
1762 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1766 * Clear user data from memcached.
1767 * Use after applying fun updates to the database; caller's
1768 * responsibility to update user_touched if appropriate.
1770 * Called implicitly from invalidateCache() and saveSettings().
1772 private function clearSharedCache() {
1776 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1781 * Immediately touch the user data cache for this account.
1782 * Updates user_touched field, and removes account data from memcached
1783 * for reload on the next hit.
1785 * @param $doDatabaseUpdate bool Do you really need to update the database? Really?
1787 function invalidateCache( $doDatabaseUpdate = false ) {
1788 if( wfReadOnly() ) {
1792 if( $this->mId
&& $doDatabaseUpdate ) {
1793 $this->mTouched
= self
::newTouchedTimestamp();
1795 $dbw = wfGetDB( DB_MASTER
);
1796 $dbw->update( 'user',
1797 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1798 array( 'user_id' => $this->mId
),
1801 $this->clearSharedCache();
1806 * Validate the cache for this account.
1807 * @param $timestamp String A timestamp in TS_MW format
1809 function validateCache( $timestamp ) {
1811 return ( $timestamp >= $this->mTouched
);
1815 * Get the user touched timestamp
1816 * @return String timestamp
1818 function getTouched() {
1820 return $this->mTouched
;
1824 * Set the password and reset the random token.
1825 * Calls through to authentication plugin if necessary;
1826 * will have no effect if the auth plugin refuses to
1827 * pass the change through or if the legal password
1830 * As a special case, setting the password to null
1831 * wipes it, so the account cannot be logged in until
1832 * a new password is set, for instance via e-mail.
1834 * @param $str String New password to set
1835 * @throws PasswordError on failure
1837 function setPassword( $str ) {
1840 if( $str !== null ) {
1841 if( !$wgAuth->allowPasswordChange() ) {
1842 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1845 if( !$this->isValidPassword( $str ) ) {
1846 global $wgMinimalPasswordLength;
1847 $valid = $this->getPasswordValidity( $str );
1848 if ( is_array( $valid ) ) {
1849 $message = array_shift( $valid );
1853 $params = array( $wgMinimalPasswordLength );
1855 throw new PasswordError( wfMsgExt( $message, array( 'parsemag' ), $params ) );
1859 if( !$wgAuth->setPassword( $this, $str ) ) {
1860 throw new PasswordError( wfMsg( 'externaldberror' ) );
1863 $this->setInternalPassword( $str );
1869 * Set the password and reset the random token unconditionally.
1871 * @param $str String New password to set
1873 function setInternalPassword( $str ) {
1877 if( $str === null ) {
1878 // Save an invalid hash...
1879 $this->mPassword
= '';
1881 $this->mPassword
= self
::crypt( $str );
1883 $this->mNewpassword
= '';
1884 $this->mNewpassTime
= null;
1888 * Get the user's current token.
1889 * @return String Token
1891 function getToken() {
1893 return $this->mToken
;
1897 * Set the random token (used for persistent authentication)
1898 * Called from loadDefaults() among other places.
1900 * @param $token String If specified, set the token to this value
1903 function setToken( $token = false ) {
1904 global $wgSecretKey, $wgProxyKey;
1907 if ( $wgSecretKey ) {
1908 $key = $wgSecretKey;
1909 } elseif ( $wgProxyKey ) {
1914 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1916 $this->mToken
= $token;
1921 * Set the cookie password
1923 * @param $str String New cookie password
1926 function setCookiePassword( $str ) {
1928 $this->mCookiePassword
= md5( $str );
1932 * Set the password for a password reminder or new account email
1934 * @param $str String New password to set
1935 * @param $throttle Bool If true, reset the throttle timestamp to the present
1937 function setNewpassword( $str, $throttle = true ) {
1939 $this->mNewpassword
= self
::crypt( $str );
1941 $this->mNewpassTime
= wfTimestampNow();
1946 * Has password reminder email been sent within the last
1947 * $wgPasswordReminderResendTime hours?
1950 function isPasswordReminderThrottled() {
1951 global $wgPasswordReminderResendTime;
1953 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1956 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1957 return time() < $expiry;
1961 * Get the user's e-mail address
1962 * @return String User's email address
1964 function getEmail() {
1966 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1967 return $this->mEmail
;
1971 * Get the timestamp of the user's e-mail authentication
1972 * @return String TS_MW timestamp
1974 function getEmailAuthenticationTimestamp() {
1976 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1977 return $this->mEmailAuthenticated
;
1981 * Set the user's e-mail address
1982 * @param $str String New e-mail address
1984 function setEmail( $str ) {
1986 $this->mEmail
= $str;
1987 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1991 * Get the user's real name
1992 * @return String User's real name
1994 function getRealName() {
1995 if ( !$this->isItemLoaded( 'realname' ) ) {
1999 return $this->mRealName
;
2003 * Set the user's real name
2004 * @param $str String New real name
2006 function setRealName( $str ) {
2008 $this->mRealName
= $str;
2012 * Get the user's current setting for a given option.
2014 * @param $oname String The option to check
2015 * @param $defaultOverride String A default value returned if the option does not exist
2016 * @param $ignoreHidden Bool = whether to ignore the effects of $wgHiddenPrefs
2017 * @return String User's current value for the option
2018 * @see getBoolOption()
2019 * @see getIntOption()
2021 function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2022 global $wgHiddenPrefs;
2023 $this->loadOptions();
2025 if ( is_null( $this->mOptions
) ) {
2026 if($defaultOverride != '') {
2027 return $defaultOverride;
2029 $this->mOptions
= User
::getDefaultOptions();
2032 # We want 'disabled' preferences to always behave as the default value for
2033 # users, even if they have set the option explicitly in their settings (ie they
2034 # set it, and then it was disabled removing their ability to change it). But
2035 # we don't want to erase the preferences in the database in case the preference
2036 # is re-enabled again. So don't touch $mOptions, just override the returned value
2037 if( in_array( $oname, $wgHiddenPrefs ) && !$ignoreHidden ){
2038 return self
::getDefaultOption( $oname );
2041 if ( array_key_exists( $oname, $this->mOptions
) ) {
2042 return $this->mOptions
[$oname];
2044 return $defaultOverride;
2049 * Get all user's options
2053 public function getOptions() {
2054 global $wgHiddenPrefs;
2055 $this->loadOptions();
2056 $options = $this->mOptions
;
2058 # We want 'disabled' preferences to always behave as the default value for
2059 # users, even if they have set the option explicitly in their settings (ie they
2060 # set it, and then it was disabled removing their ability to change it). But
2061 # we don't want to erase the preferences in the database in case the preference
2062 # is re-enabled again. So don't touch $mOptions, just override the returned value
2063 foreach( $wgHiddenPrefs as $pref ){
2064 $default = self
::getDefaultOption( $pref );
2065 if( $default !== null ){
2066 $options[$pref] = $default;
2074 * Get the user's current setting for a given option, as a boolean value.
2076 * @param $oname String The option to check
2077 * @return Bool User's current value for the option
2080 function getBoolOption( $oname ) {
2081 return (bool)$this->getOption( $oname );
2086 * Get the user's current setting for a given option, as a boolean value.
2088 * @param $oname String The option to check
2089 * @param $defaultOverride Int A default value returned if the option does not exist
2090 * @return Int User's current value for the option
2093 function getIntOption( $oname, $defaultOverride=0 ) {
2094 $val = $this->getOption( $oname );
2096 $val = $defaultOverride;
2098 return intval( $val );
2102 * Set the given option for a user.
2104 * @param $oname String The option to set
2105 * @param $val mixed New value to set
2107 function setOption( $oname, $val ) {
2109 $this->loadOptions();
2111 if ( $oname == 'skin' ) {
2112 # Clear cached skin, so the new one displays immediately in Special:Preferences
2113 $this->mSkin
= null;
2116 // Explicitly NULL values should refer to defaults
2117 global $wgDefaultUserOptions;
2118 if( is_null( $val ) && isset( $wgDefaultUserOptions[$oname] ) ) {
2119 $val = $wgDefaultUserOptions[$oname];
2122 $this->mOptions
[$oname] = $val;
2126 * Reset all options to the site defaults
2128 function resetOptions() {
2129 $this->mOptions
= self
::getDefaultOptions();
2133 * Get the user's preferred date format.
2134 * @return String User's preferred date format
2136 function getDatePreference() {
2137 // Important migration for old data rows
2138 if ( is_null( $this->mDatePreference
) ) {
2140 $value = $this->getOption( 'date' );
2141 $map = $wgLang->getDatePreferenceMigrationMap();
2142 if ( isset( $map[$value] ) ) {
2143 $value = $map[$value];
2145 $this->mDatePreference
= $value;
2147 return $this->mDatePreference
;
2151 * Get the user preferred stub threshold
2153 function getStubThreshold() {
2154 global $wgMaxArticleSize; # Maximum article size, in Kb
2155 $threshold = intval( $this->getOption( 'stubthreshold' ) );
2156 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2157 # If they have set an impossible value, disable the preference
2158 # so we can use the parser cache again.
2165 * Get the permissions this user has.
2166 * @return Array of String permission names
2168 function getRights() {
2169 if ( is_null( $this->mRights
) ) {
2170 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2171 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2172 // Force reindexation of rights when a hook has unset one of them
2173 $this->mRights
= array_values( $this->mRights
);
2175 return $this->mRights
;
2179 * Get the list of explicit group memberships this user has.
2180 * The implicit * and user groups are not included.
2181 * @return Array of String internal group names
2183 function getGroups() {
2185 return $this->mGroups
;
2189 * Get the list of implicit group memberships this user has.
2190 * This includes all explicit groups, plus 'user' if logged in,
2191 * '*' for all accounts, and autopromoted groups
2192 * @param $recache Bool Whether to avoid the cache
2193 * @return Array of String internal group names
2195 function getEffectiveGroups( $recache = false ) {
2196 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2197 wfProfileIn( __METHOD__
);
2198 $this->mEffectiveGroups
= $this->getGroups();
2199 $this->mEffectiveGroups
[] = '*';
2200 if( $this->getId() ) {
2201 $this->mEffectiveGroups
[] = 'user';
2203 $this->mEffectiveGroups
= array_unique( array_merge(
2204 $this->mEffectiveGroups
,
2205 Autopromote
::getAutopromoteGroups( $this )
2208 # Hook for additional groups
2209 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2211 wfProfileOut( __METHOD__
);
2213 return $this->mEffectiveGroups
;
2217 * Get the user's edit count.
2220 function getEditCount() {
2221 if( $this->getId() ) {
2222 if ( !isset( $this->mEditCount
) ) {
2223 /* Populate the count, if it has not been populated yet */
2224 $this->mEditCount
= User
::edits( $this->mId
);
2226 return $this->mEditCount
;
2234 * Add the user to the given group.
2235 * This takes immediate effect.
2236 * @param $group String Name of the group to add
2238 function addGroup( $group ) {
2239 if( wfRunHooks( 'UserAddGroup', array( &$this, &$group ) ) ) {
2240 $dbw = wfGetDB( DB_MASTER
);
2241 if( $this->getId() ) {
2242 $dbw->insert( 'user_groups',
2244 'ug_user' => $this->getID(),
2245 'ug_group' => $group,
2248 array( 'IGNORE' ) );
2251 $this->loadGroups();
2252 $this->mGroups
[] = $group;
2253 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2255 $this->invalidateCache( true );
2259 * Remove the user from the given group.
2260 * This takes immediate effect.
2261 * @param $group String Name of the group to remove
2263 function removeGroup( $group ) {
2265 if( wfRunHooks( 'UserRemoveGroup', array( &$this, &$group ) ) ) {
2266 $dbw = wfGetDB( DB_MASTER
);
2267 $dbw->delete( 'user_groups',
2269 'ug_user' => $this->getID(),
2270 'ug_group' => $group,
2273 $this->loadGroups();
2274 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2275 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2277 $this->invalidateCache( true );
2281 * Get whether the user is logged in
2284 function isLoggedIn() {
2285 return $this->getID() != 0;
2289 * Get whether the user is anonymous
2293 return !$this->isLoggedIn();
2297 * Check if user is allowed to access a feature / make an action
2298 * @param varargs String permissions to test
2299 * @return Boolean: True if user is allowed to perform *any* of the given actions
2301 public function isAllowedAny( /*...*/ ){
2302 $permissions = func_get_args();
2303 foreach( $permissions as $permission ){
2304 if( $this->isAllowed( $permission ) ){
2312 * @param varargs String
2313 * @return bool True if the user is allowed to perform *all* of the given actions
2315 public function isAllowedAll( /*...*/ ){
2316 $permissions = func_get_args();
2317 foreach( $permissions as $permission ){
2318 if( !$this->isAllowed( $permission ) ){
2326 * Internal mechanics of testing a permission
2327 * @param $action String
2330 public function isAllowed( $action = '' ) {
2331 if ( $action === '' ) {
2332 return true; // In the spirit of DWIM
2334 # Patrolling may not be enabled
2335 if( $action === 'patrol' ||
$action === 'autopatrol' ) {
2336 global $wgUseRCPatrol, $wgUseNPPatrol;
2337 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2340 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2341 # by misconfiguration: 0 == 'foo'
2342 return in_array( $action, $this->getRights(), true );
2346 * Check whether to enable recent changes patrol features for this user
2347 * @return Boolean: True or false
2349 public function useRCPatrol() {
2350 global $wgUseRCPatrol;
2351 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
2355 * Check whether to enable new pages patrol features for this user
2356 * @return Bool True or false
2358 public function useNPPatrol() {
2359 global $wgUseRCPatrol, $wgUseNPPatrol;
2360 return( ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) ) );
2364 * Get the current skin, loading it if required
2365 * @return Skin The current skin
2366 * @todo: FIXME : need to check the old failback system [AV]
2367 * @deprecated Use ->getSkin() in the most relevant outputting context you have
2369 function getSkin() {
2370 return RequestContext
::getMain()->getSkin();
2374 * Check the watched status of an article.
2375 * @param $title Title of the article to look at
2378 function isWatched( $title ) {
2379 $wl = WatchedItem
::fromUserTitle( $this, $title );
2380 return $wl->isWatched();
2385 * @param $title Title of the article to look at
2387 function addWatch( $title ) {
2388 $wl = WatchedItem
::fromUserTitle( $this, $title );
2390 $this->invalidateCache();
2394 * Stop watching an article.
2395 * @param $title Title of the article to look at
2397 function removeWatch( $title ) {
2398 $wl = WatchedItem
::fromUserTitle( $this, $title );
2400 $this->invalidateCache();
2404 * Clear the user's notification timestamp for the given title.
2405 * If e-notif e-mails are on, they will receive notification mails on
2406 * the next change of the page if it's watched etc.
2407 * @param $title Title of the article to look at
2409 function clearNotification( &$title ) {
2410 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2412 # Do nothing if the database is locked to writes
2413 if( wfReadOnly() ) {
2417 if( $title->getNamespace() == NS_USER_TALK
&&
2418 $title->getText() == $this->getName() ) {
2419 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2421 $this->setNewtalk( false );
2424 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2428 if( $this->isAnon() ) {
2429 // Nothing else to do...
2433 // Only update the timestamp if the page is being watched.
2434 // The query to find out if it is watched is cached both in memcached and per-invocation,
2435 // and when it does have to be executed, it can be on a slave
2436 // If this is the user's newtalk page, we always update the timestamp
2437 if( $title->getNamespace() == NS_USER_TALK
&&
2438 $title->getText() == $wgUser->getName() )
2441 } elseif ( $this->getId() == $wgUser->getId() ) {
2442 $watched = $title->userIsWatching();
2447 // If the page is watched by the user (or may be watched), update the timestamp on any
2448 // any matching rows
2450 $dbw = wfGetDB( DB_MASTER
);
2451 $dbw->update( 'watchlist',
2453 'wl_notificationtimestamp' => null
2454 ), array( /* WHERE */
2455 'wl_title' => $title->getDBkey(),
2456 'wl_namespace' => $title->getNamespace(),
2457 'wl_user' => $this->getID()
2464 * Resets all of the given user's page-change notification timestamps.
2465 * If e-notif e-mails are on, they will receive notification mails on
2466 * the next change of any watched page.
2468 * @param $currentUser Int User ID
2470 function clearAllNotifications( $currentUser ) {
2471 global $wgUseEnotif, $wgShowUpdatedMarker;
2472 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2473 $this->setNewtalk( false );
2476 if( $currentUser != 0 ) {
2477 $dbw = wfGetDB( DB_MASTER
);
2478 $dbw->update( 'watchlist',
2480 'wl_notificationtimestamp' => null
2481 ), array( /* WHERE */
2482 'wl_user' => $currentUser
2485 # We also need to clear here the "you have new message" notification for the own user_talk page
2486 # This is cleared one page view later in Article::viewUpdates();
2491 * Set this user's options from an encoded string
2492 * @param $str String Encoded options to import
2495 function decodeOptions( $str ) {
2499 $this->mOptionsLoaded
= true;
2500 $this->mOptionOverrides
= array();
2502 // If an option is not set in $str, use the default value
2503 $this->mOptions
= self
::getDefaultOptions();
2505 $a = explode( "\n", $str );
2506 foreach ( $a as $s ) {
2508 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2509 $this->mOptions
[$m[1]] = $m[2];
2510 $this->mOptionOverrides
[$m[1]] = $m[2];
2516 * Set a cookie on the user's client. Wrapper for
2517 * WebResponse::setCookie
2518 * @param $name String Name of the cookie to set
2519 * @param $value String Value to set
2520 * @param $exp Int Expiration time, as a UNIX time value;
2521 * if 0 or not specified, use the default $wgCookieExpiration
2523 protected function setCookie( $name, $value, $exp = 0 ) {
2525 $wgRequest->response()->setcookie( $name, $value, $exp );
2529 * Clear a cookie on the user's client
2530 * @param $name String Name of the cookie to clear
2532 protected function clearCookie( $name ) {
2533 $this->setCookie( $name, '', time() - 86400 );
2537 * Set the default cookies for this session on the user's client.
2539 * @param $request WebRequest object to use; $wgRequest will be used if null
2542 function setCookies( $request = null ) {
2543 if ( $request === null ) {
2545 $request = $wgRequest;
2549 if ( 0 == $this->mId
) return;
2551 'wsUserID' => $this->mId
,
2552 'wsToken' => $this->mToken
,
2553 'wsUserName' => $this->getName()
2556 'UserID' => $this->mId
,
2557 'UserName' => $this->getName(),
2559 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2560 $cookies['Token'] = $this->mToken
;
2562 $cookies['Token'] = false;
2565 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2567 foreach ( $session as $name => $value ) {
2568 $request->setSessionData( $name, $value );
2570 foreach ( $cookies as $name => $value ) {
2571 if ( $value === false ) {
2572 $this->clearCookie( $name );
2574 $this->setCookie( $name, $value );
2580 * Log this user out.
2583 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
2589 * Clear the user's cookies and session, and reset the instance cache.
2593 function doLogout() {
2596 $this->clearInstanceCache( 'defaults' );
2598 $wgRequest->setSessionData( 'wsUserID', 0 );
2600 $this->clearCookie( 'UserID' );
2601 $this->clearCookie( 'Token' );
2603 # Remember when user logged out, to prevent seeing cached pages
2604 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2608 * Save this user's settings into the database.
2609 * @todo Only rarely do all these fields need to be set!
2611 function saveSettings() {
2613 if ( wfReadOnly() ) { return; }
2614 if ( 0 == $this->mId
) { return; }
2616 $this->mTouched
= self
::newTouchedTimestamp();
2618 $dbw = wfGetDB( DB_MASTER
);
2619 $dbw->update( 'user',
2621 'user_name' => $this->mName
,
2622 'user_password' => $this->mPassword
,
2623 'user_newpassword' => $this->mNewpassword
,
2624 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2625 'user_real_name' => $this->mRealName
,
2626 'user_email' => $this->mEmail
,
2627 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2628 'user_options' => '',
2629 'user_touched' => $dbw->timestamp( $this->mTouched
),
2630 'user_token' => $this->mToken
,
2631 'user_email_token' => $this->mEmailToken
,
2632 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2633 ), array( /* WHERE */
2634 'user_id' => $this->mId
2638 $this->saveOptions();
2640 wfRunHooks( 'UserSaveSettings', array( $this ) );
2641 $this->clearSharedCache();
2642 $this->getUserPage()->invalidateCache();
2646 * If only this user's username is known, and it exists, return the user ID.
2649 function idForName() {
2650 $s = trim( $this->getName() );
2651 if ( $s === '' ) return 0;
2653 $dbr = wfGetDB( DB_SLAVE
);
2654 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2655 if ( $id === false ) {
2662 * Add a user to the database, return the user object
2664 * @param $name String Username to add
2665 * @param $params Array of Strings Non-default parameters to save to the database as user_* fields:
2666 * - password The user's password hash. Password logins will be disabled if this is omitted.
2667 * - newpassword Hash for a temporary password that has been mailed to the user
2668 * - email The user's email address
2669 * - email_authenticated The email authentication timestamp
2670 * - real_name The user's real name
2671 * - options An associative array of non-default options
2672 * - token Random authentication token. Do not set.
2673 * - registration Registration timestamp. Do not set.
2675 * @return User object, or null if the username already exists
2677 static function createNew( $name, $params = array() ) {
2680 if ( isset( $params['options'] ) ) {
2681 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
2682 unset( $params['options'] );
2684 $dbw = wfGetDB( DB_MASTER
);
2685 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2688 'user_id' => $seqVal,
2689 'user_name' => $name,
2690 'user_password' => $user->mPassword
,
2691 'user_newpassword' => $user->mNewpassword
,
2692 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
2693 'user_email' => $user->mEmail
,
2694 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2695 'user_real_name' => $user->mRealName
,
2696 'user_options' => '',
2697 'user_token' => $user->mToken
,
2698 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2699 'user_editcount' => 0,
2701 foreach ( $params as $name => $value ) {
2702 $fields["user_$name"] = $value;
2704 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2705 if ( $dbw->affectedRows() ) {
2706 $newUser = User
::newFromId( $dbw->insertId() );
2714 * Add this existing user object to the database
2716 function addToDatabase() {
2718 $dbw = wfGetDB( DB_MASTER
);
2719 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2720 $dbw->insert( 'user',
2722 'user_id' => $seqVal,
2723 'user_name' => $this->mName
,
2724 'user_password' => $this->mPassword
,
2725 'user_newpassword' => $this->mNewpassword
,
2726 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2727 'user_email' => $this->mEmail
,
2728 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2729 'user_real_name' => $this->mRealName
,
2730 'user_options' => '',
2731 'user_token' => $this->mToken
,
2732 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2733 'user_editcount' => 0,
2736 $this->mId
= $dbw->insertId();
2738 // Clear instance cache other than user table data, which is already accurate
2739 $this->clearInstanceCache();
2741 $this->saveOptions();
2745 * If this (non-anonymous) user is blocked, block any IP address
2746 * they've successfully logged in from.
2748 function spreadBlock() {
2749 wfDebug( __METHOD__
. "()\n" );
2751 if ( $this->mId
== 0 ) {
2755 $userblock = Block
::newFromTarget( $this->getName() );
2756 if ( !$userblock ) {
2760 $userblock->doAutoblock( wfGetIP() );
2764 * Generate a string which will be different for any combination of
2765 * user options which would produce different parser output.
2766 * This will be used as part of the hash key for the parser cache,
2767 * so users with the same options can share the same cached data
2770 * Extensions which require it should install 'PageRenderingHash' hook,
2771 * which will give them a chance to modify this key based on their own
2774 * @deprecated since 1.17 use the ParserOptions object to get the relevant options
2775 * @return String Page rendering hash
2777 function getPageRenderingHash() {
2778 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2780 return $this->mHash
;
2782 wfDeprecated( __METHOD__
);
2784 // stubthreshold is only included below for completeness,
2785 // since it disables the parser cache, its value will always
2786 // be 0 when this function is called by parsercache.
2788 $confstr = $this->getOption( 'math' );
2789 $confstr .= '!' . $this->getStubThreshold();
2790 if ( $wgUseDynamicDates ) { # This is wrong (bug 24714)
2791 $confstr .= '!' . $this->getDatePreference();
2793 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ?
'1' : '' );
2794 $confstr .= '!' . $wgLang->getCode();
2795 $confstr .= '!' . $this->getOption( 'thumbsize' );
2796 // add in language specific options, if any
2797 $extra = $wgContLang->getExtraHashOptions();
2800 // Since the skin could be overloading link(), it should be
2801 // included here but in practice, none of our skins do that.
2803 $confstr .= $wgRenderHashAppend;
2805 // Give a chance for extensions to modify the hash, if they have
2806 // extra options or other effects on the parser cache.
2807 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2809 // Make it a valid memcached key fragment
2810 $confstr = str_replace( ' ', '_', $confstr );
2811 $this->mHash
= $confstr;
2816 * Get whether the user is explicitly blocked from account creation.
2817 * @return Bool|Block
2819 function isBlockedFromCreateAccount() {
2820 $this->getBlockedStatus();
2821 if( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ){
2822 return $this->mBlock
;
2825 # bug 13611: if the IP address the user is trying to create an account from is
2826 # blocked with createaccount disabled, prevent new account creation there even
2827 # when the user is logged in
2828 static $accBlock = false;
2829 if( $accBlock === false ){
2830 $accBlock = Block
::newFromTarget( null, wfGetIP() );
2832 return $accBlock instanceof Block
&& $accBlock->prevents( 'createaccount' )
2838 * Get whether the user is blocked from using Special:Emailuser.
2841 function isBlockedFromEmailuser() {
2842 $this->getBlockedStatus();
2843 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
2847 * Get whether the user is allowed to create an account.
2850 function isAllowedToCreateAccount() {
2851 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2855 * Get this user's personal page title.
2857 * @return Title: User's personal page title
2859 function getUserPage() {
2860 return Title
::makeTitle( NS_USER
, $this->getName() );
2864 * Get this user's talk page title.
2866 * @return Title: User's talk page title
2868 function getTalkPage() {
2869 $title = $this->getUserPage();
2870 return $title->getTalkPage();
2874 * Get the maximum valid user ID.
2875 * @return Integer: User ID
2878 function getMaxID() {
2879 static $res; // cache
2881 if ( isset( $res ) ) {
2884 $dbr = wfGetDB( DB_SLAVE
);
2885 return $res = $dbr->selectField( 'user', 'max(user_id)', false, __METHOD__
);
2890 * Determine whether the user is a newbie. Newbies are either
2891 * anonymous IPs, or the most recently created accounts.
2894 function isNewbie() {
2895 return !$this->isAllowed( 'autoconfirmed' );
2899 * Check to see if the given clear-text password is one of the accepted passwords
2900 * @param $password String: user password.
2901 * @return Boolean: True if the given password is correct, otherwise False.
2903 function checkPassword( $password ) {
2904 global $wgAuth, $wgLegacyEncoding;
2907 // Even though we stop people from creating passwords that
2908 // are shorter than this, doesn't mean people wont be able
2909 // to. Certain authentication plugins do NOT want to save
2910 // domain passwords in a mysql database, so we should
2911 // check this (in case $wgAuth->strict() is false).
2912 if( !$this->isValidPassword( $password ) ) {
2916 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2918 } elseif( $wgAuth->strict() ) {
2919 /* Auth plugin doesn't allow local authentication */
2921 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2922 /* Auth plugin doesn't allow local authentication for this user name */
2925 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
2927 } elseif ( $wgLegacyEncoding ) {
2928 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2929 # Check for this with iconv
2930 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2931 if ( $cp1252Password != $password &&
2932 self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) )
2941 * Check if the given clear-text password matches the temporary password
2942 * sent by e-mail for password reset operations.
2943 * @return Boolean: True if matches, false otherwise
2945 function checkTemporaryPassword( $plaintext ) {
2946 global $wgNewPasswordExpiry;
2949 if( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
2950 if ( is_null( $this->mNewpassTime
) ) {
2953 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
2954 return ( time() < $expiry );
2961 * Initialize (if necessary) and return a session token value
2962 * which can be used in edit forms to show that the user's
2963 * login credentials aren't being hijacked with a foreign form
2966 * @param $salt String|Array of Strings Optional function-specific data for hashing
2967 * @param $request WebRequest object to use or null to use $wgRequest
2968 * @return String The new edit token
2970 function editToken( $salt = '', $request = null ) {
2971 if ( $request == null ) {
2973 $request = $wgRequest;
2976 if ( $this->isAnon() ) {
2977 return EDIT_TOKEN_SUFFIX
;
2979 $token = $request->getSessionData( 'wsEditToken' );
2980 if ( $token === null ) {
2981 $token = self
::generateToken();
2982 $request->setSessionData( 'wsEditToken', $token );
2984 if( is_array( $salt ) ) {
2985 $salt = implode( '|', $salt );
2987 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2992 * Generate a looking random token for various uses.
2994 * @param $salt String Optional salt value
2995 * @return String The new random token
2997 public static function generateToken( $salt = '' ) {
2998 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2999 return md5( $token . $salt );
3003 * Check given value against the token value stored in the session.
3004 * A match should confirm that the form was submitted from the
3005 * user's own login session, not a form submission from a third-party
3008 * @param $val String Input value to compare
3009 * @param $salt String Optional function-specific data for hashing
3010 * @param $request WebRequest object to use or null to use $wgRequest
3011 * @return Boolean: Whether the token matches
3013 function matchEditToken( $val, $salt = '', $request = null ) {
3014 $sessionToken = $this->editToken( $salt, $request );
3015 if ( $val != $sessionToken ) {
3016 wfDebug( "User::matchEditToken: broken session data\n" );
3018 return $val == $sessionToken;
3022 * Check given value against the token value stored in the session,
3023 * ignoring the suffix.
3025 * @param $val String Input value to compare
3026 * @param $salt String Optional function-specific data for hashing
3027 * @param $request WebRequest object to use or null to use $wgRequest
3028 * @return Boolean: Whether the token matches
3030 function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3031 $sessionToken = $this->editToken( $salt, $request );
3032 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3036 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3037 * mail to the user's given address.
3039 * @param $type String: message to send, either "created", "changed" or "set"
3040 * @return Status object
3042 function sendConfirmationMail( $type = 'created' ) {
3044 $expiration = null; // gets passed-by-ref and defined in next line.
3045 $token = $this->confirmationToken( $expiration );
3046 $url = $this->confirmationTokenUrl( $token );
3047 $invalidateURL = $this->invalidationTokenUrl( $token );
3048 $this->saveSettings();
3050 if ( $type == 'created' ||
$type === false ) {
3051 $message = 'confirmemail_body';
3052 } elseif ( $type === true ) {
3053 $message = 'confirmemail_body_changed';
3055 $message = 'confirmemail_body_' . $type;
3058 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
3063 $wgLang->timeanddate( $expiration, false ),
3065 $wgLang->date( $expiration, false ),
3066 $wgLang->time( $expiration, false ) ) );
3070 * Send an e-mail to this user's account. Does not check for
3071 * confirmed status or validity.
3073 * @param $subject String Message subject
3074 * @param $body String Message body
3075 * @param $from String Optional From address; if unspecified, default $wgPasswordSender will be used
3076 * @param $replyto String Reply-To address
3079 function sendMail( $subject, $body, $from = null, $replyto = null ) {
3080 if( is_null( $from ) ) {
3081 global $wgPasswordSender, $wgPasswordSenderName;
3082 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
3084 $sender = new MailAddress( $from );
3087 $to = new MailAddress( $this );
3088 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
3092 * Generate, store, and return a new e-mail confirmation code.
3093 * A hash (unsalted, since it's used as a key) is stored.
3095 * @note Call saveSettings() after calling this function to commit
3096 * this change to the database.
3098 * @param[out] &$expiration \mixed Accepts the expiration time
3099 * @return String New token
3102 function confirmationToken( &$expiration ) {
3103 global $wgUserEmailConfirmationTokenExpiry;
3105 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
3106 $expiration = wfTimestamp( TS_MW
, $expires );
3107 $token = self
::generateToken( $this->mId
. $this->mEmail
. $expires );
3108 $hash = md5( $token );
3110 $this->mEmailToken
= $hash;
3111 $this->mEmailTokenExpires
= $expiration;
3116 * Return a URL the user can use to confirm their email address.
3117 * @param $token String Accepts the email confirmation token
3118 * @return String New token URL
3121 function confirmationTokenUrl( $token ) {
3122 return $this->getTokenUrl( 'ConfirmEmail', $token );
3126 * Return a URL the user can use to invalidate their email address.
3127 * @param $token String Accepts the email confirmation token
3128 * @return String New token URL
3131 function invalidationTokenUrl( $token ) {
3132 return $this->getTokenUrl( 'Invalidateemail', $token );
3136 * Internal function to format the e-mail validation/invalidation URLs.
3137 * This uses $wgArticlePath directly as a quickie hack to use the
3138 * hardcoded English names of the Special: pages, for ASCII safety.
3140 * @note Since these URLs get dropped directly into emails, using the
3141 * short English names avoids insanely long URL-encoded links, which
3142 * also sometimes can get corrupted in some browsers/mailers
3143 * (bug 6957 with Gmail and Internet Explorer).
3145 * @param $page String Special page
3146 * @param $token String Token
3147 * @return String Formatted URL
3149 protected function getTokenUrl( $page, $token ) {
3150 global $wgArticlePath;
3154 "Special:$page/$token",
3159 * Mark the e-mail address confirmed.
3161 * @note Call saveSettings() after calling this function to commit the change.
3163 function confirmEmail() {
3164 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3165 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3170 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3171 * address if it was already confirmed.
3173 * @note Call saveSettings() after calling this function to commit the change.
3175 function invalidateEmail() {
3177 $this->mEmailToken
= null;
3178 $this->mEmailTokenExpires
= null;
3179 $this->setEmailAuthenticationTimestamp( null );
3180 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3185 * Set the e-mail authentication timestamp.
3186 * @param $timestamp String TS_MW timestamp
3188 function setEmailAuthenticationTimestamp( $timestamp ) {
3190 $this->mEmailAuthenticated
= $timestamp;
3191 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
3195 * Is this user allowed to send e-mails within limits of current
3196 * site configuration?
3199 function canSendEmail() {
3200 global $wgEnableEmail, $wgEnableUserEmail;
3201 if( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
3204 $canSend = $this->isEmailConfirmed();
3205 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3210 * Is this user allowed to receive e-mails within limits of current
3211 * site configuration?
3214 function canReceiveEmail() {
3215 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3219 * Is this user's e-mail address valid-looking and confirmed within
3220 * limits of the current site configuration?
3222 * @note If $wgEmailAuthentication is on, this may require the user to have
3223 * confirmed their address by returning a code or using a password
3224 * sent to the address from the wiki.
3228 function isEmailConfirmed() {
3229 global $wgEmailAuthentication;
3232 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3233 if( $this->isAnon() )
3235 if( !self
::isValidEmailAddr( $this->mEmail
) )
3237 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
3246 * Check whether there is an outstanding request for e-mail confirmation.
3249 function isEmailConfirmationPending() {
3250 global $wgEmailAuthentication;
3251 return $wgEmailAuthentication &&
3252 !$this->isEmailConfirmed() &&
3253 $this->mEmailToken
&&
3254 $this->mEmailTokenExpires
> wfTimestamp();
3258 * Get the timestamp of account creation.
3260 * @return String|Bool Timestamp of account creation, or false for
3261 * non-existent/anonymous user accounts.
3263 public function getRegistration() {
3264 if ( $this->isAnon() ) {
3268 return $this->mRegistration
;
3272 * Get the timestamp of the first edit
3274 * @return String|Bool Timestamp of first edit, or false for
3275 * non-existent/anonymous user accounts.
3277 public function getFirstEditTimestamp() {
3278 if( $this->getId() == 0 ) {
3279 return false; // anons
3281 $dbr = wfGetDB( DB_SLAVE
);
3282 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3283 array( 'rev_user' => $this->getId() ),
3285 array( 'ORDER BY' => 'rev_timestamp ASC' )
3288 return false; // no edits
3290 return wfTimestamp( TS_MW
, $time );
3294 * Get the permissions associated with a given list of groups
3296 * @param $groups Array of Strings List of internal group names
3297 * @return Array of Strings List of permission key names for given groups combined
3299 static function getGroupPermissions( $groups ) {
3300 global $wgGroupPermissions, $wgRevokePermissions;
3302 // grant every granted permission first
3303 foreach( $groups as $group ) {
3304 if( isset( $wgGroupPermissions[$group] ) ) {
3305 $rights = array_merge( $rights,
3306 // array_filter removes empty items
3307 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3310 // now revoke the revoked permissions
3311 foreach( $groups as $group ) {
3312 if( isset( $wgRevokePermissions[$group] ) ) {
3313 $rights = array_diff( $rights,
3314 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3317 return array_unique( $rights );
3321 * Get all the groups who have a given permission
3323 * @param $role String Role to check
3324 * @return Array of Strings List of internal group names with the given permission
3326 static function getGroupsWithPermission( $role ) {
3327 global $wgGroupPermissions;
3328 $allowedGroups = array();
3329 foreach ( $wgGroupPermissions as $group => $rights ) {
3330 if ( isset( $rights[$role] ) && $rights[$role] ) {
3331 $allowedGroups[] = $group;
3334 return $allowedGroups;
3338 * Get the localized descriptive name for a group, if it exists
3340 * @param $group String Internal group name
3341 * @return String Localized descriptive group name
3343 static function getGroupName( $group ) {
3344 $msg = wfMessage( "group-$group" );
3345 return $msg->isBlank() ?
$group : $msg->text();
3349 * Get the localized descriptive name for a member of a group, if it exists
3351 * @param $group String Internal group name
3352 * @return String Localized name for group member
3354 static function getGroupMember( $group ) {
3355 $msg = wfMessage( "group-$group-member" );
3356 return $msg->isBlank() ?
$group : $msg->text();
3360 * Return the set of defined explicit groups.
3361 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3362 * are not included, as they are defined automatically, not in the database.
3363 * @return Array of internal group names
3365 static function getAllGroups() {
3366 global $wgGroupPermissions, $wgRevokePermissions;
3368 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3369 self
::getImplicitGroups()
3374 * Get a list of all available permissions.
3375 * @return Array of permission names
3377 static function getAllRights() {
3378 if ( self
::$mAllRights === false ) {
3379 global $wgAvailableRights;
3380 if ( count( $wgAvailableRights ) ) {
3381 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3383 self
::$mAllRights = self
::$mCoreRights;
3385 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3387 return self
::$mAllRights;
3391 * Get a list of implicit groups
3392 * @return Array of Strings Array of internal group names
3394 public static function getImplicitGroups() {
3395 global $wgImplicitGroups;
3396 $groups = $wgImplicitGroups;
3397 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3402 * Get the title of a page describing a particular group
3404 * @param $group String Internal group name
3405 * @return Title|Bool Title of the page if it exists, false otherwise
3407 static function getGroupPage( $group ) {
3408 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
3409 if( $msg->exists() ) {
3410 $title = Title
::newFromText( $msg->text() );
3411 if( is_object( $title ) )
3418 * Create a link to the group in HTML, if available;
3419 * else return the group name.
3421 * @param $group String Internal name of the group
3422 * @param $text String The text of the link
3423 * @return String HTML link to the group
3425 static function makeGroupLinkHTML( $group, $text = '' ) {
3427 $text = self
::getGroupName( $group );
3429 $title = self
::getGroupPage( $group );
3432 $sk = $wgUser->getSkin();
3433 return $sk->link( $title, htmlspecialchars( $text ) );
3440 * Create a link to the group in Wikitext, if available;
3441 * else return the group name.
3443 * @param $group String Internal name of the group
3444 * @param $text String The text of the link
3445 * @return String Wikilink to the group
3447 static function makeGroupLinkWiki( $group, $text = '' ) {
3449 $text = self
::getGroupName( $group );
3451 $title = self
::getGroupPage( $group );
3453 $page = $title->getPrefixedText();
3454 return "[[$page|$text]]";
3461 * Returns an array of the groups that a particular group can add/remove.
3463 * @param $group String: the group to check for whether it can add/remove
3464 * @return Array array( 'add' => array( addablegroups ),
3465 * 'remove' => array( removablegroups ),
3466 * 'add-self' => array( addablegroups to self),
3467 * 'remove-self' => array( removable groups from self) )
3469 static function changeableByGroup( $group ) {
3470 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
3472 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
3473 if( empty( $wgAddGroups[$group] ) ) {
3474 // Don't add anything to $groups
3475 } elseif( $wgAddGroups[$group] === true ) {
3476 // You get everything
3477 $groups['add'] = self
::getAllGroups();
3478 } elseif( is_array( $wgAddGroups[$group] ) ) {
3479 $groups['add'] = $wgAddGroups[$group];
3482 // Same thing for remove
3483 if( empty( $wgRemoveGroups[$group] ) ) {
3484 } elseif( $wgRemoveGroups[$group] === true ) {
3485 $groups['remove'] = self
::getAllGroups();
3486 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
3487 $groups['remove'] = $wgRemoveGroups[$group];
3490 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
3491 if( empty( $wgGroupsAddToSelf['user']) ||
$wgGroupsAddToSelf['user'] !== true ) {
3492 foreach( $wgGroupsAddToSelf as $key => $value ) {
3493 if( is_int( $key ) ) {
3494 $wgGroupsAddToSelf['user'][] = $value;
3499 if( empty( $wgGroupsRemoveFromSelf['user']) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
3500 foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
3501 if( is_int( $key ) ) {
3502 $wgGroupsRemoveFromSelf['user'][] = $value;
3507 // Now figure out what groups the user can add to him/herself
3508 if( empty( $wgGroupsAddToSelf[$group] ) ) {
3509 } elseif( $wgGroupsAddToSelf[$group] === true ) {
3510 // No idea WHY this would be used, but it's there
3511 $groups['add-self'] = User
::getAllGroups();
3512 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
3513 $groups['add-self'] = $wgGroupsAddToSelf[$group];
3516 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
3517 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
3518 $groups['remove-self'] = User
::getAllGroups();
3519 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
3520 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
3527 * Returns an array of groups that this user can add and remove
3528 * @return Array array( 'add' => array( addablegroups ),
3529 * 'remove' => array( removablegroups ),
3530 * 'add-self' => array( addablegroups to self),
3531 * 'remove-self' => array( removable groups from self) )
3533 function changeableGroups() {
3534 if( $this->isAllowed( 'userrights' ) ) {
3535 // This group gives the right to modify everything (reverse-
3536 // compatibility with old "userrights lets you change
3538 // Using array_merge to make the groups reindexed
3539 $all = array_merge( User
::getAllGroups() );
3543 'add-self' => array(),
3544 'remove-self' => array()
3548 // Okay, it's not so simple, we will have to go through the arrays
3551 'remove' => array(),
3552 'add-self' => array(),
3553 'remove-self' => array()
3555 $addergroups = $this->getEffectiveGroups();
3557 foreach( $addergroups as $addergroup ) {
3558 $groups = array_merge_recursive(
3559 $groups, $this->changeableByGroup( $addergroup )
3561 $groups['add'] = array_unique( $groups['add'] );
3562 $groups['remove'] = array_unique( $groups['remove'] );
3563 $groups['add-self'] = array_unique( $groups['add-self'] );
3564 $groups['remove-self'] = array_unique( $groups['remove-self'] );
3570 * Increment the user's edit-count field.
3571 * Will have no effect for anonymous users.
3573 function incEditCount() {
3574 if( !$this->isAnon() ) {
3575 $dbw = wfGetDB( DB_MASTER
);
3576 $dbw->update( 'user',
3577 array( 'user_editcount=user_editcount+1' ),
3578 array( 'user_id' => $this->getId() ),
3581 // Lazy initialization check...
3582 if( $dbw->affectedRows() == 0 ) {
3583 // Pull from a slave to be less cruel to servers
3584 // Accuracy isn't the point anyway here
3585 $dbr = wfGetDB( DB_SLAVE
);
3586 $count = $dbr->selectField( 'revision',
3588 array( 'rev_user' => $this->getId() ),
3591 // Now here's a goddamn hack...
3592 if( $dbr !== $dbw ) {
3593 // If we actually have a slave server, the count is
3594 // at least one behind because the current transaction
3595 // has not been committed and replicated.
3598 // But if DB_SLAVE is selecting the master, then the
3599 // count we just read includes the revision that was
3600 // just added in the working transaction.
3603 $dbw->update( 'user',
3604 array( 'user_editcount' => $count ),
3605 array( 'user_id' => $this->getId() ),
3609 // edit count in user cache too
3610 $this->invalidateCache();
3614 * Get the description of a given right
3616 * @param $right String Right to query
3617 * @return String Localized description of the right
3619 static function getRightDescription( $right ) {
3620 $key = "right-$right";
3621 $name = wfMsg( $key );
3622 return $name == '' ||
wfEmptyMsg( $key )
3628 * Make an old-style password hash
3630 * @param $password String Plain-text password
3631 * @param $userId String User ID
3632 * @return String Password hash
3634 static function oldCrypt( $password, $userId ) {
3635 global $wgPasswordSalt;
3636 if ( $wgPasswordSalt ) {
3637 return md5( $userId . '-' . md5( $password ) );
3639 return md5( $password );
3644 * Make a new-style password hash
3646 * @param $password String Plain-text password
3647 * @param $salt String Optional salt, may be random or the user ID.
3648 * If unspecified or false, will generate one automatically
3649 * @return String Password hash
3651 static function crypt( $password, $salt = false ) {
3652 global $wgPasswordSalt;
3655 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3659 if( $wgPasswordSalt ) {
3660 if ( $salt === false ) {
3661 $salt = substr( wfGenerateToken(), 0, 8 );
3663 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3665 return ':A:' . md5( $password );
3670 * Compare a password hash with a plain-text password. Requires the user
3671 * ID if there's a chance that the hash is an old-style hash.
3673 * @param $hash String Password hash
3674 * @param $password String Plain-text password to compare
3675 * @param $userId String User ID for old-style password salt
3678 static function comparePasswords( $hash, $password, $userId = false ) {
3679 $type = substr( $hash, 0, 3 );
3682 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3686 if ( $type == ':A:' ) {
3688 return md5( $password ) === substr( $hash, 3 );
3689 } elseif ( $type == ':B:' ) {
3691 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3692 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3695 return self
::oldCrypt( $password, $userId ) === $hash;
3700 * Add a newuser log entry for this user
3702 * @param $byEmail Boolean: account made by email?
3703 * @param $reason String: user supplied reason
3705 public function addNewUserLogEntry( $byEmail = false, $reason = '' ) {
3706 global $wgUser, $wgContLang, $wgNewUserLog;
3707 if( empty( $wgNewUserLog ) ) {
3708 return true; // disabled
3711 if( $this->getName() == $wgUser->getName() ) {
3714 $action = 'create2';
3716 if ( $reason === '' ) {
3717 $reason = wfMsgForContent( 'newuserlog-byemail' );
3719 $reason = $wgContLang->commaList( array(
3720 $reason, wfMsgForContent( 'newuserlog-byemail' ) ) );
3724 $log = new LogPage( 'newusers' );
3727 $this->getUserPage(),
3729 array( $this->getId() )
3735 * Add an autocreate newuser log entry for this user
3736 * Used by things like CentralAuth and perhaps other authplugins.
3738 public function addNewUserLogEntryAutoCreate() {
3739 global $wgNewUserLog;
3740 if( !$wgNewUserLog ) {
3741 return true; // disabled
3743 $log = new LogPage( 'newusers', false );
3744 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3748 protected function loadOptions() {
3750 if ( $this->mOptionsLoaded ||
!$this->getId() )
3753 $this->mOptions
= self
::getDefaultOptions();
3755 // Maybe load from the object
3756 if ( !is_null( $this->mOptionOverrides
) ) {
3757 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
3758 foreach( $this->mOptionOverrides
as $key => $value ) {
3759 $this->mOptions
[$key] = $value;
3762 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
3763 // Load from database
3764 $dbr = wfGetDB( DB_SLAVE
);
3766 $res = $dbr->select(
3769 array( 'up_user' => $this->getId() ),
3773 foreach ( $res as $row ) {
3774 $this->mOptionOverrides
[$row->up_property
] = $row->up_value
;
3775 $this->mOptions
[$row->up_property
] = $row->up_value
;
3779 $this->mOptionsLoaded
= true;
3781 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
3784 protected function saveOptions() {
3785 global $wgAllowPrefChange;
3787 $extuser = ExternalUser
::newFromUser( $this );
3789 $this->loadOptions();
3790 $dbw = wfGetDB( DB_MASTER
);
3792 $insert_rows = array();
3794 $saveOptions = $this->mOptions
;
3796 // Allow hooks to abort, for instance to save to a global profile.
3797 // Reset options to default state before saving.
3798 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) )
3801 foreach( $saveOptions as $key => $value ) {
3802 # Don't bother storing default values
3803 if ( ( is_null( self
::getDefaultOption( $key ) ) &&
3804 !( $value === false ||
is_null($value) ) ) ||
3805 $value != self
::getDefaultOption( $key ) ) {
3806 $insert_rows[] = array(
3807 'up_user' => $this->getId(),
3808 'up_property' => $key,
3809 'up_value' => $value,
3812 if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
3813 switch ( $wgAllowPrefChange[$key] ) {
3819 $extuser->setPref( $key, $value );
3825 $dbw->delete( 'user_properties', array( 'up_user' => $this->getId() ), __METHOD__
);
3826 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
);
3831 * Provide an array of HTML5 attributes to put on an input element
3832 * intended for the user to enter a new password. This may include
3833 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
3835 * Do *not* use this when asking the user to enter his current password!
3836 * Regardless of configuration, users may have invalid passwords for whatever
3837 * reason (e.g., they were set before requirements were tightened up).
3838 * Only use it when asking for a new password, like on account creation or
3841 * Obviously, you still need to do server-side checking.
3843 * NOTE: A combination of bugs in various browsers means that this function
3844 * actually just returns array() unconditionally at the moment. May as
3845 * well keep it around for when the browser bugs get fixed, though.
3847 * FIXME : This does not belong here; put it in Html or Linker or somewhere
3849 * @return array Array of HTML attributes suitable for feeding to
3850 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
3851 * That will potentially output invalid XHTML 1.0 Transitional, and will
3852 * get confused by the boolean attribute syntax used.)
3854 public static function passwordChangeInputAttribs() {
3855 global $wgMinimalPasswordLength;
3857 if ( $wgMinimalPasswordLength == 0 ) {
3861 # Note that the pattern requirement will always be satisfied if the
3862 # input is empty, so we need required in all cases.
3864 # FIXME (bug 23769): This needs to not claim the password is required
3865 # if e-mail confirmation is being used. Since HTML5 input validation
3866 # is b0rked anyway in some browsers, just return nothing. When it's
3867 # re-enabled, fix this code to not output required for e-mail
3869 #$ret = array( 'required' );
3872 # We can't actually do this right now, because Opera 9.6 will print out
3873 # the entered password visibly in its error message! When other
3874 # browsers add support for this attribute, or Opera fixes its support,
3875 # we can add support with a version check to avoid doing this on Opera
3876 # versions where it will be a problem. Reported to Opera as
3877 # DSK-262266, but they don't have a public bug tracker for us to follow.
3879 if ( $wgMinimalPasswordLength > 1 ) {
3880 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
3881 $ret['title'] = wfMsgExt( 'passwordtooshort', 'parsemag',
3882 $wgMinimalPasswordLength );