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 * \type{\arrayof{\string}} 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 * \type{\arrayof{\string}} Core rights.
82 * Each of these should have a corresponding message of the form
86 static $mCoreRights = array(
104 'editusercssjs', #deprecated
116 'move-rootuserpages',
120 '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.
160 var $mDataLoaded, $mAuthLoaded, $mOptionsLoaded;
163 * \string Initialization data source if mDataLoaded==false. May be one of:
164 * - 'defaults' anonymous user initialised from class defaults
165 * - 'name' initialise from mName
166 * - 'id' initialise from mId
167 * - 'session' log in from cookies or session if possible
169 * Use the User::newFrom*() family of functions to set this.
173 /** @name Lazy-initialized variables, invalidated with clearInstanceCache */
175 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
176 $mBlockreason, $mBlock, $mEffectiveGroups, $mBlockedGlobally,
177 $mLocked, $mHideName, $mOptions;
180 static $idCacheByName = array();
183 * Lightweight constructor for an anonymous user.
184 * Use the User::newFrom* factory functions for other kinds of users.
188 * @see newFromConfirmationCode()
189 * @see newFromSession()
192 function __construct() {
193 $this->clearInstanceCache( 'defaults' );
197 * Load the user table data for this object from the source given by mFrom.
200 if ( $this->mDataLoaded ) {
203 wfProfileIn( __METHOD__ );
205 # Set it now to avoid infinite recursion in accessors
206 $this->mDataLoaded = true;
208 switch ( $this->mFrom ) {
210 $this->loadDefaults();
213 $this->mId = self::idFromName( $this->mName );
215 # Nonexistent user placeholder object
216 $this->loadDefaults( $this->mName );
225 $this->loadFromSession();
226 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
229 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
231 wfProfileOut( __METHOD__ );
235 * Load user table data, given mId has already been set.
236 * @return \bool false if the ID does not exist, true otherwise
239 function loadFromId() {
241 if ( $this->mId == 0 ) {
242 $this->loadDefaults();
247 $key = wfMemcKey( 'user', 'id', $this->mId );
248 $data = $wgMemc->get( $key );
249 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
250 # Object is expired, load from DB
255 wfDebug( "User: cache miss for user {$this->mId}\n" );
257 if ( !$this->loadFromDatabase() ) {
258 # Can't load from ID, user is anonymous
261 $this->saveToCache();
263 wfDebug( "User: got user {$this->mId} from cache\n" );
265 foreach ( self::$mCacheVars as $name ) {
266 $this->$name = $data[$name];
273 * Save user data to the shared cache
275 function saveToCache() {
278 $this->loadOptions();
279 if ( $this->isAnon() ) {
280 // Anonymous users are uncached
284 foreach ( self::$mCacheVars as $name ) {
285 $data[$name] = $this->$name;
287 $data['mVersion'] = MW_USER_VERSION;
288 $key = wfMemcKey( 'user', 'id', $this->mId );
290 $wgMemc->set( $key, $data );
294 /** @name newFrom*() static factory methods */
298 * Static factory method for creation from username.
300 * This is slightly less efficient than newFromId(), so use newFromId() if
301 * you have both an ID and a name handy.
303 * @param $name \string Username, validated by Title::newFromText()
304 * @param $validate \mixed Validate username. Takes the same parameters as
305 * User::getCanonicalName(), except that true is accepted as an alias
306 * for 'valid', for BC.
308 * @return User The User object, or false if the username is invalid
309 * (e.g. if it contains illegal characters or is an IP address). If the
310 * username is not present in the database, the result will be a user object
311 * with a name, zero user ID and default settings.
313 static function newFromName( $name, $validate = 'valid' ) {
314 if ( $validate === true ) {
317 $name = self::getCanonicalName( $name, $validate );
318 if ( $name === false ) {
321 # Create unloaded user object
330 * Static factory method for creation from a given user ID.
332 * @param $id \int Valid user ID
333 * @return \type{User} The corresponding User object
335 static function newFromId( $id ) {
343 * Factory method to fetch whichever user has a given email confirmation code.
344 * This code is generated when an account is created or its e-mail address
347 * If the code is invalid or has expired, returns NULL.
349 * @param $code \string Confirmation code
350 * @return \type{User}
352 static function newFromConfirmationCode( $code ) {
353 $dbr = wfGetDB( DB_SLAVE );
354 $id = $dbr->selectField( 'user', 'user_id', array(
355 'user_email_token' => md5( $code ),
356 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
358 if( $id !== false ) {
359 return User::newFromId( $id );
366 * Create a new user object using data from session or cookies. If the
367 * login credentials are invalid, the result is an anonymous user.
369 * @return \type{User}
371 static function newFromSession() {
373 $user->mFrom = 'session';
378 * Create a new user object from a user row.
379 * The row should have all fields from the user table in it.
380 * @param $row array A row from the user table
381 * @return \type{User}
383 static function newFromRow( $row ) {
385 $user->loadFromRow( $row );
393 * Get the username corresponding to a given user ID
394 * @param $id \int User ID
395 * @return \string The corresponding username
397 static function whoIs( $id ) {
398 $dbr = wfGetDB( DB_SLAVE );
399 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), __METHOD__ );
403 * Get the real name of a user given their user ID
405 * @param $id \int User ID
406 * @return \string The corresponding user's real name
408 static function whoIsReal( $id ) {
409 $dbr = wfGetDB( DB_SLAVE );
410 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__ );
414 * Get database id given a user name
415 * @param $name \string Username
416 * @return \types{\int,\null} The corresponding user's ID, or null if user is nonexistent
418 static function idFromName( $name ) {
419 $nt = Title::makeTitleSafe( NS_USER, $name );
420 if( is_null( $nt ) ) {
425 if ( isset( self::$idCacheByName[$name] ) ) {
426 return self::$idCacheByName[$name];
429 $dbr = wfGetDB( DB_SLAVE );
430 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
432 if ( $s === false ) {
435 $result = $s->user_id;
438 self::$idCacheByName[$name] = $result;
440 if ( count( self::$idCacheByName ) > 1000 ) {
441 self::$idCacheByName = array();
448 * Does the string match an anonymous IPv4 address?
450 * This function exists for username validation, in order to reject
451 * usernames which are similar in form to IP addresses. Strings such
452 * as 300.300.300.300 will return true because it looks like an IP
453 * address, despite not being strictly valid.
455 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
456 * address because the usemod software would "cloak" anonymous IP
457 * addresses like this, if we allowed accounts like this to be created
458 * new users could get the old edits of these anonymous users.
460 * @param $name \string String to match
461 * @return \bool True or false
463 static function isIP( $name ) {
464 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP::isIPv6($name);
468 * Is the input a valid username?
470 * Checks if the input is a valid username, we don't want an empty string,
471 * an IP address, anything that containins slashes (would mess up subpages),
472 * is longer than the maximum allowed username size or doesn't begin with
475 * @param $name \string String to match
476 * @return \bool True or false
478 static function isValidUserName( $name ) {
479 global $wgContLang, $wgMaxNameChars;
482 || User::isIP( $name )
483 || strpos( $name, '/' ) !== false
484 || strlen( $name ) > $wgMaxNameChars
485 || $name != $wgContLang->ucfirst( $name ) ) {
486 wfDebugLog( 'username', __METHOD__ .
487 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
491 // Ensure that the name can't be misresolved as a different title,
492 // such as with extra namespace keys at the start.
493 $parsed = Title::newFromText( $name );
494 if( is_null( $parsed )
495 || $parsed->getNamespace()
496 || strcmp( $name, $parsed->getPrefixedText() ) ) {
497 wfDebugLog( 'username', __METHOD__ .
498 ": '$name' invalid due to ambiguous prefixes" );
502 // Check an additional blacklist of troublemaker characters.
503 // Should these be merged into the title char list?
504 $unicodeBlacklist = '/[' .
505 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
506 '\x{00a0}' . # non-breaking space
507 '\x{2000}-\x{200f}' . # various whitespace
508 '\x{2028}-\x{202f}' . # breaks and control chars
509 '\x{3000}' . # ideographic space
510 '\x{e000}-\x{f8ff}' . # private use
512 if( preg_match( $unicodeBlacklist, $name ) ) {
513 wfDebugLog( 'username', __METHOD__ .
514 ": '$name' invalid due to blacklisted characters" );
522 * Usernames which fail to pass this function will be blocked
523 * from user login and new account registrations, but may be used
524 * internally by batch processes.
526 * If an account already exists in this form, login will be blocked
527 * by a failure to pass this function.
529 * @param $name \string String to match
530 * @return \bool True or false
532 static function isUsableName( $name ) {
533 global $wgReservedUsernames;
534 // Must be a valid username, obviously ;)
535 if ( !self::isValidUserName( $name ) ) {
539 static $reservedUsernames = false;
540 if ( !$reservedUsernames ) {
541 $reservedUsernames = $wgReservedUsernames;
542 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
545 // Certain names may be reserved for batch processes.
546 foreach ( $reservedUsernames as $reserved ) {
547 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
548 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
550 if ( $reserved == $name ) {
558 * Usernames which fail to pass this function will be blocked
559 * from new account registrations, but may be used internally
560 * either by batch processes or by user accounts which have
561 * already been created.
563 * Additional blacklisting may be added here rather than in
564 * isValidUserName() to avoid disrupting existing accounts.
566 * @param $name \string String to match
567 * @return \bool True or false
569 static function isCreatableName( $name ) {
570 global $wgInvalidUsernameCharacters;
572 // Ensure that the username isn't longer than 235 bytes, so that
573 // (at least for the builtin skins) user javascript and css files
574 // will work. (bug 23080)
575 if( strlen( $name ) > 235 ) {
576 wfDebugLog( 'username', __METHOD__ .
577 ": '$name' invalid due to length" );
581 // Preg yells if you try to give it an empty string
582 if( $wgInvalidUsernameCharacters ) {
583 if( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
584 wfDebugLog( 'username', __METHOD__ .
585 ": '$name' invalid due to wgInvalidUsernameCharacters" );
590 return self::isUsableName( $name );
594 * Is the input a valid password for this user?
596 * @param $password String Desired password
597 * @return bool True or false
599 function isValidPassword( $password ) {
600 //simple boolean wrapper for getPasswordValidity
601 return $this->getPasswordValidity( $password ) === true;
605 * Given unvalidated password input, return error message on failure.
607 * @param $password String Desired password
608 * @return mixed: true on success, string of error message on failure
610 function getPasswordValidity( $password ) {
611 global $wgMinimalPasswordLength, $wgContLang;
613 static $blockedLogins = array(
614 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
615 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
618 $result = false; //init $result to false for the internal checks
620 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
623 if ( $result === false ) {
624 if( strlen( $password ) < $wgMinimalPasswordLength ) {
625 return 'passwordtooshort';
626 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) {
627 return 'password-name-match';
628 } elseif ( isset( $blockedLogins[ $this->getName() ] ) && $password == $blockedLogins[ $this->getName() ] ) {
629 return 'password-login-forbidden';
631 //it seems weird returning true here, but this is because of the
632 //initialization of $result to false above. If the hook is never run or it
633 //doesn't modify $result, then we will likely get down into this if with
637 } elseif( $result === true ) {
640 return $result; //the isValidPassword hook set a string $result and returned true
645 * Does a string look like an e-mail address?
647 * This validates an email address using an HTML5 specification found at:
648 * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
649 * Which as of 2011-01-24 says:
651 * A valid e-mail address is a string that matches the ABNF production
652 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
653 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
656 * This function is an implementation of the specification as requested in
659 * Client-side forms will use the same standard validation rules via JS or
660 * HTML 5 validation; additional restrictions can be enforced server-side
661 * by extensions via the 'isValidEmailAddr' hook.
663 * Note that this validation doesn't 100% match RFC 2822, but is believed
664 * to be liberal enough for wide use. Some invalid addresses will still
665 * pass validation here.
667 * @param $addr String E-mail address
670 public static function isValidEmailAddr( $addr ) {
672 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
676 // Please note strings below are enclosed in brackets [], this make the
677 // hyphen "-" a range indicator. Hence it is double backslashed below.
679 $rfc5322_atext = "a-z0-9!#$%&'*+\\-\/=?^_`{|}~" ;
680 $rfc1034_ldh_str = "a-z0-9\\-" ;
682 $HTML5_email_regexp = "/
684 [$rfc5322_atext\\.]+ # user part which is liberal :p
686 [$rfc1034_ldh_str]+ # First domain part
687 (\\.[$rfc1034_ldh_str]+)* # Following part prefixed with a dot
689 /ix" ; // case Insensitive, eXtended
691 return (bool) preg_match( $HTML5_email_regexp, $addr );
695 * Given unvalidated user input, return a canonical username, or false if
696 * the username is invalid.
697 * @param $name \string User input
698 * @param $validate \types{\string,\bool} Type of validation to use:
699 * - false No validation
700 * - 'valid' Valid for batch processes
701 * - 'usable' Valid for batch processes and login
702 * - 'creatable' Valid for batch processes, login and account creation
704 static function getCanonicalName( $name, $validate = 'valid' ) {
705 # Force usernames to capital
707 $name = $wgContLang->ucfirst( $name );
709 # Reject names containing '#'; these will be cleaned up
710 # with title normalisation, but then it's too late to
712 if( strpos( $name, '#' ) !== false )
715 # Clean up name according to title rules
716 $t = ( $validate === 'valid' ) ?
717 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
718 # Check for invalid titles
719 if( is_null( $t ) ) {
723 # Reject various classes of invalid names
725 $name = $wgAuth->getCanonicalName( $t->getText() );
727 switch ( $validate ) {
731 if ( !User::isValidUserName( $name ) ) {
736 if ( !User::isUsableName( $name ) ) {
741 if ( !User::isCreatableName( $name ) ) {
746 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
752 * Count the number of edits of a user
753 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
755 * @param $uid \int User ID to check
756 * @return \int The user's edit count
758 static function edits( $uid ) {
759 wfProfileIn( __METHOD__ );
760 $dbr = wfGetDB( DB_SLAVE );
761 // check if the user_editcount field has been initialized
762 $field = $dbr->selectField(
763 'user', 'user_editcount',
764 array( 'user_id' => $uid ),
768 if( $field === null ) { // it has not been initialized. do so.
769 $dbw = wfGetDB( DB_MASTER );
770 $count = $dbr->selectField(
771 'revision', 'count(*)',
772 array( 'rev_user' => $uid ),
777 array( 'user_editcount' => $count ),
778 array( 'user_id' => $uid ),
784 wfProfileOut( __METHOD__ );
789 * Return a random password.
791 * @return \string New random password
793 static function randomPassword() {
794 global $wgMinimalPasswordLength;
795 // Decide the final password length based on our min password length, stopping at a minimum of 10 chars
796 $length = max( 10, $wgMinimalPasswordLength );
797 // Multiply by 1.25 to get the number of hex characters we need
798 $length = $length * 1.25;
799 // Generate random hex chars
800 $hex = MWCryptRand::generateHex( $length );
801 // Convert from base 16 to base 32 to get a proper password like string
802 return wfBaseConvert( $hex, 16, 32 );
806 * Set cached properties to default.
808 * @note This no longer clears uncached lazy-initialised properties;
809 * the constructor does that instead.
812 function loadDefaults( $name = false ) {
813 wfProfileIn( __METHOD__ );
818 $this->mName = $name;
819 $this->mRealName = '';
820 $this->mPassword = $this->mNewpassword = '';
821 $this->mNewpassTime = null;
823 $this->mOptionOverrides = null;
824 $this->mOptionsLoaded = false;
826 if( $wgRequest->getCookie( 'LoggedOut' ) !== null ) {
827 $this->mTouched = wfTimestamp( TS_MW, $wgRequest->getCookie( 'LoggedOut' ) );
829 $this->mTouched = '0'; # Allow any pages to be cached
832 $this->mToken = null; // Don't run cryptographic functions till we need a token
833 $this->mEmailAuthenticated = null;
834 $this->mEmailToken = '';
835 $this->mEmailTokenExpires = null;
836 $this->mRegistration = wfTimestamp( TS_MW );
837 $this->mGroups = array();
839 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
841 wfProfileOut( __METHOD__ );
845 * @deprecated Use wfSetupSession().
847 function SetupSession() {
848 wfDeprecated( __METHOD__ );
853 * Load user data from the session or login cookie. If there are no valid
854 * credentials, initialises the user as an anonymous user.
855 * @return \bool True if the user is logged in, false otherwise.
857 private function loadFromSession() {
858 global $wgRequest, $wgExternalAuthType, $wgAutocreatePolicy;
861 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
862 if ( $result !== null ) {
866 if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
867 $extUser = ExternalUser::newFromCookie();
869 # TODO: Automatically create the user here (or probably a bit
870 # lower down, in fact)
874 if ( $wgRequest->getCookie( 'UserID' ) !== null ) {
875 $sId = intval( $wgRequest->getCookie( 'UserID' ) );
876 if( isset( $_SESSION['wsUserID'] ) && $sId != $_SESSION['wsUserID'] ) {
877 $this->loadDefaults(); // Possible collision!
878 wfDebugLog( 'loginSessions', "Session user ID ({$_SESSION['wsUserID']}) and
879 cookie user ID ($sId) don't match!" );
882 $_SESSION['wsUserID'] = $sId;
883 } else if ( isset( $_SESSION['wsUserID'] ) ) {
884 if ( $_SESSION['wsUserID'] != 0 ) {
885 $sId = $_SESSION['wsUserID'];
887 $this->loadDefaults();
891 $this->loadDefaults();
895 if ( isset( $_SESSION['wsUserName'] ) ) {
896 $sName = $_SESSION['wsUserName'];
897 } else if ( $wgRequest->getCookie('UserName') !== null ) {
898 $sName = $wgRequest->getCookie('UserName');
899 $_SESSION['wsUserName'] = $sName;
901 $this->loadDefaults();
905 $proposedUser = User::newFromId( $sId );
906 if ( !$proposedUser->isLoggedIn() ) {
908 $this->loadDefaults();
912 global $wgBlockDisablesLogin;
913 if( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
914 # User blocked and we've disabled blocked user logins
915 $this->loadDefaults();
919 if ( isset( $_SESSION['wsToken'] ) && $_SESSION['wsToken'] ) {
920 $passwordCorrect = $proposedUser->getToken( false ) === $_SESSION['wsToken'];
922 } elseif ( $wgRequest->getCookie( 'Token' ) ) {
923 $passwordCorrect = $proposedUser->getToken( false ) === $wgRequest->getCookie( 'Token' );
926 # No session or persistent login cookie
927 $this->loadDefaults();
931 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
932 $this->loadFromUserObject( $proposedUser );
933 $_SESSION['wsToken'] = $this->mToken;
934 wfDebug( "User: logged in from $from\n" );
937 # Invalid credentials
938 wfDebug( "User: can't log in from $from, invalid credentials\n" );
939 $this->loadDefaults();
945 * Load the data for this user object from another user object.
947 protected function loadFromUserObject( $user ) {
950 $user->loadOptions();
951 foreach ( self::$mCacheVars as $var ) {
952 $this->$var = $user->$var;
957 * Load user and user_group data from the database.
958 * $this::mId must be set, this is how the user is identified.
960 * @return \bool True if the user exists, false if the user is anonymous
963 function loadFromDatabase() {
965 $this->mId = intval( $this->mId );
967 /** Anonymous user */
969 $this->loadDefaults();
973 $dbr = wfGetDB( DB_MASTER );
974 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ );
976 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
978 if ( $s !== false ) {
979 # Initialise user table data
980 $this->loadFromRow( $s );
981 $this->mGroups = null; // deferred
982 $this->getEditCount(); // revalidation for nulls
987 $this->loadDefaults();
993 * Initialize this object from a row from the user table.
995 * @param $row \type{\arrayof{\mixed}} Row from the user table to load.
997 function loadFromRow( $row ) {
998 $this->mDataLoaded = true;
1000 if ( isset( $row->user_id ) ) {
1001 $this->mId = intval( $row->user_id );
1003 $this->mName = $row->user_name;
1004 $this->mRealName = $row->user_real_name;
1005 $this->mPassword = $row->user_password;
1006 $this->mNewpassword = $row->user_newpassword;
1007 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
1008 $this->mEmail = $row->user_email;
1009 $this->decodeOptions( $row->user_options );
1010 $this->mTouched = wfTimestamp(TS_MW,$row->user_touched);
1011 $this->mToken = $row->user_token;
1012 if ( $this->mToken == '' ) {
1013 $this->mToken = null;
1015 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1016 $this->mEmailToken = $row->user_email_token;
1017 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1018 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1019 $this->mEditCount = $row->user_editcount;
1023 * Load the groups from the database if they aren't already loaded.
1026 function loadGroups() {
1027 if ( is_null( $this->mGroups ) ) {
1028 $dbr = wfGetDB( DB_MASTER );
1029 $res = $dbr->select( 'user_groups',
1030 array( 'ug_group' ),
1031 array( 'ug_user' => $this->mId ),
1033 $this->mGroups = array();
1034 foreach ( $res as $row ) {
1035 $this->mGroups[] = $row->ug_group;
1041 * Clear various cached data stored in this object.
1042 * @param $reloadFrom \string Reload user and user_groups table data from a
1043 * given source. May be "name", "id", "defaults", "session", or false for
1046 function clearInstanceCache( $reloadFrom = false ) {
1047 $this->mNewtalk = -1;
1048 $this->mDatePreference = null;
1049 $this->mBlockedby = -1; # Unset
1050 $this->mHash = false;
1051 $this->mSkin = null;
1052 $this->mRights = null;
1053 $this->mEffectiveGroups = null;
1054 $this->mOptions = null;
1056 if ( $reloadFrom ) {
1057 $this->mDataLoaded = false;
1058 $this->mFrom = $reloadFrom;
1063 * Combine the language default options with any site-specific options
1064 * and add the default language variants.
1066 * @return \type{\arrayof{\string}} Array of options
1068 static function getDefaultOptions() {
1069 global $wgNamespacesToBeSearchedDefault;
1071 * Site defaults will override the global/language defaults
1073 global $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1074 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
1077 * default language setting
1079 $variant = $wgContLang->getDefaultVariant();
1080 $defOpt['variant'] = $variant;
1081 $defOpt['language'] = $variant;
1082 foreach( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1083 $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1085 $defOpt['skin'] = $wgDefaultSkin;
1091 * Get a given default option value.
1093 * @param $opt \string Name of option to retrieve
1094 * @return \string Default option value
1096 public static function getDefaultOption( $opt ) {
1097 $defOpts = self::getDefaultOptions();
1098 if( isset( $defOpts[$opt] ) ) {
1099 return $defOpts[$opt];
1107 * Get blocking information
1109 * @param $bFromSlave \bool Whether to check the slave database first. To
1110 * improve performance, non-critical checks are done
1111 * against slaves. Check when actually saving should be
1112 * done against master.
1114 function getBlockedStatus( $bFromSlave = true ) {
1115 global $wgProxyWhitelist, $wgUser;
1117 if ( -1 != $this->mBlockedby ) {
1118 wfDebug( "User::getBlockedStatus: already loaded.\n" );
1122 wfProfileIn( __METHOD__ );
1123 wfDebug( __METHOD__.": checking...\n" );
1125 // Initialize data...
1126 // Otherwise something ends up stomping on $this->mBlockedby when
1127 // things get lazy-loaded later, causing false positive block hits
1128 // due to -1 !== 0. Probably session-related... Nothing should be
1129 // overwriting mBlockedby, surely?
1132 $this->mBlockedby = 0;
1133 $this->mHideName = 0;
1134 $this->mAllowUsertalk = 0;
1136 # Check if we are looking at an IP or a logged-in user
1137 if ( $this->isIP( $this->getName() ) ) {
1138 $ip = $this->getName();
1140 # Check if we are looking at the current user
1141 # If we don't, and the user is logged in, we don't know about
1142 # his IP / autoblock status, so ignore autoblock of current user's IP
1143 if ( $this->getID() != $wgUser->getID() ) {
1146 # Get IP of current user
1151 if ( $this->isAllowed( 'ipblock-exempt' ) ) {
1152 # Exempt from all types of IP-block
1157 $this->mBlock = new Block();
1158 $this->mBlock->fromMaster( !$bFromSlave );
1159 if ( $this->mBlock->load( $ip , $this->mId ) ) {
1160 wfDebug( __METHOD__ . ": Found block.\n" );
1161 $this->mBlockedby = $this->mBlock->mBy;
1162 if( $this->mBlockedby == 0 )
1163 $this->mBlockedby = $this->mBlock->mByName;
1164 $this->mBlockreason = $this->mBlock->mReason;
1165 $this->mHideName = $this->mBlock->mHideName;
1166 $this->mAllowUsertalk = $this->mBlock->mAllowUsertalk;
1167 if ( $this->isLoggedIn() && $wgUser->getID() == $this->getID() ) {
1168 $this->spreadBlock();
1171 // Bug 13611: don't remove mBlock here, to allow account creation blocks to
1172 // apply to users. Note that the existence of $this->mBlock is not used to
1173 // check for edit blocks, $this->mBlockedby is instead.
1177 if ( !$this->isAllowed( 'proxyunbannable' ) && !in_array( $ip, $wgProxyWhitelist ) ) {
1179 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1180 $this->mBlockedby = wfMsg( 'proxyblocker' );
1181 $this->mBlockreason = wfMsg( 'proxyblockreason' );
1185 if ( !$this->mBlockedby && !$this->getID() ) {
1186 if ( $this->isDnsBlacklisted( $ip ) ) {
1187 $this->mBlockedby = wfMsg( 'sorbs' );
1188 $this->mBlockreason = wfMsg( 'sorbsreason' );
1194 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1196 wfProfileOut( __METHOD__ );
1200 * Whether the given IP is in a DNS blacklist.
1202 * @param $ip \string IP to check
1203 * @param $checkWhitelist Boolean: whether to check the whitelist first
1204 * @return \bool True if blacklisted.
1206 function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1207 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1208 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1210 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
1213 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
1216 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1217 return $this->inDnsBlacklist( $ip, $urls );
1221 * Whether the given IP is in a given DNS blacklist.
1223 * @param $ip \string IP to check
1224 * @param $bases \string or Array of Strings: URL of the DNS blacklist
1225 * @return \bool True if blacklisted.
1227 function inDnsBlacklist( $ip, $bases ) {
1228 wfProfileIn( __METHOD__ );
1231 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1232 if( IP::isIPv4( $ip ) ) {
1233 # Reverse IP, bug 21255
1234 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1236 foreach( (array)$bases as $base ) {
1238 $host = "$ipReversed.$base";
1241 $ipList = gethostbynamel( $host );
1244 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1248 wfDebug( "Requested $host, not found in $base.\n" );
1253 wfProfileOut( __METHOD__ );
1258 * Is this user subject to rate limiting?
1260 * @return \bool True if rate limited
1262 public function isPingLimitable() {
1263 global $wgRateLimitsExcludedGroups;
1264 global $wgRateLimitsExcludedIPs;
1265 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1266 // Deprecated, but kept for backwards-compatibility config
1269 if( in_array( wfGetIP(), $wgRateLimitsExcludedIPs ) ) {
1270 // No other good way currently to disable rate limits
1271 // for specific IPs. :P
1272 // But this is a crappy hack and should die.
1275 return !$this->isAllowed('noratelimit');
1279 * Primitive rate limits: enforce maximum actions per time period
1280 * to put a brake on flooding.
1282 * @note When using a shared cache like memcached, IP-address
1283 * last-hit counters will be shared across wikis.
1285 * @param $action \string Action to enforce; 'edit' if unspecified
1286 * @return \bool True if a rate limiter was tripped
1288 function pingLimiter( $action = 'edit' ) {
1289 # Call the 'PingLimiter' hook
1291 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1295 global $wgRateLimits;
1296 if( !isset( $wgRateLimits[$action] ) ) {
1300 # Some groups shouldn't trigger the ping limiter, ever
1301 if( !$this->isPingLimitable() )
1304 global $wgMemc, $wgRateLimitLog;
1305 wfProfileIn( __METHOD__ );
1307 $limits = $wgRateLimits[$action];
1309 $id = $this->getId();
1313 if( isset( $limits['anon'] ) && $id == 0 ) {
1314 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1317 if( isset( $limits['user'] ) && $id != 0 ) {
1318 $userLimit = $limits['user'];
1320 if( $this->isNewbie() ) {
1321 if( isset( $limits['newbie'] ) && $id != 0 ) {
1322 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1324 if( isset( $limits['ip'] ) ) {
1325 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1328 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1329 $subnet = $matches[1];
1330 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1333 // Check for group-specific permissions
1334 // If more than one group applies, use the group with the highest limit
1335 foreach ( $this->getGroups() as $group ) {
1336 if ( isset( $limits[$group] ) ) {
1337 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1338 $userLimit = $limits[$group];
1342 // Set the user limit key
1343 if ( $userLimit !== false ) {
1344 wfDebug( __METHOD__ . ": effective user limit: $userLimit\n" );
1345 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1349 foreach( $keys as $key => $limit ) {
1350 list( $max, $period ) = $limit;
1351 $summary = "(limit $max in {$period}s)";
1352 $count = $wgMemc->get( $key );
1355 if( $count > $max ) {
1356 wfDebug( __METHOD__ . ": tripped! $key at $count $summary\n" );
1357 if( $wgRateLimitLog ) {
1358 @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1362 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1365 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1366 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1368 $wgMemc->incr( $key );
1371 wfProfileOut( __METHOD__ );
1376 * Check if user is blocked
1378 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1379 * @return \bool True if blocked, false otherwise
1381 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1382 wfDebug( "User::isBlocked: enter\n" );
1383 $this->getBlockedStatus( $bFromSlave );
1384 return $this->mBlockedby !== 0;
1388 * Check if user is blocked from editing a particular article
1390 * @param $title \string Title to check
1391 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1392 * @return \bool True if blocked, false otherwise
1394 function isBlockedFrom( $title, $bFromSlave = false ) {
1395 global $wgBlockAllowsUTEdit;
1396 wfProfileIn( __METHOD__ );
1397 wfDebug( __METHOD__ . ": enter\n" );
1399 wfDebug( __METHOD__ . ": asking isBlocked()\n" );
1400 $blocked = $this->isBlocked( $bFromSlave );
1401 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1402 # If a user's name is suppressed, they cannot make edits anywhere
1403 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName() &&
1404 $title->getNamespace() == NS_USER_TALK ) {
1406 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1409 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1411 wfProfileOut( __METHOD__ );
1416 * If user is blocked, return the name of the user who placed the block
1417 * @return \string name of blocker
1419 function blockedBy() {
1420 $this->getBlockedStatus();
1421 return $this->mBlockedby;
1425 * If user is blocked, return the specified reason for the block
1426 * @return \string Blocking reason
1428 function blockedFor() {
1429 $this->getBlockedStatus();
1430 return $this->mBlockreason;
1434 * If user is blocked, return the ID for the block
1435 * @return \int Block ID
1437 function getBlockId() {
1438 $this->getBlockedStatus();
1439 return ( $this->mBlock ? $this->mBlock->mId : false );
1443 * Check if user is blocked on all wikis.
1444 * Do not use for actual edit permission checks!
1445 * This is intented for quick UI checks.
1447 * @param $ip \type{\string} IP address, uses current client if none given
1448 * @return \type{\bool} True if blocked, false otherwise
1450 function isBlockedGlobally( $ip = '' ) {
1451 if( $this->mBlockedGlobally !== null ) {
1452 return $this->mBlockedGlobally;
1454 // User is already an IP?
1455 if( IP::isIPAddress( $this->getName() ) ) {
1456 $ip = $this->getName();
1461 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1462 $this->mBlockedGlobally = (bool)$blocked;
1463 return $this->mBlockedGlobally;
1467 * Check if user account is locked
1469 * @return \type{\bool} True if locked, false otherwise
1471 function isLocked() {
1472 if( $this->mLocked !== null ) {
1473 return $this->mLocked;
1476 $authUser = $wgAuth->getUserInstance( $this );
1477 $this->mLocked = (bool)$authUser->isLocked();
1478 return $this->mLocked;
1482 * Check if user account is hidden
1484 * @return \type{\bool} True if hidden, false otherwise
1486 function isHidden() {
1487 if( $this->mHideName !== null ) {
1488 return $this->mHideName;
1490 $this->getBlockedStatus();
1491 if( !$this->mHideName ) {
1493 $authUser = $wgAuth->getUserInstance( $this );
1494 $this->mHideName = (bool)$authUser->isHidden();
1496 return $this->mHideName;
1500 * Get the user's ID.
1501 * @return Integer The user's ID; 0 if the user is anonymous or nonexistent
1504 if( $this->mId === null and $this->mName !== null
1505 and User::isIP( $this->mName ) ) {
1506 // Special case, we know the user is anonymous
1508 } elseif( $this->mId === null ) {
1509 // Don't load if this was initialized from an ID
1516 * Set the user and reload all fields according to a given ID
1517 * @param $v \int User ID to reload
1519 function setId( $v ) {
1521 $this->clearInstanceCache( 'id' );
1525 * Get the user name, or the IP of an anonymous user
1526 * @return \string User's name or IP address
1528 function getName() {
1529 if ( !$this->mDataLoaded && $this->mFrom == 'name' ) {
1530 # Special case optimisation
1531 return $this->mName;
1534 if ( $this->mName === false ) {
1536 $this->mName = IP::sanitizeIP( wfGetIP() );
1538 return $this->mName;
1543 * Set the user name.
1545 * This does not reload fields from the database according to the given
1546 * name. Rather, it is used to create a temporary "nonexistent user" for
1547 * later addition to the database. It can also be used to set the IP
1548 * address for an anonymous user to something other than the current
1551 * @note User::newFromName() has rougly the same function, when the named user
1553 * @param $str \string New user name to set
1555 function setName( $str ) {
1557 $this->mName = $str;
1561 * Get the user's name escaped by underscores.
1562 * @return \string Username escaped by underscores.
1564 function getTitleKey() {
1565 return str_replace( ' ', '_', $this->getName() );
1569 * Check if the user has new messages.
1570 * @return \bool True if the user has new messages
1572 function getNewtalk() {
1575 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1576 if( $this->mNewtalk === -1 ) {
1577 $this->mNewtalk = false; # reset talk page status
1579 # Check memcached separately for anons, who have no
1580 # entire User object stored in there.
1583 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1584 $newtalk = $wgMemc->get( $key );
1585 if( strval( $newtalk ) !== '' ) {
1586 $this->mNewtalk = (bool)$newtalk;
1588 // Since we are caching this, make sure it is up to date by getting it
1590 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1591 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1594 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1598 return (bool)$this->mNewtalk;
1602 * Return the talk page(s) this user has new messages on.
1603 * @return \type{\arrayof{\string}} Array of page URLs
1605 function getNewMessageLinks() {
1607 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) )
1610 if( !$this->getNewtalk() )
1612 $up = $this->getUserPage();
1613 $utp = $up->getTalkPage();
1614 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL() ) );
1618 * Internal uncached check for new messages
1621 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1622 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1623 * @param $fromMaster \bool true to fetch from the master, false for a slave
1624 * @return \bool True if the user has new messages
1627 function checkNewtalk( $field, $id, $fromMaster = false ) {
1628 if ( $fromMaster ) {
1629 $db = wfGetDB( DB_MASTER );
1631 $db = wfGetDB( DB_SLAVE );
1633 $ok = $db->selectField( 'user_newtalk', $field,
1634 array( $field => $id ), __METHOD__ );
1635 return $ok !== false;
1639 * Add or update the new messages flag
1640 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1641 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1642 * @return \bool True if successful, false otherwise
1645 function updateNewtalk( $field, $id ) {
1646 $dbw = wfGetDB( DB_MASTER );
1647 $dbw->insert( 'user_newtalk',
1648 array( $field => $id ),
1651 if ( $dbw->affectedRows() ) {
1652 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
1655 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
1661 * Clear the new messages flag for the given user
1662 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1663 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1664 * @return \bool True if successful, false otherwise
1667 function deleteNewtalk( $field, $id ) {
1668 $dbw = wfGetDB( DB_MASTER );
1669 $dbw->delete( 'user_newtalk',
1670 array( $field => $id ),
1672 if ( $dbw->affectedRows() ) {
1673 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
1676 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
1682 * Update the 'You have new messages!' status.
1683 * @param $val \bool Whether the user has new messages
1685 function setNewtalk( $val ) {
1686 if( wfReadOnly() ) {
1691 $this->mNewtalk = $val;
1693 if( $this->isAnon() ) {
1695 $id = $this->getName();
1698 $id = $this->getId();
1703 $changed = $this->updateNewtalk( $field, $id );
1705 $changed = $this->deleteNewtalk( $field, $id );
1708 if( $this->isAnon() ) {
1709 // Anons have a separate memcached space, since
1710 // user records aren't kept for them.
1711 $key = wfMemcKey( 'newtalk', 'ip', $id );
1712 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
1715 $this->invalidateCache();
1720 * Generate a current or new-future timestamp to be stored in the
1721 * user_touched field when we update things.
1722 * @return \string Timestamp in TS_MW format
1724 private static function newTouchedTimestamp() {
1725 global $wgClockSkewFudge;
1726 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1730 * Clear user data from memcached.
1731 * Use after applying fun updates to the database; caller's
1732 * responsibility to update user_touched if appropriate.
1734 * Called implicitly from invalidateCache() and saveSettings().
1736 private function clearSharedCache() {
1740 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1745 * Immediately touch the user data cache for this account.
1746 * Updates user_touched field, and removes account data from memcached
1747 * for reload on the next hit.
1749 function invalidateCache() {
1750 if( wfReadOnly() ) {
1755 $this->mTouched = self::newTouchedTimestamp();
1757 $dbw = wfGetDB( DB_MASTER );
1758 $dbw->update( 'user',
1759 array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
1760 array( 'user_id' => $this->mId ),
1763 $this->clearSharedCache();
1768 * Validate the cache for this account.
1769 * @param $timestamp \string A timestamp in TS_MW format
1771 function validateCache( $timestamp ) {
1773 return ( $timestamp >= $this->mTouched );
1777 * Get the user touched timestamp
1779 function getTouched() {
1781 return $this->mTouched;
1785 * Set the password and reset the random token.
1786 * Calls through to authentication plugin if necessary;
1787 * will have no effect if the auth plugin refuses to
1788 * pass the change through or if the legal password
1791 * As a special case, setting the password to null
1792 * wipes it, so the account cannot be logged in until
1793 * a new password is set, for instance via e-mail.
1795 * @param $str \string New password to set
1796 * @throws PasswordError on failure
1798 function setPassword( $str ) {
1801 if( $str !== null ) {
1802 if( !$wgAuth->allowPasswordChange() ) {
1803 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1806 if( !$this->isValidPassword( $str ) ) {
1807 global $wgMinimalPasswordLength;
1808 $valid = $this->getPasswordValidity( $str );
1809 throw new PasswordError( wfMsgExt( $valid, array( 'parsemag' ),
1810 $wgMinimalPasswordLength ) );
1814 if( !$wgAuth->setPassword( $this, $str ) ) {
1815 throw new PasswordError( wfMsg( 'externaldberror' ) );
1818 $this->setInternalPassword( $str );
1824 * Set the password and reset the random token unconditionally.
1826 * @param $str \string New password to set
1828 function setInternalPassword( $str ) {
1832 if( $str === null ) {
1833 // Save an invalid hash...
1834 $this->mPassword = '';
1836 $this->mPassword = self::crypt( $str );
1838 $this->mNewpassword = '';
1839 $this->mNewpassTime = null;
1843 * Get the user's current token.
1844 * @param $forceCreation Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility)
1845 * @return \string Token
1847 function getToken( $forceCreation = true ) {
1849 if ( !$this->mToken && $forceCreation ) {
1852 return $this->mToken;
1856 * Set the random token (used for persistent authentication)
1857 * Called from loadDefaults() among other places.
1859 * @param $token \string If specified, set the token to this value
1862 function setToken( $token = false ) {
1863 global $wgSecretKey, $wgProxyKey;
1866 $this->mToken = MWCryptRand::generateHex( USER_TOKEN_LENGTH );
1868 $this->mToken = $token;
1873 * Set the cookie password
1875 * @param $str \string New cookie password
1878 function setCookiePassword( $str ) {
1880 $this->mCookiePassword = md5( $str );
1884 * Set the password for a password reminder or new account email
1886 * @param $str \string New password to set
1887 * @param $throttle \bool If true, reset the throttle timestamp to the present
1889 function setNewpassword( $str, $throttle = true ) {
1891 $this->mNewpassword = self::crypt( $str );
1893 $this->mNewpassTime = wfTimestampNow();
1898 * Has password reminder email been sent within the last
1899 * $wgPasswordReminderResendTime hours?
1900 * @return \bool True or false
1902 function isPasswordReminderThrottled() {
1903 global $wgPasswordReminderResendTime;
1905 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1908 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1909 return time() < $expiry;
1913 * Get the user's e-mail address
1914 * @return \string User's email address
1916 function getEmail() {
1918 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
1919 return $this->mEmail;
1923 * Get the timestamp of the user's e-mail authentication
1924 * @return \string TS_MW timestamp
1926 function getEmailAuthenticationTimestamp() {
1928 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
1929 return $this->mEmailAuthenticated;
1933 * Set the user's e-mail address
1934 * @param $str \string New e-mail address
1936 function setEmail( $str ) {
1938 $this->mEmail = $str;
1939 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
1943 * Get the user's real name
1944 * @return \string User's real name
1946 function getRealName() {
1948 return $this->mRealName;
1952 * Set the user's real name
1953 * @param $str \string New real name
1955 function setRealName( $str ) {
1957 $this->mRealName = $str;
1961 * Get the user's current setting for a given option.
1963 * @param $oname \string The option to check
1964 * @param $defaultOverride \string A default value returned if the option does not exist
1965 * @return \string User's current value for the option
1966 * @see getBoolOption()
1967 * @see getIntOption()
1969 function getOption( $oname, $defaultOverride = null ) {
1970 $this->loadOptions();
1972 if ( is_null( $this->mOptions ) ) {
1973 if($defaultOverride != '') {
1974 return $defaultOverride;
1976 $this->mOptions = User::getDefaultOptions();
1979 if ( array_key_exists( $oname, $this->mOptions ) ) {
1980 return $this->mOptions[$oname];
1982 return $defaultOverride;
1987 * Get all user's options
1991 public function getOptions() {
1992 $this->loadOptions();
1993 return $this->mOptions;
1997 * Get the user's current setting for a given option, as a boolean value.
1999 * @param $oname \string The option to check
2000 * @return \bool User's current value for the option
2003 function getBoolOption( $oname ) {
2004 return (bool)$this->getOption( $oname );
2009 * Get the user's current setting for a given option, as a boolean value.
2011 * @param $oname \string The option to check
2012 * @param $defaultOverride \int A default value returned if the option does not exist
2013 * @return \int User's current value for the option
2016 function getIntOption( $oname, $defaultOverride=0 ) {
2017 $val = $this->getOption( $oname );
2019 $val = $defaultOverride;
2021 return intval( $val );
2025 * Set the given option for a user.
2027 * @param $oname \string The option to set
2028 * @param $val \mixed New value to set
2030 function setOption( $oname, $val ) {
2032 $this->loadOptions();
2034 if ( $oname == 'skin' ) {
2035 # Clear cached skin, so the new one displays immediately in Special:Preferences
2036 $this->mSkin = null;
2039 // Explicitly NULL values should refer to defaults
2040 global $wgDefaultUserOptions;
2041 if( is_null( $val ) && isset( $wgDefaultUserOptions[$oname] ) ) {
2042 $val = $wgDefaultUserOptions[$oname];
2045 $this->mOptions[$oname] = $val;
2049 * Reset all options to the site defaults
2051 function resetOptions() {
2052 $this->mOptions = User::getDefaultOptions();
2056 * Get the user's preferred date format.
2057 * @return \string User's preferred date format
2059 function getDatePreference() {
2060 // Important migration for old data rows
2061 if ( is_null( $this->mDatePreference ) ) {
2063 $value = $this->getOption( 'date' );
2064 $map = $wgLang->getDatePreferenceMigrationMap();
2065 if ( isset( $map[$value] ) ) {
2066 $value = $map[$value];
2068 $this->mDatePreference = $value;
2070 return $this->mDatePreference;
2074 * Get the user preferred stub threshold
2076 function getStubThreshold() {
2077 global $wgMaxArticleSize; # Maximum article size, in Kb
2078 $threshold = intval( $this->getOption( 'stubthreshold' ) );
2079 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2080 # If they have set an impossible value, disable the preference
2081 # so we can use the parser cache again.
2088 * Get the permissions this user has.
2089 * @return \type{\arrayof{\string}} Array of permission names
2091 function getRights() {
2092 if ( is_null( $this->mRights ) ) {
2093 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2094 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2095 // Force reindexation of rights when a hook has unset one of them
2096 $this->mRights = array_values( $this->mRights );
2098 return $this->mRights;
2102 * Get the list of explicit group memberships this user has.
2103 * The implicit * and user groups are not included.
2104 * @return \type{\arrayof{\string}} Array of internal group names
2106 function getGroups() {
2108 return $this->mGroups;
2112 * Get the list of implicit group memberships this user has.
2113 * This includes all explicit groups, plus 'user' if logged in,
2114 * '*' for all accounts and autopromoted groups
2115 * @param $recache \bool Whether to avoid the cache
2116 * @return \type{\arrayof{\string}} Array of internal group names
2118 function getEffectiveGroups( $recache = false ) {
2119 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2120 wfProfileIn( __METHOD__ );
2121 $this->mEffectiveGroups = $this->getGroups();
2122 $this->mEffectiveGroups[] = '*';
2123 if( $this->getId() ) {
2124 $this->mEffectiveGroups[] = 'user';
2126 $this->mEffectiveGroups = array_unique( array_merge(
2127 $this->mEffectiveGroups,
2128 Autopromote::getAutopromoteGroups( $this )
2131 # Hook for additional groups
2132 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2134 wfProfileOut( __METHOD__ );
2136 return $this->mEffectiveGroups;
2140 * Get the user's edit count.
2141 * @return \int User'e edit count
2143 function getEditCount() {
2144 if( $this->getId() ) {
2145 if ( !isset( $this->mEditCount ) ) {
2146 /* Populate the count, if it has not been populated yet */
2147 $this->mEditCount = User::edits( $this->mId );
2149 return $this->mEditCount;
2157 * Add the user to the given group.
2158 * This takes immediate effect.
2159 * @param $group \string Name of the group to add
2161 function addGroup( $group ) {
2162 $dbw = wfGetDB( DB_MASTER );
2163 if( $this->getId() ) {
2164 $dbw->insert( 'user_groups',
2166 'ug_user' => $this->getID(),
2167 'ug_group' => $group,
2170 array( 'IGNORE' ) );
2173 $this->loadGroups();
2174 $this->mGroups[] = $group;
2175 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2177 $this->invalidateCache();
2181 * Remove the user from the given group.
2182 * This takes immediate effect.
2183 * @param $group \string Name of the group to remove
2185 function removeGroup( $group ) {
2187 $dbw = wfGetDB( DB_MASTER );
2188 $dbw->delete( 'user_groups',
2190 'ug_user' => $this->getID(),
2191 'ug_group' => $group,
2194 $this->loadGroups();
2195 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2196 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2198 $this->invalidateCache();
2202 * Get whether the user is logged in
2203 * @return \bool True or false
2205 function isLoggedIn() {
2206 return $this->getID() != 0;
2210 * Get whether the user is anonymous
2211 * @return \bool True or false
2214 return !$this->isLoggedIn();
2218 * Get whether the user is a bot
2219 * @return \bool True or false
2223 wfDeprecated( __METHOD__ );
2224 return $this->isAllowed( 'bot' );
2228 * Check if user is allowed to access a feature / make an action
2229 * @param $action \string action to be checked
2230 * @return Boolean: True if action is allowed, else false
2232 function isAllowed( $action = '' ) {
2233 if ( $action === '' ) {
2234 return true; // In the spirit of DWIM
2236 # Patrolling may not be enabled
2237 if( $action === 'patrol' || $action === 'autopatrol' ) {
2238 global $wgUseRCPatrol, $wgUseNPPatrol;
2239 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2242 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2243 # by misconfiguration: 0 == 'foo'
2244 return in_array( $action, $this->getRights(), true );
2248 * Check whether to enable recent changes patrol features for this user
2249 * @return Boolean: True or false
2251 public function useRCPatrol() {
2252 global $wgUseRCPatrol;
2253 return( $wgUseRCPatrol && ( $this->isAllowed( 'patrol' ) || $this->isAllowed( 'patrolmarks' ) ) );
2257 * Check whether to enable new pages patrol features for this user
2258 * @return \bool True or false
2260 public function useNPPatrol() {
2261 global $wgUseRCPatrol, $wgUseNPPatrol;
2262 return( ( $wgUseRCPatrol || $wgUseNPPatrol ) && ( $this->isAllowed( 'patrol' ) || $this->isAllowed( 'patrolmarks' ) ) );
2266 * Get the current skin, loading it if required, and setting a title
2267 * @param $t Title: the title to use in the skin
2268 * @return Skin The current skin
2269 * @todo FIXME : need to check the old failback system [AV]
2271 function getSkin( $t = null ) {
2272 if( !$this->mSkin ) {
2274 $this->mSkin = $this->createSkinObject();
2275 $this->mSkin->setTitle( $wgOut->getTitle() );
2277 if ( $t && ( !$this->mSkin->getTitle() || !$t->equals( $this->mSkin->getTitle() ) ) ) {
2278 $skin = $this->createSkinObject();
2279 $skin->setTitle( $t );
2282 return $this->mSkin;
2286 // Creates a Skin object, for getSkin()
2287 private function createSkinObject() {
2288 wfProfileIn( __METHOD__ );
2290 global $wgHiddenPrefs;
2291 if( !in_array( 'skin', $wgHiddenPrefs ) ) {
2294 $userSkin = $this->getOption( 'skin' );
2295 $userSkin = $wgRequest->getVal( 'useskin', $userSkin );
2297 # if we're not allowing users to override, then use the default
2298 global $wgDefaultSkin;
2299 $userSkin = $wgDefaultSkin;
2302 $skin = Skin::newFromKey( $userSkin );
2303 wfProfileOut( __METHOD__ );
2309 * Check the watched status of an article.
2310 * @param $title \type{Title} Title of the article to look at
2311 * @return \bool True if article is watched
2313 function isWatched( $title ) {
2314 $wl = WatchedItem::fromUserTitle( $this, $title );
2315 return $wl->isWatched();
2320 * @param $title \type{Title} Title of the article to look at
2322 function addWatch( $title ) {
2323 $wl = WatchedItem::fromUserTitle( $this, $title );
2325 $this->invalidateCache();
2329 * Stop watching an article.
2330 * @param $title \type{Title} Title of the article to look at
2332 function removeWatch( $title ) {
2333 $wl = WatchedItem::fromUserTitle( $this, $title );
2335 $this->invalidateCache();
2339 * Clear the user's notification timestamp for the given title.
2340 * If e-notif e-mails are on, they will receive notification mails on
2341 * the next change of the page if it's watched etc.
2342 * @param $title \type{Title} Title of the article to look at
2344 function clearNotification( &$title ) {
2345 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2347 # Do nothing if the database is locked to writes
2348 if( wfReadOnly() ) {
2352 if( $title->getNamespace() == NS_USER_TALK &&
2353 $title->getText() == $this->getName() ) {
2354 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2356 $this->setNewtalk( false );
2359 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2363 if( $this->isAnon() ) {
2364 // Nothing else to do...
2368 // Only update the timestamp if the page is being watched.
2369 // The query to find out if it is watched is cached both in memcached and per-invocation,
2370 // and when it does have to be executed, it can be on a slave
2371 // If this is the user's newtalk page, we always update the timestamp
2372 if( $title->getNamespace() == NS_USER_TALK &&
2373 $title->getText() == $wgUser->getName() )
2376 } elseif ( $this->getId() == $wgUser->getId() ) {
2377 $watched = $title->userIsWatching();
2382 // If the page is watched by the user (or may be watched), update the timestamp on any
2383 // any matching rows
2385 $dbw = wfGetDB( DB_MASTER );
2386 $dbw->update( 'watchlist',
2388 'wl_notificationtimestamp' => null
2389 ), array( /* WHERE */
2390 'wl_title' => $title->getDBkey(),
2391 'wl_namespace' => $title->getNamespace(),
2392 'wl_user' => $this->getID()
2399 * Resets all of the given user's page-change notification timestamps.
2400 * If e-notif e-mails are on, they will receive notification mails on
2401 * the next change of any watched page.
2403 * @param $currentUser \int User ID
2405 function clearAllNotifications( $currentUser ) {
2406 global $wgUseEnotif, $wgShowUpdatedMarker;
2407 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2408 $this->setNewtalk( false );
2411 if( $currentUser != 0 ) {
2412 $dbw = wfGetDB( DB_MASTER );
2413 $dbw->update( 'watchlist',
2415 'wl_notificationtimestamp' => null
2416 ), array( /* WHERE */
2417 'wl_user' => $currentUser
2420 # We also need to clear here the "you have new message" notification for the own user_talk page
2421 # This is cleared one page view later in Article::viewUpdates();
2426 * Set this user's options from an encoded string
2427 * @param $str \string Encoded options to import
2430 function decodeOptions( $str ) {
2434 $this->mOptionsLoaded = true;
2435 $this->mOptionOverrides = array();
2437 // If an option is not set in $str, use the default value
2438 $this->mOptions = self::getDefaultOptions();
2440 $a = explode( "\n", $str );
2441 foreach ( $a as $s ) {
2443 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2444 $this->mOptions[$m[1]] = $m[2];
2445 $this->mOptionOverrides[$m[1]] = $m[2];
2451 * Set a cookie on the user's client. Wrapper for
2452 * WebResponse::setCookie
2453 * @param $name \string Name of the cookie to set
2454 * @param $value \string Value to set
2455 * @param $exp \int Expiration time, as a UNIX time value;
2456 * if 0 or not specified, use the default $wgCookieExpiration
2458 protected function setCookie( $name, $value, $exp = 0 ) {
2460 $wgRequest->response()->setcookie( $name, $value, $exp );
2464 * Clear a cookie on the user's client
2465 * @param $name \string Name of the cookie to clear
2467 protected function clearCookie( $name ) {
2468 $this->setCookie( $name, '', time() - 86400 );
2472 * Set the default cookies for this session on the user's client.
2474 function setCookies() {
2476 if ( 0 == $this->mId ) return;
2477 if ( !$this->mToken ) {
2478 // When token is empty or NULL generate a new one and then save it to the database
2479 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
2480 // Simply by setting every cell in the user_token column to NULL and letting them be
2481 // regenerated as users log back into the wiki.
2483 $this->saveSettings();
2486 'wsUserID' => $this->mId,
2487 'wsToken' => $this->mToken,
2488 'wsUserName' => $this->getName()
2491 'UserID' => $this->mId,
2492 'UserName' => $this->getName(),
2494 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2495 $cookies['Token'] = $this->mToken;
2497 $cookies['Token'] = false;
2500 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2501 #check for null, since the hook could cause a null value
2502 if ( !is_null( $session ) && isset( $_SESSION ) ){
2503 $_SESSION = $session + $_SESSION;
2505 foreach ( $cookies as $name => $value ) {
2506 if ( $value === false ) {
2507 $this->clearCookie( $name );
2509 $this->setCookie( $name, $value );
2515 * Log this user out.
2518 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
2524 * Clear the user's cookies and session, and reset the instance cache.
2528 function doLogout() {
2529 $this->clearInstanceCache( 'defaults' );
2531 $_SESSION['wsUserID'] = 0;
2533 $this->clearCookie( 'UserID' );
2534 $this->clearCookie( 'Token' );
2536 # Remember when user logged out, to prevent seeing cached pages
2537 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
2541 * Save this user's settings into the database.
2542 * @todo Only rarely do all these fields need to be set!
2544 function saveSettings() {
2546 if ( wfReadOnly() ) { return; }
2547 if ( 0 == $this->mId ) { return; }
2549 $this->mTouched = self::newTouchedTimestamp();
2551 $dbw = wfGetDB( DB_MASTER );
2552 $dbw->update( 'user',
2554 'user_name' => $this->mName,
2555 'user_password' => $this->mPassword,
2556 'user_newpassword' => $this->mNewpassword,
2557 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2558 'user_real_name' => $this->mRealName,
2559 'user_email' => $this->mEmail,
2560 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2561 'user_options' => '',
2562 'user_touched' => $dbw->timestamp( $this->mTouched ),
2563 'user_token' => strval( $this->mToken ),
2564 'user_email_token' => $this->mEmailToken,
2565 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
2566 ), array( /* WHERE */
2567 'user_id' => $this->mId
2571 $this->saveOptions();
2573 wfRunHooks( 'UserSaveSettings', array( $this ) );
2574 $this->clearSharedCache();
2575 $this->getUserPage()->invalidateCache();
2579 * If only this user's username is known, and it exists, return the user ID.
2581 function idForName() {
2582 $s = trim( $this->getName() );
2583 if ( $s === '' ) return 0;
2585 $dbr = wfGetDB( DB_SLAVE );
2586 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
2587 if ( $id === false ) {
2594 * Add a user to the database, return the user object
2596 * @param $name \string Username to add
2597 * @param $params \type{\arrayof{\string}} Non-default parameters to save to the database:
2598 * - password The user's password. Password logins will be disabled if this is omitted.
2599 * - newpassword A temporary password mailed to the user
2600 * - email The user's email address
2601 * - email_authenticated The email authentication timestamp
2602 * - real_name The user's real name
2603 * - options An associative array of non-default options
2604 * - token Random authentication token. Do not set.
2605 * - registration Registration timestamp. Do not set.
2607 * @return \type{User} A new User object, or null if the username already exists
2609 static function createNew( $name, $params = array() ) {
2612 if ( isset( $params['options'] ) ) {
2613 $user->mOptions = $params['options'] + (array)$user->mOptions;
2614 unset( $params['options'] );
2616 $dbw = wfGetDB( DB_MASTER );
2617 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2620 'user_id' => $seqVal,
2621 'user_name' => $name,
2622 'user_password' => $user->mPassword,
2623 'user_newpassword' => $user->mNewpassword,
2624 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
2625 'user_email' => $user->mEmail,
2626 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
2627 'user_real_name' => $user->mRealName,
2628 'user_options' => '',
2629 'user_token' => strval( $user->mToken ),
2630 'user_registration' => $dbw->timestamp( $user->mRegistration ),
2631 'user_editcount' => 0,
2633 foreach ( $params as $name => $value ) {
2634 $fields["user_$name"] = $value;
2636 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
2637 if ( $dbw->affectedRows() ) {
2638 $newUser = User::newFromId( $dbw->insertId() );
2646 * Add this existing user object to the database
2648 function addToDatabase() {
2650 $dbw = wfGetDB( DB_MASTER );
2651 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2652 $dbw->insert( 'user',
2654 'user_id' => $seqVal,
2655 'user_name' => $this->mName,
2656 'user_password' => $this->mPassword,
2657 'user_newpassword' => $this->mNewpassword,
2658 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2659 'user_email' => $this->mEmail,
2660 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2661 'user_real_name' => $this->mRealName,
2662 'user_options' => '',
2663 'user_token' => strval( $this->mToken ),
2664 'user_registration' => $dbw->timestamp( $this->mRegistration ),
2665 'user_editcount' => 0,
2668 $this->mId = $dbw->insertId();
2670 // Clear instance cache other than user table data, which is already accurate
2671 $this->clearInstanceCache();
2673 $this->saveOptions();
2677 * If this (non-anonymous) user is blocked, block any IP address
2678 * they've successfully logged in from.
2680 function spreadBlock() {
2681 wfDebug( __METHOD__ . "()\n" );
2683 if ( $this->mId == 0 ) {
2687 $userblock = Block::newFromDB( '', $this->mId );
2688 if ( !$userblock ) {
2692 $userblock->doAutoblock( wfGetIP() );
2696 * Generate a string which will be different for any combination of
2697 * user options which would produce different parser output.
2698 * This will be used as part of the hash key for the parser cache,
2699 * so users with the same options can share the same cached data
2702 * Extensions which require it should install 'PageRenderingHash' hook,
2703 * which will give them a chance to modify this key based on their own
2706 * @deprecated use the ParserOptions object to get the relevant options
2707 * @return \string Page rendering hash
2709 function getPageRenderingHash() {
2710 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2712 return $this->mHash;
2714 wfDeprecated( __METHOD__ );
2716 // stubthreshold is only included below for completeness,
2717 // since it disables the parser cache, its value will always
2718 // be 0 when this function is called by parsercache.
2720 $confstr = $this->getOption( 'math' );
2721 $confstr .= '!' . $this->getStubThreshold();
2722 if ( $wgUseDynamicDates ) { # This is wrong (bug 24714)
2723 $confstr .= '!' . $this->getDatePreference();
2725 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ? '1' : '' );
2726 $confstr .= '!' . $wgLang->getCode();
2727 $confstr .= '!' . $this->getOption( 'thumbsize' );
2728 // add in language specific options, if any
2729 $extra = $wgContLang->getExtraHashOptions();
2732 // Since the skin could be overloading link(), it should be
2733 // included here but in practice, none of our skins do that.
2735 $confstr .= $wgRenderHashAppend;
2737 // Give a chance for extensions to modify the hash, if they have
2738 // extra options or other effects on the parser cache.
2739 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2741 // Make it a valid memcached key fragment
2742 $confstr = str_replace( ' ', '_', $confstr );
2743 $this->mHash = $confstr;
2748 * Get whether the user is explicitly blocked from account creation.
2749 * @return \bool True if blocked
2751 function isBlockedFromCreateAccount() {
2752 $this->getBlockedStatus();
2753 return $this->mBlock && $this->mBlock->mCreateAccount;
2757 * Get whether the user is blocked from using Special:Emailuser.
2758 * @return Boolean: True if blocked
2760 function isBlockedFromEmailuser() {
2761 $this->getBlockedStatus();
2762 return $this->mBlock && $this->mBlock->mBlockEmail;
2766 * Get whether the user is allowed to create an account.
2767 * @return Boolean: True if allowed
2769 function isAllowedToCreateAccount() {
2770 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2774 * Get this user's personal page title.
2776 * @return Title: User's personal page title
2778 function getUserPage() {
2779 return Title::makeTitle( NS_USER, $this->getName() );
2783 * Get this user's talk page title.
2785 * @return Title: User's talk page title
2787 function getTalkPage() {
2788 $title = $this->getUserPage();
2789 return $title->getTalkPage();
2793 * Get the maximum valid user ID.
2794 * @return Integer: User ID
2797 function getMaxID() {
2798 static $res; // cache
2800 if ( isset( $res ) ) {
2803 $dbr = wfGetDB( DB_SLAVE );
2804 return $res = $dbr->selectField( 'user', 'max(user_id)', false, __METHOD__ );
2809 * Determine whether the user is a newbie. Newbies are either
2810 * anonymous IPs, or the most recently created accounts.
2811 * @return Boolean: True if the user is a newbie
2813 function isNewbie() {
2814 return !$this->isAllowed( 'autoconfirmed' );
2818 * Check to see if the given clear-text password is one of the accepted passwords
2819 * @param $password String: user password.
2820 * @return Boolean: True if the given password is correct, otherwise False.
2822 function checkPassword( $password ) {
2826 // Even though we stop people from creating passwords that
2827 // are shorter than this, doesn't mean people wont be able
2828 // to. Certain authentication plugins do NOT want to save
2829 // domain passwords in a mysql database, so we should
2830 // check this (in case $wgAuth->strict() is false).
2831 if( !$this->isValidPassword( $password ) ) {
2835 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2837 } elseif( $wgAuth->strict() ) {
2838 /* Auth plugin doesn't allow local authentication */
2840 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2841 /* Auth plugin doesn't allow local authentication for this user name */
2844 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
2846 } elseif ( function_exists( 'iconv' ) ) {
2847 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2848 # Check for this with iconv
2849 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2850 if ( self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) ) {
2858 * Check if the given clear-text password matches the temporary password
2859 * sent by e-mail for password reset operations.
2860 * @return Boolean: True if matches, false otherwise
2862 function checkTemporaryPassword( $plaintext ) {
2863 global $wgNewPasswordExpiry;
2864 if( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
2865 if ( is_null( $this->mNewpassTime ) ) {
2868 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
2869 return ( time() < $expiry );
2876 * Initialize (if necessary) and return a session token value
2877 * which can be used in edit forms to show that the user's
2878 * login credentials aren't being hijacked with a foreign form
2881 * @param $salt \types{\string,\arrayof{\string}} Optional function-specific data for hashing
2882 * @return \string The new edit token
2884 function editToken( $salt = '' ) {
2885 if ( $this->isAnon() ) {
2886 return EDIT_TOKEN_SUFFIX;
2888 if( !isset( $_SESSION['wsEditToken'] ) ) {
2889 $token = MWCryptRand::generateHex( 32 );
2890 $_SESSION['wsEditToken'] = $token;
2892 $token = $_SESSION['wsEditToken'];
2894 if( is_array( $salt ) ) {
2895 $salt = implode( '|', $salt );
2897 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2902 * Generate a looking random token for various uses.
2904 * @param $salt \string Optional salt value
2905 * @return \string The new random token
2907 public static function generateToken( $salt = '' ) {
2908 return MWCryptRand::generateHex( 32 );
2912 * Check given value against the token value stored in the session.
2913 * A match should confirm that the form was submitted from the
2914 * user's own login session, not a form submission from a third-party
2917 * @param $val \string Input value to compare
2918 * @param $salt \string Optional function-specific data for hashing
2919 * @return Boolean: Whether the token matches
2921 function matchEditToken( $val, $salt = '' ) {
2922 $sessionToken = $this->editToken( $salt );
2923 if ( $val != $sessionToken ) {
2924 wfDebug( "User::matchEditToken: broken session data\n" );
2926 return $val == $sessionToken;
2930 * Check given value against the token value stored in the session,
2931 * ignoring the suffix.
2933 * @param $val \string Input value to compare
2934 * @param $salt \string Optional function-specific data for hashing
2935 * @return Boolean: Whether the token matches
2937 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2938 $sessionToken = $this->editToken( $salt );
2939 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2943 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2944 * mail to the user's given address.
2946 * @param $type String: message to send, either "created", "changed" or "set"
2947 * @return Status object
2949 function sendConfirmationMail( $type = 'created' ) {
2951 $expiration = null; // gets passed-by-ref and defined in next line.
2952 $token = $this->confirmationToken( $expiration );
2953 $url = $this->confirmationTokenUrl( $token );
2954 $invalidateURL = $this->invalidationTokenUrl( $token );
2955 $this->saveSettings();
2957 if ( $type == 'created' || $type === false ) {
2958 $message = 'confirmemail_body';
2959 } elseif ( $type === true ) {
2960 $message = 'confirmemail_body_changed';
2962 $message = 'confirmemail_body_' . $type;
2965 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2970 $wgLang->timeanddate( $expiration, false ),
2972 $wgLang->date( $expiration, false ),
2973 $wgLang->time( $expiration, false ) ) );
2977 * Send an e-mail to this user's account. Does not check for
2978 * confirmed status or validity.
2980 * @param $subject \string Message subject
2981 * @param $body \string Message body
2982 * @param $from \string Optional From address; if unspecified, default $wgPasswordSender will be used
2983 * @param $replyto \string Reply-To address
2984 * @return Status object
2986 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2987 if( is_null( $from ) ) {
2988 global $wgPasswordSender, $wgPasswordSenderName;
2989 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
2991 $sender = new MailAddress( $from );
2994 $to = new MailAddress( $this );
2995 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
2999 * Generate, store, and return a new e-mail confirmation code.
3000 * A hash (unsalted, since it's used as a key) is stored.
3002 * @note Call saveSettings() after calling this function to commit
3003 * this change to the database.
3005 * @param[out] &$expiration \mixed Accepts the expiration time
3006 * @return \string New token
3009 function confirmationToken( &$expiration ) {
3011 $expires = $now + 7 * 24 * 60 * 60;
3013 $token = MWCryptRand::generateHex( 32 );
3014 $hash = md5( $token );
3016 $this->mEmailToken = $hash;
3017 $this->mEmailTokenExpires = wfTimestamp( TS_MW, $expires );
3022 * Return a URL the user can use to confirm their email address.
3023 * @param $token \string Accepts the email confirmation token
3024 * @return \string New token URL
3027 function confirmationTokenUrl( $token ) {
3028 return $this->getTokenUrl( 'ConfirmEmail', $token );
3032 * Return a URL the user can use to invalidate their email address.
3033 * @param $token \string Accepts the email confirmation token
3034 * @return \string New token URL
3037 function invalidationTokenUrl( $token ) {
3038 return $this->getTokenUrl( 'Invalidateemail', $token );
3042 * Internal function to format the e-mail validation/invalidation URLs.
3043 * This uses $wgArticlePath directly as a quickie hack to use the
3044 * hardcoded English names of the Special: pages, for ASCII safety.
3046 * @note Since these URLs get dropped directly into emails, using the
3047 * short English names avoids insanely long URL-encoded links, which
3048 * also sometimes can get corrupted in some browsers/mailers
3049 * (bug 6957 with Gmail and Internet Explorer).
3051 * @param $page \string Special page
3052 * @param $token \string Token
3053 * @return \string Formatted URL
3055 protected function getTokenUrl( $page, $token ) {
3056 global $wgArticlePath;
3060 "Special:$page/$token",
3065 * Mark the e-mail address confirmed.
3067 * @note Call saveSettings() after calling this function to commit the change.
3069 function confirmEmail() {
3070 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3071 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3076 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3077 * address if it was already confirmed.
3079 * @note Call saveSettings() after calling this function to commit the change.
3081 function invalidateEmail() {
3083 $this->mEmailToken = null;
3084 $this->mEmailTokenExpires = null;
3085 $this->setEmailAuthenticationTimestamp( null );
3086 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3091 * Set the e-mail authentication timestamp.
3092 * @param $timestamp \string TS_MW timestamp
3094 function setEmailAuthenticationTimestamp( $timestamp ) {
3096 $this->mEmailAuthenticated = $timestamp;
3097 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
3101 * Is this user allowed to send e-mails within limits of current
3102 * site configuration?
3103 * @return Boolean: True if allowed
3105 function canSendEmail() {
3106 global $wgEnableEmail, $wgEnableUserEmail;
3107 if( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
3110 $canSend = $this->isEmailConfirmed();
3111 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3116 * Is this user allowed to receive e-mails within limits of current
3117 * site configuration?
3118 * @return Boolean: True if allowed
3120 function canReceiveEmail() {
3121 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3125 * Is this user's e-mail address valid-looking and confirmed within
3126 * limits of the current site configuration?
3128 * @note If $wgEmailAuthentication is on, this may require the user to have
3129 * confirmed their address by returning a code or using a password
3130 * sent to the address from the wiki.
3132 * @return Boolean: True if confirmed
3134 function isEmailConfirmed() {
3135 global $wgEmailAuthentication;
3138 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3139 if( $this->isAnon() )
3141 if( !self::isValidEmailAddr( $this->mEmail ) )
3143 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
3152 * Check whether there is an outstanding request for e-mail confirmation.
3153 * @return Boolean: True if pending
3155 function isEmailConfirmationPending() {
3156 global $wgEmailAuthentication;
3157 return $wgEmailAuthentication &&
3158 !$this->isEmailConfirmed() &&
3159 $this->mEmailToken &&
3160 $this->mEmailTokenExpires > wfTimestamp();
3164 * Get the timestamp of account creation.
3166 * @return \types{\string,\bool} string Timestamp of account creation, or false for
3167 * non-existent/anonymous user accounts.
3169 public function getRegistration() {
3170 return $this->getId() > 0
3171 ? $this->mRegistration
3176 * Get the timestamp of the first edit
3178 * @return \types{\string,\bool} string Timestamp of first edit, or false for
3179 * non-existent/anonymous user accounts.
3181 public function getFirstEditTimestamp() {
3182 if( $this->getId() == 0 ) return false; // anons
3183 $dbr = wfGetDB( DB_SLAVE );
3184 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3185 array( 'rev_user' => $this->getId() ),
3187 array( 'ORDER BY' => 'rev_timestamp ASC' )
3189 if( !$time ) return false; // no edits
3190 return wfTimestamp( TS_MW, $time );
3194 * Get the permissions associated with a given list of groups
3196 * @param $groups \type{\arrayof{\string}} List of internal group names
3197 * @return \type{\arrayof{\string}} List of permission key names for given groups combined
3199 static function getGroupPermissions( $groups ) {
3200 global $wgGroupPermissions, $wgRevokePermissions;
3202 // grant every granted permission first
3203 foreach( $groups as $group ) {
3204 if( isset( $wgGroupPermissions[$group] ) ) {
3205 $rights = array_merge( $rights,
3206 // array_filter removes empty items
3207 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3210 // now revoke the revoked permissions
3211 foreach( $groups as $group ) {
3212 if( isset( $wgRevokePermissions[$group] ) ) {
3213 $rights = array_diff( $rights,
3214 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3217 return array_unique( $rights );
3221 * Get all the groups who have a given permission
3223 * @param $role \string Role to check
3224 * @return \type{\arrayof{\string}} List of internal group names with the given permission
3226 static function getGroupsWithPermission( $role ) {
3227 global $wgGroupPermissions;
3228 $allowedGroups = array();
3229 foreach ( $wgGroupPermissions as $group => $rights ) {
3230 if ( isset( $rights[$role] ) && $rights[$role] ) {
3231 $allowedGroups[] = $group;
3234 return $allowedGroups;
3238 * Get the localized descriptive name for a group, if it exists
3240 * @param $group \string Internal group name
3241 * @return \string Localized descriptive group name
3243 static function getGroupName( $group ) {
3244 $key = "group-$group";
3245 $name = wfMsg( $key );
3246 return $name == '' || wfEmptyMsg( $key, $name )
3252 * Get the localized descriptive name for a member of a group, if it exists
3254 * @param $group \string Internal group name
3255 * @return \string Localized name for group member
3257 static function getGroupMember( $group ) {
3258 $key = "group-$group-member";
3259 $name = wfMsg( $key );
3260 return $name == '' || wfEmptyMsg( $key, $name )
3266 * Return the set of defined explicit groups.
3267 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3268 * are not included, as they are defined automatically, not in the database.
3269 * @return Array of internal group names
3271 static function getAllGroups() {
3272 global $wgGroupPermissions, $wgRevokePermissions;
3274 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3275 self::getImplicitGroups()
3280 * Get a list of all available permissions.
3281 * @return Array of permission names
3283 static function getAllRights() {
3284 if ( self::$mAllRights === false ) {
3285 global $wgAvailableRights;
3286 if ( count( $wgAvailableRights ) ) {
3287 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
3289 self::$mAllRights = self::$mCoreRights;
3291 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
3293 return self::$mAllRights;
3297 * Get a list of implicit groups
3298 * @return \type{\arrayof{\string}} Array of internal group names
3300 public static function getImplicitGroups() {
3301 global $wgImplicitGroups;
3302 $groups = $wgImplicitGroups;
3303 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3308 * Get the title of a page describing a particular group
3310 * @param $group \string Internal group name
3311 * @return \types{\type{Title},\bool} Title of the page if it exists, false otherwise
3313 static function getGroupPage( $group ) {
3314 $page = wfMsgForContent( 'grouppage-' . $group );
3315 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3316 $title = Title::newFromText( $page );
3317 if( is_object( $title ) )
3324 * Create a link to the group in HTML, if available;
3325 * else return the group name.
3327 * @param $group \string Internal name of the group
3328 * @param $text \string The text of the link
3329 * @return \string HTML link to the group
3331 static function makeGroupLinkHTML( $group, $text = '' ) {
3333 $text = self::getGroupName( $group );
3335 $title = self::getGroupPage( $group );
3338 $sk = $wgUser->getSkin();
3339 return $sk->link( $title, htmlspecialchars( $text ) );
3346 * Create a link to the group in Wikitext, if available;
3347 * else return the group name.
3349 * @param $group \string Internal name of the group
3350 * @param $text \string The text of the link
3351 * @return \string Wikilink to the group
3353 static function makeGroupLinkWiki( $group, $text = '' ) {
3355 $text = self::getGroupName( $group );
3357 $title = self::getGroupPage( $group );
3359 $page = $title->getPrefixedText();
3360 return "[[$page|$text]]";
3367 * Returns an array of the groups that a particular group can add/remove.
3369 * @param $group String: the group to check for whether it can add/remove
3370 * @return Array array( 'add' => array( addablegroups ),
3371 * 'remove' => array( removablegroups ),
3372 * 'add-self' => array( addablegroups to self),
3373 * 'remove-self' => array( removable groups from self) )
3375 static function changeableByGroup( $group ) {
3376 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
3378 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
3379 if( empty( $wgAddGroups[$group] ) ) {
3380 // Don't add anything to $groups
3381 } elseif( $wgAddGroups[$group] === true ) {
3382 // You get everything
3383 $groups['add'] = self::getAllGroups();
3384 } elseif( is_array( $wgAddGroups[$group] ) ) {
3385 $groups['add'] = $wgAddGroups[$group];
3388 // Same thing for remove
3389 if( empty( $wgRemoveGroups[$group] ) ) {
3390 } elseif( $wgRemoveGroups[$group] === true ) {
3391 $groups['remove'] = self::getAllGroups();
3392 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
3393 $groups['remove'] = $wgRemoveGroups[$group];
3396 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
3397 if( empty( $wgGroupsAddToSelf['user']) || $wgGroupsAddToSelf['user'] !== true ) {
3398 foreach( $wgGroupsAddToSelf as $key => $value ) {
3399 if( is_int( $key ) ) {
3400 $wgGroupsAddToSelf['user'][] = $value;
3405 if( empty( $wgGroupsRemoveFromSelf['user']) || $wgGroupsRemoveFromSelf['user'] !== true ) {
3406 foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
3407 if( is_int( $key ) ) {
3408 $wgGroupsRemoveFromSelf['user'][] = $value;
3413 // Now figure out what groups the user can add to him/herself
3414 if( empty( $wgGroupsAddToSelf[$group] ) ) {
3415 } elseif( $wgGroupsAddToSelf[$group] === true ) {
3416 // No idea WHY this would be used, but it's there
3417 $groups['add-self'] = User::getAllGroups();
3418 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
3419 $groups['add-self'] = $wgGroupsAddToSelf[$group];
3422 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
3423 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
3424 $groups['remove-self'] = User::getAllGroups();
3425 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
3426 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
3433 * Returns an array of groups that this user can add and remove
3434 * @return Array array( 'add' => array( addablegroups ),
3435 * 'remove' => array( removablegroups ),
3436 * 'add-self' => array( addablegroups to self),
3437 * 'remove-self' => array( removable groups from self) )
3439 function changeableGroups() {
3440 if( $this->isAllowed( 'userrights' ) ) {
3441 // This group gives the right to modify everything (reverse-
3442 // compatibility with old "userrights lets you change
3444 // Using array_merge to make the groups reindexed
3445 $all = array_merge( User::getAllGroups() );
3449 'add-self' => array(),
3450 'remove-self' => array()
3454 // Okay, it's not so simple, we will have to go through the arrays
3457 'remove' => array(),
3458 'add-self' => array(),
3459 'remove-self' => array()
3461 $addergroups = $this->getEffectiveGroups();
3463 foreach( $addergroups as $addergroup ) {
3464 $groups = array_merge_recursive(
3465 $groups, $this->changeableByGroup( $addergroup )
3467 $groups['add'] = array_unique( $groups['add'] );
3468 $groups['remove'] = array_unique( $groups['remove'] );
3469 $groups['add-self'] = array_unique( $groups['add-self'] );
3470 $groups['remove-self'] = array_unique( $groups['remove-self'] );
3476 * Increment the user's edit-count field.
3477 * Will have no effect for anonymous users.
3479 function incEditCount() {
3480 if( !$this->isAnon() ) {
3481 $dbw = wfGetDB( DB_MASTER );
3482 $dbw->update( 'user',
3483 array( 'user_editcount=user_editcount+1' ),
3484 array( 'user_id' => $this->getId() ),
3487 // Lazy initialization check...
3488 if( $dbw->affectedRows() == 0 ) {
3489 // Pull from a slave to be less cruel to servers
3490 // Accuracy isn't the point anyway here
3491 $dbr = wfGetDB( DB_SLAVE );
3492 $count = $dbr->selectField( 'revision',
3494 array( 'rev_user' => $this->getId() ),
3497 // Now here's a goddamn hack...
3498 if( $dbr !== $dbw ) {
3499 // If we actually have a slave server, the count is
3500 // at least one behind because the current transaction
3501 // has not been committed and replicated.
3504 // But if DB_SLAVE is selecting the master, then the
3505 // count we just read includes the revision that was
3506 // just added in the working transaction.
3509 $dbw->update( 'user',
3510 array( 'user_editcount' => $count ),
3511 array( 'user_id' => $this->getId() ),
3515 // edit count in user cache too
3516 $this->invalidateCache();
3520 * Get the description of a given right
3522 * @param $right \string Right to query
3523 * @return \string Localized description of the right
3525 static function getRightDescription( $right ) {
3526 $key = "right-$right";
3527 $name = wfMsg( $key );
3528 return $name == '' || wfEmptyMsg( $key, $name )
3534 * Make an old-style password hash
3536 * @param $password \string Plain-text password
3537 * @param $userId \string User ID
3538 * @return \string Password hash
3540 static function oldCrypt( $password, $userId ) {
3541 global $wgPasswordSalt;
3542 if ( $wgPasswordSalt ) {
3543 return md5( $userId . '-' . md5( $password ) );
3545 return md5( $password );
3550 * Make a new-style password hash
3552 * @param $password \string Plain-text password
3553 * @param $salt \string Optional salt, may be random or the user ID.
3554 * If unspecified or false, will generate one automatically
3555 * @return \string Password hash
3557 static function crypt( $password, $salt = false ) {
3558 global $wgPasswordSalt;
3561 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3565 if( $wgPasswordSalt ) {
3566 if ( $salt === false ) {
3567 $salt = MWCryptRand::generateHex( 8 );
3569 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3571 return ':A:' . md5( $password );
3576 * Compare a password hash with a plain-text password. Requires the user
3577 * ID if there's a chance that the hash is an old-style hash.
3579 * @param $hash \string Password hash
3580 * @param $password \string Plain-text password to compare
3581 * @param $userId \string User ID for old-style password salt
3584 static function comparePasswords( $hash, $password, $userId = false ) {
3585 $type = substr( $hash, 0, 3 );
3588 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3592 if ( $type == ':A:' ) {
3594 return md5( $password ) === substr( $hash, 3 );
3595 } elseif ( $type == ':B:' ) {
3597 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3598 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3601 return self::oldCrypt( $password, $userId ) === $hash;
3606 * Add a newuser log entry for this user
3608 * @param $byEmail Boolean: account made by email?
3609 * @param $reason String: user supplied reason
3611 public function addNewUserLogEntry( $byEmail = false, $reason = '' ) {
3612 global $wgUser, $wgContLang, $wgNewUserLog;
3613 if( empty( $wgNewUserLog ) ) {
3614 return true; // disabled
3617 if( $this->getName() == $wgUser->getName() ) {
3620 $action = 'create2';
3622 if ( $reason === '' ) {
3623 $reason = wfMsgForContent( 'newuserlog-byemail' );
3625 $reason = $wgContLang->commaList( array(
3626 $reason, wfMsgForContent( 'newuserlog-byemail' ) ) );
3630 $log = new LogPage( 'newusers' );
3633 $this->getUserPage(),
3635 array( $this->getId() )
3641 * Add an autocreate newuser log entry for this user
3642 * Used by things like CentralAuth and perhaps other authplugins.
3644 public function addNewUserLogEntryAutoCreate() {
3645 global $wgNewUserLog, $wgLogAutocreatedAccounts;
3646 if( !$wgNewUserLog || !$wgLogAutocreatedAccounts ) {
3647 return true; // disabled
3649 $log = new LogPage( 'newusers', false );
3650 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3654 protected function loadOptions() {
3656 if ( $this->mOptionsLoaded || !$this->getId() )
3659 $this->mOptions = self::getDefaultOptions();
3661 // Maybe load from the object
3662 if ( !is_null( $this->mOptionOverrides ) ) {
3663 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
3664 foreach( $this->mOptionOverrides as $key => $value ) {
3665 $this->mOptions[$key] = $value;
3668 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
3669 // Load from database
3670 $dbr = wfGetDB( DB_SLAVE );
3672 $res = $dbr->select(
3675 array( 'up_user' => $this->getId() ),
3679 foreach ( $res as $row ) {
3680 $this->mOptionOverrides[$row->up_property] = $row->up_value;
3681 $this->mOptions[$row->up_property] = $row->up_value;
3685 $this->mOptionsLoaded = true;
3687 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
3690 protected function saveOptions() {
3691 global $wgAllowPrefChange;
3693 $extuser = ExternalUser::newFromUser( $this );
3695 $this->loadOptions();
3696 $dbw = wfGetDB( DB_MASTER );
3698 $insert_rows = array();
3700 $saveOptions = $this->mOptions;
3702 // Allow hooks to abort, for instance to save to a global profile.
3703 // Reset options to default state before saving.
3704 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) )
3707 foreach( $saveOptions as $key => $value ) {
3708 # Don't bother storing default values
3709 if ( ( is_null( self::getDefaultOption( $key ) ) &&
3710 !( $value === false || is_null($value) ) ) ||
3711 $value != self::getDefaultOption( $key ) ) {
3712 $insert_rows[] = array(
3713 'up_user' => $this->getId(),
3714 'up_property' => $key,
3715 'up_value' => $value,
3718 if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
3719 switch ( $wgAllowPrefChange[$key] ) {
3725 $extuser->setPref( $key, $value );
3731 $dbw->delete( 'user_properties', array( 'up_user' => $this->getId() ), __METHOD__ );
3732 $dbw->insert( 'user_properties', $insert_rows, __METHOD__ );
3737 * Provide an array of HTML5 attributes to put on an input element
3738 * intended for the user to enter a new password. This may include
3739 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
3741 * Do *not* use this when asking the user to enter his current password!
3742 * Regardless of configuration, users may have invalid passwords for whatever
3743 * reason (e.g., they were set before requirements were tightened up).
3744 * Only use it when asking for a new password, like on account creation or
3747 * Obviously, you still need to do server-side checking.
3749 * NOTE: A combination of bugs in various browsers means that this function
3750 * actually just returns array() unconditionally at the moment. May as
3751 * well keep it around for when the browser bugs get fixed, though.
3753 * @return array Array of HTML attributes suitable for feeding to
3754 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
3755 * That will potentially output invalid XHTML 1.0 Transitional, and will
3756 * get confused by the boolean attribute syntax used.)
3758 public static function passwordChangeInputAttribs() {
3759 global $wgMinimalPasswordLength;
3761 if ( $wgMinimalPasswordLength == 0 ) {
3765 # Note that the pattern requirement will always be satisfied if the
3766 # input is empty, so we need required in all cases.
3768 # FIXME (bug 23769): This needs to not claim the password is required
3769 # if e-mail confirmation is being used. Since HTML5 input validation
3770 # is b0rked anyway in some browsers, just return nothing. When it's
3771 # re-enabled, fix this code to not output required for e-mail
3773 #$ret = array( 'required' );
3776 # We can't actually do this right now, because Opera 9.6 will print out
3777 # the entered password visibly in its error message! When other
3778 # browsers add support for this attribute, or Opera fixes its support,
3779 # we can add support with a version check to avoid doing this on Opera
3780 # versions where it will be a problem. Reported to Opera as
3781 # DSK-262266, but they don't have a public bug tracker for us to follow.
3783 if ( $wgMinimalPasswordLength > 1 ) {
3784 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
3785 $ret['title'] = wfMsgExt( 'passwordtooshort', 'parsemag',
3786 $wgMinimalPasswordLength );
3794 * Format the user message using a hook, a template, or, failing these, a static format.
3795 * @param $subject String the subject of the message
3796 * @param $text String the content of the message
3797 * @param $signature String the signature, if provided.
3799 static protected function formatUserMessage( $subject, $text, $signature ) {
3800 if ( wfRunHooks( 'FormatUserMessage',
3801 array( $subject, &$text, $signature ) ) ) {
3803 $signature = empty($signature) ? "~~~~~" : "{$signature} ~~~~~";
3805 $template = Title::newFromText( wfMsgForContent( 'usermessage-template' ) );
3807 || $template->getNamespace() !== NS_TEMPLATE
3808 || !$template->exists() ) {
3809 $text = "\n== $subject ==\n\n$text\n\n-- $signature";
3811 $text = '{{'. $template->getText()
3812 . " | subject=$subject | body=$text | signature=$signature }}";
3820 * Leave a user a message
3821 * @param $subject String the subject of the message
3822 * @param $text String the message to leave
3823 * @param $signature String Text to leave in the signature
3824 * @param $summary String the summary for this change, defaults to
3825 * "Leave system message."
3826 * @param $editor User The user leaving the message, defaults to
3827 * "{{MediaWiki:usermessage-editor}}"
3828 * @param $flags Int default edit flags
3830 * @return boolean true if it was successful
3832 public function leaveUserMessage( $subject, $text, $signature = "",
3833 $summary = null, $editor = null, $flags = 0 ) {
3834 if ( !isset( $summary ) ) {
3835 $summary = wfMsgForContent( 'usermessage-summary' );
3838 if ( !isset( $editor ) ) {
3839 $editor = User::newFromName( wfMsgForContent( 'usermessage-editor' ) );
3840 if ( !$editor->isLoggedIn() ) {
3841 $editor->addToDatabase();
3845 $article = new Article( $this->getTalkPage() );
3846 wfRunHooks( 'SetupUserMessageArticle',
3847 array( $this, &$article, $subject, $text, $signature, $summary, $editor ) );
3850 $text = self::formatUserMessage( $subject, $text, $signature );
3851 $flags = $article->checkFlags( $flags );
3853 if ( $flags & EDIT_UPDATE ) {
3854 $text = $article->getContent() . $text;
3857 $dbw = wfGetDB( DB_MASTER );
3861 $status = $article->doEdit( $text, $summary, $flags, false, $editor );
3862 } catch ( DBQueryError $e ) {
3863 $status = Status::newFatal("DB Error");
3866 if ( $status->isGood() ) {
3867 // Set newtalk with the right user ID
3868 $this->setNewtalk( true );
3869 wfRunHooks( 'AfterUserMessage',
3870 array( $this, $article, $summary, $text, $signature, $summary, $editor ) );
3873 // The article was concurrently created
3874 wfDebug( __METHOD__ . ": Error ".$status->getWikiText() );
3878 return $status->isGood();