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.
410 * @param $request WebRequest object to use; $wgRequest will be used if
414 static function newFromSession( WebRequest
$request = null ) {
416 $user->mFrom
= 'session';
417 $user->mRequest
= $request;
422 * Create a new user object from a user row.
423 * The row should have the following fields from the user table in it:
424 * - either user_name or user_id to load further data if needed (or both)
426 * - all other fields (email, password, etc.)
427 * It is useless to provide the remaining fields if either user_id,
428 * user_name and user_real_name are not provided because the whole row
429 * will be loaded once more from the database when accessing them.
431 * @param $row Array A row from the user table
434 static function newFromRow( $row ) {
436 $user->loadFromRow( $row );
444 * Get the username corresponding to a given user ID
445 * @param $id Int User ID
446 * @return String The corresponding username
448 static function whoIs( $id ) {
449 $dbr = wfGetDB( DB_SLAVE
);
450 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), __METHOD__
);
454 * Get the real name of a user given their user ID
456 * @param $id Int User ID
457 * @return String The corresponding user's real name
459 static function whoIsReal( $id ) {
460 $dbr = wfGetDB( DB_SLAVE
);
461 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
465 * Get database id given a user name
466 * @param $name String Username
467 * @return Int|Null The corresponding user's ID, or null if user is nonexistent
469 static function idFromName( $name ) {
470 $nt = Title
::makeTitleSafe( NS_USER
, $name );
471 if( is_null( $nt ) ) {
476 if ( isset( self
::$idCacheByName[$name] ) ) {
477 return self
::$idCacheByName[$name];
480 $dbr = wfGetDB( DB_SLAVE
);
481 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
483 if ( $s === false ) {
486 $result = $s->user_id
;
489 self
::$idCacheByName[$name] = $result;
491 if ( count( self
::$idCacheByName ) > 1000 ) {
492 self
::$idCacheByName = array();
499 * Reset the cache used in idFromName(). For use in tests.
501 public static function resetIdByNameCache() {
502 self
::$idCacheByName = array();
506 * Does the string match an anonymous IPv4 address?
508 * This function exists for username validation, in order to reject
509 * usernames which are similar in form to IP addresses. Strings such
510 * as 300.300.300.300 will return true because it looks like an IP
511 * address, despite not being strictly valid.
513 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
514 * address because the usemod software would "cloak" anonymous IP
515 * addresses like this, if we allowed accounts like this to be created
516 * new users could get the old edits of these anonymous users.
518 * @param $name String to match
521 static function isIP( $name ) {
522 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP
::isIPv6($name);
526 * Is the input a valid username?
528 * Checks if the input is a valid username, we don't want an empty string,
529 * an IP address, anything that containins slashes (would mess up subpages),
530 * is longer than the maximum allowed username size or doesn't begin with
533 * @param $name String to match
536 static function isValidUserName( $name ) {
537 global $wgContLang, $wgMaxNameChars;
540 || User
::isIP( $name )
541 ||
strpos( $name, '/' ) !== false
542 ||
strlen( $name ) > $wgMaxNameChars
543 ||
$name != $wgContLang->ucfirst( $name ) ) {
544 wfDebugLog( 'username', __METHOD__
.
545 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
549 // Ensure that the name can't be misresolved as a different title,
550 // such as with extra namespace keys at the start.
551 $parsed = Title
::newFromText( $name );
552 if( is_null( $parsed )
553 ||
$parsed->getNamespace()
554 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
555 wfDebugLog( 'username', __METHOD__
.
556 ": '$name' invalid due to ambiguous prefixes" );
560 // Check an additional blacklist of troublemaker characters.
561 // Should these be merged into the title char list?
562 $unicodeBlacklist = '/[' .
563 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
564 '\x{00a0}' . # non-breaking space
565 '\x{2000}-\x{200f}' . # various whitespace
566 '\x{2028}-\x{202f}' . # breaks and control chars
567 '\x{3000}' . # ideographic space
568 '\x{e000}-\x{f8ff}' . # private use
570 if( preg_match( $unicodeBlacklist, $name ) ) {
571 wfDebugLog( 'username', __METHOD__
.
572 ": '$name' invalid due to blacklisted characters" );
580 * Usernames which fail to pass this function will be blocked
581 * from user login and new account registrations, but may be used
582 * internally by batch processes.
584 * If an account already exists in this form, login will be blocked
585 * by a failure to pass this function.
587 * @param $name String to match
590 static function isUsableName( $name ) {
591 global $wgReservedUsernames;
592 // Must be a valid username, obviously ;)
593 if ( !self
::isValidUserName( $name ) ) {
597 static $reservedUsernames = false;
598 if ( !$reservedUsernames ) {
599 $reservedUsernames = $wgReservedUsernames;
600 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
603 // Certain names may be reserved for batch processes.
604 foreach ( $reservedUsernames as $reserved ) {
605 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
606 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
608 if ( $reserved == $name ) {
616 * Usernames which fail to pass this function will be blocked
617 * from new account registrations, but may be used internally
618 * either by batch processes or by user accounts which have
619 * already been created.
621 * Additional blacklisting may be added here rather than in
622 * isValidUserName() to avoid disrupting existing accounts.
624 * @param $name String to match
627 static function isCreatableName( $name ) {
628 global $wgInvalidUsernameCharacters;
630 // Ensure that the username isn't longer than 235 bytes, so that
631 // (at least for the builtin skins) user javascript and css files
632 // will work. (bug 23080)
633 if( strlen( $name ) > 235 ) {
634 wfDebugLog( 'username', __METHOD__
.
635 ": '$name' invalid due to length" );
639 // Preg yells if you try to give it an empty string
640 if( $wgInvalidUsernameCharacters !== '' ) {
641 if( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
642 wfDebugLog( 'username', __METHOD__
.
643 ": '$name' invalid due to wgInvalidUsernameCharacters" );
648 return self
::isUsableName( $name );
652 * Is the input a valid password for this user?
654 * @param $password String Desired password
657 function isValidPassword( $password ) {
658 //simple boolean wrapper for getPasswordValidity
659 return $this->getPasswordValidity( $password ) === true;
663 * Given unvalidated password input, return error message on failure.
665 * @param $password String Desired password
666 * @return mixed: true on success, string or array of error message on failure
668 function getPasswordValidity( $password ) {
669 global $wgMinimalPasswordLength, $wgContLang;
671 static $blockedLogins = array(
672 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
673 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
676 $result = false; //init $result to false for the internal checks
678 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
681 if ( $result === false ) {
682 if( strlen( $password ) < $wgMinimalPasswordLength ) {
683 return 'passwordtooshort';
684 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
685 return 'password-name-match';
686 } elseif ( isset( $blockedLogins[ $this->getName() ] ) && $password == $blockedLogins[ $this->getName() ] ) {
687 return 'password-login-forbidden';
689 //it seems weird returning true here, but this is because of the
690 //initialization of $result to false above. If the hook is never run or it
691 //doesn't modify $result, then we will likely get down into this if with
695 } elseif( $result === true ) {
698 return $result; //the isValidPassword hook set a string $result and returned true
703 * Does a string look like an e-mail address?
705 * This validates an email address using an HTML5 specification found at:
706 * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
707 * Which as of 2011-01-24 says:
709 * A valid e-mail address is a string that matches the ABNF production
710 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
711 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
714 * This function is an implementation of the specification as requested in
717 * Client-side forms will use the same standard validation rules via JS or
718 * HTML 5 validation; additional restrictions can be enforced server-side
719 * by extensions via the 'isValidEmailAddr' hook.
721 * Note that this validation doesn't 100% match RFC 2822, but is believed
722 * to be liberal enough for wide use. Some invalid addresses will still
723 * pass validation here.
725 * @param $addr String E-mail address
727 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
729 public static function isValidEmailAddr( $addr ) {
730 return Sanitizer
::validateEmail( $addr );
734 * Given unvalidated user input, return a canonical username, or false if
735 * the username is invalid.
736 * @param $name String User input
737 * @param $validate String|Bool type of validation to use:
738 * - false No validation
739 * - 'valid' Valid for batch processes
740 * - 'usable' Valid for batch processes and login
741 * - 'creatable' Valid for batch processes, login and account creation
743 static function getCanonicalName( $name, $validate = 'valid' ) {
744 # Force usernames to capital
746 $name = $wgContLang->ucfirst( $name );
748 # Reject names containing '#'; these will be cleaned up
749 # with title normalisation, but then it's too late to
751 if( strpos( $name, '#' ) !== false )
754 # Clean up name according to title rules
755 $t = ( $validate === 'valid' ) ?
756 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
757 # Check for invalid titles
758 if( is_null( $t ) ) {
762 # Reject various classes of invalid names
764 $name = $wgAuth->getCanonicalName( $t->getText() );
766 switch ( $validate ) {
770 if ( !User
::isValidUserName( $name ) ) {
775 if ( !User
::isUsableName( $name ) ) {
780 if ( !User
::isCreatableName( $name ) ) {
785 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
791 * Count the number of edits of a user
792 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
794 * @param $uid Int User ID to check
795 * @return Int the user's edit count
797 static function edits( $uid ) {
798 wfProfileIn( __METHOD__
);
799 $dbr = wfGetDB( DB_SLAVE
);
800 // check if the user_editcount field has been initialized
801 $field = $dbr->selectField(
802 'user', 'user_editcount',
803 array( 'user_id' => $uid ),
807 if( $field === null ) { // it has not been initialized. do so.
808 $dbw = wfGetDB( DB_MASTER
);
809 $count = $dbr->selectField(
810 'revision', 'count(*)',
811 array( 'rev_user' => $uid ),
816 array( 'user_editcount' => $count ),
817 array( 'user_id' => $uid ),
823 wfProfileOut( __METHOD__
);
828 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
829 * @todo hash random numbers to improve security, like generateToken()
831 * @return String new random password
833 static function randomPassword() {
834 global $wgMinimalPasswordLength;
835 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
836 $l = strlen( $pwchars ) - 1;
838 $pwlength = max( 7, $wgMinimalPasswordLength );
839 $digit = mt_rand( 0, $pwlength - 1 );
841 for ( $i = 0; $i < $pwlength; $i++
) {
842 $np .= $i == $digit ?
chr( mt_rand( 48, 57 ) ) : $pwchars[ mt_rand( 0, $l ) ];
848 * Set cached properties to default.
850 * @note This no longer clears uncached lazy-initialised properties;
851 * the constructor does that instead.
854 function loadDefaults( $name = false ) {
855 wfProfileIn( __METHOD__
);
858 $this->mName
= $name;
859 $this->mRealName
= '';
860 $this->mPassword
= $this->mNewpassword
= '';
861 $this->mNewpassTime
= null;
863 $this->mOptionOverrides
= null;
864 $this->mOptionsLoaded
= false;
866 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
867 if( $loggedOut !== null ) {
868 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
870 $this->mTouched
= '0'; # Allow any pages to be cached
873 $this->setToken(); # Random
874 $this->mEmailAuthenticated
= null;
875 $this->mEmailToken
= '';
876 $this->mEmailTokenExpires
= null;
877 $this->mRegistration
= wfTimestamp( TS_MW
);
878 $this->mGroups
= array();
880 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
882 wfProfileOut( __METHOD__
);
886 * Return whether an item has been loaded.
888 * @param $item String: item to check. Current possibilities:
892 * @param $all String: 'all' to check if the whole object has been loaded
893 * or any other string to check if only the item is available (e.g.
897 public function isItemLoaded( $item, $all = 'all' ) {
898 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
899 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
903 * Set that an item has been loaded
905 * @param $item String
907 private function setItemLoaded( $item ) {
908 if ( is_array( $this->mLoadedItems
) ) {
909 $this->mLoadedItems
[$item] = true;
914 * Load user data from the session or login cookie. If there are no valid
915 * credentials, initialises the user as an anonymous user.
916 * @return Bool True if the user is logged in, false otherwise.
918 private function loadFromSession() {
919 global $wgExternalAuthType, $wgAutocreatePolicy;
922 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
923 if ( $result !== null ) {
927 if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
928 $extUser = ExternalUser
::newFromCookie();
930 # TODO: Automatically create the user here (or probably a bit
931 # lower down, in fact)
935 $request = $this->getRequest();
937 $cookieId = $request->getCookie( 'UserID' );
938 $sessId = $request->getSessionData( 'wsUserID' );
940 if ( $cookieId !== null ) {
941 $sId = intval( $cookieId );
942 if( $sessId !== null && $cookieId != $sessId ) {
943 $this->loadDefaults(); // Possible collision!
944 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
945 cookie user ID ($sId) don't match!" );
948 $request->setSessionData( 'wsUserID', $sId );
949 } elseif ( $sessId !== null && $sessId != 0 ) {
952 $this->loadDefaults();
956 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
957 $sName = $request->getSessionData( 'wsUserName' );
958 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
959 $sName = $request->getCookie( 'UserName' );
960 $request->setSessionData( 'wsUserName', $sName );
962 $this->loadDefaults();
966 $proposedUser = User
::newFromId( $sId );
967 if ( !$proposedUser->isLoggedIn() ) {
969 $this->loadDefaults();
973 global $wgBlockDisablesLogin;
974 if( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
975 # User blocked and we've disabled blocked user logins
976 $this->loadDefaults();
980 if ( $request->getSessionData( 'wsToken' ) !== null ) {
981 $passwordCorrect = $proposedUser->getToken() === $request->getSessionData( 'wsToken' );
983 } elseif ( $request->getCookie( 'Token' ) !== null ) {
984 $passwordCorrect = $proposedUser->getToken() === $request->getCookie( 'Token' );
987 # No session or persistent login cookie
988 $this->loadDefaults();
992 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
993 $this->loadFromUserObject( $proposedUser );
994 $request->setSessionData( 'wsToken', $this->mToken
);
995 wfDebug( "User: logged in from $from\n" );
998 # Invalid credentials
999 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1000 $this->loadDefaults();
1006 * Load user and user_group data from the database.
1007 * $this->mId must be set, this is how the user is identified.
1009 * @return Bool True if the user exists, false if the user is anonymous
1012 function loadFromDatabase() {
1014 $this->mId
= intval( $this->mId
);
1016 /** Anonymous user */
1018 $this->loadDefaults();
1022 $dbr = wfGetDB( DB_MASTER
);
1023 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
1025 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1027 if ( $s !== false ) {
1028 # Initialise user table data
1029 $this->loadFromRow( $s );
1030 $this->mGroups
= null; // deferred
1031 $this->getEditCount(); // revalidation for nulls
1036 $this->loadDefaults();
1042 * Initialize this object from a row from the user table.
1044 * @param $row Array Row from the user table to load.
1046 function loadFromRow( $row ) {
1049 if ( isset( $row->user_name
) ) {
1050 $this->mName
= $row->user_name
;
1051 $this->mFrom
= 'name';
1052 $this->setItemLoaded( 'name' );
1057 if ( isset( $row->user_real_name
) ) {
1058 $this->mRealName
= $row->user_real_name
;
1059 $this->setItemLoaded( 'realname' );
1064 if ( isset( $row->user_id
) ) {
1065 $this->mId
= intval( $row->user_id
);
1066 $this->mFrom
= 'id';
1067 $this->setItemLoaded( 'id' );
1072 if ( isset( $row->user_password
) ) {
1073 $this->mPassword
= $row->user_password
;
1074 $this->mNewpassword
= $row->user_newpassword
;
1075 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1076 $this->mEmail
= $row->user_email
;
1077 $this->decodeOptions( $row->user_options
);
1078 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
1079 $this->mToken
= $row->user_token
;
1080 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1081 $this->mEmailToken
= $row->user_email_token
;
1082 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1083 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1084 $this->mEditCount
= $row->user_editcount
;
1090 $this->mLoadedItems
= true;
1095 * Load the data for this user object from another user object.
1099 protected function loadFromUserObject( $user ) {
1101 $user->loadGroups();
1102 $user->loadOptions();
1103 foreach ( self
::$mCacheVars as $var ) {
1104 $this->$var = $user->$var;
1109 * Load the groups from the database if they aren't already loaded.
1112 function loadGroups() {
1113 if ( is_null( $this->mGroups
) ) {
1114 $dbr = wfGetDB( DB_MASTER
);
1115 $res = $dbr->select( 'user_groups',
1116 array( 'ug_group' ),
1117 array( 'ug_user' => $this->mId
),
1119 $this->mGroups
= array();
1120 foreach ( $res as $row ) {
1121 $this->mGroups
[] = $row->ug_group
;
1127 * Add the user to the group if he/she meets given criteria.
1129 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1130 * possible to remove manually via Special:UserRights. In such case it
1131 * will not be re-added automatically. The user will also not lose the
1132 * group if they no longer meet the criteria.
1134 * @param $event String key in $wgAutopromoteOnce (each one has groups/criteria)
1136 * @return array Array of groups the user has been promoted to.
1138 * @see $wgAutopromoteOnce
1140 public function addAutopromoteOnceGroups( $event ) {
1141 global $wgAutopromoteOnceLogInRC;
1143 $toPromote = array();
1144 if ( $this->getId() ) {
1145 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1146 if ( count( $toPromote ) ) {
1147 $oldGroups = $this->getGroups(); // previous groups
1148 foreach ( $toPromote as $group ) {
1149 $this->addGroup( $group );
1151 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1153 $log = new LogPage( 'rights', $wgAutopromoteOnceLogInRC /* in RC? */ );
1154 $log->addEntry( 'autopromote',
1155 $this->getUserPage(),
1157 array( implode( ', ', $oldGroups ), implode( ', ', $newGroups ) )
1165 * Clear various cached data stored in this object.
1166 * @param $reloadFrom String Reload user and user_groups table data from a
1167 * given source. May be "name", "id", "defaults", "session", or false for
1170 function clearInstanceCache( $reloadFrom = false ) {
1171 $this->mNewtalk
= -1;
1172 $this->mDatePreference
= null;
1173 $this->mBlockedby
= -1; # Unset
1174 $this->mHash
= false;
1175 $this->mRights
= null;
1176 $this->mEffectiveGroups
= null;
1177 $this->mOptions
= null;
1179 if ( $reloadFrom ) {
1180 $this->mLoadedItems
= array();
1181 $this->mFrom
= $reloadFrom;
1186 * Combine the language default options with any site-specific options
1187 * and add the default language variants.
1189 * @return Array of String options
1191 static function getDefaultOptions() {
1192 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1194 $defOpt = $wgDefaultUserOptions;
1195 # default language setting
1196 $variant = $wgContLang->getDefaultVariant();
1197 $defOpt['variant'] = $variant;
1198 $defOpt['language'] = $variant;
1199 foreach( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1200 $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1202 $defOpt['skin'] = $wgDefaultSkin;
1208 * Get a given default option value.
1210 * @param $opt String Name of option to retrieve
1211 * @return String Default option value
1213 public static function getDefaultOption( $opt ) {
1214 $defOpts = self
::getDefaultOptions();
1215 if( isset( $defOpts[$opt] ) ) {
1216 return $defOpts[$opt];
1224 * Get blocking information
1226 * @param $bFromSlave Bool Whether to check the slave database first. To
1227 * improve performance, non-critical checks are done
1228 * against slaves. Check when actually saving should be
1229 * done against master.
1231 function getBlockedStatus( $bFromSlave = true ) {
1232 global $wgProxyWhitelist, $wgUser;
1234 if ( -1 != $this->mBlockedby
) {
1238 wfProfileIn( __METHOD__
);
1239 wfDebug( __METHOD__
.": checking...\n" );
1241 // Initialize data...
1242 // Otherwise something ends up stomping on $this->mBlockedby when
1243 // things get lazy-loaded later, causing false positive block hits
1244 // due to -1 !== 0. Probably session-related... Nothing should be
1245 // overwriting mBlockedby, surely?
1248 $this->mBlockedby
= 0;
1249 $this->mHideName
= 0;
1250 $this->mAllowUsertalk
= 0;
1252 # We only need to worry about passing the IP address to the Block generator if the
1253 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1254 # know which IP address they're actually coming from
1255 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1262 $this->mBlock
= Block
::newFromTarget( $this->getName(), $ip, !$bFromSlave );
1263 if ( $this->mBlock
instanceof Block
) {
1264 wfDebug( __METHOD__
. ": Found block.\n" );
1265 $this->mBlockedby
= $this->mBlock
->getByName();
1266 $this->mBlockreason
= $this->mBlock
->mReason
;
1267 $this->mHideName
= $this->mBlock
->mHideName
;
1268 $this->mAllowUsertalk
= !$this->mBlock
->prevents( 'editownusertalk' );
1269 if ( $this->isLoggedIn() && $wgUser->getID() == $this->getID() ) {
1270 $this->spreadBlock();
1275 if ( $ip !== null && !$this->isAllowed( 'proxyunbannable' ) && !in_array( $ip, $wgProxyWhitelist ) ) {
1277 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1278 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1279 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1283 if ( !$this->mBlockedby
&& !$this->getID() ) {
1284 if ( $this->isDnsBlacklisted( $ip ) ) {
1285 $this->mBlockedby
= wfMsg( 'sorbs' );
1286 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1292 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1294 wfProfileOut( __METHOD__
);
1298 * Whether the given IP is in a DNS blacklist.
1300 * @param $ip String IP to check
1301 * @param $checkWhitelist Bool: whether to check the whitelist first
1302 * @return Bool True if blacklisted.
1304 function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1305 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1306 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1308 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
1311 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
1314 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1315 return $this->inDnsBlacklist( $ip, $urls );
1319 * Whether the given IP is in a given DNS blacklist.
1321 * @param $ip String IP to check
1322 * @param $bases String|Array of Strings: URL of the DNS blacklist
1323 * @return Bool True if blacklisted.
1325 function inDnsBlacklist( $ip, $bases ) {
1326 wfProfileIn( __METHOD__
);
1329 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1330 if( IP
::isIPv4( $ip ) ) {
1331 # Reverse IP, bug 21255
1332 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1334 foreach( (array)$bases as $base ) {
1336 $host = "$ipReversed.$base";
1339 $ipList = gethostbynamel( $host );
1342 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1346 wfDebug( "Requested $host, not found in $base.\n" );
1351 wfProfileOut( __METHOD__
);
1356 * Check if an IP address is in the local proxy list
1359 public static function isLocallyBlockedProxy( $ip ) {
1360 global $wgProxyList;
1362 if ( !$wgProxyList ) {
1365 wfProfileIn( __METHOD__
);
1367 if ( !is_array( $wgProxyList ) ) {
1368 # Load from the specified file
1369 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1372 if ( !is_array( $wgProxyList ) ) {
1374 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1376 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1377 # Old-style flipped proxy list
1382 wfProfileOut( __METHOD__
);
1387 * Is this user subject to rate limiting?
1389 * @return Bool True if rate limited
1391 public function isPingLimitable() {
1392 global $wgRateLimitsExcludedIPs;
1393 if( in_array( wfGetIP(), $wgRateLimitsExcludedIPs ) ) {
1394 // No other good way currently to disable rate limits
1395 // for specific IPs. :P
1396 // But this is a crappy hack and should die.
1399 return !$this->isAllowed('noratelimit');
1403 * Primitive rate limits: enforce maximum actions per time period
1404 * to put a brake on flooding.
1406 * @note When using a shared cache like memcached, IP-address
1407 * last-hit counters will be shared across wikis.
1409 * @param $action String Action to enforce; 'edit' if unspecified
1410 * @return Bool True if a rate limiter was tripped
1412 function pingLimiter( $action = 'edit' ) {
1413 # Call the 'PingLimiter' hook
1415 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1419 global $wgRateLimits;
1420 if( !isset( $wgRateLimits[$action] ) ) {
1424 # Some groups shouldn't trigger the ping limiter, ever
1425 if( !$this->isPingLimitable() )
1428 global $wgMemc, $wgRateLimitLog;
1429 wfProfileIn( __METHOD__
);
1431 $limits = $wgRateLimits[$action];
1433 $id = $this->getId();
1437 if( isset( $limits['anon'] ) && $id == 0 ) {
1438 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1441 if( isset( $limits['user'] ) && $id != 0 ) {
1442 $userLimit = $limits['user'];
1444 if( $this->isNewbie() ) {
1445 if( isset( $limits['newbie'] ) && $id != 0 ) {
1446 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1448 if( isset( $limits['ip'] ) ) {
1449 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1452 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1453 $subnet = $matches[1];
1454 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1457 // Check for group-specific permissions
1458 // If more than one group applies, use the group with the highest limit
1459 foreach ( $this->getGroups() as $group ) {
1460 if ( isset( $limits[$group] ) ) {
1461 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1462 $userLimit = $limits[$group];
1466 // Set the user limit key
1467 if ( $userLimit !== false ) {
1468 wfDebug( __METHOD__
. ": effective user limit: $userLimit\n" );
1469 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1473 foreach( $keys as $key => $limit ) {
1474 list( $max, $period ) = $limit;
1475 $summary = "(limit $max in {$period}s)";
1476 $count = $wgMemc->get( $key );
1479 if( $count > $max ) {
1480 wfDebug( __METHOD__
. ": tripped! $key at $count $summary\n" );
1481 if( $wgRateLimitLog ) {
1482 wfSuppressWarnings();
1483 file_put_contents( $wgRateLimitLog, wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", FILE_APPEND
);
1484 wfRestoreWarnings();
1488 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1491 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1492 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1494 $wgMemc->incr( $key );
1497 wfProfileOut( __METHOD__
);
1502 * Check if user is blocked
1504 * @param $bFromSlave Bool Whether to check the slave database instead of the master
1505 * @return Bool True if blocked, false otherwise
1507 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1508 $this->getBlockedStatus( $bFromSlave );
1509 return $this->mBlock
instanceof Block
&& $this->mBlock
->prevents( 'edit' );
1513 * Check if user is blocked from editing a particular article
1515 * @param $title Title to check
1516 * @param $bFromSlave Bool whether to check the slave database instead of the master
1519 function isBlockedFrom( $title, $bFromSlave = false ) {
1520 global $wgBlockAllowsUTEdit;
1521 wfProfileIn( __METHOD__
);
1523 $blocked = $this->isBlocked( $bFromSlave );
1524 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1525 # If a user's name is suppressed, they cannot make edits anywhere
1526 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1527 $title->getNamespace() == NS_USER_TALK
) {
1529 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1532 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1534 wfProfileOut( __METHOD__
);
1539 * If user is blocked, return the name of the user who placed the block
1540 * @return String name of blocker
1542 function blockedBy() {
1543 $this->getBlockedStatus();
1544 return $this->mBlockedby
;
1548 * If user is blocked, return the specified reason for the block
1549 * @return String Blocking reason
1551 function blockedFor() {
1552 $this->getBlockedStatus();
1553 return $this->mBlockreason
;
1557 * If user is blocked, return the ID for the block
1558 * @return Int Block ID
1560 function getBlockId() {
1561 $this->getBlockedStatus();
1562 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1566 * Check if user is blocked on all wikis.
1567 * Do not use for actual edit permission checks!
1568 * This is intented for quick UI checks.
1570 * @param $ip String IP address, uses current client if none given
1571 * @return Bool True if blocked, false otherwise
1573 function isBlockedGlobally( $ip = '' ) {
1574 if( $this->mBlockedGlobally
!== null ) {
1575 return $this->mBlockedGlobally
;
1577 // User is already an IP?
1578 if( IP
::isIPAddress( $this->getName() ) ) {
1579 $ip = $this->getName();
1584 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1585 $this->mBlockedGlobally
= (bool)$blocked;
1586 return $this->mBlockedGlobally
;
1590 * Check if user account is locked
1592 * @return Bool True if locked, false otherwise
1594 function isLocked() {
1595 if( $this->mLocked
!== null ) {
1596 return $this->mLocked
;
1599 $authUser = $wgAuth->getUserInstance( $this );
1600 $this->mLocked
= (bool)$authUser->isLocked();
1601 return $this->mLocked
;
1605 * Check if user account is hidden
1607 * @return Bool True if hidden, false otherwise
1609 function isHidden() {
1610 if( $this->mHideName
!== null ) {
1611 return $this->mHideName
;
1613 $this->getBlockedStatus();
1614 if( !$this->mHideName
) {
1616 $authUser = $wgAuth->getUserInstance( $this );
1617 $this->mHideName
= (bool)$authUser->isHidden();
1619 return $this->mHideName
;
1623 * Get the user's ID.
1624 * @return Int The user's ID; 0 if the user is anonymous or nonexistent
1627 if( $this->mId
=== null && $this->mName
!== null
1628 && User
::isIP( $this->mName
) ) {
1629 // Special case, we know the user is anonymous
1631 } elseif( !$this->isItemLoaded( 'id' ) ) {
1632 // Don't load if this was initialized from an ID
1639 * Set the user and reload all fields according to a given ID
1640 * @param $v Int User ID to reload
1642 function setId( $v ) {
1644 $this->clearInstanceCache( 'id' );
1648 * Get the user name, or the IP of an anonymous user
1649 * @return String User's name or IP address
1651 function getName() {
1652 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1653 # Special case optimisation
1654 return $this->mName
;
1657 if ( $this->mName
=== false ) {
1659 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1661 return $this->mName
;
1666 * Set the user name.
1668 * This does not reload fields from the database according to the given
1669 * name. Rather, it is used to create a temporary "nonexistent user" for
1670 * later addition to the database. It can also be used to set the IP
1671 * address for an anonymous user to something other than the current
1674 * @note User::newFromName() has rougly the same function, when the named user
1676 * @param $str String New user name to set
1678 function setName( $str ) {
1680 $this->mName
= $str;
1684 * Get the user's name escaped by underscores.
1685 * @return String Username escaped by underscores.
1687 function getTitleKey() {
1688 return str_replace( ' ', '_', $this->getName() );
1692 * Check if the user has new messages.
1693 * @return Bool True if the user has new messages
1695 function getNewtalk() {
1698 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1699 if( $this->mNewtalk
=== -1 ) {
1700 $this->mNewtalk
= false; # reset talk page status
1702 # Check memcached separately for anons, who have no
1703 # entire User object stored in there.
1706 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1707 $newtalk = $wgMemc->get( $key );
1708 if( strval( $newtalk ) !== '' ) {
1709 $this->mNewtalk
= (bool)$newtalk;
1711 // Since we are caching this, make sure it is up to date by getting it
1713 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1714 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1717 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1721 return (bool)$this->mNewtalk
;
1725 * Return the talk page(s) this user has new messages on.
1726 * @return Array of String page URLs
1728 function getNewMessageLinks() {
1730 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) )
1733 if( !$this->getNewtalk() )
1735 $up = $this->getUserPage();
1736 $utp = $up->getTalkPage();
1737 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL() ) );
1741 * Internal uncached check for new messages
1744 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1745 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1746 * @param $fromMaster Bool true to fetch from the master, false for a slave
1747 * @return Bool True if the user has new messages
1749 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
1750 if ( $fromMaster ) {
1751 $db = wfGetDB( DB_MASTER
);
1753 $db = wfGetDB( DB_SLAVE
);
1755 $ok = $db->selectField( 'user_newtalk', $field,
1756 array( $field => $id ), __METHOD__
);
1757 return $ok !== false;
1761 * Add or update the new messages flag
1762 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1763 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1764 * @return Bool True if successful, false otherwise
1766 protected function updateNewtalk( $field, $id ) {
1767 $dbw = wfGetDB( DB_MASTER
);
1768 $dbw->insert( 'user_newtalk',
1769 array( $field => $id ),
1772 if ( $dbw->affectedRows() ) {
1773 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
1776 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
1782 * Clear the new messages flag for the given user
1783 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1784 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1785 * @return Bool True if successful, false otherwise
1787 protected function deleteNewtalk( $field, $id ) {
1788 $dbw = wfGetDB( DB_MASTER
);
1789 $dbw->delete( 'user_newtalk',
1790 array( $field => $id ),
1792 if ( $dbw->affectedRows() ) {
1793 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
1796 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
1802 * Update the 'You have new messages!' status.
1803 * @param $val Bool Whether the user has new messages
1805 function setNewtalk( $val ) {
1806 if( wfReadOnly() ) {
1811 $this->mNewtalk
= $val;
1813 if( $this->isAnon() ) {
1815 $id = $this->getName();
1818 $id = $this->getId();
1823 $changed = $this->updateNewtalk( $field, $id );
1825 $changed = $this->deleteNewtalk( $field, $id );
1828 if( $this->isAnon() ) {
1829 // Anons have a separate memcached space, since
1830 // user records aren't kept for them.
1831 $key = wfMemcKey( 'newtalk', 'ip', $id );
1832 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1835 $this->invalidateCache();
1840 * Generate a current or new-future timestamp to be stored in the
1841 * user_touched field when we update things.
1842 * @return String Timestamp in TS_MW format
1844 private static function newTouchedTimestamp() {
1845 global $wgClockSkewFudge;
1846 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1850 * Clear user data from memcached.
1851 * Use after applying fun updates to the database; caller's
1852 * responsibility to update user_touched if appropriate.
1854 * Called implicitly from invalidateCache() and saveSettings().
1856 private function clearSharedCache() {
1860 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1865 * Immediately touch the user data cache for this account.
1866 * Updates user_touched field, and removes account data from memcached
1867 * for reload on the next hit.
1869 function invalidateCache() {
1870 if( wfReadOnly() ) {
1875 $this->mTouched
= self
::newTouchedTimestamp();
1877 $dbw = wfGetDB( DB_MASTER
);
1878 $dbw->update( 'user',
1879 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1880 array( 'user_id' => $this->mId
),
1883 $this->clearSharedCache();
1888 * Validate the cache for this account.
1889 * @param $timestamp String A timestamp in TS_MW format
1891 function validateCache( $timestamp ) {
1893 return ( $timestamp >= $this->mTouched
);
1897 * Get the user touched timestamp
1898 * @return String timestamp
1900 function getTouched() {
1902 return $this->mTouched
;
1906 * Set the password and reset the random token.
1907 * Calls through to authentication plugin if necessary;
1908 * will have no effect if the auth plugin refuses to
1909 * pass the change through or if the legal password
1912 * As a special case, setting the password to null
1913 * wipes it, so the account cannot be logged in until
1914 * a new password is set, for instance via e-mail.
1916 * @param $str String New password to set
1917 * @throws PasswordError on failure
1919 function setPassword( $str ) {
1922 if( $str !== null ) {
1923 if( !$wgAuth->allowPasswordChange() ) {
1924 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1927 if( !$this->isValidPassword( $str ) ) {
1928 global $wgMinimalPasswordLength;
1929 $valid = $this->getPasswordValidity( $str );
1930 if ( is_array( $valid ) ) {
1931 $message = array_shift( $valid );
1935 $params = array( $wgMinimalPasswordLength );
1937 throw new PasswordError( wfMsgExt( $message, array( 'parsemag' ), $params ) );
1941 if( !$wgAuth->setPassword( $this, $str ) ) {
1942 throw new PasswordError( wfMsg( 'externaldberror' ) );
1945 $this->setInternalPassword( $str );
1951 * Set the password and reset the random token unconditionally.
1953 * @param $str String New password to set
1955 function setInternalPassword( $str ) {
1959 if( $str === null ) {
1960 // Save an invalid hash...
1961 $this->mPassword
= '';
1963 $this->mPassword
= self
::crypt( $str );
1965 $this->mNewpassword
= '';
1966 $this->mNewpassTime
= null;
1970 * Get the user's current token.
1971 * @return String Token
1973 function getToken() {
1975 return $this->mToken
;
1979 * Set the random token (used for persistent authentication)
1980 * Called from loadDefaults() among other places.
1982 * @param $token String If specified, set the token to this value
1985 function setToken( $token = false ) {
1986 global $wgSecretKey, $wgProxyKey;
1989 if ( $wgSecretKey ) {
1990 $key = $wgSecretKey;
1991 } elseif ( $wgProxyKey ) {
1996 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1998 $this->mToken
= $token;
2003 * Set the cookie password
2005 * @param $str String New cookie password
2008 function setCookiePassword( $str ) {
2010 $this->mCookiePassword
= md5( $str );
2014 * Set the password for a password reminder or new account email
2016 * @param $str String New password to set
2017 * @param $throttle Bool If true, reset the throttle timestamp to the present
2019 function setNewpassword( $str, $throttle = true ) {
2021 $this->mNewpassword
= self
::crypt( $str );
2023 $this->mNewpassTime
= wfTimestampNow();
2028 * Has password reminder email been sent within the last
2029 * $wgPasswordReminderResendTime hours?
2032 function isPasswordReminderThrottled() {
2033 global $wgPasswordReminderResendTime;
2035 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2038 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2039 return time() < $expiry;
2043 * Get the user's e-mail address
2044 * @return String User's email address
2046 function getEmail() {
2048 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
2049 return $this->mEmail
;
2053 * Get the timestamp of the user's e-mail authentication
2054 * @return String TS_MW timestamp
2056 function getEmailAuthenticationTimestamp() {
2058 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2059 return $this->mEmailAuthenticated
;
2063 * Set the user's e-mail address
2064 * @param $str String New e-mail address
2066 function setEmail( $str ) {
2068 $this->mEmail
= $str;
2069 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
2073 * Get the user's real name
2074 * @return String User's real name
2076 function getRealName() {
2077 if ( !$this->isItemLoaded( 'realname' ) ) {
2081 return $this->mRealName
;
2085 * Set the user's real name
2086 * @param $str String New real name
2088 function setRealName( $str ) {
2090 $this->mRealName
= $str;
2094 * Get the user's current setting for a given option.
2096 * @param $oname String The option to check
2097 * @param $defaultOverride String A default value returned if the option does not exist
2098 * @param $ignoreHidden Bool = whether to ignore the effects of $wgHiddenPrefs
2099 * @return String User's current value for the option
2100 * @see getBoolOption()
2101 * @see getIntOption()
2103 function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2104 global $wgHiddenPrefs;
2105 $this->loadOptions();
2107 if ( is_null( $this->mOptions
) ) {
2108 if($defaultOverride != '') {
2109 return $defaultOverride;
2111 $this->mOptions
= User
::getDefaultOptions();
2114 # We want 'disabled' preferences to always behave as the default value for
2115 # users, even if they have set the option explicitly in their settings (ie they
2116 # set it, and then it was disabled removing their ability to change it). But
2117 # we don't want to erase the preferences in the database in case the preference
2118 # is re-enabled again. So don't touch $mOptions, just override the returned value
2119 if( in_array( $oname, $wgHiddenPrefs ) && !$ignoreHidden ){
2120 return self
::getDefaultOption( $oname );
2123 if ( array_key_exists( $oname, $this->mOptions
) ) {
2124 return $this->mOptions
[$oname];
2126 return $defaultOverride;
2131 * Get all user's options
2135 public function getOptions() {
2136 global $wgHiddenPrefs;
2137 $this->loadOptions();
2138 $options = $this->mOptions
;
2140 # We want 'disabled' preferences to always behave as the default value for
2141 # users, even if they have set the option explicitly in their settings (ie they
2142 # set it, and then it was disabled removing their ability to change it). But
2143 # we don't want to erase the preferences in the database in case the preference
2144 # is re-enabled again. So don't touch $mOptions, just override the returned value
2145 foreach( $wgHiddenPrefs as $pref ){
2146 $default = self
::getDefaultOption( $pref );
2147 if( $default !== null ){
2148 $options[$pref] = $default;
2156 * Get the user's current setting for a given option, as a boolean value.
2158 * @param $oname String The option to check
2159 * @return Bool User's current value for the option
2162 function getBoolOption( $oname ) {
2163 return (bool)$this->getOption( $oname );
2168 * Get the user's current setting for a given option, as a boolean value.
2170 * @param $oname String The option to check
2171 * @param $defaultOverride Int A default value returned if the option does not exist
2172 * @return Int User's current value for the option
2175 function getIntOption( $oname, $defaultOverride=0 ) {
2176 $val = $this->getOption( $oname );
2178 $val = $defaultOverride;
2180 return intval( $val );
2184 * Set the given option for a user.
2186 * @param $oname String The option to set
2187 * @param $val mixed New value to set
2189 function setOption( $oname, $val ) {
2191 $this->loadOptions();
2193 // Explicitly NULL values should refer to defaults
2194 global $wgDefaultUserOptions;
2195 if( is_null( $val ) && isset( $wgDefaultUserOptions[$oname] ) ) {
2196 $val = $wgDefaultUserOptions[$oname];
2199 $this->mOptions
[$oname] = $val;
2203 * Reset all options to the site defaults
2205 function resetOptions() {
2206 $this->mOptions
= self
::getDefaultOptions();
2210 * Get the user's preferred date format.
2211 * @return String User's preferred date format
2213 function getDatePreference() {
2214 // Important migration for old data rows
2215 if ( is_null( $this->mDatePreference
) ) {
2217 $value = $this->getOption( 'date' );
2218 $map = $wgLang->getDatePreferenceMigrationMap();
2219 if ( isset( $map[$value] ) ) {
2220 $value = $map[$value];
2222 $this->mDatePreference
= $value;
2224 return $this->mDatePreference
;
2228 * Get the user preferred stub threshold
2230 function getStubThreshold() {
2231 global $wgMaxArticleSize; # Maximum article size, in Kb
2232 $threshold = intval( $this->getOption( 'stubthreshold' ) );
2233 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2234 # If they have set an impossible value, disable the preference
2235 # so we can use the parser cache again.
2242 * Get the permissions this user has.
2243 * @return Array of String permission names
2245 function getRights() {
2246 if ( is_null( $this->mRights
) ) {
2247 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2248 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2249 // Force reindexation of rights when a hook has unset one of them
2250 $this->mRights
= array_values( $this->mRights
);
2252 return $this->mRights
;
2256 * Get the list of explicit group memberships this user has.
2257 * The implicit * and user groups are not included.
2258 * @return Array of String internal group names
2260 function getGroups() {
2262 return $this->mGroups
;
2266 * Get the list of implicit group memberships this user has.
2267 * This includes all explicit groups, plus 'user' if logged in,
2268 * '*' for all accounts, and autopromoted groups
2269 * @param $recache Bool Whether to avoid the cache
2270 * @return Array of String internal group names
2272 function getEffectiveGroups( $recache = false ) {
2273 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2274 wfProfileIn( __METHOD__
);
2275 $this->mEffectiveGroups
= $this->getGroups();
2276 $this->mEffectiveGroups
[] = '*';
2277 if( $this->getId() ) {
2278 $this->mEffectiveGroups
[] = 'user';
2280 $this->mEffectiveGroups
= array_unique( array_merge(
2281 $this->mEffectiveGroups
,
2282 Autopromote
::getAutopromoteGroups( $this )
2285 # Hook for additional groups
2286 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2288 wfProfileOut( __METHOD__
);
2290 return $this->mEffectiveGroups
;
2294 * Returns the groups the user has belonged to.
2296 * The user may still belong to the returned groups. Compare with getGroups().
2298 * The function will not return groups the user had belonged to before MW 1.17
2300 * @return array Names of the groups the user has belonged to.
2302 function getFormerGroups() {
2303 if( is_null( $this->mFormerGroups
) ) {
2304 $dbr = wfGetDB( DB_MASTER
);
2305 $res = $dbr->select( 'user_former_groups',
2306 array( 'ufg_group' ),
2307 array( 'ufg_user' => $this->mId
),
2309 $this->mFormerGroups
= array();
2310 foreach( $res as $row ) {
2311 $this->mFormerGroups
[] = $row->ufg_group
;
2314 return $this->mFormerGroups
;
2318 * Get the user's edit count.
2321 function getEditCount() {
2322 if( $this->getId() ) {
2323 if ( !isset( $this->mEditCount
) ) {
2324 /* Populate the count, if it has not been populated yet */
2325 $this->mEditCount
= User
::edits( $this->mId
);
2327 return $this->mEditCount
;
2335 * Add the user to the given group.
2336 * This takes immediate effect.
2337 * @param $group String Name of the group to add
2339 function addGroup( $group ) {
2340 if( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2341 $dbw = wfGetDB( DB_MASTER
);
2342 if( $this->getId() ) {
2343 $dbw->insert( 'user_groups',
2345 'ug_user' => $this->getID(),
2346 'ug_group' => $group,
2349 array( 'IGNORE' ) );
2352 $this->loadGroups();
2353 $this->mGroups
[] = $group;
2354 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2356 $this->invalidateCache();
2360 * Remove the user from the given group.
2361 * This takes immediate effect.
2362 * @param $group String Name of the group to remove
2364 function removeGroup( $group ) {
2366 if( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2367 $dbw = wfGetDB( DB_MASTER
);
2368 $dbw->delete( 'user_groups',
2370 'ug_user' => $this->getID(),
2371 'ug_group' => $group,
2373 // Remember that the user was in this group
2374 $dbw->insert( 'user_former_groups',
2376 'ufg_user' => $this->getID(),
2377 'ufg_group' => $group,
2380 array( 'IGNORE' ) );
2382 $this->loadGroups();
2383 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2384 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
2386 $this->invalidateCache();
2390 * Get whether the user is logged in
2393 function isLoggedIn() {
2394 return $this->getID() != 0;
2398 * Get whether the user is anonymous
2402 return !$this->isLoggedIn();
2406 * Check if user is allowed to access a feature / make an action
2407 * @param varargs String permissions to test
2408 * @return Boolean: True if user is allowed to perform *any* of the given actions
2410 public function isAllowedAny( /*...*/ ){
2411 $permissions = func_get_args();
2412 foreach( $permissions as $permission ){
2413 if( $this->isAllowed( $permission ) ){
2421 * @param varargs String
2422 * @return bool True if the user is allowed to perform *all* of the given actions
2424 public function isAllowedAll( /*...*/ ){
2425 $permissions = func_get_args();
2426 foreach( $permissions as $permission ){
2427 if( !$this->isAllowed( $permission ) ){
2435 * Internal mechanics of testing a permission
2436 * @param $action String
2439 public function isAllowed( $action = '' ) {
2440 if ( $action === '' ) {
2441 return true; // In the spirit of DWIM
2443 # Patrolling may not be enabled
2444 if( $action === 'patrol' ||
$action === 'autopatrol' ) {
2445 global $wgUseRCPatrol, $wgUseNPPatrol;
2446 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2449 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2450 # by misconfiguration: 0 == 'foo'
2451 return in_array( $action, $this->getRights(), true );
2455 * Check whether to enable recent changes patrol features for this user
2456 * @return Boolean: True or false
2458 public function useRCPatrol() {
2459 global $wgUseRCPatrol;
2460 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
2464 * Check whether to enable new pages patrol features for this user
2465 * @return Bool True or false
2467 public function useNPPatrol() {
2468 global $wgUseRCPatrol, $wgUseNPPatrol;
2469 return( ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) ) );
2473 * Get the WebRequest object to use with this object
2475 * @return WebRequest
2477 public function getRequest() {
2478 if ( $this->mRequest
) {
2479 return $this->mRequest
;
2487 * Get the current skin, loading it if required
2488 * @return Skin The current skin
2489 * @todo FIXME: Need to check the old failback system [AV]
2490 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
2492 function getSkin() {
2493 return RequestContext
::getMain()->getSkin();
2497 * Check the watched status of an article.
2498 * @param $title Title of the article to look at
2501 function isWatched( $title ) {
2502 $wl = WatchedItem
::fromUserTitle( $this, $title );
2503 return $wl->isWatched();
2508 * @param $title Title of the article to look at
2510 function addWatch( $title ) {
2511 $wl = WatchedItem
::fromUserTitle( $this, $title );
2513 $this->invalidateCache();
2517 * Stop watching an article.
2518 * @param $title Title of the article to look at
2520 function removeWatch( $title ) {
2521 $wl = WatchedItem
::fromUserTitle( $this, $title );
2523 $this->invalidateCache();
2527 * Clear the user's notification timestamp for the given title.
2528 * If e-notif e-mails are on, they will receive notification mails on
2529 * the next change of the page if it's watched etc.
2530 * @param $title Title of the article to look at
2532 function clearNotification( &$title ) {
2533 global $wgUseEnotif, $wgShowUpdatedMarker;
2535 # Do nothing if the database is locked to writes
2536 if( wfReadOnly() ) {
2540 if( $title->getNamespace() == NS_USER_TALK
&&
2541 $title->getText() == $this->getName() ) {
2542 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2544 $this->setNewtalk( false );
2547 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2551 if( $this->isAnon() ) {
2552 // Nothing else to do...
2556 // Only update the timestamp if the page is being watched.
2557 // The query to find out if it is watched is cached both in memcached and per-invocation,
2558 // and when it does have to be executed, it can be on a slave
2559 // If this is the user's newtalk page, we always update the timestamp
2560 if( $title->getNamespace() == NS_USER_TALK
&&
2561 $title->getText() == $this->getName() )
2565 $watched = $this->isWatched( $title );
2568 // If the page is watched by the user (or may be watched), update the timestamp on any
2569 // any matching rows
2571 $dbw = wfGetDB( DB_MASTER
);
2572 $dbw->update( 'watchlist',
2574 'wl_notificationtimestamp' => null
2575 ), array( /* WHERE */
2576 'wl_title' => $title->getDBkey(),
2577 'wl_namespace' => $title->getNamespace(),
2578 'wl_user' => $this->getID()
2585 * Resets all of the given user's page-change notification timestamps.
2586 * If e-notif e-mails are on, they will receive notification mails on
2587 * the next change of any watched page.
2589 function clearAllNotifications() {
2590 global $wgUseEnotif, $wgShowUpdatedMarker;
2591 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2592 $this->setNewtalk( false );
2595 $id = $this->getId();
2597 $dbw = wfGetDB( DB_MASTER
);
2598 $dbw->update( 'watchlist',
2600 'wl_notificationtimestamp' => null
2601 ), array( /* WHERE */
2605 # We also need to clear here the "you have new message" notification for the own user_talk page
2606 # This is cleared one page view later in Article::viewUpdates();
2611 * Set this user's options from an encoded string
2612 * @param $str String Encoded options to import
2615 function decodeOptions( $str ) {
2619 $this->mOptionsLoaded
= true;
2620 $this->mOptionOverrides
= array();
2622 // If an option is not set in $str, use the default value
2623 $this->mOptions
= self
::getDefaultOptions();
2625 $a = explode( "\n", $str );
2626 foreach ( $a as $s ) {
2628 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2629 $this->mOptions
[$m[1]] = $m[2];
2630 $this->mOptionOverrides
[$m[1]] = $m[2];
2636 * Set a cookie on the user's client. Wrapper for
2637 * WebResponse::setCookie
2638 * @param $name String Name of the cookie to set
2639 * @param $value String Value to set
2640 * @param $exp Int Expiration time, as a UNIX time value;
2641 * if 0 or not specified, use the default $wgCookieExpiration
2643 protected function setCookie( $name, $value, $exp = 0 ) {
2644 $this->getRequest()->response()->setcookie( $name, $value, $exp );
2648 * Clear a cookie on the user's client
2649 * @param $name String Name of the cookie to clear
2651 protected function clearCookie( $name ) {
2652 $this->setCookie( $name, '', time() - 86400 );
2656 * Set the default cookies for this session on the user's client.
2658 * @param $request WebRequest object to use; $wgRequest will be used if null
2661 function setCookies( $request = null ) {
2662 if ( $request === null ) {
2663 $request = $this->getRequest();
2667 if ( 0 == $this->mId
) return;
2669 'wsUserID' => $this->mId
,
2670 'wsToken' => $this->mToken
,
2671 'wsUserName' => $this->getName()
2674 'UserID' => $this->mId
,
2675 'UserName' => $this->getName(),
2677 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2678 $cookies['Token'] = $this->mToken
;
2680 $cookies['Token'] = false;
2683 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2685 foreach ( $session as $name => $value ) {
2686 $request->setSessionData( $name, $value );
2688 foreach ( $cookies as $name => $value ) {
2689 if ( $value === false ) {
2690 $this->clearCookie( $name );
2692 $this->setCookie( $name, $value );
2698 * Log this user out.
2701 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
2707 * Clear the user's cookies and session, and reset the instance cache.
2711 function doLogout() {
2712 $this->clearInstanceCache( 'defaults' );
2714 $this->getRequest()->setSessionData( 'wsUserID', 0 );
2716 $this->clearCookie( 'UserID' );
2717 $this->clearCookie( 'Token' );
2719 # Remember when user logged out, to prevent seeing cached pages
2720 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2724 * Save this user's settings into the database.
2725 * @todo Only rarely do all these fields need to be set!
2727 function saveSettings() {
2729 if ( wfReadOnly() ) { return; }
2730 if ( 0 == $this->mId
) { return; }
2732 $this->mTouched
= self
::newTouchedTimestamp();
2734 $dbw = wfGetDB( DB_MASTER
);
2735 $dbw->update( 'user',
2737 'user_name' => $this->mName
,
2738 'user_password' => $this->mPassword
,
2739 'user_newpassword' => $this->mNewpassword
,
2740 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2741 'user_real_name' => $this->mRealName
,
2742 'user_email' => $this->mEmail
,
2743 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2744 'user_options' => '',
2745 'user_touched' => $dbw->timestamp( $this->mTouched
),
2746 'user_token' => $this->mToken
,
2747 'user_email_token' => $this->mEmailToken
,
2748 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2749 ), array( /* WHERE */
2750 'user_id' => $this->mId
2754 $this->saveOptions();
2756 wfRunHooks( 'UserSaveSettings', array( $this ) );
2757 $this->clearSharedCache();
2758 $this->getUserPage()->invalidateCache();
2762 * If only this user's username is known, and it exists, return the user ID.
2765 function idForName() {
2766 $s = trim( $this->getName() );
2767 if ( $s === '' ) return 0;
2769 $dbr = wfGetDB( DB_SLAVE
);
2770 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2771 if ( $id === false ) {
2778 * Add a user to the database, return the user object
2780 * @param $name String Username to add
2781 * @param $params Array of Strings Non-default parameters to save to the database as user_* fields:
2782 * - password The user's password hash. Password logins will be disabled if this is omitted.
2783 * - newpassword Hash for a temporary password that has been mailed to the user
2784 * - email The user's email address
2785 * - email_authenticated The email authentication timestamp
2786 * - real_name The user's real name
2787 * - options An associative array of non-default options
2788 * - token Random authentication token. Do not set.
2789 * - registration Registration timestamp. Do not set.
2791 * @return User object, or null if the username already exists
2793 static function createNew( $name, $params = array() ) {
2796 if ( isset( $params['options'] ) ) {
2797 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
2798 unset( $params['options'] );
2800 $dbw = wfGetDB( DB_MASTER
);
2801 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2804 'user_id' => $seqVal,
2805 'user_name' => $name,
2806 'user_password' => $user->mPassword
,
2807 'user_newpassword' => $user->mNewpassword
,
2808 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
2809 'user_email' => $user->mEmail
,
2810 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2811 'user_real_name' => $user->mRealName
,
2812 'user_options' => '',
2813 'user_token' => $user->mToken
,
2814 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2815 'user_editcount' => 0,
2817 foreach ( $params as $name => $value ) {
2818 $fields["user_$name"] = $value;
2820 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2821 if ( $dbw->affectedRows() ) {
2822 $newUser = User
::newFromId( $dbw->insertId() );
2830 * Add this existing user object to the database
2832 function addToDatabase() {
2834 $dbw = wfGetDB( DB_MASTER
);
2835 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2836 $dbw->insert( 'user',
2838 'user_id' => $seqVal,
2839 'user_name' => $this->mName
,
2840 'user_password' => $this->mPassword
,
2841 'user_newpassword' => $this->mNewpassword
,
2842 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2843 'user_email' => $this->mEmail
,
2844 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2845 'user_real_name' => $this->mRealName
,
2846 'user_options' => '',
2847 'user_token' => $this->mToken
,
2848 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2849 'user_editcount' => 0,
2852 $this->mId
= $dbw->insertId();
2854 // Clear instance cache other than user table data, which is already accurate
2855 $this->clearInstanceCache();
2857 $this->saveOptions();
2861 * If this (non-anonymous) user is blocked, block any IP address
2862 * they've successfully logged in from.
2864 function spreadBlock() {
2865 wfDebug( __METHOD__
. "()\n" );
2867 if ( $this->mId
== 0 ) {
2871 $userblock = Block
::newFromTarget( $this->getName() );
2872 if ( !$userblock ) {
2876 $userblock->doAutoblock( wfGetIP() );
2880 * Generate a string which will be different for any combination of
2881 * user options which would produce different parser output.
2882 * This will be used as part of the hash key for the parser cache,
2883 * so users with the same options can share the same cached data
2886 * Extensions which require it should install 'PageRenderingHash' hook,
2887 * which will give them a chance to modify this key based on their own
2890 * @deprecated since 1.17 use the ParserOptions object to get the relevant options
2891 * @return String Page rendering hash
2893 function getPageRenderingHash() {
2894 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2896 return $this->mHash
;
2898 wfDeprecated( __METHOD__
);
2900 // stubthreshold is only included below for completeness,
2901 // since it disables the parser cache, its value will always
2902 // be 0 when this function is called by parsercache.
2904 $confstr = $this->getOption( 'math' );
2905 $confstr .= '!' . $this->getStubThreshold();
2906 if ( $wgUseDynamicDates ) { # This is wrong (bug 24714)
2907 $confstr .= '!' . $this->getDatePreference();
2909 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ?
'1' : '' );
2910 $confstr .= '!' . $wgLang->getCode();
2911 $confstr .= '!' . $this->getOption( 'thumbsize' );
2912 // add in language specific options, if any
2913 $extra = $wgContLang->getExtraHashOptions();
2916 // Since the skin could be overloading link(), it should be
2917 // included here but in practice, none of our skins do that.
2919 $confstr .= $wgRenderHashAppend;
2921 // Give a chance for extensions to modify the hash, if they have
2922 // extra options or other effects on the parser cache.
2923 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2925 // Make it a valid memcached key fragment
2926 $confstr = str_replace( ' ', '_', $confstr );
2927 $this->mHash
= $confstr;
2932 * Get whether the user is explicitly blocked from account creation.
2933 * @return Bool|Block
2935 function isBlockedFromCreateAccount() {
2936 $this->getBlockedStatus();
2937 if( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ){
2938 return $this->mBlock
;
2941 # bug 13611: if the IP address the user is trying to create an account from is
2942 # blocked with createaccount disabled, prevent new account creation there even
2943 # when the user is logged in
2944 if( $this->mBlockedFromCreateAccount
=== false ){
2945 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, wfGetIP() );
2947 return $this->mBlockedFromCreateAccount
instanceof Block
&& $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
2948 ?
$this->mBlockedFromCreateAccount
2953 * Get whether the user is blocked from using Special:Emailuser.
2956 function isBlockedFromEmailuser() {
2957 $this->getBlockedStatus();
2958 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
2962 * Get whether the user is allowed to create an account.
2965 function isAllowedToCreateAccount() {
2966 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2970 * Get this user's personal page title.
2972 * @return Title: User's personal page title
2974 function getUserPage() {
2975 return Title
::makeTitle( NS_USER
, $this->getName() );
2979 * Get this user's talk page title.
2981 * @return Title: User's talk page title
2983 function getTalkPage() {
2984 $title = $this->getUserPage();
2985 return $title->getTalkPage();
2989 * Determine whether the user is a newbie. Newbies are either
2990 * anonymous IPs, or the most recently created accounts.
2993 function isNewbie() {
2994 return !$this->isAllowed( 'autoconfirmed' );
2998 * Check to see if the given clear-text password is one of the accepted passwords
2999 * @param $password String: user password.
3000 * @return Boolean: True if the given password is correct, otherwise False.
3002 function checkPassword( $password ) {
3003 global $wgAuth, $wgLegacyEncoding;
3006 // Even though we stop people from creating passwords that
3007 // are shorter than this, doesn't mean people wont be able
3008 // to. Certain authentication plugins do NOT want to save
3009 // domain passwords in a mysql database, so we should
3010 // check this (in case $wgAuth->strict() is false).
3011 if( !$this->isValidPassword( $password ) ) {
3015 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
3017 } elseif( $wgAuth->strict() ) {
3018 /* Auth plugin doesn't allow local authentication */
3020 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
3021 /* Auth plugin doesn't allow local authentication for this user name */
3024 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
3026 } elseif ( $wgLegacyEncoding ) {
3027 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3028 # Check for this with iconv
3029 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3030 if ( $cp1252Password != $password &&
3031 self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) )
3040 * Check if the given clear-text password matches the temporary password
3041 * sent by e-mail for password reset operations.
3042 * @return Boolean: True if matches, false otherwise
3044 function checkTemporaryPassword( $plaintext ) {
3045 global $wgNewPasswordExpiry;
3048 if( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
3049 if ( is_null( $this->mNewpassTime
) ) {
3052 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3053 return ( time() < $expiry );
3060 * Initialize (if necessary) and return a session token value
3061 * which can be used in edit forms to show that the user's
3062 * login credentials aren't being hijacked with a foreign form
3065 * @param $salt String|Array of Strings Optional function-specific data for hashing
3066 * @param $request WebRequest object to use or null to use $wgRequest
3067 * @return String The new edit token
3069 function editToken( $salt = '', $request = null ) {
3070 if ( $request == null ) {
3071 $request = $this->getRequest();
3074 if ( $this->isAnon() ) {
3075 return EDIT_TOKEN_SUFFIX
;
3077 $token = $request->getSessionData( 'wsEditToken' );
3078 if ( $token === null ) {
3079 $token = self
::generateToken();
3080 $request->setSessionData( 'wsEditToken', $token );
3082 if( is_array( $salt ) ) {
3083 $salt = implode( '|', $salt );
3085 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
3090 * Generate a looking random token for various uses.
3092 * @param $salt String Optional salt value
3093 * @return String The new random token
3095 public static function generateToken( $salt = '' ) {
3096 $token = dechex( mt_rand() ) . dechex( mt_rand() );
3097 return md5( $token . $salt );
3101 * Check given value against the token value stored in the session.
3102 * A match should confirm that the form was submitted from the
3103 * user's own login session, not a form submission from a third-party
3106 * @param $val String Input value to compare
3107 * @param $salt String Optional function-specific data for hashing
3108 * @param $request WebRequest object to use or null to use $wgRequest
3109 * @return Boolean: Whether the token matches
3111 function matchEditToken( $val, $salt = '', $request = null ) {
3112 $sessionToken = $this->editToken( $salt, $request );
3113 if ( $val != $sessionToken ) {
3114 wfDebug( "User::matchEditToken: broken session data\n" );
3116 return $val == $sessionToken;
3120 * Check given value against the token value stored in the session,
3121 * ignoring the suffix.
3123 * @param $val String Input value to compare
3124 * @param $salt String Optional function-specific data for hashing
3125 * @param $request WebRequest object to use or null to use $wgRequest
3126 * @return Boolean: Whether the token matches
3128 function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3129 $sessionToken = $this->editToken( $salt, $request );
3130 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3134 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3135 * mail to the user's given address.
3137 * @param $type String: message to send, either "created", "changed" or "set"
3138 * @return Status object
3140 function sendConfirmationMail( $type = 'created' ) {
3142 $expiration = null; // gets passed-by-ref and defined in next line.
3143 $token = $this->confirmationToken( $expiration );
3144 $url = $this->confirmationTokenUrl( $token );
3145 $invalidateURL = $this->invalidationTokenUrl( $token );
3146 $this->saveSettings();
3148 if ( $type == 'created' ||
$type === false ) {
3149 $message = 'confirmemail_body';
3150 } elseif ( $type === true ) {
3151 $message = 'confirmemail_body_changed';
3153 $message = 'confirmemail_body_' . $type;
3156 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
3161 $wgLang->timeanddate( $expiration, false ),
3163 $wgLang->date( $expiration, false ),
3164 $wgLang->time( $expiration, false ) ) );
3168 * Send an e-mail to this user's account. Does not check for
3169 * confirmed status or validity.
3171 * @param $subject String Message subject
3172 * @param $body String Message body
3173 * @param $from String Optional From address; if unspecified, default $wgPasswordSender will be used
3174 * @param $replyto String Reply-To address
3177 function sendMail( $subject, $body, $from = null, $replyto = null ) {
3178 if( is_null( $from ) ) {
3179 global $wgPasswordSender, $wgPasswordSenderName;
3180 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
3182 $sender = new MailAddress( $from );
3185 $to = new MailAddress( $this );
3186 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
3190 * Generate, store, and return a new e-mail confirmation code.
3191 * A hash (unsalted, since it's used as a key) is stored.
3193 * @note Call saveSettings() after calling this function to commit
3194 * this change to the database.
3196 * @param[out] &$expiration \mixed Accepts the expiration time
3197 * @return String New token
3200 function confirmationToken( &$expiration ) {
3201 global $wgUserEmailConfirmationTokenExpiry;
3203 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
3204 $expiration = wfTimestamp( TS_MW
, $expires );
3205 $token = self
::generateToken( $this->mId
. $this->mEmail
. $expires );
3206 $hash = md5( $token );
3208 $this->mEmailToken
= $hash;
3209 $this->mEmailTokenExpires
= $expiration;
3214 * Return a URL the user can use to confirm their email address.
3215 * @param $token String Accepts the email confirmation token
3216 * @return String New token URL
3219 function confirmationTokenUrl( $token ) {
3220 return $this->getTokenUrl( 'ConfirmEmail', $token );
3224 * Return a URL the user can use to invalidate their email address.
3225 * @param $token String Accepts the email confirmation token
3226 * @return String New token URL
3229 function invalidationTokenUrl( $token ) {
3230 return $this->getTokenUrl( 'Invalidateemail', $token );
3234 * Internal function to format the e-mail validation/invalidation URLs.
3235 * This uses $wgArticlePath directly as a quickie hack to use the
3236 * hardcoded English names of the Special: pages, for ASCII safety.
3238 * @note Since these URLs get dropped directly into emails, using the
3239 * short English names avoids insanely long URL-encoded links, which
3240 * also sometimes can get corrupted in some browsers/mailers
3241 * (bug 6957 with Gmail and Internet Explorer).
3243 * @param $page String Special page
3244 * @param $token String Token
3245 * @return String Formatted URL
3247 protected function getTokenUrl( $page, $token ) {
3248 global $wgArticlePath;
3252 "Special:$page/$token",
3257 * Mark the e-mail address confirmed.
3259 * @note Call saveSettings() after calling this function to commit the change.
3261 function confirmEmail() {
3262 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3263 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3268 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3269 * address if it was already confirmed.
3271 * @note Call saveSettings() after calling this function to commit the change.
3273 function invalidateEmail() {
3275 $this->mEmailToken
= null;
3276 $this->mEmailTokenExpires
= null;
3277 $this->setEmailAuthenticationTimestamp( null );
3278 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3283 * Set the e-mail authentication timestamp.
3284 * @param $timestamp String TS_MW timestamp
3286 function setEmailAuthenticationTimestamp( $timestamp ) {
3288 $this->mEmailAuthenticated
= $timestamp;
3289 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
3293 * Is this user allowed to send e-mails within limits of current
3294 * site configuration?
3297 function canSendEmail() {
3298 global $wgEnableEmail, $wgEnableUserEmail;
3299 if( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
3302 $canSend = $this->isEmailConfirmed();
3303 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3308 * Is this user allowed to receive e-mails within limits of current
3309 * site configuration?
3312 function canReceiveEmail() {
3313 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3317 * Is this user's e-mail address valid-looking and confirmed within
3318 * limits of the current site configuration?
3320 * @note If $wgEmailAuthentication is on, this may require the user to have
3321 * confirmed their address by returning a code or using a password
3322 * sent to the address from the wiki.
3326 function isEmailConfirmed() {
3327 global $wgEmailAuthentication;
3330 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3331 if( $this->isAnon() ) {
3334 if( !Sanitizer
::validateEmail( $this->mEmail
) ) {
3337 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
3347 * Check whether there is an outstanding request for e-mail confirmation.
3350 function isEmailConfirmationPending() {
3351 global $wgEmailAuthentication;
3352 return $wgEmailAuthentication &&
3353 !$this->isEmailConfirmed() &&
3354 $this->mEmailToken
&&
3355 $this->mEmailTokenExpires
> wfTimestamp();
3359 * Get the timestamp of account creation.
3361 * @return String|Bool Timestamp of account creation, or false for
3362 * non-existent/anonymous user accounts.
3364 public function getRegistration() {
3365 if ( $this->isAnon() ) {
3369 return $this->mRegistration
;
3373 * Get the timestamp of the first edit
3375 * @return String|Bool Timestamp of first edit, or false for
3376 * non-existent/anonymous user accounts.
3378 public function getFirstEditTimestamp() {
3379 if( $this->getId() == 0 ) {
3380 return false; // anons
3382 $dbr = wfGetDB( DB_SLAVE
);
3383 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3384 array( 'rev_user' => $this->getId() ),
3386 array( 'ORDER BY' => 'rev_timestamp ASC' )
3389 return false; // no edits
3391 return wfTimestamp( TS_MW
, $time );
3395 * Get the permissions associated with a given list of groups
3397 * @param $groups Array of Strings List of internal group names
3398 * @return Array of Strings List of permission key names for given groups combined
3400 static function getGroupPermissions( $groups ) {
3401 global $wgGroupPermissions, $wgRevokePermissions;
3403 // grant every granted permission first
3404 foreach( $groups as $group ) {
3405 if( isset( $wgGroupPermissions[$group] ) ) {
3406 $rights = array_merge( $rights,
3407 // array_filter removes empty items
3408 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3411 // now revoke the revoked permissions
3412 foreach( $groups as $group ) {
3413 if( isset( $wgRevokePermissions[$group] ) ) {
3414 $rights = array_diff( $rights,
3415 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3418 return array_unique( $rights );
3422 * Get all the groups who have a given permission
3424 * @param $role String Role to check
3425 * @return Array of Strings List of internal group names with the given permission
3427 static function getGroupsWithPermission( $role ) {
3428 global $wgGroupPermissions;
3429 $allowedGroups = array();
3430 foreach ( $wgGroupPermissions as $group => $rights ) {
3431 if ( isset( $rights[$role] ) && $rights[$role] ) {
3432 $allowedGroups[] = $group;
3435 return $allowedGroups;
3439 * Get the localized descriptive name for a group, if it exists
3441 * @param $group String Internal group name
3442 * @return String Localized descriptive group name
3444 static function getGroupName( $group ) {
3445 $msg = wfMessage( "group-$group" );
3446 return $msg->isBlank() ?
$group : $msg->text();
3450 * Get the localized descriptive name for a member of a group, if it exists
3452 * @param $group String Internal group name
3453 * @return String Localized name for group member
3455 static function getGroupMember( $group ) {
3456 $msg = wfMessage( "group-$group-member" );
3457 return $msg->isBlank() ?
$group : $msg->text();
3461 * Return the set of defined explicit groups.
3462 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3463 * are not included, as they are defined automatically, not in the database.
3464 * @return Array of internal group names
3466 static function getAllGroups() {
3467 global $wgGroupPermissions, $wgRevokePermissions;
3469 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3470 self
::getImplicitGroups()
3475 * Get a list of all available permissions.
3476 * @return Array of permission names
3478 static function getAllRights() {
3479 if ( self
::$mAllRights === false ) {
3480 global $wgAvailableRights;
3481 if ( count( $wgAvailableRights ) ) {
3482 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3484 self
::$mAllRights = self
::$mCoreRights;
3486 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3488 return self
::$mAllRights;
3492 * Get a list of implicit groups
3493 * @return Array of Strings Array of internal group names
3495 public static function getImplicitGroups() {
3496 global $wgImplicitGroups;
3497 $groups = $wgImplicitGroups;
3498 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3503 * Get the title of a page describing a particular group
3505 * @param $group String Internal group name
3506 * @return Title|Bool Title of the page if it exists, false otherwise
3508 static function getGroupPage( $group ) {
3509 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
3510 if( $msg->exists() ) {
3511 $title = Title
::newFromText( $msg->text() );
3512 if( is_object( $title ) )
3519 * Create a link to the group in HTML, if available;
3520 * else return the group name.
3522 * @param $group String Internal name of the group
3523 * @param $text String The text of the link
3524 * @return String HTML link to the group
3526 static function makeGroupLinkHTML( $group, $text = '' ) {
3528 $text = self
::getGroupName( $group );
3530 $title = self
::getGroupPage( $group );
3532 return Linker
::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 );