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,
176 * Bool Whether the cache variables have been loaded.
182 * Array with already loaded items or true if all items have been loaded.
184 private $mLoadedItems = array();
188 * String Initialization data source if mLoadedItems!==true. May be one of:
189 * - 'defaults' anonymous user initialised from class defaults
190 * - 'name' initialise from mName
191 * - 'id' initialise from mId
192 * - 'session' log in from cookies or session if possible
194 * Use the User::newFrom*() family of functions to set this.
199 * Lazy-initialized variables, invalidated with clearInstanceCache
201 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mRights,
202 $mBlockreason, $mEffectiveGroups, $mFormerGroups, $mBlockedGlobally,
203 $mLocked, $mHideName, $mOptions;
214 private $mBlockedFromCreateAccount = false;
216 static $idCacheByName = array();
219 * Lightweight constructor for an anonymous user.
220 * Use the User::newFrom* factory functions for other kinds of users.
224 * @see newFromConfirmationCode()
225 * @see newFromSession()
228 function __construct() {
229 $this->clearInstanceCache( 'defaults' );
232 function __toString(){
233 return $this->getName();
237 * Load the user table data for this object from the source given by mFrom.
239 public function load() {
240 if ( $this->mLoadedItems
=== true ) {
243 wfProfileIn( __METHOD__
);
245 # Set it now to avoid infinite recursion in accessors
246 $this->mLoadedItems
= true;
248 switch ( $this->mFrom
) {
250 $this->loadDefaults();
253 $this->mId
= self
::idFromName( $this->mName
);
255 # Nonexistent user placeholder object
256 $this->loadDefaults( $this->mName
);
265 $this->loadFromSession();
266 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
269 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
271 wfProfileOut( __METHOD__
);
275 * Load user table data, given mId has already been set.
276 * @return Bool false if the ID does not exist, true otherwise
278 private 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 public 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 );
332 /** @name newFrom*() static factory methods */
336 * Static factory method for creation from username.
338 * This is slightly less efficient than newFromId(), so use newFromId() if
339 * you have both an ID and a name handy.
341 * @param $name String Username, validated by Title::newFromText()
342 * @param $validate String|Bool Validate username. Takes the same parameters as
343 * User::getCanonicalName(), except that true is accepted as an alias
344 * for 'valid', for BC.
346 * @return User object, or false if the username is invalid
347 * (e.g. if it contains illegal characters or is an IP address). If the
348 * username is not present in the database, the result will be a user object
349 * with a name, zero user ID and default settings.
351 public static function newFromName( $name, $validate = 'valid' ) {
352 if ( $validate === true ) {
355 $name = self
::getCanonicalName( $name, $validate );
356 if ( $name === false ) {
359 # Create unloaded user object
363 $u->setItemLoaded( 'name' );
369 * Static factory method for creation from a given user ID.
371 * @param $id Int Valid user ID
372 * @return User The corresponding User object
374 public static function newFromId( $id ) {
378 $u->setItemLoaded( 'id' );
383 * Factory method to fetch whichever user has a given email confirmation code.
384 * This code is generated when an account is created or its e-mail address
387 * If the code is invalid or has expired, returns NULL.
389 * @param $code String Confirmation code
392 public static function newFromConfirmationCode( $code ) {
393 $dbr = wfGetDB( DB_SLAVE
);
394 $id = $dbr->selectField( 'user', 'user_id', array(
395 'user_email_token' => md5( $code ),
396 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
398 if( $id !== false ) {
399 return User
::newFromId( $id );
406 * Create a new user object using data from session or cookies. If the
407 * login credentials are invalid, the result is an anonymous user.
409 * @param $request WebRequest object to use; $wgRequest will be used if
413 public static function newFromSession( WebRequest
$request = null ) {
415 $user->mFrom
= 'session';
416 $user->mRequest
= $request;
421 * Create a new user object from a user row.
422 * The row should have the following fields from the user table in it:
423 * - either user_name or user_id to load further data if needed (or both)
425 * - all other fields (email, password, etc.)
426 * It is useless to provide the remaining fields if either user_id,
427 * user_name and user_real_name are not provided because the whole row
428 * will be loaded once more from the database when accessing them.
430 * @param $row Array A row from the user table
433 public static function newFromRow( $row ) {
435 $user->loadFromRow( $row );
443 * Get the username corresponding to a given user ID
444 * @param $id Int User ID
445 * @return String The corresponding username
447 static function whoIs( $id ) {
448 $dbr = wfGetDB( DB_SLAVE
);
449 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), __METHOD__
);
453 * Get the real name of a user given their user ID
455 * @param $id Int User ID
456 * @return String The corresponding user's real name
458 public static function whoIsReal( $id ) {
459 $dbr = wfGetDB( DB_SLAVE
);
460 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
464 * Get database id given a user name
465 * @param $name String Username
466 * @return Int|Null The corresponding user's ID, or null if user is nonexistent
468 public static function idFromName( $name ) {
469 $nt = Title
::makeTitleSafe( NS_USER
, $name );
470 if( is_null( $nt ) ) {
475 if ( isset( self
::$idCacheByName[$name] ) ) {
476 return self
::$idCacheByName[$name];
479 $dbr = wfGetDB( DB_SLAVE
);
480 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
482 if ( $s === false ) {
485 $result = $s->user_id
;
488 self
::$idCacheByName[$name] = $result;
490 if ( count( self
::$idCacheByName ) > 1000 ) {
491 self
::$idCacheByName = array();
498 * Reset the cache used in idFromName(). For use in tests.
500 public static function resetIdByNameCache() {
501 self
::$idCacheByName = array();
505 * Does the string match an anonymous IPv4 address?
507 * This function exists for username validation, in order to reject
508 * usernames which are similar in form to IP addresses. Strings such
509 * as 300.300.300.300 will return true because it looks like an IP
510 * address, despite not being strictly valid.
512 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
513 * address because the usemod software would "cloak" anonymous IP
514 * addresses like this, if we allowed accounts like this to be created
515 * new users could get the old edits of these anonymous users.
517 * @param $name String to match
520 public static function isIP( $name ) {
521 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP
::isIPv6($name);
525 * Is the input a valid username?
527 * Checks if the input is a valid username, we don't want an empty string,
528 * an IP address, anything that containins slashes (would mess up subpages),
529 * is longer than the maximum allowed username size or doesn't begin with
532 * @param $name String to match
535 public static function isValidUserName( $name ) {
536 global $wgContLang, $wgMaxNameChars;
539 || User
::isIP( $name )
540 ||
strpos( $name, '/' ) !== false
541 ||
strlen( $name ) > $wgMaxNameChars
542 ||
$name != $wgContLang->ucfirst( $name ) ) {
543 wfDebugLog( 'username', __METHOD__
.
544 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
548 // Ensure that the name can't be misresolved as a different title,
549 // such as with extra namespace keys at the start.
550 $parsed = Title
::newFromText( $name );
551 if( is_null( $parsed )
552 ||
$parsed->getNamespace()
553 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
554 wfDebugLog( 'username', __METHOD__
.
555 ": '$name' invalid due to ambiguous prefixes" );
559 // Check an additional blacklist of troublemaker characters.
560 // Should these be merged into the title char list?
561 $unicodeBlacklist = '/[' .
562 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
563 '\x{00a0}' . # non-breaking space
564 '\x{2000}-\x{200f}' . # various whitespace
565 '\x{2028}-\x{202f}' . # breaks and control chars
566 '\x{3000}' . # ideographic space
567 '\x{e000}-\x{f8ff}' . # private use
569 if( preg_match( $unicodeBlacklist, $name ) ) {
570 wfDebugLog( 'username', __METHOD__
.
571 ": '$name' invalid due to blacklisted characters" );
579 * Usernames which fail to pass this function will be blocked
580 * from user login and new account registrations, but may be used
581 * internally by batch processes.
583 * If an account already exists in this form, login will be blocked
584 * by a failure to pass this function.
586 * @param $name String to match
589 public static function isUsableName( $name ) {
590 global $wgReservedUsernames;
591 // Must be a valid username, obviously ;)
592 if ( !self
::isValidUserName( $name ) ) {
596 static $reservedUsernames = false;
597 if ( !$reservedUsernames ) {
598 $reservedUsernames = $wgReservedUsernames;
599 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
602 // Certain names may be reserved for batch processes.
603 foreach ( $reservedUsernames as $reserved ) {
604 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
605 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
607 if ( $reserved == $name ) {
615 * Usernames which fail to pass this function will be blocked
616 * from new account registrations, but may be used internally
617 * either by batch processes or by user accounts which have
618 * already been created.
620 * Additional blacklisting may be added here rather than in
621 * isValidUserName() to avoid disrupting existing accounts.
623 * @param $name String to match
626 public static function isCreatableName( $name ) {
627 global $wgInvalidUsernameCharacters;
629 // Ensure that the username isn't longer than 235 bytes, so that
630 // (at least for the builtin skins) user javascript and css files
631 // will work. (bug 23080)
632 if( strlen( $name ) > 235 ) {
633 wfDebugLog( 'username', __METHOD__
.
634 ": '$name' invalid due to length" );
638 // Preg yells if you try to give it an empty string
639 if( $wgInvalidUsernameCharacters !== '' ) {
640 if( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
641 wfDebugLog( 'username', __METHOD__
.
642 ": '$name' invalid due to wgInvalidUsernameCharacters" );
647 return self
::isUsableName( $name );
651 * Is the input a valid password for this user?
653 * @param $password String Desired password
656 public function isValidPassword( $password ) {
657 //simple boolean wrapper for getPasswordValidity
658 return $this->getPasswordValidity( $password ) === true;
662 * Given unvalidated password input, return error message on failure.
664 * @param $password String Desired password
665 * @return mixed: true on success, string or array of error message on failure
667 public function getPasswordValidity( $password ) {
668 global $wgMinimalPasswordLength, $wgContLang;
670 static $blockedLogins = array(
671 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
672 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
675 $result = false; //init $result to false for the internal checks
677 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
680 if ( $result === false ) {
681 if( strlen( $password ) < $wgMinimalPasswordLength ) {
682 return 'passwordtooshort';
683 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
684 return 'password-name-match';
685 } elseif ( isset( $blockedLogins[ $this->getName() ] ) && $password == $blockedLogins[ $this->getName() ] ) {
686 return 'password-login-forbidden';
688 //it seems weird returning true here, but this is because of the
689 //initialization of $result to false above. If the hook is never run or it
690 //doesn't modify $result, then we will likely get down into this if with
694 } elseif( $result === true ) {
697 return $result; //the isValidPassword hook set a string $result and returned true
702 * Does a string look like an e-mail address?
704 * This validates an email address using an HTML5 specification found at:
705 * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
706 * Which as of 2011-01-24 says:
708 * A valid e-mail address is a string that matches the ABNF production
709 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
710 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
713 * This function is an implementation of the specification as requested in
716 * Client-side forms will use the same standard validation rules via JS or
717 * HTML 5 validation; additional restrictions can be enforced server-side
718 * by extensions via the 'isValidEmailAddr' hook.
720 * Note that this validation doesn't 100% match RFC 2822, but is believed
721 * to be liberal enough for wide use. Some invalid addresses will still
722 * pass validation here.
724 * @param $addr String E-mail address
726 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
728 public static function isValidEmailAddr( $addr ) {
729 return Sanitizer
::validateEmail( $addr );
733 * Given unvalidated user input, return a canonical username, or false if
734 * the username is invalid.
735 * @param $name String User input
736 * @param $validate String|Bool type of validation to use:
737 * - false No validation
738 * - 'valid' Valid for batch processes
739 * - 'usable' Valid for batch processes and login
740 * - 'creatable' Valid for batch processes, login and account creation
742 public static function getCanonicalName( $name, $validate = 'valid' ) {
743 # Force usernames to capital
745 $name = $wgContLang->ucfirst( $name );
747 # Reject names containing '#'; these will be cleaned up
748 # with title normalisation, but then it's too late to
750 if( strpos( $name, '#' ) !== false )
753 # Clean up name according to title rules
754 $t = ( $validate === 'valid' ) ?
755 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
756 # Check for invalid titles
757 if( is_null( $t ) ) {
761 # Reject various classes of invalid names
763 $name = $wgAuth->getCanonicalName( $t->getText() );
765 switch ( $validate ) {
769 if ( !User
::isValidUserName( $name ) ) {
774 if ( !User
::isUsableName( $name ) ) {
779 if ( !User
::isCreatableName( $name ) ) {
784 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
790 * Count the number of edits of a user
791 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
793 * @param $uid Int User ID to check
794 * @return Int the user's edit count
796 public static function edits( $uid ) {
797 wfProfileIn( __METHOD__
);
798 $dbr = wfGetDB( DB_SLAVE
);
799 // check if the user_editcount field has been initialized
800 $field = $dbr->selectField(
801 'user', 'user_editcount',
802 array( 'user_id' => $uid ),
806 if( $field === null ) { // it has not been initialized. do so.
807 $dbw = wfGetDB( DB_MASTER
);
808 $count = $dbr->selectField(
809 'revision', 'count(*)',
810 array( 'rev_user' => $uid ),
815 array( 'user_editcount' => $count ),
816 array( 'user_id' => $uid ),
822 wfProfileOut( __METHOD__
);
827 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
828 * @todo hash random numbers to improve security, like generateToken()
830 * @return String new random password
832 public static function randomPassword() {
833 global $wgMinimalPasswordLength;
834 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
835 $l = strlen( $pwchars ) - 1;
837 $pwlength = max( 7, $wgMinimalPasswordLength );
838 $digit = mt_rand( 0, $pwlength - 1 );
840 for ( $i = 0; $i < $pwlength; $i++
) {
841 $np .= $i == $digit ?
chr( mt_rand( 48, 57 ) ) : $pwchars[ mt_rand( 0, $l ) ];
847 * Set cached properties to default.
849 * @note This no longer clears uncached lazy-initialised properties;
850 * the constructor does that instead.
852 private function loadDefaults( $name = false ) {
853 wfProfileIn( __METHOD__
);
856 $this->mName
= $name;
857 $this->mRealName
= '';
858 $this->mPassword
= $this->mNewpassword
= '';
859 $this->mNewpassTime
= null;
861 $this->mOptionOverrides
= null;
862 $this->mOptionsLoaded
= false;
864 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
865 if( $loggedOut !== null ) {
866 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
868 $this->mTouched
= '0'; # Allow any pages to be cached
871 $this->setToken(); # Random
872 $this->mEmailAuthenticated
= null;
873 $this->mEmailToken
= '';
874 $this->mEmailTokenExpires
= null;
875 $this->mRegistration
= wfTimestamp( TS_MW
);
876 $this->mGroups
= array();
878 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
880 wfProfileOut( __METHOD__
);
884 * Return whether an item has been loaded.
886 * @param $item String: item to check. Current possibilities:
890 * @param $all String: 'all' to check if the whole object has been loaded
891 * or any other string to check if only the item is available (e.g.
895 public function isItemLoaded( $item, $all = 'all' ) {
896 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
897 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
901 * Set that an item has been loaded
903 * @param $item String
905 private function setItemLoaded( $item ) {
906 if ( is_array( $this->mLoadedItems
) ) {
907 $this->mLoadedItems
[$item] = true;
912 * Load user data from the session or login cookie. If there are no valid
913 * credentials, initialises the user as an anonymous user.
914 * @return Bool True if the user is logged in, false otherwise.
916 private function loadFromSession() {
917 global $wgExternalAuthType, $wgAutocreatePolicy;
920 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
921 if ( $result !== null ) {
925 if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
926 $extUser = ExternalUser
::newFromCookie();
928 # TODO: Automatically create the user here (or probably a bit
929 # lower down, in fact)
933 $request = $this->getRequest();
935 $cookieId = $request->getCookie( 'UserID' );
936 $sessId = $request->getSessionData( 'wsUserID' );
938 if ( $cookieId !== null ) {
939 $sId = intval( $cookieId );
940 if( $sessId !== null && $cookieId != $sessId ) {
941 $this->loadDefaults(); // Possible collision!
942 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
943 cookie user ID ($sId) don't match!" );
946 $request->setSessionData( 'wsUserID', $sId );
947 } elseif ( $sessId !== null && $sessId != 0 ) {
950 $this->loadDefaults();
954 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
955 $sName = $request->getSessionData( 'wsUserName' );
956 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
957 $sName = $request->getCookie( 'UserName' );
958 $request->setSessionData( 'wsUserName', $sName );
960 $this->loadDefaults();
964 $proposedUser = User
::newFromId( $sId );
965 if ( !$proposedUser->isLoggedIn() ) {
967 $this->loadDefaults();
971 global $wgBlockDisablesLogin;
972 if( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
973 # User blocked and we've disabled blocked user logins
974 $this->loadDefaults();
978 if ( $request->getSessionData( 'wsToken' ) !== null ) {
979 $passwordCorrect = $proposedUser->getToken() === $request->getSessionData( 'wsToken' );
981 } elseif ( $request->getCookie( 'Token' ) !== null ) {
982 $passwordCorrect = $proposedUser->getToken() === $request->getCookie( 'Token' );
985 # No session or persistent login cookie
986 $this->loadDefaults();
990 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
991 $this->loadFromUserObject( $proposedUser );
992 $request->setSessionData( 'wsToken', $this->mToken
);
993 wfDebug( "User: logged in from $from\n" );
996 # Invalid credentials
997 wfDebug( "User: can't log in from $from, invalid credentials\n" );
998 $this->loadDefaults();
1004 * Load user and user_group data from the database.
1005 * $this->mId must be set, this is how the user is identified.
1007 * @return Bool True if the user exists, false if the user is anonymous
1009 private function loadFromDatabase() {
1011 $this->mId
= intval( $this->mId
);
1013 /** Anonymous user */
1015 $this->loadDefaults();
1019 $dbr = wfGetDB( DB_MASTER
);
1020 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
1022 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1024 if ( $s !== false ) {
1025 # Initialise user table data
1026 $this->loadFromRow( $s );
1027 $this->mGroups
= null; // deferred
1028 $this->getEditCount(); // revalidation for nulls
1033 $this->loadDefaults();
1039 * Initialize this object from a row from the user table.
1041 * @param $row Array Row from the user table to load.
1043 public function loadFromRow( $row ) {
1046 if ( isset( $row->user_name
) ) {
1047 $this->mName
= $row->user_name
;
1048 $this->mFrom
= 'name';
1049 $this->setItemLoaded( 'name' );
1054 if ( isset( $row->user_real_name
) ) {
1055 $this->mRealName
= $row->user_real_name
;
1056 $this->setItemLoaded( 'realname' );
1061 if ( isset( $row->user_id
) ) {
1062 $this->mId
= intval( $row->user_id
);
1063 $this->mFrom
= 'id';
1064 $this->setItemLoaded( 'id' );
1069 if ( isset( $row->user_password
) ) {
1070 $this->mPassword
= $row->user_password
;
1071 $this->mNewpassword
= $row->user_newpassword
;
1072 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1073 $this->mEmail
= $row->user_email
;
1074 $this->decodeOptions( $row->user_options
);
1075 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
1076 $this->mToken
= $row->user_token
;
1077 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1078 $this->mEmailToken
= $row->user_email_token
;
1079 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1080 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1081 $this->mEditCount
= $row->user_editcount
;
1087 $this->mLoadedItems
= true;
1092 * Load the data for this user object from another user object.
1096 protected function loadFromUserObject( $user ) {
1098 $user->loadGroups();
1099 $user->loadOptions();
1100 foreach ( self
::$mCacheVars as $var ) {
1101 $this->$var = $user->$var;
1106 * Load the groups from the database if they aren't already loaded.
1108 private function loadGroups() {
1109 if ( is_null( $this->mGroups
) ) {
1110 $dbr = wfGetDB( DB_MASTER
);
1111 $res = $dbr->select( 'user_groups',
1112 array( 'ug_group' ),
1113 array( 'ug_user' => $this->mId
),
1115 $this->mGroups
= array();
1116 foreach ( $res as $row ) {
1117 $this->mGroups
[] = $row->ug_group
;
1123 * Add the user to the group if he/she meets given criteria.
1125 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1126 * possible to remove manually via Special:UserRights. In such case it
1127 * will not be re-added automatically. The user will also not lose the
1128 * group if they no longer meet the criteria.
1130 * @param $event String key in $wgAutopromoteOnce (each one has groups/criteria)
1132 * @return array Array of groups the user has been promoted to.
1134 * @see $wgAutopromoteOnce
1136 public function addAutopromoteOnceGroups( $event ) {
1137 global $wgAutopromoteOnceLogInRC;
1139 $toPromote = array();
1140 if ( $this->getId() ) {
1141 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1142 if ( count( $toPromote ) ) {
1143 $oldGroups = $this->getGroups(); // previous groups
1144 foreach ( $toPromote as $group ) {
1145 $this->addGroup( $group );
1147 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1149 $log = new LogPage( 'rights', $wgAutopromoteOnceLogInRC /* in RC? */ );
1150 $log->addEntry( 'autopromote',
1151 $this->getUserPage(),
1153 array( implode( ', ', $oldGroups ), implode( ', ', $newGroups ) )
1161 * Clear various cached data stored in this object.
1162 * @param $reloadFrom String Reload user and user_groups table data from a
1163 * given source. May be "name", "id", "defaults", "session", or false for
1166 public function clearInstanceCache( $reloadFrom = false ) {
1167 $this->mNewtalk
= -1;
1168 $this->mDatePreference
= null;
1169 $this->mBlockedby
= -1; # Unset
1170 $this->mHash
= false;
1171 $this->mRights
= null;
1172 $this->mEffectiveGroups
= null;
1173 $this->mOptions
= null;
1175 if ( $reloadFrom ) {
1176 $this->mLoadedItems
= array();
1177 $this->mFrom
= $reloadFrom;
1182 * Combine the language default options with any site-specific options
1183 * and add the default language variants.
1185 * @return Array of String options
1187 public static function getDefaultOptions() {
1188 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1190 $defOpt = $wgDefaultUserOptions;
1191 # default language setting
1192 $variant = $wgContLang->getDefaultVariant();
1193 $defOpt['variant'] = $variant;
1194 $defOpt['language'] = $variant;
1195 foreach( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1196 $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1198 $defOpt['skin'] = $wgDefaultSkin;
1204 * Get a given default option value.
1206 * @param $opt String Name of option to retrieve
1207 * @return String Default option value
1209 public static function getDefaultOption( $opt ) {
1210 $defOpts = self
::getDefaultOptions();
1211 if( isset( $defOpts[$opt] ) ) {
1212 return $defOpts[$opt];
1220 * Get blocking information
1221 * @param $bFromSlave Bool Whether to check the slave database first. To
1222 * improve performance, non-critical checks are done
1223 * against slaves. Check when actually saving should be
1224 * done against master.
1226 private function getBlockedStatus( $bFromSlave = true ) {
1227 global $wgProxyWhitelist, $wgUser;
1229 if ( -1 != $this->mBlockedby
) {
1233 wfProfileIn( __METHOD__
);
1234 wfDebug( __METHOD__
.": checking...\n" );
1236 // Initialize data...
1237 // Otherwise something ends up stomping on $this->mBlockedby when
1238 // things get lazy-loaded later, causing false positive block hits
1239 // due to -1 !== 0. Probably session-related... Nothing should be
1240 // overwriting mBlockedby, surely?
1243 $this->mBlockedby
= 0;
1244 $this->mHideName
= 0;
1245 $this->mAllowUsertalk
= 0;
1247 # We only need to worry about passing the IP address to the Block generator if the
1248 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1249 # know which IP address they're actually coming from
1250 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1257 $this->mBlock
= Block
::newFromTarget( $this->getName(), $ip, !$bFromSlave );
1258 if ( $this->mBlock
instanceof Block
) {
1259 wfDebug( __METHOD__
. ": Found block.\n" );
1260 $this->mBlockedby
= $this->mBlock
->getByName();
1261 $this->mBlockreason
= $this->mBlock
->mReason
;
1262 $this->mHideName
= $this->mBlock
->mHideName
;
1263 $this->mAllowUsertalk
= !$this->mBlock
->prevents( 'editownusertalk' );
1264 if ( $this->isLoggedIn() && $wgUser->getID() == $this->getID() ) {
1265 $this->spreadBlock();
1270 if ( $ip !== null && !$this->isAllowed( 'proxyunbannable' ) && !in_array( $ip, $wgProxyWhitelist ) ) {
1272 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1273 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1274 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1278 if ( !$this->mBlockedby
&& !$this->getID() ) {
1279 if ( $this->isDnsBlacklisted( $ip ) ) {
1280 $this->mBlockedby
= wfMsg( 'sorbs' );
1281 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1287 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1289 wfProfileOut( __METHOD__
);
1293 * Whether the given IP is in a DNS blacklist.
1295 * @param $ip String IP to check
1296 * @param $checkWhitelist Bool: whether to check the whitelist first
1297 * @return Bool True if blacklisted.
1299 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1300 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1301 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1303 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
1306 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
1309 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1310 return $this->inDnsBlacklist( $ip, $urls );
1314 * Whether the given IP is in a given DNS blacklist.
1316 * @param $ip String IP to check
1317 * @param $bases String|Array of Strings: URL of the DNS blacklist
1318 * @return Bool True if blacklisted.
1320 public function inDnsBlacklist( $ip, $bases ) {
1321 wfProfileIn( __METHOD__
);
1324 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1325 if( IP
::isIPv4( $ip ) ) {
1326 # Reverse IP, bug 21255
1327 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1329 foreach( (array)$bases as $base ) {
1331 $host = "$ipReversed.$base";
1334 $ipList = gethostbynamel( $host );
1337 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1341 wfDebug( "Requested $host, not found in $base.\n" );
1346 wfProfileOut( __METHOD__
);
1351 * Check if an IP address is in the local proxy list
1354 public static function isLocallyBlockedProxy( $ip ) {
1355 global $wgProxyList;
1357 if ( !$wgProxyList ) {
1360 wfProfileIn( __METHOD__
);
1362 if ( !is_array( $wgProxyList ) ) {
1363 # Load from the specified file
1364 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1367 if ( !is_array( $wgProxyList ) ) {
1369 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1371 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1372 # Old-style flipped proxy list
1377 wfProfileOut( __METHOD__
);
1382 * Is this user subject to rate limiting?
1384 * @return Bool True if rate limited
1386 public function isPingLimitable() {
1387 global $wgRateLimitsExcludedIPs;
1388 if( in_array( wfGetIP(), $wgRateLimitsExcludedIPs ) ) {
1389 // No other good way currently to disable rate limits
1390 // for specific IPs. :P
1391 // But this is a crappy hack and should die.
1394 return !$this->isAllowed('noratelimit');
1398 * Primitive rate limits: enforce maximum actions per time period
1399 * to put a brake on flooding.
1401 * @note When using a shared cache like memcached, IP-address
1402 * last-hit counters will be shared across wikis.
1404 * @param $action String Action to enforce; 'edit' if unspecified
1405 * @return Bool True if a rate limiter was tripped
1407 public function pingLimiter( $action = 'edit' ) {
1408 # Call the 'PingLimiter' hook
1410 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1414 global $wgRateLimits;
1415 if( !isset( $wgRateLimits[$action] ) ) {
1419 # Some groups shouldn't trigger the ping limiter, ever
1420 if( !$this->isPingLimitable() )
1423 global $wgMemc, $wgRateLimitLog;
1424 wfProfileIn( __METHOD__
);
1426 $limits = $wgRateLimits[$action];
1428 $id = $this->getId();
1432 if( isset( $limits['anon'] ) && $id == 0 ) {
1433 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1436 if( isset( $limits['user'] ) && $id != 0 ) {
1437 $userLimit = $limits['user'];
1439 if( $this->isNewbie() ) {
1440 if( isset( $limits['newbie'] ) && $id != 0 ) {
1441 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1443 if( isset( $limits['ip'] ) ) {
1444 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1447 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1448 $subnet = $matches[1];
1449 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1452 // Check for group-specific permissions
1453 // If more than one group applies, use the group with the highest limit
1454 foreach ( $this->getGroups() as $group ) {
1455 if ( isset( $limits[$group] ) ) {
1456 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1457 $userLimit = $limits[$group];
1461 // Set the user limit key
1462 if ( $userLimit !== false ) {
1463 wfDebug( __METHOD__
. ": effective user limit: $userLimit\n" );
1464 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1468 foreach( $keys as $key => $limit ) {
1469 list( $max, $period ) = $limit;
1470 $summary = "(limit $max in {$period}s)";
1471 $count = $wgMemc->get( $key );
1474 if( $count > $max ) {
1475 wfDebug( __METHOD__
. ": tripped! $key at $count $summary\n" );
1476 if( $wgRateLimitLog ) {
1477 wfSuppressWarnings();
1478 file_put_contents( $wgRateLimitLog, wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", FILE_APPEND
);
1479 wfRestoreWarnings();
1483 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1486 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1487 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1489 $wgMemc->incr( $key );
1492 wfProfileOut( __METHOD__
);
1497 * Check if user is blocked
1499 * @param $bFromSlave Bool Whether to check the slave database instead of the master
1500 * @return Bool True if blocked, false otherwise
1502 public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1503 $this->getBlockedStatus( $bFromSlave );
1504 return $this->mBlock
instanceof Block
&& $this->mBlock
->prevents( 'edit' );
1508 * Check if user is blocked from editing a particular article
1510 * @param $title Title to check
1511 * @param $bFromSlave Bool whether to check the slave database instead of the master
1514 function isBlockedFrom( $title, $bFromSlave = false ) {
1515 global $wgBlockAllowsUTEdit;
1516 wfProfileIn( __METHOD__
);
1518 $blocked = $this->isBlocked( $bFromSlave );
1519 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1520 # If a user's name is suppressed, they cannot make edits anywhere
1521 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName() &&
1522 $title->getNamespace() == NS_USER_TALK
) {
1524 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1527 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1529 wfProfileOut( __METHOD__
);
1534 * If user is blocked, return the name of the user who placed the block
1535 * @return String name of blocker
1537 public function blockedBy() {
1538 $this->getBlockedStatus();
1539 return $this->mBlockedby
;
1543 * If user is blocked, return the specified reason for the block
1544 * @return String Blocking reason
1546 public function blockedFor() {
1547 $this->getBlockedStatus();
1548 return $this->mBlockreason
;
1552 * If user is blocked, return the ID for the block
1553 * @return Int Block ID
1555 public function getBlockId() {
1556 $this->getBlockedStatus();
1557 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1561 * Check if user is blocked on all wikis.
1562 * Do not use for actual edit permission checks!
1563 * This is intented for quick UI checks.
1565 * @param $ip String IP address, uses current client if none given
1566 * @return Bool True if blocked, false otherwise
1568 public function isBlockedGlobally( $ip = '' ) {
1569 if( $this->mBlockedGlobally
!== null ) {
1570 return $this->mBlockedGlobally
;
1572 // User is already an IP?
1573 if( IP
::isIPAddress( $this->getName() ) ) {
1574 $ip = $this->getName();
1579 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1580 $this->mBlockedGlobally
= (bool)$blocked;
1581 return $this->mBlockedGlobally
;
1585 * Check if user account is locked
1587 * @return Bool True if locked, false otherwise
1589 public function isLocked() {
1590 if( $this->mLocked
!== null ) {
1591 return $this->mLocked
;
1594 $authUser = $wgAuth->getUserInstance( $this );
1595 $this->mLocked
= (bool)$authUser->isLocked();
1596 return $this->mLocked
;
1600 * Check if user account is hidden
1602 * @return Bool True if hidden, false otherwise
1604 public function isHidden() {
1605 if( $this->mHideName
!== null ) {
1606 return $this->mHideName
;
1608 $this->getBlockedStatus();
1609 if( !$this->mHideName
) {
1611 $authUser = $wgAuth->getUserInstance( $this );
1612 $this->mHideName
= (bool)$authUser->isHidden();
1614 return $this->mHideName
;
1618 * Get the user's ID.
1619 * @return Int The user's ID; 0 if the user is anonymous or nonexistent
1621 public function getId() {
1622 if( $this->mId
=== null && $this->mName
!== null
1623 && User
::isIP( $this->mName
) ) {
1624 // Special case, we know the user is anonymous
1626 } elseif( !$this->isItemLoaded( 'id' ) ) {
1627 // Don't load if this was initialized from an ID
1634 * Set the user and reload all fields according to a given ID
1635 * @param $v Int User ID to reload
1637 public function setId( $v ) {
1639 $this->clearInstanceCache( 'id' );
1643 * Get the user name, or the IP of an anonymous user
1644 * @return String User's name or IP address
1646 public function getName() {
1647 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1648 # Special case optimisation
1649 return $this->mName
;
1652 if ( $this->mName
=== false ) {
1654 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1656 return $this->mName
;
1661 * Set the user name.
1663 * This does not reload fields from the database according to the given
1664 * name. Rather, it is used to create a temporary "nonexistent user" for
1665 * later addition to the database. It can also be used to set the IP
1666 * address for an anonymous user to something other than the current
1669 * @note User::newFromName() has rougly the same function, when the named user
1671 * @param $str String New user name to set
1673 public function setName( $str ) {
1675 $this->mName
= $str;
1679 * Get the user's name escaped by underscores.
1680 * @return String Username escaped by underscores.
1682 public function getTitleKey() {
1683 return str_replace( ' ', '_', $this->getName() );
1687 * Check if the user has new messages.
1688 * @return Bool True if the user has new messages
1690 public function getNewtalk() {
1693 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1694 if( $this->mNewtalk
=== -1 ) {
1695 $this->mNewtalk
= false; # reset talk page status
1697 # Check memcached separately for anons, who have no
1698 # entire User object stored in there.
1701 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1702 $newtalk = $wgMemc->get( $key );
1703 if( strval( $newtalk ) !== '' ) {
1704 $this->mNewtalk
= (bool)$newtalk;
1706 // Since we are caching this, make sure it is up to date by getting it
1708 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1709 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1712 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1716 return (bool)$this->mNewtalk
;
1720 * Return the talk page(s) this user has new messages on.
1721 * @return Array of String page URLs
1723 public function getNewMessageLinks() {
1725 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) )
1728 if( !$this->getNewtalk() )
1730 $up = $this->getUserPage();
1731 $utp = $up->getTalkPage();
1732 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL() ) );
1736 * Internal uncached check for new messages
1739 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1740 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1741 * @param $fromMaster Bool true to fetch from the master, false for a slave
1742 * @return Bool True if the user has new messages
1744 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
1745 if ( $fromMaster ) {
1746 $db = wfGetDB( DB_MASTER
);
1748 $db = wfGetDB( DB_SLAVE
);
1750 $ok = $db->selectField( 'user_newtalk', $field,
1751 array( $field => $id ), __METHOD__
);
1752 return $ok !== false;
1756 * Add or update the new messages flag
1757 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1758 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1759 * @return Bool True if successful, false otherwise
1761 protected function updateNewtalk( $field, $id ) {
1762 $dbw = wfGetDB( DB_MASTER
);
1763 $dbw->insert( 'user_newtalk',
1764 array( $field => $id ),
1767 if ( $dbw->affectedRows() ) {
1768 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
1771 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
1777 * Clear the new messages flag for the given user
1778 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1779 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1780 * @return Bool True if successful, false otherwise
1782 protected function deleteNewtalk( $field, $id ) {
1783 $dbw = wfGetDB( DB_MASTER
);
1784 $dbw->delete( 'user_newtalk',
1785 array( $field => $id ),
1787 if ( $dbw->affectedRows() ) {
1788 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
1791 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
1797 * Update the 'You have new messages!' status.
1798 * @param $val Bool Whether the user has new messages
1800 public function setNewtalk( $val ) {
1801 if( wfReadOnly() ) {
1806 $this->mNewtalk
= $val;
1808 if( $this->isAnon() ) {
1810 $id = $this->getName();
1813 $id = $this->getId();
1818 $changed = $this->updateNewtalk( $field, $id );
1820 $changed = $this->deleteNewtalk( $field, $id );
1823 if( $this->isAnon() ) {
1824 // Anons have a separate memcached space, since
1825 // user records aren't kept for them.
1826 $key = wfMemcKey( 'newtalk', 'ip', $id );
1827 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1830 $this->invalidateCache();
1835 * Generate a current or new-future timestamp to be stored in the
1836 * user_touched field when we update things.
1837 * @return String Timestamp in TS_MW format
1839 private static function newTouchedTimestamp() {
1840 global $wgClockSkewFudge;
1841 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1845 * Clear user data from memcached.
1846 * Use after applying fun updates to the database; caller's
1847 * responsibility to update user_touched if appropriate.
1849 * Called implicitly from invalidateCache() and saveSettings().
1851 private function clearSharedCache() {
1855 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1860 * Immediately touch the user data cache for this account.
1861 * Updates user_touched field, and removes account data from memcached
1862 * for reload on the next hit.
1864 public function invalidateCache() {
1865 if( wfReadOnly() ) {
1870 $this->mTouched
= self
::newTouchedTimestamp();
1872 $dbw = wfGetDB( DB_MASTER
);
1873 $dbw->update( 'user',
1874 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1875 array( 'user_id' => $this->mId
),
1878 $this->clearSharedCache();
1883 * Validate the cache for this account.
1884 * @param $timestamp String A timestamp in TS_MW format
1886 public function validateCache( $timestamp ) {
1888 return ( $timestamp >= $this->mTouched
);
1892 * Get the user touched timestamp
1893 * @return String timestamp
1895 public function getTouched() {
1897 return $this->mTouched
;
1901 * Set the password and reset the random token.
1902 * Calls through to authentication plugin if necessary;
1903 * will have no effect if the auth plugin refuses to
1904 * pass the change through or if the legal password
1907 * As a special case, setting the password to null
1908 * wipes it, so the account cannot be logged in until
1909 * a new password is set, for instance via e-mail.
1911 * @param $str String New password to set
1912 * @throws PasswordError on failure
1914 public function setPassword( $str ) {
1917 if( $str !== null ) {
1918 if( !$wgAuth->allowPasswordChange() ) {
1919 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1922 if( !$this->isValidPassword( $str ) ) {
1923 global $wgMinimalPasswordLength;
1924 $valid = $this->getPasswordValidity( $str );
1925 if ( is_array( $valid ) ) {
1926 $message = array_shift( $valid );
1930 $params = array( $wgMinimalPasswordLength );
1932 throw new PasswordError( wfMsgExt( $message, array( 'parsemag' ), $params ) );
1936 if( !$wgAuth->setPassword( $this, $str ) ) {
1937 throw new PasswordError( wfMsg( 'externaldberror' ) );
1940 $this->setInternalPassword( $str );
1946 * Set the password and reset the random token unconditionally.
1948 * @param $str String New password to set
1950 public function setInternalPassword( $str ) {
1954 if( $str === null ) {
1955 // Save an invalid hash...
1956 $this->mPassword
= '';
1958 $this->mPassword
= self
::crypt( $str );
1960 $this->mNewpassword
= '';
1961 $this->mNewpassTime
= null;
1965 * Get the user's current token.
1966 * @return String Token
1968 public function getToken() {
1970 return $this->mToken
;
1974 * Set the random token (used for persistent authentication)
1975 * Called from loadDefaults() among other places.
1977 * @param $token String If specified, set the token to this value
1979 public function setToken( $token = false ) {
1980 global $wgSecretKey, $wgProxyKey;
1983 if ( $wgSecretKey ) {
1984 $key = $wgSecretKey;
1985 } elseif ( $wgProxyKey ) {
1990 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1992 $this->mToken
= $token;
1997 * Set the cookie password
1999 * @param $str String New cookie password
2001 private function setCookiePassword( $str ) {
2003 $this->mCookiePassword
= md5( $str );
2007 * Set the password for a password reminder or new account email
2009 * @param $str String New password to set
2010 * @param $throttle Bool If true, reset the throttle timestamp to the present
2012 public function setNewpassword( $str, $throttle = true ) {
2014 $this->mNewpassword
= self
::crypt( $str );
2016 $this->mNewpassTime
= wfTimestampNow();
2021 * Has password reminder email been sent within the last
2022 * $wgPasswordReminderResendTime hours?
2025 public function isPasswordReminderThrottled() {
2026 global $wgPasswordReminderResendTime;
2028 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2031 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2032 return time() < $expiry;
2036 * Get the user's e-mail address
2037 * @return String User's email address
2039 public function getEmail() {
2041 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
2042 return $this->mEmail
;
2046 * Get the timestamp of the user's e-mail authentication
2047 * @return String TS_MW timestamp
2049 public function getEmailAuthenticationTimestamp() {
2051 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2052 return $this->mEmailAuthenticated
;
2056 * Set the user's e-mail address
2057 * @param $str String New e-mail address
2059 public function setEmail( $str ) {
2061 $this->mEmail
= $str;
2062 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
2066 * Get the user's real name
2067 * @return String User's real name
2069 public function getRealName() {
2070 if ( !$this->isItemLoaded( 'realname' ) ) {
2074 return $this->mRealName
;
2078 * Set the user's real name
2079 * @param $str String New real name
2081 public function setRealName( $str ) {
2083 $this->mRealName
= $str;
2087 * Get the user's current setting for a given option.
2089 * @param $oname String The option to check
2090 * @param $defaultOverride String A default value returned if the option does not exist
2091 * @param $ignoreHidden Bool = whether to ignore the effects of $wgHiddenPrefs
2092 * @return String User's current value for the option
2093 * @see getBoolOption()
2094 * @see getIntOption()
2096 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2097 global $wgHiddenPrefs;
2098 $this->loadOptions();
2100 if ( is_null( $this->mOptions
) ) {
2101 if($defaultOverride != '') {
2102 return $defaultOverride;
2104 $this->mOptions
= User
::getDefaultOptions();
2107 # We want 'disabled' preferences to always behave as the default value for
2108 # users, even if they have set the option explicitly in their settings (ie they
2109 # set it, and then it was disabled removing their ability to change it). But
2110 # we don't want to erase the preferences in the database in case the preference
2111 # is re-enabled again. So don't touch $mOptions, just override the returned value
2112 if( in_array( $oname, $wgHiddenPrefs ) && !$ignoreHidden ){
2113 return self
::getDefaultOption( $oname );
2116 if ( array_key_exists( $oname, $this->mOptions
) ) {
2117 return $this->mOptions
[$oname];
2119 return $defaultOverride;
2124 * Get all user's options
2128 public function getOptions() {
2129 global $wgHiddenPrefs;
2130 $this->loadOptions();
2131 $options = $this->mOptions
;
2133 # We want 'disabled' preferences to always behave as the default value for
2134 # users, even if they have set the option explicitly in their settings (ie they
2135 # set it, and then it was disabled removing their ability to change it). But
2136 # we don't want to erase the preferences in the database in case the preference
2137 # is re-enabled again. So don't touch $mOptions, just override the returned value
2138 foreach( $wgHiddenPrefs as $pref ){
2139 $default = self
::getDefaultOption( $pref );
2140 if( $default !== null ){
2141 $options[$pref] = $default;
2149 * Get the user's current setting for a given option, as a boolean value.
2151 * @param $oname String The option to check
2152 * @return Bool User's current value for the option
2155 public function getBoolOption( $oname ) {
2156 return (bool)$this->getOption( $oname );
2160 * Get the user's current setting for a given option, as a boolean value.
2162 * @param $oname String The option to check
2163 * @param $defaultOverride Int A default value returned if the option does not exist
2164 * @return Int User's current value for the option
2167 public function getIntOption( $oname, $defaultOverride=0 ) {
2168 $val = $this->getOption( $oname );
2170 $val = $defaultOverride;
2172 return intval( $val );
2176 * Set the given option for a user.
2178 * @param $oname String The option to set
2179 * @param $val mixed New value to set
2181 public function setOption( $oname, $val ) {
2183 $this->loadOptions();
2185 // Explicitly NULL values should refer to defaults
2186 global $wgDefaultUserOptions;
2187 if( is_null( $val ) && isset( $wgDefaultUserOptions[$oname] ) ) {
2188 $val = $wgDefaultUserOptions[$oname];
2191 $this->mOptions
[$oname] = $val;
2195 * Reset all options to the site defaults
2197 public function resetOptions() {
2198 $this->mOptions
= self
::getDefaultOptions();
2202 * Get the user's preferred date format.
2203 * @return String User's preferred date format
2205 public function getDatePreference() {
2206 // Important migration for old data rows
2207 if ( is_null( $this->mDatePreference
) ) {
2209 $value = $this->getOption( 'date' );
2210 $map = $wgLang->getDatePreferenceMigrationMap();
2211 if ( isset( $map[$value] ) ) {
2212 $value = $map[$value];
2214 $this->mDatePreference
= $value;
2216 return $this->mDatePreference
;
2220 * Get the user preferred stub threshold
2222 public function getStubThreshold() {
2223 global $wgMaxArticleSize; # Maximum article size, in Kb
2224 $threshold = intval( $this->getOption( 'stubthreshold' ) );
2225 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2226 # If they have set an impossible value, disable the preference
2227 # so we can use the parser cache again.
2234 * Get the permissions this user has.
2235 * @param $ns int If numeric, get permissions for this namespace
2236 * @return Array of String permission names
2238 public function getRights( $ns = null ) {
2239 $key = is_null( $ns ) ?
'*' : intval( $ns );
2241 if ( is_null( $this->mRights
) ) {
2242 $this->mRights
= array();
2245 if ( !isset( $this->mRights
[$key] ) ) {
2246 $this->mRights
[$key] = self
::getGroupPermissions( $this->getEffectiveGroups(), $ns );
2247 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
[$key], $ns ) );
2248 // Force reindexation of rights when a hook has unset one of them
2249 $this->mRights
[$key] = array_values( $this->mRights
[$key] );
2251 if ( is_null( $ns ) ) {
2252 return $this->mRights
[$key];
2254 // Merge non namespace specific rights
2255 return array_merge( $this->mRights
[$key], $this->getRights() );
2261 * Get the list of explicit group memberships this user has.
2262 * The implicit * and user groups are not included.
2263 * @return Array of String internal group names
2265 public function getGroups() {
2267 return $this->mGroups
;
2271 * Get the list of implicit group memberships this user has.
2272 * This includes all explicit groups, plus 'user' if logged in,
2273 * '*' for all accounts, and autopromoted groups
2274 * @param $recache Bool Whether to avoid the cache
2275 * @return Array of String internal group names
2277 public function getEffectiveGroups( $recache = false ) {
2278 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2279 wfProfileIn( __METHOD__
);
2280 $this->mEffectiveGroups
= $this->getGroups();
2281 $this->mEffectiveGroups
[] = '*';
2282 if( $this->getId() ) {
2283 $this->mEffectiveGroups
[] = 'user';
2285 $this->mEffectiveGroups
= array_unique( array_merge(
2286 $this->mEffectiveGroups
,
2287 Autopromote
::getAutopromoteGroups( $this )
2290 # Hook for additional groups
2291 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2293 wfProfileOut( __METHOD__
);
2295 return $this->mEffectiveGroups
;
2299 * Returns the groups the user has belonged to.
2301 * The user may still belong to the returned groups. Compare with getGroups().
2303 * The function will not return groups the user had belonged to before MW 1.17
2305 * @return array Names of the groups the user has belonged to.
2307 public function getFormerGroups() {
2308 if( is_null( $this->mFormerGroups
) ) {
2309 $dbr = wfGetDB( DB_MASTER
);
2310 $res = $dbr->select( 'user_former_groups',
2311 array( 'ufg_group' ),
2312 array( 'ufg_user' => $this->mId
),
2314 $this->mFormerGroups
= array();
2315 foreach( $res as $row ) {
2316 $this->mFormerGroups
[] = $row->ufg_group
;
2319 return $this->mFormerGroups
;
2323 * Get the user's edit count.
2326 public function getEditCount() {
2327 if( $this->getId() ) {
2328 if ( !isset( $this->mEditCount
) ) {
2329 /* Populate the count, if it has not been populated yet */
2330 $this->mEditCount
= User
::edits( $this->mId
);
2332 return $this->mEditCount
;
2340 * Add the user to the given group.
2341 * This takes immediate effect.
2342 * @param $group String Name of the group to add
2344 public function addGroup( $group ) {
2345 if( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2346 $dbw = wfGetDB( DB_MASTER
);
2347 if( $this->getId() ) {
2348 $dbw->insert( 'user_groups',
2350 'ug_user' => $this->getID(),
2351 'ug_group' => $group,
2354 array( 'IGNORE' ) );
2357 $this->loadGroups();
2358 $this->mGroups
[] = $group;
2359 $this->mRights
= null;
2361 $this->invalidateCache();
2365 * Remove the user from the given group.
2366 * This takes immediate effect.
2367 * @param $group String Name of the group to remove
2369 public function removeGroup( $group ) {
2371 if( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2372 $dbw = wfGetDB( DB_MASTER
);
2373 $dbw->delete( 'user_groups',
2375 'ug_user' => $this->getID(),
2376 'ug_group' => $group,
2378 // Remember that the user was in this group
2379 $dbw->insert( 'user_former_groups',
2381 'ufg_user' => $this->getID(),
2382 'ufg_group' => $group,
2385 array( 'IGNORE' ) );
2387 $this->loadGroups();
2388 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
2389 $this->mRights
= null;
2391 $this->invalidateCache();
2395 * Get whether the user is logged in
2398 public function isLoggedIn() {
2399 return $this->getID() != 0;
2403 * Get whether the user is anonymous
2406 public function isAnon() {
2407 return !$this->isLoggedIn();
2411 * Check if user is allowed to access a feature / make an action
2412 * @param varargs String permissions to test
2413 * @return Boolean: True if user is allowed to perform *any* of the given actions
2415 public function isAllowedAny( /*...*/ ){
2416 $permissions = func_get_args();
2417 foreach( $permissions as $permission ){
2418 if( $this->isAllowed( $permission ) ){
2426 * @param varargs String
2427 * @return bool True if the user is allowed to perform *all* of the given actions
2429 public function isAllowedAll( /*...*/ ){
2430 $permissions = func_get_args();
2431 foreach( $permissions as $permission ){
2432 if( !$this->isAllowed( $permission ) ){
2440 * Internal mechanics of testing a permission
2441 * @param $action String
2442 * @paramn $ns int Namespace optional
2445 public function isAllowed( $action = '', $ns = null ) {
2446 if ( $action === '' ) {
2447 return true; // In the spirit of DWIM
2449 # Patrolling may not be enabled
2450 if( $action === 'patrol' ||
$action === 'autopatrol' ) {
2451 global $wgUseRCPatrol, $wgUseNPPatrol;
2452 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2455 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2456 # by misconfiguration: 0 == 'foo'
2457 return in_array( $action, $this->getRights( $ns ), true );
2461 * Check whether to enable recent changes patrol features for this user
2462 * @return Boolean: True or false
2464 public function useRCPatrol() {
2465 global $wgUseRCPatrol;
2466 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
2470 * Check whether to enable new pages patrol features for this user
2471 * @return Bool True or false
2473 public function useNPPatrol() {
2474 global $wgUseRCPatrol, $wgUseNPPatrol;
2475 return( ( $wgUseRCPatrol ||
$wgUseNPPatrol ) && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) ) );
2479 * Get the WebRequest object to use with this object
2481 * @return WebRequest
2483 public function getRequest() {
2484 if ( $this->mRequest
) {
2485 return $this->mRequest
;
2493 * Get the current skin, loading it if required
2494 * @return Skin The current skin
2495 * @todo FIXME: Need to check the old failback system [AV]
2496 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
2498 public function getSkin() {
2499 return RequestContext
::getMain()->getSkin();
2503 * Check the watched status of an article.
2504 * @param $title Title of the article to look at
2507 public function isWatched( $title ) {
2508 $wl = WatchedItem
::fromUserTitle( $this, $title );
2509 return $wl->isWatched();
2514 * @param $title Title of the article to look at
2516 public function addWatch( $title ) {
2517 $wl = WatchedItem
::fromUserTitle( $this, $title );
2519 $this->invalidateCache();
2523 * Stop watching an article.
2524 * @param $title Title of the article to look at
2526 public function removeWatch( $title ) {
2527 $wl = WatchedItem
::fromUserTitle( $this, $title );
2529 $this->invalidateCache();
2533 * Clear the user's notification timestamp for the given title.
2534 * If e-notif e-mails are on, they will receive notification mails on
2535 * the next change of the page if it's watched etc.
2536 * @param $title Title of the article to look at
2538 public function clearNotification( &$title ) {
2539 global $wgUseEnotif, $wgShowUpdatedMarker;
2541 # Do nothing if the database is locked to writes
2542 if( wfReadOnly() ) {
2546 if( $title->getNamespace() == NS_USER_TALK
&&
2547 $title->getText() == $this->getName() ) {
2548 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2550 $this->setNewtalk( false );
2553 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2557 if( $this->isAnon() ) {
2558 // Nothing else to do...
2562 // Only update the timestamp if the page is being watched.
2563 // The query to find out if it is watched is cached both in memcached and per-invocation,
2564 // and when it does have to be executed, it can be on a slave
2565 // If this is the user's newtalk page, we always update the timestamp
2566 if( $title->getNamespace() == NS_USER_TALK
&&
2567 $title->getText() == $this->getName() )
2571 $watched = $this->isWatched( $title );
2574 // If the page is watched by the user (or may be watched), update the timestamp on any
2575 // any matching rows
2577 $dbw = wfGetDB( DB_MASTER
);
2578 $dbw->update( 'watchlist',
2580 'wl_notificationtimestamp' => null
2581 ), array( /* WHERE */
2582 'wl_title' => $title->getDBkey(),
2583 'wl_namespace' => $title->getNamespace(),
2584 'wl_user' => $this->getID()
2591 * Resets all of the given user's page-change notification timestamps.
2592 * If e-notif e-mails are on, they will receive notification mails on
2593 * the next change of any watched page.
2595 public function clearAllNotifications() {
2596 global $wgUseEnotif, $wgShowUpdatedMarker;
2597 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2598 $this->setNewtalk( false );
2601 $id = $this->getId();
2603 $dbw = wfGetDB( DB_MASTER
);
2604 $dbw->update( 'watchlist',
2606 'wl_notificationtimestamp' => null
2607 ), array( /* WHERE */
2611 # We also need to clear here the "you have new message" notification for the own user_talk page
2612 # This is cleared one page view later in Article::viewUpdates();
2617 * Set this user's options from an encoded string
2618 * @param $str String Encoded options to import
2620 private function decodeOptions( $str ) {
2624 $this->mOptionsLoaded
= true;
2625 $this->mOptionOverrides
= array();
2627 // If an option is not set in $str, use the default value
2628 $this->mOptions
= self
::getDefaultOptions();
2630 $a = explode( "\n", $str );
2631 foreach ( $a as $s ) {
2633 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2634 $this->mOptions
[$m[1]] = $m[2];
2635 $this->mOptionOverrides
[$m[1]] = $m[2];
2641 * Set a cookie on the user's client. Wrapper for
2642 * WebResponse::setCookie
2643 * @param $name String Name of the cookie to set
2644 * @param $value String Value to set
2645 * @param $exp Int Expiration time, as a UNIX time value;
2646 * if 0 or not specified, use the default $wgCookieExpiration
2648 protected function setCookie( $name, $value, $exp = 0 ) {
2649 $this->getRequest()->response()->setcookie( $name, $value, $exp );
2653 * Clear a cookie on the user's client
2654 * @param $name String Name of the cookie to clear
2656 protected function clearCookie( $name ) {
2657 $this->setCookie( $name, '', time() - 86400 );
2661 * Set the default cookies for this session on the user's client.
2663 * @param $request WebRequest object to use; $wgRequest will be used if null
2666 public function setCookies( $request = null ) {
2667 if ( $request === null ) {
2668 $request = $this->getRequest();
2672 if ( 0 == $this->mId
) return;
2674 'wsUserID' => $this->mId
,
2675 'wsToken' => $this->mToken
,
2676 'wsUserName' => $this->getName()
2679 'UserID' => $this->mId
,
2680 'UserName' => $this->getName(),
2682 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2683 $cookies['Token'] = $this->mToken
;
2685 $cookies['Token'] = false;
2688 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2690 foreach ( $session as $name => $value ) {
2691 $request->setSessionData( $name, $value );
2693 foreach ( $cookies as $name => $value ) {
2694 if ( $value === false ) {
2695 $this->clearCookie( $name );
2697 $this->setCookie( $name, $value );
2703 * Log this user out.
2705 public function logout() {
2706 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
2712 * Clear the user's cookies and session, and reset the instance cache.
2715 private function doLogout() {
2716 $this->clearInstanceCache( 'defaults' );
2718 $this->getRequest()->setSessionData( 'wsUserID', 0 );
2720 $this->clearCookie( 'UserID' );
2721 $this->clearCookie( 'Token' );
2723 # Remember when user logged out, to prevent seeing cached pages
2724 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2728 * Save this user's settings into the database.
2729 * @todo Only rarely do all these fields need to be set!
2731 public function saveSettings() {
2733 if ( wfReadOnly() ) { return; }
2734 if ( 0 == $this->mId
) { return; }
2736 $this->mTouched
= self
::newTouchedTimestamp();
2738 $dbw = wfGetDB( DB_MASTER
);
2739 $dbw->update( 'user',
2741 'user_name' => $this->mName
,
2742 'user_password' => $this->mPassword
,
2743 'user_newpassword' => $this->mNewpassword
,
2744 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2745 'user_real_name' => $this->mRealName
,
2746 'user_email' => $this->mEmail
,
2747 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2748 'user_options' => '',
2749 'user_touched' => $dbw->timestamp( $this->mTouched
),
2750 'user_token' => $this->mToken
,
2751 'user_email_token' => $this->mEmailToken
,
2752 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2753 ), array( /* WHERE */
2754 'user_id' => $this->mId
2758 $this->saveOptions();
2760 wfRunHooks( 'UserSaveSettings', array( $this ) );
2761 $this->clearSharedCache();
2762 $this->getUserPage()->invalidateCache();
2766 * If only this user's username is known, and it exists, return the user ID.
2769 public function idForName() {
2770 $s = trim( $this->getName() );
2771 if ( $s === '' ) return 0;
2773 $dbr = wfGetDB( DB_SLAVE
);
2774 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2775 if ( $id === false ) {
2782 * Add a user to the database, return the user object
2784 * @param $name String Username to add
2785 * @param $params Array of Strings Non-default parameters to save to the database as user_* fields:
2786 * - password The user's password hash. Password logins will be disabled if this is omitted.
2787 * - newpassword Hash for a temporary password that has been mailed to the user
2788 * - email The user's email address
2789 * - email_authenticated The email authentication timestamp
2790 * - real_name The user's real name
2791 * - options An associative array of non-default options
2792 * - token Random authentication token. Do not set.
2793 * - registration Registration timestamp. Do not set.
2795 * @return User object, or null if the username already exists
2797 public static function createNew( $name, $params = array() ) {
2800 if ( isset( $params['options'] ) ) {
2801 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
2802 unset( $params['options'] );
2804 $dbw = wfGetDB( DB_MASTER
);
2805 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2808 'user_id' => $seqVal,
2809 'user_name' => $name,
2810 'user_password' => $user->mPassword
,
2811 'user_newpassword' => $user->mNewpassword
,
2812 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
2813 'user_email' => $user->mEmail
,
2814 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2815 'user_real_name' => $user->mRealName
,
2816 'user_options' => '',
2817 'user_token' => $user->mToken
,
2818 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2819 'user_editcount' => 0,
2821 foreach ( $params as $name => $value ) {
2822 $fields["user_$name"] = $value;
2824 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2825 if ( $dbw->affectedRows() ) {
2826 $newUser = User
::newFromId( $dbw->insertId() );
2834 * Add this existing user object to the database
2836 public function addToDatabase() {
2838 $dbw = wfGetDB( DB_MASTER
);
2839 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2840 $dbw->insert( 'user',
2842 'user_id' => $seqVal,
2843 'user_name' => $this->mName
,
2844 'user_password' => $this->mPassword
,
2845 'user_newpassword' => $this->mNewpassword
,
2846 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2847 'user_email' => $this->mEmail
,
2848 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2849 'user_real_name' => $this->mRealName
,
2850 'user_options' => '',
2851 'user_token' => $this->mToken
,
2852 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2853 'user_editcount' => 0,
2856 $this->mId
= $dbw->insertId();
2858 // Clear instance cache other than user table data, which is already accurate
2859 $this->clearInstanceCache();
2861 $this->saveOptions();
2865 * If this (non-anonymous) user is blocked, block any IP address
2866 * they've successfully logged in from.
2868 public function spreadBlock() {
2869 wfDebug( __METHOD__
. "()\n" );
2871 if ( $this->mId
== 0 ) {
2875 $userblock = Block
::newFromTarget( $this->getName() );
2876 if ( !$userblock ) {
2880 $userblock->doAutoblock( wfGetIP() );
2884 * Generate a string which will be different for any combination of
2885 * user options which would produce different parser output.
2886 * This will be used as part of the hash key for the parser cache,
2887 * so users with the same options can share the same cached data
2890 * Extensions which require it should install 'PageRenderingHash' hook,
2891 * which will give them a chance to modify this key based on their own
2894 * @deprecated since 1.17 use the ParserOptions object to get the relevant options
2895 * @return String Page rendering hash
2897 public function getPageRenderingHash() {
2898 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2900 return $this->mHash
;
2902 wfDeprecated( __METHOD__
);
2904 // stubthreshold is only included below for completeness,
2905 // since it disables the parser cache, its value will always
2906 // be 0 when this function is called by parsercache.
2908 $confstr = $this->getOption( 'math' );
2909 $confstr .= '!' . $this->getStubThreshold();
2910 if ( $wgUseDynamicDates ) { # This is wrong (bug 24714)
2911 $confstr .= '!' . $this->getDatePreference();
2913 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ?
'1' : '' );
2914 $confstr .= '!' . $wgLang->getCode();
2915 $confstr .= '!' . $this->getOption( 'thumbsize' );
2916 // add in language specific options, if any
2917 $extra = $wgContLang->getExtraHashOptions();
2920 // Since the skin could be overloading link(), it should be
2921 // included here but in practice, none of our skins do that.
2923 $confstr .= $wgRenderHashAppend;
2925 // Give a chance for extensions to modify the hash, if they have
2926 // extra options or other effects on the parser cache.
2927 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2929 // Make it a valid memcached key fragment
2930 $confstr = str_replace( ' ', '_', $confstr );
2931 $this->mHash
= $confstr;
2936 * Get whether the user is explicitly blocked from account creation.
2937 * @return Bool|Block
2939 public function isBlockedFromCreateAccount() {
2940 $this->getBlockedStatus();
2941 if( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ){
2942 return $this->mBlock
;
2945 # bug 13611: if the IP address the user is trying to create an account from is
2946 # blocked with createaccount disabled, prevent new account creation there even
2947 # when the user is logged in
2948 if( $this->mBlockedFromCreateAccount
=== false ){
2949 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, wfGetIP() );
2951 return $this->mBlockedFromCreateAccount
instanceof Block
&& $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
2952 ?
$this->mBlockedFromCreateAccount
2957 * Get whether the user is blocked from using Special:Emailuser.
2960 public function isBlockedFromEmailuser() {
2961 $this->getBlockedStatus();
2962 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
2966 * Get whether the user is allowed to create an account.
2969 function isAllowedToCreateAccount() {
2970 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2974 * Get this user's personal page title.
2976 * @return Title: User's personal page title
2978 public function getUserPage() {
2979 return Title
::makeTitle( NS_USER
, $this->getName() );
2983 * Get this user's talk page title.
2985 * @return Title: User's talk page title
2987 public function getTalkPage() {
2988 $title = $this->getUserPage();
2989 return $title->getTalkPage();
2993 * Determine whether the user is a newbie. Newbies are either
2994 * anonymous IPs, or the most recently created accounts.
2997 public function isNewbie() {
2998 return !$this->isAllowed( 'autoconfirmed' );
3002 * Check to see if the given clear-text password is one of the accepted passwords
3003 * @param $password String: user password.
3004 * @return Boolean: True if the given password is correct, otherwise False.
3006 public function checkPassword( $password ) {
3007 global $wgAuth, $wgLegacyEncoding;
3010 // Even though we stop people from creating passwords that
3011 // are shorter than this, doesn't mean people wont be able
3012 // to. Certain authentication plugins do NOT want to save
3013 // domain passwords in a mysql database, so we should
3014 // check this (in case $wgAuth->strict() is false).
3015 if( !$this->isValidPassword( $password ) ) {
3019 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
3021 } elseif( $wgAuth->strict() ) {
3022 /* Auth plugin doesn't allow local authentication */
3024 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
3025 /* Auth plugin doesn't allow local authentication for this user name */
3028 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
3030 } elseif ( $wgLegacyEncoding ) {
3031 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3032 # Check for this with iconv
3033 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3034 if ( $cp1252Password != $password &&
3035 self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) )
3044 * Check if the given clear-text password matches the temporary password
3045 * sent by e-mail for password reset operations.
3046 * @return Boolean: True if matches, false otherwise
3048 public function checkTemporaryPassword( $plaintext ) {
3049 global $wgNewPasswordExpiry;
3052 if( self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() ) ) {
3053 if ( is_null( $this->mNewpassTime
) ) {
3056 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3057 return ( time() < $expiry );
3064 * Initialize (if necessary) and return a session token value
3065 * which can be used in edit forms to show that the user's
3066 * login credentials aren't being hijacked with a foreign form
3069 * @param $salt String|Array of Strings Optional function-specific data for hashing
3070 * @param $request WebRequest object to use or null to use $wgRequest
3071 * @return String The new edit token
3073 public function editToken( $salt = '', $request = null ) {
3074 if ( $request == null ) {
3075 $request = $this->getRequest();
3078 if ( $this->isAnon() ) {
3079 return EDIT_TOKEN_SUFFIX
;
3081 $token = $request->getSessionData( 'wsEditToken' );
3082 if ( $token === null ) {
3083 $token = self
::generateToken();
3084 $request->setSessionData( 'wsEditToken', $token );
3086 if( is_array( $salt ) ) {
3087 $salt = implode( '|', $salt );
3089 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
3094 * Generate a looking random token for various uses.
3096 * @param $salt String Optional salt value
3097 * @return String The new random token
3099 public static function generateToken( $salt = '' ) {
3100 $token = dechex( mt_rand() ) . dechex( mt_rand() );
3101 return md5( $token . $salt );
3105 * Check given value against the token value stored in the session.
3106 * A match should confirm that the form was submitted from the
3107 * user's own login session, not a form submission from a third-party
3110 * @param $val String Input value to compare
3111 * @param $salt String Optional function-specific data for hashing
3112 * @param $request WebRequest object to use or null to use $wgRequest
3113 * @return Boolean: Whether the token matches
3115 public function matchEditToken( $val, $salt = '', $request = null ) {
3116 $sessionToken = $this->editToken( $salt, $request );
3117 if ( $val != $sessionToken ) {
3118 wfDebug( "User::matchEditToken: broken session data\n" );
3120 return $val == $sessionToken;
3124 * Check given value against the token value stored in the session,
3125 * ignoring the suffix.
3127 * @param $val String Input value to compare
3128 * @param $salt String Optional function-specific data for hashing
3129 * @param $request WebRequest object to use or null to use $wgRequest
3130 * @return Boolean: Whether the token matches
3132 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3133 $sessionToken = $this->editToken( $salt, $request );
3134 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3138 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3139 * mail to the user's given address.
3141 * @param $type String: message to send, either "created", "changed" or "set"
3142 * @return Status object
3144 public function sendConfirmationMail( $type = 'created' ) {
3146 $expiration = null; // gets passed-by-ref and defined in next line.
3147 $token = $this->confirmationToken( $expiration );
3148 $url = $this->confirmationTokenUrl( $token );
3149 $invalidateURL = $this->invalidationTokenUrl( $token );
3150 $this->saveSettings();
3152 if ( $type == 'created' ||
$type === false ) {
3153 $message = 'confirmemail_body';
3154 } elseif ( $type === true ) {
3155 $message = 'confirmemail_body_changed';
3157 $message = 'confirmemail_body_' . $type;
3160 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
3165 $wgLang->timeanddate( $expiration, false ),
3167 $wgLang->date( $expiration, false ),
3168 $wgLang->time( $expiration, false ) ) );
3172 * Send an e-mail to this user's account. Does not check for
3173 * confirmed status or validity.
3175 * @param $subject String Message subject
3176 * @param $body String Message body
3177 * @param $from String Optional From address; if unspecified, default $wgPasswordSender will be used
3178 * @param $replyto String Reply-To address
3181 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3182 if( is_null( $from ) ) {
3183 global $wgPasswordSender, $wgPasswordSenderName;
3184 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
3186 $sender = new MailAddress( $from );
3189 $to = new MailAddress( $this );
3190 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
3194 * Generate, store, and return a new e-mail confirmation code.
3195 * A hash (unsalted, since it's used as a key) is stored.
3197 * @note Call saveSettings() after calling this function to commit
3198 * this change to the database.
3200 * @param[out] &$expiration \mixed Accepts the expiration time
3201 * @return String New token
3203 private function confirmationToken( &$expiration ) {
3204 global $wgUserEmailConfirmationTokenExpiry;
3206 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
3207 $expiration = wfTimestamp( TS_MW
, $expires );
3208 $token = self
::generateToken( $this->mId
. $this->mEmail
. $expires );
3209 $hash = md5( $token );
3211 $this->mEmailToken
= $hash;
3212 $this->mEmailTokenExpires
= $expiration;
3217 * Return a URL the user can use to confirm their email address.
3218 * @param $token String Accepts the email confirmation token
3219 * @return String New token URL
3221 private function confirmationTokenUrl( $token ) {
3222 return $this->getTokenUrl( 'ConfirmEmail', $token );
3226 * Return a URL the user can use to invalidate their email address.
3227 * @param $token String Accepts the email confirmation token
3228 * @return String New token URL
3230 private function invalidationTokenUrl( $token ) {
3231 return $this->getTokenUrl( 'Invalidateemail', $token );
3235 * Internal function to format the e-mail validation/invalidation URLs.
3236 * This uses $wgArticlePath directly as a quickie hack to use the
3237 * hardcoded English names of the Special: pages, for ASCII safety.
3239 * @note Since these URLs get dropped directly into emails, using the
3240 * short English names avoids insanely long URL-encoded links, which
3241 * also sometimes can get corrupted in some browsers/mailers
3242 * (bug 6957 with Gmail and Internet Explorer).
3244 * @param $page String Special page
3245 * @param $token String Token
3246 * @return String Formatted URL
3248 protected function getTokenUrl( $page, $token ) {
3249 global $wgArticlePath;
3253 "Special:$page/$token",
3258 * Mark the e-mail address confirmed.
3260 * @note Call saveSettings() after calling this function to commit the change.
3262 public function confirmEmail() {
3263 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3264 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3269 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3270 * address if it was already confirmed.
3272 * @note Call saveSettings() after calling this function to commit the change.
3275 function invalidateEmail() {
3277 $this->mEmailToken
= null;
3278 $this->mEmailTokenExpires
= null;
3279 $this->setEmailAuthenticationTimestamp( null );
3280 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3285 * Set the e-mail authentication timestamp.
3286 * @param $timestamp String TS_MW timestamp
3288 function setEmailAuthenticationTimestamp( $timestamp ) {
3290 $this->mEmailAuthenticated
= $timestamp;
3291 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
3295 * Is this user allowed to send e-mails within limits of current
3296 * site configuration?
3299 public function canSendEmail() {
3300 global $wgEnableEmail, $wgEnableUserEmail;
3301 if( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
3304 $canSend = $this->isEmailConfirmed();
3305 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3310 * Is this user allowed to receive e-mails within limits of current
3311 * site configuration?
3314 public function canReceiveEmail() {
3315 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3319 * Is this user's e-mail address valid-looking and confirmed within
3320 * limits of the current site configuration?
3322 * @note If $wgEmailAuthentication is on, this may require the user to have
3323 * confirmed their address by returning a code or using a password
3324 * sent to the address from the wiki.
3328 public function isEmailConfirmed() {
3329 global $wgEmailAuthentication;
3332 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3333 if( $this->isAnon() ) {
3336 if( !Sanitizer
::validateEmail( $this->mEmail
) ) {
3339 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
3349 * Check whether there is an outstanding request for e-mail confirmation.
3352 public function isEmailConfirmationPending() {
3353 global $wgEmailAuthentication;
3354 return $wgEmailAuthentication &&
3355 !$this->isEmailConfirmed() &&
3356 $this->mEmailToken
&&
3357 $this->mEmailTokenExpires
> wfTimestamp();
3361 * Get the timestamp of account creation.
3363 * @return String|Bool Timestamp of account creation, or false for
3364 * non-existent/anonymous user accounts.
3366 public function getRegistration() {
3367 if ( $this->isAnon() ) {
3371 return $this->mRegistration
;
3375 * Get the timestamp of the first edit
3377 * @return String|Bool Timestamp of first edit, or false for
3378 * non-existent/anonymous user accounts.
3380 public function getFirstEditTimestamp() {
3381 if( $this->getId() == 0 ) {
3382 return false; // anons
3384 $dbr = wfGetDB( DB_SLAVE
);
3385 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3386 array( 'rev_user' => $this->getId() ),
3388 array( 'ORDER BY' => 'rev_timestamp ASC' )
3391 return false; // no edits
3393 return wfTimestamp( TS_MW
, $time );
3397 * Get the permissions associated with a given list of groups
3399 * @param $groups Array of Strings List of internal group names
3400 * @return Array of Strings List of permission key names for given groups combined
3402 public static function getGroupPermissions( $groups, $ns = null ) {
3403 global $wgGroupPermissions, $wgRevokePermissions;
3406 // Grant every granted permission first
3407 foreach( $groups as $group ) {
3408 if( isset( $wgGroupPermissions[$group] ) ) {
3409 $rights = array_merge( $rights, self
::extractRights(
3410 $wgGroupPermissions[$group], $ns ) );
3414 // Revoke the revoked permissions
3415 foreach( $groups as $group ) {
3416 if( isset( $wgRevokePermissions[$group] ) ) {
3417 $rights = array_diff( $rights, self
::extractRights(
3418 $wgRevokePermissions[$group], $ns ) );
3421 return array_unique( $rights );
3425 * Helper for User::getGroupPermissions
3426 * @param array $list
3430 private static function extractRights( $list, $ns ) {
3432 foreach( $list as $right => $value ) {
3433 if ( is_array( $value ) ) {
3434 # This is a list of namespaces where the permission applies
3435 if ( !is_null( $ns ) && !empty( $value[$ns] ) ) {
3439 # This is a boolean indicating that the permission applies
3449 * Get all the groups who have a given permission
3451 * @param $role String Role to check
3452 * @return Array of Strings List of internal group names with the given permission
3454 public static function getGroupsWithPermission( $role, $ns = null ) {
3455 global $wgGroupPermissions;
3456 $allowedGroups = array();
3457 foreach ( $wgGroupPermissions as $group => $rights ) {
3458 if ( in_array( $role, self
::getGroupPermissions( array( $group ), $ns ), true ) ) {
3459 $allowedGroups[] = $group;
3462 return $allowedGroups;
3466 * Get the localized descriptive name for a group, if it exists
3468 * @param $group String Internal group name
3469 * @return String Localized descriptive group name
3471 public static function getGroupName( $group ) {
3472 $msg = wfMessage( "group-$group" );
3473 return $msg->isBlank() ?
$group : $msg->text();
3477 * Get the localized descriptive name for a member of a group, if it exists
3479 * @param $group String Internal group name
3480 * @return String Localized name for group member
3482 public static function getGroupMember( $group ) {
3483 $msg = wfMessage( "group-$group-member" );
3484 return $msg->isBlank() ?
$group : $msg->text();
3488 * Return the set of defined explicit groups.
3489 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3490 * are not included, as they are defined automatically, not in the database.
3491 * @return Array of internal group names
3493 public static function getAllGroups() {
3494 global $wgGroupPermissions, $wgRevokePermissions;
3496 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3497 self
::getImplicitGroups()
3502 * Get a list of all available permissions.
3503 * @return Array of permission names
3505 public static function getAllRights() {
3506 if ( self
::$mAllRights === false ) {
3507 global $wgAvailableRights;
3508 if ( count( $wgAvailableRights ) ) {
3509 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
3511 self
::$mAllRights = self
::$mCoreRights;
3513 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
3515 return self
::$mAllRights;
3519 * Get a list of implicit groups
3520 * @return Array of Strings Array of internal group names
3522 public static function getImplicitGroups() {
3523 global $wgImplicitGroups;
3524 $groups = $wgImplicitGroups;
3525 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3530 * Get the title of a page describing a particular group
3532 * @param $group String Internal group name
3533 * @return Title|Bool Title of the page if it exists, false otherwise
3535 public static function getGroupPage( $group ) {
3536 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
3537 if( $msg->exists() ) {
3538 $title = Title
::newFromText( $msg->text() );
3539 if( is_object( $title ) )
3546 * Create a link to the group in HTML, if available;
3547 * else return the group name.
3549 * @param $group String Internal name of the group
3550 * @param $text String The text of the link
3551 * @return String HTML link to the group
3553 public static function makeGroupLinkHTML( $group, $text = '' ) {
3555 $text = self
::getGroupName( $group );
3557 $title = self
::getGroupPage( $group );
3559 return Linker
::link( $title, htmlspecialchars( $text ) );
3566 * Create a link to the group in Wikitext, if available;
3567 * else return the group name.
3569 * @param $group String Internal name of the group
3570 * @param $text String The text of the link
3571 * @return String Wikilink to the group
3573 public static function makeGroupLinkWiki( $group, $text = '' ) {
3575 $text = self
::getGroupName( $group );
3577 $title = self
::getGroupPage( $group );
3579 $page = $title->getPrefixedText();
3580 return "[[$page|$text]]";
3587 * Returns an array of the groups that a particular group can add/remove.
3589 * @param $group String: the group to check for whether it can add/remove
3590 * @return Array array( 'add' => array( addablegroups ),
3591 * 'remove' => array( removablegroups ),
3592 * 'add-self' => array( addablegroups to self),
3593 * 'remove-self' => array( removable groups from self) )
3595 public static function changeableByGroup( $group ) {
3596 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
3598 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
3599 if( empty( $wgAddGroups[$group] ) ) {
3600 // Don't add anything to $groups
3601 } elseif( $wgAddGroups[$group] === true ) {
3602 // You get everything
3603 $groups['add'] = self
::getAllGroups();
3604 } elseif( is_array( $wgAddGroups[$group] ) ) {
3605 $groups['add'] = $wgAddGroups[$group];
3608 // Same thing for remove
3609 if( empty( $wgRemoveGroups[$group] ) ) {
3610 } elseif( $wgRemoveGroups[$group] === true ) {
3611 $groups['remove'] = self
::getAllGroups();
3612 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
3613 $groups['remove'] = $wgRemoveGroups[$group];
3616 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
3617 if( empty( $wgGroupsAddToSelf['user']) ||
$wgGroupsAddToSelf['user'] !== true ) {
3618 foreach( $wgGroupsAddToSelf as $key => $value ) {
3619 if( is_int( $key ) ) {
3620 $wgGroupsAddToSelf['user'][] = $value;
3625 if( empty( $wgGroupsRemoveFromSelf['user']) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
3626 foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
3627 if( is_int( $key ) ) {
3628 $wgGroupsRemoveFromSelf['user'][] = $value;
3633 // Now figure out what groups the user can add to him/herself
3634 if( empty( $wgGroupsAddToSelf[$group] ) ) {
3635 } elseif( $wgGroupsAddToSelf[$group] === true ) {
3636 // No idea WHY this would be used, but it's there
3637 $groups['add-self'] = User
::getAllGroups();
3638 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
3639 $groups['add-self'] = $wgGroupsAddToSelf[$group];
3642 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
3643 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
3644 $groups['remove-self'] = User
::getAllGroups();
3645 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
3646 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
3653 * Returns an array of groups that this user can add and remove
3654 * @return Array array( 'add' => array( addablegroups ),
3655 * 'remove' => array( removablegroups ),
3656 * 'add-self' => array( addablegroups to self),
3657 * 'remove-self' => array( removable groups from self) )
3659 public function changeableGroups() {
3660 if( $this->isAllowed( 'userrights' ) ) {
3661 // This group gives the right to modify everything (reverse-
3662 // compatibility with old "userrights lets you change
3664 // Using array_merge to make the groups reindexed
3665 $all = array_merge( User
::getAllGroups() );
3669 'add-self' => array(),
3670 'remove-self' => array()
3674 // Okay, it's not so simple, we will have to go through the arrays
3677 'remove' => array(),
3678 'add-self' => array(),
3679 'remove-self' => array()
3681 $addergroups = $this->getEffectiveGroups();
3683 foreach( $addergroups as $addergroup ) {
3684 $groups = array_merge_recursive(
3685 $groups, $this->changeableByGroup( $addergroup )
3687 $groups['add'] = array_unique( $groups['add'] );
3688 $groups['remove'] = array_unique( $groups['remove'] );
3689 $groups['add-self'] = array_unique( $groups['add-self'] );
3690 $groups['remove-self'] = array_unique( $groups['remove-self'] );
3696 * Increment the user's edit-count field.
3697 * Will have no effect for anonymous users.
3699 public function incEditCount() {
3700 if( !$this->isAnon() ) {
3701 $dbw = wfGetDB( DB_MASTER
);
3702 $dbw->update( 'user',
3703 array( 'user_editcount=user_editcount+1' ),
3704 array( 'user_id' => $this->getId() ),
3707 // Lazy initialization check...
3708 if( $dbw->affectedRows() == 0 ) {
3709 // Pull from a slave to be less cruel to servers
3710 // Accuracy isn't the point anyway here
3711 $dbr = wfGetDB( DB_SLAVE
);
3712 $count = $dbr->selectField( 'revision',
3714 array( 'rev_user' => $this->getId() ),
3717 // Now here's a goddamn hack...
3718 if( $dbr !== $dbw ) {
3719 // If we actually have a slave server, the count is
3720 // at least one behind because the current transaction
3721 // has not been committed and replicated.
3724 // But if DB_SLAVE is selecting the master, then the
3725 // count we just read includes the revision that was
3726 // just added in the working transaction.
3729 $dbw->update( 'user',
3730 array( 'user_editcount' => $count ),
3731 array( 'user_id' => $this->getId() ),
3735 // edit count in user cache too
3736 $this->invalidateCache();
3740 * Get the description of a given right
3742 * @param $right String Right to query
3743 * @return String Localized description of the right
3745 public static function getRightDescription( $right ) {
3746 $key = "right-$right";
3747 $msg = wfMessage( $key );
3748 return $msg->isBlank() ?
$right : $msg->text();
3752 * Make an old-style password hash
3754 * @param $password String Plain-text password
3755 * @param $userId String User ID
3756 * @return String Password hash
3758 public static function oldCrypt( $password, $userId ) {
3759 global $wgPasswordSalt;
3760 if ( $wgPasswordSalt ) {
3761 return md5( $userId . '-' . md5( $password ) );
3763 return md5( $password );
3768 * Make a new-style password hash
3770 * @param $password String Plain-text password
3771 * @param $salt String Optional salt, may be random or the user ID.
3772 * If unspecified or false, will generate one automatically
3773 * @return String Password hash
3775 public static function crypt( $password, $salt = false ) {
3776 global $wgPasswordSalt;
3779 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3783 if( $wgPasswordSalt ) {
3784 if ( $salt === false ) {
3785 $salt = substr( wfGenerateToken(), 0, 8 );
3787 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3789 return ':A:' . md5( $password );
3794 * Compare a password hash with a plain-text password. Requires the user
3795 * ID if there's a chance that the hash is an old-style hash.
3797 * @param $hash String Password hash
3798 * @param $password String Plain-text password to compare
3799 * @param $userId String User ID for old-style password salt
3802 public static function comparePasswords( $hash, $password, $userId = false ) {
3803 $type = substr( $hash, 0, 3 );
3806 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3810 if ( $type == ':A:' ) {
3812 return md5( $password ) === substr( $hash, 3 );
3813 } elseif ( $type == ':B:' ) {
3815 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3816 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3819 return self
::oldCrypt( $password, $userId ) === $hash;
3824 * Add a newuser log entry for this user
3826 * @param $byEmail Boolean: account made by email?
3827 * @param $reason String: user supplied reason
3831 public function addNewUserLogEntry( $byEmail = false, $reason = '' ) {
3832 global $wgUser, $wgContLang, $wgNewUserLog;
3833 if( empty( $wgNewUserLog ) ) {
3834 return true; // disabled
3837 if( $this->getName() == $wgUser->getName() ) {
3840 $action = 'create2';
3842 if ( $reason === '' ) {
3843 $reason = wfMsgForContent( 'newuserlog-byemail' );
3845 $reason = $wgContLang->commaList( array(
3846 $reason, wfMsgForContent( 'newuserlog-byemail' ) ) );
3850 $log = new LogPage( 'newusers' );
3853 $this->getUserPage(),
3855 array( $this->getId() )
3861 * Add an autocreate newuser log entry for this user
3862 * Used by things like CentralAuth and perhaps other authplugins.
3866 public function addNewUserLogEntryAutoCreate() {
3867 global $wgNewUserLog;
3868 if( !$wgNewUserLog ) {
3869 return true; // disabled
3871 $log = new LogPage( 'newusers', false );
3872 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3876 protected function loadOptions() {
3878 if ( $this->mOptionsLoaded ||
!$this->getId() )
3881 $this->mOptions
= self
::getDefaultOptions();
3883 // Maybe load from the object
3884 if ( !is_null( $this->mOptionOverrides
) ) {
3885 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
3886 foreach( $this->mOptionOverrides
as $key => $value ) {
3887 $this->mOptions
[$key] = $value;
3890 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
3891 // Load from database
3892 $dbr = wfGetDB( DB_SLAVE
);
3894 $res = $dbr->select(
3897 array( 'up_user' => $this->getId() ),
3901 foreach ( $res as $row ) {
3902 $this->mOptionOverrides
[$row->up_property
] = $row->up_value
;
3903 $this->mOptions
[$row->up_property
] = $row->up_value
;
3907 $this->mOptionsLoaded
= true;
3909 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
3912 protected function saveOptions() {
3913 global $wgAllowPrefChange;
3915 $extuser = ExternalUser
::newFromUser( $this );
3917 $this->loadOptions();
3918 $dbw = wfGetDB( DB_MASTER
);
3920 $insert_rows = array();
3922 $saveOptions = $this->mOptions
;
3924 // Allow hooks to abort, for instance to save to a global profile.
3925 // Reset options to default state before saving.
3926 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) )
3929 foreach( $saveOptions as $key => $value ) {
3930 # Don't bother storing default values
3931 if ( ( is_null( self
::getDefaultOption( $key ) ) &&
3932 !( $value === false ||
is_null($value) ) ) ||
3933 $value != self
::getDefaultOption( $key ) ) {
3934 $insert_rows[] = array(
3935 'up_user' => $this->getId(),
3936 'up_property' => $key,
3937 'up_value' => $value,
3940 if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
3941 switch ( $wgAllowPrefChange[$key] ) {
3947 $extuser->setPref( $key, $value );
3953 $dbw->delete( 'user_properties', array( 'up_user' => $this->getId() ), __METHOD__
);
3954 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
);
3959 * Provide an array of HTML5 attributes to put on an input element
3960 * intended for the user to enter a new password. This may include
3961 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
3963 * Do *not* use this when asking the user to enter his current password!
3964 * Regardless of configuration, users may have invalid passwords for whatever
3965 * reason (e.g., they were set before requirements were tightened up).
3966 * Only use it when asking for a new password, like on account creation or
3969 * Obviously, you still need to do server-side checking.
3971 * NOTE: A combination of bugs in various browsers means that this function
3972 * actually just returns array() unconditionally at the moment. May as
3973 * well keep it around for when the browser bugs get fixed, though.
3975 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
3977 * @return array Array of HTML attributes suitable for feeding to
3978 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
3979 * That will potentially output invalid XHTML 1.0 Transitional, and will
3980 * get confused by the boolean attribute syntax used.)
3982 public static function passwordChangeInputAttribs() {
3983 global $wgMinimalPasswordLength;
3985 if ( $wgMinimalPasswordLength == 0 ) {
3989 # Note that the pattern requirement will always be satisfied if the
3990 # input is empty, so we need required in all cases.
3992 # @todo FIXME: Bug 23769: This needs to not claim the password is required
3993 # if e-mail confirmation is being used. Since HTML5 input validation
3994 # is b0rked anyway in some browsers, just return nothing. When it's
3995 # re-enabled, fix this code to not output required for e-mail
3997 #$ret = array( 'required' );
4000 # We can't actually do this right now, because Opera 9.6 will print out
4001 # the entered password visibly in its error message! When other
4002 # browsers add support for this attribute, or Opera fixes its support,
4003 # we can add support with a version check to avoid doing this on Opera
4004 # versions where it will be a problem. Reported to Opera as
4005 # DSK-262266, but they don't have a public bug tracker for us to follow.
4007 if ( $wgMinimalPasswordLength > 1 ) {
4008 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4009 $ret['title'] = wfMsgExt( 'passwordtooshort', 'parsemag',
4010 $wgMinimalPasswordLength );