3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Int Number of characters in user_token field.
27 define( 'USER_TOKEN_LENGTH', 32 );
30 * Int Serialized record version.
33 define( 'MW_USER_VERSION', 8 );
36 * String Some punctuation to prevent editing from broken text-mangling proxies.
39 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
42 * Thrown by User::setPassword() on error.
45 class PasswordError
extends MWException
{
50 * The User object encapsulates all of the user-specific settings (user_id,
51 * name, rights, password, email address, options, last login time). Client
52 * classes use the getXXX() functions to access these fields. These functions
53 * do all the work of determining whether the user is logged in,
54 * whether the requested option can be satisfied from cookies or
55 * whether a database query is needed. Most of the settings needed
56 * for rendering normal pages are set in the cookie to minimize use
61 * Global constants made accessible as class constants so that autoloader
64 const USER_TOKEN_LENGTH
= USER_TOKEN_LENGTH
;
65 const MW_USER_VERSION
= MW_USER_VERSION
;
66 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
69 * Array of Strings List of member variables which are saved to the
70 * shared cache (memcached). Any operation which changes the
71 * corresponding database fields must call a cache-clearing function.
74 static $mCacheVars = array(
85 'mEmailAuthenticated',
92 // user_properties table
97 * Array of Strings Core rights.
98 * Each of these should have a corresponding message of the form
102 static $mCoreRights = array(
121 'editusercssjs', #deprecated
133 'move-rootuserpages',
137 'override-export-depth',
159 'userrights-interwiki',
163 * String Cached results of getAllRights()
165 static $mAllRights = false;
167 /** @name Cache variables */
169 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
170 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
171 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups, $mOptionOverrides;
175 * Bool Whether the cache variables have been loaded.
181 * Array with already loaded items or true if all items have been loaded.
183 private $mLoadedItems = array();
187 * String Initialization data source if mLoadedItems!==true. May be one of:
188 * - 'defaults' anonymous user initialised from class defaults
189 * - 'name' initialise from mName
190 * - 'id' initialise from mId
191 * - 'session' log in from cookies or session if possible
193 * Use the User::newFrom*() family of functions to set this.
198 * Lazy-initialized variables, invalidated with clearInstanceCache
200 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mRights,
201 $mBlockreason, $mEffectiveGroups, $mFormerGroups, $mBlockedGlobally,
202 $mLocked, $mHideName, $mOptions;
213 private $mBlockedFromCreateAccount = false;
215 static $idCacheByName = array();
218 * Lightweight constructor for an anonymous user.
219 * Use the User::newFrom* factory functions for other kinds of users.
223 * @see newFromConfirmationCode()
224 * @see newFromSession()
227 function __construct() {
228 $this->clearInstanceCache( 'defaults' );
231 function __toString(){
232 return $this->getName();
236 * Load the user table data for this object from the source given by mFrom.
239 if ( $this->mLoadedItems
=== true ) {
242 wfProfileIn( __METHOD__
);
244 # Set it now to avoid infinite recursion in accessors
245 $this->mLoadedItems
= true;
247 switch ( $this->mFrom
) {
249 $this->loadDefaults();
252 $this->mId
= self
::idFromName( $this->mName
);
254 # Nonexistent user placeholder object
255 $this->loadDefaults( $this->mName
);
264 $this->loadFromSession();
265 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
268 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
270 wfProfileOut( __METHOD__
);
274 * Load user table data, given mId has already been set.
275 * @return Bool false if the ID does not exist, true otherwise
278 function loadFromId() {
280 if ( $this->mId
== 0 ) {
281 $this->loadDefaults();
286 $key = wfMemcKey( 'user', 'id', $this->mId
);
287 $data = $wgMemc->get( $key );
288 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
289 # Object is expired, load from DB
294 wfDebug( "User: cache miss for user {$this->mId}\n" );
296 if ( !$this->loadFromDatabase() ) {
297 # Can't load from ID, user is anonymous
300 $this->saveToCache();
302 wfDebug( "User: got user {$this->mId} from cache\n" );
304 foreach ( self
::$mCacheVars as $name ) {
305 $this->$name = $data[$name];
312 * Save user data to the shared cache
314 function saveToCache() {
317 $this->loadOptions();
318 if ( $this->isAnon() ) {
319 // Anonymous users are uncached
323 foreach ( self
::$mCacheVars as $name ) {
324 $data[$name] = $this->$name;
326 $data['mVersion'] = MW_USER_VERSION
;
327 $key = wfMemcKey( 'user', 'id', $this->mId
);
329 $wgMemc->set( $key, $data );
333 /** @name newFrom*() static factory methods */
337 * Static factory method for creation from username.
339 * This is slightly less efficient than newFromId(), so use newFromId() if
340 * you have both an ID and a name handy.
342 * @param $name String Username, validated by Title::newFromText()
343 * @param $validate String|Bool Validate username. Takes the same parameters as
344 * User::getCanonicalName(), except that true is accepted as an alias
345 * for 'valid', for BC.
347 * @return User object, or false if the username is invalid
348 * (e.g. if it contains illegal characters or is an IP address). If the
349 * username is not present in the database, the result will be a user object
350 * with a name, zero user ID and default settings.
352 static function newFromName( $name, $validate = 'valid' ) {
353 if ( $validate === true ) {
356 $name = self
::getCanonicalName( $name, $validate );
357 if ( $name === false ) {
360 # Create unloaded user object
364 $u->setItemLoaded( 'name' );
370 * Static factory method for creation from a given user ID.
372 * @param $id Int Valid user ID
373 * @return User The corresponding User object
375 static function newFromId( $id ) {
379 $u->setItemLoaded( 'id' );
384 * Factory method to fetch whichever user has a given email confirmation code.
385 * This code is generated when an account is created or its e-mail address
388 * If the code is invalid or has expired, returns NULL.
390 * @param $code String Confirmation code
393 static function newFromConfirmationCode( $code ) {
394 $dbr = wfGetDB( DB_SLAVE
);
395 $id = $dbr->selectField( 'user', 'user_id', array(
396 'user_email_token' => md5( $code ),
397 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
399 if( $id !== false ) {
400 return User
::newFromId( $id );
407 * Create a new user object using data from session or cookies. If the
408 * login credentials are invalid, the result is an anonymous user.
412 static function newFromSession() {
414 $user->mFrom
= 'session';
419 * Create a new user object from a user row.
420 * The row should have the following fields from the user table in it:
421 * - either user_name or user_id to load further data if needed (or both)
423 * - all other fields (email, password, etc.)
424 * It is useless to provide the remaining fields if either user_id,
425 * user_name and user_real_name are not provided because the whole row
426 * will be loaded once more from the database when accessing them.
428 * @param $row Array A row from the user table
431 static function newFromRow( $row ) {
433 $user->loadFromRow( $row );
441 * Get the username corresponding to a given user ID
442 * @param $id Int User ID
443 * @return String The corresponding username
445 static function whoIs( $id ) {
446 $dbr = wfGetDB( DB_SLAVE
);
447 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), __METHOD__
);
451 * Get the real name of a user given their user ID
453 * @param $id Int User ID
454 * @return String The corresponding user's real name
456 static function whoIsReal( $id ) {
457 $dbr = wfGetDB( DB_SLAVE
);
458 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
462 * Get database id given a user name
463 * @param $name String Username
464 * @return Int|Null The corresponding user's ID, or null if user is nonexistent
466 static function idFromName( $name ) {
467 $nt = Title
::makeTitleSafe( NS_USER
, $name );
468 if( is_null( $nt ) ) {
473 if ( isset( self
::$idCacheByName[$name] ) ) {
474 return self
::$idCacheByName[$name];
477 $dbr = wfGetDB( DB_SLAVE
);
478 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
480 if ( $s === false ) {
483 $result = $s->user_id
;
486 self
::$idCacheByName[$name] = $result;
488 if ( count( self
::$idCacheByName ) > 1000 ) {
489 self
::$idCacheByName = array();
496 * Reset the cache used in idFromName(). For use in tests.
498 public static function resetIdByNameCache() {
499 self
::$idCacheByName = array();
503 * Does the string match an anonymous IPv4 address?
505 * This function exists for username validation, in order to reject
506 * usernames which are similar in form to IP addresses. Strings such
507 * as 300.300.300.300 will return true because it looks like an IP
508 * address, despite not being strictly valid.
510 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
511 * address because the usemod software would "cloak" anonymous IP
512 * addresses like this, if we allowed accounts like this to be created
513 * new users could get the old edits of these anonymous users.
515 * @param $name String to match
518 static function isIP( $name ) {
519 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP
::isIPv6($name);
523 * Is the input a valid username?
525 * Checks if the input is a valid username, we don't want an empty string,
526 * an IP address, anything that containins slashes (would mess up subpages),
527 * is longer than the maximum allowed username size or doesn't begin with
530 * @param $name String to match
533 static function isValidUserName( $name ) {
534 global $wgContLang, $wgMaxNameChars;
537 || User
::isIP( $name )
538 ||
strpos( $name, '/' ) !== false
539 ||
strlen( $name ) > $wgMaxNameChars
540 ||
$name != $wgContLang->ucfirst( $name ) ) {
541 wfDebugLog( 'username', __METHOD__
.
542 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
546 // Ensure that the name can't be misresolved as a different title,
547 // such as with extra namespace keys at the start.
548 $parsed = Title
::newFromText( $name );
549 if( is_null( $parsed )
550 ||
$parsed->getNamespace()
551 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
552 wfDebugLog( 'username', __METHOD__
.
553 ": '$name' invalid due to ambiguous prefixes" );
557 // Check an additional blacklist of troublemaker characters.
558 // Should these be merged into the title char list?
559 $unicodeBlacklist = '/[' .
560 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
561 '\x{00a0}' . # non-breaking space
562 '\x{2000}-\x{200f}' . # various whitespace
563 '\x{2028}-\x{202f}' . # breaks and control chars
564 '\x{3000}' . # ideographic space
565 '\x{e000}-\x{f8ff}' . # private use
567 if( preg_match( $unicodeBlacklist, $name ) ) {
568 wfDebugLog( 'username', __METHOD__
.
569 ": '$name' invalid due to blacklisted characters" );
577 * Usernames which fail to pass this function will be blocked
578 * from user login and new account registrations, but may be used
579 * internally by batch processes.
581 * If an account already exists in this form, login will be blocked
582 * by a failure to pass this function.
584 * @param $name String to match
587 static function isUsableName( $name ) {
588 global $wgReservedUsernames;
589 // Must be a valid username, obviously ;)
590 if ( !self
::isValidUserName( $name ) ) {
594 static $reservedUsernames = false;
595 if ( !$reservedUsernames ) {
596 $reservedUsernames = $wgReservedUsernames;
597 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
600 // Certain names may be reserved for batch processes.
601 foreach ( $reservedUsernames as $reserved ) {
602 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
603 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
605 if ( $reserved == $name ) {
613 * Usernames which fail to pass this function will be blocked
614 * from new account registrations, but may be used internally
615 * either by batch processes or by user accounts which have
616 * already been created.
618 * Additional blacklisting may be added here rather than in
619 * isValidUserName() to avoid disrupting existing accounts.
621 * @param $name String to match
624 static function isCreatableName( $name ) {
625 global $wgInvalidUsernameCharacters;
627 // Ensure that the username isn't longer than 235 bytes, so that
628 // (at least for the builtin skins) user javascript and css files
629 // will work. (bug 23080)
630 if( strlen( $name ) > 235 ) {
631 wfDebugLog( 'username', __METHOD__
.
632 ": '$name' invalid due to length" );
636 // Preg yells if you try to give it an empty string
637 if( $wgInvalidUsernameCharacters !== '' ) {
638 if( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
639 wfDebugLog( 'username', __METHOD__
.
640 ": '$name' invalid due to wgInvalidUsernameCharacters" );
645 return self
::isUsableName( $name );
649 * Is the input a valid password for this user?
651 * @param $password String Desired password
654 function isValidPassword( $password ) {
655 //simple boolean wrapper for getPasswordValidity
656 return $this->getPasswordValidity( $password ) === true;
660 * Given unvalidated password input, return error message on failure.
662 * @param $password String Desired password
663 * @return mixed: true on success, string or array of error message on failure
665 function getPasswordValidity( $password ) {
666 global $wgMinimalPasswordLength, $wgContLang;
668 static $blockedLogins = array(
669 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
670 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
673 $result = false; //init $result to false for the internal checks
675 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
678 if ( $result === false ) {
679 if( strlen( $password ) < $wgMinimalPasswordLength ) {
680 return 'passwordtooshort';
681 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
682 return 'password-name-match';
683 } elseif ( isset( $blockedLogins[ $this->getName() ] ) && $password == $blockedLogins[ $this->getName() ] ) {
684 return 'password-login-forbidden';
686 //it seems weird returning true here, but this is because of the
687 //initialization of $result to false above. If the hook is never run or it
688 //doesn't modify $result, then we will likely get down into this if with
692 } elseif( $result === true ) {
695 return $result; //the isValidPassword hook set a string $result and returned true
700 * Does a string look like an e-mail address?
702 * This validates an email address using an HTML5 specification found at:
703 * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
704 * Which as of 2011-01-24 says:
706 * A valid e-mail address is a string that matches the ABNF production
707 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
708 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
711 * This function is an implementation of the specification as requested in
714 * Client-side forms will use the same standard validation rules via JS or
715 * HTML 5 validation; additional restrictions can be enforced server-side
716 * by extensions via the 'isValidEmailAddr' hook.
718 * Note that this validation doesn't 100% match RFC 2822, but is believed
719 * to be liberal enough for wide use. Some invalid addresses will still
720 * pass validation here.
722 * @param $addr String E-mail address
724 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
726 public static function isValidEmailAddr( $addr ) {
727 return Sanitizer
::validateEmail( $addr );
731 * Given unvalidated user input, return a canonical username, or false if
732 * the username is invalid.
733 * @param $name String User input
734 * @param $validate String|Bool type of validation to use:
735 * - false No validation
736 * - 'valid' Valid for batch processes
737 * - 'usable' Valid for batch processes and login
738 * - 'creatable' Valid for batch processes, login and account creation
740 static function getCanonicalName( $name, $validate = 'valid' ) {
741 # Force usernames to capital
743 $name = $wgContLang->ucfirst( $name );
745 # Reject names containing '#'; these will be cleaned up
746 # with title normalisation, but then it's too late to
748 if( strpos( $name, '#' ) !== false )
751 # Clean up name according to title rules
752 $t = ( $validate === 'valid' ) ?
753 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
754 # Check for invalid titles
755 if( is_null( $t ) ) {
759 # Reject various classes of invalid names
761 $name = $wgAuth->getCanonicalName( $t->getText() );
763 switch ( $validate ) {
767 if ( !User
::isValidUserName( $name ) ) {
772 if ( !User
::isUsableName( $name ) ) {
777 if ( !User
::isCreatableName( $name ) ) {
782 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
788 * Count the number of edits of a user
789 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
791 * @param $uid Int User ID to check
792 * @return Int the user's edit count
794 static function edits( $uid ) {
795 wfProfileIn( __METHOD__
);
796 $dbr = wfGetDB( DB_SLAVE
);
797 // check if the user_editcount field has been initialized
798 $field = $dbr->selectField(
799 'user', 'user_editcount',
800 array( 'user_id' => $uid ),
804 if( $field === null ) { // it has not been initialized. do so.
805 $dbw = wfGetDB( DB_MASTER
);
806 $count = $dbr->selectField(
807 'revision', 'count(*)',
808 array( 'rev_user' => $uid ),
813 array( 'user_editcount' => $count ),
814 array( 'user_id' => $uid ),
820 wfProfileOut( __METHOD__
);
825 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
826 * @todo hash random numbers to improve security, like generateToken()
828 * @return String new random password
830 static function randomPassword() {
831 global $wgMinimalPasswordLength;
832 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
833 $l = strlen( $pwchars ) - 1;
835 $pwlength = max( 7, $wgMinimalPasswordLength );
836 $digit = mt_rand( 0, $pwlength - 1 );
838 for ( $i = 0; $i < $pwlength; $i++
) {
839 $np .= $i == $digit ?
chr( mt_rand( 48, 57 ) ) : $pwchars[ mt_rand( 0, $l ) ];
845 * Set cached properties to default.
847 * @note This no longer clears uncached lazy-initialised properties;
848 * the constructor does that instead.
851 function loadDefaults( $name = false ) {
852 wfProfileIn( __METHOD__
);
857 $this->mName
= $name;
858 $this->mRealName
= '';
859 $this->mPassword
= $this->mNewpassword
= '';
860 $this->mNewpassTime
= null;
862 $this->mOptionOverrides
= null;
863 $this->mOptionsLoaded
= false;
865 if( $wgRequest->getCookie( 'LoggedOut' ) !== null ) {
866 $this->mTouched
= wfTimestamp( TS_MW
, $wgRequest->getCookie( 'LoggedOut' ) );
868 $this->mTouched
= '0'; # Allow any pages to be cached
871 $this->setToken(); # Random
872 $this->mEmailAuthenticated
= null;
873 $this->mEmailToken
= '';
874 $this->mEmailTokenExpires
= null;
875 $this->mRegistration
= wfTimestamp( TS_MW
);
876 $this->mGroups
= array();
878 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
880 wfProfileOut( __METHOD__
);
884 * Return whether an item has been loaded.
886 * @param $item String: item to check. Current possibilities:
890 * @param $all String: 'all' to check if the whole object has been loaded
891 * or any other string to check if only the item is available (e.g.
895 public function isItemLoaded( $item, $all = 'all' ) {
896 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
897 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
901 * Set that an item has been loaded
903 * @param $item String
905 private function setItemLoaded( $item ) {
906 if ( is_array( $this->mLoadedItems
) ) {
907 $this->mLoadedItems
[$item] = true;
912 * Load user data from the session or login cookie. If there are no valid
913 * credentials, initialises the user as an anonymous user.
914 * @return Bool True if the user is logged in, false otherwise.
916 private function loadFromSession() {
917 global $wgRequest, $wgExternalAuthType, $wgAutocreatePolicy;
920 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
921 if ( $result !== null ) {
925 if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
926 $extUser = ExternalUser
::newFromCookie();
928 # TODO: Automatically create the user here (or probably a bit
929 # lower down, in fact)
933 $cookieId = $wgRequest->getCookie( 'UserID' );
934 $sessId = $wgRequest->getSessionData( 'wsUserID' );
936 if ( $cookieId !== null ) {
937 $sId = intval( $cookieId );
938 if( $sessId !== null && $cookieId != $sessId ) {
939 $this->loadDefaults(); // Possible collision!
940 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
941 cookie user ID ($sId) don't match!" );
944 $wgRequest->setSessionData( 'wsUserID', $sId );
945 } elseif ( $sessId !== null && $sessId != 0 ) {
948 $this->loadDefaults();
952 if ( $wgRequest->getSessionData( 'wsUserName' ) !== null ) {
953 $sName = $wgRequest->getSessionData( 'wsUserName' );
954 } elseif ( $wgRequest->getCookie( 'UserName' ) !== null ) {
955 $sName = $wgRequest->getCookie( 'UserName' );
956 $wgRequest->setSessionData( 'wsUserName', $sName );
958 $this->loadDefaults();
962 $proposedUser = User
::newFromId( $sId );
963 if ( !$proposedUser->isLoggedIn() ) {
965 $this->loadDefaults();
969 global $wgBlockDisablesLogin;
970 if( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
971 # User blocked and we've disabled blocked user logins
972 $this->loadDefaults();
976 if ( $wgRequest->getSessionData( 'wsToken' ) !== null ) {
977 $passwordCorrect = $proposedUser->getToken() === $wgRequest->getSessionData( 'wsToken' );
979 } elseif ( $wgRequest->getCookie( 'Token' ) !== null ) {
980 $passwordCorrect = $proposedUser->getToken() === $wgRequest->getCookie( 'Token' );
983 # No session or persistent login cookie
984 $this->loadDefaults();
988 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
989 $this->loadFromUserObject( $proposedUser );
990 $wgRequest->setSessionData( 'wsToken', $this->mToken
);
991 wfDebug( "User: logged in from $from\n" );
994 # Invalid credentials
995 wfDebug( "User: can't log in from $from, invalid credentials\n" );
996 $this->loadDefaults();
1002 * Load user and user_group data from the database.
1003 * $this->mId must be set, this is how the user is identified.
1005 * @return Bool True if the user exists, false if the user is anonymous
1008 function loadFromDatabase() {
1010 $this->mId
= intval( $this->mId
);
1012 /** Anonymous user */
1014 $this->loadDefaults();
1018 $dbr = wfGetDB( DB_MASTER
);
1019 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
1021 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1023 if ( $s !== false ) {
1024 # Initialise user table data
1025 $this->loadFromRow( $s );
1026 $this->mGroups
= null; // deferred
1027 $this->getEditCount(); // revalidation for nulls
1032 $this->loadDefaults();
1038 * Initialize this object from a row from the user table.
1040 * @param $row Array Row from the user table to load.
1042 function loadFromRow( $row ) {
1045 if ( isset( $row->user_name
) ) {
1046 $this->mName
= $row->user_name
;
1047 $this->mFrom
= 'name';
1048 $this->setItemLoaded( 'name' );
1053 if ( isset( $row->user_real_name
) ) {
1054 $this->mRealName
= $row->user_real_name
;
1055 $this->setItemLoaded( 'realname' );
1060 if ( isset( $row->user_id
) ) {
1061 $this->mId
= intval( $row->user_id
);
1062 $this->mFrom
= 'id';
1063 $this->setItemLoaded( 'id' );
1068 if ( isset( $row->user_password
) ) {
1069 $this->mPassword
= $row->user_password
;
1070 $this->mNewpassword
= $row->user_newpassword
;
1071 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1072 $this->mEmail
= $row->user_email
;
1073 $this->decodeOptions( $row->user_options
);
1074 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
1075 $this->mToken
= $row->user_token
;
1076 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1077 $this->mEmailToken
= $row->user_email_token
;
1078 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1079 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1080 $this->mEditCount
= $row->user_editcount
;
1086 $this->mLoadedItems
= true;
1091 * Load the data for this user object from another user object.
1095 protected function loadFromUserObject( $user ) {
1097 $user->loadGroups();
1098 $user->loadOptions();
1099 foreach ( self
::$mCacheVars as $var ) {
1100 $this->$var = $user->$var;
1105 * Load the groups from the database if they aren't already loaded.
1108 function loadGroups() {
1109 if ( is_null( $this->mGroups
) ) {
1110 $dbr = wfGetDB( DB_MASTER
);
1111 $res = $dbr->select( 'user_groups',
1112 array( 'ug_group' ),
1113 array( 'ug_user' => $this->mId
),
1115 $this->mGroups
= array();
1116 foreach ( $res as $row ) {
1117 $this->mGroups
[] = $row->ug_group
;
1123 * Add the user to the group if he/she meets given criteria.
1125 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1126 * possible to remove manually via Special:UserRights. In such case it
1127 * will not be re-added automatically. The user will also not lose the
1128 * group if they no longer meet the criteria.
1130 * @param $event String key in $wgAutopromoteOnce (each one has groups/criteria)
1132 * @return array Array of groups the user has been promoted to.
1134 * @see $wgAutopromoteOnce
1136 public function addAutopromoteOnceGroups( $event ) {
1137 $toPromote = array();
1138 if ( $this->getId() ) {
1139 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1140 if ( count( $toPromote ) ) {
1141 $oldGroups = $this->getGroups(); // previous groups
1142 foreach ( $toPromote as $group ) {
1143 $this->addGroup( $group );
1145 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1147 $log = new LogPage( 'rights', false /* not in RC */ );
1148 $log->addEntry( 'autopromote',
1149 $this->getUserPage(),
1151 array( implode( ', ', $oldGroups ), implode( ', ', $newGroups ) )
1159 * Clear various cached data stored in this object.
1160 * @param $reloadFrom String Reload user and user_groups table data from a
1161 * given source. May be "name", "id", "defaults", "session", or false for
1164 function clearInstanceCache( $reloadFrom = false ) {
1165 $this->mNewtalk
= -1;
1166 $this->mDatePreference
= null;
1167 $this->mBlockedby
= -1; # Unset
1168 $this->mHash
= false;
1169 $this->mSkin
= null;
1170 $this->mRights
= null;
1171 $this->mEffectiveGroups
= null;
1172 $this->mOptions
= null;
1174 if ( $reloadFrom ) {
1175 $this->mLoadedItems
= array();
1176 $this->mFrom
= $reloadFrom;
1181 * Combine the language default options with any site-specific options
1182 * and add the default language variants.
1184 * @return Array of String options
1186 static function getDefaultOptions() {
1187 global $wgNamespacesToBeSearchedDefault;
1189 * Site defaults will override the global/language defaults
1191 global $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1192 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
1195 * default language setting
1197 $variant = $wgContLang->getDefaultVariant();
1198 $defOpt['variant'] = $variant;
1199 $defOpt['language'] = $variant;
1200 foreach( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1201 $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1203 $defOpt['skin'] = $wgDefaultSkin;
1209 * Get a given default option value.
1211 * @param $opt String Name of option to retrieve
1212 * @return String Default option value
1214 public static function getDefaultOption( $opt ) {
1215 $defOpts = self
::getDefaultOptions();
1216 if( isset( $defOpts[$opt] ) ) {
1217 return $defOpts[$opt];
1225 * Get blocking information
1227 * @param $bFromSlave Bool Whether to check the slave database first. To
1228 * improve performance, non-critical checks are done
1229 * against slaves. Check when actually saving should be
1230 * done against master.
1232 function getBlockedStatus( $bFromSlave = true ) {
1233 global $wgProxyWhitelist, $wgUser;
1235 if ( -1 != $this->mBlockedby
) {
1239 wfProfileIn( __METHOD__
);
1240 wfDebug( __METHOD__
.": checking...\n" );
1242 // Initialize data...
1243 // Otherwise something ends up stomping on $this->mBlockedby when
1244 // things get lazy-loaded later, causing false positive block hits
1245 // due to -1 !== 0. Probably session-related... Nothing should be
1246 // overwriting mBlockedby, surely?
1249 $this->mBlockedby
= 0;
1250 $this->mHideName
= 0;
1251 $this->mAllowUsertalk
= 0;
1253 # We only need to worry about passing the IP address to the Block generator if the
1254 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1255 # know which IP address they're actually coming from
1256 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1263 $this->mBlock
= Block
::newFromTarget( $this->getName(), $ip, !$bFromSlave );
1264 if ( $this->mBlock
instanceof Block
) {
1265 wfDebug( __METHOD__
. ": Found block.\n" );
1266 $this->mBlockedby
= $this->mBlock
->getByName();
1267 $this->mBlockreason
= $this->mBlock
->mReason
;
1268 $this->mHideName
= $this->mBlock
->mHideName
;
1269 $this->mAllowUsertalk
= !$this->mBlock
->prevents( 'editownusertalk' );
1270 if ( $this->isLoggedIn() && $wgUser->getID() == $this->getID() ) {
1271 $this->spreadBlock();
1276 if ( $ip !== null && !$this->isAllowed( 'proxyunbannable' ) && !in_array( $ip, $wgProxyWhitelist ) ) {
1278 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1279 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1280 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1284 if ( !$this->mBlockedby
&& !$this->getID() ) {
1285 if ( $this->isDnsBlacklisted( $ip ) ) {
1286 $this->mBlockedby
= wfMsg( 'sorbs' );
1287 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1293 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1295 wfProfileOut( __METHOD__
);
1299 * Whether the given IP is in a DNS blacklist.
1301 * @param $ip String IP to check
1302 * @param $checkWhitelist Bool: whether to check the whitelist first
1303 * @return Bool True if blacklisted.
1305 function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1306 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1307 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1309 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
1312 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
1315 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1316 return $this->inDnsBlacklist( $ip, $urls );
1320 * Whether the given IP is in a given DNS blacklist.
1322 * @param $ip String IP to check
1323 * @param $bases String|Array of Strings: URL of the DNS blacklist
1324 * @return Bool True if blacklisted.
1326 function inDnsBlacklist( $ip, $bases ) {
1327 wfProfileIn( __METHOD__
);
1330 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1331 if( IP
::isIPv4( $ip ) ) {
1332 # Reverse IP, bug 21255
1333 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1335 foreach( (array)$bases as $base ) {
1337 $host = "$ipReversed.$base";
1340 $ipList = gethostbynamel( $host );
1343 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1347 wfDebug( "Requested $host, not found in $base.\n" );
1352 wfProfileOut( __METHOD__
);
1357 * Check if an IP address is in the local proxy list
1360 public static function isLocallyBlockedProxy( $ip ) {
1361 global $wgProxyList;
1363 if ( !$wgProxyList ) {
1366 wfProfileIn( __METHOD__
);
1368 if ( !is_array( $wgProxyList ) ) {
1369 # Load from the specified file
1370 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1373 if ( !is_array( $wgProxyList ) ) {
1375 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1377 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1378 # Old-style flipped proxy list
1383 wfProfileOut( __METHOD__
);
1388 * Is this user subject to rate limiting?
1390 * @return Bool True if rate limited
1392 public function isPingLimitable() {
1393 global $wgRateLimitsExcludedIPs;
1394 if( in_array( wfGetIP(), $wgRateLimitsExcludedIPs ) ) {
1395 // No other good way currently to disable rate limits
1396 // for specific IPs. :P
1397 // But this is a crappy hack and should die.
1400 return !$this->isAllowed('noratelimit');
1404 * Primitive rate limits: enforce maximum actions per time period
1405 * to put a brake on flooding.
1407 * @note When using a shared cache like memcached, IP-address
1408 * last-hit counters will be shared across wikis.
1410 * @param $action String Action to enforce; 'edit' if unspecified
1411 * @return Bool True if a rate limiter was tripped
1413 function pingLimiter( $action = 'edit' ) {
1414 # Call the 'PingLimiter' hook
1416 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1420 global $wgRateLimits;
1421 if( !isset( $wgRateLimits[$action] ) ) {
1425 # Some groups shouldn't trigger the ping limiter, ever
1426 if( !$this->isPingLimitable() )
1429 global $wgMemc, $wgRateLimitLog;
1430 wfProfileIn( __METHOD__
);
1432 $limits = $wgRateLimits[$action];
1434 $id = $this->getId();
1438 if( isset( $limits['anon'] ) && $id == 0 ) {
1439 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1442 if( isset( $limits['user'] ) && $id != 0 ) {
1443 $userLimit = $limits['user'];
1445 if( $this->isNewbie() ) {
1446 if( isset( $limits['newbie'] ) && $id != 0 ) {
1447 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1449 if( isset( $limits['ip'] ) ) {
1450 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1453 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1454 $subnet = $matches[1];
1455 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1458 // Check for group-specific permissions
1459 // If more than one group applies, use the group with the highest limit
1460 foreach ( $this->getGroups() as $group ) {
1461 if ( isset( $limits[$group] ) ) {
1462 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1463 $userLimit = $limits[$group];
1467 // Set the user limit key
1468 if ( $userLimit !== false ) {
1469 wfDebug( __METHOD__
. ": effective user limit: $userLimit\n" );
1470 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1474 foreach( $keys as $key => $limit ) {
1475 list( $max, $period ) = $limit;
1476 $summary = "(limit $max in {$period}s)";
1477 $count = $wgMemc->get( $key );
1480 if( $count > $max ) {
1481 wfDebug( __METHOD__
. ": tripped! $key at $count $summary\n" );
1482 if( $wgRateLimitLog ) {
1483 @file_put_contents
( $wgRateLimitLog, wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", FILE_APPEND
);
1487 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1490 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1491 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1493 $wgMemc->incr( $key );
1496 wfProfileOut( __METHOD__
);
1501 * Check if user is blocked
1503 * @param $bFromSlave Bool Whether to check the slave database instead of the master
1504 * @return Bool True if blocked, false otherwise
1506 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1507 $this->getBlockedStatus( $bFromSlave );
1508 return $this->mBlock
instanceof Block
&& $this->mBlock
->prevents( 'edit' );
1512 * Check if user is blocked from editing a particular article
1514 * @param $title Title to check
1515 * @param $bFromSlave Bool whether to check the slave database instead of the master
1518 function isBlockedFrom( $title, $bFromSlave = false ) {
1519 global $wgBlockAllowsUTEdit;
1520 wfProfileIn( __METHOD__
);
1522 $blocked = $this->isBlocked( $bFromSlave );
1523 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1524 # If a user's name is suppressed, they cannot make edits anywhere
1525 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1526 $title->getNamespace() == NS_USER_TALK
) {
1528 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1531 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1533 wfProfileOut( __METHOD__
);
1538 * If user is blocked, return the name of the user who placed the block
1539 * @return String name of blocker
1541 function blockedBy() {
1542 $this->getBlockedStatus();
1543 return $this->mBlockedby
;
1547 * If user is blocked, return the specified reason for the block
1548 * @return String Blocking reason
1550 function blockedFor() {
1551 $this->getBlockedStatus();
1552 return $this->mBlockreason
;
1556 * If user is blocked, return the ID for the block
1557 * @return Int Block ID
1559 function getBlockId() {
1560 $this->getBlockedStatus();
1561 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1565 * Check if user is blocked on all wikis.
1566 * Do not use for actual edit permission checks!
1567 * This is intented for quick UI checks.
1569 * @param $ip String IP address, uses current client if none given
1570 * @return Bool True if blocked, false otherwise
1572 function isBlockedGlobally( $ip = '' ) {
1573 if( $this->mBlockedGlobally
!== null ) {
1574 return $this->mBlockedGlobally
;
1576 // User is already an IP?
1577 if( IP
::isIPAddress( $this->getName() ) ) {
1578 $ip = $this->getName();
1583 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1584 $this->mBlockedGlobally
= (bool)$blocked;
1585 return $this->mBlockedGlobally
;
1589 * Check if user account is locked
1591 * @return Bool True if locked, false otherwise
1593 function isLocked() {
1594 if( $this->mLocked
!== null ) {
1595 return $this->mLocked
;
1598 $authUser = $wgAuth->getUserInstance( $this );
1599 $this->mLocked
= (bool)$authUser->isLocked();
1600 return $this->mLocked
;
1604 * Check if user account is hidden
1606 * @return Bool True if hidden, false otherwise
1608 function isHidden() {
1609 if( $this->mHideName
!== null ) {
1610 return $this->mHideName
;
1612 $this->getBlockedStatus();
1613 if( !$this->mHideName
) {
1615 $authUser = $wgAuth->getUserInstance( $this );
1616 $this->mHideName
= (bool)$authUser->isHidden();
1618 return $this->mHideName
;
1622 * Get the user's ID.
1623 * @return Int The user's ID; 0 if the user is anonymous or nonexistent
1626 if( $this->mId
=== null && $this->mName
!== null
1627 && User
::isIP( $this->mName
) ) {
1628 // Special case, we know the user is anonymous
1630 } elseif( !$this->isItemLoaded( 'id' ) ) {
1631 // Don't load if this was initialized from an ID
1638 * Set the user and reload all fields according to a given ID
1639 * @param $v Int User ID to reload
1641 function setId( $v ) {
1643 $this->clearInstanceCache( 'id' );
1647 * Get the user name, or the IP of an anonymous user
1648 * @return String User's name or IP address
1650 function getName() {
1651 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1652 # Special case optimisation
1653 return $this->mName
;
1656 if ( $this->mName
=== false ) {
1658 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1660 return $this->mName
;
1665 * Set the user name.
1667 * This does not reload fields from the database according to the given
1668 * name. Rather, it is used to create a temporary "nonexistent user" for
1669 * later addition to the database. It can also be used to set the IP
1670 * address for an anonymous user to something other than the current
1673 * @note User::newFromName() has rougly the same function, when the named user
1675 * @param $str String New user name to set
1677 function setName( $str ) {
1679 $this->mName
= $str;
1683 * Get the user's name escaped by underscores.
1684 * @return String Username escaped by underscores.
1686 function getTitleKey() {
1687 return str_replace( ' ', '_', $this->getName() );
1691 * Check if the user has new messages.
1692 * @return Bool True if the user has new messages
1694 function getNewtalk() {
1697 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1698 if( $this->mNewtalk
=== -1 ) {
1699 $this->mNewtalk
= false; # reset talk page status
1701 # Check memcached separately for anons, who have no
1702 # entire User object stored in there.
1705 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1706 $newtalk = $wgMemc->get( $key );
1707 if( strval( $newtalk ) !== '' ) {
1708 $this->mNewtalk
= (bool)$newtalk;
1710 // Since we are caching this, make sure it is up to date by getting it
1712 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1713 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1716 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1720 return (bool)$this->mNewtalk
;
1724 * Return the talk page(s) this user has new messages on.
1725 * @return Array of String page URLs
1727 function getNewMessageLinks() {
1729 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) )
1732 if( !$this->getNewtalk() )
1734 $up = $this->getUserPage();
1735 $utp = $up->getTalkPage();
1736 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL() ) );
1740 * Internal uncached check for new messages
1743 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1744 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1745 * @param $fromMaster Bool true to fetch from the master, false for a slave
1746 * @return Bool True if the user has new messages
1748 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
1749 if ( $fromMaster ) {
1750 $db = wfGetDB( DB_MASTER
);
1752 $db = wfGetDB( DB_SLAVE
);
1754 $ok = $db->selectField( 'user_newtalk', $field,
1755 array( $field => $id ), __METHOD__
);
1756 return $ok !== false;
1760 * Add or update the new messages flag
1761 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1762 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1763 * @return Bool True if successful, false otherwise
1765 protected function updateNewtalk( $field, $id ) {
1766 $dbw = wfGetDB( DB_MASTER
);
1767 $dbw->insert( 'user_newtalk',
1768 array( $field => $id ),
1771 if ( $dbw->affectedRows() ) {
1772 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
1775 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
1781 * Clear the new messages flag for the given user
1782 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1783 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1784 * @return Bool True if successful, false otherwise
1786 protected function deleteNewtalk( $field, $id ) {
1787 $dbw = wfGetDB( DB_MASTER
);
1788 $dbw->delete( 'user_newtalk',
1789 array( $field => $id ),
1791 if ( $dbw->affectedRows() ) {
1792 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
1795 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
1801 * Update the 'You have new messages!' status.
1802 * @param $val Bool Whether the user has new messages
1804 function setNewtalk( $val ) {
1805 if( wfReadOnly() ) {
1810 $this->mNewtalk
= $val;
1812 if( $this->isAnon() ) {
1814 $id = $this->getName();
1817 $id = $this->getId();
1822 $changed = $this->updateNewtalk( $field, $id );
1824 $changed = $this->deleteNewtalk( $field, $id );
1827 if( $this->isAnon() ) {
1828 // Anons have a separate memcached space, since
1829 // user records aren't kept for them.
1830 $key = wfMemcKey( 'newtalk', 'ip', $id );
1831 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1834 $this->invalidateCache();
1839 * Generate a current or new-future timestamp to be stored in the
1840 * user_touched field when we update things.
1841 * @return String Timestamp in TS_MW format
1843 private static function newTouchedTimestamp() {
1844 global $wgClockSkewFudge;
1845 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1849 * Clear user data from memcached.
1850 * Use after applying fun updates to the database; caller's
1851 * responsibility to update user_touched if appropriate.
1853 * Called implicitly from invalidateCache() and saveSettings().
1855 private function clearSharedCache() {
1859 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1864 * Immediately touch the user data cache for this account.
1865 * Updates user_touched field, and removes account data from memcached
1866 * for reload on the next hit.
1868 function invalidateCache() {
1869 if( wfReadOnly() ) {
1874 $this->mTouched
= self
::newTouchedTimestamp();
1876 $dbw = wfGetDB( DB_MASTER
);
1877 $dbw->update( 'user',
1878 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1879 array( 'user_id' => $this->mId
),
1882 $this->clearSharedCache();
1887 * Validate the cache for this account.
1888 * @param $timestamp String A timestamp in TS_MW format
1890 function validateCache( $timestamp ) {
1892 return ( $timestamp >= $this->mTouched
);
1896 * Get the user touched timestamp
1897 * @return String timestamp
1899 function getTouched() {
1901 return $this->mTouched
;
1905 * Set the password and reset the random token.
1906 * Calls through to authentication plugin if necessary;
1907 * will have no effect if the auth plugin refuses to
1908 * pass the change through or if the legal password
1911 * As a special case, setting the password to null
1912 * wipes it, so the account cannot be logged in until
1913 * a new password is set, for instance via e-mail.
1915 * @param $str String New password to set
1916 * @throws PasswordError on failure
1918 function setPassword( $str ) {
1921 if( $str !== null ) {
1922 if( !$wgAuth->allowPasswordChange() ) {
1923 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1926 if( !$this->isValidPassword( $str ) ) {
1927 global $wgMinimalPasswordLength;
1928 $valid = $this->getPasswordValidity( $str );
1929 if ( is_array( $valid ) ) {
1930 $message = array_shift( $valid );
1934 $params = array( $wgMinimalPasswordLength );
1936 throw new PasswordError( wfMsgExt( $message, array( 'parsemag' ), $params ) );
1940 if( !$wgAuth->setPassword( $this, $str ) ) {
1941 throw new PasswordError( wfMsg( 'externaldberror' ) );
1944 $this->setInternalPassword( $str );
1950 * Set the password and reset the random token unconditionally.
1952 * @param $str String New password to set
1954 function setInternalPassword( $str ) {
1958 if( $str === null ) {
1959 // Save an invalid hash...
1960 $this->mPassword
= '';
1962 $this->mPassword
= self
::crypt( $str );
1964 $this->mNewpassword
= '';
1965 $this->mNewpassTime
= null;
1969 * Get the user's current token.
1970 * @return String Token
1972 function getToken() {
1974 return $this->mToken
;
1978 * Set the random token (used for persistent authentication)
1979 * Called from loadDefaults() among other places.
1981 * @param $token String If specified, set the token to this value
1984 function setToken( $token = false ) {
1985 global $wgSecretKey, $wgProxyKey;
1988 if ( $wgSecretKey ) {
1989 $key = $wgSecretKey;
1990 } elseif ( $wgProxyKey ) {
1995 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1997 $this->mToken
= $token;
2002 * Set the cookie password
2004 * @param $str String New cookie password
2007 function setCookiePassword( $str ) {
2009 $this->mCookiePassword
= md5( $str );
2013 * Set the password for a password reminder or new account email
2015 * @param $str String New password to set
2016 * @param $throttle Bool If true, reset the throttle timestamp to the present
2018 function setNewpassword( $str, $throttle = true ) {
2020 $this->mNewpassword
= self
::crypt( $str );
2022 $this->mNewpassTime
= wfTimestampNow();
2027 * Has password reminder email been sent within the last
2028 * $wgPasswordReminderResendTime hours?
2031 function isPasswordReminderThrottled() {
2032 global $wgPasswordReminderResendTime;
2034 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2037 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2038 return time() < $expiry;
2042 * Get the user's e-mail address
2043 * @return String User's email address
2045 function getEmail() {
2047 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
2048 return $this->mEmail
;
2052 * Get the timestamp of the user's e-mail authentication
2053 * @return String TS_MW timestamp
2055 function getEmailAuthenticationTimestamp() {
2057 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2058 return $this->mEmailAuthenticated
;
2062 * Set the user's e-mail address
2063 * @param $str String New e-mail address
2065 function setEmail( $str ) {
2067 $this->mEmail
= $str;
2068 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
2072 * Get the user's real name
2073 * @return String User's real name
2075 function getRealName() {
2076 if ( !$this->isItemLoaded( 'realname' ) ) {
2080 return $this->mRealName
;
2084 * Set the user's real name
2085 * @param $str String New real name
2087 function setRealName( $str ) {
2089 $this->mRealName
= $str;
2093 * Get the user's current setting for a given option.
2095 * @param $oname String The option to check
2096 * @param $defaultOverride String A default value returned if the option does not exist
2097 * @param $ignoreHidden Bool = whether to ignore the effects of $wgHiddenPrefs
2098 * @return String User's current value for the option
2099 * @see getBoolOption()
2100 * @see getIntOption()
2102 function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2103 global $wgHiddenPrefs;
2104 $this->loadOptions();
2106 if ( is_null( $this->mOptions
) ) {
2107 if($defaultOverride != '') {
2108 return $defaultOverride;
2110 $this->mOptions
= User
::getDefaultOptions();
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 if( in_array( $oname, $wgHiddenPrefs ) && !$ignoreHidden ){
2119 return self
::getDefaultOption( $oname );
2122 if ( array_key_exists( $oname, $this->mOptions
) ) {
2123 return $this->mOptions
[$oname];
2125 return $defaultOverride;
2130 * Get all user's options
2134 public function getOptions() {
2135 global $wgHiddenPrefs;
2136 $this->loadOptions();
2137 $options = $this->mOptions
;
2139 # We want 'disabled' preferences to always behave as the default value for
2140 # users, even if they have set the option explicitly in their settings (ie they
2141 # set it, and then it was disabled removing their ability to change it). But
2142 # we don't want to erase the preferences in the database in case the preference
2143 # is re-enabled again. So don't touch $mOptions, just override the returned value
2144 foreach( $wgHiddenPrefs as $pref ){
2145 $default = self
::getDefaultOption( $pref );
2146 if( $default !== null ){
2147 $options[$pref] = $default;
2155 * Get the user's current setting for a given option, as a boolean value.
2157 * @param $oname String The option to check
2158 * @return Bool User's current value for the option
2161 function getBoolOption( $oname ) {
2162 return (bool)$this->getOption( $oname );
2167 * Get the user's current setting for a given option, as a boolean value.
2169 * @param $oname String The option to check
2170 * @param $defaultOverride Int A default value returned if the option does not exist
2171 * @return Int User's current value for the option
2174 function getIntOption( $oname, $defaultOverride=0 ) {
2175 $val = $this->getOption( $oname );
2177 $val = $defaultOverride;
2179 return intval( $val );
2183 * Set the given option for a user.
2185 * @param $oname String The option to set
2186 * @param $val mixed New value to set
2188 function setOption( $oname, $val ) {
2190 $this->loadOptions();
2192 if ( $oname == 'skin' ) {
2193 # Clear cached skin, so the new one displays immediately in Special:Preferences
2194 $this->mSkin
= null;
2197 // Explicitly NULL values should refer to defaults
2198 global $wgDefaultUserOptions;
2199 if( is_null( $val ) && isset( $wgDefaultUserOptions[$oname] ) ) {
2200 $val = $wgDefaultUserOptions[$oname];
2203 $this->mOptions
[$oname] = $val;
2207 * Reset all options to the site defaults
2209 function resetOptions() {
2210 $this->mOptions
= self
::getDefaultOptions();
2214 * Get the user's preferred date format.
2215 * @return String User's preferred date format
2217 function getDatePreference() {
2218 // Important migration for old data rows
2219 if ( is_null( $this->mDatePreference
) ) {
2221 $value = $this->getOption( 'date' );
2222 $map = $wgLang->getDatePreferenceMigrationMap();
2223 if ( isset( $map[$value] ) ) {
2224 $value = $map[$value];
2226 $this->mDatePreference
= $value;
2228 return $this->mDatePreference
;
2232 * Get the user preferred stub threshold
2234 function getStubThreshold() {
2235 global $wgMaxArticleSize; # Maximum article size, in Kb
2236 $threshold = intval( $this->getOption( 'stubthreshold' ) );
2237 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2238 # If they have set an impossible value, disable the preference
2239 # so we can use the parser cache again.
2246 * Get the permissions this user has.
2247 * @return Array of String permission names
2249 function getRights() {
2250 if ( is_null( $this->mRights
) ) {
2251 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2252 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2253 // Force reindexation of rights when a hook has unset one of them
2254 $this->mRights
= array_values( $this->mRights
);
2256 return $this->mRights
;
2260 * Get the list of explicit group memberships this user has.
2261 * The implicit * and user groups are not included.
2262 * @return Array of String internal group names
2264 function getGroups() {
2266 return $this->mGroups
;
2270 * Get the list of implicit group memberships this user has.
2271 * This includes all explicit groups, plus 'user' if logged in,
2272 * '*' for all accounts, and autopromoted groups
2273 * @param $recache Bool Whether to avoid the cache
2274 * @return Array of String internal group names
2276 function getEffectiveGroups( $recache = false ) {
2277 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2278 wfProfileIn( __METHOD__
);
2279 $this->mEffectiveGroups
= $this->getGroups();
2280 $this->mEffectiveGroups
[] = '*';
2281 if( $this->getId() ) {
2282 $this->mEffectiveGroups
[] = 'user';
2284 $this->mEffectiveGroups
= array_unique( array_merge(
2285 $this->mEffectiveGroups
,
2286 Autopromote
::getAutopromoteGroups( $this )
2289 # Hook for additional groups
2290 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2292 wfProfileOut( __METHOD__
);
2294 return $this->mEffectiveGroups
;
2298 * Returns the groups the user has belonged to.
2300 * The user may still belong to the returned groups. Compare with getGroups().
2302 * The function will not return groups the user had belonged to before MW 1.17
2304 * @return array Names of the groups the user has belonged to.
2306 function getFormerGroups() {
2307 if( is_null( $this->mFormerGroups
) ) {
2308 $dbr = wfGetDB( DB_MASTER
);
2309 $res = $dbr->select( 'user_former_groups',
2310 array( 'ufg_group' ),
2311 array( 'ufg_user' => $this->mId
),
2313 $this->mFormerGroups
= array();
2314 foreach( $res as $row ) {
2315 $this->mFormerGroups
[] = $row->ufg_group
;
2318 return $this->mFormerGroups
;
2322 * Get the user's edit count.
2325 function getEditCount() {
2326 if( $this->getId() ) {
2327 if ( !isset( $this->mEditCount
) ) {
2328 /* Populate the count, if it has not been populated yet */
2329 $this->mEditCount
= User
::edits( $this->mId
);
2331 return $this->mEditCount
;
2339 * Add the user to the given group.
2340 * This takes immediate effect.
2341 * @param $group String Name of the group to add
2343 function addGroup( $group ) {
2344 if( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2345 $dbw = wfGetDB( DB_MASTER
);
2346 if( $this->getId() ) {
2347 $dbw->insert( 'user_groups',
2349 'ug_user' => $this->getID(),
2350 'ug_group' => $group,
2353 array( 'IGNORE' ) );
2356 $this->loadGroups();
2357 $this->mGroups
[] = $group;
2358 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2360 $this->invalidateCache();
2364 * Remove the user from the given group.
2365 * This takes immediate effect.
2366 * @param $group String Name of the group to remove
2368 function removeGroup( $group ) {
2370 if( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2371 $dbw = wfGetDB( DB_MASTER
);
2372 $dbw->delete( 'user_groups',
2374 'ug_user' => $this->getID(),
2375 'ug_group' => $group,
2377 // Remember that the user was in this group
2378 $dbw->insert( 'user_former_groups',
2380 'ufg_user' => $this->getID(),
2381 'ufg_group' => $group,
2384 array( 'IGNORE' ) );
2386 $this->loadGroups();
2387 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2388 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2390 $this->invalidateCache();
2394 * Get whether the user is logged in
2397 function isLoggedIn() {
2398 return $this->getID() != 0;
2402 * Get whether the user is anonymous
2406 return !$this->isLoggedIn();
2410 * Check if user is allowed to access a feature / make an action
2411 * @param varargs String permissions to test
2412 * @return Boolean: True if user is allowed to perform *any* of the given actions
2414 public function isAllowedAny( /*...*/ ){
2415 $permissions = func_get_args();
2416 foreach( $permissions as $permission ){
2417 if( $this->isAllowed( $permission ) ){
2425 * @param varargs String
2426 * @return bool True if the user is allowed to perform *all* of the given actions
2428 public function isAllowedAll( /*...*/ ){
2429 $permissions = func_get_args();
2430 foreach( $permissions as $permission ){
2431 if( !$this->isAllowed( $permission ) ){
2439 * Internal mechanics of testing a permission
2440 * @param $action String
2443 public function isAllowed( $action = '' ) {
2444 if ( $action === '' ) {
2445 return true; // In the spirit of DWIM
2447 # Patrolling may not be enabled
2448 if( $action === 'patrol' ||
$action === 'autopatrol' ) {
2449 global $wgUseRCPatrol, $wgUseNPPatrol;
2450 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2453 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2454 # by misconfiguration: 0 == 'foo'
2455 return in_array( $action, $this->getRights(), true );
2459 * Check whether to enable recent changes patrol features for this user
2460 * @return Boolean: True or false
2462 public function useRCPatrol() {
2463 global $wgUseRCPatrol;
2464 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
2468 * Check whether to enable new pages patrol features for this user
2469 * @return Bool True or false
2471 public function useNPPatrol() {
2472 global $wgUseRCPatrol, $wgUseNPPatrol;
2473 return( ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) ) );
2477 * Get the current skin, loading it if required
2478 * @return Skin The current skin
2479 * @todo FIXME: Need to check the old failback system [AV]
2480 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
2482 function getSkin() {
2483 return RequestContext
::getMain()->getSkin();
2487 * Check the watched status of an article.
2488 * @param $title Title of the article to look at
2491 function isWatched( $title ) {
2492 $wl = WatchedItem
::fromUserTitle( $this, $title );
2493 return $wl->isWatched();
2498 * @param $title Title of the article to look at
2500 function addWatch( $title ) {
2501 $wl = WatchedItem
::fromUserTitle( $this, $title );
2503 $this->invalidateCache();
2507 * Stop watching an article.
2508 * @param $title Title of the article to look at
2510 function removeWatch( $title ) {
2511 $wl = WatchedItem
::fromUserTitle( $this, $title );
2513 $this->invalidateCache();
2517 * Clear the user's notification timestamp for the given title.
2518 * If e-notif e-mails are on, they will receive notification mails on
2519 * the next change of the page if it's watched etc.
2520 * @param $title Title of the article to look at
2522 function clearNotification( &$title ) {
2523 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2525 # Do nothing if the database is locked to writes
2526 if( wfReadOnly() ) {
2530 if( $title->getNamespace() == NS_USER_TALK
&&
2531 $title->getText() == $this->getName() ) {
2532 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2534 $this->setNewtalk( false );
2537 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2541 if( $this->isAnon() ) {
2542 // Nothing else to do...
2546 // Only update the timestamp if the page is being watched.
2547 // The query to find out if it is watched is cached both in memcached and per-invocation,
2548 // and when it does have to be executed, it can be on a slave
2549 // If this is the user's newtalk page, we always update the timestamp
2550 if( $title->getNamespace() == NS_USER_TALK
&&
2551 $title->getText() == $wgUser->getName() )
2554 } elseif ( $this->getId() == $wgUser->getId() ) {
2555 $watched = $title->userIsWatching();
2560 // If the page is watched by the user (or may be watched), update the timestamp on any
2561 // any matching rows
2563 $dbw = wfGetDB( DB_MASTER
);
2564 $dbw->update( 'watchlist',
2566 'wl_notificationtimestamp' => null
2567 ), array( /* WHERE */
2568 'wl_title' => $title->getDBkey(),
2569 'wl_namespace' => $title->getNamespace(),
2570 'wl_user' => $this->getID()
2577 * Resets all of the given user's page-change notification timestamps.
2578 * If e-notif e-mails are on, they will receive notification mails on
2579 * the next change of any watched page.
2581 * @param $currentUser Int User ID
2583 function clearAllNotifications( $currentUser ) {
2584 global $wgUseEnotif, $wgShowUpdatedMarker;
2585 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2586 $this->setNewtalk( false );
2589 if( $currentUser != 0 ) {
2590 $dbw = wfGetDB( DB_MASTER
);
2591 $dbw->update( 'watchlist',
2593 'wl_notificationtimestamp' => null
2594 ), array( /* WHERE */
2595 'wl_user' => $currentUser
2598 # We also need to clear here the "you have new message" notification for the own user_talk page
2599 # This is cleared one page view later in Article::viewUpdates();
2604 * Set this user's options from an encoded string
2605 * @param $str String Encoded options to import
2608 function decodeOptions( $str ) {
2612 $this->mOptionsLoaded
= true;
2613 $this->mOptionOverrides
= array();
2615 // If an option is not set in $str, use the default value
2616 $this->mOptions
= self
::getDefaultOptions();
2618 $a = explode( "\n", $str );
2619 foreach ( $a as $s ) {
2621 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2622 $this->mOptions
[$m[1]] = $m[2];
2623 $this->mOptionOverrides
[$m[1]] = $m[2];
2629 * Set a cookie on the user's client. Wrapper for
2630 * WebResponse::setCookie
2631 * @param $name String Name of the cookie to set
2632 * @param $value String Value to set
2633 * @param $exp Int Expiration time, as a UNIX time value;
2634 * if 0 or not specified, use the default $wgCookieExpiration
2636 protected function setCookie( $name, $value, $exp = 0 ) {
2638 $wgRequest->response()->setcookie( $name, $value, $exp );
2642 * Clear a cookie on the user's client
2643 * @param $name String Name of the cookie to clear
2645 protected function clearCookie( $name ) {
2646 $this->setCookie( $name, '', time() - 86400 );
2650 * Set the default cookies for this session on the user's client.
2652 * @param $request WebRequest object to use; $wgRequest will be used if null
2655 function setCookies( $request = null ) {
2656 if ( $request === null ) {
2658 $request = $wgRequest;
2662 if ( 0 == $this->mId
) return;
2664 'wsUserID' => $this->mId
,
2665 'wsToken' => $this->mToken
,
2666 'wsUserName' => $this->getName()
2669 'UserID' => $this->mId
,
2670 'UserName' => $this->getName(),
2672 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2673 $cookies['Token'] = $this->mToken
;
2675 $cookies['Token'] = false;
2678 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2680 foreach ( $session as $name => $value ) {
2681 $request->setSessionData( $name, $value );
2683 foreach ( $cookies as $name => $value ) {
2684 if ( $value === false ) {
2685 $this->clearCookie( $name );
2687 $this->setCookie( $name, $value );
2693 * Log this user out.
2696 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
2702 * Clear the user's cookies and session, and reset the instance cache.
2706 function doLogout() {
2709 $this->clearInstanceCache( 'defaults' );
2711 $wgRequest->setSessionData( 'wsUserID', 0 );
2713 $this->clearCookie( 'UserID' );
2714 $this->clearCookie( 'Token' );
2716 # Remember when user logged out, to prevent seeing cached pages
2717 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2721 * Save this user's settings into the database.
2722 * @todo Only rarely do all these fields need to be set!
2724 function saveSettings() {
2726 if ( wfReadOnly() ) { return; }
2727 if ( 0 == $this->mId
) { return; }
2729 $this->mTouched
= self
::newTouchedTimestamp();
2731 $dbw = wfGetDB( DB_MASTER
);
2732 $dbw->update( 'user',
2734 'user_name' => $this->mName
,
2735 'user_password' => $this->mPassword
,
2736 'user_newpassword' => $this->mNewpassword
,
2737 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2738 'user_real_name' => $this->mRealName
,
2739 'user_email' => $this->mEmail
,
2740 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2741 'user_options' => '',
2742 'user_touched' => $dbw->timestamp( $this->mTouched
),
2743 'user_token' => $this->mToken
,
2744 'user_email_token' => $this->mEmailToken
,
2745 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2746 ), array( /* WHERE */
2747 'user_id' => $this->mId
2751 $this->saveOptions();
2753 wfRunHooks( 'UserSaveSettings', array( $this ) );
2754 $this->clearSharedCache();
2755 $this->getUserPage()->invalidateCache();
2759 * If only this user's username is known, and it exists, return the user ID.
2762 function idForName() {
2763 $s = trim( $this->getName() );
2764 if ( $s === '' ) return 0;
2766 $dbr = wfGetDB( DB_SLAVE
);
2767 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2768 if ( $id === false ) {
2775 * Add a user to the database, return the user object
2777 * @param $name String Username to add
2778 * @param $params Array of Strings Non-default parameters to save to the database as user_* fields:
2779 * - password The user's password hash. Password logins will be disabled if this is omitted.
2780 * - newpassword Hash for a temporary password that has been mailed to the user
2781 * - email The user's email address
2782 * - email_authenticated The email authentication timestamp
2783 * - real_name The user's real name
2784 * - options An associative array of non-default options
2785 * - token Random authentication token. Do not set.
2786 * - registration Registration timestamp. Do not set.
2788 * @return User object, or null if the username already exists
2790 static function createNew( $name, $params = array() ) {
2793 if ( isset( $params['options'] ) ) {
2794 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
2795 unset( $params['options'] );
2797 $dbw = wfGetDB( DB_MASTER
);
2798 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2801 'user_id' => $seqVal,
2802 'user_name' => $name,
2803 'user_password' => $user->mPassword
,
2804 'user_newpassword' => $user->mNewpassword
,
2805 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
2806 'user_email' => $user->mEmail
,
2807 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2808 'user_real_name' => $user->mRealName
,
2809 'user_options' => '',
2810 'user_token' => $user->mToken
,
2811 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2812 'user_editcount' => 0,
2814 foreach ( $params as $name => $value ) {
2815 $fields["user_$name"] = $value;
2817 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2818 if ( $dbw->affectedRows() ) {
2819 $newUser = User
::newFromId( $dbw->insertId() );
2827 * Add this existing user object to the database
2829 function addToDatabase() {
2831 $dbw = wfGetDB( DB_MASTER
);
2832 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2833 $dbw->insert( 'user',
2835 'user_id' => $seqVal,
2836 'user_name' => $this->mName
,
2837 'user_password' => $this->mPassword
,
2838 'user_newpassword' => $this->mNewpassword
,
2839 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2840 'user_email' => $this->mEmail
,
2841 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2842 'user_real_name' => $this->mRealName
,
2843 'user_options' => '',
2844 'user_token' => $this->mToken
,
2845 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2846 'user_editcount' => 0,
2849 $this->mId
= $dbw->insertId();
2851 // Clear instance cache other than user table data, which is already accurate
2852 $this->clearInstanceCache();
2854 $this->saveOptions();
2858 * If this (non-anonymous) user is blocked, block any IP address
2859 * they've successfully logged in from.
2861 function spreadBlock() {
2862 wfDebug( __METHOD__
. "()\n" );
2864 if ( $this->mId
== 0 ) {
2868 $userblock = Block
::newFromTarget( $this->getName() );
2869 if ( !$userblock ) {
2873 $userblock->doAutoblock( wfGetIP() );
2877 * Generate a string which will be different for any combination of
2878 * user options which would produce different parser output.
2879 * This will be used as part of the hash key for the parser cache,
2880 * so users with the same options can share the same cached data
2883 * Extensions which require it should install 'PageRenderingHash' hook,
2884 * which will give them a chance to modify this key based on their own
2887 * @deprecated since 1.17 use the ParserOptions object to get the relevant options
2888 * @return String Page rendering hash
2890 function getPageRenderingHash() {
2891 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2893 return $this->mHash
;
2895 wfDeprecated( __METHOD__
);
2897 // stubthreshold is only included below for completeness,
2898 // since it disables the parser cache, its value will always
2899 // be 0 when this function is called by parsercache.
2901 $confstr = $this->getOption( 'math' );
2902 $confstr .= '!' . $this->getStubThreshold();
2903 if ( $wgUseDynamicDates ) { # This is wrong (bug 24714)
2904 $confstr .= '!' . $this->getDatePreference();
2906 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ?
'1' : '' );
2907 $confstr .= '!' . $wgLang->getCode();
2908 $confstr .= '!' . $this->getOption( 'thumbsize' );
2909 // add in language specific options, if any
2910 $extra = $wgContLang->getExtraHashOptions();
2913 // Since the skin could be overloading link(), it should be
2914 // included here but in practice, none of our skins do that.
2916 $confstr .= $wgRenderHashAppend;
2918 // Give a chance for extensions to modify the hash, if they have
2919 // extra options or other effects on the parser cache.
2920 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2922 // Make it a valid memcached key fragment
2923 $confstr = str_replace( ' ', '_', $confstr );
2924 $this->mHash
= $confstr;
2929 * Get whether the user is explicitly blocked from account creation.
2930 * @return Bool|Block
2932 function isBlockedFromCreateAccount() {
2933 $this->getBlockedStatus();
2934 if( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ){
2935 return $this->mBlock
;
2938 # bug 13611: if the IP address the user is trying to create an account from is
2939 # blocked with createaccount disabled, prevent new account creation there even
2940 # when the user is logged in
2941 if( $this->mBlockedFromCreateAccount
=== false ){
2942 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, wfGetIP() );
2944 return $this->mBlockedFromCreateAccount
instanceof Block
&& $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
2945 ?
$this->mBlockedFromCreateAccount
2950 * Get whether the user is blocked from using Special:Emailuser.
2953 function isBlockedFromEmailuser() {
2954 $this->getBlockedStatus();
2955 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
2959 * Get whether the user is allowed to create an account.
2962 function isAllowedToCreateAccount() {
2963 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2967 * Get this user's personal page title.
2969 * @return Title: User's personal page title
2971 function getUserPage() {
2972 return Title
::makeTitle( NS_USER
, $this->getName() );
2976 * Get this user's talk page title.
2978 * @return Title: User's talk page title
2980 function getTalkPage() {
2981 $title = $this->getUserPage();
2982 return $title->getTalkPage();
2986 * Determine whether the user is a newbie. Newbies are either
2987 * anonymous IPs, or the most recently created accounts.
2990 function isNewbie() {
2991 return !$this->isAllowed( 'autoconfirmed' );
2995 * Check to see if the given clear-text password is one of the accepted passwords
2996 * @param $password String: user password.
2997 * @return Boolean: True if the given password is correct, otherwise False.
2999 function checkPassword( $password ) {
3000 global $wgAuth, $wgLegacyEncoding;
3003 // Even though we stop people from creating passwords that
3004 // are shorter than this, doesn't mean people wont be able
3005 // to. Certain authentication plugins do NOT want to save
3006 // domain passwords in a mysql database, so we should
3007 // check this (in case $wgAuth->strict() is false).
3008 if( !$this->isValidPassword( $password ) ) {
3012 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
3014 } elseif( $wgAuth->strict() ) {
3015 /* Auth plugin doesn't allow local authentication */
3017 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
3018 /* Auth plugin doesn't allow local authentication for this user name */
3021 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
3023 } elseif ( $wgLegacyEncoding ) {
3024 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3025 # Check for this with iconv
3026 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3027 if ( $cp1252Password != $password &&
3028 self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) )
3037 * Check if the given clear-text password matches the temporary password
3038 * sent by e-mail for password reset operations.
3039 * @return Boolean: True if matches, false otherwise
3041 function checkTemporaryPassword( $plaintext ) {
3042 global $wgNewPasswordExpiry;
3045 if( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
3046 if ( is_null( $this->mNewpassTime
) ) {
3049 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3050 return ( time() < $expiry );
3057 * Initialize (if necessary) and return a session token value
3058 * which can be used in edit forms to show that the user's
3059 * login credentials aren't being hijacked with a foreign form
3062 * @param $salt String|Array of Strings Optional function-specific data for hashing
3063 * @param $request WebRequest object to use or null to use $wgRequest
3064 * @return String The new edit token
3066 function editToken( $salt = '', $request = null ) {
3067 if ( $request == null ) {
3069 $request = $wgRequest;
3072 if ( $this->isAnon() ) {
3073 return EDIT_TOKEN_SUFFIX
;
3075 $token = $request->getSessionData( 'wsEditToken' );
3076 if ( $token === null ) {
3077 $token = self
::generateToken();
3078 $request->setSessionData( 'wsEditToken', $token );
3080 if( is_array( $salt ) ) {
3081 $salt = implode( '|', $salt );
3083 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
3088 * Generate a looking random token for various uses.
3090 * @param $salt String Optional salt value
3091 * @return String The new random token
3093 public static function generateToken( $salt = '' ) {
3094 $token = dechex( mt_rand() ) . dechex( mt_rand() );
3095 return md5( $token . $salt );
3099 * Check given value against the token value stored in the session.
3100 * A match should confirm that the form was submitted from the
3101 * user's own login session, not a form submission from a third-party
3104 * @param $val String Input value to compare
3105 * @param $salt String Optional function-specific data for hashing
3106 * @param $request WebRequest object to use or null to use $wgRequest
3107 * @return Boolean: Whether the token matches
3109 function matchEditToken( $val, $salt = '', $request = null ) {
3110 $sessionToken = $this->editToken( $salt, $request );
3111 if ( $val != $sessionToken ) {
3112 wfDebug( "User::matchEditToken: broken session data\n" );
3114 return $val == $sessionToken;
3118 * Check given value against the token value stored in the session,
3119 * ignoring the suffix.
3121 * @param $val String Input value to compare
3122 * @param $salt String Optional function-specific data for hashing
3123 * @param $request WebRequest object to use or null to use $wgRequest
3124 * @return Boolean: Whether the token matches
3126 function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3127 $sessionToken = $this->editToken( $salt, $request );
3128 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3132 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3133 * mail to the user's given address.
3135 * @param $type String: message to send, either "created", "changed" or "set"
3136 * @return Status object
3138 function sendConfirmationMail( $type = 'created' ) {
3140 $expiration = null; // gets passed-by-ref and defined in next line.
3141 $token = $this->confirmationToken( $expiration );
3142 $url = $this->confirmationTokenUrl( $token );
3143 $invalidateURL = $this->invalidationTokenUrl( $token );
3144 $this->saveSettings();
3146 if ( $type == 'created' ||
$type === false ) {
3147 $message = 'confirmemail_body';
3148 } elseif ( $type === true ) {
3149 $message = 'confirmemail_body_changed';
3151 $message = 'confirmemail_body_' . $type;
3154 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
3159 $wgLang->timeanddate( $expiration, false ),
3161 $wgLang->date( $expiration, false ),
3162 $wgLang->time( $expiration, false ) ) );
3166 * Send an e-mail to this user's account. Does not check for
3167 * confirmed status or validity.
3169 * @param $subject String Message subject
3170 * @param $body String Message body
3171 * @param $from String Optional From address; if unspecified, default $wgPasswordSender will be used
3172 * @param $replyto String Reply-To address
3175 function sendMail( $subject, $body, $from = null, $replyto = null ) {
3176 if( is_null( $from ) ) {
3177 global $wgPasswordSender, $wgPasswordSenderName;
3178 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
3180 $sender = new MailAddress( $from );
3183 $to = new MailAddress( $this );
3184 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
3188 * Generate, store, and return a new e-mail confirmation code.
3189 * A hash (unsalted, since it's used as a key) is stored.
3191 * @note Call saveSettings() after calling this function to commit
3192 * this change to the database.
3194 * @param[out] &$expiration \mixed Accepts the expiration time
3195 * @return String New token
3198 function confirmationToken( &$expiration ) {
3199 global $wgUserEmailConfirmationTokenExpiry;
3201 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
3202 $expiration = wfTimestamp( TS_MW
, $expires );
3203 $token = self
::generateToken( $this->mId
. $this->mEmail
. $expires );
3204 $hash = md5( $token );
3206 $this->mEmailToken
= $hash;
3207 $this->mEmailTokenExpires
= $expiration;
3212 * Return a URL the user can use to confirm their email address.
3213 * @param $token String Accepts the email confirmation token
3214 * @return String New token URL
3217 function confirmationTokenUrl( $token ) {
3218 return $this->getTokenUrl( 'ConfirmEmail', $token );
3222 * Return a URL the user can use to invalidate their email address.
3223 * @param $token String Accepts the email confirmation token
3224 * @return String New token URL
3227 function invalidationTokenUrl( $token ) {
3228 return $this->getTokenUrl( 'Invalidateemail', $token );
3232 * Internal function to format the e-mail validation/invalidation URLs.
3233 * This uses $wgArticlePath directly as a quickie hack to use the
3234 * hardcoded English names of the Special: pages, for ASCII safety.
3236 * @note Since these URLs get dropped directly into emails, using the
3237 * short English names avoids insanely long URL-encoded links, which
3238 * also sometimes can get corrupted in some browsers/mailers
3239 * (bug 6957 with Gmail and Internet Explorer).
3241 * @param $page String Special page
3242 * @param $token String Token
3243 * @return String Formatted URL
3245 protected function getTokenUrl( $page, $token ) {
3246 global $wgArticlePath;
3250 "Special:$page/$token",
3255 * Mark the e-mail address confirmed.
3257 * @note Call saveSettings() after calling this function to commit the change.
3259 function confirmEmail() {
3260 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3261 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3266 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3267 * address if it was already confirmed.
3269 * @note Call saveSettings() after calling this function to commit the change.
3271 function invalidateEmail() {
3273 $this->mEmailToken
= null;
3274 $this->mEmailTokenExpires
= null;
3275 $this->setEmailAuthenticationTimestamp( null );
3276 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3281 * Set the e-mail authentication timestamp.
3282 * @param $timestamp String TS_MW timestamp
3284 function setEmailAuthenticationTimestamp( $timestamp ) {
3286 $this->mEmailAuthenticated
= $timestamp;
3287 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
3291 * Is this user allowed to send e-mails within limits of current
3292 * site configuration?
3295 function canSendEmail() {
3296 global $wgEnableEmail, $wgEnableUserEmail;
3297 if( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
3300 $canSend = $this->isEmailConfirmed();
3301 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3306 * Is this user allowed to receive e-mails within limits of current
3307 * site configuration?
3310 function canReceiveEmail() {
3311 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3315 * Is this user's e-mail address valid-looking and confirmed within
3316 * limits of the current site configuration?
3318 * @note If $wgEmailAuthentication is on, this may require the user to have
3319 * confirmed their address by returning a code or using a password
3320 * sent to the address from the wiki.
3324 function isEmailConfirmed() {
3325 global $wgEmailAuthentication;
3328 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3329 if( $this->isAnon() ) {
3332 if( !Sanitizer
::validateEmail( $this->mEmail
) ) {
3335 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
3345 * Check whether there is an outstanding request for e-mail confirmation.
3348 function isEmailConfirmationPending() {
3349 global $wgEmailAuthentication;
3350 return $wgEmailAuthentication &&
3351 !$this->isEmailConfirmed() &&
3352 $this->mEmailToken
&&
3353 $this->mEmailTokenExpires
> wfTimestamp();
3357 * Get the timestamp of account creation.
3359 * @return String|Bool Timestamp of account creation, or false for
3360 * non-existent/anonymous user accounts.
3362 public function getRegistration() {
3363 if ( $this->isAnon() ) {
3367 return $this->mRegistration
;
3371 * Get the timestamp of the first edit
3373 * @return String|Bool Timestamp of first edit, or false for
3374 * non-existent/anonymous user accounts.
3376 public function getFirstEditTimestamp() {
3377 if( $this->getId() == 0 ) {
3378 return false; // anons
3380 $dbr = wfGetDB( DB_SLAVE
);
3381 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3382 array( 'rev_user' => $this->getId() ),
3384 array( 'ORDER BY' => 'rev_timestamp ASC' )
3387 return false; // no edits
3389 return wfTimestamp( TS_MW
, $time );
3393 * Get the permissions associated with a given list of groups
3395 * @param $groups Array of Strings List of internal group names
3396 * @return Array of Strings List of permission key names for given groups combined
3398 static function getGroupPermissions( $groups ) {
3399 global $wgGroupPermissions, $wgRevokePermissions;
3401 // grant every granted permission first
3402 foreach( $groups as $group ) {
3403 if( isset( $wgGroupPermissions[$group] ) ) {
3404 $rights = array_merge( $rights,
3405 // array_filter removes empty items
3406 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3409 // now revoke the revoked permissions
3410 foreach( $groups as $group ) {
3411 if( isset( $wgRevokePermissions[$group] ) ) {
3412 $rights = array_diff( $rights,
3413 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3416 return array_unique( $rights );
3420 * Get all the groups who have a given permission
3422 * @param $role String Role to check
3423 * @return Array of Strings List of internal group names with the given permission
3425 static function getGroupsWithPermission( $role ) {
3426 global $wgGroupPermissions;
3427 $allowedGroups = array();
3428 foreach ( $wgGroupPermissions as $group => $rights ) {
3429 if ( isset( $rights[$role] ) && $rights[$role] ) {
3430 $allowedGroups[] = $group;
3433 return $allowedGroups;
3437 * Get the localized descriptive name for a group, if it exists
3439 * @param $group String Internal group name
3440 * @return String Localized descriptive group name
3442 static function getGroupName( $group ) {
3443 $msg = wfMessage( "group-$group" );
3444 return $msg->isBlank() ?
$group : $msg->text();
3448 * Get the localized descriptive name for a member of a group, if it exists
3450 * @param $group String Internal group name
3451 * @return String Localized name for group member
3453 static function getGroupMember( $group ) {
3454 $msg = wfMessage( "group-$group-member" );
3455 return $msg->isBlank() ?
$group : $msg->text();
3459 * Return the set of defined explicit groups.
3460 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3461 * are not included, as they are defined automatically, not in the database.
3462 * @return Array of internal group names
3464 static function getAllGroups() {
3465 global $wgGroupPermissions, $wgRevokePermissions;
3467 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3468 self
::getImplicitGroups()
3473 * Get a list of all available permissions.
3474 * @return Array of permission names
3476 static function getAllRights() {
3477 if ( self
::$mAllRights === false ) {
3478 global $wgAvailableRights;
3479 if ( count( $wgAvailableRights ) ) {
3480 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3482 self
::$mAllRights = self
::$mCoreRights;
3484 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3486 return self
::$mAllRights;
3490 * Get a list of implicit groups
3491 * @return Array of Strings Array of internal group names
3493 public static function getImplicitGroups() {
3494 global $wgImplicitGroups;
3495 $groups = $wgImplicitGroups;
3496 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3501 * Get the title of a page describing a particular group
3503 * @param $group String Internal group name
3504 * @return Title|Bool Title of the page if it exists, false otherwise
3506 static function getGroupPage( $group ) {
3507 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
3508 if( $msg->exists() ) {
3509 $title = Title
::newFromText( $msg->text() );
3510 if( is_object( $title ) )
3517 * Create a link to the group in HTML, if available;
3518 * else return the group name.
3520 * @param $group String Internal name of the group
3521 * @param $text String The text of the link
3522 * @return String HTML link to the group
3524 static function makeGroupLinkHTML( $group, $text = '' ) {
3526 $text = self
::getGroupName( $group );
3528 $title = self
::getGroupPage( $group );
3531 $sk = $wgUser->getSkin();
3532 return $sk->link( $title, htmlspecialchars( $text ) );
3539 * Create a link to the group in Wikitext, if available;
3540 * else return the group name.
3542 * @param $group String Internal name of the group
3543 * @param $text String The text of the link
3544 * @return String Wikilink to the group
3546 static function makeGroupLinkWiki( $group, $text = '' ) {
3548 $text = self
::getGroupName( $group );
3550 $title = self
::getGroupPage( $group );
3552 $page = $title->getPrefixedText();
3553 return "[[$page|$text]]";
3560 * Returns an array of the groups that a particular group can add/remove.
3562 * @param $group String: the group to check for whether it can add/remove
3563 * @return Array array( 'add' => array( addablegroups ),
3564 * 'remove' => array( removablegroups ),
3565 * 'add-self' => array( addablegroups to self),
3566 * 'remove-self' => array( removable groups from self) )
3568 static function changeableByGroup( $group ) {
3569 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
3571 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
3572 if( empty( $wgAddGroups[$group] ) ) {
3573 // Don't add anything to $groups
3574 } elseif( $wgAddGroups[$group] === true ) {
3575 // You get everything
3576 $groups['add'] = self
::getAllGroups();
3577 } elseif( is_array( $wgAddGroups[$group] ) ) {
3578 $groups['add'] = $wgAddGroups[$group];
3581 // Same thing for remove
3582 if( empty( $wgRemoveGroups[$group] ) ) {
3583 } elseif( $wgRemoveGroups[$group] === true ) {
3584 $groups['remove'] = self
::getAllGroups();
3585 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
3586 $groups['remove'] = $wgRemoveGroups[$group];
3589 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
3590 if( empty( $wgGroupsAddToSelf['user']) ||
$wgGroupsAddToSelf['user'] !== true ) {
3591 foreach( $wgGroupsAddToSelf as $key => $value ) {
3592 if( is_int( $key ) ) {
3593 $wgGroupsAddToSelf['user'][] = $value;
3598 if( empty( $wgGroupsRemoveFromSelf['user']) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
3599 foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
3600 if( is_int( $key ) ) {
3601 $wgGroupsRemoveFromSelf['user'][] = $value;
3606 // Now figure out what groups the user can add to him/herself
3607 if( empty( $wgGroupsAddToSelf[$group] ) ) {
3608 } elseif( $wgGroupsAddToSelf[$group] === true ) {
3609 // No idea WHY this would be used, but it's there
3610 $groups['add-self'] = User
::getAllGroups();
3611 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
3612 $groups['add-self'] = $wgGroupsAddToSelf[$group];
3615 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
3616 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
3617 $groups['remove-self'] = User
::getAllGroups();
3618 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
3619 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
3626 * Returns an array of groups that this user can add and remove
3627 * @return Array array( 'add' => array( addablegroups ),
3628 * 'remove' => array( removablegroups ),
3629 * 'add-self' => array( addablegroups to self),
3630 * 'remove-self' => array( removable groups from self) )
3632 function changeableGroups() {
3633 if( $this->isAllowed( 'userrights' ) ) {
3634 // This group gives the right to modify everything (reverse-
3635 // compatibility with old "userrights lets you change
3637 // Using array_merge to make the groups reindexed
3638 $all = array_merge( User
::getAllGroups() );
3642 'add-self' => array(),
3643 'remove-self' => array()
3647 // Okay, it's not so simple, we will have to go through the arrays
3650 'remove' => array(),
3651 'add-self' => array(),
3652 'remove-self' => array()
3654 $addergroups = $this->getEffectiveGroups();
3656 foreach( $addergroups as $addergroup ) {
3657 $groups = array_merge_recursive(
3658 $groups, $this->changeableByGroup( $addergroup )
3660 $groups['add'] = array_unique( $groups['add'] );
3661 $groups['remove'] = array_unique( $groups['remove'] );
3662 $groups['add-self'] = array_unique( $groups['add-self'] );
3663 $groups['remove-self'] = array_unique( $groups['remove-self'] );
3669 * Increment the user's edit-count field.
3670 * Will have no effect for anonymous users.
3672 function incEditCount() {
3673 if( !$this->isAnon() ) {
3674 $dbw = wfGetDB( DB_MASTER
);
3675 $dbw->update( 'user',
3676 array( 'user_editcount=user_editcount+1' ),
3677 array( 'user_id' => $this->getId() ),
3680 // Lazy initialization check...
3681 if( $dbw->affectedRows() == 0 ) {
3682 // Pull from a slave to be less cruel to servers
3683 // Accuracy isn't the point anyway here
3684 $dbr = wfGetDB( DB_SLAVE
);
3685 $count = $dbr->selectField( 'revision',
3687 array( 'rev_user' => $this->getId() ),
3690 // Now here's a goddamn hack...
3691 if( $dbr !== $dbw ) {
3692 // If we actually have a slave server, the count is
3693 // at least one behind because the current transaction
3694 // has not been committed and replicated.
3697 // But if DB_SLAVE is selecting the master, then the
3698 // count we just read includes the revision that was
3699 // just added in the working transaction.
3702 $dbw->update( 'user',
3703 array( 'user_editcount' => $count ),
3704 array( 'user_id' => $this->getId() ),
3708 // edit count in user cache too
3709 $this->invalidateCache();
3713 * Get the description of a given right
3715 * @param $right String Right to query
3716 * @return String Localized description of the right
3718 static function getRightDescription( $right ) {
3719 $key = "right-$right";
3720 $msg = wfMessage( $key );
3721 return $msg->isBlank() ?
$right : $msg->text();
3725 * Make an old-style password hash
3727 * @param $password String Plain-text password
3728 * @param $userId String User ID
3729 * @return String Password hash
3731 static function oldCrypt( $password, $userId ) {
3732 global $wgPasswordSalt;
3733 if ( $wgPasswordSalt ) {
3734 return md5( $userId . '-' . md5( $password ) );
3736 return md5( $password );
3741 * Make a new-style password hash
3743 * @param $password String Plain-text password
3744 * @param $salt String Optional salt, may be random or the user ID.
3745 * If unspecified or false, will generate one automatically
3746 * @return String Password hash
3748 static function crypt( $password, $salt = false ) {
3749 global $wgPasswordSalt;
3752 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3756 if( $wgPasswordSalt ) {
3757 if ( $salt === false ) {
3758 $salt = substr( wfGenerateToken(), 0, 8 );
3760 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3762 return ':A:' . md5( $password );
3767 * Compare a password hash with a plain-text password. Requires the user
3768 * ID if there's a chance that the hash is an old-style hash.
3770 * @param $hash String Password hash
3771 * @param $password String Plain-text password to compare
3772 * @param $userId String User ID for old-style password salt
3775 static function comparePasswords( $hash, $password, $userId = false ) {
3776 $type = substr( $hash, 0, 3 );
3779 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3783 if ( $type == ':A:' ) {
3785 return md5( $password ) === substr( $hash, 3 );
3786 } elseif ( $type == ':B:' ) {
3788 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3789 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3792 return self
::oldCrypt( $password, $userId ) === $hash;
3797 * Add a newuser log entry for this user
3799 * @param $byEmail Boolean: account made by email?
3800 * @param $reason String: user supplied reason
3804 public function addNewUserLogEntry( $byEmail = false, $reason = '' ) {
3805 global $wgUser, $wgContLang, $wgNewUserLog;
3806 if( empty( $wgNewUserLog ) ) {
3807 return true; // disabled
3810 if( $this->getName() == $wgUser->getName() ) {
3813 $action = 'create2';
3815 if ( $reason === '' ) {
3816 $reason = wfMsgForContent( 'newuserlog-byemail' );
3818 $reason = $wgContLang->commaList( array(
3819 $reason, wfMsgForContent( 'newuserlog-byemail' ) ) );
3823 $log = new LogPage( 'newusers' );
3826 $this->getUserPage(),
3828 array( $this->getId() )
3834 * Add an autocreate newuser log entry for this user
3835 * Used by things like CentralAuth and perhaps other authplugins.
3839 public function addNewUserLogEntryAutoCreate() {
3840 global $wgNewUserLog;
3841 if( !$wgNewUserLog ) {
3842 return true; // disabled
3844 $log = new LogPage( 'newusers', false );
3845 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3849 protected function loadOptions() {
3851 if ( $this->mOptionsLoaded ||
!$this->getId() )
3854 $this->mOptions
= self
::getDefaultOptions();
3856 // Maybe load from the object
3857 if ( !is_null( $this->mOptionOverrides
) ) {
3858 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
3859 foreach( $this->mOptionOverrides
as $key => $value ) {
3860 $this->mOptions
[$key] = $value;
3863 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
3864 // Load from database
3865 $dbr = wfGetDB( DB_SLAVE
);
3867 $res = $dbr->select(
3870 array( 'up_user' => $this->getId() ),
3874 foreach ( $res as $row ) {
3875 $this->mOptionOverrides
[$row->up_property
] = $row->up_value
;
3876 $this->mOptions
[$row->up_property
] = $row->up_value
;
3880 $this->mOptionsLoaded
= true;
3882 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
3885 protected function saveOptions() {
3886 global $wgAllowPrefChange;
3888 $extuser = ExternalUser
::newFromUser( $this );
3890 $this->loadOptions();
3891 $dbw = wfGetDB( DB_MASTER
);
3893 $insert_rows = array();
3895 $saveOptions = $this->mOptions
;
3897 // Allow hooks to abort, for instance to save to a global profile.
3898 // Reset options to default state before saving.
3899 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) )
3902 foreach( $saveOptions as $key => $value ) {
3903 # Don't bother storing default values
3904 if ( ( is_null( self
::getDefaultOption( $key ) ) &&
3905 !( $value === false ||
is_null($value) ) ) ||
3906 $value != self
::getDefaultOption( $key ) ) {
3907 $insert_rows[] = array(
3908 'up_user' => $this->getId(),
3909 'up_property' => $key,
3910 'up_value' => $value,
3913 if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
3914 switch ( $wgAllowPrefChange[$key] ) {
3920 $extuser->setPref( $key, $value );
3926 $dbw->delete( 'user_properties', array( 'up_user' => $this->getId() ), __METHOD__
);
3927 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
);
3932 * Provide an array of HTML5 attributes to put on an input element
3933 * intended for the user to enter a new password. This may include
3934 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
3936 * Do *not* use this when asking the user to enter his current password!
3937 * Regardless of configuration, users may have invalid passwords for whatever
3938 * reason (e.g., they were set before requirements were tightened up).
3939 * Only use it when asking for a new password, like on account creation or
3942 * Obviously, you still need to do server-side checking.
3944 * NOTE: A combination of bugs in various browsers means that this function
3945 * actually just returns array() unconditionally at the moment. May as
3946 * well keep it around for when the browser bugs get fixed, though.
3948 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
3950 * @return array Array of HTML attributes suitable for feeding to
3951 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
3952 * That will potentially output invalid XHTML 1.0 Transitional, and will
3953 * get confused by the boolean attribute syntax used.)
3955 public static function passwordChangeInputAttribs() {
3956 global $wgMinimalPasswordLength;
3958 if ( $wgMinimalPasswordLength == 0 ) {
3962 # Note that the pattern requirement will always be satisfied if the
3963 # input is empty, so we need required in all cases.
3965 # @todo FIXME: Bug 23769: This needs to not claim the password is required
3966 # if e-mail confirmation is being used. Since HTML5 input validation
3967 # is b0rked anyway in some browsers, just return nothing. When it's
3968 # re-enabled, fix this code to not output required for e-mail
3970 #$ret = array( 'required' );
3973 # We can't actually do this right now, because Opera 9.6 will print out
3974 # the entered password visibly in its error message! When other
3975 # browsers add support for this attribute, or Opera fixes its support,
3976 # we can add support with a version check to avoid doing this on Opera
3977 # versions where it will be a problem. Reported to Opera as
3978 # DSK-262266, but they don't have a public bug tracker for us to follow.
3980 if ( $wgMinimalPasswordLength > 1 ) {
3981 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
3982 $ret['title'] = wfMsgExt( 'passwordtooshort', 'parsemag',
3983 $wgMinimalPasswordLength );