3 * Implements the User class for the %MediaWiki software.
8 * Int Number of characters in user_token field.
11 define( 'USER_TOKEN_LENGTH', 32 );
14 * Int Serialized record version.
17 define( 'MW_USER_VERSION', 8 );
20 * String Some punctuation to prevent editing from broken text-mangling proxies.
23 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
26 * Thrown by User::setPassword() on error.
29 class PasswordError
extends MWException
{
34 * The User object encapsulates all of the user-specific settings (user_id,
35 * name, rights, password, email address, options, last login time). Client
36 * classes use the getXXX() functions to access these fields. These functions
37 * do all the work of determining whether the user is logged in,
38 * whether the requested option can be satisfied from cookies or
39 * whether a database query is needed. Most of the settings needed
40 * for rendering normal pages are set in the cookie to minimize use
45 * Global constants made accessible as class constants so that autoloader
48 const USER_TOKEN_LENGTH
= USER_TOKEN_LENGTH
;
49 const MW_USER_VERSION
= MW_USER_VERSION
;
50 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
53 * Array of Strings List of member variables which are saved to the
54 * shared cache (memcached). Any operation which changes the
55 * corresponding database fields must call a cache-clearing function.
58 static $mCacheVars = array(
69 'mEmailAuthenticated',
76 // user_properties table
81 * Array of Strings Core rights.
82 * Each of these should have a corresponding message of the form
86 static $mCoreRights = array(
105 'editusercssjs', #deprecated
117 'move-rootuserpages',
121 'override-export-depth',
142 'userrights-interwiki',
146 * String Cached results of getAllRights()
148 static $mAllRights = false;
150 /** @name Cache variables */
152 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
153 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
154 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups, $mOptionOverrides;
158 * Bool Whether the cache variables have been loaded.
160 var $mDataLoaded, $mAuthLoaded, $mOptionsLoaded;
163 * String Initialization data source if mDataLoaded==false. May be one of:
164 * - 'defaults' anonymous user initialised from class defaults
165 * - 'name' initialise from mName
166 * - 'id' initialise from mId
167 * - 'session' log in from cookies or session if possible
169 * Use the User::newFrom*() family of functions to set this.
174 * Lazy-initialized variables, invalidated with clearInstanceCache
176 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mRights,
177 $mBlockreason, $mEffectiveGroups, $mBlockedGlobally,
178 $mLocked, $mHideName, $mOptions;
190 static $idCacheByName = array();
193 * Lightweight constructor for an anonymous user.
194 * Use the User::newFrom* factory functions for other kinds of users.
198 * @see newFromConfirmationCode()
199 * @see newFromSession()
202 function __construct() {
203 $this->clearInstanceCache( 'defaults' );
206 function __toString(){
207 return $this->getName();
211 * Load the user table data for this object from the source given by mFrom.
214 if ( $this->mDataLoaded
) {
217 wfProfileIn( __METHOD__
);
219 # Set it now to avoid infinite recursion in accessors
220 $this->mDataLoaded
= true;
222 switch ( $this->mFrom
) {
224 $this->loadDefaults();
227 $this->mId
= self
::idFromName( $this->mName
);
229 # Nonexistent user placeholder object
230 $this->loadDefaults( $this->mName
);
239 $this->loadFromSession();
240 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
243 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
245 wfProfileOut( __METHOD__
);
249 * Load user table data, given mId has already been set.
250 * @return Bool false if the ID does not exist, true otherwise
253 function loadFromId() {
255 if ( $this->mId
== 0 ) {
256 $this->loadDefaults();
261 $key = wfMemcKey( 'user', 'id', $this->mId
);
262 $data = $wgMemc->get( $key );
263 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
264 # Object is expired, load from DB
269 wfDebug( "User: cache miss for user {$this->mId}\n" );
271 if ( !$this->loadFromDatabase() ) {
272 # Can't load from ID, user is anonymous
275 $this->saveToCache();
277 wfDebug( "User: got user {$this->mId} from cache\n" );
279 foreach ( self
::$mCacheVars as $name ) {
280 $this->$name = $data[$name];
287 * Save user data to the shared cache
289 function saveToCache() {
292 $this->loadOptions();
293 if ( $this->isAnon() ) {
294 // Anonymous users are uncached
298 foreach ( self
::$mCacheVars as $name ) {
299 $data[$name] = $this->$name;
301 $data['mVersion'] = MW_USER_VERSION
;
302 $key = wfMemcKey( 'user', 'id', $this->mId
);
304 $wgMemc->set( $key, $data );
308 /** @name newFrom*() static factory methods */
312 * Static factory method for creation from username.
314 * This is slightly less efficient than newFromId(), so use newFromId() if
315 * you have both an ID and a name handy.
317 * @param $name String Username, validated by Title::newFromText()
318 * @param $validate String|Bool Validate username. Takes the same parameters as
319 * User::getCanonicalName(), except that true is accepted as an alias
320 * for 'valid', for BC.
322 * @return User object, or false if the username is invalid
323 * (e.g. if it contains illegal characters or is an IP address). If the
324 * username is not present in the database, the result will be a user object
325 * with a name, zero user ID and default settings.
327 static function newFromName( $name, $validate = 'valid' ) {
328 if ( $validate === true ) {
331 $name = self
::getCanonicalName( $name, $validate );
332 if ( $name === false ) {
335 # Create unloaded user object
344 * Static factory method for creation from a given user ID.
346 * @param $id Int Valid user ID
347 * @return User The corresponding User object
349 static function newFromId( $id ) {
357 * Factory method to fetch whichever user has a given email confirmation code.
358 * This code is generated when an account is created or its e-mail address
361 * If the code is invalid or has expired, returns NULL.
363 * @param $code String Confirmation code
366 static function newFromConfirmationCode( $code ) {
367 $dbr = wfGetDB( DB_SLAVE
);
368 $id = $dbr->selectField( 'user', 'user_id', array(
369 'user_email_token' => md5( $code ),
370 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
372 if( $id !== false ) {
373 return User
::newFromId( $id );
380 * Create a new user object using data from session or cookies. If the
381 * login credentials are invalid, the result is an anonymous user.
385 static function newFromSession() {
387 $user->mFrom
= 'session';
392 * Create a new user object from a user row.
393 * The row should have all fields from the user table in it.
394 * @param $row Array A row from the user table
397 static function newFromRow( $row ) {
399 $user->loadFromRow( $row );
407 * Get the username corresponding to a given user ID
408 * @param $id Int User ID
409 * @return String The corresponding username
411 static function whoIs( $id ) {
412 $dbr = wfGetDB( DB_SLAVE
);
413 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), __METHOD__
);
417 * Get the real name of a user given their user ID
419 * @param $id Int User ID
420 * @return String The corresponding user's real name
422 static function whoIsReal( $id ) {
423 $dbr = wfGetDB( DB_SLAVE
);
424 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
428 * Get database id given a user name
429 * @param $name String Username
430 * @return Int|Null The corresponding user's ID, or null if user is nonexistent
432 static function idFromName( $name ) {
433 $nt = Title
::makeTitleSafe( NS_USER
, $name );
434 if( is_null( $nt ) ) {
439 if ( isset( self
::$idCacheByName[$name] ) ) {
440 return self
::$idCacheByName[$name];
443 $dbr = wfGetDB( DB_SLAVE
);
444 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
446 if ( $s === false ) {
449 $result = $s->user_id
;
452 self
::$idCacheByName[$name] = $result;
454 if ( count( self
::$idCacheByName ) > 1000 ) {
455 self
::$idCacheByName = array();
462 * Reset the cache used in idFromName(). For use in tests.
464 public static function resetIdByNameCache() {
465 self
::$idCacheByName = array();
469 * Does the string match an anonymous IPv4 address?
471 * This function exists for username validation, in order to reject
472 * usernames which are similar in form to IP addresses. Strings such
473 * as 300.300.300.300 will return true because it looks like an IP
474 * address, despite not being strictly valid.
476 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
477 * address because the usemod software would "cloak" anonymous IP
478 * addresses like this, if we allowed accounts like this to be created
479 * new users could get the old edits of these anonymous users.
481 * @param $name String to match
484 static function isIP( $name ) {
485 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP
::isIPv6($name);
489 * Is the input a valid username?
491 * Checks if the input is a valid username, we don't want an empty string,
492 * an IP address, anything that containins slashes (would mess up subpages),
493 * is longer than the maximum allowed username size or doesn't begin with
496 * @param $name String to match
499 static function isValidUserName( $name ) {
500 global $wgContLang, $wgMaxNameChars;
503 || User
::isIP( $name )
504 ||
strpos( $name, '/' ) !== false
505 ||
strlen( $name ) > $wgMaxNameChars
506 ||
$name != $wgContLang->ucfirst( $name ) ) {
507 wfDebugLog( 'username', __METHOD__
.
508 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
512 // Ensure that the name can't be misresolved as a different title,
513 // such as with extra namespace keys at the start.
514 $parsed = Title
::newFromText( $name );
515 if( is_null( $parsed )
516 ||
$parsed->getNamespace()
517 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
518 wfDebugLog( 'username', __METHOD__
.
519 ": '$name' invalid due to ambiguous prefixes" );
523 // Check an additional blacklist of troublemaker characters.
524 // Should these be merged into the title char list?
525 $unicodeBlacklist = '/[' .
526 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
527 '\x{00a0}' . # non-breaking space
528 '\x{2000}-\x{200f}' . # various whitespace
529 '\x{2028}-\x{202f}' . # breaks and control chars
530 '\x{3000}' . # ideographic space
531 '\x{e000}-\x{f8ff}' . # private use
533 if( preg_match( $unicodeBlacklist, $name ) ) {
534 wfDebugLog( 'username', __METHOD__
.
535 ": '$name' invalid due to blacklisted characters" );
543 * Usernames which fail to pass this function will be blocked
544 * from user login and new account registrations, but may be used
545 * internally by batch processes.
547 * If an account already exists in this form, login will be blocked
548 * by a failure to pass this function.
550 * @param $name String to match
553 static function isUsableName( $name ) {
554 global $wgReservedUsernames;
555 // Must be a valid username, obviously ;)
556 if ( !self
::isValidUserName( $name ) ) {
560 static $reservedUsernames = false;
561 if ( !$reservedUsernames ) {
562 $reservedUsernames = $wgReservedUsernames;
563 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
566 // Certain names may be reserved for batch processes.
567 foreach ( $reservedUsernames as $reserved ) {
568 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
569 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
571 if ( $reserved == $name ) {
579 * Usernames which fail to pass this function will be blocked
580 * from new account registrations, but may be used internally
581 * either by batch processes or by user accounts which have
582 * already been created.
584 * Additional blacklisting may be added here rather than in
585 * isValidUserName() to avoid disrupting existing accounts.
587 * @param $name String to match
590 static function isCreatableName( $name ) {
591 global $wgInvalidUsernameCharacters;
593 // Ensure that the username isn't longer than 235 bytes, so that
594 // (at least for the builtin skins) user javascript and css files
595 // will work. (bug 23080)
596 if( strlen( $name ) > 235 ) {
597 wfDebugLog( 'username', __METHOD__
.
598 ": '$name' invalid due to length" );
602 // Preg yells if you try to give it an empty string
603 if( $wgInvalidUsernameCharacters !== '' ) {
604 if( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
605 wfDebugLog( 'username', __METHOD__
.
606 ": '$name' invalid due to wgInvalidUsernameCharacters" );
611 return self
::isUsableName( $name );
615 * Is the input a valid password for this user?
617 * @param $password String Desired password
620 function isValidPassword( $password ) {
621 //simple boolean wrapper for getPasswordValidity
622 return $this->getPasswordValidity( $password ) === true;
626 * Given unvalidated password input, return error message on failure.
628 * @param $password String Desired password
629 * @return mixed: true on success, string or array of error message on failure
631 function getPasswordValidity( $password ) {
632 global $wgMinimalPasswordLength, $wgContLang;
634 static $blockedLogins = array(
635 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
636 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
639 $result = false; //init $result to false for the internal checks
641 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
644 if ( $result === false ) {
645 if( strlen( $password ) < $wgMinimalPasswordLength ) {
646 return 'passwordtooshort';
647 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
648 return 'password-name-match';
649 } elseif ( isset( $blockedLogins[ $this->getName() ] ) && $password == $blockedLogins[ $this->getName() ] ) {
650 return 'password-login-forbidden';
652 //it seems weird returning true here, but this is because of the
653 //initialization of $result to false above. If the hook is never run or it
654 //doesn't modify $result, then we will likely get down into this if with
658 } elseif( $result === true ) {
661 return $result; //the isValidPassword hook set a string $result and returned true
666 * Does a string look like an e-mail address?
668 * This validates an email address using an HTML5 specification found at:
669 * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
670 * Which as of 2011-01-24 says:
672 * A valid e-mail address is a string that matches the ABNF production
673 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
674 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
677 * This function is an implementation of the specification as requested in
680 * Client-side forms will use the same standard validation rules via JS or
681 * HTML 5 validation; additional restrictions can be enforced server-side
682 * by extensions via the 'isValidEmailAddr' hook.
684 * Note that this validation doesn't 100% match RFC 2822, but is believed
685 * to be liberal enough for wide use. Some invalid addresses will still
686 * pass validation here.
688 * @param $addr String E-mail address
691 public static function isValidEmailAddr( $addr ) {
693 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
697 // Please note strings below are enclosed in brackets [], this make the
698 // hyphen "-" a range indicator. Hence it is double backslashed below.
700 $rfc5322_atext = "a-z0-9!#$%&'*+\\-\/=?^_`{|}~" ;
701 $rfc1034_ldh_str = "a-z0-9\\-" ;
703 $HTML5_email_regexp = "/
705 [$rfc5322_atext\\.]+ # user part which is liberal :p
707 [$rfc1034_ldh_str]+ # First domain part
708 (\\.[$rfc1034_ldh_str]+)* # Following part prefixed with a dot
710 /ix" ; // case Insensitive, eXtended
712 return (bool) preg_match( $HTML5_email_regexp, $addr );
716 * Given unvalidated user input, return a canonical username, or false if
717 * the username is invalid.
718 * @param $name String User input
719 * @param $validate String|Bool type of validation to use:
720 * - false No validation
721 * - 'valid' Valid for batch processes
722 * - 'usable' Valid for batch processes and login
723 * - 'creatable' Valid for batch processes, login and account creation
725 static function getCanonicalName( $name, $validate = 'valid' ) {
726 # Force usernames to capital
728 $name = $wgContLang->ucfirst( $name );
730 # Reject names containing '#'; these will be cleaned up
731 # with title normalisation, but then it's too late to
733 if( strpos( $name, '#' ) !== false )
736 # Clean up name according to title rules
737 $t = ( $validate === 'valid' ) ?
738 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
739 # Check for invalid titles
740 if( is_null( $t ) ) {
744 # Reject various classes of invalid names
746 $name = $wgAuth->getCanonicalName( $t->getText() );
748 switch ( $validate ) {
752 if ( !User
::isValidUserName( $name ) ) {
757 if ( !User
::isUsableName( $name ) ) {
762 if ( !User
::isCreatableName( $name ) ) {
767 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
773 * Count the number of edits of a user
774 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
776 * @param $uid Int User ID to check
777 * @return Int the user's edit count
779 static function edits( $uid ) {
780 wfProfileIn( __METHOD__
);
781 $dbr = wfGetDB( DB_SLAVE
);
782 // check if the user_editcount field has been initialized
783 $field = $dbr->selectField(
784 'user', 'user_editcount',
785 array( 'user_id' => $uid ),
789 if( $field === null ) { // it has not been initialized. do so.
790 $dbw = wfGetDB( DB_MASTER
);
791 $count = $dbr->selectField(
792 'revision', 'count(*)',
793 array( 'rev_user' => $uid ),
798 array( 'user_editcount' => $count ),
799 array( 'user_id' => $uid ),
805 wfProfileOut( __METHOD__
);
810 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
811 * @todo hash random numbers to improve security, like generateToken()
813 * @return String new random password
815 static function randomPassword() {
816 global $wgMinimalPasswordLength;
817 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
818 $l = strlen( $pwchars ) - 1;
820 $pwlength = max( 7, $wgMinimalPasswordLength );
821 $digit = mt_rand( 0, $pwlength - 1 );
823 for ( $i = 0; $i < $pwlength; $i++
) {
824 $np .= $i == $digit ?
chr( mt_rand( 48, 57 ) ) : $pwchars{ mt_rand( 0, $l ) };
830 * Set cached properties to default.
832 * @note This no longer clears uncached lazy-initialised properties;
833 * the constructor does that instead.
836 function loadDefaults( $name = false ) {
837 wfProfileIn( __METHOD__
);
842 $this->mName
= $name;
843 $this->mRealName
= '';
844 $this->mPassword
= $this->mNewpassword
= '';
845 $this->mNewpassTime
= null;
847 $this->mOptionOverrides
= null;
848 $this->mOptionsLoaded
= false;
850 if( $wgRequest->getCookie( 'LoggedOut' ) !== null ) {
851 $this->mTouched
= wfTimestamp( TS_MW
, $wgRequest->getCookie( 'LoggedOut' ) );
853 $this->mTouched
= '0'; # Allow any pages to be cached
856 $this->setToken(); # Random
857 $this->mEmailAuthenticated
= null;
858 $this->mEmailToken
= '';
859 $this->mEmailTokenExpires
= null;
860 $this->mRegistration
= wfTimestamp( TS_MW
);
861 $this->mGroups
= array();
863 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
865 wfProfileOut( __METHOD__
);
869 * Load user data from the session or login cookie. If there are no valid
870 * credentials, initialises the user as an anonymous user.
871 * @return Bool True if the user is logged in, false otherwise.
873 private function loadFromSession() {
874 global $wgRequest, $wgExternalAuthType, $wgAutocreatePolicy;
877 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
878 if ( $result !== null ) {
882 if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
883 $extUser = ExternalUser
::newFromCookie();
885 # TODO: Automatically create the user here (or probably a bit
886 # lower down, in fact)
890 $cookieId = $wgRequest->getCookie( 'UserID' );
891 $sessId = $wgRequest->getSessionData( 'wsUserID' );
893 if ( $cookieId !== null ) {
894 $sId = intval( $cookieId );
895 if( $sessId !== null && $cookieId != $sessId ) {
896 $this->loadDefaults(); // Possible collision!
897 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
898 cookie user ID ($sId) don't match!" );
901 $wgRequest->setSessionData( 'wsUserID', $sId );
902 } else if ( $sessId !== null && $sessId != 0 ) {
905 $this->loadDefaults();
909 if ( $wgRequest->getSessionData( 'wsUserName' ) !== null ) {
910 $sName = $wgRequest->getSessionData( 'wsUserName' );
911 } else if ( $wgRequest->getCookie( 'UserName' ) !== null ) {
912 $sName = $wgRequest->getCookie( 'UserName' );
913 $wgRequest->setSessionData( 'wsUserName', $sName );
915 $this->loadDefaults();
920 if ( !$this->loadFromId() ) {
921 # Not a valid ID, loadFromId has switched the object to anon for us
925 global $wgBlockDisablesLogin;
926 if( $wgBlockDisablesLogin && $this->isBlocked() ) {
927 # User blocked and we've disabled blocked user logins
928 $this->loadDefaults();
932 if ( $wgRequest->getSessionData( 'wsToken' ) !== null ) {
933 $passwordCorrect = $this->mToken
== $wgRequest->getSessionData( 'wsToken' );
935 } else if ( $wgRequest->getCookie( 'Token' ) !== null ) {
936 $passwordCorrect = $this->mToken
== $wgRequest->getCookie( 'Token' );
939 # No session or persistent login cookie
940 $this->loadDefaults();
944 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
945 $wgRequest->setSessionData( 'wsToken', $this->mToken
);
946 wfDebug( "User: logged in from $from\n" );
949 # Invalid credentials
950 wfDebug( "User: can't log in from $from, invalid credentials\n" );
951 $this->loadDefaults();
957 * Load user and user_group data from the database.
958 * $this::mId must be set, this is how the user is identified.
960 * @return Bool True if the user exists, false if the user is anonymous
963 function loadFromDatabase() {
965 $this->mId
= intval( $this->mId
);
967 /** Anonymous user */
969 $this->loadDefaults();
973 $dbr = wfGetDB( DB_MASTER
);
974 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
976 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
978 if ( $s !== false ) {
979 # Initialise user table data
980 $this->loadFromRow( $s );
981 $this->mGroups
= null; // deferred
982 $this->getEditCount(); // revalidation for nulls
987 $this->loadDefaults();
993 * Initialize this object from a row from the user table.
995 * @param $row Array Row from the user table to load.
997 function loadFromRow( $row ) {
998 $this->mDataLoaded
= true;
1000 if ( isset( $row->user_id
) ) {
1001 $this->mId
= intval( $row->user_id
);
1003 $this->mName
= $row->user_name
;
1004 $this->mRealName
= $row->user_real_name
;
1005 $this->mPassword
= $row->user_password
;
1006 $this->mNewpassword
= $row->user_newpassword
;
1007 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1008 $this->mEmail
= $row->user_email
;
1009 $this->decodeOptions( $row->user_options
);
1010 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
1011 $this->mToken
= $row->user_token
;
1012 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1013 $this->mEmailToken
= $row->user_email_token
;
1014 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1015 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1016 $this->mEditCount
= $row->user_editcount
;
1020 * Load the groups from the database if they aren't already loaded.
1023 function loadGroups() {
1024 if ( is_null( $this->mGroups
) ) {
1025 $dbr = wfGetDB( DB_MASTER
);
1026 $res = $dbr->select( 'user_groups',
1027 array( 'ug_group' ),
1028 array( 'ug_user' => $this->mId
),
1030 $this->mGroups
= array();
1031 foreach ( $res as $row ) {
1032 $this->mGroups
[] = $row->ug_group
;
1038 * Clear various cached data stored in this object.
1039 * @param $reloadFrom String Reload user and user_groups table data from a
1040 * given source. May be "name", "id", "defaults", "session", or false for
1043 function clearInstanceCache( $reloadFrom = false ) {
1044 $this->mNewtalk
= -1;
1045 $this->mDatePreference
= null;
1046 $this->mBlockedby
= -1; # Unset
1047 $this->mHash
= false;
1048 $this->mSkin
= null;
1049 $this->mRights
= null;
1050 $this->mEffectiveGroups
= null;
1051 $this->mOptions
= null;
1053 if ( $reloadFrom ) {
1054 $this->mDataLoaded
= false;
1055 $this->mFrom
= $reloadFrom;
1060 * Combine the language default options with any site-specific options
1061 * and add the default language variants.
1063 * @return Array of String options
1065 static function getDefaultOptions() {
1066 global $wgNamespacesToBeSearchedDefault;
1068 * Site defaults will override the global/language defaults
1070 global $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1071 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
1074 * default language setting
1076 $variant = $wgContLang->getDefaultVariant();
1077 $defOpt['variant'] = $variant;
1078 $defOpt['language'] = $variant;
1079 foreach( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1080 $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1082 $defOpt['skin'] = $wgDefaultSkin;
1088 * Get a given default option value.
1090 * @param $opt String Name of option to retrieve
1091 * @return String Default option value
1093 public static function getDefaultOption( $opt ) {
1094 $defOpts = self
::getDefaultOptions();
1095 if( isset( $defOpts[$opt] ) ) {
1096 return $defOpts[$opt];
1104 * Get blocking information
1106 * @param $bFromSlave Bool Whether to check the slave database first. To
1107 * improve performance, non-critical checks are done
1108 * against slaves. Check when actually saving should be
1109 * done against master.
1111 function getBlockedStatus( $bFromSlave = true ) {
1112 global $wgProxyWhitelist, $wgUser;
1114 if ( -1 != $this->mBlockedby
) {
1118 wfProfileIn( __METHOD__
);
1119 wfDebug( __METHOD__
.": checking...\n" );
1121 // Initialize data...
1122 // Otherwise something ends up stomping on $this->mBlockedby when
1123 // things get lazy-loaded later, causing false positive block hits
1124 // due to -1 !== 0. Probably session-related... Nothing should be
1125 // overwriting mBlockedby, surely?
1128 $this->mBlockedby
= 0;
1129 $this->mHideName
= 0;
1130 $this->mAllowUsertalk
= 0;
1132 # We only need to worry about passing the IP address to the Block generator if the
1133 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1134 # know which IP address they're actually coming from
1135 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1142 $this->mBlock
= Block
::newFromTarget( $this->getName(), $ip, !$bFromSlave );
1143 if ( $this->mBlock
instanceof Block
) {
1144 wfDebug( __METHOD__
. ": Found block.\n" );
1145 $this->mBlockedby
= $this->mBlock
->getBlocker()->getName();
1146 $this->mBlockreason
= $this->mBlock
->mReason
;
1147 $this->mHideName
= $this->mBlock
->mHideName
;
1148 $this->mAllowUsertalk
= !$this->mBlock
->prevents( 'editownusertalk' );
1149 if ( $this->isLoggedIn() && $wgUser->getID() == $this->getID() ) {
1150 $this->spreadBlock();
1155 if ( !$this->isAllowed( 'proxyunbannable' ) && !in_array( $ip, $wgProxyWhitelist ) ) {
1157 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1158 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1159 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1163 if ( !$this->mBlockedby
&& !$this->getID() ) {
1164 if ( $this->isDnsBlacklisted( $ip ) ) {
1165 $this->mBlockedby
= wfMsg( 'sorbs' );
1166 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1172 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1174 wfProfileOut( __METHOD__
);
1178 * Whether the given IP is in a DNS blacklist.
1180 * @param $ip String IP to check
1181 * @param $checkWhitelist Bool: whether to check the whitelist first
1182 * @return Bool True if blacklisted.
1184 function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1185 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1186 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1188 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
1191 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
1194 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1195 return $this->inDnsBlacklist( $ip, $urls );
1199 * Whether the given IP is in a given DNS blacklist.
1201 * @param $ip String IP to check
1202 * @param $bases String|Array of Strings: URL of the DNS blacklist
1203 * @return Bool True if blacklisted.
1205 function inDnsBlacklist( $ip, $bases ) {
1206 wfProfileIn( __METHOD__
);
1209 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1210 if( IP
::isIPv4( $ip ) ) {
1211 # Reverse IP, bug 21255
1212 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1214 foreach( (array)$bases as $base ) {
1216 $host = "$ipReversed.$base";
1219 $ipList = gethostbynamel( $host );
1222 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1226 wfDebug( "Requested $host, not found in $base.\n" );
1231 wfProfileOut( __METHOD__
);
1236 * Is this user subject to rate limiting?
1238 * @return Bool True if rate limited
1240 public function isPingLimitable() {
1241 global $wgRateLimitsExcludedGroups;
1242 global $wgRateLimitsExcludedIPs;
1243 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1244 // Deprecated, but kept for backwards-compatibility config
1247 if( in_array( wfGetIP(), $wgRateLimitsExcludedIPs ) ) {
1248 // No other good way currently to disable rate limits
1249 // for specific IPs. :P
1250 // But this is a crappy hack and should die.
1253 return !$this->isAllowed('noratelimit');
1257 * Primitive rate limits: enforce maximum actions per time period
1258 * to put a brake on flooding.
1260 * @note When using a shared cache like memcached, IP-address
1261 * last-hit counters will be shared across wikis.
1263 * @param $action String Action to enforce; 'edit' if unspecified
1264 * @return Bool True if a rate limiter was tripped
1266 function pingLimiter( $action = 'edit' ) {
1267 # Call the 'PingLimiter' hook
1269 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1273 global $wgRateLimits;
1274 if( !isset( $wgRateLimits[$action] ) ) {
1278 # Some groups shouldn't trigger the ping limiter, ever
1279 if( !$this->isPingLimitable() )
1282 global $wgMemc, $wgRateLimitLog;
1283 wfProfileIn( __METHOD__
);
1285 $limits = $wgRateLimits[$action];
1287 $id = $this->getId();
1291 if( isset( $limits['anon'] ) && $id == 0 ) {
1292 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1295 if( isset( $limits['user'] ) && $id != 0 ) {
1296 $userLimit = $limits['user'];
1298 if( $this->isNewbie() ) {
1299 if( isset( $limits['newbie'] ) && $id != 0 ) {
1300 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1302 if( isset( $limits['ip'] ) ) {
1303 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1306 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1307 $subnet = $matches[1];
1308 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1311 // Check for group-specific permissions
1312 // If more than one group applies, use the group with the highest limit
1313 foreach ( $this->getGroups() as $group ) {
1314 if ( isset( $limits[$group] ) ) {
1315 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1316 $userLimit = $limits[$group];
1320 // Set the user limit key
1321 if ( $userLimit !== false ) {
1322 wfDebug( __METHOD__
. ": effective user limit: $userLimit\n" );
1323 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1327 foreach( $keys as $key => $limit ) {
1328 list( $max, $period ) = $limit;
1329 $summary = "(limit $max in {$period}s)";
1330 $count = $wgMemc->get( $key );
1333 if( $count > $max ) {
1334 wfDebug( __METHOD__
. ": tripped! $key at $count $summary\n" );
1335 if( $wgRateLimitLog ) {
1336 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1340 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1343 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1344 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1346 $wgMemc->incr( $key );
1349 wfProfileOut( __METHOD__
);
1354 * Check if user is blocked
1356 * @param $bFromSlave Bool Whether to check the slave database instead of the master
1357 * @return Bool True if blocked, false otherwise
1359 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1360 $this->getBlockedStatus( $bFromSlave );
1361 return $this->mBlock
instanceof Block
&& $this->mBlock
->prevents( 'edit' );
1365 * Check if user is blocked from editing a particular article
1367 * @param $title Title to check
1368 * @param $bFromSlave Bool whether to check the slave database instead of the master
1371 function isBlockedFrom( $title, $bFromSlave = false ) {
1372 global $wgBlockAllowsUTEdit;
1373 wfProfileIn( __METHOD__
);
1375 $blocked = $this->isBlocked( $bFromSlave );
1376 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1377 # If a user's name is suppressed, they cannot make edits anywhere
1378 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1379 $title->getNamespace() == NS_USER_TALK
) {
1381 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1384 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1386 wfProfileOut( __METHOD__
);
1391 * If user is blocked, return the name of the user who placed the block
1392 * @return String name of blocker
1394 function blockedBy() {
1395 $this->getBlockedStatus();
1396 return $this->mBlockedby
;
1400 * If user is blocked, return the specified reason for the block
1401 * @return String Blocking reason
1403 function blockedFor() {
1404 $this->getBlockedStatus();
1405 return $this->mBlockreason
;
1409 * If user is blocked, return the ID for the block
1410 * @return Int Block ID
1412 function getBlockId() {
1413 $this->getBlockedStatus();
1414 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1418 * Check if user is blocked on all wikis.
1419 * Do not use for actual edit permission checks!
1420 * This is intented for quick UI checks.
1422 * @param $ip String IP address, uses current client if none given
1423 * @return Bool True if blocked, false otherwise
1425 function isBlockedGlobally( $ip = '' ) {
1426 if( $this->mBlockedGlobally
!== null ) {
1427 return $this->mBlockedGlobally
;
1429 // User is already an IP?
1430 if( IP
::isIPAddress( $this->getName() ) ) {
1431 $ip = $this->getName();
1436 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1437 $this->mBlockedGlobally
= (bool)$blocked;
1438 return $this->mBlockedGlobally
;
1442 * Check if user account is locked
1444 * @return Bool True if locked, false otherwise
1446 function isLocked() {
1447 if( $this->mLocked
!== null ) {
1448 return $this->mLocked
;
1451 $authUser = $wgAuth->getUserInstance( $this );
1452 $this->mLocked
= (bool)$authUser->isLocked();
1453 return $this->mLocked
;
1457 * Check if user account is hidden
1459 * @return Bool True if hidden, false otherwise
1461 function isHidden() {
1462 if( $this->mHideName
!== null ) {
1463 return $this->mHideName
;
1465 $this->getBlockedStatus();
1466 if( !$this->mHideName
) {
1468 $authUser = $wgAuth->getUserInstance( $this );
1469 $this->mHideName
= (bool)$authUser->isHidden();
1471 return $this->mHideName
;
1475 * Get the user's ID.
1476 * @return Int The user's ID; 0 if the user is anonymous or nonexistent
1479 if( $this->mId
=== null && $this->mName
!== null
1480 && User
::isIP( $this->mName
) ) {
1481 // Special case, we know the user is anonymous
1483 } elseif( $this->mId
=== null ) {
1484 // Don't load if this was initialized from an ID
1491 * Set the user and reload all fields according to a given ID
1492 * @param $v Int User ID to reload
1494 function setId( $v ) {
1496 $this->clearInstanceCache( 'id' );
1500 * Get the user name, or the IP of an anonymous user
1501 * @return String User's name or IP address
1503 function getName() {
1504 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1505 # Special case optimisation
1506 return $this->mName
;
1509 if ( $this->mName
=== false ) {
1511 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1513 return $this->mName
;
1518 * Set the user name.
1520 * This does not reload fields from the database according to the given
1521 * name. Rather, it is used to create a temporary "nonexistent user" for
1522 * later addition to the database. It can also be used to set the IP
1523 * address for an anonymous user to something other than the current
1526 * @note User::newFromName() has rougly the same function, when the named user
1528 * @param $str String New user name to set
1530 function setName( $str ) {
1532 $this->mName
= $str;
1536 * Get the user's name escaped by underscores.
1537 * @return String Username escaped by underscores.
1539 function getTitleKey() {
1540 return str_replace( ' ', '_', $this->getName() );
1544 * Check if the user has new messages.
1545 * @return Bool True if the user has new messages
1547 function getNewtalk() {
1550 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1551 if( $this->mNewtalk
=== -1 ) {
1552 $this->mNewtalk
= false; # reset talk page status
1554 # Check memcached separately for anons, who have no
1555 # entire User object stored in there.
1558 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1559 $newtalk = $wgMemc->get( $key );
1560 if( strval( $newtalk ) !== '' ) {
1561 $this->mNewtalk
= (bool)$newtalk;
1563 // Since we are caching this, make sure it is up to date by getting it
1565 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1566 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1569 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1573 return (bool)$this->mNewtalk
;
1577 * Return the talk page(s) this user has new messages on.
1578 * @return Array of String page URLs
1580 function getNewMessageLinks() {
1582 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) )
1585 if( !$this->getNewtalk() )
1587 $up = $this->getUserPage();
1588 $utp = $up->getTalkPage();
1589 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL() ) );
1593 * Internal uncached check for new messages
1596 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1597 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1598 * @param $fromMaster Bool true to fetch from the master, false for a slave
1599 * @return Bool True if the user has new messages
1602 function checkNewtalk( $field, $id, $fromMaster = false ) {
1603 if ( $fromMaster ) {
1604 $db = wfGetDB( DB_MASTER
);
1606 $db = wfGetDB( DB_SLAVE
);
1608 $ok = $db->selectField( 'user_newtalk', $field,
1609 array( $field => $id ), __METHOD__
);
1610 return $ok !== false;
1614 * Add or update the new messages flag
1615 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1616 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1617 * @return Bool True if successful, false otherwise
1620 function updateNewtalk( $field, $id ) {
1621 $dbw = wfGetDB( DB_MASTER
);
1622 $dbw->insert( 'user_newtalk',
1623 array( $field => $id ),
1626 if ( $dbw->affectedRows() ) {
1627 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
1630 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
1636 * Clear the new messages flag for the given user
1637 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1638 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1639 * @return Bool True if successful, false otherwise
1642 function deleteNewtalk( $field, $id ) {
1643 $dbw = wfGetDB( DB_MASTER
);
1644 $dbw->delete( 'user_newtalk',
1645 array( $field => $id ),
1647 if ( $dbw->affectedRows() ) {
1648 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
1651 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
1657 * Update the 'You have new messages!' status.
1658 * @param $val Bool Whether the user has new messages
1660 function setNewtalk( $val ) {
1661 if( wfReadOnly() ) {
1666 $this->mNewtalk
= $val;
1668 if( $this->isAnon() ) {
1670 $id = $this->getName();
1673 $id = $this->getId();
1678 $changed = $this->updateNewtalk( $field, $id );
1680 $changed = $this->deleteNewtalk( $field, $id );
1683 if( $this->isAnon() ) {
1684 // Anons have a separate memcached space, since
1685 // user records aren't kept for them.
1686 $key = wfMemcKey( 'newtalk', 'ip', $id );
1687 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1690 $this->invalidateCache();
1695 * Generate a current or new-future timestamp to be stored in the
1696 * user_touched field when we update things.
1697 * @return String Timestamp in TS_MW format
1699 private static function newTouchedTimestamp() {
1700 global $wgClockSkewFudge;
1701 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1705 * Clear user data from memcached.
1706 * Use after applying fun updates to the database; caller's
1707 * responsibility to update user_touched if appropriate.
1709 * Called implicitly from invalidateCache() and saveSettings().
1711 private function clearSharedCache() {
1715 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1720 * Immediately touch the user data cache for this account.
1721 * Updates user_touched field, and removes account data from memcached
1722 * for reload on the next hit.
1724 function invalidateCache() {
1725 if( wfReadOnly() ) {
1730 $this->mTouched
= self
::newTouchedTimestamp();
1732 $dbw = wfGetDB( DB_MASTER
);
1733 $dbw->update( 'user',
1734 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1735 array( 'user_id' => $this->mId
),
1738 $this->clearSharedCache();
1743 * Validate the cache for this account.
1744 * @param $timestamp String A timestamp in TS_MW format
1746 function validateCache( $timestamp ) {
1748 return ( $timestamp >= $this->mTouched
);
1752 * Get the user touched timestamp
1753 * @return String timestamp
1755 function getTouched() {
1757 return $this->mTouched
;
1761 * Set the password and reset the random token.
1762 * Calls through to authentication plugin if necessary;
1763 * will have no effect if the auth plugin refuses to
1764 * pass the change through or if the legal password
1767 * As a special case, setting the password to null
1768 * wipes it, so the account cannot be logged in until
1769 * a new password is set, for instance via e-mail.
1771 * @param $str String New password to set
1772 * @throws PasswordError on failure
1774 function setPassword( $str ) {
1777 if( $str !== null ) {
1778 if( !$wgAuth->allowPasswordChange() ) {
1779 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1782 if( !$this->isValidPassword( $str ) ) {
1783 global $wgMinimalPasswordLength;
1784 $valid = $this->getPasswordValidity( $str );
1785 if ( is_array( $valid ) ) {
1786 $message = array_shift( $valid );
1790 $params = array( $wgMinimalPasswordLength );
1792 throw new PasswordError( wfMsgExt( $message, array( 'parsemag' ), $params ) );
1796 if( !$wgAuth->setPassword( $this, $str ) ) {
1797 throw new PasswordError( wfMsg( 'externaldberror' ) );
1800 $this->setInternalPassword( $str );
1806 * Set the password and reset the random token unconditionally.
1808 * @param $str String New password to set
1810 function setInternalPassword( $str ) {
1814 if( $str === null ) {
1815 // Save an invalid hash...
1816 $this->mPassword
= '';
1818 $this->mPassword
= self
::crypt( $str );
1820 $this->mNewpassword
= '';
1821 $this->mNewpassTime
= null;
1825 * Get the user's current token.
1826 * @return String Token
1828 function getToken() {
1830 return $this->mToken
;
1834 * Set the random token (used for persistent authentication)
1835 * Called from loadDefaults() among other places.
1837 * @param $token String If specified, set the token to this value
1840 function setToken( $token = false ) {
1841 global $wgSecretKey, $wgProxyKey;
1844 if ( $wgSecretKey ) {
1845 $key = $wgSecretKey;
1846 } elseif ( $wgProxyKey ) {
1851 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1853 $this->mToken
= $token;
1858 * Set the cookie password
1860 * @param $str String New cookie password
1863 function setCookiePassword( $str ) {
1865 $this->mCookiePassword
= md5( $str );
1869 * Set the password for a password reminder or new account email
1871 * @param $str String New password to set
1872 * @param $throttle Bool If true, reset the throttle timestamp to the present
1874 function setNewpassword( $str, $throttle = true ) {
1876 $this->mNewpassword
= self
::crypt( $str );
1878 $this->mNewpassTime
= wfTimestampNow();
1883 * Has password reminder email been sent within the last
1884 * $wgPasswordReminderResendTime hours?
1887 function isPasswordReminderThrottled() {
1888 global $wgPasswordReminderResendTime;
1890 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1893 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1894 return time() < $expiry;
1898 * Get the user's e-mail address
1899 * @return String User's email address
1901 function getEmail() {
1903 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1904 return $this->mEmail
;
1908 * Get the timestamp of the user's e-mail authentication
1909 * @return String TS_MW timestamp
1911 function getEmailAuthenticationTimestamp() {
1913 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1914 return $this->mEmailAuthenticated
;
1918 * Set the user's e-mail address
1919 * @param $str String New e-mail address
1921 function setEmail( $str ) {
1923 $this->mEmail
= $str;
1924 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1928 * Get the user's real name
1929 * @return String User's real name
1931 function getRealName() {
1933 return $this->mRealName
;
1937 * Set the user's real name
1938 * @param $str String New real name
1940 function setRealName( $str ) {
1942 $this->mRealName
= $str;
1946 * Get the user's current setting for a given option.
1948 * @param $oname String The option to check
1949 * @param $defaultOverride String A default value returned if the option does not exist
1950 * @param $ignoreHidden Bool = whether to ignore the effects of $wgHiddenPrefs
1951 * @return String User's current value for the option
1952 * @see getBoolOption()
1953 * @see getIntOption()
1955 function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
1956 global $wgHiddenPrefs;
1957 $this->loadOptions();
1959 if ( is_null( $this->mOptions
) ) {
1960 if($defaultOverride != '') {
1961 return $defaultOverride;
1963 $this->mOptions
= User
::getDefaultOptions();
1966 # We want 'disabled' preferences to always behave as the default value for
1967 # users, even if they have set the option explicitly in their settings (ie they
1968 # set it, and then it was disabled removing their ability to change it). But
1969 # we don't want to erase the preferences in the database in case the preference
1970 # is re-enabled again. So don't touch $mOptions, just override the returned value
1971 if( in_array( $oname, $wgHiddenPrefs ) && !$ignoreHidden ){
1972 return self
::getDefaultOption( $oname );
1975 if ( array_key_exists( $oname, $this->mOptions
) ) {
1976 return $this->mOptions
[$oname];
1978 return $defaultOverride;
1983 * Get all user's options
1987 public function getOptions() {
1988 global $wgHiddenPrefs;
1989 $this->loadOptions();
1990 $options = $this->mOptions
;
1992 # We want 'disabled' preferences to always behave as the default value for
1993 # users, even if they have set the option explicitly in their settings (ie they
1994 # set it, and then it was disabled removing their ability to change it). But
1995 # we don't want to erase the preferences in the database in case the preference
1996 # is re-enabled again. So don't touch $mOptions, just override the returned value
1997 foreach( $wgHiddenPrefs as $pref ){
1998 $default = self
::getDefaultOption( $pref );
1999 if( $default !== null ){
2000 $options[$pref] = $default;
2008 * Get the user's current setting for a given option, as a boolean value.
2010 * @param $oname String The option to check
2011 * @return Bool User's current value for the option
2014 function getBoolOption( $oname ) {
2015 return (bool)$this->getOption( $oname );
2020 * Get the user's current setting for a given option, as a boolean value.
2022 * @param $oname String The option to check
2023 * @param $defaultOverride Int A default value returned if the option does not exist
2024 * @return Int User's current value for the option
2027 function getIntOption( $oname, $defaultOverride=0 ) {
2028 $val = $this->getOption( $oname );
2030 $val = $defaultOverride;
2032 return intval( $val );
2036 * Set the given option for a user.
2038 * @param $oname String The option to set
2039 * @param $val mixed New value to set
2041 function setOption( $oname, $val ) {
2043 $this->loadOptions();
2045 if ( $oname == 'skin' ) {
2046 # Clear cached skin, so the new one displays immediately in Special:Preferences
2047 $this->mSkin
= null;
2050 // Explicitly NULL values should refer to defaults
2051 global $wgDefaultUserOptions;
2052 if( is_null( $val ) && isset( $wgDefaultUserOptions[$oname] ) ) {
2053 $val = $wgDefaultUserOptions[$oname];
2056 $this->mOptions
[$oname] = $val;
2060 * Reset all options to the site defaults
2062 function resetOptions() {
2063 $this->mOptions
= self
::getDefaultOptions();
2067 * Get the user's preferred date format.
2068 * @return String User's preferred date format
2070 function getDatePreference() {
2071 // Important migration for old data rows
2072 if ( is_null( $this->mDatePreference
) ) {
2074 $value = $this->getOption( 'date' );
2075 $map = $wgLang->getDatePreferenceMigrationMap();
2076 if ( isset( $map[$value] ) ) {
2077 $value = $map[$value];
2079 $this->mDatePreference
= $value;
2081 return $this->mDatePreference
;
2085 * Get the user preferred stub threshold
2087 function getStubThreshold() {
2088 global $wgMaxArticleSize; # Maximum article size, in Kb
2089 $threshold = intval( $this->getOption( 'stubthreshold' ) );
2090 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2091 # If they have set an impossible value, disable the preference
2092 # so we can use the parser cache again.
2099 * Get the permissions this user has.
2100 * @return Array of String permission names
2102 function getRights() {
2103 if ( is_null( $this->mRights
) ) {
2104 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2105 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2106 // Force reindexation of rights when a hook has unset one of them
2107 $this->mRights
= array_values( $this->mRights
);
2109 return $this->mRights
;
2113 * Get the list of explicit group memberships this user has.
2114 * The implicit * and user groups are not included.
2115 * @return Array of String internal group names
2117 function getGroups() {
2119 return $this->mGroups
;
2123 * Get the list of implicit group memberships this user has.
2124 * This includes all explicit groups, plus 'user' if logged in,
2125 * '*' for all accounts, and autopromoted groups
2126 * @param $recache Bool Whether to avoid the cache
2127 * @return Array of String internal group names
2129 function getEffectiveGroups( $recache = false ) {
2130 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2131 wfProfileIn( __METHOD__
);
2132 $this->mEffectiveGroups
= $this->getGroups();
2133 $this->mEffectiveGroups
[] = '*';
2134 if( $this->getId() ) {
2135 $this->mEffectiveGroups
[] = 'user';
2137 $this->mEffectiveGroups
= array_unique( array_merge(
2138 $this->mEffectiveGroups
,
2139 Autopromote
::getAutopromoteGroups( $this )
2142 # Hook for additional groups
2143 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2145 wfProfileOut( __METHOD__
);
2147 return $this->mEffectiveGroups
;
2151 * Get the user's edit count.
2154 function getEditCount() {
2155 if( $this->getId() ) {
2156 if ( !isset( $this->mEditCount
) ) {
2157 /* Populate the count, if it has not been populated yet */
2158 $this->mEditCount
= User
::edits( $this->mId
);
2160 return $this->mEditCount
;
2168 * Add the user to the given group.
2169 * This takes immediate effect.
2170 * @param $group String Name of the group to add
2172 function addGroup( $group ) {
2173 if( wfRunHooks( 'UserAddGroup', array( &$this, &$group ) ) ) {
2174 $dbw = wfGetDB( DB_MASTER
);
2175 if( $this->getId() ) {
2176 $dbw->insert( 'user_groups',
2178 'ug_user' => $this->getID(),
2179 'ug_group' => $group,
2182 array( 'IGNORE' ) );
2185 $this->loadGroups();
2186 $this->mGroups
[] = $group;
2187 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2189 $this->invalidateCache();
2193 * Remove the user from the given group.
2194 * This takes immediate effect.
2195 * @param $group String Name of the group to remove
2197 function removeGroup( $group ) {
2199 if( wfRunHooks( 'UserRemoveGroup', array( &$this, &$group ) ) ) {
2200 $dbw = wfGetDB( DB_MASTER
);
2201 $dbw->delete( 'user_groups',
2203 'ug_user' => $this->getID(),
2204 'ug_group' => $group,
2207 $this->loadGroups();
2208 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2209 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2211 $this->invalidateCache();
2215 * Get whether the user is logged in
2218 function isLoggedIn() {
2219 return $this->getID() != 0;
2223 * Get whether the user is anonymous
2227 return !$this->isLoggedIn();
2231 * Check if user is allowed to access a feature / make an action
2232 * @param varargs String permissions to test
2233 * @return Boolean: True if user is allowed to perform *any* of the given actions
2235 public function isAllowedAny( /*...*/ ){
2236 $permissions = func_get_args();
2237 foreach( $permissions as $permission ){
2238 if( $this->isAllowed( $permission ) ){
2246 * @param varargs String
2247 * @return bool True if the user is allowed to perform *all* of the given actions
2249 public function isAllowedAll( /*...*/ ){
2250 $permissions = func_get_args();
2251 foreach( $permissions as $permission ){
2252 if( !$this->isAllowed( $permission ) ){
2260 * Internal mechanics of testing a permission
2261 * @param $action String
2264 public function isAllowed( $action = '' ) {
2265 if ( $action === '' ) {
2266 return true; // In the spirit of DWIM
2268 # Patrolling may not be enabled
2269 if( $action === 'patrol' ||
$action === 'autopatrol' ) {
2270 global $wgUseRCPatrol, $wgUseNPPatrol;
2271 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2274 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2275 # by misconfiguration: 0 == 'foo'
2276 return in_array( $action, $this->getRights(), true );
2280 * Check whether to enable recent changes patrol features for this user
2281 * @return Boolean: True or false
2283 public function useRCPatrol() {
2284 global $wgUseRCPatrol;
2285 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
2289 * Check whether to enable new pages patrol features for this user
2290 * @return Bool True or false
2292 public function useNPPatrol() {
2293 global $wgUseRCPatrol, $wgUseNPPatrol;
2294 return( ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) ) );
2298 * Get the current skin, loading it if required, and setting a title
2299 * @param $t Title: the title to use in the skin
2300 * @return Skin The current skin
2301 * @todo: FIXME : need to check the old failback system [AV]
2303 function getSkin( $t = null ) {
2304 if( !$this->mSkin
) {
2306 $this->mSkin
= $this->createSkinObject();
2307 $this->mSkin
->setTitle( $wgOut->getTitle() );
2309 if ( $t && ( !$this->mSkin
->getTitle() ||
!$t->equals( $this->mSkin
->getTitle() ) ) ) {
2310 $skin = $this->createSkinObject();
2311 $skin->setTitle( $t );
2314 return $this->mSkin
;
2318 // Creates a Skin object, for getSkin()
2319 private function createSkinObject() {
2320 wfProfileIn( __METHOD__
);
2322 global $wgHiddenPrefs;
2323 if( !in_array( 'skin', $wgHiddenPrefs ) ) {
2326 $userSkin = $this->getOption( 'skin' );
2327 $userSkin = $wgRequest->getVal( 'useskin', $userSkin );
2329 # if we're not allowing users to override, then use the default
2330 global $wgDefaultSkin;
2331 $userSkin = $wgDefaultSkin;
2334 $skin = Skin
::newFromKey( $userSkin );
2335 wfProfileOut( __METHOD__
);
2341 * Check the watched status of an article.
2342 * @param $title Title of the article to look at
2345 function isWatched( $title ) {
2346 $wl = WatchedItem
::fromUserTitle( $this, $title );
2347 return $wl->isWatched();
2352 * @param $title Title of the article to look at
2354 function addWatch( $title ) {
2355 $wl = WatchedItem
::fromUserTitle( $this, $title );
2357 $this->invalidateCache();
2361 * Stop watching an article.
2362 * @param $title Title of the article to look at
2364 function removeWatch( $title ) {
2365 $wl = WatchedItem
::fromUserTitle( $this, $title );
2367 $this->invalidateCache();
2371 * Clear the user's notification timestamp for the given title.
2372 * If e-notif e-mails are on, they will receive notification mails on
2373 * the next change of the page if it's watched etc.
2374 * @param $title Title of the article to look at
2376 function clearNotification( &$title ) {
2377 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2379 # Do nothing if the database is locked to writes
2380 if( wfReadOnly() ) {
2384 if( $title->getNamespace() == NS_USER_TALK
&&
2385 $title->getText() == $this->getName() ) {
2386 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2388 $this->setNewtalk( false );
2391 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2395 if( $this->isAnon() ) {
2396 // Nothing else to do...
2400 // Only update the timestamp if the page is being watched.
2401 // The query to find out if it is watched is cached both in memcached and per-invocation,
2402 // and when it does have to be executed, it can be on a slave
2403 // If this is the user's newtalk page, we always update the timestamp
2404 if( $title->getNamespace() == NS_USER_TALK
&&
2405 $title->getText() == $wgUser->getName() )
2408 } elseif ( $this->getId() == $wgUser->getId() ) {
2409 $watched = $title->userIsWatching();
2414 // If the page is watched by the user (or may be watched), update the timestamp on any
2415 // any matching rows
2417 $dbw = wfGetDB( DB_MASTER
);
2418 $dbw->update( 'watchlist',
2420 'wl_notificationtimestamp' => null
2421 ), array( /* WHERE */
2422 'wl_title' => $title->getDBkey(),
2423 'wl_namespace' => $title->getNamespace(),
2424 'wl_user' => $this->getID()
2431 * Resets all of the given user's page-change notification timestamps.
2432 * If e-notif e-mails are on, they will receive notification mails on
2433 * the next change of any watched page.
2435 * @param $currentUser Int User ID
2437 function clearAllNotifications( $currentUser ) {
2438 global $wgUseEnotif, $wgShowUpdatedMarker;
2439 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2440 $this->setNewtalk( false );
2443 if( $currentUser != 0 ) {
2444 $dbw = wfGetDB( DB_MASTER
);
2445 $dbw->update( 'watchlist',
2447 'wl_notificationtimestamp' => null
2448 ), array( /* WHERE */
2449 'wl_user' => $currentUser
2452 # We also need to clear here the "you have new message" notification for the own user_talk page
2453 # This is cleared one page view later in Article::viewUpdates();
2458 * Set this user's options from an encoded string
2459 * @param $str String Encoded options to import
2462 function decodeOptions( $str ) {
2466 $this->mOptionsLoaded
= true;
2467 $this->mOptionOverrides
= array();
2469 // If an option is not set in $str, use the default value
2470 $this->mOptions
= self
::getDefaultOptions();
2472 $a = explode( "\n", $str );
2473 foreach ( $a as $s ) {
2475 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2476 $this->mOptions
[$m[1]] = $m[2];
2477 $this->mOptionOverrides
[$m[1]] = $m[2];
2483 * Set a cookie on the user's client. Wrapper for
2484 * WebResponse::setCookie
2485 * @param $name String Name of the cookie to set
2486 * @param $value String Value to set
2487 * @param $exp Int Expiration time, as a UNIX time value;
2488 * if 0 or not specified, use the default $wgCookieExpiration
2490 protected function setCookie( $name, $value, $exp = 0 ) {
2492 $wgRequest->response()->setcookie( $name, $value, $exp );
2496 * Clear a cookie on the user's client
2497 * @param $name String Name of the cookie to clear
2499 protected function clearCookie( $name ) {
2500 $this->setCookie( $name, '', time() - 86400 );
2504 * Set the default cookies for this session on the user's client.
2506 * @param $request WebRequest object to use; $wgRequest will be used if null
2509 function setCookies( $request = null ) {
2510 if ( $request === null ) {
2512 $request = $wgRequest;
2516 if ( 0 == $this->mId
) return;
2518 'wsUserID' => $this->mId
,
2519 'wsToken' => $this->mToken
,
2520 'wsUserName' => $this->getName()
2523 'UserID' => $this->mId
,
2524 'UserName' => $this->getName(),
2526 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2527 $cookies['Token'] = $this->mToken
;
2529 $cookies['Token'] = false;
2532 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2534 foreach ( $session as $name => $value ) {
2535 $request->setSessionData( $name, $value );
2537 foreach ( $cookies as $name => $value ) {
2538 if ( $value === false ) {
2539 $this->clearCookie( $name );
2541 $this->setCookie( $name, $value );
2547 * Log this user out.
2550 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
2556 * Clear the user's cookies and session, and reset the instance cache.
2560 function doLogout() {
2563 $this->clearInstanceCache( 'defaults' );
2565 $wgRequest->setSessionData( 'wsUserID', 0 );
2567 $this->clearCookie( 'UserID' );
2568 $this->clearCookie( 'Token' );
2570 # Remember when user logged out, to prevent seeing cached pages
2571 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2575 * Save this user's settings into the database.
2576 * @todo Only rarely do all these fields need to be set!
2578 function saveSettings() {
2580 if ( wfReadOnly() ) { return; }
2581 if ( 0 == $this->mId
) { return; }
2583 $this->mTouched
= self
::newTouchedTimestamp();
2585 $dbw = wfGetDB( DB_MASTER
);
2586 $dbw->update( 'user',
2588 'user_name' => $this->mName
,
2589 'user_password' => $this->mPassword
,
2590 'user_newpassword' => $this->mNewpassword
,
2591 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2592 'user_real_name' => $this->mRealName
,
2593 'user_email' => $this->mEmail
,
2594 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2595 'user_options' => '',
2596 'user_touched' => $dbw->timestamp( $this->mTouched
),
2597 'user_token' => $this->mToken
,
2598 'user_email_token' => $this->mEmailToken
,
2599 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2600 ), array( /* WHERE */
2601 'user_id' => $this->mId
2605 $this->saveOptions();
2607 wfRunHooks( 'UserSaveSettings', array( $this ) );
2608 $this->clearSharedCache();
2609 $this->getUserPage()->invalidateCache();
2613 * If only this user's username is known, and it exists, return the user ID.
2616 function idForName() {
2617 $s = trim( $this->getName() );
2618 if ( $s === '' ) return 0;
2620 $dbr = wfGetDB( DB_SLAVE
);
2621 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2622 if ( $id === false ) {
2629 * Add a user to the database, return the user object
2631 * @param $name String Username to add
2632 * @param $params Array of Strings Non-default parameters to save to the database as user_* fields:
2633 * - password The user's password hash. Password logins will be disabled if this is omitted.
2634 * - newpassword Hash for a temporary password that has been mailed to the user
2635 * - email The user's email address
2636 * - email_authenticated The email authentication timestamp
2637 * - real_name The user's real name
2638 * - options An associative array of non-default options
2639 * - token Random authentication token. Do not set.
2640 * - registration Registration timestamp. Do not set.
2642 * @return User object, or null if the username already exists
2644 static function createNew( $name, $params = array() ) {
2647 if ( isset( $params['options'] ) ) {
2648 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
2649 unset( $params['options'] );
2651 $dbw = wfGetDB( DB_MASTER
);
2652 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2655 'user_id' => $seqVal,
2656 'user_name' => $name,
2657 'user_password' => $user->mPassword
,
2658 'user_newpassword' => $user->mNewpassword
,
2659 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
2660 'user_email' => $user->mEmail
,
2661 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2662 'user_real_name' => $user->mRealName
,
2663 'user_options' => '',
2664 'user_token' => $user->mToken
,
2665 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2666 'user_editcount' => 0,
2668 foreach ( $params as $name => $value ) {
2669 $fields["user_$name"] = $value;
2671 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2672 if ( $dbw->affectedRows() ) {
2673 $newUser = User
::newFromId( $dbw->insertId() );
2681 * Add this existing user object to the database
2683 function addToDatabase() {
2685 $dbw = wfGetDB( DB_MASTER
);
2686 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2687 $dbw->insert( 'user',
2689 'user_id' => $seqVal,
2690 'user_name' => $this->mName
,
2691 'user_password' => $this->mPassword
,
2692 'user_newpassword' => $this->mNewpassword
,
2693 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2694 'user_email' => $this->mEmail
,
2695 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2696 'user_real_name' => $this->mRealName
,
2697 'user_options' => '',
2698 'user_token' => $this->mToken
,
2699 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2700 'user_editcount' => 0,
2703 $this->mId
= $dbw->insertId();
2705 // Clear instance cache other than user table data, which is already accurate
2706 $this->clearInstanceCache();
2708 $this->saveOptions();
2712 * If this (non-anonymous) user is blocked, block any IP address
2713 * they've successfully logged in from.
2715 function spreadBlock() {
2716 wfDebug( __METHOD__
. "()\n" );
2718 if ( $this->mId
== 0 ) {
2722 $userblock = Block
::newFromTarget( $this->getName() );
2723 if ( !$userblock ) {
2727 $userblock->doAutoblock( wfGetIP() );
2731 * Generate a string which will be different for any combination of
2732 * user options which would produce different parser output.
2733 * This will be used as part of the hash key for the parser cache,
2734 * so users with the same options can share the same cached data
2737 * Extensions which require it should install 'PageRenderingHash' hook,
2738 * which will give them a chance to modify this key based on their own
2741 * @deprecated since 1.17 use the ParserOptions object to get the relevant options
2742 * @return String Page rendering hash
2744 function getPageRenderingHash() {
2745 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2747 return $this->mHash
;
2749 wfDeprecated( __METHOD__
);
2751 // stubthreshold is only included below for completeness,
2752 // since it disables the parser cache, its value will always
2753 // be 0 when this function is called by parsercache.
2755 $confstr = $this->getOption( 'math' );
2756 $confstr .= '!' . $this->getStubThreshold();
2757 if ( $wgUseDynamicDates ) { # This is wrong (bug 24714)
2758 $confstr .= '!' . $this->getDatePreference();
2760 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ?
'1' : '' );
2761 $confstr .= '!' . $wgLang->getCode();
2762 $confstr .= '!' . $this->getOption( 'thumbsize' );
2763 // add in language specific options, if any
2764 $extra = $wgContLang->getExtraHashOptions();
2767 // Since the skin could be overloading link(), it should be
2768 // included here but in practice, none of our skins do that.
2770 $confstr .= $wgRenderHashAppend;
2772 // Give a chance for extensions to modify the hash, if they have
2773 // extra options or other effects on the parser cache.
2774 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2776 // Make it a valid memcached key fragment
2777 $confstr = str_replace( ' ', '_', $confstr );
2778 $this->mHash
= $confstr;
2783 * Get whether the user is explicitly blocked from account creation.
2784 * @return Bool|Block
2786 function isBlockedFromCreateAccount() {
2787 $this->getBlockedStatus();
2788 if( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ){
2789 return $this->mBlock
;
2792 # bug 13611: if the IP address the user is trying to create an account from is
2793 # blocked with createaccount disabled, prevent new account creation there even
2794 # when the user is logged in
2795 static $accBlock = false;
2796 if( $accBlock === false ){
2797 $accBlock = Block
::newFromTarget( null, wfGetIP() );
2799 return $accBlock instanceof Block
&& $accBlock->prevents( 'createaccount' )
2805 * Get whether the user is blocked from using Special:Emailuser.
2808 function isBlockedFromEmailuser() {
2809 $this->getBlockedStatus();
2810 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
2814 * Get whether the user is allowed to create an account.
2817 function isAllowedToCreateAccount() {
2818 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2822 * Get this user's personal page title.
2824 * @return Title: User's personal page title
2826 function getUserPage() {
2827 return Title
::makeTitle( NS_USER
, $this->getName() );
2831 * Get this user's talk page title.
2833 * @return Title: User's talk page title
2835 function getTalkPage() {
2836 $title = $this->getUserPage();
2837 return $title->getTalkPage();
2841 * Get the maximum valid user ID.
2842 * @return Integer: User ID
2845 function getMaxID() {
2846 static $res; // cache
2848 if ( isset( $res ) ) {
2851 $dbr = wfGetDB( DB_SLAVE
);
2852 return $res = $dbr->selectField( 'user', 'max(user_id)', false, __METHOD__
);
2857 * Determine whether the user is a newbie. Newbies are either
2858 * anonymous IPs, or the most recently created accounts.
2861 function isNewbie() {
2862 return !$this->isAllowed( 'autoconfirmed' );
2866 * Check to see if the given clear-text password is one of the accepted passwords
2867 * @param $password String: user password.
2868 * @return Boolean: True if the given password is correct, otherwise False.
2870 function checkPassword( $password ) {
2871 global $wgAuth, $wgLegacyEncoding;
2874 // Even though we stop people from creating passwords that
2875 // are shorter than this, doesn't mean people wont be able
2876 // to. Certain authentication plugins do NOT want to save
2877 // domain passwords in a mysql database, so we should
2878 // check this (in case $wgAuth->strict() is false).
2879 if( !$this->isValidPassword( $password ) ) {
2883 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2885 } elseif( $wgAuth->strict() ) {
2886 /* Auth plugin doesn't allow local authentication */
2888 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2889 /* Auth plugin doesn't allow local authentication for this user name */
2892 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
2894 } elseif ( $wgLegacyEncoding ) {
2895 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2896 # Check for this with iconv
2897 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2898 if ( $cp1252Password != $password &&
2899 self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) )
2908 * Check if the given clear-text password matches the temporary password
2909 * sent by e-mail for password reset operations.
2910 * @return Boolean: True if matches, false otherwise
2912 function checkTemporaryPassword( $plaintext ) {
2913 global $wgNewPasswordExpiry;
2914 if( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
2915 if ( is_null( $this->mNewpassTime
) ) {
2918 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
2919 return ( time() < $expiry );
2926 * Initialize (if necessary) and return a session token value
2927 * which can be used in edit forms to show that the user's
2928 * login credentials aren't being hijacked with a foreign form
2931 * @param $salt String|Array of Strings Optional function-specific data for hashing
2932 * @param $request WebRequest object to use or null to use $wgRequest
2933 * @return String The new edit token
2935 function editToken( $salt = '', $request = null ) {
2936 if ( $request == null ) {
2938 $request = $wgRequest;
2941 if ( $this->isAnon() ) {
2942 return EDIT_TOKEN_SUFFIX
;
2944 $token = $request->getSessionData( 'wsEditToken' );
2945 if ( $token === null ) {
2946 $token = self
::generateToken();
2947 $request->setSessionData( 'wsEditToken', $token );
2949 if( is_array( $salt ) ) {
2950 $salt = implode( '|', $salt );
2952 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2957 * Generate a looking random token for various uses.
2959 * @param $salt String Optional salt value
2960 * @return String The new random token
2962 public static function generateToken( $salt = '' ) {
2963 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2964 return md5( $token . $salt );
2968 * Check given value against the token value stored in the session.
2969 * A match should confirm that the form was submitted from the
2970 * user's own login session, not a form submission from a third-party
2973 * @param $val String Input value to compare
2974 * @param $salt String Optional function-specific data for hashing
2975 * @param $request WebRequest object to use or null to use $wgRequest
2976 * @return Boolean: Whether the token matches
2978 function matchEditToken( $val, $salt = '', $request = null ) {
2979 $sessionToken = $this->editToken( $salt, $request );
2980 if ( $val != $sessionToken ) {
2981 wfDebug( "User::matchEditToken: broken session data\n" );
2983 return $val == $sessionToken;
2987 * Check given value against the token value stored in the session,
2988 * ignoring the suffix.
2990 * @param $val String Input value to compare
2991 * @param $salt String Optional function-specific data for hashing
2992 * @param $request WebRequest object to use or null to use $wgRequest
2993 * @return Boolean: Whether the token matches
2995 function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
2996 $sessionToken = $this->editToken( $salt, $request );
2997 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3001 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3002 * mail to the user's given address.
3004 * @param $type String: message to send, either "created", "changed" or "set"
3005 * @return Status object
3007 function sendConfirmationMail( $type = 'created' ) {
3009 $expiration = null; // gets passed-by-ref and defined in next line.
3010 $token = $this->confirmationToken( $expiration );
3011 $url = $this->confirmationTokenUrl( $token );
3012 $invalidateURL = $this->invalidationTokenUrl( $token );
3013 $this->saveSettings();
3015 if ( $type == 'created' ||
$type === false ) {
3016 $message = 'confirmemail_body';
3017 } elseif ( $type === true ) {
3018 $message = 'confirmemail_body_changed';
3020 $message = 'confirmemail_body_' . $type;
3023 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
3028 $wgLang->timeanddate( $expiration, false ),
3030 $wgLang->date( $expiration, false ),
3031 $wgLang->time( $expiration, false ) ) );
3035 * Send an e-mail to this user's account. Does not check for
3036 * confirmed status or validity.
3038 * @param $subject String Message subject
3039 * @param $body String Message body
3040 * @param $from String Optional From address; if unspecified, default $wgPasswordSender will be used
3041 * @param $replyto String Reply-To address
3044 function sendMail( $subject, $body, $from = null, $replyto = null ) {
3045 if( is_null( $from ) ) {
3046 global $wgPasswordSender, $wgPasswordSenderName;
3047 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
3049 $sender = new MailAddress( $from );
3052 $to = new MailAddress( $this );
3053 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
3057 * Generate, store, and return a new e-mail confirmation code.
3058 * A hash (unsalted, since it's used as a key) is stored.
3060 * @note Call saveSettings() after calling this function to commit
3061 * this change to the database.
3063 * @param[out] &$expiration \mixed Accepts the expiration time
3064 * @return String New token
3067 function confirmationToken( &$expiration ) {
3068 global $wgUserEmailConfirmationTokenExpiry;
3070 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
3071 $expiration = wfTimestamp( TS_MW
, $expires );
3072 $token = self
::generateToken( $this->mId
. $this->mEmail
. $expires );
3073 $hash = md5( $token );
3075 $this->mEmailToken
= $hash;
3076 $this->mEmailTokenExpires
= $expiration;
3081 * Return a URL the user can use to confirm their email address.
3082 * @param $token String Accepts the email confirmation token
3083 * @return String New token URL
3086 function confirmationTokenUrl( $token ) {
3087 return $this->getTokenUrl( 'ConfirmEmail', $token );
3091 * Return a URL the user can use to invalidate their email address.
3092 * @param $token String Accepts the email confirmation token
3093 * @return String New token URL
3096 function invalidationTokenUrl( $token ) {
3097 return $this->getTokenUrl( 'Invalidateemail', $token );
3101 * Internal function to format the e-mail validation/invalidation URLs.
3102 * This uses $wgArticlePath directly as a quickie hack to use the
3103 * hardcoded English names of the Special: pages, for ASCII safety.
3105 * @note Since these URLs get dropped directly into emails, using the
3106 * short English names avoids insanely long URL-encoded links, which
3107 * also sometimes can get corrupted in some browsers/mailers
3108 * (bug 6957 with Gmail and Internet Explorer).
3110 * @param $page String Special page
3111 * @param $token String Token
3112 * @return String Formatted URL
3114 protected function getTokenUrl( $page, $token ) {
3115 global $wgArticlePath;
3119 "Special:$page/$token",
3124 * Mark the e-mail address confirmed.
3126 * @note Call saveSettings() after calling this function to commit the change.
3128 function confirmEmail() {
3129 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3130 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3135 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3136 * address if it was already confirmed.
3138 * @note Call saveSettings() after calling this function to commit the change.
3140 function invalidateEmail() {
3142 $this->mEmailToken
= null;
3143 $this->mEmailTokenExpires
= null;
3144 $this->setEmailAuthenticationTimestamp( null );
3145 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3150 * Set the e-mail authentication timestamp.
3151 * @param $timestamp String TS_MW timestamp
3153 function setEmailAuthenticationTimestamp( $timestamp ) {
3155 $this->mEmailAuthenticated
= $timestamp;
3156 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
3160 * Is this user allowed to send e-mails within limits of current
3161 * site configuration?
3164 function canSendEmail() {
3165 global $wgEnableEmail, $wgEnableUserEmail;
3166 if( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
3169 $canSend = $this->isEmailConfirmed();
3170 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3175 * Is this user allowed to receive e-mails within limits of current
3176 * site configuration?
3179 function canReceiveEmail() {
3180 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3184 * Is this user's e-mail address valid-looking and confirmed within
3185 * limits of the current site configuration?
3187 * @note If $wgEmailAuthentication is on, this may require the user to have
3188 * confirmed their address by returning a code or using a password
3189 * sent to the address from the wiki.
3193 function isEmailConfirmed() {
3194 global $wgEmailAuthentication;
3197 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3198 if( $this->isAnon() )
3200 if( !self
::isValidEmailAddr( $this->mEmail
) )
3202 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
3211 * Check whether there is an outstanding request for e-mail confirmation.
3214 function isEmailConfirmationPending() {
3215 global $wgEmailAuthentication;
3216 return $wgEmailAuthentication &&
3217 !$this->isEmailConfirmed() &&
3218 $this->mEmailToken
&&
3219 $this->mEmailTokenExpires
> wfTimestamp();
3223 * Get the timestamp of account creation.
3225 * @return String|Bool Timestamp of account creation, or false for
3226 * non-existent/anonymous user accounts.
3228 public function getRegistration() {
3229 return $this->getId() > 0
3230 ?
$this->mRegistration
3235 * Get the timestamp of the first edit
3237 * @return String|Bool Timestamp of first edit, or false for
3238 * non-existent/anonymous user accounts.
3240 public function getFirstEditTimestamp() {
3241 if( $this->getId() == 0 ) {
3242 return false; // anons
3244 $dbr = wfGetDB( DB_SLAVE
);
3245 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3246 array( 'rev_user' => $this->getId() ),
3248 array( 'ORDER BY' => 'rev_timestamp ASC' )
3251 return false; // no edits
3253 return wfTimestamp( TS_MW
, $time );
3257 * Get the permissions associated with a given list of groups
3259 * @param $groups Array of Strings List of internal group names
3260 * @return Array of Strings List of permission key names for given groups combined
3262 static function getGroupPermissions( $groups ) {
3263 global $wgGroupPermissions, $wgRevokePermissions;
3265 // grant every granted permission first
3266 foreach( $groups as $group ) {
3267 if( isset( $wgGroupPermissions[$group] ) ) {
3268 $rights = array_merge( $rights,
3269 // array_filter removes empty items
3270 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3273 // now revoke the revoked permissions
3274 foreach( $groups as $group ) {
3275 if( isset( $wgRevokePermissions[$group] ) ) {
3276 $rights = array_diff( $rights,
3277 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3280 return array_unique( $rights );
3284 * Get all the groups who have a given permission
3286 * @param $role String Role to check
3287 * @return Array of Strings List of internal group names with the given permission
3289 static function getGroupsWithPermission( $role ) {
3290 global $wgGroupPermissions;
3291 $allowedGroups = array();
3292 foreach ( $wgGroupPermissions as $group => $rights ) {
3293 if ( isset( $rights[$role] ) && $rights[$role] ) {
3294 $allowedGroups[] = $group;
3297 return $allowedGroups;
3301 * Get the localized descriptive name for a group, if it exists
3303 * @param $group String Internal group name
3304 * @return String Localized descriptive group name
3306 static function getGroupName( $group ) {
3307 $msg = wfMessage( "group-$group" );
3308 return $msg->isBlank() ?
$group : $msg->text();
3312 * Get the localized descriptive name for a member of a group, if it exists
3314 * @param $group String Internal group name
3315 * @return String Localized name for group member
3317 static function getGroupMember( $group ) {
3318 $msg = wfMessage( "group-$group-member" );
3319 return $msg->isBlank() ?
$group : $msg->text();
3323 * Return the set of defined explicit groups.
3324 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3325 * are not included, as they are defined automatically, not in the database.
3326 * @return Array of internal group names
3328 static function getAllGroups() {
3329 global $wgGroupPermissions, $wgRevokePermissions;
3331 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3332 self
::getImplicitGroups()
3337 * Get a list of all available permissions.
3338 * @return Array of permission names
3340 static function getAllRights() {
3341 if ( self
::$mAllRights === false ) {
3342 global $wgAvailableRights;
3343 if ( count( $wgAvailableRights ) ) {
3344 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3346 self
::$mAllRights = self
::$mCoreRights;
3348 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3350 return self
::$mAllRights;
3354 * Get a list of implicit groups
3355 * @return Array of Strings Array of internal group names
3357 public static function getImplicitGroups() {
3358 global $wgImplicitGroups;
3359 $groups = $wgImplicitGroups;
3360 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3365 * Get the title of a page describing a particular group
3367 * @param $group String Internal group name
3368 * @return Title|Bool Title of the page if it exists, false otherwise
3370 static function getGroupPage( $group ) {
3371 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
3372 if( $msg->exists() ) {
3373 $title = Title
::newFromText( $msg->text() );
3374 if( is_object( $title ) )
3381 * Create a link to the group in HTML, if available;
3382 * else return the group name.
3384 * @param $group String Internal name of the group
3385 * @param $text String The text of the link
3386 * @return String HTML link to the group
3388 static function makeGroupLinkHTML( $group, $text = '' ) {
3390 $text = self
::getGroupName( $group );
3392 $title = self
::getGroupPage( $group );
3395 $sk = $wgUser->getSkin();
3396 return $sk->link( $title, htmlspecialchars( $text ) );
3403 * Create a link to the group in Wikitext, if available;
3404 * else return the group name.
3406 * @param $group String Internal name of the group
3407 * @param $text String The text of the link
3408 * @return String Wikilink to the group
3410 static function makeGroupLinkWiki( $group, $text = '' ) {
3412 $text = self
::getGroupName( $group );
3414 $title = self
::getGroupPage( $group );
3416 $page = $title->getPrefixedText();
3417 return "[[$page|$text]]";
3424 * Returns an array of the groups that a particular group can add/remove.
3426 * @param $group String: the group to check for whether it can add/remove
3427 * @return Array array( 'add' => array( addablegroups ),
3428 * 'remove' => array( removablegroups ),
3429 * 'add-self' => array( addablegroups to self),
3430 * 'remove-self' => array( removable groups from self) )
3432 static function changeableByGroup( $group ) {
3433 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
3435 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
3436 if( empty( $wgAddGroups[$group] ) ) {
3437 // Don't add anything to $groups
3438 } elseif( $wgAddGroups[$group] === true ) {
3439 // You get everything
3440 $groups['add'] = self
::getAllGroups();
3441 } elseif( is_array( $wgAddGroups[$group] ) ) {
3442 $groups['add'] = $wgAddGroups[$group];
3445 // Same thing for remove
3446 if( empty( $wgRemoveGroups[$group] ) ) {
3447 } elseif( $wgRemoveGroups[$group] === true ) {
3448 $groups['remove'] = self
::getAllGroups();
3449 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
3450 $groups['remove'] = $wgRemoveGroups[$group];
3453 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
3454 if( empty( $wgGroupsAddToSelf['user']) ||
$wgGroupsAddToSelf['user'] !== true ) {
3455 foreach( $wgGroupsAddToSelf as $key => $value ) {
3456 if( is_int( $key ) ) {
3457 $wgGroupsAddToSelf['user'][] = $value;
3462 if( empty( $wgGroupsRemoveFromSelf['user']) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
3463 foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
3464 if( is_int( $key ) ) {
3465 $wgGroupsRemoveFromSelf['user'][] = $value;
3470 // Now figure out what groups the user can add to him/herself
3471 if( empty( $wgGroupsAddToSelf[$group] ) ) {
3472 } elseif( $wgGroupsAddToSelf[$group] === true ) {
3473 // No idea WHY this would be used, but it's there
3474 $groups['add-self'] = User
::getAllGroups();
3475 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
3476 $groups['add-self'] = $wgGroupsAddToSelf[$group];
3479 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
3480 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
3481 $groups['remove-self'] = User
::getAllGroups();
3482 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
3483 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
3490 * Returns an array of groups that this user can add and remove
3491 * @return Array array( 'add' => array( addablegroups ),
3492 * 'remove' => array( removablegroups ),
3493 * 'add-self' => array( addablegroups to self),
3494 * 'remove-self' => array( removable groups from self) )
3496 function changeableGroups() {
3497 if( $this->isAllowed( 'userrights' ) ) {
3498 // This group gives the right to modify everything (reverse-
3499 // compatibility with old "userrights lets you change
3501 // Using array_merge to make the groups reindexed
3502 $all = array_merge( User
::getAllGroups() );
3506 'add-self' => array(),
3507 'remove-self' => array()
3511 // Okay, it's not so simple, we will have to go through the arrays
3514 'remove' => array(),
3515 'add-self' => array(),
3516 'remove-self' => array()
3518 $addergroups = $this->getEffectiveGroups();
3520 foreach( $addergroups as $addergroup ) {
3521 $groups = array_merge_recursive(
3522 $groups, $this->changeableByGroup( $addergroup )
3524 $groups['add'] = array_unique( $groups['add'] );
3525 $groups['remove'] = array_unique( $groups['remove'] );
3526 $groups['add-self'] = array_unique( $groups['add-self'] );
3527 $groups['remove-self'] = array_unique( $groups['remove-self'] );
3533 * Increment the user's edit-count field.
3534 * Will have no effect for anonymous users.
3536 function incEditCount() {
3537 if( !$this->isAnon() ) {
3538 $dbw = wfGetDB( DB_MASTER
);
3539 $dbw->update( 'user',
3540 array( 'user_editcount=user_editcount+1' ),
3541 array( 'user_id' => $this->getId() ),
3544 // Lazy initialization check...
3545 if( $dbw->affectedRows() == 0 ) {
3546 // Pull from a slave to be less cruel to servers
3547 // Accuracy isn't the point anyway here
3548 $dbr = wfGetDB( DB_SLAVE
);
3549 $count = $dbr->selectField( 'revision',
3551 array( 'rev_user' => $this->getId() ),
3554 // Now here's a goddamn hack...
3555 if( $dbr !== $dbw ) {
3556 // If we actually have a slave server, the count is
3557 // at least one behind because the current transaction
3558 // has not been committed and replicated.
3561 // But if DB_SLAVE is selecting the master, then the
3562 // count we just read includes the revision that was
3563 // just added in the working transaction.
3566 $dbw->update( 'user',
3567 array( 'user_editcount' => $count ),
3568 array( 'user_id' => $this->getId() ),
3572 // edit count in user cache too
3573 $this->invalidateCache();
3577 * Get the description of a given right
3579 * @param $right String Right to query
3580 * @return String Localized description of the right
3582 static function getRightDescription( $right ) {
3583 $key = "right-$right";
3584 $name = wfMsg( $key );
3585 return $name == '' ||
wfEmptyMsg( $key )
3591 * Make an old-style password hash
3593 * @param $password String Plain-text password
3594 * @param $userId String User ID
3595 * @return String Password hash
3597 static function oldCrypt( $password, $userId ) {
3598 global $wgPasswordSalt;
3599 if ( $wgPasswordSalt ) {
3600 return md5( $userId . '-' . md5( $password ) );
3602 return md5( $password );
3607 * Make a new-style password hash
3609 * @param $password String Plain-text password
3610 * @param $salt String Optional salt, may be random or the user ID.
3611 * If unspecified or false, will generate one automatically
3612 * @return String Password hash
3614 static function crypt( $password, $salt = false ) {
3615 global $wgPasswordSalt;
3618 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3622 if( $wgPasswordSalt ) {
3623 if ( $salt === false ) {
3624 $salt = substr( wfGenerateToken(), 0, 8 );
3626 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3628 return ':A:' . md5( $password );
3633 * Compare a password hash with a plain-text password. Requires the user
3634 * ID if there's a chance that the hash is an old-style hash.
3636 * @param $hash String Password hash
3637 * @param $password String Plain-text password to compare
3638 * @param $userId String User ID for old-style password salt
3641 static function comparePasswords( $hash, $password, $userId = false ) {
3642 $type = substr( $hash, 0, 3 );
3645 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3649 if ( $type == ':A:' ) {
3651 return md5( $password ) === substr( $hash, 3 );
3652 } elseif ( $type == ':B:' ) {
3654 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3655 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3658 return self
::oldCrypt( $password, $userId ) === $hash;
3663 * Add a newuser log entry for this user
3665 * @param $byEmail Boolean: account made by email?
3666 * @param $reason String: user supplied reason
3668 public function addNewUserLogEntry( $byEmail = false, $reason = '' ) {
3669 global $wgUser, $wgContLang, $wgNewUserLog;
3670 if( empty( $wgNewUserLog ) ) {
3671 return true; // disabled
3674 if( $this->getName() == $wgUser->getName() ) {
3677 $action = 'create2';
3679 if ( $reason === '' ) {
3680 $reason = wfMsgForContent( 'newuserlog-byemail' );
3682 $reason = $wgContLang->commaList( array(
3683 $reason, wfMsgForContent( 'newuserlog-byemail' ) ) );
3687 $log = new LogPage( 'newusers' );
3690 $this->getUserPage(),
3692 array( $this->getId() )
3698 * Add an autocreate newuser log entry for this user
3699 * Used by things like CentralAuth and perhaps other authplugins.
3701 public function addNewUserLogEntryAutoCreate() {
3702 global $wgNewUserLog, $wgLogAutocreatedAccounts;
3703 if( !$wgNewUserLog ||
!$wgLogAutocreatedAccounts ) {
3704 return true; // disabled
3706 $log = new LogPage( 'newusers', false );
3707 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3711 protected function loadOptions() {
3713 if ( $this->mOptionsLoaded ||
!$this->getId() )
3716 $this->mOptions
= self
::getDefaultOptions();
3718 // Maybe load from the object
3719 if ( !is_null( $this->mOptionOverrides
) ) {
3720 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
3721 foreach( $this->mOptionOverrides
as $key => $value ) {
3722 $this->mOptions
[$key] = $value;
3725 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
3726 // Load from database
3727 $dbr = wfGetDB( DB_SLAVE
);
3729 $res = $dbr->select(
3732 array( 'up_user' => $this->getId() ),
3736 foreach ( $res as $row ) {
3737 $this->mOptionOverrides
[$row->up_property
] = $row->up_value
;
3738 $this->mOptions
[$row->up_property
] = $row->up_value
;
3742 $this->mOptionsLoaded
= true;
3744 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
3747 protected function saveOptions() {
3748 global $wgAllowPrefChange;
3750 $extuser = ExternalUser
::newFromUser( $this );
3752 $this->loadOptions();
3753 $dbw = wfGetDB( DB_MASTER
);
3755 $insert_rows = array();
3757 $saveOptions = $this->mOptions
;
3759 // Allow hooks to abort, for instance to save to a global profile.
3760 // Reset options to default state before saving.
3761 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) )
3764 foreach( $saveOptions as $key => $value ) {
3765 # Don't bother storing default values
3766 if ( ( is_null( self
::getDefaultOption( $key ) ) &&
3767 !( $value === false ||
is_null($value) ) ) ||
3768 $value != self
::getDefaultOption( $key ) ) {
3769 $insert_rows[] = array(
3770 'up_user' => $this->getId(),
3771 'up_property' => $key,
3772 'up_value' => $value,
3775 if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
3776 switch ( $wgAllowPrefChange[$key] ) {
3782 $extuser->setPref( $key, $value );
3788 $dbw->delete( 'user_properties', array( 'up_user' => $this->getId() ), __METHOD__
);
3789 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
);
3794 * Provide an array of HTML5 attributes to put on an input element
3795 * intended for the user to enter a new password. This may include
3796 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
3798 * Do *not* use this when asking the user to enter his current password!
3799 * Regardless of configuration, users may have invalid passwords for whatever
3800 * reason (e.g., they were set before requirements were tightened up).
3801 * Only use it when asking for a new password, like on account creation or
3804 * Obviously, you still need to do server-side checking.
3806 * NOTE: A combination of bugs in various browsers means that this function
3807 * actually just returns array() unconditionally at the moment. May as
3808 * well keep it around for when the browser bugs get fixed, though.
3810 * FIXME : This does not belong here; put it in Html or Linker or somewhere
3812 * @return array Array of HTML attributes suitable for feeding to
3813 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
3814 * That will potentially output invalid XHTML 1.0 Transitional, and will
3815 * get confused by the boolean attribute syntax used.)
3817 public static function passwordChangeInputAttribs() {
3818 global $wgMinimalPasswordLength;
3820 if ( $wgMinimalPasswordLength == 0 ) {
3824 # Note that the pattern requirement will always be satisfied if the
3825 # input is empty, so we need required in all cases.
3827 # FIXME (bug 23769): This needs to not claim the password is required
3828 # if e-mail confirmation is being used. Since HTML5 input validation
3829 # is b0rked anyway in some browsers, just return nothing. When it's
3830 # re-enabled, fix this code to not output required for e-mail
3832 #$ret = array( 'required' );
3835 # We can't actually do this right now, because Opera 9.6 will print out
3836 # the entered password visibly in its error message! When other
3837 # browsers add support for this attribute, or Opera fixes its support,
3838 # we can add support with a version check to avoid doing this on Opera
3839 # versions where it will be a problem. Reported to Opera as
3840 # DSK-262266, but they don't have a public bug tracker for us to follow.
3842 if ( $wgMinimalPasswordLength > 1 ) {
3843 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
3844 $ret['title'] = wfMsgExt( 'passwordtooshort', 'parsemag',
3845 $wgMinimalPasswordLength );