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',
143 'userrights-interwiki',
147 * String Cached results of getAllRights()
149 static $mAllRights = false;
151 /** @name Cache variables */
153 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
154 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
155 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups, $mOptionOverrides;
159 * Bool Whether the cache variables have been loaded.
165 * Array with already loaded items or true if all items have been loaded.
167 private $mLoadedItems = array();
171 * String Initialization data source if mLoadedItems!==true. May be one of:
172 * - 'defaults' anonymous user initialised from class defaults
173 * - 'name' initialise from mName
174 * - 'id' initialise from mId
175 * - 'session' log in from cookies or session if possible
177 * Use the User::newFrom*() family of functions to set this.
182 * Lazy-initialized variables, invalidated with clearInstanceCache
184 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mRights,
185 $mBlockreason, $mEffectiveGroups, $mFormerGroups, $mBlockedGlobally,
186 $mLocked, $mHideName, $mOptions;
198 static $idCacheByName = array();
201 * Lightweight constructor for an anonymous user.
202 * Use the User::newFrom* factory functions for other kinds of users.
206 * @see newFromConfirmationCode()
207 * @see newFromSession()
210 function __construct() {
211 $this->clearInstanceCache( 'defaults' );
214 function __toString(){
215 return $this->getName();
219 * Load the user table data for this object from the source given by mFrom.
222 if ( $this->mLoadedItems
=== true ) {
225 wfProfileIn( __METHOD__
);
227 # Set it now to avoid infinite recursion in accessors
228 $this->mLoadedItems
= true;
230 switch ( $this->mFrom
) {
232 $this->loadDefaults();
235 $this->mId
= self
::idFromName( $this->mName
);
237 # Nonexistent user placeholder object
238 $this->loadDefaults( $this->mName
);
247 $this->loadFromSession();
248 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
251 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
253 wfProfileOut( __METHOD__
);
257 * Load user table data, given mId has already been set.
258 * @return Bool false if the ID does not exist, true otherwise
261 function loadFromId() {
263 if ( $this->mId
== 0 ) {
264 $this->loadDefaults();
269 $key = wfMemcKey( 'user', 'id', $this->mId
);
270 $data = $wgMemc->get( $key );
271 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
272 # Object is expired, load from DB
277 wfDebug( "User: cache miss for user {$this->mId}\n" );
279 if ( !$this->loadFromDatabase() ) {
280 # Can't load from ID, user is anonymous
283 $this->saveToCache();
285 wfDebug( "User: got user {$this->mId} from cache\n" );
287 foreach ( self
::$mCacheVars as $name ) {
288 $this->$name = $data[$name];
295 * Save user data to the shared cache
297 function saveToCache() {
300 $this->loadOptions();
301 if ( $this->isAnon() ) {
302 // Anonymous users are uncached
306 foreach ( self
::$mCacheVars as $name ) {
307 $data[$name] = $this->$name;
309 $data['mVersion'] = MW_USER_VERSION
;
310 $key = wfMemcKey( 'user', 'id', $this->mId
);
312 $wgMemc->set( $key, $data );
316 /** @name newFrom*() static factory methods */
320 * Static factory method for creation from username.
322 * This is slightly less efficient than newFromId(), so use newFromId() if
323 * you have both an ID and a name handy.
325 * @param $name String Username, validated by Title::newFromText()
326 * @param $validate String|Bool Validate username. Takes the same parameters as
327 * User::getCanonicalName(), except that true is accepted as an alias
328 * for 'valid', for BC.
330 * @return User object, or false if the username is invalid
331 * (e.g. if it contains illegal characters or is an IP address). If the
332 * username is not present in the database, the result will be a user object
333 * with a name, zero user ID and default settings.
335 static function newFromName( $name, $validate = 'valid' ) {
336 if ( $validate === true ) {
339 $name = self
::getCanonicalName( $name, $validate );
340 if ( $name === false ) {
343 # Create unloaded user object
347 $u->setItemLoaded( 'name' );
353 * Static factory method for creation from a given user ID.
355 * @param $id Int Valid user ID
356 * @return User The corresponding User object
358 static function newFromId( $id ) {
362 $u->setItemLoaded( 'id' );
367 * Factory method to fetch whichever user has a given email confirmation code.
368 * This code is generated when an account is created or its e-mail address
371 * If the code is invalid or has expired, returns NULL.
373 * @param $code String Confirmation code
376 static function newFromConfirmationCode( $code ) {
377 $dbr = wfGetDB( DB_SLAVE
);
378 $id = $dbr->selectField( 'user', 'user_id', array(
379 'user_email_token' => md5( $code ),
380 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
382 if( $id !== false ) {
383 return User
::newFromId( $id );
390 * Create a new user object using data from session or cookies. If the
391 * login credentials are invalid, the result is an anonymous user.
395 static function newFromSession() {
397 $user->mFrom
= 'session';
402 * Create a new user object from a user row.
403 * The row should have the following fields from the user table in it:
404 * - either user_name or user_id to load further data if needed (or both)
406 * - all other fields (email, password, etc.)
407 * It is useless to provide the remaining fields if either user_id,
408 * user_name and user_real_name are not provided because the whole row
409 * will be loaded once more from the database when accessing them.
411 * @param $row Array A row from the user table
414 static function newFromRow( $row ) {
416 $user->loadFromRow( $row );
424 * Get the username corresponding to a given user ID
425 * @param $id Int User ID
426 * @return String The corresponding username
428 static function whoIs( $id ) {
429 $dbr = wfGetDB( DB_SLAVE
);
430 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), __METHOD__
);
434 * Get the real name of a user given their user ID
436 * @param $id Int User ID
437 * @return String The corresponding user's real name
439 static function whoIsReal( $id ) {
440 $dbr = wfGetDB( DB_SLAVE
);
441 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
445 * Get database id given a user name
446 * @param $name String Username
447 * @return Int|Null The corresponding user's ID, or null if user is nonexistent
449 static function idFromName( $name ) {
450 $nt = Title
::makeTitleSafe( NS_USER
, $name );
451 if( is_null( $nt ) ) {
456 if ( isset( self
::$idCacheByName[$name] ) ) {
457 return self
::$idCacheByName[$name];
460 $dbr = wfGetDB( DB_SLAVE
);
461 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
463 if ( $s === false ) {
466 $result = $s->user_id
;
469 self
::$idCacheByName[$name] = $result;
471 if ( count( self
::$idCacheByName ) > 1000 ) {
472 self
::$idCacheByName = array();
479 * Reset the cache used in idFromName(). For use in tests.
481 public static function resetIdByNameCache() {
482 self
::$idCacheByName = array();
486 * Does the string match an anonymous IPv4 address?
488 * This function exists for username validation, in order to reject
489 * usernames which are similar in form to IP addresses. Strings such
490 * as 300.300.300.300 will return true because it looks like an IP
491 * address, despite not being strictly valid.
493 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
494 * address because the usemod software would "cloak" anonymous IP
495 * addresses like this, if we allowed accounts like this to be created
496 * new users could get the old edits of these anonymous users.
498 * @param $name String to match
501 static function isIP( $name ) {
502 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP
::isIPv6($name);
506 * Is the input a valid username?
508 * Checks if the input is a valid username, we don't want an empty string,
509 * an IP address, anything that containins slashes (would mess up subpages),
510 * is longer than the maximum allowed username size or doesn't begin with
513 * @param $name String to match
516 static function isValidUserName( $name ) {
517 global $wgContLang, $wgMaxNameChars;
520 || User
::isIP( $name )
521 ||
strpos( $name, '/' ) !== false
522 ||
strlen( $name ) > $wgMaxNameChars
523 ||
$name != $wgContLang->ucfirst( $name ) ) {
524 wfDebugLog( 'username', __METHOD__
.
525 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
529 // Ensure that the name can't be misresolved as a different title,
530 // such as with extra namespace keys at the start.
531 $parsed = Title
::newFromText( $name );
532 if( is_null( $parsed )
533 ||
$parsed->getNamespace()
534 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
535 wfDebugLog( 'username', __METHOD__
.
536 ": '$name' invalid due to ambiguous prefixes" );
540 // Check an additional blacklist of troublemaker characters.
541 // Should these be merged into the title char list?
542 $unicodeBlacklist = '/[' .
543 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
544 '\x{00a0}' . # non-breaking space
545 '\x{2000}-\x{200f}' . # various whitespace
546 '\x{2028}-\x{202f}' . # breaks and control chars
547 '\x{3000}' . # ideographic space
548 '\x{e000}-\x{f8ff}' . # private use
550 if( preg_match( $unicodeBlacklist, $name ) ) {
551 wfDebugLog( 'username', __METHOD__
.
552 ": '$name' invalid due to blacklisted characters" );
560 * Usernames which fail to pass this function will be blocked
561 * from user login and new account registrations, but may be used
562 * internally by batch processes.
564 * If an account already exists in this form, login will be blocked
565 * by a failure to pass this function.
567 * @param $name String to match
570 static function isUsableName( $name ) {
571 global $wgReservedUsernames;
572 // Must be a valid username, obviously ;)
573 if ( !self
::isValidUserName( $name ) ) {
577 static $reservedUsernames = false;
578 if ( !$reservedUsernames ) {
579 $reservedUsernames = $wgReservedUsernames;
580 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
583 // Certain names may be reserved for batch processes.
584 foreach ( $reservedUsernames as $reserved ) {
585 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
586 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
588 if ( $reserved == $name ) {
596 * Usernames which fail to pass this function will be blocked
597 * from new account registrations, but may be used internally
598 * either by batch processes or by user accounts which have
599 * already been created.
601 * Additional blacklisting may be added here rather than in
602 * isValidUserName() to avoid disrupting existing accounts.
604 * @param $name String to match
607 static function isCreatableName( $name ) {
608 global $wgInvalidUsernameCharacters;
610 // Ensure that the username isn't longer than 235 bytes, so that
611 // (at least for the builtin skins) user javascript and css files
612 // will work. (bug 23080)
613 if( strlen( $name ) > 235 ) {
614 wfDebugLog( 'username', __METHOD__
.
615 ": '$name' invalid due to length" );
619 // Preg yells if you try to give it an empty string
620 if( $wgInvalidUsernameCharacters !== '' ) {
621 if( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
622 wfDebugLog( 'username', __METHOD__
.
623 ": '$name' invalid due to wgInvalidUsernameCharacters" );
628 return self
::isUsableName( $name );
632 * Is the input a valid password for this user?
634 * @param $password String Desired password
637 function isValidPassword( $password ) {
638 //simple boolean wrapper for getPasswordValidity
639 return $this->getPasswordValidity( $password ) === true;
643 * Given unvalidated password input, return error message on failure.
645 * @param $password String Desired password
646 * @return mixed: true on success, string or array of error message on failure
648 function getPasswordValidity( $password ) {
649 global $wgMinimalPasswordLength, $wgContLang;
651 static $blockedLogins = array(
652 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
653 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
656 $result = false; //init $result to false for the internal checks
658 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
661 if ( $result === false ) {
662 if( strlen( $password ) < $wgMinimalPasswordLength ) {
663 return 'passwordtooshort';
664 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
665 return 'password-name-match';
666 } elseif ( isset( $blockedLogins[ $this->getName() ] ) && $password == $blockedLogins[ $this->getName() ] ) {
667 return 'password-login-forbidden';
669 //it seems weird returning true here, but this is because of the
670 //initialization of $result to false above. If the hook is never run or it
671 //doesn't modify $result, then we will likely get down into this if with
675 } elseif( $result === true ) {
678 return $result; //the isValidPassword hook set a string $result and returned true
683 * Does a string look like an e-mail address?
685 * This validates an email address using an HTML5 specification found at:
686 * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
687 * Which as of 2011-01-24 says:
689 * A valid e-mail address is a string that matches the ABNF production
690 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
691 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
694 * This function is an implementation of the specification as requested in
697 * Client-side forms will use the same standard validation rules via JS or
698 * HTML 5 validation; additional restrictions can be enforced server-side
699 * by extensions via the 'isValidEmailAddr' hook.
701 * Note that this validation doesn't 100% match RFC 2822, but is believed
702 * to be liberal enough for wide use. Some invalid addresses will still
703 * pass validation here.
705 * @param $addr String E-mail address
707 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
709 public static function isValidEmailAddr( $addr ) {
710 return Sanitizer
::validateEmail( $addr );
714 * Given unvalidated user input, return a canonical username, or false if
715 * the username is invalid.
716 * @param $name String User input
717 * @param $validate String|Bool type of validation to use:
718 * - false No validation
719 * - 'valid' Valid for batch processes
720 * - 'usable' Valid for batch processes and login
721 * - 'creatable' Valid for batch processes, login and account creation
723 static function getCanonicalName( $name, $validate = 'valid' ) {
724 # Force usernames to capital
726 $name = $wgContLang->ucfirst( $name );
728 # Reject names containing '#'; these will be cleaned up
729 # with title normalisation, but then it's too late to
731 if( strpos( $name, '#' ) !== false )
734 # Clean up name according to title rules
735 $t = ( $validate === 'valid' ) ?
736 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
737 # Check for invalid titles
738 if( is_null( $t ) ) {
742 # Reject various classes of invalid names
744 $name = $wgAuth->getCanonicalName( $t->getText() );
746 switch ( $validate ) {
750 if ( !User
::isValidUserName( $name ) ) {
755 if ( !User
::isUsableName( $name ) ) {
760 if ( !User
::isCreatableName( $name ) ) {
765 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
771 * Count the number of edits of a user
772 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
774 * @param $uid Int User ID to check
775 * @return Int the user's edit count
777 static function edits( $uid ) {
778 wfProfileIn( __METHOD__
);
779 $dbr = wfGetDB( DB_SLAVE
);
780 // check if the user_editcount field has been initialized
781 $field = $dbr->selectField(
782 'user', 'user_editcount',
783 array( 'user_id' => $uid ),
787 if( $field === null ) { // it has not been initialized. do so.
788 $dbw = wfGetDB( DB_MASTER
);
789 $count = $dbr->selectField(
790 'revision', 'count(*)',
791 array( 'rev_user' => $uid ),
796 array( 'user_editcount' => $count ),
797 array( 'user_id' => $uid ),
803 wfProfileOut( __METHOD__
);
808 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
809 * @todo hash random numbers to improve security, like generateToken()
811 * @return String new random password
813 static function randomPassword() {
814 global $wgMinimalPasswordLength;
815 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
816 $l = strlen( $pwchars ) - 1;
818 $pwlength = max( 7, $wgMinimalPasswordLength );
819 $digit = mt_rand( 0, $pwlength - 1 );
821 for ( $i = 0; $i < $pwlength; $i++
) {
822 $np .= $i == $digit ?
chr( mt_rand( 48, 57 ) ) : $pwchars[ mt_rand( 0, $l ) ];
828 * Set cached properties to default.
830 * @note This no longer clears uncached lazy-initialised properties;
831 * the constructor does that instead.
834 function loadDefaults( $name = false ) {
835 wfProfileIn( __METHOD__
);
840 $this->mName
= $name;
841 $this->mRealName
= '';
842 $this->mPassword
= $this->mNewpassword
= '';
843 $this->mNewpassTime
= null;
845 $this->mOptionOverrides
= null;
846 $this->mOptionsLoaded
= false;
848 if( $wgRequest->getCookie( 'LoggedOut' ) !== null ) {
849 $this->mTouched
= wfTimestamp( TS_MW
, $wgRequest->getCookie( 'LoggedOut' ) );
851 $this->mTouched
= '0'; # Allow any pages to be cached
854 $this->setToken(); # Random
855 $this->mEmailAuthenticated
= null;
856 $this->mEmailToken
= '';
857 $this->mEmailTokenExpires
= null;
858 $this->mRegistration
= wfTimestamp( TS_MW
);
859 $this->mGroups
= array();
861 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
863 wfProfileOut( __METHOD__
);
867 * Return whether an item has been loaded.
869 * @param $item String: item to check. Current possibilities:
873 * @param $all String: 'all' to check if the whole object has been loaded
874 * or any other string to check if only the item is available (e.g.
878 public function isItemLoaded( $item, $all = 'all' ) {
879 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
880 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
884 * Set that an item has been loaded
886 * @param $item String
888 private function setItemLoaded( $item ) {
889 if ( is_array( $this->mLoadedItems
) ) {
890 $this->mLoadedItems
[$item] = true;
895 * Load user data from the session or login cookie. If there are no valid
896 * credentials, initialises the user as an anonymous user.
897 * @return Bool True if the user is logged in, false otherwise.
899 private function loadFromSession() {
900 global $wgRequest, $wgExternalAuthType, $wgAutocreatePolicy;
903 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
904 if ( $result !== null ) {
908 if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
909 $extUser = ExternalUser
::newFromCookie();
911 # TODO: Automatically create the user here (or probably a bit
912 # lower down, in fact)
916 $cookieId = $wgRequest->getCookie( 'UserID' );
917 $sessId = $wgRequest->getSessionData( 'wsUserID' );
919 if ( $cookieId !== null ) {
920 $sId = intval( $cookieId );
921 if( $sessId !== null && $cookieId != $sessId ) {
922 $this->loadDefaults(); // Possible collision!
923 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
924 cookie user ID ($sId) don't match!" );
927 $wgRequest->setSessionData( 'wsUserID', $sId );
928 } elseif ( $sessId !== null && $sessId != 0 ) {
931 $this->loadDefaults();
935 if ( $wgRequest->getSessionData( 'wsUserName' ) !== null ) {
936 $sName = $wgRequest->getSessionData( 'wsUserName' );
937 } elseif ( $wgRequest->getCookie( 'UserName' ) !== null ) {
938 $sName = $wgRequest->getCookie( 'UserName' );
939 $wgRequest->setSessionData( 'wsUserName', $sName );
941 $this->loadDefaults();
945 $proposedUser = User
::newFromId( $sId );
946 if ( !$proposedUser->isLoggedIn() ) {
948 $this->loadDefaults();
952 global $wgBlockDisablesLogin;
953 if( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
954 # User blocked and we've disabled blocked user logins
955 $this->loadDefaults();
959 if ( $wgRequest->getSessionData( 'wsToken' ) !== null ) {
960 $passwordCorrect = $proposedUser->getToken() === $wgRequest->getSessionData( 'wsToken' );
962 } elseif ( $wgRequest->getCookie( 'Token' ) !== null ) {
963 $passwordCorrect = $proposedUser->getToken() === $wgRequest->getCookie( 'Token' );
966 # No session or persistent login cookie
967 $this->loadDefaults();
971 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
972 $this->loadFromUserObject( $proposedUser );
973 $wgRequest->setSessionData( 'wsToken', $this->mToken
);
974 wfDebug( "User: logged in from $from\n" );
977 # Invalid credentials
978 wfDebug( "User: can't log in from $from, invalid credentials\n" );
979 $this->loadDefaults();
985 * Load user and user_group data from the database.
986 * $this->mId must be set, this is how the user is identified.
988 * @return Bool True if the user exists, false if the user is anonymous
991 function loadFromDatabase() {
993 $this->mId
= intval( $this->mId
);
995 /** Anonymous user */
997 $this->loadDefaults();
1001 $dbr = wfGetDB( DB_MASTER
);
1002 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
1004 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1006 if ( $s !== false ) {
1007 # Initialise user table data
1008 $this->loadFromRow( $s );
1009 $this->mGroups
= null; // deferred
1010 $this->getEditCount(); // revalidation for nulls
1015 $this->loadDefaults();
1021 * Initialize this object from a row from the user table.
1023 * @param $row Array Row from the user table to load.
1025 function loadFromRow( $row ) {
1028 if ( isset( $row->user_name
) ) {
1029 $this->mName
= $row->user_name
;
1030 $this->mFrom
= 'name';
1031 $this->setItemLoaded( 'name' );
1036 if ( isset( $row->user_real_name
) ) {
1037 $this->mRealName
= $row->user_real_name
;
1038 $this->setItemLoaded( 'realname' );
1043 if ( isset( $row->user_id
) ) {
1044 $this->mId
= intval( $row->user_id
);
1045 $this->mFrom
= 'id';
1046 $this->setItemLoaded( 'id' );
1051 if ( isset( $row->user_password
) ) {
1052 $this->mPassword
= $row->user_password
;
1053 $this->mNewpassword
= $row->user_newpassword
;
1054 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1055 $this->mEmail
= $row->user_email
;
1056 $this->decodeOptions( $row->user_options
);
1057 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
1058 $this->mToken
= $row->user_token
;
1059 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1060 $this->mEmailToken
= $row->user_email_token
;
1061 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1062 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1063 $this->mEditCount
= $row->user_editcount
;
1069 $this->mLoadedItems
= true;
1074 * Load the data for this user object from another user object.
1078 protected function loadFromUserObject( $user ) {
1080 $user->loadGroups();
1081 $user->loadOptions();
1082 foreach ( self
::$mCacheVars as $var ) {
1083 $this->$var = $user->$var;
1088 * Load the groups from the database if they aren't already loaded.
1091 function loadGroups() {
1092 if ( is_null( $this->mGroups
) ) {
1093 $dbr = wfGetDB( DB_MASTER
);
1094 $res = $dbr->select( 'user_groups',
1095 array( 'ug_group' ),
1096 array( 'ug_user' => $this->mId
),
1098 $this->mGroups
= array();
1099 foreach ( $res as $row ) {
1100 $this->mGroups
[] = $row->ug_group
;
1106 * Add the user to the group if he/she meets given criteria.
1108 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1109 * possible to remove manually via Special:UserRights. In such case it
1110 * will not be re-added autmoatically. The user will also not lose the
1111 * group if they no longer meet the criteria.
1113 * @param $criteria array Groups and conditions the user must meet in order
1114 * to be promoted to these groups. Array of the same format as
1115 * \ref $wgAutopromote.
1117 * @return array Array of groups the user has been promoted to.
1119 * @see $wgAutopromote
1120 * @see Autopromote::autopromoteOnceHook()
1122 public function autopromoteOnce( $criteria ) {
1123 if ($this->getId()) {
1124 $toPromote = Autopromote
::getAutopromoteOnceGroups($this, $criteria);
1125 foreach($toPromote as $group)
1126 $this->addGroup($group);
1133 * Clear various cached data stored in this object.
1134 * @param $reloadFrom String Reload user and user_groups table data from a
1135 * given source. May be "name", "id", "defaults", "session", or false for
1138 function clearInstanceCache( $reloadFrom = false ) {
1139 $this->mNewtalk
= -1;
1140 $this->mDatePreference
= null;
1141 $this->mBlockedby
= -1; # Unset
1142 $this->mHash
= false;
1143 $this->mSkin
= null;
1144 $this->mRights
= null;
1145 $this->mEffectiveGroups
= null;
1146 $this->mOptions
= null;
1148 if ( $reloadFrom ) {
1149 $this->mLoadedItems
= array();
1150 $this->mFrom
= $reloadFrom;
1155 * Combine the language default options with any site-specific options
1156 * and add the default language variants.
1158 * @return Array of String options
1160 static function getDefaultOptions() {
1161 global $wgNamespacesToBeSearchedDefault;
1163 * Site defaults will override the global/language defaults
1165 global $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1166 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
1169 * default language setting
1171 $variant = $wgContLang->getDefaultVariant();
1172 $defOpt['variant'] = $variant;
1173 $defOpt['language'] = $variant;
1174 foreach( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1175 $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1177 $defOpt['skin'] = $wgDefaultSkin;
1183 * Get a given default option value.
1185 * @param $opt String Name of option to retrieve
1186 * @return String Default option value
1188 public static function getDefaultOption( $opt ) {
1189 $defOpts = self
::getDefaultOptions();
1190 if( isset( $defOpts[$opt] ) ) {
1191 return $defOpts[$opt];
1199 * Get blocking information
1201 * @param $bFromSlave Bool Whether to check the slave database first. To
1202 * improve performance, non-critical checks are done
1203 * against slaves. Check when actually saving should be
1204 * done against master.
1206 function getBlockedStatus( $bFromSlave = true ) {
1207 global $wgProxyWhitelist, $wgUser;
1209 if ( -1 != $this->mBlockedby
) {
1213 wfProfileIn( __METHOD__
);
1214 wfDebug( __METHOD__
.": checking...\n" );
1216 // Initialize data...
1217 // Otherwise something ends up stomping on $this->mBlockedby when
1218 // things get lazy-loaded later, causing false positive block hits
1219 // due to -1 !== 0. Probably session-related... Nothing should be
1220 // overwriting mBlockedby, surely?
1223 $this->mBlockedby
= 0;
1224 $this->mHideName
= 0;
1225 $this->mAllowUsertalk
= 0;
1227 # We only need to worry about passing the IP address to the Block generator if the
1228 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1229 # know which IP address they're actually coming from
1230 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1237 $this->mBlock
= Block
::newFromTarget( $this->getName(), $ip, !$bFromSlave );
1238 if ( $this->mBlock
instanceof Block
) {
1239 wfDebug( __METHOD__
. ": Found block.\n" );
1240 $this->mBlockedby
= $this->mBlock
->getBlocker()->getName();
1241 $this->mBlockreason
= $this->mBlock
->mReason
;
1242 $this->mHideName
= $this->mBlock
->mHideName
;
1243 $this->mAllowUsertalk
= !$this->mBlock
->prevents( 'editownusertalk' );
1244 if ( $this->isLoggedIn() && $wgUser->getID() == $this->getID() ) {
1245 $this->spreadBlock();
1250 if ( $ip !== null && !$this->isAllowed( 'proxyunbannable' ) && !in_array( $ip, $wgProxyWhitelist ) ) {
1252 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1253 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1254 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1258 if ( !$this->mBlockedby
&& !$this->getID() ) {
1259 if ( $this->isDnsBlacklisted( $ip ) ) {
1260 $this->mBlockedby
= wfMsg( 'sorbs' );
1261 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1267 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1269 wfProfileOut( __METHOD__
);
1273 * Whether the given IP is in a DNS blacklist.
1275 * @param $ip String IP to check
1276 * @param $checkWhitelist Bool: whether to check the whitelist first
1277 * @return Bool True if blacklisted.
1279 function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1280 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1281 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1283 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
1286 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
1289 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1290 return $this->inDnsBlacklist( $ip, $urls );
1294 * Whether the given IP is in a given DNS blacklist.
1296 * @param $ip String IP to check
1297 * @param $bases String|Array of Strings: URL of the DNS blacklist
1298 * @return Bool True if blacklisted.
1300 function inDnsBlacklist( $ip, $bases ) {
1301 wfProfileIn( __METHOD__
);
1304 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1305 if( IP
::isIPv4( $ip ) ) {
1306 # Reverse IP, bug 21255
1307 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1309 foreach( (array)$bases as $base ) {
1311 $host = "$ipReversed.$base";
1314 $ipList = gethostbynamel( $host );
1317 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1321 wfDebug( "Requested $host, not found in $base.\n" );
1326 wfProfileOut( __METHOD__
);
1331 * Check if an IP address is in the local proxy list
1334 public static function isLocallyBlockedProxy( $ip ) {
1335 global $wgProxyList;
1337 if ( !$wgProxyList ) {
1340 wfProfileIn( __METHOD__
);
1342 if ( !is_array( $wgProxyList ) ) {
1343 # Load from the specified file
1344 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1347 if ( !is_array( $wgProxyList ) ) {
1349 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1351 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1352 # Old-style flipped proxy list
1357 wfProfileOut( __METHOD__
);
1362 * Is this user subject to rate limiting?
1364 * @return Bool True if rate limited
1366 public function isPingLimitable() {
1367 global $wgRateLimitsExcludedIPs;
1368 if( in_array( wfGetIP(), $wgRateLimitsExcludedIPs ) ) {
1369 // No other good way currently to disable rate limits
1370 // for specific IPs. :P
1371 // But this is a crappy hack and should die.
1374 return !$this->isAllowed('noratelimit');
1378 * Primitive rate limits: enforce maximum actions per time period
1379 * to put a brake on flooding.
1381 * @note When using a shared cache like memcached, IP-address
1382 * last-hit counters will be shared across wikis.
1384 * @param $action String Action to enforce; 'edit' if unspecified
1385 * @return Bool True if a rate limiter was tripped
1387 function pingLimiter( $action = 'edit' ) {
1388 # Call the 'PingLimiter' hook
1390 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1394 global $wgRateLimits;
1395 if( !isset( $wgRateLimits[$action] ) ) {
1399 # Some groups shouldn't trigger the ping limiter, ever
1400 if( !$this->isPingLimitable() )
1403 global $wgMemc, $wgRateLimitLog;
1404 wfProfileIn( __METHOD__
);
1406 $limits = $wgRateLimits[$action];
1408 $id = $this->getId();
1412 if( isset( $limits['anon'] ) && $id == 0 ) {
1413 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1416 if( isset( $limits['user'] ) && $id != 0 ) {
1417 $userLimit = $limits['user'];
1419 if( $this->isNewbie() ) {
1420 if( isset( $limits['newbie'] ) && $id != 0 ) {
1421 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1423 if( isset( $limits['ip'] ) ) {
1424 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1427 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1428 $subnet = $matches[1];
1429 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1432 // Check for group-specific permissions
1433 // If more than one group applies, use the group with the highest limit
1434 foreach ( $this->getGroups() as $group ) {
1435 if ( isset( $limits[$group] ) ) {
1436 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1437 $userLimit = $limits[$group];
1441 // Set the user limit key
1442 if ( $userLimit !== false ) {
1443 wfDebug( __METHOD__
. ": effective user limit: $userLimit\n" );
1444 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1448 foreach( $keys as $key => $limit ) {
1449 list( $max, $period ) = $limit;
1450 $summary = "(limit $max in {$period}s)";
1451 $count = $wgMemc->get( $key );
1454 if( $count > $max ) {
1455 wfDebug( __METHOD__
. ": tripped! $key at $count $summary\n" );
1456 if( $wgRateLimitLog ) {
1457 @file_put_contents
( $wgRateLimitLog, wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", FILE_APPEND
);
1461 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1464 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1465 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1467 $wgMemc->incr( $key );
1470 wfProfileOut( __METHOD__
);
1475 * Check if user is blocked
1477 * @param $bFromSlave Bool Whether to check the slave database instead of the master
1478 * @return Bool True if blocked, false otherwise
1480 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1481 $this->getBlockedStatus( $bFromSlave );
1482 return $this->mBlock
instanceof Block
&& $this->mBlock
->prevents( 'edit' );
1486 * Check if user is blocked from editing a particular article
1488 * @param $title Title to check
1489 * @param $bFromSlave Bool whether to check the slave database instead of the master
1492 function isBlockedFrom( $title, $bFromSlave = false ) {
1493 global $wgBlockAllowsUTEdit;
1494 wfProfileIn( __METHOD__
);
1496 $blocked = $this->isBlocked( $bFromSlave );
1497 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1498 # If a user's name is suppressed, they cannot make edits anywhere
1499 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1500 $title->getNamespace() == NS_USER_TALK
) {
1502 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1505 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1507 wfProfileOut( __METHOD__
);
1512 * If user is blocked, return the name of the user who placed the block
1513 * @return String name of blocker
1515 function blockedBy() {
1516 $this->getBlockedStatus();
1517 return $this->mBlockedby
;
1521 * If user is blocked, return the specified reason for the block
1522 * @return String Blocking reason
1524 function blockedFor() {
1525 $this->getBlockedStatus();
1526 return $this->mBlockreason
;
1530 * If user is blocked, return the ID for the block
1531 * @return Int Block ID
1533 function getBlockId() {
1534 $this->getBlockedStatus();
1535 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1539 * Check if user is blocked on all wikis.
1540 * Do not use for actual edit permission checks!
1541 * This is intented for quick UI checks.
1543 * @param $ip String IP address, uses current client if none given
1544 * @return Bool True if blocked, false otherwise
1546 function isBlockedGlobally( $ip = '' ) {
1547 if( $this->mBlockedGlobally
!== null ) {
1548 return $this->mBlockedGlobally
;
1550 // User is already an IP?
1551 if( IP
::isIPAddress( $this->getName() ) ) {
1552 $ip = $this->getName();
1557 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1558 $this->mBlockedGlobally
= (bool)$blocked;
1559 return $this->mBlockedGlobally
;
1563 * Check if user account is locked
1565 * @return Bool True if locked, false otherwise
1567 function isLocked() {
1568 if( $this->mLocked
!== null ) {
1569 return $this->mLocked
;
1572 $authUser = $wgAuth->getUserInstance( $this );
1573 $this->mLocked
= (bool)$authUser->isLocked();
1574 return $this->mLocked
;
1578 * Check if user account is hidden
1580 * @return Bool True if hidden, false otherwise
1582 function isHidden() {
1583 if( $this->mHideName
!== null ) {
1584 return $this->mHideName
;
1586 $this->getBlockedStatus();
1587 if( !$this->mHideName
) {
1589 $authUser = $wgAuth->getUserInstance( $this );
1590 $this->mHideName
= (bool)$authUser->isHidden();
1592 return $this->mHideName
;
1596 * Get the user's ID.
1597 * @return Int The user's ID; 0 if the user is anonymous or nonexistent
1600 if( $this->mId
=== null && $this->mName
!== null
1601 && User
::isIP( $this->mName
) ) {
1602 // Special case, we know the user is anonymous
1604 } elseif( !$this->isItemLoaded( 'id' ) ) {
1605 // Don't load if this was initialized from an ID
1612 * Set the user and reload all fields according to a given ID
1613 * @param $v Int User ID to reload
1615 function setId( $v ) {
1617 $this->clearInstanceCache( 'id' );
1621 * Get the user name, or the IP of an anonymous user
1622 * @return String User's name or IP address
1624 function getName() {
1625 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1626 # Special case optimisation
1627 return $this->mName
;
1630 if ( $this->mName
=== false ) {
1632 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1634 return $this->mName
;
1639 * Set the user name.
1641 * This does not reload fields from the database according to the given
1642 * name. Rather, it is used to create a temporary "nonexistent user" for
1643 * later addition to the database. It can also be used to set the IP
1644 * address for an anonymous user to something other than the current
1647 * @note User::newFromName() has rougly the same function, when the named user
1649 * @param $str String New user name to set
1651 function setName( $str ) {
1653 $this->mName
= $str;
1657 * Get the user's name escaped by underscores.
1658 * @return String Username escaped by underscores.
1660 function getTitleKey() {
1661 return str_replace( ' ', '_', $this->getName() );
1665 * Check if the user has new messages.
1666 * @return Bool True if the user has new messages
1668 function getNewtalk() {
1671 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1672 if( $this->mNewtalk
=== -1 ) {
1673 $this->mNewtalk
= false; # reset talk page status
1675 # Check memcached separately for anons, who have no
1676 # entire User object stored in there.
1679 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1680 $newtalk = $wgMemc->get( $key );
1681 if( strval( $newtalk ) !== '' ) {
1682 $this->mNewtalk
= (bool)$newtalk;
1684 // Since we are caching this, make sure it is up to date by getting it
1686 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1687 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1690 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1694 return (bool)$this->mNewtalk
;
1698 * Return the talk page(s) this user has new messages on.
1699 * @return Array of String page URLs
1701 function getNewMessageLinks() {
1703 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) )
1706 if( !$this->getNewtalk() )
1708 $up = $this->getUserPage();
1709 $utp = $up->getTalkPage();
1710 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL() ) );
1714 * Internal uncached check for new messages
1717 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1718 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1719 * @param $fromMaster Bool true to fetch from the master, false for a slave
1720 * @return Bool True if the user has new messages
1722 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
1723 if ( $fromMaster ) {
1724 $db = wfGetDB( DB_MASTER
);
1726 $db = wfGetDB( DB_SLAVE
);
1728 $ok = $db->selectField( 'user_newtalk', $field,
1729 array( $field => $id ), __METHOD__
);
1730 return $ok !== false;
1734 * Add or update the new messages flag
1735 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1736 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1737 * @return Bool True if successful, false otherwise
1739 protected function updateNewtalk( $field, $id ) {
1740 $dbw = wfGetDB( DB_MASTER
);
1741 $dbw->insert( 'user_newtalk',
1742 array( $field => $id ),
1745 if ( $dbw->affectedRows() ) {
1746 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
1749 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
1755 * Clear the new messages flag for the given user
1756 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1757 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1758 * @return Bool True if successful, false otherwise
1760 protected function deleteNewtalk( $field, $id ) {
1761 $dbw = wfGetDB( DB_MASTER
);
1762 $dbw->delete( 'user_newtalk',
1763 array( $field => $id ),
1765 if ( $dbw->affectedRows() ) {
1766 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
1769 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
1775 * Update the 'You have new messages!' status.
1776 * @param $val Bool Whether the user has new messages
1778 function setNewtalk( $val ) {
1779 if( wfReadOnly() ) {
1784 $this->mNewtalk
= $val;
1786 if( $this->isAnon() ) {
1788 $id = $this->getName();
1791 $id = $this->getId();
1796 $changed = $this->updateNewtalk( $field, $id );
1798 $changed = $this->deleteNewtalk( $field, $id );
1801 if( $this->isAnon() ) {
1802 // Anons have a separate memcached space, since
1803 // user records aren't kept for them.
1804 $key = wfMemcKey( 'newtalk', 'ip', $id );
1805 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1808 $this->invalidateCache();
1813 * Generate a current or new-future timestamp to be stored in the
1814 * user_touched field when we update things.
1815 * @return String Timestamp in TS_MW format
1817 private static function newTouchedTimestamp() {
1818 global $wgClockSkewFudge;
1819 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1823 * Clear user data from memcached.
1824 * Use after applying fun updates to the database; caller's
1825 * responsibility to update user_touched if appropriate.
1827 * Called implicitly from invalidateCache() and saveSettings().
1829 private function clearSharedCache() {
1833 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1838 * Immediately touch the user data cache for this account.
1839 * Updates user_touched field, and removes account data from memcached
1840 * for reload on the next hit.
1842 function invalidateCache() {
1843 if( wfReadOnly() ) {
1848 $this->mTouched
= self
::newTouchedTimestamp();
1850 $dbw = wfGetDB( DB_MASTER
);
1851 $dbw->update( 'user',
1852 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1853 array( 'user_id' => $this->mId
),
1856 $this->clearSharedCache();
1861 * Validate the cache for this account.
1862 * @param $timestamp String A timestamp in TS_MW format
1864 function validateCache( $timestamp ) {
1866 return ( $timestamp >= $this->mTouched
);
1870 * Get the user touched timestamp
1871 * @return String timestamp
1873 function getTouched() {
1875 return $this->mTouched
;
1879 * Set the password and reset the random token.
1880 * Calls through to authentication plugin if necessary;
1881 * will have no effect if the auth plugin refuses to
1882 * pass the change through or if the legal password
1885 * As a special case, setting the password to null
1886 * wipes it, so the account cannot be logged in until
1887 * a new password is set, for instance via e-mail.
1889 * @param $str String New password to set
1890 * @throws PasswordError on failure
1892 function setPassword( $str ) {
1895 if( $str !== null ) {
1896 if( !$wgAuth->allowPasswordChange() ) {
1897 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1900 if( !$this->isValidPassword( $str ) ) {
1901 global $wgMinimalPasswordLength;
1902 $valid = $this->getPasswordValidity( $str );
1903 if ( is_array( $valid ) ) {
1904 $message = array_shift( $valid );
1908 $params = array( $wgMinimalPasswordLength );
1910 throw new PasswordError( wfMsgExt( $message, array( 'parsemag' ), $params ) );
1914 if( !$wgAuth->setPassword( $this, $str ) ) {
1915 throw new PasswordError( wfMsg( 'externaldberror' ) );
1918 $this->setInternalPassword( $str );
1924 * Set the password and reset the random token unconditionally.
1926 * @param $str String New password to set
1928 function setInternalPassword( $str ) {
1932 if( $str === null ) {
1933 // Save an invalid hash...
1934 $this->mPassword
= '';
1936 $this->mPassword
= self
::crypt( $str );
1938 $this->mNewpassword
= '';
1939 $this->mNewpassTime
= null;
1943 * Get the user's current token.
1944 * @return String Token
1946 function getToken() {
1948 return $this->mToken
;
1952 * Set the random token (used for persistent authentication)
1953 * Called from loadDefaults() among other places.
1955 * @param $token String If specified, set the token to this value
1958 function setToken( $token = false ) {
1959 global $wgSecretKey, $wgProxyKey;
1962 if ( $wgSecretKey ) {
1963 $key = $wgSecretKey;
1964 } elseif ( $wgProxyKey ) {
1969 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1971 $this->mToken
= $token;
1976 * Set the cookie password
1978 * @param $str String New cookie password
1981 function setCookiePassword( $str ) {
1983 $this->mCookiePassword
= md5( $str );
1987 * Set the password for a password reminder or new account email
1989 * @param $str String New password to set
1990 * @param $throttle Bool If true, reset the throttle timestamp to the present
1992 function setNewpassword( $str, $throttle = true ) {
1994 $this->mNewpassword
= self
::crypt( $str );
1996 $this->mNewpassTime
= wfTimestampNow();
2001 * Has password reminder email been sent within the last
2002 * $wgPasswordReminderResendTime hours?
2005 function isPasswordReminderThrottled() {
2006 global $wgPasswordReminderResendTime;
2008 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2011 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2012 return time() < $expiry;
2016 * Get the user's e-mail address
2017 * @return String User's email address
2019 function getEmail() {
2021 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
2022 return $this->mEmail
;
2026 * Get the timestamp of the user's e-mail authentication
2027 * @return String TS_MW timestamp
2029 function getEmailAuthenticationTimestamp() {
2031 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2032 return $this->mEmailAuthenticated
;
2036 * Set the user's e-mail address
2037 * @param $str String New e-mail address
2039 function setEmail( $str ) {
2041 $this->mEmail
= $str;
2042 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
2046 * Get the user's real name
2047 * @return String User's real name
2049 function getRealName() {
2050 if ( !$this->isItemLoaded( 'realname' ) ) {
2054 return $this->mRealName
;
2058 * Set the user's real name
2059 * @param $str String New real name
2061 function setRealName( $str ) {
2063 $this->mRealName
= $str;
2067 * Get the user's current setting for a given option.
2069 * @param $oname String The option to check
2070 * @param $defaultOverride String A default value returned if the option does not exist
2071 * @param $ignoreHidden Bool = whether to ignore the effects of $wgHiddenPrefs
2072 * @return String User's current value for the option
2073 * @see getBoolOption()
2074 * @see getIntOption()
2076 function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2077 global $wgHiddenPrefs;
2078 $this->loadOptions();
2080 if ( is_null( $this->mOptions
) ) {
2081 if($defaultOverride != '') {
2082 return $defaultOverride;
2084 $this->mOptions
= User
::getDefaultOptions();
2087 # We want 'disabled' preferences to always behave as the default value for
2088 # users, even if they have set the option explicitly in their settings (ie they
2089 # set it, and then it was disabled removing their ability to change it). But
2090 # we don't want to erase the preferences in the database in case the preference
2091 # is re-enabled again. So don't touch $mOptions, just override the returned value
2092 if( in_array( $oname, $wgHiddenPrefs ) && !$ignoreHidden ){
2093 return self
::getDefaultOption( $oname );
2096 if ( array_key_exists( $oname, $this->mOptions
) ) {
2097 return $this->mOptions
[$oname];
2099 return $defaultOverride;
2104 * Get all user's options
2108 public function getOptions() {
2109 global $wgHiddenPrefs;
2110 $this->loadOptions();
2111 $options = $this->mOptions
;
2113 # We want 'disabled' preferences to always behave as the default value for
2114 # users, even if they have set the option explicitly in their settings (ie they
2115 # set it, and then it was disabled removing their ability to change it). But
2116 # we don't want to erase the preferences in the database in case the preference
2117 # is re-enabled again. So don't touch $mOptions, just override the returned value
2118 foreach( $wgHiddenPrefs as $pref ){
2119 $default = self
::getDefaultOption( $pref );
2120 if( $default !== null ){
2121 $options[$pref] = $default;
2129 * Get the user's current setting for a given option, as a boolean value.
2131 * @param $oname String The option to check
2132 * @return Bool User's current value for the option
2135 function getBoolOption( $oname ) {
2136 return (bool)$this->getOption( $oname );
2141 * Get the user's current setting for a given option, as a boolean value.
2143 * @param $oname String The option to check
2144 * @param $defaultOverride Int A default value returned if the option does not exist
2145 * @return Int User's current value for the option
2148 function getIntOption( $oname, $defaultOverride=0 ) {
2149 $val = $this->getOption( $oname );
2151 $val = $defaultOverride;
2153 return intval( $val );
2157 * Set the given option for a user.
2159 * @param $oname String The option to set
2160 * @param $val mixed New value to set
2162 function setOption( $oname, $val ) {
2164 $this->loadOptions();
2166 if ( $oname == 'skin' ) {
2167 # Clear cached skin, so the new one displays immediately in Special:Preferences
2168 $this->mSkin
= null;
2171 // Explicitly NULL values should refer to defaults
2172 global $wgDefaultUserOptions;
2173 if( is_null( $val ) && isset( $wgDefaultUserOptions[$oname] ) ) {
2174 $val = $wgDefaultUserOptions[$oname];
2177 $this->mOptions
[$oname] = $val;
2181 * Reset all options to the site defaults
2183 function resetOptions() {
2184 $this->mOptions
= self
::getDefaultOptions();
2188 * Get the user's preferred date format.
2189 * @return String User's preferred date format
2191 function getDatePreference() {
2192 // Important migration for old data rows
2193 if ( is_null( $this->mDatePreference
) ) {
2195 $value = $this->getOption( 'date' );
2196 $map = $wgLang->getDatePreferenceMigrationMap();
2197 if ( isset( $map[$value] ) ) {
2198 $value = $map[$value];
2200 $this->mDatePreference
= $value;
2202 return $this->mDatePreference
;
2206 * Get the user preferred stub threshold
2208 function getStubThreshold() {
2209 global $wgMaxArticleSize; # Maximum article size, in Kb
2210 $threshold = intval( $this->getOption( 'stubthreshold' ) );
2211 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2212 # If they have set an impossible value, disable the preference
2213 # so we can use the parser cache again.
2220 * Get the permissions this user has.
2221 * @return Array of String permission names
2223 function getRights() {
2224 if ( is_null( $this->mRights
) ) {
2225 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2226 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2227 // Force reindexation of rights when a hook has unset one of them
2228 $this->mRights
= array_values( $this->mRights
);
2230 return $this->mRights
;
2234 * Get the list of explicit group memberships this user has.
2235 * The implicit * and user groups are not included.
2236 * @return Array of String internal group names
2238 function getGroups() {
2240 return $this->mGroups
;
2244 * Get the list of implicit group memberships this user has.
2245 * This includes all explicit groups, plus 'user' if logged in,
2246 * '*' for all accounts, and autopromoted groups
2247 * @param $recache Bool Whether to avoid the cache
2248 * @return Array of String internal group names
2250 function getEffectiveGroups( $recache = false ) {
2251 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2252 wfProfileIn( __METHOD__
);
2253 $this->mEffectiveGroups
= $this->getGroups();
2254 $this->mEffectiveGroups
[] = '*';
2255 if( $this->getId() ) {
2256 $this->mEffectiveGroups
[] = 'user';
2258 $this->mEffectiveGroups
= array_unique( array_merge(
2259 $this->mEffectiveGroups
,
2260 Autopromote
::getAutopromoteGroups( $this )
2263 # Hook for additional groups
2264 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2266 wfProfileOut( __METHOD__
);
2268 return $this->mEffectiveGroups
;
2272 * Returns the groups the user has belonged to.
2274 * The user may still belong to the returned groups. Compare with getGroups().
2276 * The function will not return groups the user had belonged to before MW 1.17
2278 * @return array Names of the groups the user has belonged to.
2280 function getFormerGroups() {
2281 if(is_null($this->mFormerGroups
)) {
2282 $dbr = wfGetDB( DB_MASTER
);
2283 $res = $dbr->select( 'user_former_groups',
2284 array( 'ufg_group' ),
2285 array( 'ufg_user' => $this->mId
),
2287 $this->mFormerGroups
= array();
2288 while( $row = $dbr->fetchObject( $res ) ) {
2289 $this->mFormerGroups
[] = $row->ufg_group
;
2292 return $this->mFormerGroups
;
2296 * Get the user's edit count.
2299 function getEditCount() {
2300 if( $this->getId() ) {
2301 if ( !isset( $this->mEditCount
) ) {
2302 /* Populate the count, if it has not been populated yet */
2303 $this->mEditCount
= User
::edits( $this->mId
);
2305 return $this->mEditCount
;
2313 * Add the user to the given group.
2314 * This takes immediate effect.
2315 * @param $group String Name of the group to add
2317 function addGroup( $group ) {
2318 if( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2319 $dbw = wfGetDB( DB_MASTER
);
2320 if( $this->getId() ) {
2321 $dbw->insert( 'user_groups',
2323 'ug_user' => $this->getID(),
2324 'ug_group' => $group,
2327 array( 'IGNORE' ) );
2330 $this->loadGroups();
2331 $this->mGroups
[] = $group;
2332 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2334 $this->invalidateCache();
2338 * Remove the user from the given group.
2339 * This takes immediate effect.
2340 * @param $group String Name of the group to remove
2342 function removeGroup( $group ) {
2344 if( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2345 $dbw = wfGetDB( DB_MASTER
);
2346 $dbw->delete( 'user_groups',
2348 'ug_user' => $this->getID(),
2349 'ug_group' => $group,
2351 //remember that the user has had this group
2352 $dbw->insert( 'user_former_groups',
2354 'ufg_user' => $this->getID(),
2355 'ufg_group' => $group,
2358 array( 'IGNORE' ) );
2360 $this->loadGroups();
2361 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2362 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2364 $this->invalidateCache();
2368 * Get whether the user is logged in
2371 function isLoggedIn() {
2372 return $this->getID() != 0;
2376 * Get whether the user is anonymous
2380 return !$this->isLoggedIn();
2384 * Check if user is allowed to access a feature / make an action
2385 * @param varargs String permissions to test
2386 * @return Boolean: True if user is allowed to perform *any* of the given actions
2388 public function isAllowedAny( /*...*/ ){
2389 $permissions = func_get_args();
2390 foreach( $permissions as $permission ){
2391 if( $this->isAllowed( $permission ) ){
2399 * @param varargs String
2400 * @return bool True if the user is allowed to perform *all* of the given actions
2402 public function isAllowedAll( /*...*/ ){
2403 $permissions = func_get_args();
2404 foreach( $permissions as $permission ){
2405 if( !$this->isAllowed( $permission ) ){
2413 * Internal mechanics of testing a permission
2414 * @param $action String
2417 public function isAllowed( $action = '' ) {
2418 if ( $action === '' ) {
2419 return true; // In the spirit of DWIM
2421 # Patrolling may not be enabled
2422 if( $action === 'patrol' ||
$action === 'autopatrol' ) {
2423 global $wgUseRCPatrol, $wgUseNPPatrol;
2424 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2427 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2428 # by misconfiguration: 0 == 'foo'
2429 return in_array( $action, $this->getRights(), true );
2433 * Check whether to enable recent changes patrol features for this user
2434 * @return Boolean: True or false
2436 public function useRCPatrol() {
2437 global $wgUseRCPatrol;
2438 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
2442 * Check whether to enable new pages patrol features for this user
2443 * @return Bool True or false
2445 public function useNPPatrol() {
2446 global $wgUseRCPatrol, $wgUseNPPatrol;
2447 return( ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) ) );
2451 * Get the current skin, loading it if required
2452 * @return Skin The current skin
2453 * @todo FIXME: Need to check the old failback system [AV]
2454 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
2456 function getSkin() {
2457 return RequestContext
::getMain()->getSkin();
2461 * Check the watched status of an article.
2462 * @param $title Title of the article to look at
2465 function isWatched( $title ) {
2466 $wl = WatchedItem
::fromUserTitle( $this, $title );
2467 return $wl->isWatched();
2472 * @param $title Title of the article to look at
2474 function addWatch( $title ) {
2475 $wl = WatchedItem
::fromUserTitle( $this, $title );
2477 $this->invalidateCache();
2481 * Stop watching an article.
2482 * @param $title Title of the article to look at
2484 function removeWatch( $title ) {
2485 $wl = WatchedItem
::fromUserTitle( $this, $title );
2487 $this->invalidateCache();
2491 * Clear the user's notification timestamp for the given title.
2492 * If e-notif e-mails are on, they will receive notification mails on
2493 * the next change of the page if it's watched etc.
2494 * @param $title Title of the article to look at
2496 function clearNotification( &$title ) {
2497 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2499 # Do nothing if the database is locked to writes
2500 if( wfReadOnly() ) {
2504 if( $title->getNamespace() == NS_USER_TALK
&&
2505 $title->getText() == $this->getName() ) {
2506 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2508 $this->setNewtalk( false );
2511 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2515 if( $this->isAnon() ) {
2516 // Nothing else to do...
2520 // Only update the timestamp if the page is being watched.
2521 // The query to find out if it is watched is cached both in memcached and per-invocation,
2522 // and when it does have to be executed, it can be on a slave
2523 // If this is the user's newtalk page, we always update the timestamp
2524 if( $title->getNamespace() == NS_USER_TALK
&&
2525 $title->getText() == $wgUser->getName() )
2528 } elseif ( $this->getId() == $wgUser->getId() ) {
2529 $watched = $title->userIsWatching();
2534 // If the page is watched by the user (or may be watched), update the timestamp on any
2535 // any matching rows
2537 $dbw = wfGetDB( DB_MASTER
);
2538 $dbw->update( 'watchlist',
2540 'wl_notificationtimestamp' => null
2541 ), array( /* WHERE */
2542 'wl_title' => $title->getDBkey(),
2543 'wl_namespace' => $title->getNamespace(),
2544 'wl_user' => $this->getID()
2551 * Resets all of the given user's page-change notification timestamps.
2552 * If e-notif e-mails are on, they will receive notification mails on
2553 * the next change of any watched page.
2555 * @param $currentUser Int User ID
2557 function clearAllNotifications( $currentUser ) {
2558 global $wgUseEnotif, $wgShowUpdatedMarker;
2559 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2560 $this->setNewtalk( false );
2563 if( $currentUser != 0 ) {
2564 $dbw = wfGetDB( DB_MASTER
);
2565 $dbw->update( 'watchlist',
2567 'wl_notificationtimestamp' => null
2568 ), array( /* WHERE */
2569 'wl_user' => $currentUser
2572 # We also need to clear here the "you have new message" notification for the own user_talk page
2573 # This is cleared one page view later in Article::viewUpdates();
2578 * Set this user's options from an encoded string
2579 * @param $str String Encoded options to import
2582 function decodeOptions( $str ) {
2586 $this->mOptionsLoaded
= true;
2587 $this->mOptionOverrides
= array();
2589 // If an option is not set in $str, use the default value
2590 $this->mOptions
= self
::getDefaultOptions();
2592 $a = explode( "\n", $str );
2593 foreach ( $a as $s ) {
2595 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2596 $this->mOptions
[$m[1]] = $m[2];
2597 $this->mOptionOverrides
[$m[1]] = $m[2];
2603 * Set a cookie on the user's client. Wrapper for
2604 * WebResponse::setCookie
2605 * @param $name String Name of the cookie to set
2606 * @param $value String Value to set
2607 * @param $exp Int Expiration time, as a UNIX time value;
2608 * if 0 or not specified, use the default $wgCookieExpiration
2610 protected function setCookie( $name, $value, $exp = 0 ) {
2612 $wgRequest->response()->setcookie( $name, $value, $exp );
2616 * Clear a cookie on the user's client
2617 * @param $name String Name of the cookie to clear
2619 protected function clearCookie( $name ) {
2620 $this->setCookie( $name, '', time() - 86400 );
2624 * Set the default cookies for this session on the user's client.
2626 * @param $request WebRequest object to use; $wgRequest will be used if null
2629 function setCookies( $request = null ) {
2630 if ( $request === null ) {
2632 $request = $wgRequest;
2636 if ( 0 == $this->mId
) return;
2638 'wsUserID' => $this->mId
,
2639 'wsToken' => $this->mToken
,
2640 'wsUserName' => $this->getName()
2643 'UserID' => $this->mId
,
2644 'UserName' => $this->getName(),
2646 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2647 $cookies['Token'] = $this->mToken
;
2649 $cookies['Token'] = false;
2652 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2654 foreach ( $session as $name => $value ) {
2655 $request->setSessionData( $name, $value );
2657 foreach ( $cookies as $name => $value ) {
2658 if ( $value === false ) {
2659 $this->clearCookie( $name );
2661 $this->setCookie( $name, $value );
2667 * Log this user out.
2670 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
2676 * Clear the user's cookies and session, and reset the instance cache.
2680 function doLogout() {
2683 $this->clearInstanceCache( 'defaults' );
2685 $wgRequest->setSessionData( 'wsUserID', 0 );
2687 $this->clearCookie( 'UserID' );
2688 $this->clearCookie( 'Token' );
2690 # Remember when user logged out, to prevent seeing cached pages
2691 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2695 * Save this user's settings into the database.
2696 * @todo Only rarely do all these fields need to be set!
2698 function saveSettings() {
2700 if ( wfReadOnly() ) { return; }
2701 if ( 0 == $this->mId
) { return; }
2703 $this->mTouched
= self
::newTouchedTimestamp();
2705 $dbw = wfGetDB( DB_MASTER
);
2706 $dbw->update( 'user',
2708 'user_name' => $this->mName
,
2709 'user_password' => $this->mPassword
,
2710 'user_newpassword' => $this->mNewpassword
,
2711 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2712 'user_real_name' => $this->mRealName
,
2713 'user_email' => $this->mEmail
,
2714 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2715 'user_options' => '',
2716 'user_touched' => $dbw->timestamp( $this->mTouched
),
2717 'user_token' => $this->mToken
,
2718 'user_email_token' => $this->mEmailToken
,
2719 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2720 ), array( /* WHERE */
2721 'user_id' => $this->mId
2725 $this->saveOptions();
2727 wfRunHooks( 'UserSaveSettings', array( $this ) );
2728 $this->clearSharedCache();
2729 $this->getUserPage()->invalidateCache();
2733 * If only this user's username is known, and it exists, return the user ID.
2736 function idForName() {
2737 $s = trim( $this->getName() );
2738 if ( $s === '' ) return 0;
2740 $dbr = wfGetDB( DB_SLAVE
);
2741 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2742 if ( $id === false ) {
2749 * Add a user to the database, return the user object
2751 * @param $name String Username to add
2752 * @param $params Array of Strings Non-default parameters to save to the database as user_* fields:
2753 * - password The user's password hash. Password logins will be disabled if this is omitted.
2754 * - newpassword Hash for a temporary password that has been mailed to the user
2755 * - email The user's email address
2756 * - email_authenticated The email authentication timestamp
2757 * - real_name The user's real name
2758 * - options An associative array of non-default options
2759 * - token Random authentication token. Do not set.
2760 * - registration Registration timestamp. Do not set.
2762 * @return User object, or null if the username already exists
2764 static function createNew( $name, $params = array() ) {
2767 if ( isset( $params['options'] ) ) {
2768 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
2769 unset( $params['options'] );
2771 $dbw = wfGetDB( DB_MASTER
);
2772 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2775 'user_id' => $seqVal,
2776 'user_name' => $name,
2777 'user_password' => $user->mPassword
,
2778 'user_newpassword' => $user->mNewpassword
,
2779 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
2780 'user_email' => $user->mEmail
,
2781 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2782 'user_real_name' => $user->mRealName
,
2783 'user_options' => '',
2784 'user_token' => $user->mToken
,
2785 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2786 'user_editcount' => 0,
2788 foreach ( $params as $name => $value ) {
2789 $fields["user_$name"] = $value;
2791 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2792 if ( $dbw->affectedRows() ) {
2793 $newUser = User
::newFromId( $dbw->insertId() );
2801 * Add this existing user object to the database
2803 function addToDatabase() {
2805 $dbw = wfGetDB( DB_MASTER
);
2806 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2807 $dbw->insert( 'user',
2809 'user_id' => $seqVal,
2810 'user_name' => $this->mName
,
2811 'user_password' => $this->mPassword
,
2812 'user_newpassword' => $this->mNewpassword
,
2813 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2814 'user_email' => $this->mEmail
,
2815 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2816 'user_real_name' => $this->mRealName
,
2817 'user_options' => '',
2818 'user_token' => $this->mToken
,
2819 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2820 'user_editcount' => 0,
2823 $this->mId
= $dbw->insertId();
2825 // Clear instance cache other than user table data, which is already accurate
2826 $this->clearInstanceCache();
2828 $this->saveOptions();
2832 * If this (non-anonymous) user is blocked, block any IP address
2833 * they've successfully logged in from.
2835 function spreadBlock() {
2836 wfDebug( __METHOD__
. "()\n" );
2838 if ( $this->mId
== 0 ) {
2842 $userblock = Block
::newFromTarget( $this->getName() );
2843 if ( !$userblock ) {
2847 $userblock->doAutoblock( wfGetIP() );
2851 * Generate a string which will be different for any combination of
2852 * user options which would produce different parser output.
2853 * This will be used as part of the hash key for the parser cache,
2854 * so users with the same options can share the same cached data
2857 * Extensions which require it should install 'PageRenderingHash' hook,
2858 * which will give them a chance to modify this key based on their own
2861 * @deprecated since 1.17 use the ParserOptions object to get the relevant options
2862 * @return String Page rendering hash
2864 function getPageRenderingHash() {
2865 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2867 return $this->mHash
;
2869 wfDeprecated( __METHOD__
);
2871 // stubthreshold is only included below for completeness,
2872 // since it disables the parser cache, its value will always
2873 // be 0 when this function is called by parsercache.
2875 $confstr = $this->getOption( 'math' );
2876 $confstr .= '!' . $this->getStubThreshold();
2877 if ( $wgUseDynamicDates ) { # This is wrong (bug 24714)
2878 $confstr .= '!' . $this->getDatePreference();
2880 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ?
'1' : '' );
2881 $confstr .= '!' . $wgLang->getCode();
2882 $confstr .= '!' . $this->getOption( 'thumbsize' );
2883 // add in language specific options, if any
2884 $extra = $wgContLang->getExtraHashOptions();
2887 // Since the skin could be overloading link(), it should be
2888 // included here but in practice, none of our skins do that.
2890 $confstr .= $wgRenderHashAppend;
2892 // Give a chance for extensions to modify the hash, if they have
2893 // extra options or other effects on the parser cache.
2894 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2896 // Make it a valid memcached key fragment
2897 $confstr = str_replace( ' ', '_', $confstr );
2898 $this->mHash
= $confstr;
2903 * Get whether the user is explicitly blocked from account creation.
2904 * @return Bool|Block
2906 function isBlockedFromCreateAccount() {
2907 $this->getBlockedStatus();
2908 if( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ){
2909 return $this->mBlock
;
2912 # bug 13611: if the IP address the user is trying to create an account from is
2913 # blocked with createaccount disabled, prevent new account creation there even
2914 # when the user is logged in
2915 static $accBlock = false;
2916 if( $accBlock === false ){
2917 $accBlock = Block
::newFromTarget( null, wfGetIP() );
2919 return $accBlock instanceof Block
&& $accBlock->prevents( 'createaccount' )
2925 * Get whether the user is blocked from using Special:Emailuser.
2928 function isBlockedFromEmailuser() {
2929 $this->getBlockedStatus();
2930 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
2934 * Get whether the user is allowed to create an account.
2937 function isAllowedToCreateAccount() {
2938 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2942 * Get this user's personal page title.
2944 * @return Title: User's personal page title
2946 function getUserPage() {
2947 return Title
::makeTitle( NS_USER
, $this->getName() );
2951 * Get this user's talk page title.
2953 * @return Title: User's talk page title
2955 function getTalkPage() {
2956 $title = $this->getUserPage();
2957 return $title->getTalkPage();
2961 * Determine whether the user is a newbie. Newbies are either
2962 * anonymous IPs, or the most recently created accounts.
2965 function isNewbie() {
2966 return !$this->isAllowed( 'autoconfirmed' );
2970 * Check to see if the given clear-text password is one of the accepted passwords
2971 * @param $password String: user password.
2972 * @return Boolean: True if the given password is correct, otherwise False.
2974 function checkPassword( $password ) {
2975 global $wgAuth, $wgLegacyEncoding;
2978 // Even though we stop people from creating passwords that
2979 // are shorter than this, doesn't mean people wont be able
2980 // to. Certain authentication plugins do NOT want to save
2981 // domain passwords in a mysql database, so we should
2982 // check this (in case $wgAuth->strict() is false).
2983 if( !$this->isValidPassword( $password ) ) {
2987 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2989 } elseif( $wgAuth->strict() ) {
2990 /* Auth plugin doesn't allow local authentication */
2992 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2993 /* Auth plugin doesn't allow local authentication for this user name */
2996 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
2998 } elseif ( $wgLegacyEncoding ) {
2999 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3000 # Check for this with iconv
3001 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3002 if ( $cp1252Password != $password &&
3003 self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) )
3012 * Check if the given clear-text password matches the temporary password
3013 * sent by e-mail for password reset operations.
3014 * @return Boolean: True if matches, false otherwise
3016 function checkTemporaryPassword( $plaintext ) {
3017 global $wgNewPasswordExpiry;
3020 if( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
3021 if ( is_null( $this->mNewpassTime
) ) {
3024 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3025 return ( time() < $expiry );
3032 * Initialize (if necessary) and return a session token value
3033 * which can be used in edit forms to show that the user's
3034 * login credentials aren't being hijacked with a foreign form
3037 * @param $salt String|Array of Strings Optional function-specific data for hashing
3038 * @param $request WebRequest object to use or null to use $wgRequest
3039 * @return String The new edit token
3041 function editToken( $salt = '', $request = null ) {
3042 if ( $request == null ) {
3044 $request = $wgRequest;
3047 if ( $this->isAnon() ) {
3048 return EDIT_TOKEN_SUFFIX
;
3050 $token = $request->getSessionData( 'wsEditToken' );
3051 if ( $token === null ) {
3052 $token = self
::generateToken();
3053 $request->setSessionData( 'wsEditToken', $token );
3055 if( is_array( $salt ) ) {
3056 $salt = implode( '|', $salt );
3058 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
3063 * Generate a looking random token for various uses.
3065 * @param $salt String Optional salt value
3066 * @return String The new random token
3068 public static function generateToken( $salt = '' ) {
3069 $token = dechex( mt_rand() ) . dechex( mt_rand() );
3070 return md5( $token . $salt );
3074 * Check given value against the token value stored in the session.
3075 * A match should confirm that the form was submitted from the
3076 * user's own login session, not a form submission from a third-party
3079 * @param $val String Input value to compare
3080 * @param $salt String Optional function-specific data for hashing
3081 * @param $request WebRequest object to use or null to use $wgRequest
3082 * @return Boolean: Whether the token matches
3084 function matchEditToken( $val, $salt = '', $request = null ) {
3085 $sessionToken = $this->editToken( $salt, $request );
3086 if ( $val != $sessionToken ) {
3087 wfDebug( "User::matchEditToken: broken session data\n" );
3089 return $val == $sessionToken;
3093 * Check given value against the token value stored in the session,
3094 * ignoring the suffix.
3096 * @param $val String Input value to compare
3097 * @param $salt String Optional function-specific data for hashing
3098 * @param $request WebRequest object to use or null to use $wgRequest
3099 * @return Boolean: Whether the token matches
3101 function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3102 $sessionToken = $this->editToken( $salt, $request );
3103 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3107 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3108 * mail to the user's given address.
3110 * @param $type String: message to send, either "created", "changed" or "set"
3111 * @return Status object
3113 function sendConfirmationMail( $type = 'created' ) {
3115 $expiration = null; // gets passed-by-ref and defined in next line.
3116 $token = $this->confirmationToken( $expiration );
3117 $url = $this->confirmationTokenUrl( $token );
3118 $invalidateURL = $this->invalidationTokenUrl( $token );
3119 $this->saveSettings();
3121 if ( $type == 'created' ||
$type === false ) {
3122 $message = 'confirmemail_body';
3123 } elseif ( $type === true ) {
3124 $message = 'confirmemail_body_changed';
3126 $message = 'confirmemail_body_' . $type;
3129 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
3134 $wgLang->timeanddate( $expiration, false ),
3136 $wgLang->date( $expiration, false ),
3137 $wgLang->time( $expiration, false ) ) );
3141 * Send an e-mail to this user's account. Does not check for
3142 * confirmed status or validity.
3144 * @param $subject String Message subject
3145 * @param $body String Message body
3146 * @param $from String Optional From address; if unspecified, default $wgPasswordSender will be used
3147 * @param $replyto String Reply-To address
3150 function sendMail( $subject, $body, $from = null, $replyto = null ) {
3151 if( is_null( $from ) ) {
3152 global $wgPasswordSender, $wgPasswordSenderName;
3153 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
3155 $sender = new MailAddress( $from );
3158 $to = new MailAddress( $this );
3159 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
3163 * Generate, store, and return a new e-mail confirmation code.
3164 * A hash (unsalted, since it's used as a key) is stored.
3166 * @note Call saveSettings() after calling this function to commit
3167 * this change to the database.
3169 * @param[out] &$expiration \mixed Accepts the expiration time
3170 * @return String New token
3173 function confirmationToken( &$expiration ) {
3174 global $wgUserEmailConfirmationTokenExpiry;
3176 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
3177 $expiration = wfTimestamp( TS_MW
, $expires );
3178 $token = self
::generateToken( $this->mId
. $this->mEmail
. $expires );
3179 $hash = md5( $token );
3181 $this->mEmailToken
= $hash;
3182 $this->mEmailTokenExpires
= $expiration;
3187 * Return a URL the user can use to confirm their email address.
3188 * @param $token String Accepts the email confirmation token
3189 * @return String New token URL
3192 function confirmationTokenUrl( $token ) {
3193 return $this->getTokenUrl( 'ConfirmEmail', $token );
3197 * Return a URL the user can use to invalidate their email address.
3198 * @param $token String Accepts the email confirmation token
3199 * @return String New token URL
3202 function invalidationTokenUrl( $token ) {
3203 return $this->getTokenUrl( 'Invalidateemail', $token );
3207 * Internal function to format the e-mail validation/invalidation URLs.
3208 * This uses $wgArticlePath directly as a quickie hack to use the
3209 * hardcoded English names of the Special: pages, for ASCII safety.
3211 * @note Since these URLs get dropped directly into emails, using the
3212 * short English names avoids insanely long URL-encoded links, which
3213 * also sometimes can get corrupted in some browsers/mailers
3214 * (bug 6957 with Gmail and Internet Explorer).
3216 * @param $page String Special page
3217 * @param $token String Token
3218 * @return String Formatted URL
3220 protected function getTokenUrl( $page, $token ) {
3221 global $wgArticlePath;
3225 "Special:$page/$token",
3230 * Mark the e-mail address confirmed.
3232 * @note Call saveSettings() after calling this function to commit the change.
3234 function confirmEmail() {
3235 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3236 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3241 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3242 * address if it was already confirmed.
3244 * @note Call saveSettings() after calling this function to commit the change.
3246 function invalidateEmail() {
3248 $this->mEmailToken
= null;
3249 $this->mEmailTokenExpires
= null;
3250 $this->setEmailAuthenticationTimestamp( null );
3251 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3256 * Set the e-mail authentication timestamp.
3257 * @param $timestamp String TS_MW timestamp
3259 function setEmailAuthenticationTimestamp( $timestamp ) {
3261 $this->mEmailAuthenticated
= $timestamp;
3262 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
3266 * Is this user allowed to send e-mails within limits of current
3267 * site configuration?
3270 function canSendEmail() {
3271 global $wgEnableEmail, $wgEnableUserEmail;
3272 if( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
3275 $canSend = $this->isEmailConfirmed();
3276 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3281 * Is this user allowed to receive e-mails within limits of current
3282 * site configuration?
3285 function canReceiveEmail() {
3286 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3290 * Is this user's e-mail address valid-looking and confirmed within
3291 * limits of the current site configuration?
3293 * @note If $wgEmailAuthentication is on, this may require the user to have
3294 * confirmed their address by returning a code or using a password
3295 * sent to the address from the wiki.
3299 function isEmailConfirmed() {
3300 global $wgEmailAuthentication;
3303 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3304 if( $this->isAnon() )
3306 if( !self
::isValidEmailAddr( $this->mEmail
) )
3308 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
3317 * Check whether there is an outstanding request for e-mail confirmation.
3320 function isEmailConfirmationPending() {
3321 global $wgEmailAuthentication;
3322 return $wgEmailAuthentication &&
3323 !$this->isEmailConfirmed() &&
3324 $this->mEmailToken
&&
3325 $this->mEmailTokenExpires
> wfTimestamp();
3329 * Get the timestamp of account creation.
3331 * @return String|Bool Timestamp of account creation, or false for
3332 * non-existent/anonymous user accounts.
3334 public function getRegistration() {
3335 if ( $this->isAnon() ) {
3339 return $this->mRegistration
;
3343 * Get the timestamp of the first edit
3345 * @return String|Bool Timestamp of first edit, or false for
3346 * non-existent/anonymous user accounts.
3348 public function getFirstEditTimestamp() {
3349 if( $this->getId() == 0 ) {
3350 return false; // anons
3352 $dbr = wfGetDB( DB_SLAVE
);
3353 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3354 array( 'rev_user' => $this->getId() ),
3356 array( 'ORDER BY' => 'rev_timestamp ASC' )
3359 return false; // no edits
3361 return wfTimestamp( TS_MW
, $time );
3365 * Get the permissions associated with a given list of groups
3367 * @param $groups Array of Strings List of internal group names
3368 * @return Array of Strings List of permission key names for given groups combined
3370 static function getGroupPermissions( $groups ) {
3371 global $wgGroupPermissions, $wgRevokePermissions;
3373 // grant every granted permission first
3374 foreach( $groups as $group ) {
3375 if( isset( $wgGroupPermissions[$group] ) ) {
3376 $rights = array_merge( $rights,
3377 // array_filter removes empty items
3378 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3381 // now revoke the revoked permissions
3382 foreach( $groups as $group ) {
3383 if( isset( $wgRevokePermissions[$group] ) ) {
3384 $rights = array_diff( $rights,
3385 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3388 return array_unique( $rights );
3392 * Get all the groups who have a given permission
3394 * @param $role String Role to check
3395 * @return Array of Strings List of internal group names with the given permission
3397 static function getGroupsWithPermission( $role ) {
3398 global $wgGroupPermissions;
3399 $allowedGroups = array();
3400 foreach ( $wgGroupPermissions as $group => $rights ) {
3401 if ( isset( $rights[$role] ) && $rights[$role] ) {
3402 $allowedGroups[] = $group;
3405 return $allowedGroups;
3409 * Get the localized descriptive name for a group, if it exists
3411 * @param $group String Internal group name
3412 * @return String Localized descriptive group name
3414 static function getGroupName( $group ) {
3415 $msg = wfMessage( "group-$group" );
3416 return $msg->isBlank() ?
$group : $msg->text();
3420 * Get the localized descriptive name for a member of a group, if it exists
3422 * @param $group String Internal group name
3423 * @return String Localized name for group member
3425 static function getGroupMember( $group ) {
3426 $msg = wfMessage( "group-$group-member" );
3427 return $msg->isBlank() ?
$group : $msg->text();
3431 * Return the set of defined explicit groups.
3432 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3433 * are not included, as they are defined automatically, not in the database.
3434 * @return Array of internal group names
3436 static function getAllGroups() {
3437 global $wgGroupPermissions, $wgRevokePermissions;
3439 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3440 self
::getImplicitGroups()
3445 * Get a list of all available permissions.
3446 * @return Array of permission names
3448 static function getAllRights() {
3449 if ( self
::$mAllRights === false ) {
3450 global $wgAvailableRights;
3451 if ( count( $wgAvailableRights ) ) {
3452 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3454 self
::$mAllRights = self
::$mCoreRights;
3456 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3458 return self
::$mAllRights;
3462 * Get a list of implicit groups
3463 * @return Array of Strings Array of internal group names
3465 public static function getImplicitGroups() {
3466 global $wgImplicitGroups;
3467 $groups = $wgImplicitGroups;
3468 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3473 * Get the title of a page describing a particular group
3475 * @param $group String Internal group name
3476 * @return Title|Bool Title of the page if it exists, false otherwise
3478 static function getGroupPage( $group ) {
3479 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
3480 if( $msg->exists() ) {
3481 $title = Title
::newFromText( $msg->text() );
3482 if( is_object( $title ) )
3489 * Create a link to the group in HTML, if available;
3490 * else return the group name.
3492 * @param $group String Internal name of the group
3493 * @param $text String The text of the link
3494 * @return String HTML link to the group
3496 static function makeGroupLinkHTML( $group, $text = '' ) {
3498 $text = self
::getGroupName( $group );
3500 $title = self
::getGroupPage( $group );
3503 $sk = $wgUser->getSkin();
3504 return $sk->link( $title, htmlspecialchars( $text ) );
3511 * Create a link to the group in Wikitext, if available;
3512 * else return the group name.
3514 * @param $group String Internal name of the group
3515 * @param $text String The text of the link
3516 * @return String Wikilink to the group
3518 static function makeGroupLinkWiki( $group, $text = '' ) {
3520 $text = self
::getGroupName( $group );
3522 $title = self
::getGroupPage( $group );
3524 $page = $title->getPrefixedText();
3525 return "[[$page|$text]]";
3532 * Returns an array of the groups that a particular group can add/remove.
3534 * @param $group String: the group to check for whether it can add/remove
3535 * @return Array array( 'add' => array( addablegroups ),
3536 * 'remove' => array( removablegroups ),
3537 * 'add-self' => array( addablegroups to self),
3538 * 'remove-self' => array( removable groups from self) )
3540 static function changeableByGroup( $group ) {
3541 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
3543 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
3544 if( empty( $wgAddGroups[$group] ) ) {
3545 // Don't add anything to $groups
3546 } elseif( $wgAddGroups[$group] === true ) {
3547 // You get everything
3548 $groups['add'] = self
::getAllGroups();
3549 } elseif( is_array( $wgAddGroups[$group] ) ) {
3550 $groups['add'] = $wgAddGroups[$group];
3553 // Same thing for remove
3554 if( empty( $wgRemoveGroups[$group] ) ) {
3555 } elseif( $wgRemoveGroups[$group] === true ) {
3556 $groups['remove'] = self
::getAllGroups();
3557 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
3558 $groups['remove'] = $wgRemoveGroups[$group];
3561 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
3562 if( empty( $wgGroupsAddToSelf['user']) ||
$wgGroupsAddToSelf['user'] !== true ) {
3563 foreach( $wgGroupsAddToSelf as $key => $value ) {
3564 if( is_int( $key ) ) {
3565 $wgGroupsAddToSelf['user'][] = $value;
3570 if( empty( $wgGroupsRemoveFromSelf['user']) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
3571 foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
3572 if( is_int( $key ) ) {
3573 $wgGroupsRemoveFromSelf['user'][] = $value;
3578 // Now figure out what groups the user can add to him/herself
3579 if( empty( $wgGroupsAddToSelf[$group] ) ) {
3580 } elseif( $wgGroupsAddToSelf[$group] === true ) {
3581 // No idea WHY this would be used, but it's there
3582 $groups['add-self'] = User
::getAllGroups();
3583 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
3584 $groups['add-self'] = $wgGroupsAddToSelf[$group];
3587 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
3588 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
3589 $groups['remove-self'] = User
::getAllGroups();
3590 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
3591 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
3598 * Returns an array of groups that this user can add and remove
3599 * @return Array array( 'add' => array( addablegroups ),
3600 * 'remove' => array( removablegroups ),
3601 * 'add-self' => array( addablegroups to self),
3602 * 'remove-self' => array( removable groups from self) )
3604 function changeableGroups() {
3605 if( $this->isAllowed( 'userrights' ) ) {
3606 // This group gives the right to modify everything (reverse-
3607 // compatibility with old "userrights lets you change
3609 // Using array_merge to make the groups reindexed
3610 $all = array_merge( User
::getAllGroups() );
3614 'add-self' => array(),
3615 'remove-self' => array()
3619 // Okay, it's not so simple, we will have to go through the arrays
3622 'remove' => array(),
3623 'add-self' => array(),
3624 'remove-self' => array()
3626 $addergroups = $this->getEffectiveGroups();
3628 foreach( $addergroups as $addergroup ) {
3629 $groups = array_merge_recursive(
3630 $groups, $this->changeableByGroup( $addergroup )
3632 $groups['add'] = array_unique( $groups['add'] );
3633 $groups['remove'] = array_unique( $groups['remove'] );
3634 $groups['add-self'] = array_unique( $groups['add-self'] );
3635 $groups['remove-self'] = array_unique( $groups['remove-self'] );
3641 * Increment the user's edit-count field.
3642 * Will have no effect for anonymous users.
3644 function incEditCount() {
3645 if( !$this->isAnon() ) {
3646 $dbw = wfGetDB( DB_MASTER
);
3647 $dbw->update( 'user',
3648 array( 'user_editcount=user_editcount+1' ),
3649 array( 'user_id' => $this->getId() ),
3652 // Lazy initialization check...
3653 if( $dbw->affectedRows() == 0 ) {
3654 // Pull from a slave to be less cruel to servers
3655 // Accuracy isn't the point anyway here
3656 $dbr = wfGetDB( DB_SLAVE
);
3657 $count = $dbr->selectField( 'revision',
3659 array( 'rev_user' => $this->getId() ),
3662 // Now here's a goddamn hack...
3663 if( $dbr !== $dbw ) {
3664 // If we actually have a slave server, the count is
3665 // at least one behind because the current transaction
3666 // has not been committed and replicated.
3669 // But if DB_SLAVE is selecting the master, then the
3670 // count we just read includes the revision that was
3671 // just added in the working transaction.
3674 $dbw->update( 'user',
3675 array( 'user_editcount' => $count ),
3676 array( 'user_id' => $this->getId() ),
3680 // edit count in user cache too
3681 $this->invalidateCache();
3685 * Get the description of a given right
3687 * @param $right String Right to query
3688 * @return String Localized description of the right
3690 static function getRightDescription( $right ) {
3691 $key = "right-$right";
3692 $msg = wfMessage( $key );
3693 return $msg->isBlank() ?
$right : $msg->text();
3697 * Make an old-style password hash
3699 * @param $password String Plain-text password
3700 * @param $userId String User ID
3701 * @return String Password hash
3703 static function oldCrypt( $password, $userId ) {
3704 global $wgPasswordSalt;
3705 if ( $wgPasswordSalt ) {
3706 return md5( $userId . '-' . md5( $password ) );
3708 return md5( $password );
3713 * Make a new-style password hash
3715 * @param $password String Plain-text password
3716 * @param $salt String Optional salt, may be random or the user ID.
3717 * If unspecified or false, will generate one automatically
3718 * @return String Password hash
3720 static function crypt( $password, $salt = false ) {
3721 global $wgPasswordSalt;
3724 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3728 if( $wgPasswordSalt ) {
3729 if ( $salt === false ) {
3730 $salt = substr( wfGenerateToken(), 0, 8 );
3732 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3734 return ':A:' . md5( $password );
3739 * Compare a password hash with a plain-text password. Requires the user
3740 * ID if there's a chance that the hash is an old-style hash.
3742 * @param $hash String Password hash
3743 * @param $password String Plain-text password to compare
3744 * @param $userId String User ID for old-style password salt
3747 static function comparePasswords( $hash, $password, $userId = false ) {
3748 $type = substr( $hash, 0, 3 );
3751 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3755 if ( $type == ':A:' ) {
3757 return md5( $password ) === substr( $hash, 3 );
3758 } elseif ( $type == ':B:' ) {
3760 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3761 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3764 return self
::oldCrypt( $password, $userId ) === $hash;
3769 * Add a newuser log entry for this user
3771 * @param $byEmail Boolean: account made by email?
3772 * @param $reason String: user supplied reason
3776 public function addNewUserLogEntry( $byEmail = false, $reason = '' ) {
3777 global $wgUser, $wgContLang, $wgNewUserLog;
3778 if( empty( $wgNewUserLog ) ) {
3779 return true; // disabled
3782 if( $this->getName() == $wgUser->getName() ) {
3785 $action = 'create2';
3787 if ( $reason === '' ) {
3788 $reason = wfMsgForContent( 'newuserlog-byemail' );
3790 $reason = $wgContLang->commaList( array(
3791 $reason, wfMsgForContent( 'newuserlog-byemail' ) ) );
3795 $log = new LogPage( 'newusers' );
3798 $this->getUserPage(),
3800 array( $this->getId() )
3806 * Add an autocreate newuser log entry for this user
3807 * Used by things like CentralAuth and perhaps other authplugins.
3811 public function addNewUserLogEntryAutoCreate() {
3812 global $wgNewUserLog;
3813 if( !$wgNewUserLog ) {
3814 return true; // disabled
3816 $log = new LogPage( 'newusers', false );
3817 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3821 protected function loadOptions() {
3823 if ( $this->mOptionsLoaded ||
!$this->getId() )
3826 $this->mOptions
= self
::getDefaultOptions();
3828 // Maybe load from the object
3829 if ( !is_null( $this->mOptionOverrides
) ) {
3830 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
3831 foreach( $this->mOptionOverrides
as $key => $value ) {
3832 $this->mOptions
[$key] = $value;
3835 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
3836 // Load from database
3837 $dbr = wfGetDB( DB_SLAVE
);
3839 $res = $dbr->select(
3842 array( 'up_user' => $this->getId() ),
3846 foreach ( $res as $row ) {
3847 $this->mOptionOverrides
[$row->up_property
] = $row->up_value
;
3848 $this->mOptions
[$row->up_property
] = $row->up_value
;
3852 $this->mOptionsLoaded
= true;
3854 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
3857 protected function saveOptions() {
3858 global $wgAllowPrefChange;
3860 $extuser = ExternalUser
::newFromUser( $this );
3862 $this->loadOptions();
3863 $dbw = wfGetDB( DB_MASTER
);
3865 $insert_rows = array();
3867 $saveOptions = $this->mOptions
;
3869 // Allow hooks to abort, for instance to save to a global profile.
3870 // Reset options to default state before saving.
3871 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) )
3874 foreach( $saveOptions as $key => $value ) {
3875 # Don't bother storing default values
3876 if ( ( is_null( self
::getDefaultOption( $key ) ) &&
3877 !( $value === false ||
is_null($value) ) ) ||
3878 $value != self
::getDefaultOption( $key ) ) {
3879 $insert_rows[] = array(
3880 'up_user' => $this->getId(),
3881 'up_property' => $key,
3882 'up_value' => $value,
3885 if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
3886 switch ( $wgAllowPrefChange[$key] ) {
3892 $extuser->setPref( $key, $value );
3898 $dbw->delete( 'user_properties', array( 'up_user' => $this->getId() ), __METHOD__
);
3899 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
);
3904 * Provide an array of HTML5 attributes to put on an input element
3905 * intended for the user to enter a new password. This may include
3906 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
3908 * Do *not* use this when asking the user to enter his current password!
3909 * Regardless of configuration, users may have invalid passwords for whatever
3910 * reason (e.g., they were set before requirements were tightened up).
3911 * Only use it when asking for a new password, like on account creation or
3914 * Obviously, you still need to do server-side checking.
3916 * NOTE: A combination of bugs in various browsers means that this function
3917 * actually just returns array() unconditionally at the moment. May as
3918 * well keep it around for when the browser bugs get fixed, though.
3920 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
3922 * @return array Array of HTML attributes suitable for feeding to
3923 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
3924 * That will potentially output invalid XHTML 1.0 Transitional, and will
3925 * get confused by the boolean attribute syntax used.)
3927 public static function passwordChangeInputAttribs() {
3928 global $wgMinimalPasswordLength;
3930 if ( $wgMinimalPasswordLength == 0 ) {
3934 # Note that the pattern requirement will always be satisfied if the
3935 # input is empty, so we need required in all cases.
3937 # @todo FIXME: Bug 23769: This needs to not claim the password is required
3938 # if e-mail confirmation is being used. Since HTML5 input validation
3939 # is b0rked anyway in some browsers, just return nothing. When it's
3940 # re-enabled, fix this code to not output required for e-mail
3942 #$ret = array( 'required' );
3945 # We can't actually do this right now, because Opera 9.6 will print out
3946 # the entered password visibly in its error message! When other
3947 # browsers add support for this attribute, or Opera fixes its support,
3948 # we can add support with a version check to avoid doing this on Opera
3949 # versions where it will be a problem. Reported to Opera as
3950 # DSK-262266, but they don't have a public bug tracker for us to follow.
3952 if ( $wgMinimalPasswordLength > 1 ) {
3953 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
3954 $ret['title'] = wfMsgExt( 'passwordtooshort', 'parsemag',
3955 $wgMinimalPasswordLength );