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 * @param $ns int If numeric, get permissions for this namespace
2244 * @return Array of String permission names
2246 function getRights( $ns = null ) {
2247 $key = is_null( $ns ) ?
'*' : intval( $ns );
2249 if ( is_null( $this->mRights
) ) {
2250 $this->mRights
= array();
2253 if ( !isset( $this->mRights
[$key] ) ) {
2254 $this->mRights
[$key] = self
::getGroupPermissions( $this->getEffectiveGroups(), $ns );
2255 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
[$key], $ns ) );
2256 // Force reindexation of rights when a hook has unset one of them
2257 $this->mRights
[$key] = array_values( $this->mRights
[$key] );
2259 if ( is_null( $ns ) ) {
2260 return $this->mRights
[$key];
2262 // Merge non namespace specific rights
2263 return array_merge( $this->mRights
[$key], $this->getRights() );
2269 * Get the list of explicit group memberships this user has.
2270 * The implicit * and user groups are not included.
2271 * @return Array of String internal group names
2273 function getGroups() {
2275 return $this->mGroups
;
2279 * Get the list of implicit group memberships this user has.
2280 * This includes all explicit groups, plus 'user' if logged in,
2281 * '*' for all accounts, and autopromoted groups
2282 * @param $recache Bool Whether to avoid the cache
2283 * @return Array of String internal group names
2285 function getEffectiveGroups( $recache = false ) {
2286 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2287 wfProfileIn( __METHOD__
);
2288 $this->mEffectiveGroups
= $this->getGroups();
2289 $this->mEffectiveGroups
[] = '*';
2290 if( $this->getId() ) {
2291 $this->mEffectiveGroups
[] = 'user';
2293 $this->mEffectiveGroups
= array_unique( array_merge(
2294 $this->mEffectiveGroups
,
2295 Autopromote
::getAutopromoteGroups( $this )
2298 # Hook for additional groups
2299 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2301 wfProfileOut( __METHOD__
);
2303 return $this->mEffectiveGroups
;
2307 * Returns the groups the user has belonged to.
2309 * The user may still belong to the returned groups. Compare with getGroups().
2311 * The function will not return groups the user had belonged to before MW 1.17
2313 * @return array Names of the groups the user has belonged to.
2315 function getFormerGroups() {
2316 if( is_null( $this->mFormerGroups
) ) {
2317 $dbr = wfGetDB( DB_MASTER
);
2318 $res = $dbr->select( 'user_former_groups',
2319 array( 'ufg_group' ),
2320 array( 'ufg_user' => $this->mId
),
2322 $this->mFormerGroups
= array();
2323 foreach( $res as $row ) {
2324 $this->mFormerGroups
[] = $row->ufg_group
;
2327 return $this->mFormerGroups
;
2331 * Get the user's edit count.
2334 function getEditCount() {
2335 if( $this->getId() ) {
2336 if ( !isset( $this->mEditCount
) ) {
2337 /* Populate the count, if it has not been populated yet */
2338 $this->mEditCount
= User
::edits( $this->mId
);
2340 return $this->mEditCount
;
2348 * Add the user to the given group.
2349 * This takes immediate effect.
2350 * @param $group String Name of the group to add
2352 function addGroup( $group ) {
2353 if( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2354 $dbw = wfGetDB( DB_MASTER
);
2355 if( $this->getId() ) {
2356 $dbw->insert( 'user_groups',
2358 'ug_user' => $this->getID(),
2359 'ug_group' => $group,
2362 array( 'IGNORE' ) );
2365 $this->loadGroups();
2366 $this->mGroups
[] = $group;
2367 $this->mRights
= null;
2369 $this->invalidateCache();
2373 * Remove the user from the given group.
2374 * This takes immediate effect.
2375 * @param $group String Name of the group to remove
2377 function removeGroup( $group ) {
2379 if( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2380 $dbw = wfGetDB( DB_MASTER
);
2381 $dbw->delete( 'user_groups',
2383 'ug_user' => $this->getID(),
2384 'ug_group' => $group,
2386 // Remember that the user was in this group
2387 $dbw->insert( 'user_former_groups',
2389 'ufg_user' => $this->getID(),
2390 'ufg_group' => $group,
2393 array( 'IGNORE' ) );
2395 $this->loadGroups();
2396 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2397 $this->mRights
= null;
2399 $this->invalidateCache();
2403 * Get whether the user is logged in
2406 function isLoggedIn() {
2407 return $this->getID() != 0;
2411 * Get whether the user is anonymous
2415 return !$this->isLoggedIn();
2419 * Check if user is allowed to access a feature / make an action
2420 * @param varargs String permissions to test
2421 * @return Boolean: True if user is allowed to perform *any* of the given actions
2423 public function isAllowedAny( /*...*/ ){
2424 $permissions = func_get_args();
2425 foreach( $permissions as $permission ){
2426 if( $this->isAllowed( $permission ) ){
2434 * @param varargs String
2435 * @return bool True if the user is allowed to perform *all* of the given actions
2437 public function isAllowedAll( /*...*/ ){
2438 $permissions = func_get_args();
2439 foreach( $permissions as $permission ){
2440 if( !$this->isAllowed( $permission ) ){
2448 * Internal mechanics of testing a permission
2449 * @param $action String
2450 * @paramn $ns int Namespace optional
2453 public function isAllowed( $action = '', $ns = null ) {
2454 if ( $action === '' ) {
2455 return true; // In the spirit of DWIM
2457 # Patrolling may not be enabled
2458 if( $action === 'patrol' ||
$action === 'autopatrol' ) {
2459 global $wgUseRCPatrol, $wgUseNPPatrol;
2460 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2463 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2464 # by misconfiguration: 0 == 'foo'
2465 return in_array( $action, $this->getRights( $ns ), true );
2469 * Check whether to enable recent changes patrol features for this user
2470 * @return Boolean: True or false
2472 public function useRCPatrol() {
2473 global $wgUseRCPatrol;
2474 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
2478 * Check whether to enable new pages patrol features for this user
2479 * @return Bool True or false
2481 public function useNPPatrol() {
2482 global $wgUseRCPatrol, $wgUseNPPatrol;
2483 return( ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) ) );
2487 * Get the WebRequest object to use with this object
2489 * @return WebRequest
2491 public function getRequest() {
2492 if ( $this->mRequest
) {
2493 return $this->mRequest
;
2501 * Get the current skin, loading it if required
2502 * @return Skin The current skin
2503 * @todo FIXME: Need to check the old failback system [AV]
2504 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
2506 function getSkin() {
2507 return RequestContext
::getMain()->getSkin();
2511 * Check the watched status of an article.
2512 * @param $title Title of the article to look at
2515 function isWatched( $title ) {
2516 $wl = WatchedItem
::fromUserTitle( $this, $title );
2517 return $wl->isWatched();
2522 * @param $title Title of the article to look at
2524 function addWatch( $title ) {
2525 $wl = WatchedItem
::fromUserTitle( $this, $title );
2527 $this->invalidateCache();
2531 * Stop watching an article.
2532 * @param $title Title of the article to look at
2534 function removeWatch( $title ) {
2535 $wl = WatchedItem
::fromUserTitle( $this, $title );
2537 $this->invalidateCache();
2541 * Clear the user's notification timestamp for the given title.
2542 * If e-notif e-mails are on, they will receive notification mails on
2543 * the next change of the page if it's watched etc.
2544 * @param $title Title of the article to look at
2546 function clearNotification( &$title ) {
2547 global $wgUseEnotif, $wgShowUpdatedMarker;
2549 # Do nothing if the database is locked to writes
2550 if( wfReadOnly() ) {
2554 if( $title->getNamespace() == NS_USER_TALK
&&
2555 $title->getText() == $this->getName() ) {
2556 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2558 $this->setNewtalk( false );
2561 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2565 if( $this->isAnon() ) {
2566 // Nothing else to do...
2570 // Only update the timestamp if the page is being watched.
2571 // The query to find out if it is watched is cached both in memcached and per-invocation,
2572 // and when it does have to be executed, it can be on a slave
2573 // If this is the user's newtalk page, we always update the timestamp
2574 if( $title->getNamespace() == NS_USER_TALK
&&
2575 $title->getText() == $this->getName() )
2579 $watched = $this->isWatched( $title );
2582 // If the page is watched by the user (or may be watched), update the timestamp on any
2583 // any matching rows
2585 $dbw = wfGetDB( DB_MASTER
);
2586 $dbw->update( 'watchlist',
2588 'wl_notificationtimestamp' => null
2589 ), array( /* WHERE */
2590 'wl_title' => $title->getDBkey(),
2591 'wl_namespace' => $title->getNamespace(),
2592 'wl_user' => $this->getID()
2599 * Resets all of the given user's page-change notification timestamps.
2600 * If e-notif e-mails are on, they will receive notification mails on
2601 * the next change of any watched page.
2603 function clearAllNotifications() {
2604 global $wgUseEnotif, $wgShowUpdatedMarker;
2605 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2606 $this->setNewtalk( false );
2609 $id = $this->getId();
2611 $dbw = wfGetDB( DB_MASTER
);
2612 $dbw->update( 'watchlist',
2614 'wl_notificationtimestamp' => null
2615 ), array( /* WHERE */
2619 # We also need to clear here the "you have new message" notification for the own user_talk page
2620 # This is cleared one page view later in Article::viewUpdates();
2625 * Set this user's options from an encoded string
2626 * @param $str String Encoded options to import
2629 function decodeOptions( $str ) {
2633 $this->mOptionsLoaded
= true;
2634 $this->mOptionOverrides
= array();
2636 // If an option is not set in $str, use the default value
2637 $this->mOptions
= self
::getDefaultOptions();
2639 $a = explode( "\n", $str );
2640 foreach ( $a as $s ) {
2642 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2643 $this->mOptions
[$m[1]] = $m[2];
2644 $this->mOptionOverrides
[$m[1]] = $m[2];
2650 * Set a cookie on the user's client. Wrapper for
2651 * WebResponse::setCookie
2652 * @param $name String Name of the cookie to set
2653 * @param $value String Value to set
2654 * @param $exp Int Expiration time, as a UNIX time value;
2655 * if 0 or not specified, use the default $wgCookieExpiration
2657 protected function setCookie( $name, $value, $exp = 0 ) {
2658 $this->getRequest()->response()->setcookie( $name, $value, $exp );
2662 * Clear a cookie on the user's client
2663 * @param $name String Name of the cookie to clear
2665 protected function clearCookie( $name ) {
2666 $this->setCookie( $name, '', time() - 86400 );
2670 * Set the default cookies for this session on the user's client.
2672 * @param $request WebRequest object to use; $wgRequest will be used if null
2675 function setCookies( $request = null ) {
2676 if ( $request === null ) {
2677 $request = $this->getRequest();
2681 if ( 0 == $this->mId
) return;
2683 'wsUserID' => $this->mId
,
2684 'wsToken' => $this->mToken
,
2685 'wsUserName' => $this->getName()
2688 'UserID' => $this->mId
,
2689 'UserName' => $this->getName(),
2691 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2692 $cookies['Token'] = $this->mToken
;
2694 $cookies['Token'] = false;
2697 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2699 foreach ( $session as $name => $value ) {
2700 $request->setSessionData( $name, $value );
2702 foreach ( $cookies as $name => $value ) {
2703 if ( $value === false ) {
2704 $this->clearCookie( $name );
2706 $this->setCookie( $name, $value );
2712 * Log this user out.
2715 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
2721 * Clear the user's cookies and session, and reset the instance cache.
2725 function doLogout() {
2726 $this->clearInstanceCache( 'defaults' );
2728 $this->getRequest()->setSessionData( 'wsUserID', 0 );
2730 $this->clearCookie( 'UserID' );
2731 $this->clearCookie( 'Token' );
2733 # Remember when user logged out, to prevent seeing cached pages
2734 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2738 * Save this user's settings into the database.
2739 * @todo Only rarely do all these fields need to be set!
2741 function saveSettings() {
2743 if ( wfReadOnly() ) { return; }
2744 if ( 0 == $this->mId
) { return; }
2746 $this->mTouched
= self
::newTouchedTimestamp();
2748 $dbw = wfGetDB( DB_MASTER
);
2749 $dbw->update( 'user',
2751 'user_name' => $this->mName
,
2752 'user_password' => $this->mPassword
,
2753 'user_newpassword' => $this->mNewpassword
,
2754 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2755 'user_real_name' => $this->mRealName
,
2756 'user_email' => $this->mEmail
,
2757 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2758 'user_options' => '',
2759 'user_touched' => $dbw->timestamp( $this->mTouched
),
2760 'user_token' => $this->mToken
,
2761 'user_email_token' => $this->mEmailToken
,
2762 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2763 ), array( /* WHERE */
2764 'user_id' => $this->mId
2768 $this->saveOptions();
2770 wfRunHooks( 'UserSaveSettings', array( $this ) );
2771 $this->clearSharedCache();
2772 $this->getUserPage()->invalidateCache();
2776 * If only this user's username is known, and it exists, return the user ID.
2779 function idForName() {
2780 $s = trim( $this->getName() );
2781 if ( $s === '' ) return 0;
2783 $dbr = wfGetDB( DB_SLAVE
);
2784 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2785 if ( $id === false ) {
2792 * Add a user to the database, return the user object
2794 * @param $name String Username to add
2795 * @param $params Array of Strings Non-default parameters to save to the database as user_* fields:
2796 * - password The user's password hash. Password logins will be disabled if this is omitted.
2797 * - newpassword Hash for a temporary password that has been mailed to the user
2798 * - email The user's email address
2799 * - email_authenticated The email authentication timestamp
2800 * - real_name The user's real name
2801 * - options An associative array of non-default options
2802 * - token Random authentication token. Do not set.
2803 * - registration Registration timestamp. Do not set.
2805 * @return User object, or null if the username already exists
2807 static function createNew( $name, $params = array() ) {
2810 if ( isset( $params['options'] ) ) {
2811 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
2812 unset( $params['options'] );
2814 $dbw = wfGetDB( DB_MASTER
);
2815 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2818 'user_id' => $seqVal,
2819 'user_name' => $name,
2820 'user_password' => $user->mPassword
,
2821 'user_newpassword' => $user->mNewpassword
,
2822 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
2823 'user_email' => $user->mEmail
,
2824 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2825 'user_real_name' => $user->mRealName
,
2826 'user_options' => '',
2827 'user_token' => $user->mToken
,
2828 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2829 'user_editcount' => 0,
2831 foreach ( $params as $name => $value ) {
2832 $fields["user_$name"] = $value;
2834 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2835 if ( $dbw->affectedRows() ) {
2836 $newUser = User
::newFromId( $dbw->insertId() );
2844 * Add this existing user object to the database
2846 function addToDatabase() {
2848 $dbw = wfGetDB( DB_MASTER
);
2849 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2850 $dbw->insert( 'user',
2852 'user_id' => $seqVal,
2853 'user_name' => $this->mName
,
2854 'user_password' => $this->mPassword
,
2855 'user_newpassword' => $this->mNewpassword
,
2856 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2857 'user_email' => $this->mEmail
,
2858 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2859 'user_real_name' => $this->mRealName
,
2860 'user_options' => '',
2861 'user_token' => $this->mToken
,
2862 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2863 'user_editcount' => 0,
2866 $this->mId
= $dbw->insertId();
2868 // Clear instance cache other than user table data, which is already accurate
2869 $this->clearInstanceCache();
2871 $this->saveOptions();
2875 * If this (non-anonymous) user is blocked, block any IP address
2876 * they've successfully logged in from.
2878 function spreadBlock() {
2879 wfDebug( __METHOD__
. "()\n" );
2881 if ( $this->mId
== 0 ) {
2885 $userblock = Block
::newFromTarget( $this->getName() );
2886 if ( !$userblock ) {
2890 $userblock->doAutoblock( wfGetIP() );
2894 * Generate a string which will be different for any combination of
2895 * user options which would produce different parser output.
2896 * This will be used as part of the hash key for the parser cache,
2897 * so users with the same options can share the same cached data
2900 * Extensions which require it should install 'PageRenderingHash' hook,
2901 * which will give them a chance to modify this key based on their own
2904 * @deprecated since 1.17 use the ParserOptions object to get the relevant options
2905 * @return String Page rendering hash
2907 function getPageRenderingHash() {
2908 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2910 return $this->mHash
;
2912 wfDeprecated( __METHOD__
);
2914 // stubthreshold is only included below for completeness,
2915 // since it disables the parser cache, its value will always
2916 // be 0 when this function is called by parsercache.
2918 $confstr = $this->getOption( 'math' );
2919 $confstr .= '!' . $this->getStubThreshold();
2920 if ( $wgUseDynamicDates ) { # This is wrong (bug 24714)
2921 $confstr .= '!' . $this->getDatePreference();
2923 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ?
'1' : '' );
2924 $confstr .= '!' . $wgLang->getCode();
2925 $confstr .= '!' . $this->getOption( 'thumbsize' );
2926 // add in language specific options, if any
2927 $extra = $wgContLang->getExtraHashOptions();
2930 // Since the skin could be overloading link(), it should be
2931 // included here but in practice, none of our skins do that.
2933 $confstr .= $wgRenderHashAppend;
2935 // Give a chance for extensions to modify the hash, if they have
2936 // extra options or other effects on the parser cache.
2937 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2939 // Make it a valid memcached key fragment
2940 $confstr = str_replace( ' ', '_', $confstr );
2941 $this->mHash
= $confstr;
2946 * Get whether the user is explicitly blocked from account creation.
2947 * @return Bool|Block
2949 function isBlockedFromCreateAccount() {
2950 $this->getBlockedStatus();
2951 if( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ){
2952 return $this->mBlock
;
2955 # bug 13611: if the IP address the user is trying to create an account from is
2956 # blocked with createaccount disabled, prevent new account creation there even
2957 # when the user is logged in
2958 if( $this->mBlockedFromCreateAccount
=== false ){
2959 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, wfGetIP() );
2961 return $this->mBlockedFromCreateAccount
instanceof Block
&& $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
2962 ?
$this->mBlockedFromCreateAccount
2967 * Get whether the user is blocked from using Special:Emailuser.
2970 function isBlockedFromEmailuser() {
2971 $this->getBlockedStatus();
2972 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
2976 * Get whether the user is allowed to create an account.
2979 function isAllowedToCreateAccount() {
2980 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2984 * Get this user's personal page title.
2986 * @return Title: User's personal page title
2988 function getUserPage() {
2989 return Title
::makeTitle( NS_USER
, $this->getName() );
2993 * Get this user's talk page title.
2995 * @return Title: User's talk page title
2997 function getTalkPage() {
2998 $title = $this->getUserPage();
2999 return $title->getTalkPage();
3003 * Determine whether the user is a newbie. Newbies are either
3004 * anonymous IPs, or the most recently created accounts.
3007 function isNewbie() {
3008 return !$this->isAllowed( 'autoconfirmed' );
3012 * Check to see if the given clear-text password is one of the accepted passwords
3013 * @param $password String: user password.
3014 * @return Boolean: True if the given password is correct, otherwise False.
3016 function checkPassword( $password ) {
3017 global $wgAuth, $wgLegacyEncoding;
3020 // Even though we stop people from creating passwords that
3021 // are shorter than this, doesn't mean people wont be able
3022 // to. Certain authentication plugins do NOT want to save
3023 // domain passwords in a mysql database, so we should
3024 // check this (in case $wgAuth->strict() is false).
3025 if( !$this->isValidPassword( $password ) ) {
3029 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
3031 } elseif( $wgAuth->strict() ) {
3032 /* Auth plugin doesn't allow local authentication */
3034 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
3035 /* Auth plugin doesn't allow local authentication for this user name */
3038 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
3040 } elseif ( $wgLegacyEncoding ) {
3041 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3042 # Check for this with iconv
3043 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3044 if ( $cp1252Password != $password &&
3045 self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) )
3054 * Check if the given clear-text password matches the temporary password
3055 * sent by e-mail for password reset operations.
3056 * @return Boolean: True if matches, false otherwise
3058 function checkTemporaryPassword( $plaintext ) {
3059 global $wgNewPasswordExpiry;
3062 if( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
3063 if ( is_null( $this->mNewpassTime
) ) {
3066 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3067 return ( time() < $expiry );
3074 * Initialize (if necessary) and return a session token value
3075 * which can be used in edit forms to show that the user's
3076 * login credentials aren't being hijacked with a foreign form
3079 * @param $salt String|Array of Strings Optional function-specific data for hashing
3080 * @param $request WebRequest object to use or null to use $wgRequest
3081 * @return String The new edit token
3083 function editToken( $salt = '', $request = null ) {
3084 if ( $request == null ) {
3085 $request = $this->getRequest();
3088 if ( $this->isAnon() ) {
3089 return EDIT_TOKEN_SUFFIX
;
3091 $token = $request->getSessionData( 'wsEditToken' );
3092 if ( $token === null ) {
3093 $token = self
::generateToken();
3094 $request->setSessionData( 'wsEditToken', $token );
3096 if( is_array( $salt ) ) {
3097 $salt = implode( '|', $salt );
3099 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
3104 * Generate a looking random token for various uses.
3106 * @param $salt String Optional salt value
3107 * @return String The new random token
3109 public static function generateToken( $salt = '' ) {
3110 $token = dechex( mt_rand() ) . dechex( mt_rand() );
3111 return md5( $token . $salt );
3115 * Check given value against the token value stored in the session.
3116 * A match should confirm that the form was submitted from the
3117 * user's own login session, not a form submission from a third-party
3120 * @param $val String Input value to compare
3121 * @param $salt String Optional function-specific data for hashing
3122 * @param $request WebRequest object to use or null to use $wgRequest
3123 * @return Boolean: Whether the token matches
3125 function matchEditToken( $val, $salt = '', $request = null ) {
3126 $sessionToken = $this->editToken( $salt, $request );
3127 if ( $val != $sessionToken ) {
3128 wfDebug( "User::matchEditToken: broken session data\n" );
3130 return $val == $sessionToken;
3134 * Check given value against the token value stored in the session,
3135 * ignoring the suffix.
3137 * @param $val String Input value to compare
3138 * @param $salt String Optional function-specific data for hashing
3139 * @param $request WebRequest object to use or null to use $wgRequest
3140 * @return Boolean: Whether the token matches
3142 function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3143 $sessionToken = $this->editToken( $salt, $request );
3144 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3148 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3149 * mail to the user's given address.
3151 * @param $type String: message to send, either "created", "changed" or "set"
3152 * @return Status object
3154 function sendConfirmationMail( $type = 'created' ) {
3156 $expiration = null; // gets passed-by-ref and defined in next line.
3157 $token = $this->confirmationToken( $expiration );
3158 $url = $this->confirmationTokenUrl( $token );
3159 $invalidateURL = $this->invalidationTokenUrl( $token );
3160 $this->saveSettings();
3162 if ( $type == 'created' ||
$type === false ) {
3163 $message = 'confirmemail_body';
3164 } elseif ( $type === true ) {
3165 $message = 'confirmemail_body_changed';
3167 $message = 'confirmemail_body_' . $type;
3170 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
3175 $wgLang->timeanddate( $expiration, false ),
3177 $wgLang->date( $expiration, false ),
3178 $wgLang->time( $expiration, false ) ) );
3182 * Send an e-mail to this user's account. Does not check for
3183 * confirmed status or validity.
3185 * @param $subject String Message subject
3186 * @param $body String Message body
3187 * @param $from String Optional From address; if unspecified, default $wgPasswordSender will be used
3188 * @param $replyto String Reply-To address
3191 function sendMail( $subject, $body, $from = null, $replyto = null ) {
3192 if( is_null( $from ) ) {
3193 global $wgPasswordSender, $wgPasswordSenderName;
3194 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
3196 $sender = new MailAddress( $from );
3199 $to = new MailAddress( $this );
3200 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
3204 * Generate, store, and return a new e-mail confirmation code.
3205 * A hash (unsalted, since it's used as a key) is stored.
3207 * @note Call saveSettings() after calling this function to commit
3208 * this change to the database.
3210 * @param[out] &$expiration \mixed Accepts the expiration time
3211 * @return String New token
3214 function confirmationToken( &$expiration ) {
3215 global $wgUserEmailConfirmationTokenExpiry;
3217 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
3218 $expiration = wfTimestamp( TS_MW
, $expires );
3219 $token = self
::generateToken( $this->mId
. $this->mEmail
. $expires );
3220 $hash = md5( $token );
3222 $this->mEmailToken
= $hash;
3223 $this->mEmailTokenExpires
= $expiration;
3228 * Return a URL the user can use to confirm their email address.
3229 * @param $token String Accepts the email confirmation token
3230 * @return String New token URL
3233 function confirmationTokenUrl( $token ) {
3234 return $this->getTokenUrl( 'ConfirmEmail', $token );
3238 * Return a URL the user can use to invalidate their email address.
3239 * @param $token String Accepts the email confirmation token
3240 * @return String New token URL
3243 function invalidationTokenUrl( $token ) {
3244 return $this->getTokenUrl( 'Invalidateemail', $token );
3248 * Internal function to format the e-mail validation/invalidation URLs.
3249 * This uses $wgArticlePath directly as a quickie hack to use the
3250 * hardcoded English names of the Special: pages, for ASCII safety.
3252 * @note Since these URLs get dropped directly into emails, using the
3253 * short English names avoids insanely long URL-encoded links, which
3254 * also sometimes can get corrupted in some browsers/mailers
3255 * (bug 6957 with Gmail and Internet Explorer).
3257 * @param $page String Special page
3258 * @param $token String Token
3259 * @return String Formatted URL
3261 protected function getTokenUrl( $page, $token ) {
3262 global $wgArticlePath;
3266 "Special:$page/$token",
3271 * Mark the e-mail address confirmed.
3273 * @note Call saveSettings() after calling this function to commit the change.
3275 function confirmEmail() {
3276 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3277 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3282 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3283 * address if it was already confirmed.
3285 * @note Call saveSettings() after calling this function to commit the change.
3287 function invalidateEmail() {
3289 $this->mEmailToken
= null;
3290 $this->mEmailTokenExpires
= null;
3291 $this->setEmailAuthenticationTimestamp( null );
3292 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3297 * Set the e-mail authentication timestamp.
3298 * @param $timestamp String TS_MW timestamp
3300 function setEmailAuthenticationTimestamp( $timestamp ) {
3302 $this->mEmailAuthenticated
= $timestamp;
3303 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
3307 * Is this user allowed to send e-mails within limits of current
3308 * site configuration?
3311 function canSendEmail() {
3312 global $wgEnableEmail, $wgEnableUserEmail;
3313 if( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
3316 $canSend = $this->isEmailConfirmed();
3317 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3322 * Is this user allowed to receive e-mails within limits of current
3323 * site configuration?
3326 function canReceiveEmail() {
3327 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3331 * Is this user's e-mail address valid-looking and confirmed within
3332 * limits of the current site configuration?
3334 * @note If $wgEmailAuthentication is on, this may require the user to have
3335 * confirmed their address by returning a code or using a password
3336 * sent to the address from the wiki.
3340 function isEmailConfirmed() {
3341 global $wgEmailAuthentication;
3344 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3345 if( $this->isAnon() ) {
3348 if( !Sanitizer
::validateEmail( $this->mEmail
) ) {
3351 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
3361 * Check whether there is an outstanding request for e-mail confirmation.
3364 function isEmailConfirmationPending() {
3365 global $wgEmailAuthentication;
3366 return $wgEmailAuthentication &&
3367 !$this->isEmailConfirmed() &&
3368 $this->mEmailToken
&&
3369 $this->mEmailTokenExpires
> wfTimestamp();
3373 * Get the timestamp of account creation.
3375 * @return String|Bool Timestamp of account creation, or false for
3376 * non-existent/anonymous user accounts.
3378 public function getRegistration() {
3379 if ( $this->isAnon() ) {
3383 return $this->mRegistration
;
3387 * Get the timestamp of the first edit
3389 * @return String|Bool Timestamp of first edit, or false for
3390 * non-existent/anonymous user accounts.
3392 public function getFirstEditTimestamp() {
3393 if( $this->getId() == 0 ) {
3394 return false; // anons
3396 $dbr = wfGetDB( DB_SLAVE
);
3397 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3398 array( 'rev_user' => $this->getId() ),
3400 array( 'ORDER BY' => 'rev_timestamp ASC' )
3403 return false; // no edits
3405 return wfTimestamp( TS_MW
, $time );
3409 * Get the permissions associated with a given list of groups
3411 * @param $groups Array of Strings List of internal group names
3412 * @return Array of Strings List of permission key names for given groups combined
3414 static function getGroupPermissions( $groups, $ns = null ) {
3415 global $wgGroupPermissions, $wgRevokePermissions;
3418 // Grant every granted permission first
3419 foreach( $groups as $group ) {
3420 if( isset( $wgGroupPermissions[$group] ) ) {
3421 $rights = array_merge( $rights, self
::extractRights(
3422 $wgGroupPermissions[$group], $ns ) );
3426 // Revoke the revoked permissions
3427 foreach( $groups as $group ) {
3428 if( isset( $wgRevokePermissions[$group] ) ) {
3429 $rights = array_diff( $rights, self
::extractRights(
3430 $wgRevokePermissions[$group], $ns ) );
3433 return array_unique( $rights );
3437 * Helper for User::getGroupPermissions
3438 * @param array $list
3442 private static function extractRights( $list, $ns ) {
3444 foreach( $list as $right => $value ) {
3445 if ( is_array( $value ) ) {
3446 # This is a list of namespaces where the permission applies
3447 if ( !is_null( $ns ) && !empty( $value[$ns] ) ) {
3451 # This is a boolean indicating that the permission applies
3461 * Get all the groups who have a given permission
3463 * @param $role String Role to check
3464 * @return Array of Strings List of internal group names with the given permission
3466 static function getGroupsWithPermission( $role, $ns = null ) {
3467 global $wgGroupPermissions;
3468 $allowedGroups = array();
3469 foreach ( $wgGroupPermissions as $group => $rights ) {
3470 if ( in_array( $role, self
::getGroupPermissions( array( $group ), $ns ), true ) ) {
3471 $allowedGroups[] = $group;
3474 return $allowedGroups;
3478 * Get the localized descriptive name for a group, if it exists
3480 * @param $group String Internal group name
3481 * @return String Localized descriptive group name
3483 static function getGroupName( $group ) {
3484 $msg = wfMessage( "group-$group" );
3485 return $msg->isBlank() ?
$group : $msg->text();
3489 * Get the localized descriptive name for a member of a group, if it exists
3491 * @param $group String Internal group name
3492 * @return String Localized name for group member
3494 static function getGroupMember( $group ) {
3495 $msg = wfMessage( "group-$group-member" );
3496 return $msg->isBlank() ?
$group : $msg->text();
3500 * Return the set of defined explicit groups.
3501 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3502 * are not included, as they are defined automatically, not in the database.
3503 * @return Array of internal group names
3505 static function getAllGroups() {
3506 global $wgGroupPermissions, $wgRevokePermissions;
3508 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3509 self
::getImplicitGroups()
3514 * Get a list of all available permissions.
3515 * @return Array of permission names
3517 static function getAllRights() {
3518 if ( self
::$mAllRights === false ) {
3519 global $wgAvailableRights;
3520 if ( count( $wgAvailableRights ) ) {
3521 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3523 self
::$mAllRights = self
::$mCoreRights;
3525 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3527 return self
::$mAllRights;
3531 * Get a list of implicit groups
3532 * @return Array of Strings Array of internal group names
3534 public static function getImplicitGroups() {
3535 global $wgImplicitGroups;
3536 $groups = $wgImplicitGroups;
3537 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3542 * Get the title of a page describing a particular group
3544 * @param $group String Internal group name
3545 * @return Title|Bool Title of the page if it exists, false otherwise
3547 static function getGroupPage( $group ) {
3548 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
3549 if( $msg->exists() ) {
3550 $title = Title
::newFromText( $msg->text() );
3551 if( is_object( $title ) )
3558 * Create a link to the group in HTML, if available;
3559 * else return the group name.
3561 * @param $group String Internal name of the group
3562 * @param $text String The text of the link
3563 * @return String HTML link to the group
3565 static function makeGroupLinkHTML( $group, $text = '' ) {
3567 $text = self
::getGroupName( $group );
3569 $title = self
::getGroupPage( $group );
3571 return Linker
::link( $title, htmlspecialchars( $text ) );
3578 * Create a link to the group in Wikitext, if available;
3579 * else return the group name.
3581 * @param $group String Internal name of the group
3582 * @param $text String The text of the link
3583 * @return String Wikilink to the group
3585 static function makeGroupLinkWiki( $group, $text = '' ) {
3587 $text = self
::getGroupName( $group );
3589 $title = self
::getGroupPage( $group );
3591 $page = $title->getPrefixedText();
3592 return "[[$page|$text]]";
3599 * Returns an array of the groups that a particular group can add/remove.
3601 * @param $group String: the group to check for whether it can add/remove
3602 * @return Array array( 'add' => array( addablegroups ),
3603 * 'remove' => array( removablegroups ),
3604 * 'add-self' => array( addablegroups to self),
3605 * 'remove-self' => array( removable groups from self) )
3607 static function changeableByGroup( $group ) {
3608 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
3610 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
3611 if( empty( $wgAddGroups[$group] ) ) {
3612 // Don't add anything to $groups
3613 } elseif( $wgAddGroups[$group] === true ) {
3614 // You get everything
3615 $groups['add'] = self
::getAllGroups();
3616 } elseif( is_array( $wgAddGroups[$group] ) ) {
3617 $groups['add'] = $wgAddGroups[$group];
3620 // Same thing for remove
3621 if( empty( $wgRemoveGroups[$group] ) ) {
3622 } elseif( $wgRemoveGroups[$group] === true ) {
3623 $groups['remove'] = self
::getAllGroups();
3624 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
3625 $groups['remove'] = $wgRemoveGroups[$group];
3628 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
3629 if( empty( $wgGroupsAddToSelf['user']) ||
$wgGroupsAddToSelf['user'] !== true ) {
3630 foreach( $wgGroupsAddToSelf as $key => $value ) {
3631 if( is_int( $key ) ) {
3632 $wgGroupsAddToSelf['user'][] = $value;
3637 if( empty( $wgGroupsRemoveFromSelf['user']) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
3638 foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
3639 if( is_int( $key ) ) {
3640 $wgGroupsRemoveFromSelf['user'][] = $value;
3645 // Now figure out what groups the user can add to him/herself
3646 if( empty( $wgGroupsAddToSelf[$group] ) ) {
3647 } elseif( $wgGroupsAddToSelf[$group] === true ) {
3648 // No idea WHY this would be used, but it's there
3649 $groups['add-self'] = User
::getAllGroups();
3650 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
3651 $groups['add-self'] = $wgGroupsAddToSelf[$group];
3654 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
3655 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
3656 $groups['remove-self'] = User
::getAllGroups();
3657 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
3658 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
3665 * Returns an array of groups that this user can add and remove
3666 * @return Array array( 'add' => array( addablegroups ),
3667 * 'remove' => array( removablegroups ),
3668 * 'add-self' => array( addablegroups to self),
3669 * 'remove-self' => array( removable groups from self) )
3671 function changeableGroups() {
3672 if( $this->isAllowed( 'userrights' ) ) {
3673 // This group gives the right to modify everything (reverse-
3674 // compatibility with old "userrights lets you change
3676 // Using array_merge to make the groups reindexed
3677 $all = array_merge( User
::getAllGroups() );
3681 'add-self' => array(),
3682 'remove-self' => array()
3686 // Okay, it's not so simple, we will have to go through the arrays
3689 'remove' => array(),
3690 'add-self' => array(),
3691 'remove-self' => array()
3693 $addergroups = $this->getEffectiveGroups();
3695 foreach( $addergroups as $addergroup ) {
3696 $groups = array_merge_recursive(
3697 $groups, $this->changeableByGroup( $addergroup )
3699 $groups['add'] = array_unique( $groups['add'] );
3700 $groups['remove'] = array_unique( $groups['remove'] );
3701 $groups['add-self'] = array_unique( $groups['add-self'] );
3702 $groups['remove-self'] = array_unique( $groups['remove-self'] );
3708 * Increment the user's edit-count field.
3709 * Will have no effect for anonymous users.
3711 function incEditCount() {
3712 if( !$this->isAnon() ) {
3713 $dbw = wfGetDB( DB_MASTER
);
3714 $dbw->update( 'user',
3715 array( 'user_editcount=user_editcount+1' ),
3716 array( 'user_id' => $this->getId() ),
3719 // Lazy initialization check...
3720 if( $dbw->affectedRows() == 0 ) {
3721 // Pull from a slave to be less cruel to servers
3722 // Accuracy isn't the point anyway here
3723 $dbr = wfGetDB( DB_SLAVE
);
3724 $count = $dbr->selectField( 'revision',
3726 array( 'rev_user' => $this->getId() ),
3729 // Now here's a goddamn hack...
3730 if( $dbr !== $dbw ) {
3731 // If we actually have a slave server, the count is
3732 // at least one behind because the current transaction
3733 // has not been committed and replicated.
3736 // But if DB_SLAVE is selecting the master, then the
3737 // count we just read includes the revision that was
3738 // just added in the working transaction.
3741 $dbw->update( 'user',
3742 array( 'user_editcount' => $count ),
3743 array( 'user_id' => $this->getId() ),
3747 // edit count in user cache too
3748 $this->invalidateCache();
3752 * Get the description of a given right
3754 * @param $right String Right to query
3755 * @return String Localized description of the right
3757 static function getRightDescription( $right ) {
3758 $key = "right-$right";
3759 $msg = wfMessage( $key );
3760 return $msg->isBlank() ?
$right : $msg->text();
3764 * Make an old-style password hash
3766 * @param $password String Plain-text password
3767 * @param $userId String User ID
3768 * @return String Password hash
3770 static function oldCrypt( $password, $userId ) {
3771 global $wgPasswordSalt;
3772 if ( $wgPasswordSalt ) {
3773 return md5( $userId . '-' . md5( $password ) );
3775 return md5( $password );
3780 * Make a new-style password hash
3782 * @param $password String Plain-text password
3783 * @param $salt String Optional salt, may be random or the user ID.
3784 * If unspecified or false, will generate one automatically
3785 * @return String Password hash
3787 static function crypt( $password, $salt = false ) {
3788 global $wgPasswordSalt;
3791 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3795 if( $wgPasswordSalt ) {
3796 if ( $salt === false ) {
3797 $salt = substr( wfGenerateToken(), 0, 8 );
3799 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3801 return ':A:' . md5( $password );
3806 * Compare a password hash with a plain-text password. Requires the user
3807 * ID if there's a chance that the hash is an old-style hash.
3809 * @param $hash String Password hash
3810 * @param $password String Plain-text password to compare
3811 * @param $userId String User ID for old-style password salt
3814 static function comparePasswords( $hash, $password, $userId = false ) {
3815 $type = substr( $hash, 0, 3 );
3818 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3822 if ( $type == ':A:' ) {
3824 return md5( $password ) === substr( $hash, 3 );
3825 } elseif ( $type == ':B:' ) {
3827 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3828 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3831 return self
::oldCrypt( $password, $userId ) === $hash;
3836 * Add a newuser log entry for this user
3838 * @param $byEmail Boolean: account made by email?
3839 * @param $reason String: user supplied reason
3843 public function addNewUserLogEntry( $byEmail = false, $reason = '' ) {
3844 global $wgUser, $wgContLang, $wgNewUserLog;
3845 if( empty( $wgNewUserLog ) ) {
3846 return true; // disabled
3849 if( $this->getName() == $wgUser->getName() ) {
3852 $action = 'create2';
3854 if ( $reason === '' ) {
3855 $reason = wfMsgForContent( 'newuserlog-byemail' );
3857 $reason = $wgContLang->commaList( array(
3858 $reason, wfMsgForContent( 'newuserlog-byemail' ) ) );
3862 $log = new LogPage( 'newusers' );
3865 $this->getUserPage(),
3867 array( $this->getId() )
3873 * Add an autocreate newuser log entry for this user
3874 * Used by things like CentralAuth and perhaps other authplugins.
3878 public function addNewUserLogEntryAutoCreate() {
3879 global $wgNewUserLog;
3880 if( !$wgNewUserLog ) {
3881 return true; // disabled
3883 $log = new LogPage( 'newusers', false );
3884 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3888 protected function loadOptions() {
3890 if ( $this->mOptionsLoaded ||
!$this->getId() )
3893 $this->mOptions
= self
::getDefaultOptions();
3895 // Maybe load from the object
3896 if ( !is_null( $this->mOptionOverrides
) ) {
3897 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
3898 foreach( $this->mOptionOverrides
as $key => $value ) {
3899 $this->mOptions
[$key] = $value;
3902 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
3903 // Load from database
3904 $dbr = wfGetDB( DB_SLAVE
);
3906 $res = $dbr->select(
3909 array( 'up_user' => $this->getId() ),
3913 foreach ( $res as $row ) {
3914 $this->mOptionOverrides
[$row->up_property
] = $row->up_value
;
3915 $this->mOptions
[$row->up_property
] = $row->up_value
;
3919 $this->mOptionsLoaded
= true;
3921 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
3924 protected function saveOptions() {
3925 global $wgAllowPrefChange;
3927 $extuser = ExternalUser
::newFromUser( $this );
3929 $this->loadOptions();
3930 $dbw = wfGetDB( DB_MASTER
);
3932 $insert_rows = array();
3934 $saveOptions = $this->mOptions
;
3936 // Allow hooks to abort, for instance to save to a global profile.
3937 // Reset options to default state before saving.
3938 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) )
3941 foreach( $saveOptions as $key => $value ) {
3942 # Don't bother storing default values
3943 if ( ( is_null( self
::getDefaultOption( $key ) ) &&
3944 !( $value === false ||
is_null($value) ) ) ||
3945 $value != self
::getDefaultOption( $key ) ) {
3946 $insert_rows[] = array(
3947 'up_user' => $this->getId(),
3948 'up_property' => $key,
3949 'up_value' => $value,
3952 if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
3953 switch ( $wgAllowPrefChange[$key] ) {
3959 $extuser->setPref( $key, $value );
3965 $dbw->delete( 'user_properties', array( 'up_user' => $this->getId() ), __METHOD__
);
3966 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
);
3971 * Provide an array of HTML5 attributes to put on an input element
3972 * intended for the user to enter a new password. This may include
3973 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
3975 * Do *not* use this when asking the user to enter his current password!
3976 * Regardless of configuration, users may have invalid passwords for whatever
3977 * reason (e.g., they were set before requirements were tightened up).
3978 * Only use it when asking for a new password, like on account creation or
3981 * Obviously, you still need to do server-side checking.
3983 * NOTE: A combination of bugs in various browsers means that this function
3984 * actually just returns array() unconditionally at the moment. May as
3985 * well keep it around for when the browser bugs get fixed, though.
3987 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
3989 * @return array Array of HTML attributes suitable for feeding to
3990 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
3991 * That will potentially output invalid XHTML 1.0 Transitional, and will
3992 * get confused by the boolean attribute syntax used.)
3994 public static function passwordChangeInputAttribs() {
3995 global $wgMinimalPasswordLength;
3997 if ( $wgMinimalPasswordLength == 0 ) {
4001 # Note that the pattern requirement will always be satisfied if the
4002 # input is empty, so we need required in all cases.
4004 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4005 # if e-mail confirmation is being used. Since HTML5 input validation
4006 # is b0rked anyway in some browsers, just return nothing. When it's
4007 # re-enabled, fix this code to not output required for e-mail
4009 #$ret = array( 'required' );
4012 # We can't actually do this right now, because Opera 9.6 will print out
4013 # the entered password visibly in its error message! When other
4014 # browsers add support for this attribute, or Opera fixes its support,
4015 # we can add support with a version check to avoid doing this on Opera
4016 # versions where it will be a problem. Reported to Opera as
4017 # DSK-262266, but they don't have a public bug tracker for us to follow.
4019 if ( $wgMinimalPasswordLength > 1 ) {
4020 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4021 $ret['title'] = wfMsgExt( 'passwordtooshort', 'parsemag',
4022 $wgMinimalPasswordLength );