3 * Implements the User class for the %MediaWiki software.
8 * Int Number of characters in user_token field.
11 define( 'USER_TOKEN_LENGTH', 32 );
14 * Int Serialized record version.
17 define( 'MW_USER_VERSION', 8 );
20 * String Some punctuation to prevent editing from broken text-mangling proxies.
23 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
26 * Thrown by User::setPassword() on error.
29 class PasswordError
extends MWException
{
34 * The User object encapsulates all of the user-specific settings (user_id,
35 * name, rights, password, email address, options, last login time). Client
36 * classes use the getXXX() functions to access these fields. These functions
37 * do all the work of determining whether the user is logged in,
38 * whether the requested option can be satisfied from cookies or
39 * whether a database query is needed. Most of the settings needed
40 * for rendering normal pages are set in the cookie to minimize use
45 * Global constants made accessible as class constants so that autoloader
48 const USER_TOKEN_LENGTH
= USER_TOKEN_LENGTH
;
49 const MW_USER_VERSION
= MW_USER_VERSION
;
50 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
53 * Array of Strings List of member variables which are saved to the
54 * shared cache (memcached). Any operation which changes the
55 * corresponding database fields must call a cache-clearing function.
58 static $mCacheVars = array(
69 'mEmailAuthenticated',
76 // user_properties table
81 * Array of Strings Core rights.
82 * Each of these should have a corresponding message of the form
86 static $mCoreRights = array(
105 'editusercssjs', #deprecated
117 'move-rootuserpages',
121 'override-export-depth',
142 'userrights-interwiki',
146 * String Cached results of getAllRights()
148 static $mAllRights = false;
150 /** @name Cache variables */
152 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
153 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
154 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups, $mOptionOverrides;
158 * Bool Whether the cache variables have been loaded.
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.
174 * Lazy-initialized variables, invalidated with clearInstanceCache
176 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
177 $mBlockreason, $mBlock, $mEffectiveGroups, $mBlockedGlobally,
178 $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 String|Bool 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 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 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
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.
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
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 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 * Reset the cache used in idFromName(). For use in tests.
450 public static function resetIdByNameCache() {
451 self
::$idCacheByName = array();
455 * Does the string match an anonymous IPv4 address?
457 * This function exists for username validation, in order to reject
458 * usernames which are similar in form to IP addresses. Strings such
459 * as 300.300.300.300 will return true because it looks like an IP
460 * address, despite not being strictly valid.
462 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
463 * address because the usemod software would "cloak" anonymous IP
464 * addresses like this, if we allowed accounts like this to be created
465 * new users could get the old edits of these anonymous users.
467 * @param $name String to match
470 static function isIP( $name ) {
471 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP
::isIPv6($name);
475 * Is the input a valid username?
477 * Checks if the input is a valid username, we don't want an empty string,
478 * an IP address, anything that containins slashes (would mess up subpages),
479 * is longer than the maximum allowed username size or doesn't begin with
482 * @param $name String to match
485 static function isValidUserName( $name ) {
486 global $wgContLang, $wgMaxNameChars;
489 || User
::isIP( $name )
490 ||
strpos( $name, '/' ) !== false
491 ||
strlen( $name ) > $wgMaxNameChars
492 ||
$name != $wgContLang->ucfirst( $name ) ) {
493 wfDebugLog( 'username', __METHOD__
.
494 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
498 // Ensure that the name can't be misresolved as a different title,
499 // such as with extra namespace keys at the start.
500 $parsed = Title
::newFromText( $name );
501 if( is_null( $parsed )
502 ||
$parsed->getNamespace()
503 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
504 wfDebugLog( 'username', __METHOD__
.
505 ": '$name' invalid due to ambiguous prefixes" );
509 // Check an additional blacklist of troublemaker characters.
510 // Should these be merged into the title char list?
511 $unicodeBlacklist = '/[' .
512 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
513 '\x{00a0}' . # non-breaking space
514 '\x{2000}-\x{200f}' . # various whitespace
515 '\x{2028}-\x{202f}' . # breaks and control chars
516 '\x{3000}' . # ideographic space
517 '\x{e000}-\x{f8ff}' . # private use
519 if( preg_match( $unicodeBlacklist, $name ) ) {
520 wfDebugLog( 'username', __METHOD__
.
521 ": '$name' invalid due to blacklisted characters" );
529 * Usernames which fail to pass this function will be blocked
530 * from user login and new account registrations, but may be used
531 * internally by batch processes.
533 * If an account already exists in this form, login will be blocked
534 * by a failure to pass this function.
536 * @param $name String to match
539 static function isUsableName( $name ) {
540 global $wgReservedUsernames;
541 // Must be a valid username, obviously ;)
542 if ( !self
::isValidUserName( $name ) ) {
546 static $reservedUsernames = false;
547 if ( !$reservedUsernames ) {
548 $reservedUsernames = $wgReservedUsernames;
549 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
552 // Certain names may be reserved for batch processes.
553 foreach ( $reservedUsernames as $reserved ) {
554 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
555 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
557 if ( $reserved == $name ) {
565 * Usernames which fail to pass this function will be blocked
566 * from new account registrations, but may be used internally
567 * either by batch processes or by user accounts which have
568 * already been created.
570 * Additional blacklisting may be added here rather than in
571 * isValidUserName() to avoid disrupting existing accounts.
573 * @param $name String to match
576 static function isCreatableName( $name ) {
577 global $wgInvalidUsernameCharacters;
579 // Ensure that the username isn't longer than 235 bytes, so that
580 // (at least for the builtin skins) user javascript and css files
581 // will work. (bug 23080)
582 if( strlen( $name ) > 235 ) {
583 wfDebugLog( 'username', __METHOD__
.
584 ": '$name' invalid due to length" );
588 // Preg yells if you try to give it an empty string
589 if( $wgInvalidUsernameCharacters !== '' ) {
590 if( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
591 wfDebugLog( 'username', __METHOD__
.
592 ": '$name' invalid due to wgInvalidUsernameCharacters" );
597 return self
::isUsableName( $name );
601 * Is the input a valid password for this user?
603 * @param $password String Desired password
606 function isValidPassword( $password ) {
607 //simple boolean wrapper for getPasswordValidity
608 return $this->getPasswordValidity( $password ) === true;
612 * Given unvalidated password input, return error message on failure.
614 * @param $password String Desired password
615 * @return mixed: true on success, string or array of error message on failure
617 function getPasswordValidity( $password ) {
618 global $wgMinimalPasswordLength, $wgContLang;
620 static $blockedLogins = array(
621 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
622 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
625 $result = false; //init $result to false for the internal checks
627 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
630 if ( $result === false ) {
631 if( strlen( $password ) < $wgMinimalPasswordLength ) {
632 return 'passwordtooshort';
633 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
634 return 'password-name-match';
635 } elseif ( isset( $blockedLogins[ $this->getName() ] ) && $password == $blockedLogins[ $this->getName() ] ) {
636 return 'password-login-forbidden';
638 //it seems weird returning true here, but this is because of the
639 //initialization of $result to false above. If the hook is never run or it
640 //doesn't modify $result, then we will likely get down into this if with
644 } elseif( $result === true ) {
647 return $result; //the isValidPassword hook set a string $result and returned true
652 * Does a string look like an e-mail address?
654 * This validates an email address using an HTML5 specification found at:
655 * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
656 * Which as of 2011-01-24 says:
658 * A valid e-mail address is a string that matches the ABNF production
659 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
660 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
663 * This function is an implementation of the specification as requested in
666 * Client-side forms will use the same standard validation rules via JS or
667 * HTML 5 validation; additional restrictions can be enforced server-side
668 * by extensions via the 'isValidEmailAddr' hook.
670 * Note that this validation doesn't 100% match RFC 2822, but is believed
671 * to be liberal enough for wide use. Some invalid addresses will still
672 * pass validation here.
674 * @param $addr String E-mail address
677 public static function isValidEmailAddr( $addr ) {
679 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
683 // Please note strings below are enclosed in brackets [], this make the
684 // hyphen "-" a range indicator. Hence it is double backslashed below.
686 $rfc5322_atext = "a-z0-9!#$%&'*+\\-\/=?^_`{|}~" ;
687 $rfc1034_ldh_str = "a-z0-9\\-" ;
689 $HTML5_email_regexp = "/
691 [$rfc5322_atext\\.]+ # user part which is liberal :p
693 [$rfc1034_ldh_str]+ # First domain part
694 (\\.[$rfc1034_ldh_str]+)* # Following part prefixed with a dot
696 /ix" ; // case Insensitive, eXtended
698 return (bool) preg_match( $HTML5_email_regexp, $addr );
702 * Given unvalidated user input, return a canonical username, or false if
703 * the username is invalid.
704 * @param $name String User input
705 * @param $validate String|Bool type of validation to use:
706 * - false No validation
707 * - 'valid' Valid for batch processes
708 * - 'usable' Valid for batch processes and login
709 * - 'creatable' Valid for batch processes, login and account creation
711 static function getCanonicalName( $name, $validate = 'valid' ) {
712 # Force usernames to capital
714 $name = $wgContLang->ucfirst( $name );
716 # Reject names containing '#'; these will be cleaned up
717 # with title normalisation, but then it's too late to
719 if( strpos( $name, '#' ) !== false )
722 # Clean up name according to title rules
723 $t = ( $validate === 'valid' ) ?
724 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
725 # Check for invalid titles
726 if( is_null( $t ) ) {
730 # Reject various classes of invalid names
732 $name = $wgAuth->getCanonicalName( $t->getText() );
734 switch ( $validate ) {
738 if ( !User
::isValidUserName( $name ) ) {
743 if ( !User
::isUsableName( $name ) ) {
748 if ( !User
::isCreatableName( $name ) ) {
753 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
759 * Count the number of edits of a user
760 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
762 * @param $uid Int User ID to check
763 * @return Int the user's edit count
765 static function edits( $uid ) {
766 wfProfileIn( __METHOD__
);
767 $dbr = wfGetDB( DB_SLAVE
);
768 // check if the user_editcount field has been initialized
769 $field = $dbr->selectField(
770 'user', 'user_editcount',
771 array( 'user_id' => $uid ),
775 if( $field === null ) { // it has not been initialized. do so.
776 $dbw = wfGetDB( DB_MASTER
);
777 $count = $dbr->selectField(
778 'revision', 'count(*)',
779 array( 'rev_user' => $uid ),
784 array( 'user_editcount' => $count ),
785 array( 'user_id' => $uid ),
791 wfProfileOut( __METHOD__
);
796 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
797 * @todo hash random numbers to improve security, like generateToken()
799 * @return String new random password
801 static function randomPassword() {
802 global $wgMinimalPasswordLength;
803 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
804 $l = strlen( $pwchars ) - 1;
806 $pwlength = max( 7, $wgMinimalPasswordLength );
807 $digit = mt_rand( 0, $pwlength - 1 );
809 for ( $i = 0; $i < $pwlength; $i++
) {
810 $np .= $i == $digit ?
chr( mt_rand( 48, 57 ) ) : $pwchars{ mt_rand( 0, $l ) };
816 * Set cached properties to default.
818 * @note This no longer clears uncached lazy-initialised properties;
819 * the constructor does that instead.
822 function loadDefaults( $name = false ) {
823 wfProfileIn( __METHOD__
);
828 $this->mName
= $name;
829 $this->mRealName
= '';
830 $this->mPassword
= $this->mNewpassword
= '';
831 $this->mNewpassTime
= null;
833 $this->mOptionOverrides
= null;
834 $this->mOptionsLoaded
= false;
836 if( $wgRequest->getCookie( 'LoggedOut' ) !== null ) {
837 $this->mTouched
= wfTimestamp( TS_MW
, $wgRequest->getCookie( 'LoggedOut' ) );
839 $this->mTouched
= '0'; # Allow any pages to be cached
842 $this->setToken(); # Random
843 $this->mEmailAuthenticated
= null;
844 $this->mEmailToken
= '';
845 $this->mEmailTokenExpires
= null;
846 $this->mRegistration
= wfTimestamp( TS_MW
);
847 $this->mGroups
= array();
849 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
851 wfProfileOut( __METHOD__
);
855 * Load user data from the session or login cookie. If there are no valid
856 * credentials, initialises the user as an anonymous user.
857 * @return Bool True if the user is logged in, false otherwise.
859 private function loadFromSession() {
860 global $wgRequest, $wgExternalAuthType, $wgAutocreatePolicy;
863 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
864 if ( $result !== null ) {
868 if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
869 $extUser = ExternalUser
::newFromCookie();
871 # TODO: Automatically create the user here (or probably a bit
872 # lower down, in fact)
876 $cookieId = $wgRequest->getCookie( 'UserID' );
877 $sessId = $wgRequest->getSessionData( 'wsUserID' );
879 if ( $cookieId !== null ) {
880 $sId = intval( $cookieId );
881 if( $sessId !== null && $cookieId != $sessId ) {
882 $this->loadDefaults(); // Possible collision!
883 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
884 cookie user ID ($sId) don't match!" );
887 $wgRequest->setSessionData( 'wsUserID', $sId );
888 } else if ( $sessId !== null && $sessId != 0 ) {
891 $this->loadDefaults();
895 if ( $wgRequest->getSessionData( 'wsUserName' ) !== null ) {
896 $sName = $wgRequest->getSessionData( 'wsUserName' );
897 } else if ( $wgRequest->getCookie( 'UserName' ) !== null ) {
898 $sName = $wgRequest->getCookie( 'UserName' );
899 $wgRequest->setSessionData( 'wsUserName', $sName );
901 $this->loadDefaults();
906 if ( !$this->loadFromId() ) {
907 # Not a valid ID, loadFromId has switched the object to anon for us
911 global $wgBlockDisablesLogin;
912 if( $wgBlockDisablesLogin && $this->isBlocked() ) {
913 # User blocked and we've disabled blocked user logins
914 $this->loadDefaults();
918 if ( $wgRequest->getSessionData( 'wsToken' ) !== null ) {
919 $passwordCorrect = $this->mToken
== $wgRequest->getSessionData( 'wsToken' );
921 } else if ( $wgRequest->getCookie( 'Token' ) !== null ) {
922 $passwordCorrect = $this->mToken
== $wgRequest->getCookie( 'Token' );
925 # No session or persistent login cookie
926 $this->loadDefaults();
930 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
931 $wgRequest->setSessionData( 'wsToken', $this->mToken
);
932 wfDebug( "User: logged in from $from\n" );
935 # Invalid credentials
936 wfDebug( "User: can't log in from $from, invalid credentials\n" );
937 $this->loadDefaults();
943 * Load user and user_group data from the database.
944 * $this::mId must be set, this is how the user is identified.
946 * @return Bool True if the user exists, false if the user is anonymous
949 function loadFromDatabase() {
951 $this->mId
= intval( $this->mId
);
953 /** Anonymous user */
955 $this->loadDefaults();
959 $dbr = wfGetDB( DB_MASTER
);
960 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
962 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
964 if ( $s !== false ) {
965 # Initialise user table data
966 $this->loadFromRow( $s );
967 $this->mGroups
= null; // deferred
968 $this->getEditCount(); // revalidation for nulls
973 $this->loadDefaults();
979 * Initialize this object from a row from the user table.
981 * @param $row Array Row from the user table to load.
983 function loadFromRow( $row ) {
984 $this->mDataLoaded
= true;
986 if ( isset( $row->user_id
) ) {
987 $this->mId
= intval( $row->user_id
);
989 $this->mName
= $row->user_name
;
990 $this->mRealName
= $row->user_real_name
;
991 $this->mPassword
= $row->user_password
;
992 $this->mNewpassword
= $row->user_newpassword
;
993 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
994 $this->mEmail
= $row->user_email
;
995 $this->decodeOptions( $row->user_options
);
996 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
997 $this->mToken
= $row->user_token
;
998 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
999 $this->mEmailToken
= $row->user_email_token
;
1000 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1001 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1002 $this->mEditCount
= $row->user_editcount
;
1006 * Load the groups from the database if they aren't already loaded.
1009 function loadGroups() {
1010 if ( is_null( $this->mGroups
) ) {
1011 $dbr = wfGetDB( DB_MASTER
);
1012 $res = $dbr->select( 'user_groups',
1013 array( 'ug_group' ),
1014 array( 'ug_user' => $this->mId
),
1016 $this->mGroups
= array();
1017 foreach ( $res as $row ) {
1018 $this->mGroups
[] = $row->ug_group
;
1024 * Clear various cached data stored in this object.
1025 * @param $reloadFrom String Reload user and user_groups table data from a
1026 * given source. May be "name", "id", "defaults", "session", or false for
1029 function clearInstanceCache( $reloadFrom = false ) {
1030 $this->mNewtalk
= -1;
1031 $this->mDatePreference
= null;
1032 $this->mBlockedby
= -1; # Unset
1033 $this->mHash
= false;
1034 $this->mSkin
= null;
1035 $this->mRights
= null;
1036 $this->mEffectiveGroups
= null;
1037 $this->mOptions
= null;
1039 if ( $reloadFrom ) {
1040 $this->mDataLoaded
= false;
1041 $this->mFrom
= $reloadFrom;
1046 * Combine the language default options with any site-specific options
1047 * and add the default language variants.
1049 * @return Array of String options
1051 static function getDefaultOptions() {
1052 global $wgNamespacesToBeSearchedDefault;
1054 * Site defaults will override the global/language defaults
1056 global $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1057 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
1060 * default language setting
1062 $variant = $wgContLang->getDefaultVariant();
1063 $defOpt['variant'] = $variant;
1064 $defOpt['language'] = $variant;
1065 foreach( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1066 $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1068 $defOpt['skin'] = $wgDefaultSkin;
1074 * Get a given default option value.
1076 * @param $opt String Name of option to retrieve
1077 * @return String Default option value
1079 public static function getDefaultOption( $opt ) {
1080 $defOpts = self
::getDefaultOptions();
1081 if( isset( $defOpts[$opt] ) ) {
1082 return $defOpts[$opt];
1090 * Get blocking information
1092 * @param $bFromSlave Bool Whether to check the slave database first. To
1093 * improve performance, non-critical checks are done
1094 * against slaves. Check when actually saving should be
1095 * done against master.
1097 function getBlockedStatus( $bFromSlave = true ) {
1098 global $wgProxyWhitelist, $wgUser;
1100 if ( -1 != $this->mBlockedby
) {
1104 wfProfileIn( __METHOD__
);
1105 wfDebug( __METHOD__
.": checking...\n" );
1107 // Initialize data...
1108 // Otherwise something ends up stomping on $this->mBlockedby when
1109 // things get lazy-loaded later, causing false positive block hits
1110 // due to -1 !== 0. Probably session-related... Nothing should be
1111 // overwriting mBlockedby, surely?
1114 $this->mBlockedby
= 0;
1115 $this->mHideName
= 0;
1116 $this->mAllowUsertalk
= 0;
1118 # Check if we are looking at an IP or a logged-in user
1119 if ( $this->isAllowed( 'ipblock-exempt' ) ) {
1120 # Exempt from all types of IP-block
1122 } elseif ( $this->isIP( $this->getName() ) ) {
1123 $ip = $this->getName();
1125 # Check if we are looking at the current user
1126 # If we don't, and the user is logged in, we don't know about
1127 # his IP / autoblock status, so ignore autoblock of current user's IP
1128 if ( $this->getID() != $wgUser->getID() ) {
1131 # Get IP of current user
1137 $this->mBlock
= new Block();
1138 $this->mBlock
->fromMaster( !$bFromSlave );
1139 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
1140 wfDebug( __METHOD__
. ": Found block.\n" );
1141 $this->mBlockedby
= $this->mBlock
->mBy
;
1142 if( $this->mBlockedby
== 0 )
1143 $this->mBlockedby
= $this->mBlock
->mByName
;
1144 $this->mBlockreason
= $this->mBlock
->mReason
;
1145 $this->mHideName
= $this->mBlock
->mHideName
;
1146 $this->mAllowUsertalk
= $this->mBlock
->mAllowUsertalk
;
1147 if ( $this->isLoggedIn() && $wgUser->getID() == $this->getID() ) {
1148 $this->spreadBlock();
1151 // Bug 13611: don't remove mBlock here, to allow account creation blocks to
1152 // apply to users. Note that the existence of $this->mBlock is not used to
1153 // check for edit blocks, $this->mBlockedby is instead.
1157 if ( !$this->isAllowed( 'proxyunbannable' ) && !in_array( $ip, $wgProxyWhitelist ) ) {
1159 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1160 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1161 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1165 if ( !$this->mBlockedby
&& !$this->getID() ) {
1166 if ( $this->isDnsBlacklisted( $ip ) ) {
1167 $this->mBlockedby
= wfMsg( 'sorbs' );
1168 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1174 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1176 wfProfileOut( __METHOD__
);
1180 * Whether the given IP is in a DNS blacklist.
1182 * @param $ip String IP to check
1183 * @param $checkWhitelist Bool: whether to check the whitelist first
1184 * @return Bool True if blacklisted.
1186 function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1187 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1188 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1190 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
1193 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
1196 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1197 return $this->inDnsBlacklist( $ip, $urls );
1201 * Whether the given IP is in a given DNS blacklist.
1203 * @param $ip String IP to check
1204 * @param $bases String|Array of Strings: URL of the DNS blacklist
1205 * @return Bool True if blacklisted.
1207 function inDnsBlacklist( $ip, $bases ) {
1208 wfProfileIn( __METHOD__
);
1211 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1212 if( IP
::isIPv4( $ip ) ) {
1213 # Reverse IP, bug 21255
1214 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1216 foreach( (array)$bases as $base ) {
1218 $host = "$ipReversed.$base";
1221 $ipList = gethostbynamel( $host );
1224 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1228 wfDebug( "Requested $host, not found in $base.\n" );
1233 wfProfileOut( __METHOD__
);
1238 * Is this user subject to rate limiting?
1240 * @return Bool True if rate limited
1242 public function isPingLimitable() {
1243 global $wgRateLimitsExcludedGroups;
1244 global $wgRateLimitsExcludedIPs;
1245 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1246 // Deprecated, but kept for backwards-compatibility config
1249 if( in_array( wfGetIP(), $wgRateLimitsExcludedIPs ) ) {
1250 // No other good way currently to disable rate limits
1251 // for specific IPs. :P
1252 // But this is a crappy hack and should die.
1255 return !$this->isAllowed('noratelimit');
1259 * Primitive rate limits: enforce maximum actions per time period
1260 * to put a brake on flooding.
1262 * @note When using a shared cache like memcached, IP-address
1263 * last-hit counters will be shared across wikis.
1265 * @param $action String Action to enforce; 'edit' if unspecified
1266 * @return Bool True if a rate limiter was tripped
1268 function pingLimiter( $action = 'edit' ) {
1269 # Call the 'PingLimiter' hook
1271 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1275 global $wgRateLimits;
1276 if( !isset( $wgRateLimits[$action] ) ) {
1280 # Some groups shouldn't trigger the ping limiter, ever
1281 if( !$this->isPingLimitable() )
1284 global $wgMemc, $wgRateLimitLog;
1285 wfProfileIn( __METHOD__
);
1287 $limits = $wgRateLimits[$action];
1289 $id = $this->getId();
1293 if( isset( $limits['anon'] ) && $id == 0 ) {
1294 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1297 if( isset( $limits['user'] ) && $id != 0 ) {
1298 $userLimit = $limits['user'];
1300 if( $this->isNewbie() ) {
1301 if( isset( $limits['newbie'] ) && $id != 0 ) {
1302 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1304 if( isset( $limits['ip'] ) ) {
1305 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1308 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1309 $subnet = $matches[1];
1310 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1313 // Check for group-specific permissions
1314 // If more than one group applies, use the group with the highest limit
1315 foreach ( $this->getGroups() as $group ) {
1316 if ( isset( $limits[$group] ) ) {
1317 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1318 $userLimit = $limits[$group];
1322 // Set the user limit key
1323 if ( $userLimit !== false ) {
1324 wfDebug( __METHOD__
. ": effective user limit: $userLimit\n" );
1325 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1329 foreach( $keys as $key => $limit ) {
1330 list( $max, $period ) = $limit;
1331 $summary = "(limit $max in {$period}s)";
1332 $count = $wgMemc->get( $key );
1335 if( $count > $max ) {
1336 wfDebug( __METHOD__
. ": tripped! $key at $count $summary\n" );
1337 if( $wgRateLimitLog ) {
1338 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1342 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1345 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1346 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1348 $wgMemc->incr( $key );
1351 wfProfileOut( __METHOD__
);
1356 * Check if user is blocked
1358 * @param $bFromSlave Bool Whether to check the slave database instead of the master
1359 * @return Bool True if blocked, false otherwise
1361 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1362 $this->getBlockedStatus( $bFromSlave );
1363 return $this->mBlockedby
!== 0;
1367 * Check if user is blocked from editing a particular article
1369 * @param $title Title to check
1370 * @param $bFromSlave Bool whether to check the slave database instead of the master
1373 function isBlockedFrom( $title, $bFromSlave = false ) {
1374 global $wgBlockAllowsUTEdit;
1375 wfProfileIn( __METHOD__
);
1377 $blocked = $this->isBlocked( $bFromSlave );
1378 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1379 # If a user's name is suppressed, they cannot make edits anywhere
1380 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1381 $title->getNamespace() == NS_USER_TALK
) {
1383 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1386 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1388 wfProfileOut( __METHOD__
);
1393 * If user is blocked, return the name of the user who placed the block
1394 * @return String name of blocker
1396 function blockedBy() {
1397 $this->getBlockedStatus();
1398 return $this->mBlockedby
;
1402 * If user is blocked, return the specified reason for the block
1403 * @return String Blocking reason
1405 function blockedFor() {
1406 $this->getBlockedStatus();
1407 return $this->mBlockreason
;
1411 * If user is blocked, return the ID for the block
1412 * @return Int Block ID
1414 function getBlockId() {
1415 $this->getBlockedStatus();
1416 return ( $this->mBlock ?
$this->mBlock
->mId
: false );
1420 * Check if user is blocked on all wikis.
1421 * Do not use for actual edit permission checks!
1422 * This is intented for quick UI checks.
1424 * @param $ip String IP address, uses current client if none given
1425 * @return Bool True if blocked, false otherwise
1427 function isBlockedGlobally( $ip = '' ) {
1428 if( $this->mBlockedGlobally
!== null ) {
1429 return $this->mBlockedGlobally
;
1431 // User is already an IP?
1432 if( IP
::isIPAddress( $this->getName() ) ) {
1433 $ip = $this->getName();
1438 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1439 $this->mBlockedGlobally
= (bool)$blocked;
1440 return $this->mBlockedGlobally
;
1444 * Check if user account is locked
1446 * @return Bool True if locked, false otherwise
1448 function isLocked() {
1449 if( $this->mLocked
!== null ) {
1450 return $this->mLocked
;
1453 $authUser = $wgAuth->getUserInstance( $this );
1454 $this->mLocked
= (bool)$authUser->isLocked();
1455 return $this->mLocked
;
1459 * Check if user account is hidden
1461 * @return Bool True if hidden, false otherwise
1463 function isHidden() {
1464 if( $this->mHideName
!== null ) {
1465 return $this->mHideName
;
1467 $this->getBlockedStatus();
1468 if( !$this->mHideName
) {
1470 $authUser = $wgAuth->getUserInstance( $this );
1471 $this->mHideName
= (bool)$authUser->isHidden();
1473 return $this->mHideName
;
1477 * Get the user's ID.
1478 * @return Int The user's ID; 0 if the user is anonymous or nonexistent
1481 if( $this->mId
=== null and $this->mName
!== null
1482 and User
::isIP( $this->mName
) ) {
1483 // Special case, we know the user is anonymous
1485 } elseif( $this->mId
=== null ) {
1486 // Don't load if this was initialized from an ID
1493 * Set the user and reload all fields according to a given ID
1494 * @param $v Int User ID to reload
1496 function setId( $v ) {
1498 $this->clearInstanceCache( 'id' );
1502 * Get the user name, or the IP of an anonymous user
1503 * @return String User's name or IP address
1505 function getName() {
1506 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1507 # Special case optimisation
1508 return $this->mName
;
1511 if ( $this->mName
=== false ) {
1513 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1515 return $this->mName
;
1520 * Set the user name.
1522 * This does not reload fields from the database according to the given
1523 * name. Rather, it is used to create a temporary "nonexistent user" for
1524 * later addition to the database. It can also be used to set the IP
1525 * address for an anonymous user to something other than the current
1528 * @note User::newFromName() has rougly the same function, when the named user
1530 * @param $str String New user name to set
1532 function setName( $str ) {
1534 $this->mName
= $str;
1538 * Get the user's name escaped by underscores.
1539 * @return String Username escaped by underscores.
1541 function getTitleKey() {
1542 return str_replace( ' ', '_', $this->getName() );
1546 * Check if the user has new messages.
1547 * @return Bool True if the user has new messages
1549 function getNewtalk() {
1552 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1553 if( $this->mNewtalk
=== -1 ) {
1554 $this->mNewtalk
= false; # reset talk page status
1556 # Check memcached separately for anons, who have no
1557 # entire User object stored in there.
1560 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1561 $newtalk = $wgMemc->get( $key );
1562 if( strval( $newtalk ) !== '' ) {
1563 $this->mNewtalk
= (bool)$newtalk;
1565 // Since we are caching this, make sure it is up to date by getting it
1567 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1568 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1571 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1575 return (bool)$this->mNewtalk
;
1579 * Return the talk page(s) this user has new messages on.
1580 * @return Array of String page URLs
1582 function getNewMessageLinks() {
1584 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) )
1587 if( !$this->getNewtalk() )
1589 $up = $this->getUserPage();
1590 $utp = $up->getTalkPage();
1591 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL() ) );
1595 * Internal uncached check for new messages
1598 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1599 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1600 * @param $fromMaster Bool true to fetch from the master, false for a slave
1601 * @return Bool True if the user has new messages
1604 function checkNewtalk( $field, $id, $fromMaster = false ) {
1605 if ( $fromMaster ) {
1606 $db = wfGetDB( DB_MASTER
);
1608 $db = wfGetDB( DB_SLAVE
);
1610 $ok = $db->selectField( 'user_newtalk', $field,
1611 array( $field => $id ), __METHOD__
);
1612 return $ok !== false;
1616 * Add or update the new messages flag
1617 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1618 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1619 * @return Bool True if successful, false otherwise
1622 function updateNewtalk( $field, $id ) {
1623 $dbw = wfGetDB( DB_MASTER
);
1624 $dbw->insert( 'user_newtalk',
1625 array( $field => $id ),
1628 if ( $dbw->affectedRows() ) {
1629 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
1632 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
1638 * Clear the new messages flag for the given user
1639 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1640 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1641 * @return Bool True if successful, false otherwise
1644 function deleteNewtalk( $field, $id ) {
1645 $dbw = wfGetDB( DB_MASTER
);
1646 $dbw->delete( 'user_newtalk',
1647 array( $field => $id ),
1649 if ( $dbw->affectedRows() ) {
1650 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
1653 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
1659 * Update the 'You have new messages!' status.
1660 * @param $val Bool Whether the user has new messages
1662 function setNewtalk( $val ) {
1663 if( wfReadOnly() ) {
1668 $this->mNewtalk
= $val;
1670 if( $this->isAnon() ) {
1672 $id = $this->getName();
1675 $id = $this->getId();
1680 $changed = $this->updateNewtalk( $field, $id );
1682 $changed = $this->deleteNewtalk( $field, $id );
1685 if( $this->isAnon() ) {
1686 // Anons have a separate memcached space, since
1687 // user records aren't kept for them.
1688 $key = wfMemcKey( 'newtalk', 'ip', $id );
1689 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1692 $this->invalidateCache();
1697 * Generate a current or new-future timestamp to be stored in the
1698 * user_touched field when we update things.
1699 * @return String Timestamp in TS_MW format
1701 private static function newTouchedTimestamp() {
1702 global $wgClockSkewFudge;
1703 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1707 * Clear user data from memcached.
1708 * Use after applying fun updates to the database; caller's
1709 * responsibility to update user_touched if appropriate.
1711 * Called implicitly from invalidateCache() and saveSettings().
1713 private function clearSharedCache() {
1717 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1722 * Immediately touch the user data cache for this account.
1723 * Updates user_touched field, and removes account data from memcached
1724 * for reload on the next hit.
1726 function invalidateCache() {
1727 if( wfReadOnly() ) {
1732 $this->mTouched
= self
::newTouchedTimestamp();
1734 $dbw = wfGetDB( DB_MASTER
);
1735 $dbw->update( 'user',
1736 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1737 array( 'user_id' => $this->mId
),
1740 $this->clearSharedCache();
1745 * Validate the cache for this account.
1746 * @param $timestamp String A timestamp in TS_MW format
1748 function validateCache( $timestamp ) {
1750 return ( $timestamp >= $this->mTouched
);
1754 * Get the user touched timestamp
1755 * @return String timestamp
1757 function getTouched() {
1759 return $this->mTouched
;
1763 * Set the password and reset the random token.
1764 * Calls through to authentication plugin if necessary;
1765 * will have no effect if the auth plugin refuses to
1766 * pass the change through or if the legal password
1769 * As a special case, setting the password to null
1770 * wipes it, so the account cannot be logged in until
1771 * a new password is set, for instance via e-mail.
1773 * @param $str String New password to set
1774 * @throws PasswordError on failure
1776 function setPassword( $str ) {
1779 if( $str !== null ) {
1780 if( !$wgAuth->allowPasswordChange() ) {
1781 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1784 if( !$this->isValidPassword( $str ) ) {
1785 global $wgMinimalPasswordLength;
1786 $valid = $this->getPasswordValidity( $str );
1787 if ( is_array( $valid ) ) {
1788 $message = array_shift( $valid );
1792 $params = array( $wgMinimalPasswordLength );
1794 throw new PasswordError( wfMsgExt( $message, array( 'parsemag' ), $params ) );
1798 if( !$wgAuth->setPassword( $this, $str ) ) {
1799 throw new PasswordError( wfMsg( 'externaldberror' ) );
1802 $this->setInternalPassword( $str );
1808 * Set the password and reset the random token unconditionally.
1810 * @param $str String New password to set
1812 function setInternalPassword( $str ) {
1816 if( $str === null ) {
1817 // Save an invalid hash...
1818 $this->mPassword
= '';
1820 $this->mPassword
= self
::crypt( $str );
1822 $this->mNewpassword
= '';
1823 $this->mNewpassTime
= null;
1827 * Get the user's current token.
1828 * @return String Token
1830 function getToken() {
1832 return $this->mToken
;
1836 * Set the random token (used for persistent authentication)
1837 * Called from loadDefaults() among other places.
1839 * @param $token String If specified, set the token to this value
1842 function setToken( $token = false ) {
1843 global $wgSecretKey, $wgProxyKey;
1846 if ( $wgSecretKey ) {
1847 $key = $wgSecretKey;
1848 } elseif ( $wgProxyKey ) {
1853 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1855 $this->mToken
= $token;
1860 * Set the cookie password
1862 * @param $str String New cookie password
1865 function setCookiePassword( $str ) {
1867 $this->mCookiePassword
= md5( $str );
1871 * Set the password for a password reminder or new account email
1873 * @param $str String New password to set
1874 * @param $throttle Bool If true, reset the throttle timestamp to the present
1876 function setNewpassword( $str, $throttle = true ) {
1878 $this->mNewpassword
= self
::crypt( $str );
1880 $this->mNewpassTime
= wfTimestampNow();
1885 * Has password reminder email been sent within the last
1886 * $wgPasswordReminderResendTime hours?
1889 function isPasswordReminderThrottled() {
1890 global $wgPasswordReminderResendTime;
1892 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1895 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1896 return time() < $expiry;
1900 * Get the user's e-mail address
1901 * @return String User's email address
1903 function getEmail() {
1905 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1906 return $this->mEmail
;
1910 * Get the timestamp of the user's e-mail authentication
1911 * @return String TS_MW timestamp
1913 function getEmailAuthenticationTimestamp() {
1915 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1916 return $this->mEmailAuthenticated
;
1920 * Set the user's e-mail address
1921 * @param $str String New e-mail address
1923 function setEmail( $str ) {
1925 $this->mEmail
= $str;
1926 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1930 * Get the user's real name
1931 * @return String User's real name
1933 function getRealName() {
1935 return $this->mRealName
;
1939 * Set the user's real name
1940 * @param $str String New real name
1942 function setRealName( $str ) {
1944 $this->mRealName
= $str;
1948 * Get the user's current setting for a given option.
1950 * @param $oname String The option to check
1951 * @param $defaultOverride String A default value returned if the option does not exist
1952 * @return String User's current value for the option
1953 * @see getBoolOption()
1954 * @see getIntOption()
1956 function getOption( $oname, $defaultOverride = null ) {
1957 $this->loadOptions();
1959 if ( is_null( $this->mOptions
) ) {
1960 if($defaultOverride != '') {
1961 return $defaultOverride;
1963 $this->mOptions
= User
::getDefaultOptions();
1966 if ( array_key_exists( $oname, $this->mOptions
) ) {
1967 return $this->mOptions
[$oname];
1969 return $defaultOverride;
1974 * Get all user's options
1978 public function getOptions() {
1979 $this->loadOptions();
1980 return $this->mOptions
;
1984 * Get the user's current setting for a given option, as a boolean value.
1986 * @param $oname String The option to check
1987 * @return Bool User's current value for the option
1990 function getBoolOption( $oname ) {
1991 return (bool)$this->getOption( $oname );
1996 * Get the user's current setting for a given option, as a boolean value.
1998 * @param $oname String The option to check
1999 * @param $defaultOverride Int A default value returned if the option does not exist
2000 * @return Int User's current value for the option
2003 function getIntOption( $oname, $defaultOverride=0 ) {
2004 $val = $this->getOption( $oname );
2006 $val = $defaultOverride;
2008 return intval( $val );
2012 * Set the given option for a user.
2014 * @param $oname String The option to set
2015 * @param $val mixed New value to set
2017 function setOption( $oname, $val ) {
2019 $this->loadOptions();
2021 if ( $oname == 'skin' ) {
2022 # Clear cached skin, so the new one displays immediately in Special:Preferences
2023 $this->mSkin
= null;
2026 // Explicitly NULL values should refer to defaults
2027 global $wgDefaultUserOptions;
2028 if( is_null( $val ) && isset( $wgDefaultUserOptions[$oname] ) ) {
2029 $val = $wgDefaultUserOptions[$oname];
2032 $this->mOptions
[$oname] = $val;
2036 * Reset all options to the site defaults
2038 function resetOptions() {
2039 $this->mOptions
= self
::getDefaultOptions();
2043 * Get the user's preferred date format.
2044 * @return String User's preferred date format
2046 function getDatePreference() {
2047 // Important migration for old data rows
2048 if ( is_null( $this->mDatePreference
) ) {
2050 $value = $this->getOption( 'date' );
2051 $map = $wgLang->getDatePreferenceMigrationMap();
2052 if ( isset( $map[$value] ) ) {
2053 $value = $map[$value];
2055 $this->mDatePreference
= $value;
2057 return $this->mDatePreference
;
2061 * Get the user preferred stub threshold
2063 function getStubThreshold() {
2064 global $wgMaxArticleSize; # Maximum article size, in Kb
2065 $threshold = intval( $this->getOption( 'stubthreshold' ) );
2066 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2067 # If they have set an impossible value, disable the preference
2068 # so we can use the parser cache again.
2075 * Get the permissions this user has.
2076 * @return Array of String permission names
2078 function getRights() {
2079 if ( is_null( $this->mRights
) ) {
2080 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2081 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2082 // Force reindexation of rights when a hook has unset one of them
2083 $this->mRights
= array_values( $this->mRights
);
2085 return $this->mRights
;
2089 * Get the list of explicit group memberships this user has.
2090 * The implicit * and user groups are not included.
2091 * @return Array of String internal group names
2093 function getGroups() {
2095 return $this->mGroups
;
2099 * Get the list of implicit group memberships this user has.
2100 * This includes all explicit groups, plus 'user' if logged in,
2101 * '*' for all accounts, and autopromoted groups
2102 * @param $recache Bool Whether to avoid the cache
2103 * @return Array of String internal group names
2105 function getEffectiveGroups( $recache = false ) {
2106 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2107 wfProfileIn( __METHOD__
);
2108 $this->mEffectiveGroups
= $this->getGroups();
2109 $this->mEffectiveGroups
[] = '*';
2110 if( $this->getId() ) {
2111 $this->mEffectiveGroups
[] = 'user';
2113 $this->mEffectiveGroups
= array_unique( array_merge(
2114 $this->mEffectiveGroups
,
2115 Autopromote
::getAutopromoteGroups( $this )
2118 # Hook for additional groups
2119 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2121 wfProfileOut( __METHOD__
);
2123 return $this->mEffectiveGroups
;
2127 * Get the user's edit count.
2130 function getEditCount() {
2131 if( $this->getId() ) {
2132 if ( !isset( $this->mEditCount
) ) {
2133 /* Populate the count, if it has not been populated yet */
2134 $this->mEditCount
= User
::edits( $this->mId
);
2136 return $this->mEditCount
;
2144 * Add the user to the given group.
2145 * This takes immediate effect.
2146 * @param $group String Name of the group to add
2148 function addGroup( $group ) {
2149 $dbw = wfGetDB( DB_MASTER
);
2150 if( $this->getId() ) {
2151 $dbw->insert( 'user_groups',
2153 'ug_user' => $this->getID(),
2154 'ug_group' => $group,
2157 array( 'IGNORE' ) );
2160 $this->loadGroups();
2161 $this->mGroups
[] = $group;
2162 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2164 $this->invalidateCache();
2168 * Remove the user from the given group.
2169 * This takes immediate effect.
2170 * @param $group String Name of the group to remove
2172 function removeGroup( $group ) {
2174 $dbw = wfGetDB( DB_MASTER
);
2175 $dbw->delete( 'user_groups',
2177 'ug_user' => $this->getID(),
2178 'ug_group' => $group,
2181 $this->loadGroups();
2182 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2183 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2185 $this->invalidateCache();
2189 * Get whether the user is logged in
2192 function isLoggedIn() {
2193 return $this->getID() != 0;
2197 * Get whether the user is anonymous
2201 return !$this->isLoggedIn();
2205 * Check if user is allowed to access a feature / make an action
2206 * @param $action String action to be checked
2207 * @return Boolean: True if action is allowed, else false
2209 function isAllowed( $action = '' ) {
2210 if ( $action === '' ) {
2211 return true; // In the spirit of DWIM
2213 # Patrolling may not be enabled
2214 if( $action === 'patrol' ||
$action === 'autopatrol' ) {
2215 global $wgUseRCPatrol, $wgUseNPPatrol;
2216 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2219 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2220 # by misconfiguration: 0 == 'foo'
2221 return in_array( $action, $this->getRights(), true );
2225 * Check whether to enable recent changes patrol features for this user
2226 * @return Boolean: True or false
2228 public function useRCPatrol() {
2229 global $wgUseRCPatrol;
2230 return( $wgUseRCPatrol && ( $this->isAllowed( 'patrol' ) ||
$this->isAllowed( 'patrolmarks' ) ) );
2234 * Check whether to enable new pages patrol features for this user
2235 * @return Bool True or false
2237 public function useNPPatrol() {
2238 global $wgUseRCPatrol, $wgUseNPPatrol;
2239 return( ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && ( $this->isAllowed( 'patrol' ) ||
$this->isAllowed( 'patrolmarks' ) ) );
2243 * Get the current skin, loading it if required, and setting a title
2244 * @param $t Title: the title to use in the skin
2245 * @return Skin The current skin
2246 * @todo: FIXME : need to check the old failback system [AV]
2248 function getSkin( $t = null ) {
2249 if( !$this->mSkin
) {
2251 $this->mSkin
= $this->createSkinObject();
2252 $this->mSkin
->setTitle( $wgOut->getTitle() );
2254 if ( $t && ( !$this->mSkin
->getTitle() ||
!$t->equals( $this->mSkin
->getTitle() ) ) ) {
2255 $skin = $this->createSkinObject();
2256 $skin->setTitle( $t );
2259 return $this->mSkin
;
2263 // Creates a Skin object, for getSkin()
2264 private function createSkinObject() {
2265 wfProfileIn( __METHOD__
);
2267 global $wgHiddenPrefs;
2268 if( !in_array( 'skin', $wgHiddenPrefs ) ) {
2271 $userSkin = $this->getOption( 'skin' );
2272 $userSkin = $wgRequest->getVal( 'useskin', $userSkin );
2274 # if we're not allowing users to override, then use the default
2275 global $wgDefaultSkin;
2276 $userSkin = $wgDefaultSkin;
2279 $skin = Skin
::newFromKey( $userSkin );
2280 wfProfileOut( __METHOD__
);
2286 * Check the watched status of an article.
2287 * @param $title Title of the article to look at
2290 function isWatched( $title ) {
2291 $wl = WatchedItem
::fromUserTitle( $this, $title );
2292 return $wl->isWatched();
2297 * @param $title Title of the article to look at
2299 function addWatch( $title ) {
2300 $wl = WatchedItem
::fromUserTitle( $this, $title );
2302 $this->invalidateCache();
2306 * Stop watching an article.
2307 * @param $title Title of the article to look at
2309 function removeWatch( $title ) {
2310 $wl = WatchedItem
::fromUserTitle( $this, $title );
2312 $this->invalidateCache();
2316 * Clear the user's notification timestamp for the given title.
2317 * If e-notif e-mails are on, they will receive notification mails on
2318 * the next change of the page if it's watched etc.
2319 * @param $title Title of the article to look at
2321 function clearNotification( &$title ) {
2322 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2324 # Do nothing if the database is locked to writes
2325 if( wfReadOnly() ) {
2329 if( $title->getNamespace() == NS_USER_TALK
&&
2330 $title->getText() == $this->getName() ) {
2331 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2333 $this->setNewtalk( false );
2336 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2340 if( $this->isAnon() ) {
2341 // Nothing else to do...
2345 // Only update the timestamp if the page is being watched.
2346 // The query to find out if it is watched is cached both in memcached and per-invocation,
2347 // and when it does have to be executed, it can be on a slave
2348 // If this is the user's newtalk page, we always update the timestamp
2349 if( $title->getNamespace() == NS_USER_TALK
&&
2350 $title->getText() == $wgUser->getName() )
2353 } elseif ( $this->getId() == $wgUser->getId() ) {
2354 $watched = $title->userIsWatching();
2359 // If the page is watched by the user (or may be watched), update the timestamp on any
2360 // any matching rows
2362 $dbw = wfGetDB( DB_MASTER
);
2363 $dbw->update( 'watchlist',
2365 'wl_notificationtimestamp' => null
2366 ), array( /* WHERE */
2367 'wl_title' => $title->getDBkey(),
2368 'wl_namespace' => $title->getNamespace(),
2369 'wl_user' => $this->getID()
2376 * Resets all of the given user's page-change notification timestamps.
2377 * If e-notif e-mails are on, they will receive notification mails on
2378 * the next change of any watched page.
2380 * @param $currentUser Int User ID
2382 function clearAllNotifications( $currentUser ) {
2383 global $wgUseEnotif, $wgShowUpdatedMarker;
2384 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2385 $this->setNewtalk( false );
2388 if( $currentUser != 0 ) {
2389 $dbw = wfGetDB( DB_MASTER
);
2390 $dbw->update( 'watchlist',
2392 'wl_notificationtimestamp' => null
2393 ), array( /* WHERE */
2394 'wl_user' => $currentUser
2397 # We also need to clear here the "you have new message" notification for the own user_talk page
2398 # This is cleared one page view later in Article::viewUpdates();
2403 * Set this user's options from an encoded string
2404 * @param $str String Encoded options to import
2407 function decodeOptions( $str ) {
2411 $this->mOptionsLoaded
= true;
2412 $this->mOptionOverrides
= array();
2414 // If an option is not set in $str, use the default value
2415 $this->mOptions
= self
::getDefaultOptions();
2417 $a = explode( "\n", $str );
2418 foreach ( $a as $s ) {
2420 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2421 $this->mOptions
[$m[1]] = $m[2];
2422 $this->mOptionOverrides
[$m[1]] = $m[2];
2428 * Set a cookie on the user's client. Wrapper for
2429 * WebResponse::setCookie
2430 * @param $name String Name of the cookie to set
2431 * @param $value String Value to set
2432 * @param $exp Int Expiration time, as a UNIX time value;
2433 * if 0 or not specified, use the default $wgCookieExpiration
2435 protected function setCookie( $name, $value, $exp = 0 ) {
2437 $wgRequest->response()->setcookie( $name, $value, $exp );
2441 * Clear a cookie on the user's client
2442 * @param $name String Name of the cookie to clear
2444 protected function clearCookie( $name ) {
2445 $this->setCookie( $name, '', time() - 86400 );
2449 * Set the default cookies for this session on the user's client.
2451 function setCookies() {
2455 if ( 0 == $this->mId
) return;
2457 'wsUserID' => $this->mId
,
2458 'wsToken' => $this->mToken
,
2459 'wsUserName' => $this->getName()
2462 'UserID' => $this->mId
,
2463 'UserName' => $this->getName(),
2465 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2466 $cookies['Token'] = $this->mToken
;
2468 $cookies['Token'] = false;
2471 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2473 foreach ( $session as $name => $value ) {
2474 $wgRequest->setSessionData( $name, $value );
2476 foreach ( $cookies as $name => $value ) {
2477 if ( $value === false ) {
2478 $this->clearCookie( $name );
2480 $this->setCookie( $name, $value );
2486 * Log this user out.
2489 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
2495 * Clear the user's cookies and session, and reset the instance cache.
2499 function doLogout() {
2502 $this->clearInstanceCache( 'defaults' );
2504 $wgRequest->setSessionData( 'wsUserID', 0 );
2506 $this->clearCookie( 'UserID' );
2507 $this->clearCookie( 'Token' );
2509 # Remember when user logged out, to prevent seeing cached pages
2510 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2514 * Save this user's settings into the database.
2515 * @todo Only rarely do all these fields need to be set!
2517 function saveSettings() {
2519 if ( wfReadOnly() ) { return; }
2520 if ( 0 == $this->mId
) { return; }
2522 $this->mTouched
= self
::newTouchedTimestamp();
2524 $dbw = wfGetDB( DB_MASTER
);
2525 $dbw->update( 'user',
2527 'user_name' => $this->mName
,
2528 'user_password' => $this->mPassword
,
2529 'user_newpassword' => $this->mNewpassword
,
2530 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2531 'user_real_name' => $this->mRealName
,
2532 'user_email' => $this->mEmail
,
2533 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2534 'user_options' => '',
2535 'user_touched' => $dbw->timestamp( $this->mTouched
),
2536 'user_token' => $this->mToken
,
2537 'user_email_token' => $this->mEmailToken
,
2538 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2539 ), array( /* WHERE */
2540 'user_id' => $this->mId
2544 $this->saveOptions();
2546 wfRunHooks( 'UserSaveSettings', array( $this ) );
2547 $this->clearSharedCache();
2548 $this->getUserPage()->invalidateCache();
2552 * If only this user's username is known, and it exists, return the user ID.
2555 function idForName() {
2556 $s = trim( $this->getName() );
2557 if ( $s === '' ) return 0;
2559 $dbr = wfGetDB( DB_SLAVE
);
2560 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2561 if ( $id === false ) {
2568 * Add a user to the database, return the user object
2570 * @param $name String Username to add
2571 * @param $params Array of Strings Non-default parameters to save to the database:
2572 * - password The user's password. Password logins will be disabled if this is omitted.
2573 * - newpassword A temporary password mailed to the user
2574 * - email The user's email address
2575 * - email_authenticated The email authentication timestamp
2576 * - real_name The user's real name
2577 * - options An associative array of non-default options
2578 * - token Random authentication token. Do not set.
2579 * - registration Registration timestamp. Do not set.
2581 * @return User object, or null if the username already exists
2583 static function createNew( $name, $params = array() ) {
2586 if ( isset( $params['options'] ) ) {
2587 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
2588 unset( $params['options'] );
2590 $dbw = wfGetDB( DB_MASTER
);
2591 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2594 'user_id' => $seqVal,
2595 'user_name' => $name,
2596 'user_password' => $user->mPassword
,
2597 'user_newpassword' => $user->mNewpassword
,
2598 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
2599 'user_email' => $user->mEmail
,
2600 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2601 'user_real_name' => $user->mRealName
,
2602 'user_options' => '',
2603 'user_token' => $user->mToken
,
2604 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2605 'user_editcount' => 0,
2607 foreach ( $params as $name => $value ) {
2608 $fields["user_$name"] = $value;
2610 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2611 if ( $dbw->affectedRows() ) {
2612 $newUser = User
::newFromId( $dbw->insertId() );
2620 * Add this existing user object to the database
2622 function addToDatabase() {
2624 $dbw = wfGetDB( DB_MASTER
);
2625 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2626 $dbw->insert( 'user',
2628 'user_id' => $seqVal,
2629 'user_name' => $this->mName
,
2630 'user_password' => $this->mPassword
,
2631 'user_newpassword' => $this->mNewpassword
,
2632 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2633 'user_email' => $this->mEmail
,
2634 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2635 'user_real_name' => $this->mRealName
,
2636 'user_options' => '',
2637 'user_token' => $this->mToken
,
2638 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2639 'user_editcount' => 0,
2642 $this->mId
= $dbw->insertId();
2644 // Clear instance cache other than user table data, which is already accurate
2645 $this->clearInstanceCache();
2647 $this->saveOptions();
2651 * If this (non-anonymous) user is blocked, block any IP address
2652 * they've successfully logged in from.
2654 function spreadBlock() {
2655 wfDebug( __METHOD__
. "()\n" );
2657 if ( $this->mId
== 0 ) {
2661 $userblock = Block
::newFromDB( '', $this->mId
);
2662 if ( !$userblock ) {
2666 $userblock->doAutoblock( wfGetIP() );
2670 * Generate a string which will be different for any combination of
2671 * user options which would produce different parser output.
2672 * This will be used as part of the hash key for the parser cache,
2673 * so users with the same options can share the same cached data
2676 * Extensions which require it should install 'PageRenderingHash' hook,
2677 * which will give them a chance to modify this key based on their own
2680 * @deprecated @since 1.17 use the ParserOptions object to get the relevant options
2681 * @return String Page rendering hash
2683 function getPageRenderingHash() {
2684 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2686 return $this->mHash
;
2688 wfDeprecated( __METHOD__
);
2690 // stubthreshold is only included below for completeness,
2691 // since it disables the parser cache, its value will always
2692 // be 0 when this function is called by parsercache.
2694 $confstr = $this->getOption( 'math' );
2695 $confstr .= '!' . $this->getStubThreshold();
2696 if ( $wgUseDynamicDates ) { # This is wrong (bug 24714)
2697 $confstr .= '!' . $this->getDatePreference();
2699 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ?
'1' : '' );
2700 $confstr .= '!' . $wgLang->getCode();
2701 $confstr .= '!' . $this->getOption( 'thumbsize' );
2702 // add in language specific options, if any
2703 $extra = $wgContLang->getExtraHashOptions();
2706 // Since the skin could be overloading link(), it should be
2707 // included here but in practice, none of our skins do that.
2709 $confstr .= $wgRenderHashAppend;
2711 // Give a chance for extensions to modify the hash, if they have
2712 // extra options or other effects on the parser cache.
2713 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2715 // Make it a valid memcached key fragment
2716 $confstr = str_replace( ' ', '_', $confstr );
2717 $this->mHash
= $confstr;
2722 * Get whether the user is explicitly blocked from account creation.
2725 function isBlockedFromCreateAccount() {
2726 $this->getBlockedStatus();
2727 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2731 * Get whether the user is blocked from using Special:Emailuser.
2734 function isBlockedFromEmailuser() {
2735 $this->getBlockedStatus();
2736 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2740 * Get whether the user is allowed to create an account.
2743 function isAllowedToCreateAccount() {
2744 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2748 * Get this user's personal page title.
2750 * @return Title: User's personal page title
2752 function getUserPage() {
2753 return Title
::makeTitle( NS_USER
, $this->getName() );
2757 * Get this user's talk page title.
2759 * @return Title: User's talk page title
2761 function getTalkPage() {
2762 $title = $this->getUserPage();
2763 return $title->getTalkPage();
2767 * Get the maximum valid user ID.
2768 * @return Integer: User ID
2771 function getMaxID() {
2772 static $res; // cache
2774 if ( isset( $res ) ) {
2777 $dbr = wfGetDB( DB_SLAVE
);
2778 return $res = $dbr->selectField( 'user', 'max(user_id)', false, __METHOD__
);
2783 * Determine whether the user is a newbie. Newbies are either
2784 * anonymous IPs, or the most recently created accounts.
2787 function isNewbie() {
2788 return !$this->isAllowed( 'autoconfirmed' );
2792 * Check to see if the given clear-text password is one of the accepted passwords
2793 * @param $password String: user password.
2794 * @return Boolean: True if the given password is correct, otherwise False.
2796 function checkPassword( $password ) {
2797 global $wgAuth, $wgLegacyEncoding;
2800 // Even though we stop people from creating passwords that
2801 // are shorter than this, doesn't mean people wont be able
2802 // to. Certain authentication plugins do NOT want to save
2803 // domain passwords in a mysql database, so we should
2804 // check this (in case $wgAuth->strict() is false).
2805 if( !$this->isValidPassword( $password ) ) {
2809 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2811 } elseif( $wgAuth->strict() ) {
2812 /* Auth plugin doesn't allow local authentication */
2814 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2815 /* Auth plugin doesn't allow local authentication for this user name */
2818 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
2820 } elseif ( $wgLegacyEncoding ) {
2821 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2822 # Check for this with iconv
2823 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2824 if ( $cp1252Password != $password &&
2825 self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) )
2834 * Check if the given clear-text password matches the temporary password
2835 * sent by e-mail for password reset operations.
2836 * @return Boolean: True if matches, false otherwise
2838 function checkTemporaryPassword( $plaintext ) {
2839 global $wgNewPasswordExpiry;
2840 if( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
2841 if ( is_null( $this->mNewpassTime
) ) {
2844 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
2845 return ( time() < $expiry );
2852 * Initialize (if necessary) and return a session token value
2853 * which can be used in edit forms to show that the user's
2854 * login credentials aren't being hijacked with a foreign form
2857 * @param $salt String|Array of Strings Optional function-specific data for hashing
2858 * @param $request WebRequest object to use or null to use $wgRequest
2859 * @return String The new edit token
2861 function editToken( $salt = '', $request = null ) {
2862 if ( $request == null ) {
2864 $request = $wgRequest;
2867 if ( $this->isAnon() ) {
2868 return EDIT_TOKEN_SUFFIX
;
2870 $token = $request->getSessionData( 'wsEditToken' );
2871 if ( $token === null ) {
2872 $token = self
::generateToken();
2873 $request->setSessionData( 'wsEditToken', $token );
2875 if( is_array( $salt ) ) {
2876 $salt = implode( '|', $salt );
2878 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2883 * Generate a looking random token for various uses.
2885 * @param $salt String Optional salt value
2886 * @return String The new random token
2888 public static function generateToken( $salt = '' ) {
2889 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2890 return md5( $token . $salt );
2894 * Check given value against the token value stored in the session.
2895 * A match should confirm that the form was submitted from the
2896 * user's own login session, not a form submission from a third-party
2899 * @param $val String Input value to compare
2900 * @param $salt String Optional function-specific data for hashing
2901 * @param $request WebRequest object to use or null to use $wgRequest
2902 * @return Boolean: Whether the token matches
2904 function matchEditToken( $val, $salt = '', $request = null ) {
2905 $sessionToken = $this->editToken( $salt, $request );
2906 if ( $val != $sessionToken ) {
2907 wfDebug( "User::matchEditToken: broken session data\n" );
2909 return $val == $sessionToken;
2913 * Check given value against the token value stored in the session,
2914 * ignoring the suffix.
2916 * @param $val String Input value to compare
2917 * @param $salt String Optional function-specific data for hashing
2918 * @return Boolean: Whether the token matches
2920 function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
2921 $sessionToken = $this->editToken( $salt );
2922 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2926 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2927 * mail to the user's given address.
2929 * @param $type String: message to send, either "created", "changed" or "set"
2930 * @return Status object
2932 function sendConfirmationMail( $type = 'created' ) {
2934 $expiration = null; // gets passed-by-ref and defined in next line.
2935 $token = $this->confirmationToken( $expiration );
2936 $url = $this->confirmationTokenUrl( $token );
2937 $invalidateURL = $this->invalidationTokenUrl( $token );
2938 $this->saveSettings();
2940 if ( $type == 'created' ||
$type === false ) {
2941 $message = 'confirmemail_body';
2942 } elseif ( $type === true ) {
2943 $message = 'confirmemail_body_changed';
2945 $message = 'confirmemail_body_' . $type;
2948 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2953 $wgLang->timeanddate( $expiration, false ),
2955 $wgLang->date( $expiration, false ),
2956 $wgLang->time( $expiration, false ) ) );
2960 * Send an e-mail to this user's account. Does not check for
2961 * confirmed status or validity.
2963 * @param $subject String Message subject
2964 * @param $body String Message body
2965 * @param $from String Optional From address; if unspecified, default $wgPasswordSender will be used
2966 * @param $replyto String Reply-To address
2969 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2970 if( is_null( $from ) ) {
2971 global $wgPasswordSender, $wgPasswordSenderName;
2972 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
2974 $sender = new MailAddress( $from );
2977 $to = new MailAddress( $this );
2978 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2982 * Generate, store, and return a new e-mail confirmation code.
2983 * A hash (unsalted, since it's used as a key) is stored.
2985 * @note Call saveSettings() after calling this function to commit
2986 * this change to the database.
2988 * @param[out] &$expiration \mixed Accepts the expiration time
2989 * @return String New token
2992 function confirmationToken( &$expiration ) {
2993 global $wgUserEmailConfirmationTokenExpiry;
2995 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
2996 $expiration = wfTimestamp( TS_MW
, $expires );
2997 $token = self
::generateToken( $this->mId
. $this->mEmail
. $expires );
2998 $hash = md5( $token );
3000 $this->mEmailToken
= $hash;
3001 $this->mEmailTokenExpires
= $expiration;
3006 * Return a URL the user can use to confirm their email address.
3007 * @param $token String Accepts the email confirmation token
3008 * @return String New token URL
3011 function confirmationTokenUrl( $token ) {
3012 return $this->getTokenUrl( 'ConfirmEmail', $token );
3016 * Return a URL the user can use to invalidate their email address.
3017 * @param $token String Accepts the email confirmation token
3018 * @return String New token URL
3021 function invalidationTokenUrl( $token ) {
3022 return $this->getTokenUrl( 'Invalidateemail', $token );
3026 * Internal function to format the e-mail validation/invalidation URLs.
3027 * This uses $wgArticlePath directly as a quickie hack to use the
3028 * hardcoded English names of the Special: pages, for ASCII safety.
3030 * @note Since these URLs get dropped directly into emails, using the
3031 * short English names avoids insanely long URL-encoded links, which
3032 * also sometimes can get corrupted in some browsers/mailers
3033 * (bug 6957 with Gmail and Internet Explorer).
3035 * @param $page String Special page
3036 * @param $token String Token
3037 * @return String Formatted URL
3039 protected function getTokenUrl( $page, $token ) {
3040 global $wgArticlePath;
3044 "Special:$page/$token",
3049 * Mark the e-mail address confirmed.
3051 * @note Call saveSettings() after calling this function to commit the change.
3053 function confirmEmail() {
3054 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3055 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3060 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3061 * address if it was already confirmed.
3063 * @note Call saveSettings() after calling this function to commit the change.
3065 function invalidateEmail() {
3067 $this->mEmailToken
= null;
3068 $this->mEmailTokenExpires
= null;
3069 $this->setEmailAuthenticationTimestamp( null );
3070 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3075 * Set the e-mail authentication timestamp.
3076 * @param $timestamp String TS_MW timestamp
3078 function setEmailAuthenticationTimestamp( $timestamp ) {
3080 $this->mEmailAuthenticated
= $timestamp;
3081 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
3085 * Is this user allowed to send e-mails within limits of current
3086 * site configuration?
3089 function canSendEmail() {
3090 global $wgEnableEmail, $wgEnableUserEmail;
3091 if( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
3094 $canSend = $this->isEmailConfirmed();
3095 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3100 * Is this user allowed to receive e-mails within limits of current
3101 * site configuration?
3104 function canReceiveEmail() {
3105 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3109 * Is this user's e-mail address valid-looking and confirmed within
3110 * limits of the current site configuration?
3112 * @note If $wgEmailAuthentication is on, this may require the user to have
3113 * confirmed their address by returning a code or using a password
3114 * sent to the address from the wiki.
3118 function isEmailConfirmed() {
3119 global $wgEmailAuthentication;
3122 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3123 if( $this->isAnon() )
3125 if( !self
::isValidEmailAddr( $this->mEmail
) )
3127 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
3136 * Check whether there is an outstanding request for e-mail confirmation.
3139 function isEmailConfirmationPending() {
3140 global $wgEmailAuthentication;
3141 return $wgEmailAuthentication &&
3142 !$this->isEmailConfirmed() &&
3143 $this->mEmailToken
&&
3144 $this->mEmailTokenExpires
> wfTimestamp();
3148 * Get the timestamp of account creation.
3150 * @return String|Bool Timestamp of account creation, or false for
3151 * non-existent/anonymous user accounts.
3153 public function getRegistration() {
3154 return $this->getId() > 0
3155 ?
$this->mRegistration
3160 * Get the timestamp of the first edit
3162 * @return String|Bool Timestamp of first edit, or false for
3163 * non-existent/anonymous user accounts.
3165 public function getFirstEditTimestamp() {
3166 if( $this->getId() == 0 ) {
3167 return false; // anons
3169 $dbr = wfGetDB( DB_SLAVE
);
3170 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3171 array( 'rev_user' => $this->getId() ),
3173 array( 'ORDER BY' => 'rev_timestamp ASC' )
3176 return false; // no edits
3178 return wfTimestamp( TS_MW
, $time );
3182 * Get the permissions associated with a given list of groups
3184 * @param $groups Array of Strings List of internal group names
3185 * @return Array of Strings List of permission key names for given groups combined
3187 static function getGroupPermissions( $groups ) {
3188 global $wgGroupPermissions, $wgRevokePermissions;
3190 // grant every granted permission first
3191 foreach( $groups as $group ) {
3192 if( isset( $wgGroupPermissions[$group] ) ) {
3193 $rights = array_merge( $rights,
3194 // array_filter removes empty items
3195 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3198 // now revoke the revoked permissions
3199 foreach( $groups as $group ) {
3200 if( isset( $wgRevokePermissions[$group] ) ) {
3201 $rights = array_diff( $rights,
3202 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3205 return array_unique( $rights );
3209 * Get all the groups who have a given permission
3211 * @param $role String Role to check
3212 * @return Array of Strings List of internal group names with the given permission
3214 static function getGroupsWithPermission( $role ) {
3215 global $wgGroupPermissions;
3216 $allowedGroups = array();
3217 foreach ( $wgGroupPermissions as $group => $rights ) {
3218 if ( isset( $rights[$role] ) && $rights[$role] ) {
3219 $allowedGroups[] = $group;
3222 return $allowedGroups;
3226 * Get the localized descriptive name for a group, if it exists
3228 * @param $group String Internal group name
3229 * @return String Localized descriptive group name
3231 static function getGroupName( $group ) {
3232 $msg = wfMessage( "group-$group" );
3233 return $msg->isBlank() ?
$group : $msg->text();
3237 * Get the localized descriptive name for a member of a group, if it exists
3239 * @param $group String Internal group name
3240 * @return String Localized name for group member
3242 static function getGroupMember( $group ) {
3243 $msg = wfMessage( "group-$group-member" );
3244 return $msg->isBlank() ?
$group : $msg->text();
3248 * Return the set of defined explicit groups.
3249 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3250 * are not included, as they are defined automatically, not in the database.
3251 * @return Array of internal group names
3253 static function getAllGroups() {
3254 global $wgGroupPermissions, $wgRevokePermissions;
3256 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3257 self
::getImplicitGroups()
3262 * Get a list of all available permissions.
3263 * @return Array of permission names
3265 static function getAllRights() {
3266 if ( self
::$mAllRights === false ) {
3267 global $wgAvailableRights;
3268 if ( count( $wgAvailableRights ) ) {
3269 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3271 self
::$mAllRights = self
::$mCoreRights;
3273 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3275 return self
::$mAllRights;
3279 * Get a list of implicit groups
3280 * @return Array of Strings Array of internal group names
3282 public static function getImplicitGroups() {
3283 global $wgImplicitGroups;
3284 $groups = $wgImplicitGroups;
3285 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3290 * Get the title of a page describing a particular group
3292 * @param $group String Internal group name
3293 * @return Title|Bool Title of the page if it exists, false otherwise
3295 static function getGroupPage( $group ) {
3296 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
3297 if( $msg->exists() ) {
3298 $title = Title
::newFromText( $msg->text() );
3299 if( is_object( $title ) )
3306 * Create a link to the group in HTML, if available;
3307 * else return the group name.
3309 * @param $group String Internal name of the group
3310 * @param $text String The text of the link
3311 * @return String HTML link to the group
3313 static function makeGroupLinkHTML( $group, $text = '' ) {
3315 $text = self
::getGroupName( $group );
3317 $title = self
::getGroupPage( $group );
3320 $sk = $wgUser->getSkin();
3321 return $sk->link( $title, htmlspecialchars( $text ) );
3328 * Create a link to the group in Wikitext, if available;
3329 * else return the group name.
3331 * @param $group String Internal name of the group
3332 * @param $text String The text of the link
3333 * @return String Wikilink to the group
3335 static function makeGroupLinkWiki( $group, $text = '' ) {
3337 $text = self
::getGroupName( $group );
3339 $title = self
::getGroupPage( $group );
3341 $page = $title->getPrefixedText();
3342 return "[[$page|$text]]";
3349 * Returns an array of the groups that a particular group can add/remove.
3351 * @param $group String: the group to check for whether it can add/remove
3352 * @return Array array( 'add' => array( addablegroups ),
3353 * 'remove' => array( removablegroups ),
3354 * 'add-self' => array( addablegroups to self),
3355 * 'remove-self' => array( removable groups from self) )
3357 static function changeableByGroup( $group ) {
3358 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
3360 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
3361 if( empty( $wgAddGroups[$group] ) ) {
3362 // Don't add anything to $groups
3363 } elseif( $wgAddGroups[$group] === true ) {
3364 // You get everything
3365 $groups['add'] = self
::getAllGroups();
3366 } elseif( is_array( $wgAddGroups[$group] ) ) {
3367 $groups['add'] = $wgAddGroups[$group];
3370 // Same thing for remove
3371 if( empty( $wgRemoveGroups[$group] ) ) {
3372 } elseif( $wgRemoveGroups[$group] === true ) {
3373 $groups['remove'] = self
::getAllGroups();
3374 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
3375 $groups['remove'] = $wgRemoveGroups[$group];
3378 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
3379 if( empty( $wgGroupsAddToSelf['user']) ||
$wgGroupsAddToSelf['user'] !== true ) {
3380 foreach( $wgGroupsAddToSelf as $key => $value ) {
3381 if( is_int( $key ) ) {
3382 $wgGroupsAddToSelf['user'][] = $value;
3387 if( empty( $wgGroupsRemoveFromSelf['user']) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
3388 foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
3389 if( is_int( $key ) ) {
3390 $wgGroupsRemoveFromSelf['user'][] = $value;
3395 // Now figure out what groups the user can add to him/herself
3396 if( empty( $wgGroupsAddToSelf[$group] ) ) {
3397 } elseif( $wgGroupsAddToSelf[$group] === true ) {
3398 // No idea WHY this would be used, but it's there
3399 $groups['add-self'] = User
::getAllGroups();
3400 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
3401 $groups['add-self'] = $wgGroupsAddToSelf[$group];
3404 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
3405 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
3406 $groups['remove-self'] = User
::getAllGroups();
3407 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
3408 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
3415 * Returns an array of groups that this user can add and remove
3416 * @return Array array( 'add' => array( addablegroups ),
3417 * 'remove' => array( removablegroups ),
3418 * 'add-self' => array( addablegroups to self),
3419 * 'remove-self' => array( removable groups from self) )
3421 function changeableGroups() {
3422 if( $this->isAllowed( 'userrights' ) ) {
3423 // This group gives the right to modify everything (reverse-
3424 // compatibility with old "userrights lets you change
3426 // Using array_merge to make the groups reindexed
3427 $all = array_merge( User
::getAllGroups() );
3431 'add-self' => array(),
3432 'remove-self' => array()
3436 // Okay, it's not so simple, we will have to go through the arrays
3439 'remove' => array(),
3440 'add-self' => array(),
3441 'remove-self' => array()
3443 $addergroups = $this->getEffectiveGroups();
3445 foreach( $addergroups as $addergroup ) {
3446 $groups = array_merge_recursive(
3447 $groups, $this->changeableByGroup( $addergroup )
3449 $groups['add'] = array_unique( $groups['add'] );
3450 $groups['remove'] = array_unique( $groups['remove'] );
3451 $groups['add-self'] = array_unique( $groups['add-self'] );
3452 $groups['remove-self'] = array_unique( $groups['remove-self'] );
3458 * Increment the user's edit-count field.
3459 * Will have no effect for anonymous users.
3461 function incEditCount() {
3462 if( !$this->isAnon() ) {
3463 $dbw = wfGetDB( DB_MASTER
);
3464 $dbw->update( 'user',
3465 array( 'user_editcount=user_editcount+1' ),
3466 array( 'user_id' => $this->getId() ),
3469 // Lazy initialization check...
3470 if( $dbw->affectedRows() == 0 ) {
3471 // Pull from a slave to be less cruel to servers
3472 // Accuracy isn't the point anyway here
3473 $dbr = wfGetDB( DB_SLAVE
);
3474 $count = $dbr->selectField( 'revision',
3476 array( 'rev_user' => $this->getId() ),
3479 // Now here's a goddamn hack...
3480 if( $dbr !== $dbw ) {
3481 // If we actually have a slave server, the count is
3482 // at least one behind because the current transaction
3483 // has not been committed and replicated.
3486 // But if DB_SLAVE is selecting the master, then the
3487 // count we just read includes the revision that was
3488 // just added in the working transaction.
3491 $dbw->update( 'user',
3492 array( 'user_editcount' => $count ),
3493 array( 'user_id' => $this->getId() ),
3497 // edit count in user cache too
3498 $this->invalidateCache();
3502 * Get the description of a given right
3504 * @param $right String Right to query
3505 * @return String Localized description of the right
3507 static function getRightDescription( $right ) {
3508 $key = "right-$right";
3509 $name = wfMsg( $key );
3510 return $name == '' ||
wfEmptyMsg( $key, $name )
3516 * Make an old-style password hash
3518 * @param $password String Plain-text password
3519 * @param $userId String User ID
3520 * @return String Password hash
3522 static function oldCrypt( $password, $userId ) {
3523 global $wgPasswordSalt;
3524 if ( $wgPasswordSalt ) {
3525 return md5( $userId . '-' . md5( $password ) );
3527 return md5( $password );
3532 * Make a new-style password hash
3534 * @param $password String Plain-text password
3535 * @param $salt String Optional salt, may be random or the user ID.
3536 * If unspecified or false, will generate one automatically
3537 * @return String Password hash
3539 static function crypt( $password, $salt = false ) {
3540 global $wgPasswordSalt;
3543 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3547 if( $wgPasswordSalt ) {
3548 if ( $salt === false ) {
3549 $salt = substr( wfGenerateToken(), 0, 8 );
3551 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3553 return ':A:' . md5( $password );
3558 * Compare a password hash with a plain-text password. Requires the user
3559 * ID if there's a chance that the hash is an old-style hash.
3561 * @param $hash String Password hash
3562 * @param $password String Plain-text password to compare
3563 * @param $userId String User ID for old-style password salt
3566 static function comparePasswords( $hash, $password, $userId = false ) {
3567 $type = substr( $hash, 0, 3 );
3570 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3574 if ( $type == ':A:' ) {
3576 return md5( $password ) === substr( $hash, 3 );
3577 } elseif ( $type == ':B:' ) {
3579 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3580 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3583 return self
::oldCrypt( $password, $userId ) === $hash;
3588 * Add a newuser log entry for this user
3590 * @param $byEmail Boolean: account made by email?
3591 * @param $reason String: user supplied reason
3593 public function addNewUserLogEntry( $byEmail = false, $reason = '' ) {
3594 global $wgUser, $wgContLang, $wgNewUserLog;
3595 if( empty( $wgNewUserLog ) ) {
3596 return true; // disabled
3599 if( $this->getName() == $wgUser->getName() ) {
3602 $action = 'create2';
3604 if ( $reason === '' ) {
3605 $reason = wfMsgForContent( 'newuserlog-byemail' );
3607 $reason = $wgContLang->commaList( array(
3608 $reason, wfMsgForContent( 'newuserlog-byemail' ) ) );
3612 $log = new LogPage( 'newusers' );
3615 $this->getUserPage(),
3617 array( $this->getId() )
3623 * Add an autocreate newuser log entry for this user
3624 * Used by things like CentralAuth and perhaps other authplugins.
3626 public function addNewUserLogEntryAutoCreate() {
3627 global $wgNewUserLog, $wgLogAutocreatedAccounts;
3628 if( !$wgNewUserLog ||
!$wgLogAutocreatedAccounts ) {
3629 return true; // disabled
3631 $log = new LogPage( 'newusers', false );
3632 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3636 protected function loadOptions() {
3638 if ( $this->mOptionsLoaded ||
!$this->getId() )
3641 $this->mOptions
= self
::getDefaultOptions();
3643 // Maybe load from the object
3644 if ( !is_null( $this->mOptionOverrides
) ) {
3645 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
3646 foreach( $this->mOptionOverrides
as $key => $value ) {
3647 $this->mOptions
[$key] = $value;
3650 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
3651 // Load from database
3652 $dbr = wfGetDB( DB_SLAVE
);
3654 $res = $dbr->select(
3657 array( 'up_user' => $this->getId() ),
3661 foreach ( $res as $row ) {
3662 $this->mOptionOverrides
[$row->up_property
] = $row->up_value
;
3663 $this->mOptions
[$row->up_property
] = $row->up_value
;
3667 $this->mOptionsLoaded
= true;
3669 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
3672 protected function saveOptions() {
3673 global $wgAllowPrefChange;
3675 $extuser = ExternalUser
::newFromUser( $this );
3677 $this->loadOptions();
3678 $dbw = wfGetDB( DB_MASTER
);
3680 $insert_rows = array();
3682 $saveOptions = $this->mOptions
;
3684 // Allow hooks to abort, for instance to save to a global profile.
3685 // Reset options to default state before saving.
3686 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) )
3689 foreach( $saveOptions as $key => $value ) {
3690 # Don't bother storing default values
3691 if ( ( is_null( self
::getDefaultOption( $key ) ) &&
3692 !( $value === false ||
is_null($value) ) ) ||
3693 $value != self
::getDefaultOption( $key ) ) {
3694 $insert_rows[] = array(
3695 'up_user' => $this->getId(),
3696 'up_property' => $key,
3697 'up_value' => $value,
3700 if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
3701 switch ( $wgAllowPrefChange[$key] ) {
3707 $extuser->setPref( $key, $value );
3713 $dbw->delete( 'user_properties', array( 'up_user' => $this->getId() ), __METHOD__
);
3714 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
);
3719 * Provide an array of HTML5 attributes to put on an input element
3720 * intended for the user to enter a new password. This may include
3721 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
3723 * Do *not* use this when asking the user to enter his current password!
3724 * Regardless of configuration, users may have invalid passwords for whatever
3725 * reason (e.g., they were set before requirements were tightened up).
3726 * Only use it when asking for a new password, like on account creation or
3729 * Obviously, you still need to do server-side checking.
3731 * NOTE: A combination of bugs in various browsers means that this function
3732 * actually just returns array() unconditionally at the moment. May as
3733 * well keep it around for when the browser bugs get fixed, though.
3735 * FIXME : This does not belong here; put it in Html or Linker or somewhere
3737 * @return array Array of HTML attributes suitable for feeding to
3738 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
3739 * That will potentially output invalid XHTML 1.0 Transitional, and will
3740 * get confused by the boolean attribute syntax used.)
3742 public static function passwordChangeInputAttribs() {
3743 global $wgMinimalPasswordLength;
3745 if ( $wgMinimalPasswordLength == 0 ) {
3749 # Note that the pattern requirement will always be satisfied if the
3750 # input is empty, so we need required in all cases.
3752 # FIXME (bug 23769): This needs to not claim the password is required
3753 # if e-mail confirmation is being used. Since HTML5 input validation
3754 # is b0rked anyway in some browsers, just return nothing. When it's
3755 # re-enabled, fix this code to not output required for e-mail
3757 #$ret = array( 'required' );
3760 # We can't actually do this right now, because Opera 9.6 will print out
3761 # the entered password visibly in its error message! When other
3762 # browsers add support for this attribute, or Opera fixes its support,
3763 # we can add support with a version check to avoid doing this on Opera
3764 # versions where it will be a problem. Reported to Opera as
3765 # DSK-262266, but they don't have a public bug tracker for us to follow.
3767 if ( $wgMinimalPasswordLength > 1 ) {
3768 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
3769 $ret['title'] = wfMsgExt( 'passwordtooshort', 'parsemag',
3770 $wgMinimalPasswordLength );