3 * Implements the User class for the %MediaWiki software.
8 * Int Serialized record version.
11 define( 'MW_USER_VERSION', 8 );
14 * String Some punctuation to prevent editing from broken text-mangling proxies.
17 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
20 * Thrown by User::setPassword() on error.
23 class PasswordError
extends MWException
{
28 * The User object encapsulates all of the user-specific settings (user_id,
29 * name, rights, password, email address, options, last login time). Client
30 * classes use the getXXX() functions to access these fields. These functions
31 * do all the work of determining whether the user is logged in,
32 * whether the requested option can be satisfied from cookies or
33 * whether a database query is needed. Most of the settings needed
34 * for rendering normal pages are set in the cookie to minimize use
40 * Array of Strings List of member variables which are saved to the
41 * shared cache (memcached). Any operation which changes the
42 * corresponding database fields must call a cache-clearing function.
45 static $mCacheVars = array(
56 'mEmailAuthenticated',
63 // user_properties table
68 * Array of Strings Core rights.
69 * Each of these should have a corresponding message of the form
73 static $mCoreRights = array(
92 'editusercssjs', #deprecated
104 'move-rootuserpages',
108 'override-export-depth',
129 'userrights-interwiki',
133 * String Cached results of getAllRights()
135 static $mAllRights = false;
137 /** @name Cache variables */
139 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
140 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
141 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups, $mOptionOverrides;
145 * Bool Whether the cache variables have been loaded.
147 var $mDataLoaded, $mAuthLoaded, $mOptionsLoaded;
150 * String Initialization data source if mDataLoaded==false. May be one of:
151 * - 'defaults' anonymous user initialised from class defaults
152 * - 'name' initialise from mName
153 * - 'id' initialise from mId
154 * - 'session' log in from cookies or session if possible
156 * Use the User::newFrom*() family of functions to set this.
161 * Lazy-initialized variables, invalidated with clearInstanceCache
163 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
164 $mBlockreason, $mBlock, $mEffectiveGroups, $mBlockedGlobally,
165 $mLocked, $mHideName, $mOptions;
167 static $idCacheByName = array();
170 * Lightweight constructor for an anonymous user.
171 * Use the User::newFrom* factory functions for other kinds of users.
175 * @see newFromConfirmationCode()
176 * @see newFromSession()
179 function __construct() {
180 $this->clearInstanceCache( 'defaults' );
184 * Load the user table data for this object from the source given by mFrom.
187 if ( $this->mDataLoaded
) {
190 wfProfileIn( __METHOD__
);
192 # Set it now to avoid infinite recursion in accessors
193 $this->mDataLoaded
= true;
195 switch ( $this->mFrom
) {
197 $this->loadDefaults();
200 $this->mId
= self
::idFromName( $this->mName
);
202 # Nonexistent user placeholder object
203 $this->loadDefaults( $this->mName
);
212 $this->loadFromSession();
213 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
216 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
218 wfProfileOut( __METHOD__
);
222 * Load user table data, given mId has already been set.
223 * @return Bool false if the ID does not exist, true otherwise
226 function loadFromId() {
228 if ( $this->mId
== 0 ) {
229 $this->loadDefaults();
234 $key = wfMemcKey( 'user', 'id', $this->mId
);
235 $data = $wgMemc->get( $key );
236 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
237 # Object is expired, load from DB
242 wfDebug( "User: cache miss for user {$this->mId}\n" );
244 if ( !$this->loadFromDatabase() ) {
245 # Can't load from ID, user is anonymous
248 $this->saveToCache();
250 wfDebug( "User: got user {$this->mId} from cache\n" );
252 foreach ( self
::$mCacheVars as $name ) {
253 $this->$name = $data[$name];
260 * Save user data to the shared cache
262 function saveToCache() {
265 $this->loadOptions();
266 if ( $this->isAnon() ) {
267 // Anonymous users are uncached
271 foreach ( self
::$mCacheVars as $name ) {
272 $data[$name] = $this->$name;
274 $data['mVersion'] = MW_USER_VERSION
;
275 $key = wfMemcKey( 'user', 'id', $this->mId
);
277 $wgMemc->set( $key, $data );
281 /** @name newFrom*() static factory methods */
285 * Static factory method for creation from username.
287 * This is slightly less efficient than newFromId(), so use newFromId() if
288 * you have both an ID and a name handy.
290 * @param $name String Username, validated by Title::newFromText()
291 * @param $validate String|Bool Validate username. Takes the same parameters as
292 * User::getCanonicalName(), except that true is accepted as an alias
293 * for 'valid', for BC.
295 * @return User object, or false if the username is invalid
296 * (e.g. if it contains illegal characters or is an IP address). If the
297 * username is not present in the database, the result will be a user object
298 * with a name, zero user ID and default settings.
300 static function newFromName( $name, $validate = 'valid' ) {
301 if ( $validate === true ) {
304 $name = self
::getCanonicalName( $name, $validate );
305 if ( $name === false ) {
308 # Create unloaded user object
317 * Static factory method for creation from a given user ID.
319 * @param $id Int Valid user ID
320 * @return User The corresponding User object
322 static function newFromId( $id ) {
330 * Factory method to fetch whichever user has a given email confirmation code.
331 * This code is generated when an account is created or its e-mail address
334 * If the code is invalid or has expired, returns NULL.
336 * @param $code String Confirmation code
339 static function newFromConfirmationCode( $code ) {
340 $dbr = wfGetDB( DB_SLAVE
);
341 $id = $dbr->selectField( 'user', 'user_id', array(
342 'user_email_token' => md5( $code ),
343 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
345 if( $id !== false ) {
346 return User
::newFromId( $id );
353 * Create a new user object using data from session or cookies. If the
354 * login credentials are invalid, the result is an anonymous user.
358 static function newFromSession() {
360 $user->mFrom
= 'session';
365 * Create a new user object from a user row.
366 * The row should have all fields from the user table in it.
367 * @param $row array A row from the user table
370 static function newFromRow( $row ) {
372 $user->loadFromRow( $row );
380 * Get the username corresponding to a given user ID
381 * @param $id Int User ID
382 * @return String The corresponding username
384 static function whoIs( $id ) {
385 $dbr = wfGetDB( DB_SLAVE
);
386 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), __METHOD__
);
390 * Get the real name of a user given their user ID
392 * @param $id Int User ID
393 * @return String The corresponding user's real name
395 static function whoIsReal( $id ) {
396 $dbr = wfGetDB( DB_SLAVE
);
397 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
401 * Get database id given a user name
402 * @param $name String Username
403 * @return Int|Null The corresponding user's ID, or null if user is nonexistent
405 static function idFromName( $name ) {
406 $nt = Title
::makeTitleSafe( NS_USER
, $name );
407 if( is_null( $nt ) ) {
412 if ( isset( self
::$idCacheByName[$name] ) ) {
413 return self
::$idCacheByName[$name];
416 $dbr = wfGetDB( DB_SLAVE
);
417 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
419 if ( $s === false ) {
422 $result = $s->user_id
;
425 self
::$idCacheByName[$name] = $result;
427 if ( count( self
::$idCacheByName ) > 1000 ) {
428 self
::$idCacheByName = array();
435 * Reset the cache used in idFromName(). For use in tests.
437 public static function resetIdByNameCache() {
438 self
::$idCacheByName = array();
442 * Does the string match an anonymous IPv4 address?
444 * This function exists for username validation, in order to reject
445 * usernames which are similar in form to IP addresses. Strings such
446 * as 300.300.300.300 will return true because it looks like an IP
447 * address, despite not being strictly valid.
449 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
450 * address because the usemod software would "cloak" anonymous IP
451 * addresses like this, if we allowed accounts like this to be created
452 * new users could get the old edits of these anonymous users.
454 * @param $name String to match
457 static function isIP( $name ) {
458 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP
::isIPv6($name);
462 * Is the input a valid username?
464 * Checks if the input is a valid username, we don't want an empty string,
465 * an IP address, anything that containins slashes (would mess up subpages),
466 * is longer than the maximum allowed username size or doesn't begin with
469 * @param $name String to match
472 static function isValidUserName( $name ) {
473 global $wgContLang, $wgMaxNameChars;
476 || User
::isIP( $name )
477 ||
strpos( $name, '/' ) !== false
478 ||
strlen( $name ) > $wgMaxNameChars
479 ||
$name != $wgContLang->ucfirst( $name ) ) {
480 wfDebugLog( 'username', __METHOD__
.
481 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
485 // Ensure that the name can't be misresolved as a different title,
486 // such as with extra namespace keys at the start.
487 $parsed = Title
::newFromText( $name );
488 if( is_null( $parsed )
489 ||
$parsed->getNamespace()
490 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
491 wfDebugLog( 'username', __METHOD__
.
492 ": '$name' invalid due to ambiguous prefixes" );
496 // Check an additional blacklist of troublemaker characters.
497 // Should these be merged into the title char list?
498 $unicodeBlacklist = '/[' .
499 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
500 '\x{00a0}' . # non-breaking space
501 '\x{2000}-\x{200f}' . # various whitespace
502 '\x{2028}-\x{202f}' . # breaks and control chars
503 '\x{3000}' . # ideographic space
504 '\x{e000}-\x{f8ff}' . # private use
506 if( preg_match( $unicodeBlacklist, $name ) ) {
507 wfDebugLog( 'username', __METHOD__
.
508 ": '$name' invalid due to blacklisted characters" );
516 * Usernames which fail to pass this function will be blocked
517 * from user login and new account registrations, but may be used
518 * internally by batch processes.
520 * If an account already exists in this form, login will be blocked
521 * by a failure to pass this function.
523 * @param $name String to match
526 static function isUsableName( $name ) {
527 global $wgReservedUsernames;
528 // Must be a valid username, obviously ;)
529 if ( !self
::isValidUserName( $name ) ) {
533 static $reservedUsernames = false;
534 if ( !$reservedUsernames ) {
535 $reservedUsernames = $wgReservedUsernames;
536 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
539 // Certain names may be reserved for batch processes.
540 foreach ( $reservedUsernames as $reserved ) {
541 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
542 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
544 if ( $reserved == $name ) {
552 * Usernames which fail to pass this function will be blocked
553 * from new account registrations, but may be used internally
554 * either by batch processes or by user accounts which have
555 * already been created.
557 * Additional blacklisting may be added here rather than in
558 * isValidUserName() to avoid disrupting existing accounts.
560 * @param $name String to match
563 static function isCreatableName( $name ) {
564 global $wgInvalidUsernameCharacters;
566 // Ensure that the username isn't longer than 235 bytes, so that
567 // (at least for the builtin skins) user javascript and css files
568 // will work. (bug 23080)
569 if( strlen( $name ) > 235 ) {
570 wfDebugLog( 'username', __METHOD__
.
571 ": '$name' invalid due to length" );
575 // Preg yells if you try to give it an empty string
576 if( $wgInvalidUsernameCharacters !== '' ) {
577 if( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
578 wfDebugLog( 'username', __METHOD__
.
579 ": '$name' invalid due to wgInvalidUsernameCharacters" );
584 return self
::isUsableName( $name );
588 * Is the input a valid password for this user?
590 * @param $password String Desired password
593 function isValidPassword( $password ) {
594 //simple boolean wrapper for getPasswordValidity
595 return $this->getPasswordValidity( $password ) === true;
599 * Given unvalidated password input, return error message on failure.
601 * @param $password String Desired password
602 * @return mixed: true on success, string or array of error message on failure
604 function getPasswordValidity( $password ) {
605 global $wgMinimalPasswordLength, $wgContLang;
607 static $blockedLogins = array(
608 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
609 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
612 $result = false; //init $result to false for the internal checks
614 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
618 if ( $result === false ) {
619 if( strlen( $password ) < $wgMinimalPasswordLength ) {
620 return 'passwordtooshort';
621 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
622 return 'password-name-match';
623 } elseif ( isset( $blockedLogins[ $this->getName() ] ) && $password == $blockedLogins[ $this->getName() ] ) {
624 return 'password-login-forbidden';
626 //it seems weird returning true here, but this is because of the
627 //initialization of $result to false above. If the hook is never run or it
628 //doesn't modify $result, then we will likely get down into this if with
632 } elseif( $result === true ) {
635 return $result; //the isValidPassword hook set a string $result and returned true
640 * Does a string look like an e-mail address?
642 * This validates an email address using an HTML5 specification found at:
643 * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
644 * Which as of 2011-01-24 says:
646 * A valid e-mail address is a string that matches the ABNF production
647 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
648 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
651 * This function is an implementation of the specification as requested in
654 * Client-side forms will use the same standard validation rules via JS or
655 * HTML 5 validation; additional restrictions can be enforced server-side
656 * by extensions via the 'isValidEmailAddr' hook.
658 * Note that this validation doesn't 100% match RFC 2822, but is believed
659 * to be liberal enough for wide use. Some invalid addresses will still
660 * pass validation here.
662 * @param $addr String E-mail address
665 public static function isValidEmailAddr( $addr ) {
667 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
671 // Please note strings below are enclosed in brackets [], this make the
672 // hyphen "-" a range indicator. Hence it is double backslashed below.
674 $rfc5322_atext = "a-z0-9!#$%&'*+\\-\/=?^_`{|}~" ;
675 $rfc1034_ldh_str = "a-z0-9\\-" ;
677 $HTML5_email_regexp = "/
679 [$rfc5322_atext\\.]+ # user part which is liberal :p
681 [$rfc1034_ldh_str]+ # First domain part
682 (\\.[$rfc1034_ldh_str]+)* # Following part prefixed with a dot
684 /ix" ; // case Insensitive, eXtended
686 return (bool) preg_match( $HTML5_email_regexp, $addr );
690 * Given unvalidated user input, return a canonical username, or false if
691 * the username is invalid.
692 * @param $name String User input
693 * @param $validate String|Bool type of validation to use:
694 * - false No validation
695 * - 'valid' Valid for batch processes
696 * - 'usable' Valid for batch processes and login
697 * - 'creatable' Valid for batch processes, login and account creation
699 static function getCanonicalName( $name, $validate = 'valid' ) {
700 # Force usernames to capital
702 $name = $wgContLang->ucfirst( $name );
704 # Reject names containing '#'; these will be cleaned up
705 # with title normalisation, but then it's too late to
707 if( strpos( $name, '#' ) !== false )
710 # Clean up name according to title rules
711 $t = ( $validate === 'valid' ) ?
712 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
713 # Check for invalid titles
714 if( is_null( $t ) ) {
718 # Reject various classes of invalid names
720 $name = $wgAuth->getCanonicalName( $t->getText() );
722 switch ( $validate ) {
726 if ( !User
::isValidUserName( $name ) ) {
731 if ( !User
::isUsableName( $name ) ) {
736 if ( !User
::isCreatableName( $name ) ) {
741 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
747 * Count the number of edits of a user
748 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
750 * @param $uid Int User ID to check
751 * @return Int the user's edit count
753 static function edits( $uid ) {
754 wfProfileIn( __METHOD__
);
755 $dbr = wfGetDB( DB_SLAVE
);
756 // check if the user_editcount field has been initialized
757 $field = $dbr->selectField(
758 'user', 'user_editcount',
759 array( 'user_id' => $uid ),
763 if( $field === null ) { // it has not been initialized. do so.
764 $dbw = wfGetDB( DB_MASTER
);
765 $count = $dbr->selectField(
766 'revision', 'count(*)',
767 array( 'rev_user' => $uid ),
772 array( 'user_editcount' => $count ),
773 array( 'user_id' => $uid ),
779 wfProfileOut( __METHOD__
);
784 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
785 * @todo hash random numbers to improve security, like generateToken()
787 * @return String new random password
789 static function randomPassword() {
790 global $wgMinimalPasswordLength;
791 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
792 $l = strlen( $pwchars ) - 1;
794 $pwlength = max( 7, $wgMinimalPasswordLength );
795 $digit = mt_rand( 0, $pwlength - 1 );
797 for ( $i = 0; $i < $pwlength; $i++
) {
798 $np .= $i == $digit ?
chr( mt_rand( 48, 57 ) ) : $pwchars{ mt_rand( 0, $l ) };
804 * Set cached properties to default.
806 * @note This no longer clears uncached lazy-initialised properties;
807 * the constructor does that instead.
810 function loadDefaults( $name = false ) {
811 wfProfileIn( __METHOD__
);
816 $this->mName
= $name;
817 $this->mRealName
= '';
818 $this->mPassword
= $this->mNewpassword
= '';
819 $this->mNewpassTime
= null;
821 $this->mOptionOverrides
= null;
822 $this->mOptionsLoaded
= false;
824 if( $wgRequest->getCookie( 'LoggedOut' ) !== null ) {
825 $this->mTouched
= wfTimestamp( TS_MW
, $wgRequest->getCookie( 'LoggedOut' ) );
827 $this->mTouched
= '0'; # Allow any pages to be cached
830 $this->setToken(); # Random
831 $this->mEmailAuthenticated
= null;
832 $this->mEmailToken
= '';
833 $this->mEmailTokenExpires
= null;
834 $this->mRegistration
= wfTimestamp( TS_MW
);
835 $this->mGroups
= array();
837 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
839 wfProfileOut( __METHOD__
);
843 * Load user data from the session or login cookie. If there are no valid
844 * credentials, initialises the user as an anonymous user.
845 * @return Bool True if the user is logged in, false otherwise.
847 private function loadFromSession() {
848 global $wgRequest, $wgExternalAuthType, $wgAutocreatePolicy;
851 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
852 if ( $result !== null ) {
856 if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
857 $extUser = ExternalUser
::newFromCookie();
859 # TODO: Automatically create the user here (or probably a bit
860 # lower down, in fact)
864 if ( $wgRequest->getCookie( 'UserID' ) !== null ) {
865 $sId = intval( $wgRequest->getCookie( 'UserID' ) );
866 if( isset( $_SESSION['wsUserID'] ) && $sId != $_SESSION['wsUserID'] ) {
867 $this->loadDefaults(); // Possible collision!
868 wfDebugLog( 'loginSessions', "Session user ID ({$_SESSION['wsUserID']}) and
869 cookie user ID ($sId) don't match!" );
872 $_SESSION['wsUserID'] = $sId;
873 } else if ( isset( $_SESSION['wsUserID'] ) ) {
874 if ( $_SESSION['wsUserID'] != 0 ) {
875 $sId = $_SESSION['wsUserID'];
877 $this->loadDefaults();
881 $this->loadDefaults();
885 if ( isset( $_SESSION['wsUserName'] ) ) {
886 $sName = $_SESSION['wsUserName'];
887 } else if ( $wgRequest->getCookie('UserName') !== null ) {
888 $sName = $wgRequest->getCookie('UserName');
889 $_SESSION['wsUserName'] = $sName;
891 $this->loadDefaults();
896 if ( !$this->loadFromId() ) {
897 # Not a valid ID, loadFromId has switched the object to anon for us
901 global $wgBlockDisablesLogin;
902 if( $wgBlockDisablesLogin && $this->isBlocked() ) {
903 # User blocked and we've disabled blocked user logins
904 $this->loadDefaults();
908 if ( isset( $_SESSION['wsToken'] ) ) {
909 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
911 } else if ( $wgRequest->getCookie( 'Token' ) !== null ) {
912 $passwordCorrect = $this->mToken
== $wgRequest->getCookie( 'Token' );
915 # No session or persistent login cookie
916 $this->loadDefaults();
920 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
921 $_SESSION['wsToken'] = $this->mToken
;
922 wfDebug( "User: logged in from $from\n" );
925 # Invalid credentials
926 wfDebug( "User: can't log in from $from, invalid credentials\n" );
927 $this->loadDefaults();
933 * Load user and user_group data from the database.
934 * $this::mId must be set, this is how the user is identified.
936 * @return Bool True if the user exists, false if the user is anonymous
939 function loadFromDatabase() {
941 $this->mId
= intval( $this->mId
);
943 /** Anonymous user */
945 $this->loadDefaults();
949 $dbr = wfGetDB( DB_MASTER
);
950 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
952 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
954 if ( $s !== false ) {
955 # Initialise user table data
956 $this->loadFromRow( $s );
957 $this->mGroups
= null; // deferred
958 $this->getEditCount(); // revalidation for nulls
963 $this->loadDefaults();
969 * Initialize this object from a row from the user table.
971 * @param $row Array Row from the user table to load.
973 function loadFromRow( $row ) {
974 $this->mDataLoaded
= true;
976 if ( isset( $row->user_id
) ) {
977 $this->mId
= intval( $row->user_id
);
979 $this->mName
= $row->user_name
;
980 $this->mRealName
= $row->user_real_name
;
981 $this->mPassword
= $row->user_password
;
982 $this->mNewpassword
= $row->user_newpassword
;
983 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
984 $this->mEmail
= $row->user_email
;
985 $this->decodeOptions( $row->user_options
);
986 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
987 $this->mToken
= $row->user_token
;
988 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
989 $this->mEmailToken
= $row->user_email_token
;
990 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
991 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
992 $this->mEditCount
= $row->user_editcount
;
996 * Load the groups from the database if they aren't already loaded.
999 function loadGroups() {
1000 if ( is_null( $this->mGroups
) ) {
1001 $dbr = wfGetDB( DB_MASTER
);
1002 $res = $dbr->select( 'user_groups',
1003 array( 'ug_group' ),
1004 array( 'ug_user' => $this->mId
),
1006 $this->mGroups
= array();
1007 foreach ( $res as $row ) {
1008 $this->mGroups
[] = $row->ug_group
;
1014 * Clear various cached data stored in this object.
1015 * @param $reloadFrom String Reload user and user_groups table data from a
1016 * given source. May be "name", "id", "defaults", "session", or false for
1019 function clearInstanceCache( $reloadFrom = false ) {
1020 $this->mNewtalk
= -1;
1021 $this->mDatePreference
= null;
1022 $this->mBlockedby
= -1; # Unset
1023 $this->mHash
= false;
1024 $this->mSkin
= null;
1025 $this->mRights
= null;
1026 $this->mEffectiveGroups
= null;
1027 $this->mOptions
= null;
1029 if ( $reloadFrom ) {
1030 $this->mDataLoaded
= false;
1031 $this->mFrom
= $reloadFrom;
1036 * Combine the language default options with any site-specific options
1037 * and add the default language variants.
1039 * @return Array of String options
1041 static function getDefaultOptions() {
1042 global $wgNamespacesToBeSearchedDefault;
1044 * Site defaults will override the global/language defaults
1046 global $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1047 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
1050 * default language setting
1052 $variant = $wgContLang->getDefaultVariant();
1053 $defOpt['variant'] = $variant;
1054 $defOpt['language'] = $variant;
1055 foreach( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1056 $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1058 $defOpt['skin'] = $wgDefaultSkin;
1064 * Get a given default option value.
1066 * @param $opt String Name of option to retrieve
1067 * @return String Default option value
1069 public static function getDefaultOption( $opt ) {
1070 $defOpts = self
::getDefaultOptions();
1071 if( isset( $defOpts[$opt] ) ) {
1072 return $defOpts[$opt];
1080 * Get blocking information
1082 * @param $bFromSlave Bool Whether to check the slave database first. To
1083 * improve performance, non-critical checks are done
1084 * against slaves. Check when actually saving should be
1085 * done against master.
1087 function getBlockedStatus( $bFromSlave = true ) {
1088 global $wgProxyWhitelist, $wgUser;
1090 if ( -1 != $this->mBlockedby
) {
1094 wfProfileIn( __METHOD__
);
1095 wfDebug( __METHOD__
.": checking...\n" );
1097 // Initialize data...
1098 // Otherwise something ends up stomping on $this->mBlockedby when
1099 // things get lazy-loaded later, causing false positive block hits
1100 // due to -1 !== 0. Probably session-related... Nothing should be
1101 // overwriting mBlockedby, surely?
1104 $this->mBlockedby
= 0;
1105 $this->mHideName
= 0;
1106 $this->mAllowUsertalk
= 0;
1108 # Check if we are looking at an IP or a logged-in user
1109 if ( $this->isIP( $this->getName() ) ) {
1110 $ip = $this->getName();
1112 # Check if we are looking at the current user
1113 # If we don't, and the user is logged in, we don't know about
1114 # his IP / autoblock status, so ignore autoblock of current user's IP
1115 if ( $this->getID() != $wgUser->getID() ) {
1118 # Get IP of current user
1123 if ( $this->isAllowed( 'ipblock-exempt' ) ) {
1124 # Exempt from all types of IP-block
1129 $this->mBlock
= new Block();
1130 $this->mBlock
->fromMaster( !$bFromSlave );
1131 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
1132 wfDebug( __METHOD__
. ": Found block.\n" );
1133 $this->mBlockedby
= $this->mBlock
->mBy
;
1134 if( $this->mBlockedby
== 0 )
1135 $this->mBlockedby
= $this->mBlock
->mByName
;
1136 $this->mBlockreason
= $this->mBlock
->mReason
;
1137 $this->mHideName
= $this->mBlock
->mHideName
;
1138 $this->mAllowUsertalk
= $this->mBlock
->mAllowUsertalk
;
1139 if ( $this->isLoggedIn() && $wgUser->getID() == $this->getID() ) {
1140 $this->spreadBlock();
1143 // Bug 13611: don't remove mBlock here, to allow account creation blocks to
1144 // apply to users. Note that the existence of $this->mBlock is not used to
1145 // check for edit blocks, $this->mBlockedby is instead.
1149 if ( !$this->isAllowed( 'proxyunbannable' ) && !in_array( $ip, $wgProxyWhitelist ) ) {
1151 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1152 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1153 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1157 if ( !$this->mBlockedby
&& !$this->getID() ) {
1158 if ( $this->isDnsBlacklisted( $ip ) ) {
1159 $this->mBlockedby
= wfMsg( 'sorbs' );
1160 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1166 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1168 wfProfileOut( __METHOD__
);
1172 * Whether the given IP is in a DNS blacklist.
1174 * @param $ip String IP to check
1175 * @param $checkWhitelist Bool: whether to check the whitelist first
1176 * @return Bool True if blacklisted.
1178 function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1179 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1180 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1182 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
1185 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
1188 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1189 return $this->inDnsBlacklist( $ip, $urls );
1193 * Whether the given IP is in a given DNS blacklist.
1195 * @param $ip String IP to check
1196 * @param $bases String|Array of Strings: URL of the DNS blacklist
1197 * @return Bool True if blacklisted.
1199 function inDnsBlacklist( $ip, $bases ) {
1200 wfProfileIn( __METHOD__
);
1203 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1204 if( IP
::isIPv4( $ip ) ) {
1205 # Reverse IP, bug 21255
1206 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1208 foreach( (array)$bases as $base ) {
1210 $host = "$ipReversed.$base";
1213 $ipList = gethostbynamel( $host );
1216 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1220 wfDebug( "Requested $host, not found in $base.\n" );
1225 wfProfileOut( __METHOD__
);
1230 * Is this user subject to rate limiting?
1232 * @return Bool True if rate limited
1234 public function isPingLimitable() {
1235 global $wgRateLimitsExcludedGroups;
1236 global $wgRateLimitsExcludedIPs;
1237 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1238 // Deprecated, but kept for backwards-compatibility config
1244 if( in_array( wfGetIP(), $wgRateLimitsExcludedIPs ) ) {
1245 // No other good way currently to disable rate limits
1246 // for specific IPs. :P
1247 // But this is a crappy hack and should die.
1250 return !$this->isAllowed('noratelimit');
1254 * Primitive rate limits: enforce maximum actions per time period
1255 * to put a brake on flooding.
1257 * @note When using a shared cache like memcached, IP-address
1258 * last-hit counters will be shared across wikis.
1260 * @param $action String Action to enforce; 'edit' if unspecified
1261 * @return Bool True if a rate limiter was tripped
1263 function pingLimiter( $action = 'edit' ) {
1264 # Call the 'PingLimiter' hook
1266 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1270 global $wgRateLimits;
1271 if( !isset( $wgRateLimits[$action] ) ) {
1275 # Some groups shouldn't trigger the ping limiter, ever
1276 if( !$this->isPingLimitable() )
1279 global $wgMemc, $wgRateLimitLog;
1280 wfProfileIn( __METHOD__
);
1282 $limits = $wgRateLimits[$action];
1284 $id = $this->getId();
1288 if( isset( $limits['anon'] ) && $id == 0 ) {
1289 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1292 if( isset( $limits['user'] ) && $id != 0 ) {
1293 $userLimit = $limits['user'];
1295 if( $this->isNewbie() ) {
1296 if( isset( $limits['newbie'] ) && $id != 0 ) {
1297 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1299 if( isset( $limits['ip'] ) ) {
1300 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1303 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1304 $subnet = $matches[1];
1305 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1308 // Check for group-specific permissions
1309 // If more than one group applies, use the group with the highest limit
1310 foreach ( $this->getGroups() as $group ) {
1311 if ( isset( $limits[$group] ) ) {
1312 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1313 $userLimit = $limits[$group];
1317 // Set the user limit key
1318 if ( $userLimit !== false ) {
1319 wfDebug( __METHOD__
. ": effective user limit: $userLimit\n" );
1320 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1324 foreach( $keys as $key => $limit ) {
1325 list( $max, $period ) = $limit;
1326 $summary = "(limit $max in {$period}s)";
1327 $count = $wgMemc->get( $key );
1330 if( $count > $max ) {
1331 wfDebug( __METHOD__
. ": tripped! $key at $count $summary\n" );
1332 if( $wgRateLimitLog ) {
1333 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1337 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1340 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1341 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1343 $wgMemc->incr( $key );
1346 wfProfileOut( __METHOD__
);
1351 * Check if user is blocked
1353 * @param $bFromSlave Bool Whether to check the slave database instead of the master
1354 * @return Bool True if blocked, false otherwise
1356 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1357 $this->getBlockedStatus( $bFromSlave );
1358 return $this->mBlockedby
!== 0;
1362 * Check if user is blocked from editing a particular article
1364 * @param $title Title to check
1365 * @param $bFromSlave Bool whether to check the slave database instead of the master
1368 function isBlockedFrom( $title, $bFromSlave = false ) {
1369 global $wgBlockAllowsUTEdit;
1370 wfProfileIn( __METHOD__
);
1372 $blocked = $this->isBlocked( $bFromSlave );
1373 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1374 # If a user's name is suppressed, they cannot make edits anywhere
1375 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1376 $title->getNamespace() == NS_USER_TALK
) {
1378 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1381 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1383 wfProfileOut( __METHOD__
);
1388 * If user is blocked, return the name of the user who placed the block
1389 * @return String name of blocker
1391 function blockedBy() {
1392 $this->getBlockedStatus();
1393 return $this->mBlockedby
;
1397 * If user is blocked, return the specified reason for the block
1398 * @return String Blocking reason
1400 function blockedFor() {
1401 $this->getBlockedStatus();
1402 return $this->mBlockreason
;
1406 * If user is blocked, return the ID for the block
1407 * @return Int Block ID
1409 function getBlockId() {
1410 $this->getBlockedStatus();
1411 return ( $this->mBlock ?
$this->mBlock
->mId
: false );
1415 * Check if user is blocked on all wikis.
1416 * Do not use for actual edit permission checks!
1417 * This is intented for quick UI checks.
1419 * @param $ip String IP address, uses current client if none given
1420 * @return Bool True if blocked, false otherwise
1422 function isBlockedGlobally( $ip = '' ) {
1423 if( $this->mBlockedGlobally
!== null ) {
1424 return $this->mBlockedGlobally
;
1426 // User is already an IP?
1427 if( IP
::isIPAddress( $this->getName() ) ) {
1428 $ip = $this->getName();
1433 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1434 $this->mBlockedGlobally
= (bool)$blocked;
1435 return $this->mBlockedGlobally
;
1439 * Check if user account is locked
1441 * @return Bool True if locked, false otherwise
1443 function isLocked() {
1444 if( $this->mLocked
!== null ) {
1445 return $this->mLocked
;
1448 $authUser = $wgAuth->getUserInstance( $this );
1449 $this->mLocked
= (bool)$authUser->isLocked();
1450 return $this->mLocked
;
1454 * Check if user account is hidden
1456 * @return Bool True if hidden, false otherwise
1458 function isHidden() {
1459 if( $this->mHideName
!== null ) {
1460 return $this->mHideName
;
1462 $this->getBlockedStatus();
1463 if( !$this->mHideName
) {
1465 $authUser = $wgAuth->getUserInstance( $this );
1466 $this->mHideName
= (bool)$authUser->isHidden();
1468 return $this->mHideName
;
1472 * Get the user's ID.
1473 * @return Int The user's ID; 0 if the user is anonymous or nonexistent
1476 if( $this->mId
=== null and $this->mName
!== null
1477 and User
::isIP( $this->mName
) ) {
1478 // Special case, we know the user is anonymous
1480 } elseif( $this->mId
=== null ) {
1481 // Don't load if this was initialized from an ID
1488 * Set the user and reload all fields according to a given ID
1489 * @param $v Int User ID to reload
1491 function setId( $v ) {
1493 $this->clearInstanceCache( 'id' );
1497 * Get the user name, or the IP of an anonymous user
1498 * @return String User's name or IP address
1500 function getName() {
1501 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1502 # Special case optimisation
1503 return $this->mName
;
1506 if ( $this->mName
=== false ) {
1508 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1510 return $this->mName
;
1515 * Set the user name.
1517 * This does not reload fields from the database according to the given
1518 * name. Rather, it is used to create a temporary "nonexistent user" for
1519 * later addition to the database. It can also be used to set the IP
1520 * address for an anonymous user to something other than the current
1523 * @note User::newFromName() has rougly the same function, when the named user
1525 * @param $str String New user name to set
1527 function setName( $str ) {
1529 $this->mName
= $str;
1533 * Get the user's name escaped by underscores.
1534 * @return String Username escaped by underscores.
1536 function getTitleKey() {
1537 return str_replace( ' ', '_', $this->getName() );
1541 * Check if the user has new messages.
1542 * @return Bool True if the user has new messages
1544 function getNewtalk() {
1547 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1548 if( $this->mNewtalk
=== -1 ) {
1549 $this->mNewtalk
= false; # reset talk page status
1551 # Check memcached separately for anons, who have no
1552 # entire User object stored in there.
1555 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1556 $newtalk = $wgMemc->get( $key );
1557 if( strval( $newtalk ) !== '' ) {
1558 $this->mNewtalk
= (bool)$newtalk;
1560 // Since we are caching this, make sure it is up to date by getting it
1562 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1563 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1566 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1570 return (bool)$this->mNewtalk
;
1574 * Return the talk page(s) this user has new messages on.
1575 * @return Array of String page URLs
1577 function getNewMessageLinks() {
1579 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) )
1582 if( !$this->getNewtalk() )
1584 $up = $this->getUserPage();
1585 $utp = $up->getTalkPage();
1586 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL() ) );
1590 * Internal uncached check for new messages
1593 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1594 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1595 * @param $fromMaster Bool true to fetch from the master, false for a slave
1596 * @return Bool True if the user has new messages
1599 function checkNewtalk( $field, $id, $fromMaster = false ) {
1600 if ( $fromMaster ) {
1601 $db = wfGetDB( DB_MASTER
);
1603 $db = wfGetDB( DB_SLAVE
);
1605 $ok = $db->selectField( 'user_newtalk', $field,
1606 array( $field => $id ), __METHOD__
);
1607 return $ok !== false;
1611 * Add or update the new messages flag
1612 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1613 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1614 * @return Bool True if successful, false otherwise
1617 function updateNewtalk( $field, $id ) {
1618 $dbw = wfGetDB( DB_MASTER
);
1619 $dbw->insert( 'user_newtalk',
1620 array( $field => $id ),
1623 if ( $dbw->affectedRows() ) {
1624 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
1627 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
1633 * Clear the new messages flag for the given user
1634 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1635 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1636 * @return Bool True if successful, false otherwise
1639 function deleteNewtalk( $field, $id ) {
1640 $dbw = wfGetDB( DB_MASTER
);
1641 $dbw->delete( 'user_newtalk',
1642 array( $field => $id ),
1644 if ( $dbw->affectedRows() ) {
1645 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
1648 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
1654 * Update the 'You have new messages!' status.
1655 * @param $val Bool Whether the user has new messages
1657 function setNewtalk( $val ) {
1658 if( wfReadOnly() ) {
1663 $this->mNewtalk
= $val;
1665 if( $this->isAnon() ) {
1667 $id = $this->getName();
1670 $id = $this->getId();
1675 $changed = $this->updateNewtalk( $field, $id );
1677 $changed = $this->deleteNewtalk( $field, $id );
1680 if( $this->isAnon() ) {
1681 // Anons have a separate memcached space, since
1682 // user records aren't kept for them.
1683 $key = wfMemcKey( 'newtalk', 'ip', $id );
1684 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1687 $this->invalidateCache();
1692 * Generate a current or new-future timestamp to be stored in the
1693 * user_touched field when we update things.
1694 * @return String Timestamp in TS_MW format
1696 private static function newTouchedTimestamp() {
1697 global $wgClockSkewFudge;
1698 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1702 * Clear user data from memcached.
1703 * Use after applying fun updates to the database; caller's
1704 * responsibility to update user_touched if appropriate.
1706 * Called implicitly from invalidateCache() and saveSettings().
1708 private function clearSharedCache() {
1712 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1717 * Immediately touch the user data cache for this account.
1718 * Updates user_touched field, and removes account data from memcached
1719 * for reload on the next hit.
1721 function invalidateCache() {
1722 if( wfReadOnly() ) {
1727 $this->mTouched
= self
::newTouchedTimestamp();
1729 $dbw = wfGetDB( DB_MASTER
);
1730 $dbw->update( 'user',
1731 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1732 array( 'user_id' => $this->mId
),
1735 $this->clearSharedCache();
1740 * Validate the cache for this account.
1741 * @param $timestamp String A timestamp in TS_MW format
1743 function validateCache( $timestamp ) {
1745 return ( $timestamp >= $this->mTouched
);
1749 * Get the user touched timestamp
1750 * @return String timestamp
1752 function getTouched() {
1754 return $this->mTouched
;
1758 * Set the password and reset the random token.
1759 * Calls through to authentication plugin if necessary;
1760 * will have no effect if the auth plugin refuses to
1761 * pass the change through or if the legal password
1764 * As a special case, setting the password to null
1765 * wipes it, so the account cannot be logged in until
1766 * a new password is set, for instance via e-mail.
1768 * @param $str String New password to set
1769 * @throws PasswordError on failure
1771 function setPassword( $str ) {
1774 if( $str !== null ) {
1775 if( !$wgAuth->allowPasswordChange() ) {
1776 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1779 if( !$this->isValidPassword( $str ) ) {
1780 global $wgMinimalPasswordLength;
1781 $valid = $this->getPasswordValidity( $str );
1782 if ( is_array( $valid ) ) {
1783 $message = array_shift( $valid );
1787 $params = array( $wgMinimalPasswordLength );
1789 throw new PasswordError( wfMsgExt( $message, array( 'parsemag' ), $params ) );
1793 if( !$wgAuth->setPassword( $this, $str ) ) {
1794 throw new PasswordError( wfMsg( 'externaldberror' ) );
1797 $this->setInternalPassword( $str );
1803 * Set the password and reset the random token unconditionally.
1805 * @param $str String New password to set
1807 function setInternalPassword( $str ) {
1811 if( $str === null ) {
1812 // Save an invalid hash...
1813 $this->mPassword
= '';
1815 $this->mPassword
= self
::crypt( $str );
1817 $this->mNewpassword
= '';
1818 $this->mNewpassTime
= null;
1822 * Get the user's current token.
1823 * @return String Token
1825 function getToken() {
1827 return $this->mToken
;
1831 * Set the random token (used for persistent authentication)
1832 * Called from loadDefaults() among other places.
1834 * @param $token String If specified, set the token to this value
1837 function setToken( $token = false ) {
1838 global $wgSecretKey, $wgProxyKey;
1841 if ( $wgSecretKey ) {
1842 $key = $wgSecretKey;
1843 } elseif ( $wgProxyKey ) {
1848 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1850 $this->mToken
= $token;
1855 * Set the cookie password
1857 * @param $str String New cookie password
1860 function setCookiePassword( $str ) {
1862 $this->mCookiePassword
= md5( $str );
1866 * Set the password for a password reminder or new account email
1868 * @param $str String New password to set
1869 * @param $throttle Bool If true, reset the throttle timestamp to the present
1871 function setNewpassword( $str, $throttle = true ) {
1873 $this->mNewpassword
= self
::crypt( $str );
1875 $this->mNewpassTime
= wfTimestampNow();
1880 * Has password reminder email been sent within the last
1881 * $wgPasswordReminderResendTime hours?
1884 function isPasswordReminderThrottled() {
1885 global $wgPasswordReminderResendTime;
1887 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1890 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1891 return time() < $expiry;
1895 * Get the user's e-mail address
1896 * @return String User's email address
1898 function getEmail() {
1900 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1901 return $this->mEmail
;
1905 * Get the timestamp of the user's e-mail authentication
1906 * @return String TS_MW timestamp
1908 function getEmailAuthenticationTimestamp() {
1910 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1911 return $this->mEmailAuthenticated
;
1915 * Set the user's e-mail address
1916 * @param $str String New e-mail address
1918 function setEmail( $str ) {
1920 $this->mEmail
= $str;
1921 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1925 * Get the user's real name
1926 * @return String User's real name
1928 function getRealName() {
1930 return $this->mRealName
;
1934 * Set the user's real name
1935 * @param $str String New real name
1937 function setRealName( $str ) {
1939 $this->mRealName
= $str;
1943 * Get the user's current setting for a given option.
1945 * @param $oname String The option to check
1946 * @param $defaultOverride String A default value returned if the option does not exist
1947 * @return String User's current value for the option
1948 * @see getBoolOption()
1949 * @see getIntOption()
1951 function getOption( $oname, $defaultOverride = null ) {
1952 $this->loadOptions();
1954 if ( is_null( $this->mOptions
) ) {
1955 if($defaultOverride != '') {
1956 return $defaultOverride;
1958 $this->mOptions
= User
::getDefaultOptions();
1961 if ( array_key_exists( $oname, $this->mOptions
) ) {
1962 return $this->mOptions
[$oname];
1964 return $defaultOverride;
1969 * Get all user's options
1973 public function getOptions() {
1974 $this->loadOptions();
1975 return $this->mOptions
;
1979 * Get the user's current setting for a given option, as a boolean value.
1981 * @param $oname String The option to check
1982 * @return Bool User's current value for the option
1985 function getBoolOption( $oname ) {
1986 return (bool)$this->getOption( $oname );
1991 * Get the user's current setting for a given option, as a boolean value.
1993 * @param $oname String The option to check
1994 * @param $defaultOverride Int A default value returned if the option does not exist
1995 * @return Int User's current value for the option
1998 function getIntOption( $oname, $defaultOverride=0 ) {
1999 $val = $this->getOption( $oname );
2001 $val = $defaultOverride;
2003 return intval( $val );
2007 * Set the given option for a user.
2009 * @param $oname String The option to set
2010 * @param $val mixed New value to set
2012 function setOption( $oname, $val ) {
2014 $this->loadOptions();
2016 if ( $oname == 'skin' ) {
2017 # Clear cached skin, so the new one displays immediately in Special:Preferences
2018 $this->mSkin
= null;
2021 // Explicitly NULL values should refer to defaults
2022 global $wgDefaultUserOptions;
2023 if( is_null( $val ) && isset( $wgDefaultUserOptions[$oname] ) ) {
2024 $val = $wgDefaultUserOptions[$oname];
2027 $this->mOptions
[$oname] = $val;
2031 * Reset all options to the site defaults
2033 function resetOptions() {
2034 $this->mOptions
= self
::getDefaultOptions();
2038 * Get the user's preferred date format.
2039 * @return String User's preferred date format
2041 function getDatePreference() {
2042 // Important migration for old data rows
2043 if ( is_null( $this->mDatePreference
) ) {
2045 $value = $this->getOption( 'date' );
2046 $map = $wgLang->getDatePreferenceMigrationMap();
2047 if ( isset( $map[$value] ) ) {
2048 $value = $map[$value];
2050 $this->mDatePreference
= $value;
2052 return $this->mDatePreference
;
2056 * Get the user preferred stub threshold
2058 function getStubThreshold() {
2059 global $wgMaxArticleSize; # Maximum article size, in Kb
2060 $threshold = intval( $this->getOption( 'stubthreshold' ) );
2061 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2062 # If they have set an impossible value, disable the preference
2063 # so we can use the parser cache again.
2070 * Get the permissions this user has.
2071 * @return Array of String permission names
2073 function getRights() {
2074 if ( is_null( $this->mRights
) ) {
2075 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2076 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2077 // Force reindexation of rights when a hook has unset one of them
2078 $this->mRights
= array_values( $this->mRights
);
2080 return $this->mRights
;
2084 * Get the list of explicit group memberships this user has.
2085 * The implicit * and user groups are not included.
2086 * @return Array of String internal group names
2088 function getGroups() {
2090 return $this->mGroups
;
2094 * Get the list of implicit group memberships this user has.
2095 * This includes all explicit groups, plus 'user' if logged in,
2096 * '*' for all accounts, and autopromoted groups
2097 * @param $recache Bool Whether to avoid the cache
2098 * @return Array of String internal group names
2100 function getEffectiveGroups( $recache = false ) {
2101 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2102 wfProfileIn( __METHOD__
);
2103 $this->mEffectiveGroups
= $this->getGroups();
2104 $this->mEffectiveGroups
[] = '*';
2105 if( $this->getId() ) {
2106 $this->mEffectiveGroups
[] = 'user';
2108 $this->mEffectiveGroups
= array_unique( array_merge(
2109 $this->mEffectiveGroups
,
2110 Autopromote
::getAutopromoteGroups( $this )
2113 # Hook for additional groups
2114 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2116 wfProfileOut( __METHOD__
);
2118 return $this->mEffectiveGroups
;
2122 * Get the user's edit count.
2125 function getEditCount() {
2126 if( $this->getId() ) {
2127 if ( !isset( $this->mEditCount
) ) {
2128 /* Populate the count, if it has not been populated yet */
2129 $this->mEditCount
= User
::edits( $this->mId
);
2131 return $this->mEditCount
;
2139 * Add the user to the given group.
2140 * This takes immediate effect.
2141 * @param $group String Name of the group to add
2143 function addGroup( $group ) {
2144 $dbw = wfGetDB( DB_MASTER
);
2145 if( $this->getId() ) {
2146 $dbw->insert( 'user_groups',
2148 'ug_user' => $this->getID(),
2149 'ug_group' => $group,
2152 array( 'IGNORE' ) );
2155 $this->loadGroups();
2156 $this->mGroups
[] = $group;
2157 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2159 $this->invalidateCache();
2163 * Remove the user from the given group.
2164 * This takes immediate effect.
2165 * @param $group String Name of the group to remove
2167 function removeGroup( $group ) {
2169 $dbw = wfGetDB( DB_MASTER
);
2170 $dbw->delete( 'user_groups',
2172 'ug_user' => $this->getID(),
2173 'ug_group' => $group,
2176 $this->loadGroups();
2177 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2178 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2180 $this->invalidateCache();
2184 * Get whether the user is logged in
2187 function isLoggedIn() {
2188 return $this->getID() != 0;
2192 * Get whether the user is anonymous
2196 return !$this->isLoggedIn();
2201 * Check if user is allowed to access a feature / make an action
2202 * @param $action String action to be checked
2203 * @return Boolean: True if action is allowed, else false
2205 function isAllowed( $action = '' ) {
2206 if ( $action === '' ) {
2207 return true; // In the spirit of DWIM
2209 # Patrolling may not be enabled
2210 if( $action === 'patrol' ||
$action === 'autopatrol' ) {
2211 global $wgUseRCPatrol, $wgUseNPPatrol;
2212 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2215 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2216 # by misconfiguration: 0 == 'foo'
2217 return in_array( $action, $this->getRights(), true );
2221 * Check whether to enable recent changes patrol features for this user
2222 * @return Boolean: True or false
2224 public function useRCPatrol() {
2225 global $wgUseRCPatrol;
2226 return( $wgUseRCPatrol && ( $this->isAllowed( 'patrol' ) ||
$this->isAllowed( 'patrolmarks' ) ) );
2230 * Check whether to enable new pages patrol features for this user
2231 * @return Bool True or false
2233 public function useNPPatrol() {
2234 global $wgUseRCPatrol, $wgUseNPPatrol;
2235 return( ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && ( $this->isAllowed( 'patrol' ) ||
$this->isAllowed( 'patrolmarks' ) ) );
2239 * Get the current skin, loading it if required, and setting a title
2240 * @param $t Title: the title to use in the skin
2241 * @return Skin The current skin
2242 * @todo: FIXME : need to check the old failback system [AV]
2244 function getSkin( $t = null ) {
2245 if( !$this->mSkin
) {
2247 $this->mSkin
= $this->createSkinObject();
2248 $this->mSkin
->setTitle( $wgOut->getTitle() );
2250 if ( $t && ( !$this->mSkin
->getTitle() ||
!$t->equals( $this->mSkin
->getTitle() ) ) ) {
2251 $skin = $this->createSkinObject();
2252 $skin->setTitle( $t );
2255 return $this->mSkin
;
2259 // Creates a Skin object, for getSkin()
2260 private function createSkinObject() {
2261 wfProfileIn( __METHOD__
);
2263 global $wgHiddenPrefs;
2264 if( !in_array( 'skin', $wgHiddenPrefs ) ) {
2267 $userSkin = $this->getOption( 'skin' );
2268 $userSkin = $wgRequest->getVal( 'useskin', $userSkin );
2270 # if we're not allowing users to override, then use the default
2271 global $wgDefaultSkin;
2272 $userSkin = $wgDefaultSkin;
2275 $skin = Skin
::newFromKey( $userSkin );
2276 wfProfileOut( __METHOD__
);
2282 * Check the watched status of an article.
2283 * @param $title Title of the article to look at
2286 function isWatched( $title ) {
2287 $wl = WatchedItem
::fromUserTitle( $this, $title );
2288 return $wl->isWatched();
2293 * @param $title Title of the article to look at
2295 function addWatch( $title ) {
2296 $wl = WatchedItem
::fromUserTitle( $this, $title );
2298 $this->invalidateCache();
2302 * Stop watching an article.
2303 * @param $title Title of the article to look at
2305 function removeWatch( $title ) {
2306 $wl = WatchedItem
::fromUserTitle( $this, $title );
2308 $this->invalidateCache();
2312 * Clear the user's notification timestamp for the given title.
2313 * If e-notif e-mails are on, they will receive notification mails on
2314 * the next change of the page if it's watched etc.
2315 * @param $title Title of the article to look at
2317 function clearNotification( &$title ) {
2318 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2320 # Do nothing if the database is locked to writes
2321 if( wfReadOnly() ) {
2325 if( $title->getNamespace() == NS_USER_TALK
&&
2326 $title->getText() == $this->getName() ) {
2327 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2329 $this->setNewtalk( false );
2332 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2336 if( $this->isAnon() ) {
2337 // Nothing else to do...
2341 // Only update the timestamp if the page is being watched.
2342 // The query to find out if it is watched is cached both in memcached and per-invocation,
2343 // and when it does have to be executed, it can be on a slave
2344 // If this is the user's newtalk page, we always update the timestamp
2345 if( $title->getNamespace() == NS_USER_TALK
&&
2346 $title->getText() == $wgUser->getName() )
2349 } elseif ( $this->getId() == $wgUser->getId() ) {
2350 $watched = $title->userIsWatching();
2355 // If the page is watched by the user (or may be watched), update the timestamp on any
2356 // any matching rows
2358 $dbw = wfGetDB( DB_MASTER
);
2359 $dbw->update( 'watchlist',
2361 'wl_notificationtimestamp' => null
2362 ), array( /* WHERE */
2363 'wl_title' => $title->getDBkey(),
2364 'wl_namespace' => $title->getNamespace(),
2365 'wl_user' => $this->getID()
2372 * Resets all of the given user's page-change notification timestamps.
2373 * If e-notif e-mails are on, they will receive notification mails on
2374 * the next change of any watched page.
2376 * @param $currentUser Int User ID
2378 function clearAllNotifications( $currentUser ) {
2379 global $wgUseEnotif, $wgShowUpdatedMarker;
2380 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2381 $this->setNewtalk( false );
2384 if( $currentUser != 0 ) {
2385 $dbw = wfGetDB( DB_MASTER
);
2386 $dbw->update( 'watchlist',
2388 'wl_notificationtimestamp' => null
2389 ), array( /* WHERE */
2390 'wl_user' => $currentUser
2393 # We also need to clear here the "you have new message" notification for the own user_talk page
2394 # This is cleared one page view later in Article::viewUpdates();
2399 * Set this user's options from an encoded string
2400 * @param $str String Encoded options to import
2403 function decodeOptions( $str ) {
2407 $this->mOptionsLoaded
= true;
2408 $this->mOptionOverrides
= array();
2410 // If an option is not set in $str, use the default value
2411 $this->mOptions
= self
::getDefaultOptions();
2413 $a = explode( "\n", $str );
2414 foreach ( $a as $s ) {
2416 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2417 $this->mOptions
[$m[1]] = $m[2];
2418 $this->mOptionOverrides
[$m[1]] = $m[2];
2424 * Set a cookie on the user's client. Wrapper for
2425 * WebResponse::setCookie
2426 * @param $name String Name of the cookie to set
2427 * @param $value String Value to set
2428 * @param $exp Int Expiration time, as a UNIX time value;
2429 * if 0 or not specified, use the default $wgCookieExpiration
2431 protected function setCookie( $name, $value, $exp = 0 ) {
2433 $wgRequest->response()->setcookie( $name, $value, $exp );
2437 * Clear a cookie on the user's client
2438 * @param $name String Name of the cookie to clear
2440 protected function clearCookie( $name ) {
2441 $this->setCookie( $name, '', time() - 86400 );
2445 * Set the default cookies for this session on the user's client.
2447 function setCookies() {
2449 if ( 0 == $this->mId
) return;
2451 'wsUserID' => $this->mId
,
2452 'wsToken' => $this->mToken
,
2453 'wsUserName' => $this->getName()
2456 'UserID' => $this->mId
,
2457 'UserName' => $this->getName(),
2459 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2460 $cookies['Token'] = $this->mToken
;
2462 $cookies['Token'] = false;
2465 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2466 #check for null, since the hook could cause a null value
2467 if ( !is_null( $session ) && isset( $_SESSION ) ){
2468 $_SESSION = $session +
$_SESSION;
2470 foreach ( $cookies as $name => $value ) {
2471 if ( $value === false ) {
2472 $this->clearCookie( $name );
2474 $this->setCookie( $name, $value );
2480 * Log this user out.
2483 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
2489 * Clear the user's cookies and session, and reset the instance cache.
2493 function doLogout() {
2494 $this->clearInstanceCache( 'defaults' );
2496 $_SESSION['wsUserID'] = 0;
2498 $this->clearCookie( 'UserID' );
2499 $this->clearCookie( 'Token' );
2501 # Remember when user logged out, to prevent seeing cached pages
2502 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2506 * Save this user's settings into the database.
2507 * @todo Only rarely do all these fields need to be set!
2509 function saveSettings() {
2511 if ( wfReadOnly() ) { return; }
2512 if ( 0 == $this->mId
) { return; }
2514 $this->mTouched
= self
::newTouchedTimestamp();
2516 $dbw = wfGetDB( DB_MASTER
);
2517 $dbw->update( 'user',
2519 'user_name' => $this->mName
,
2520 'user_password' => $this->mPassword
,
2521 'user_newpassword' => $this->mNewpassword
,
2522 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2523 'user_real_name' => $this->mRealName
,
2524 'user_email' => $this->mEmail
,
2525 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2526 'user_options' => '',
2527 'user_touched' => $dbw->timestamp( $this->mTouched
),
2528 'user_token' => $this->mToken
,
2529 'user_email_token' => $this->mEmailToken
,
2530 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2531 ), array( /* WHERE */
2532 'user_id' => $this->mId
2536 $this->saveOptions();
2538 wfRunHooks( 'UserSaveSettings', array( $this ) );
2539 $this->clearSharedCache();
2540 $this->getUserPage()->invalidateCache();
2544 * If only this user's username is known, and it exists, return the user ID.
2547 function idForName() {
2548 $s = trim( $this->getName() );
2549 if ( $s === '' ) return 0;
2551 $dbr = wfGetDB( DB_SLAVE
);
2552 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2553 if ( $id === false ) {
2560 * Add a user to the database, return the user object
2562 * @param $name String Username to add
2563 * @param $params Array of Strings Non-default parameters to save to the database:
2564 * - password The user's password. Password logins will be disabled if this is omitted.
2565 * - newpassword A temporary password mailed to the user
2566 * - email The user's email address
2567 * - email_authenticated The email authentication timestamp
2568 * - real_name The user's real name
2569 * - options An associative array of non-default options
2570 * - token Random authentication token. Do not set.
2571 * - registration Registration timestamp. Do not set.
2573 * @return User object, or null if the username already exists
2575 static function createNew( $name, $params = array() ) {
2578 if ( isset( $params['options'] ) ) {
2579 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
2580 unset( $params['options'] );
2582 $dbw = wfGetDB( DB_MASTER
);
2583 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2585 'user_id' => $seqVal,
2586 'user_name' => $name,
2587 'user_password' => $user->mPassword
,
2588 'user_newpassword' => $user->mNewpassword
,
2589 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
2590 'user_email' => $user->mEmail
,
2591 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2592 'user_real_name' => $user->mRealName
,
2593 'user_options' => '',
2594 'user_token' => $user->mToken
,
2595 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2596 'user_editcount' => 0,
2598 foreach ( $params as $name => $value ) {
2599 $fields["user_$name"] = $value;
2601 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2602 if ( $dbw->affectedRows() ) {
2603 $newUser = User
::newFromId( $dbw->insertId() );
2611 * Add this existing user object to the database
2613 function addToDatabase() {
2615 $dbw = wfGetDB( DB_MASTER
);
2616 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2617 $dbw->insert( 'user',
2619 'user_id' => $seqVal,
2620 'user_name' => $this->mName
,
2621 'user_password' => $this->mPassword
,
2622 'user_newpassword' => $this->mNewpassword
,
2623 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2624 'user_email' => $this->mEmail
,
2625 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2626 'user_real_name' => $this->mRealName
,
2627 'user_options' => '',
2628 'user_token' => $this->mToken
,
2629 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2630 'user_editcount' => 0,
2633 $this->mId
= $dbw->insertId();
2635 // Clear instance cache other than user table data, which is already accurate
2636 $this->clearInstanceCache();
2638 $this->saveOptions();
2642 * If this (non-anonymous) user is blocked, block any IP address
2643 * they've successfully logged in from.
2645 function spreadBlock() {
2646 wfDebug( __METHOD__
. "()\n" );
2648 if ( $this->mId
== 0 ) {
2652 $userblock = Block
::newFromDB( '', $this->mId
);
2653 if ( !$userblock ) {
2657 $userblock->doAutoblock( wfGetIP() );
2661 * Generate a string which will be different for any combination of
2662 * user options which would produce different parser output.
2663 * This will be used as part of the hash key for the parser cache,
2664 * so users with the same options can share the same cached data
2667 * Extensions which require it should install 'PageRenderingHash' hook,
2668 * which will give them a chance to modify this key based on their own
2671 * @deprecated @since 1.17 use the ParserOptions object to get the relevant options
2672 * @return String Page rendering hash
2674 function getPageRenderingHash() {
2675 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2677 return $this->mHash
;
2679 wfDeprecated( __METHOD__
);
2681 // stubthreshold is only included below for completeness,
2682 // since it disables the parser cache, its value will always
2683 // be 0 when this function is called by parsercache.
2685 $confstr = $this->getOption( 'math' );
2686 $confstr .= '!' . $this->getStubThreshold();
2687 if ( $wgUseDynamicDates ) { # This is wrong (bug 24714)
2688 $confstr .= '!' . $this->getDatePreference();
2690 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ?
'1' : '' );
2691 $confstr .= '!' . $wgLang->getCode();
2692 $confstr .= '!' . $this->getOption( 'thumbsize' );
2693 // add in language specific options, if any
2694 $extra = $wgContLang->getExtraHashOptions();
2697 // Since the skin could be overloading link(), it should be
2698 // included here but in practice, none of our skins do that.
2700 $confstr .= $wgRenderHashAppend;
2702 // Give a chance for extensions to modify the hash, if they have
2703 // extra options or other effects on the parser cache.
2704 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2706 // Make it a valid memcached key fragment
2707 $confstr = str_replace( ' ', '_', $confstr );
2708 $this->mHash
= $confstr;
2713 * Get whether the user is explicitly blocked from account creation.
2716 function isBlockedFromCreateAccount() {
2717 $this->getBlockedStatus();
2718 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2722 * Get whether the user is blocked from using Special:Emailuser.
2725 function isBlockedFromEmailuser() {
2726 $this->getBlockedStatus();
2727 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2731 * Get whether the user is allowed to create an account.
2734 function isAllowedToCreateAccount() {
2735 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2739 * Get this user's personal page title.
2741 * @return Title: User's personal page title
2743 function getUserPage() {
2744 return Title
::makeTitle( NS_USER
, $this->getName() );
2748 * Get this user's talk page title.
2750 * @return Title: User's talk page title
2752 function getTalkPage() {
2753 $title = $this->getUserPage();
2754 return $title->getTalkPage();
2758 * Get the maximum valid user ID.
2759 * @return Integer: User ID
2762 function getMaxID() {
2763 static $res; // cache
2765 if ( isset( $res ) ) {
2768 $dbr = wfGetDB( DB_SLAVE
);
2769 return $res = $dbr->selectField( 'user', 'max(user_id)', false, __METHOD__
);
2774 * Determine whether the user is a newbie. Newbies are either
2775 * anonymous IPs, or the most recently created accounts.
2778 function isNewbie() {
2779 return !$this->isAllowed( 'autoconfirmed' );
2783 * Check to see if the given clear-text password is one of the accepted passwords
2784 * @param $password String: user password.
2785 * @return Boolean: True if the given password is correct, otherwise False.
2787 function checkPassword( $password ) {
2791 // Even though we stop people from creating passwords that
2792 // are shorter than this, doesn't mean people wont be able
2793 // to. Certain authentication plugins do NOT want to save
2794 // domain passwords in a mysql database, so we should
2795 // check this (incase $wgAuth->strict() is false).
2796 if( !$this->isValidPassword( $password ) ) {
2800 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2802 } elseif( $wgAuth->strict() ) {
2803 /* Auth plugin doesn't allow local authentication */
2805 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2806 /* Auth plugin doesn't allow local authentication for this user name */
2809 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
2811 } elseif ( function_exists( 'iconv' ) ) {
2812 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2813 # Check for this with iconv
2814 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2815 if ( self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) ) {
2823 * Check if the given clear-text password matches the temporary password
2824 * sent by e-mail for password reset operations.
2825 * @return Boolean: True if matches, false otherwise
2827 function checkTemporaryPassword( $plaintext ) {
2828 global $wgNewPasswordExpiry;
2829 if( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
2830 if ( is_null( $this->mNewpassTime
) ) {
2833 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
2834 return ( time() < $expiry );
2841 * Initialize (if necessary) and return a session token value
2842 * which can be used in edit forms to show that the user's
2843 * login credentials aren't being hijacked with a foreign form
2846 * @param $salt String|Array of Strings Optional function-specific data for hashing
2847 * @return String The new edit token
2849 function editToken( $salt = '' ) {
2850 if ( $this->isAnon() ) {
2851 return EDIT_TOKEN_SUFFIX
;
2853 if( !isset( $_SESSION['wsEditToken'] ) ) {
2854 $token = $this->generateToken();
2855 $_SESSION['wsEditToken'] = $token;
2857 $token = $_SESSION['wsEditToken'];
2859 if( is_array( $salt ) ) {
2860 $salt = implode( '|', $salt );
2862 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2867 * Generate a looking random token for various uses.
2869 * @param $salt String Optional salt value
2870 * @return String The new random token
2872 function generateToken( $salt = '' ) {
2873 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2874 return md5( $token . $salt );
2878 * Check given value against the token value stored in the session.
2879 * A match should confirm that the form was submitted from the
2880 * user's own login session, not a form submission from a third-party
2883 * @param $val String Input value to compare
2884 * @param $salt String Optional function-specific data for hashing
2885 * @return Boolean: Whether the token matches
2887 function matchEditToken( $val, $salt = '' ) {
2888 $sessionToken = $this->editToken( $salt );
2889 if ( $val != $sessionToken ) {
2890 wfDebug( "User::matchEditToken: broken session data\n" );
2892 return $val == $sessionToken;
2896 * Check given value against the token value stored in the session,
2897 * ignoring the suffix.
2899 * @param $val String Input value to compare
2900 * @param $salt String Optional function-specific data for hashing
2901 * @return Boolean: Whether the token matches
2903 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2904 $sessionToken = $this->editToken( $salt );
2905 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2909 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2910 * mail to the user's given address.
2912 * @param $type String: message to send, either "created", "changed" or "set"
2913 * @return Status object
2915 function sendConfirmationMail( $type = 'created' ) {
2917 $expiration = null; // gets passed-by-ref and defined in next line.
2918 $token = $this->confirmationToken( $expiration );
2919 $url = $this->confirmationTokenUrl( $token );
2920 $invalidateURL = $this->invalidationTokenUrl( $token );
2921 $this->saveSettings();
2923 if ( $type == 'created' ||
$type === false ) {
2924 $message = 'confirmemail_body';
2925 } elseif ( $type === true ) {
2926 $message = 'confirmemail_body_changed';
2928 $message = 'confirmemail_body_' . $type;
2931 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2936 $wgLang->timeanddate( $expiration, false ),
2938 $wgLang->date( $expiration, false ),
2939 $wgLang->time( $expiration, false ) ) );
2943 * Send an e-mail to this user's account. Does not check for
2944 * confirmed status or validity.
2946 * @param $subject String Message subject
2947 * @param $body String Message body
2948 * @param $from String Optional From address; if unspecified, default $wgPasswordSender will be used
2949 * @param $replyto String Reply-To address
2952 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2953 if( is_null( $from ) ) {
2954 global $wgPasswordSender, $wgPasswordSenderName;
2955 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
2957 $sender = new MailAddress( $from );
2960 $to = new MailAddress( $this );
2961 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2965 * Generate, store, and return a new e-mail confirmation code.
2966 * A hash (unsalted, since it's used as a key) is stored.
2968 * @note Call saveSettings() after calling this function to commit
2969 * this change to the database.
2971 * @param[out] &$expiration \mixed Accepts the expiration time
2972 * @return String New token
2975 function confirmationToken( &$expiration ) {
2976 global $wgUserEmailConfirmationTokenExpiry;
2978 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
2979 $expiration = wfTimestamp( TS_MW
, $expires );
2980 $token = wfGenerateToken( $this->mId
. $this->mEmail
. $expires );
2981 $hash = md5( $token );
2983 $this->mEmailToken
= $hash;
2984 $this->mEmailTokenExpires
= $expiration;
2989 * Return a URL the user can use to confirm their email address.
2990 * @param $token String Accepts the email confirmation token
2991 * @return String New token URL
2994 function confirmationTokenUrl( $token ) {
2995 return $this->getTokenUrl( 'ConfirmEmail', $token );
2999 * Return a URL the user can use to invalidate their email address.
3000 * @param $token String Accepts the email confirmation token
3001 * @return String New token URL
3004 function invalidationTokenUrl( $token ) {
3005 return $this->getTokenUrl( 'Invalidateemail', $token );
3009 * Internal function to format the e-mail validation/invalidation URLs.
3010 * This uses $wgArticlePath directly as a quickie hack to use the
3011 * hardcoded English names of the Special: pages, for ASCII safety.
3013 * @note Since these URLs get dropped directly into emails, using the
3014 * short English names avoids insanely long URL-encoded links, which
3015 * also sometimes can get corrupted in some browsers/mailers
3016 * (bug 6957 with Gmail and Internet Explorer).
3018 * @param $page String Special page
3019 * @param $token String Token
3020 * @return String Formatted URL
3022 protected function getTokenUrl( $page, $token ) {
3023 global $wgArticlePath;
3027 "Special:$page/$token",
3032 * Mark the e-mail address confirmed.
3034 * @note Call saveSettings() after calling this function to commit the change.
3036 function confirmEmail() {
3037 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3038 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3043 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3044 * address if it was already confirmed.
3046 * @note Call saveSettings() after calling this function to commit the change.
3048 function invalidateEmail() {
3050 $this->mEmailToken
= null;
3051 $this->mEmailTokenExpires
= null;
3052 $this->setEmailAuthenticationTimestamp( null );
3053 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3058 * Set the e-mail authentication timestamp.
3059 * @param $timestamp String TS_MW timestamp
3061 function setEmailAuthenticationTimestamp( $timestamp ) {
3063 $this->mEmailAuthenticated
= $timestamp;
3064 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
3068 * Is this user allowed to send e-mails within limits of current
3069 * site configuration?
3072 function canSendEmail() {
3073 global $wgEnableEmail, $wgEnableUserEmail;
3074 if( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
3077 $canSend = $this->isEmailConfirmed();
3078 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3083 * Is this user allowed to receive e-mails within limits of current
3084 * site configuration?
3087 function canReceiveEmail() {
3088 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3092 * Is this user's e-mail address valid-looking and confirmed within
3093 * limits of the current site configuration?
3095 * @note If $wgEmailAuthentication is on, this may require the user to have
3096 * confirmed their address by returning a code or using a password
3097 * sent to the address from the wiki.
3101 function isEmailConfirmed() {
3102 global $wgEmailAuthentication;
3105 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3106 if( $this->isAnon() )
3108 if( !self
::isValidEmailAddr( $this->mEmail
) )
3110 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
3119 * Check whether there is an outstanding request for e-mail confirmation.
3122 function isEmailConfirmationPending() {
3123 global $wgEmailAuthentication;
3124 return $wgEmailAuthentication &&
3125 !$this->isEmailConfirmed() &&
3126 $this->mEmailToken
&&
3127 $this->mEmailTokenExpires
> wfTimestamp();
3131 * Get the timestamp of account creation.
3133 * @return String|Bool Timestamp of account creation, or false for
3134 * non-existent/anonymous user accounts.
3136 public function getRegistration() {
3137 return $this->getId() > 0
3138 ?
$this->mRegistration
3143 * Get the timestamp of the first edit
3145 * @return String|Bool Timestamp of first edit, or false for
3146 * non-existent/anonymous user accounts.
3148 public function getFirstEditTimestamp() {
3149 if( $this->getId() == 0 ) {
3150 return false; // anons
3152 $dbr = wfGetDB( DB_SLAVE
);
3153 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3154 array( 'rev_user' => $this->getId() ),
3156 array( 'ORDER BY' => 'rev_timestamp ASC' )
3159 return false; // no edits
3161 return wfTimestamp( TS_MW
, $time );
3165 * Get the permissions associated with a given list of groups
3167 * @param $groups Array of Strings List of internal group names
3168 * @return Array of Strings List of permission key names for given groups combined
3170 static function getGroupPermissions( $groups ) {
3171 global $wgGroupPermissions, $wgRevokePermissions;
3173 // grant every granted permission first
3174 foreach( $groups as $group ) {
3175 if( isset( $wgGroupPermissions[$group] ) ) {
3176 $rights = array_merge( $rights,
3177 // array_filter removes empty items
3178 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3181 // now revoke the revoked permissions
3182 foreach( $groups as $group ) {
3183 if( isset( $wgRevokePermissions[$group] ) ) {
3184 $rights = array_diff( $rights,
3185 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3188 return array_unique( $rights );
3192 * Get all the groups who have a given permission
3194 * @param $role String Role to check
3195 * @return Array of Strings List of internal group names with the given permission
3197 static function getGroupsWithPermission( $role ) {
3198 global $wgGroupPermissions;
3199 $allowedGroups = array();
3200 foreach ( $wgGroupPermissions as $group => $rights ) {
3201 if ( isset( $rights[$role] ) && $rights[$role] ) {
3202 $allowedGroups[] = $group;
3205 return $allowedGroups;
3209 * Get the localized descriptive name for a group, if it exists
3211 * @param $group String Internal group name
3212 * @return String Localized descriptive group name
3214 static function getGroupName( $group ) {
3215 $msg = wfMessage( "group-$group" );
3216 return $msg->isBlank() ?
$group : $msg->text();
3220 * Get the localized descriptive name for a member of a group, if it exists
3222 * @param $group String Internal group name
3223 * @return String Localized name for group member
3225 static function getGroupMember( $group ) {
3226 $msg = wfMessage( "group-$group-member" );
3227 return $msg->isBlank() ?
$group : $msg->text();
3231 * Return the set of defined explicit groups.
3232 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3233 * are not included, as they are defined automatically, not in the database.
3234 * @return Array of internal group names
3236 static function getAllGroups() {
3237 global $wgGroupPermissions, $wgRevokePermissions;
3239 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3240 self
::getImplicitGroups()
3245 * Get a list of all available permissions.
3246 * @return Array of permission names
3248 static function getAllRights() {
3249 if ( self
::$mAllRights === false ) {
3250 global $wgAvailableRights;
3251 if ( count( $wgAvailableRights ) ) {
3252 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3254 self
::$mAllRights = self
::$mCoreRights;
3256 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3258 return self
::$mAllRights;
3262 * Get a list of implicit groups
3263 * @return Array of Strings Array of internal group names
3265 public static function getImplicitGroups() {
3266 global $wgImplicitGroups;
3267 $groups = $wgImplicitGroups;
3268 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3273 * Get the title of a page describing a particular group
3275 * @param $group String Internal group name
3276 * @return Title|Bool Title of the page if it exists, false otherwise
3278 static function getGroupPage( $group ) {
3279 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
3280 if( $msg->exists() ) {
3281 $title = Title
::newFromText( $msg->text() );
3282 if( is_object( $title ) )
3289 * Create a link to the group in HTML, if available;
3290 * else return the group name.
3292 * @param $group String Internal name of the group
3293 * @param $text String The text of the link
3294 * @return String HTML link to the group
3296 static function makeGroupLinkHTML( $group, $text = '' ) {
3298 $text = self
::getGroupName( $group );
3300 $title = self
::getGroupPage( $group );
3303 $sk = $wgUser->getSkin();
3304 return $sk->link( $title, htmlspecialchars( $text ) );
3311 * Create a link to the group in Wikitext, if available;
3312 * else return the group name.
3314 * @param $group String Internal name of the group
3315 * @param $text String The text of the link
3316 * @return String Wikilink to the group
3318 static function makeGroupLinkWiki( $group, $text = '' ) {
3320 $text = self
::getGroupName( $group );
3322 $title = self
::getGroupPage( $group );
3324 $page = $title->getPrefixedText();
3325 return "[[$page|$text]]";
3332 * Returns an array of the groups that a particular group can add/remove.
3334 * @param $group String: the group to check for whether it can add/remove
3335 * @return Array array( 'add' => array( addablegroups ),
3336 * 'remove' => array( removablegroups ),
3337 * 'add-self' => array( addablegroups to self),
3338 * 'remove-self' => array( removable groups from self) )
3340 static function changeableByGroup( $group ) {
3341 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
3343 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
3344 if( empty( $wgAddGroups[$group] ) ) {
3345 // Don't add anything to $groups
3346 } elseif( $wgAddGroups[$group] === true ) {
3347 // You get everything
3348 $groups['add'] = self
::getAllGroups();
3349 } elseif( is_array( $wgAddGroups[$group] ) ) {
3350 $groups['add'] = $wgAddGroups[$group];
3353 // Same thing for remove
3354 if( empty( $wgRemoveGroups[$group] ) ) {
3355 } elseif( $wgRemoveGroups[$group] === true ) {
3356 $groups['remove'] = self
::getAllGroups();
3357 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
3358 $groups['remove'] = $wgRemoveGroups[$group];
3361 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
3362 if( empty( $wgGroupsAddToSelf['user']) ||
$wgGroupsAddToSelf['user'] !== true ) {
3363 foreach( $wgGroupsAddToSelf as $key => $value ) {
3364 if( is_int( $key ) ) {
3365 $wgGroupsAddToSelf['user'][] = $value;
3370 if( empty( $wgGroupsRemoveFromSelf['user']) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
3371 foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
3372 if( is_int( $key ) ) {
3373 $wgGroupsRemoveFromSelf['user'][] = $value;
3378 // Now figure out what groups the user can add to him/herself
3379 if( empty( $wgGroupsAddToSelf[$group] ) ) {
3380 } elseif( $wgGroupsAddToSelf[$group] === true ) {
3381 // No idea WHY this would be used, but it's there
3382 $groups['add-self'] = User
::getAllGroups();
3383 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
3384 $groups['add-self'] = $wgGroupsAddToSelf[$group];
3387 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
3388 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
3389 $groups['remove-self'] = User
::getAllGroups();
3390 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
3391 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
3398 * Returns an array of groups that this user can add and remove
3399 * @return Array array( 'add' => array( addablegroups ),
3400 * 'remove' => array( removablegroups ),
3401 * 'add-self' => array( addablegroups to self),
3402 * 'remove-self' => array( removable groups from self) )
3404 function changeableGroups() {
3405 if( $this->isAllowed( 'userrights' ) ) {
3406 // This group gives the right to modify everything (reverse-
3407 // compatibility with old "userrights lets you change
3409 // Using array_merge to make the groups reindexed
3410 $all = array_merge( User
::getAllGroups() );
3414 'add-self' => array(),
3415 'remove-self' => array()
3419 // Okay, it's not so simple, we will have to go through the arrays
3422 'remove' => array(),
3423 'add-self' => array(),
3424 'remove-self' => array()
3426 $addergroups = $this->getEffectiveGroups();
3428 foreach( $addergroups as $addergroup ) {
3429 $groups = array_merge_recursive(
3430 $groups, $this->changeableByGroup( $addergroup )
3432 $groups['add'] = array_unique( $groups['add'] );
3433 $groups['remove'] = array_unique( $groups['remove'] );
3434 $groups['add-self'] = array_unique( $groups['add-self'] );
3435 $groups['remove-self'] = array_unique( $groups['remove-self'] );
3441 * Increment the user's edit-count field.
3442 * Will have no effect for anonymous users.
3444 function incEditCount() {
3445 if( !$this->isAnon() ) {
3446 $dbw = wfGetDB( DB_MASTER
);
3447 $dbw->update( 'user',
3448 array( 'user_editcount=user_editcount+1' ),
3449 array( 'user_id' => $this->getId() ),
3452 // Lazy initialization check...
3453 if( $dbw->affectedRows() == 0 ) {
3454 // Pull from a slave to be less cruel to servers
3455 // Accuracy isn't the point anyway here
3456 $dbr = wfGetDB( DB_SLAVE
);
3457 $count = $dbr->selectField( 'revision',
3459 array( 'rev_user' => $this->getId() ),
3462 // Now here's a goddamn hack...
3463 if( $dbr !== $dbw ) {
3464 // If we actually have a slave server, the count is
3465 // at least one behind because the current transaction
3466 // has not been committed and replicated.
3469 // But if DB_SLAVE is selecting the master, then the
3470 // count we just read includes the revision that was
3471 // just added in the working transaction.
3474 $dbw->update( 'user',
3475 array( 'user_editcount' => $count ),
3476 array( 'user_id' => $this->getId() ),
3480 // edit count in user cache too
3481 $this->invalidateCache();
3485 * Get the description of a given right
3487 * @param $right String Right to query
3488 * @return String Localized description of the right
3490 static function getRightDescription( $right ) {
3491 $key = "right-$right";
3492 $name = wfMsg( $key );
3493 return $name == '' ||
wfEmptyMsg( $key, $name )
3499 * Make an old-style password hash
3501 * @param $password String Plain-text password
3502 * @param $userId String User ID
3503 * @return String Password hash
3505 static function oldCrypt( $password, $userId ) {
3506 global $wgPasswordSalt;
3507 if ( $wgPasswordSalt ) {
3508 return md5( $userId . '-' . md5( $password ) );
3510 return md5( $password );
3515 * Make a new-style password hash
3517 * @param $password String Plain-text password
3518 * @param $salt String Optional salt, may be random or the user ID.
3519 * If unspecified or false, will generate one automatically
3520 * @return String Password hash
3522 static function crypt( $password, $salt = false ) {
3523 global $wgPasswordSalt;
3526 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3530 if( $wgPasswordSalt ) {
3531 if ( $salt === false ) {
3532 $salt = substr( wfGenerateToken(), 0, 8 );
3534 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3536 return ':A:' . md5( $password );
3541 * Compare a password hash with a plain-text password. Requires the user
3542 * ID if there's a chance that the hash is an old-style hash.
3544 * @param $hash String Password hash
3545 * @param $password String Plain-text password to compare
3546 * @param $userId String User ID for old-style password salt
3549 static function comparePasswords( $hash, $password, $userId = false ) {
3550 $type = substr( $hash, 0, 3 );
3553 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3557 if ( $type == ':A:' ) {
3559 return md5( $password ) === substr( $hash, 3 );
3560 } elseif ( $type == ':B:' ) {
3562 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3563 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3566 return self
::oldCrypt( $password, $userId ) === $hash;
3571 * Add a newuser log entry for this user
3573 * @param $byEmail Boolean: account made by email?
3574 * @param $reason String: user supplied reason
3576 public function addNewUserLogEntry( $creator, $byEmail = false ) {
3577 global $wgUser, $wgNewUserLog;
3578 if( empty( $wgNewUserLog ) ) {
3579 return true; // disabled
3582 $action = ( $creator == $wgUser )
3583 ?
'create2' # Safe to publish the creator
3584 : 'create'; # Creator is an IP, don't splash it all over Special:Log
3587 ?
wfMsgForContent( 'newuserlog-byemail' )
3590 $log = new LogPage( 'newusers' );
3593 $this->getUserPage(),
3595 array( $this->getId() ),
3602 * Add an autocreate newuser log entry for this user
3603 * Used by things like CentralAuth and perhaps other authplugins.
3605 public function addNewUserLogEntryAutoCreate() {
3606 global $wgNewUserLog;
3607 if( empty( $wgNewUserLog ) ) {
3608 return true; // disabled
3610 $log = new LogPage( 'newusers', false );
3613 $this->getUserPage(),
3615 array( $this->getId() ),
3621 protected function loadOptions() {
3623 if ( $this->mOptionsLoaded ||
!$this->getId() )
3626 $this->mOptions
= self
::getDefaultOptions();
3628 // Maybe load from the object
3629 if ( !is_null( $this->mOptionOverrides
) ) {
3630 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
3631 foreach( $this->mOptionOverrides
as $key => $value ) {
3632 $this->mOptions
[$key] = $value;
3635 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
3636 // Load from database
3637 $dbr = wfGetDB( DB_SLAVE
);
3639 $res = $dbr->select(
3642 array( 'up_user' => $this->getId() ),
3646 foreach ( $res as $row ) {
3647 $this->mOptionOverrides
[$row->up_property
] = $row->up_value
;
3648 $this->mOptions
[$row->up_property
] = $row->up_value
;
3652 $this->mOptionsLoaded
= true;
3654 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
3657 protected function saveOptions() {
3658 global $wgAllowPrefChange;
3660 $extuser = ExternalUser
::newFromUser( $this );
3662 $this->loadOptions();
3663 $dbw = wfGetDB( DB_MASTER
);
3665 $insert_rows = array();
3667 $saveOptions = $this->mOptions
;
3669 // Allow hooks to abort, for instance to save to a global profile.
3670 // Reset options to default state before saving.
3671 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) )
3674 foreach( $saveOptions as $key => $value ) {
3675 # Don't bother storing default values
3676 if ( ( is_null( self
::getDefaultOption( $key ) ) &&
3677 !( $value === false ||
is_null($value) ) ) ||
3678 $value != self
::getDefaultOption( $key ) ) {
3679 $insert_rows[] = array(
3680 'up_user' => $this->getId(),
3681 'up_property' => $key,
3682 'up_value' => $value,
3685 if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
3686 switch ( $wgAllowPrefChange[$key] ) {
3692 $extuser->setPref( $key, $value );
3698 $dbw->delete( 'user_properties', array( 'up_user' => $this->getId() ), __METHOD__
);
3699 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
);
3704 * Provide an array of HTML5 attributes to put on an input element
3705 * intended for the user to enter a new password. This may include
3706 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
3708 * Do *not* use this when asking the user to enter his current password!
3709 * Regardless of configuration, users may have invalid passwords for whatever
3710 * reason (e.g., they were set before requirements were tightened up).
3711 * Only use it when asking for a new password, like on account creation or
3714 * Obviously, you still need to do server-side checking.
3716 * NOTE: A combination of bugs in various browsers means that this function
3717 * actually just returns array() unconditionally at the moment. May as
3718 * well keep it around for when the browser bugs get fixed, though.
3720 * FIXME : This does not belong here; put it in Html or Linker or somewhere
3722 * @return array Array of HTML attributes suitable for feeding to
3723 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
3724 * That will potentially output invalid XHTML 1.0 Transitional, and will
3725 * get confused by the boolean attribute syntax used.)
3727 public static function passwordChangeInputAttribs() {
3728 global $wgMinimalPasswordLength;
3730 if ( $wgMinimalPasswordLength == 0 ) {
3734 # Note that the pattern requirement will always be satisfied if the
3735 # input is empty, so we need required in all cases.
3737 # FIXME (bug 23769): This needs to not claim the password is required
3738 # if e-mail confirmation is being used. Since HTML5 input validation
3739 # is b0rked anyway in some browsers, just return nothing. When it's
3740 # re-enabled, fix this code to not output required for e-mail
3742 #$ret = array( 'required' );
3745 # We can't actually do this right now, because Opera 9.6 will print out
3746 # the entered password visibly in its error message! When other
3747 # browsers add support for this attribute, or Opera fixes its support,
3748 # we can add support with a version check to avoid doing this on Opera
3749 # versions where it will be a problem. Reported to Opera as
3750 # DSK-262266, but they don't have a public bug tracker for us to follow.
3752 if ( $wgMinimalPasswordLength > 1 ) {
3753 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
3754 $ret['title'] = wfMsgExt( 'passwordtooshort', 'parsemag',
3755 $wgMinimalPasswordLength );