Localisation updates from http://translatewiki.net.
[mediawiki.git] / includes / User.php
blob685bce741fdad24a97a94e622c9e94f062807a4b
1 <?php
2 /**
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
20 * @file
23 /**
24 * Int Number of characters in user_token field.
25 * @ingroup Constants
27 define( 'USER_TOKEN_LENGTH', 32 );
29 /**
30 * Int Serialized record version.
31 * @ingroup Constants
33 define( 'MW_USER_VERSION', 8 );
35 /**
36 * String Some punctuation to prevent editing from broken text-mangling proxies.
37 * @ingroup Constants
39 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
41 /**
42 * Thrown by User::setPassword() on error.
43 * @ingroup Exception
45 class PasswordError extends MWException {
46 // NOP
49 /**
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
57 * of the database.
59 class User {
60 /**
61 * Global constants made accessible as class constants so that autoloader
62 * magic can be used.
64 const USER_TOKEN_LENGTH = USER_TOKEN_LENGTH;
65 const MW_USER_VERSION = MW_USER_VERSION;
66 const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
68 /**
69 * Maximum items in $mWatchedItems
71 const MAX_WATCHED_ITEMS_CACHE = 100;
73 /**
74 * Array of Strings List of member variables which are saved to the
75 * shared cache (memcached). Any operation which changes the
76 * corresponding database fields must call a cache-clearing function.
77 * @showinitializer
79 static $mCacheVars = array(
80 // user table
81 'mId',
82 'mName',
83 'mRealName',
84 'mPassword',
85 'mNewpassword',
86 'mNewpassTime',
87 'mEmail',
88 'mTouched',
89 'mToken',
90 'mEmailAuthenticated',
91 'mEmailToken',
92 'mEmailTokenExpires',
93 'mRegistration',
94 'mEditCount',
95 // user_groups table
96 'mGroups',
97 // user_properties table
98 'mOptionOverrides',
102 * Array of Strings Core rights.
103 * Each of these should have a corresponding message of the form
104 * "right-$right".
105 * @showinitializer
107 static $mCoreRights = array(
108 'apihighlimits',
109 'autoconfirmed',
110 'autopatrol',
111 'bigdelete',
112 'block',
113 'blockemail',
114 'bot',
115 'browsearchive',
116 'createaccount',
117 'createpage',
118 'createtalk',
119 'delete',
120 'deletedhistory',
121 'deletedtext',
122 'deletelogentry',
123 'deleterevision',
124 'edit',
125 'editinterface',
126 'editprotected',
127 'editmyoptions',
128 'editmyprivateinfo',
129 'editmyusercss',
130 'editmyuserjs',
131 'editmywatchlist',
132 'editsemiprotected',
133 'editusercssjs', #deprecated
134 'editusercss',
135 'edituserjs',
136 'hideuser',
137 'import',
138 'importupload',
139 'ipblock-exempt',
140 'markbotedits',
141 'mergehistory',
142 'minoredit',
143 'move',
144 'movefile',
145 'move-rootuserpages',
146 'move-subpages',
147 'nominornewtalk',
148 'noratelimit',
149 'override-export-depth',
150 'passwordreset',
151 'patrol',
152 'patrolmarks',
153 'protect',
154 'proxyunbannable',
155 'purge',
156 'read',
157 'reupload',
158 'reupload-own',
159 'reupload-shared',
160 'rollback',
161 'sendemail',
162 'siteadmin',
163 'suppressionlog',
164 'suppressredirect',
165 'suppressrevision',
166 'unblockself',
167 'undelete',
168 'unwatchedpages',
169 'upload',
170 'upload_by_url',
171 'userrights',
172 'userrights-interwiki',
173 'viewmyprivateinfo',
174 'viewmywatchlist',
175 'writeapi',
178 * String Cached results of getAllRights()
180 static $mAllRights = false;
182 /** @name Cache variables */
183 //@{
184 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
185 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
186 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mEditCount,
187 $mGroups, $mOptionOverrides;
188 //@}
191 * Bool Whether the cache variables have been loaded.
193 //@{
194 var $mOptionsLoaded;
197 * Array with already loaded items or true if all items have been loaded.
199 private $mLoadedItems = array();
200 //@}
203 * String Initialization data source if mLoadedItems!==true. May be one of:
204 * - 'defaults' anonymous user initialised from class defaults
205 * - 'name' initialise from mName
206 * - 'id' initialise from mId
207 * - 'session' log in from cookies or session if possible
209 * Use the User::newFrom*() family of functions to set this.
211 var $mFrom;
214 * Lazy-initialized variables, invalidated with clearInstanceCache
216 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mRights,
217 $mBlockreason, $mEffectiveGroups, $mImplicitGroups, $mFormerGroups, $mBlockedGlobally,
218 $mLocked, $mHideName, $mOptions;
221 * @var WebRequest
223 private $mRequest;
226 * @var Block
228 var $mBlock;
231 * @var bool
233 var $mAllowUsertalk;
236 * @var Block
238 private $mBlockedFromCreateAccount = false;
241 * @var Array
243 private $mWatchedItems = array();
245 static $idCacheByName = array();
248 * Lightweight constructor for an anonymous user.
249 * Use the User::newFrom* factory functions for other kinds of users.
251 * @see newFromName()
252 * @see newFromId()
253 * @see newFromConfirmationCode()
254 * @see newFromSession()
255 * @see newFromRow()
257 function __construct() {
258 $this->clearInstanceCache( 'defaults' );
262 * @return string
264 function __toString() {
265 return $this->getName();
269 * Load the user table data for this object from the source given by mFrom.
271 public function load() {
272 if ( $this->mLoadedItems === true ) {
273 return;
275 wfProfileIn( __METHOD__ );
277 // Set it now to avoid infinite recursion in accessors
278 $this->mLoadedItems = true;
280 switch ( $this->mFrom ) {
281 case 'defaults':
282 $this->loadDefaults();
283 break;
284 case 'name':
285 $this->mId = self::idFromName( $this->mName );
286 if ( !$this->mId ) {
287 // Nonexistent user placeholder object
288 $this->loadDefaults( $this->mName );
289 } else {
290 $this->loadFromId();
292 break;
293 case 'id':
294 $this->loadFromId();
295 break;
296 case 'session':
297 if ( !$this->loadFromSession() ) {
298 // Loading from session failed. Load defaults.
299 $this->loadDefaults();
301 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
302 break;
303 default:
304 wfProfileOut( __METHOD__ );
305 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
307 wfProfileOut( __METHOD__ );
311 * Load user table data, given mId has already been set.
312 * @return bool false if the ID does not exist, true otherwise
314 public function loadFromId() {
315 global $wgMemc;
316 if ( $this->mId == 0 ) {
317 $this->loadDefaults();
318 return false;
321 // Try cache
322 $key = wfMemcKey( 'user', 'id', $this->mId );
323 $data = $wgMemc->get( $key );
324 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
325 // Object is expired, load from DB
326 $data = false;
329 if ( !$data ) {
330 wfDebug( "User: cache miss for user {$this->mId}\n" );
331 // Load from DB
332 if ( !$this->loadFromDatabase() ) {
333 // Can't load from ID, user is anonymous
334 return false;
336 $this->saveToCache();
337 } else {
338 wfDebug( "User: got user {$this->mId} from cache\n" );
339 // Restore from cache
340 foreach ( self::$mCacheVars as $name ) {
341 $this->$name = $data[$name];
345 $this->mLoadedItems = true;
347 return true;
351 * Save user data to the shared cache
353 public function saveToCache() {
354 $this->load();
355 $this->loadGroups();
356 $this->loadOptions();
357 if ( $this->isAnon() ) {
358 // Anonymous users are uncached
359 return;
361 $data = array();
362 foreach ( self::$mCacheVars as $name ) {
363 $data[$name] = $this->$name;
365 $data['mVersion'] = MW_USER_VERSION;
366 $key = wfMemcKey( 'user', 'id', $this->mId );
367 global $wgMemc;
368 $wgMemc->set( $key, $data );
371 /** @name newFrom*() static factory methods */
372 //@{
375 * Static factory method for creation from username.
377 * This is slightly less efficient than newFromId(), so use newFromId() if
378 * you have both an ID and a name handy.
380 * @param string $name Username, validated by Title::newFromText()
381 * @param string|bool $validate Validate username. Takes the same parameters as
382 * User::getCanonicalName(), except that true is accepted as an alias
383 * for 'valid', for BC.
385 * @return User|bool User object, or false if the username is invalid
386 * (e.g. if it contains illegal characters or is an IP address). If the
387 * username is not present in the database, the result will be a user object
388 * with a name, zero user ID and default settings.
390 public static function newFromName( $name, $validate = 'valid' ) {
391 if ( $validate === true ) {
392 $validate = 'valid';
394 $name = self::getCanonicalName( $name, $validate );
395 if ( $name === false ) {
396 return false;
397 } else {
398 // Create unloaded user object
399 $u = new User;
400 $u->mName = $name;
401 $u->mFrom = 'name';
402 $u->setItemLoaded( 'name' );
403 return $u;
408 * Static factory method for creation from a given user ID.
410 * @param int $id Valid user ID
411 * @return User The corresponding User object
413 public static function newFromId( $id ) {
414 $u = new User;
415 $u->mId = $id;
416 $u->mFrom = 'id';
417 $u->setItemLoaded( 'id' );
418 return $u;
422 * Factory method to fetch whichever user has a given email confirmation code.
423 * This code is generated when an account is created or its e-mail address
424 * has changed.
426 * If the code is invalid or has expired, returns NULL.
428 * @param string $code Confirmation code
429 * @return User|null
431 public static function newFromConfirmationCode( $code ) {
432 $dbr = wfGetDB( DB_SLAVE );
433 $id = $dbr->selectField( 'user', 'user_id', array(
434 'user_email_token' => md5( $code ),
435 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
436 ) );
437 if ( $id !== false ) {
438 return User::newFromId( $id );
439 } else {
440 return null;
445 * Create a new user object using data from session or cookies. If the
446 * login credentials are invalid, the result is an anonymous user.
448 * @param WebRequest $request Object to use; $wgRequest will be used if omitted.
449 * @return User object
451 public static function newFromSession( WebRequest $request = null ) {
452 $user = new User;
453 $user->mFrom = 'session';
454 $user->mRequest = $request;
455 return $user;
459 * Create a new user object from a user row.
460 * The row should have the following fields from the user table in it:
461 * - either user_name or user_id to load further data if needed (or both)
462 * - user_real_name
463 * - all other fields (email, password, etc.)
464 * It is useless to provide the remaining fields if either user_id,
465 * user_name and user_real_name are not provided because the whole row
466 * will be loaded once more from the database when accessing them.
468 * @param array $row A row from the user table
469 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
470 * @return User
472 public static function newFromRow( $row, $data = null ) {
473 $user = new User;
474 $user->loadFromRow( $row, $data );
475 return $user;
478 //@}
481 * Get the username corresponding to a given user ID
482 * @param int $id User ID
483 * @return string|bool The corresponding username
485 public static function whoIs( $id ) {
486 return UserCache::singleton()->getProp( $id, 'name' );
490 * Get the real name of a user given their user ID
492 * @param int $id User ID
493 * @return string|bool The corresponding user's real name
495 public static function whoIsReal( $id ) {
496 return UserCache::singleton()->getProp( $id, 'real_name' );
500 * Get database id given a user name
501 * @param string $name Username
502 * @return int|null The corresponding user's ID, or null if user is nonexistent
504 public static function idFromName( $name ) {
505 $nt = Title::makeTitleSafe( NS_USER, $name );
506 if ( is_null( $nt ) ) {
507 // Illegal name
508 return null;
511 if ( isset( self::$idCacheByName[$name] ) ) {
512 return self::$idCacheByName[$name];
515 $dbr = wfGetDB( DB_SLAVE );
516 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
518 if ( $s === false ) {
519 $result = null;
520 } else {
521 $result = $s->user_id;
524 self::$idCacheByName[$name] = $result;
526 if ( count( self::$idCacheByName ) > 1000 ) {
527 self::$idCacheByName = array();
530 return $result;
534 * Reset the cache used in idFromName(). For use in tests.
536 public static function resetIdByNameCache() {
537 self::$idCacheByName = array();
541 * Does the string match an anonymous IPv4 address?
543 * This function exists for username validation, in order to reject
544 * usernames which are similar in form to IP addresses. Strings such
545 * as 300.300.300.300 will return true because it looks like an IP
546 * address, despite not being strictly valid.
548 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
549 * address because the usemod software would "cloak" anonymous IP
550 * addresses like this, if we allowed accounts like this to be created
551 * new users could get the old edits of these anonymous users.
553 * @param string $name Name to match
554 * @return bool
556 public static function isIP( $name ) {
557 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name ) || IP::isIPv6( $name );
561 * Is the input a valid username?
563 * Checks if the input is a valid username, we don't want an empty string,
564 * an IP address, anything that contains slashes (would mess up subpages),
565 * is longer than the maximum allowed username size or doesn't begin with
566 * a capital letter.
568 * @param string $name Name to match
569 * @return bool
571 public static function isValidUserName( $name ) {
572 global $wgContLang, $wgMaxNameChars;
574 if ( $name == ''
575 || User::isIP( $name )
576 || strpos( $name, '/' ) !== false
577 || strlen( $name ) > $wgMaxNameChars
578 || $name != $wgContLang->ucfirst( $name ) ) {
579 wfDebugLog( 'username', __METHOD__ .
580 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
581 return false;
584 // Ensure that the name can't be misresolved as a different title,
585 // such as with extra namespace keys at the start.
586 $parsed = Title::newFromText( $name );
587 if ( is_null( $parsed )
588 || $parsed->getNamespace()
589 || strcmp( $name, $parsed->getPrefixedText() ) ) {
590 wfDebugLog( 'username', __METHOD__ .
591 ": '$name' invalid due to ambiguous prefixes" );
592 return false;
595 // Check an additional blacklist of troublemaker characters.
596 // Should these be merged into the title char list?
597 $unicodeBlacklist = '/[' .
598 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
599 '\x{00a0}' . # non-breaking space
600 '\x{2000}-\x{200f}' . # various whitespace
601 '\x{2028}-\x{202f}' . # breaks and control chars
602 '\x{3000}' . # ideographic space
603 '\x{e000}-\x{f8ff}' . # private use
604 ']/u';
605 if ( preg_match( $unicodeBlacklist, $name ) ) {
606 wfDebugLog( 'username', __METHOD__ .
607 ": '$name' invalid due to blacklisted characters" );
608 return false;
611 return true;
615 * Usernames which fail to pass this function will be blocked
616 * from user login and new account registrations, but may be used
617 * internally by batch processes.
619 * If an account already exists in this form, login will be blocked
620 * by a failure to pass this function.
622 * @param string $name Name to match
623 * @return bool
625 public static function isUsableName( $name ) {
626 global $wgReservedUsernames;
627 // Must be a valid username, obviously ;)
628 if ( !self::isValidUserName( $name ) ) {
629 return false;
632 static $reservedUsernames = false;
633 if ( !$reservedUsernames ) {
634 $reservedUsernames = $wgReservedUsernames;
635 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
638 // Certain names may be reserved for batch processes.
639 foreach ( $reservedUsernames as $reserved ) {
640 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
641 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
643 if ( $reserved == $name ) {
644 return false;
647 return true;
651 * Usernames which fail to pass this function will be blocked
652 * from new account registrations, but may be used internally
653 * either by batch processes or by user accounts which have
654 * already been created.
656 * Additional blacklisting may be added here rather than in
657 * isValidUserName() to avoid disrupting existing accounts.
659 * @param string $name to match
660 * @return bool
662 public static function isCreatableName( $name ) {
663 global $wgInvalidUsernameCharacters;
665 // Ensure that the username isn't longer than 235 bytes, so that
666 // (at least for the builtin skins) user javascript and css files
667 // will work. (bug 23080)
668 if ( strlen( $name ) > 235 ) {
669 wfDebugLog( 'username', __METHOD__ .
670 ": '$name' invalid due to length" );
671 return false;
674 // Preg yells if you try to give it an empty string
675 if ( $wgInvalidUsernameCharacters !== '' ) {
676 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
677 wfDebugLog( 'username', __METHOD__ .
678 ": '$name' invalid due to wgInvalidUsernameCharacters" );
679 return false;
683 return self::isUsableName( $name );
687 * Is the input a valid password for this user?
689 * @param string $password Desired password
690 * @return bool
692 public function isValidPassword( $password ) {
693 //simple boolean wrapper for getPasswordValidity
694 return $this->getPasswordValidity( $password ) === true;
698 * Given unvalidated password input, return error message on failure.
700 * @param string $password Desired password
701 * @return mixed: true on success, string or array of error message on failure
703 public function getPasswordValidity( $password ) {
704 global $wgMinimalPasswordLength, $wgContLang;
706 static $blockedLogins = array(
707 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
708 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
711 $result = false; //init $result to false for the internal checks
713 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
714 return $result;
717 if ( $result === false ) {
718 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
719 return 'passwordtooshort';
720 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) {
721 return 'password-name-match';
722 } elseif ( isset( $blockedLogins[$this->getName()] ) && $password == $blockedLogins[$this->getName()] ) {
723 return 'password-login-forbidden';
724 } else {
725 //it seems weird returning true here, but this is because of the
726 //initialization of $result to false above. If the hook is never run or it
727 //doesn't modify $result, then we will likely get down into this if with
728 //a valid password.
729 return true;
731 } elseif ( $result === true ) {
732 return true;
733 } else {
734 return $result; //the isValidPassword hook set a string $result and returned true
739 * Does a string look like an e-mail address?
741 * This validates an email address using an HTML5 specification found at:
742 * http://www.whatwg.org/html/states-of-the-type-attribute.html#valid-e-mail-address
743 * Which as of 2011-01-24 says:
745 * A valid e-mail address is a string that matches the ABNF production
746 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
747 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
748 * 3.5.
750 * This function is an implementation of the specification as requested in
751 * bug 22449.
753 * Client-side forms will use the same standard validation rules via JS or
754 * HTML 5 validation; additional restrictions can be enforced server-side
755 * by extensions via the 'isValidEmailAddr' hook.
757 * Note that this validation doesn't 100% match RFC 2822, but is believed
758 * to be liberal enough for wide use. Some invalid addresses will still
759 * pass validation here.
761 * @param string $addr E-mail address
762 * @return bool
763 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
765 public static function isValidEmailAddr( $addr ) {
766 wfDeprecated( __METHOD__, '1.18' );
767 return Sanitizer::validateEmail( $addr );
771 * Given unvalidated user input, return a canonical username, or false if
772 * the username is invalid.
773 * @param string $name User input
774 * @param string|bool $validate type of validation to use:
775 * - false No validation
776 * - 'valid' Valid for batch processes
777 * - 'usable' Valid for batch processes and login
778 * - 'creatable' Valid for batch processes, login and account creation
780 * @throws MWException
781 * @return bool|string
783 public static function getCanonicalName( $name, $validate = 'valid' ) {
784 // Force usernames to capital
785 global $wgContLang;
786 $name = $wgContLang->ucfirst( $name );
788 # Reject names containing '#'; these will be cleaned up
789 # with title normalisation, but then it's too late to
790 # check elsewhere
791 if ( strpos( $name, '#' ) !== false ) {
792 return false;
795 // Clean up name according to title rules
796 $t = ( $validate === 'valid' ) ?
797 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
798 // Check for invalid titles
799 if ( is_null( $t ) ) {
800 return false;
803 // Reject various classes of invalid names
804 global $wgAuth;
805 $name = $wgAuth->getCanonicalName( $t->getText() );
807 switch ( $validate ) {
808 case false:
809 break;
810 case 'valid':
811 if ( !User::isValidUserName( $name ) ) {
812 $name = false;
814 break;
815 case 'usable':
816 if ( !User::isUsableName( $name ) ) {
817 $name = false;
819 break;
820 case 'creatable':
821 if ( !User::isCreatableName( $name ) ) {
822 $name = false;
824 break;
825 default:
826 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
828 return $name;
832 * Count the number of edits of a user
834 * @param int $uid User ID to check
835 * @return int The user's edit count
837 * @deprecated since 1.21 in favour of User::getEditCount
839 public static function edits( $uid ) {
840 wfDeprecated( __METHOD__, '1.21' );
841 $user = self::newFromId( $uid );
842 return $user->getEditCount();
846 * Return a random password.
848 * @return string New random password
850 public static function randomPassword() {
851 global $wgMinimalPasswordLength;
852 // Decide the final password length based on our min password length, stopping at a minimum of 10 chars
853 $length = max( 10, $wgMinimalPasswordLength );
854 // Multiply by 1.25 to get the number of hex characters we need
855 $length = $length * 1.25;
856 // Generate random hex chars
857 $hex = MWCryptRand::generateHex( $length );
858 // Convert from base 16 to base 32 to get a proper password like string
859 return wfBaseConvert( $hex, 16, 32 );
863 * Set cached properties to default.
865 * @note This no longer clears uncached lazy-initialised properties;
866 * the constructor does that instead.
868 * @param $name string|bool
870 public function loadDefaults( $name = false ) {
871 wfProfileIn( __METHOD__ );
873 $this->mId = 0;
874 $this->mName = $name;
875 $this->mRealName = '';
876 $this->mPassword = $this->mNewpassword = '';
877 $this->mNewpassTime = null;
878 $this->mEmail = '';
879 $this->mOptionOverrides = null;
880 $this->mOptionsLoaded = false;
882 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
883 if ( $loggedOut !== null ) {
884 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
885 } else {
886 $this->mTouched = '1'; # Allow any pages to be cached
889 $this->mToken = null; // Don't run cryptographic functions till we need a token
890 $this->mEmailAuthenticated = null;
891 $this->mEmailToken = '';
892 $this->mEmailTokenExpires = null;
893 $this->mRegistration = wfTimestamp( TS_MW );
894 $this->mGroups = array();
896 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
898 wfProfileOut( __METHOD__ );
902 * Return whether an item has been loaded.
904 * @param string $item item to check. Current possibilities:
905 * - id
906 * - name
907 * - realname
908 * @param string $all 'all' to check if the whole object has been loaded
909 * or any other string to check if only the item is available (e.g.
910 * for optimisation)
911 * @return boolean
913 public function isItemLoaded( $item, $all = 'all' ) {
914 return ( $this->mLoadedItems === true && $all === 'all' ) ||
915 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
919 * Set that an item has been loaded
921 * @param string $item
923 protected function setItemLoaded( $item ) {
924 if ( is_array( $this->mLoadedItems ) ) {
925 $this->mLoadedItems[$item] = true;
930 * Load user data from the session or login cookie.
931 * @return bool True if the user is logged in, false otherwise.
933 private function loadFromSession() {
934 $result = null;
935 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
936 if ( $result !== null ) {
937 return $result;
940 $request = $this->getRequest();
942 $cookieId = $request->getCookie( 'UserID' );
943 $sessId = $request->getSessionData( 'wsUserID' );
945 if ( $cookieId !== null ) {
946 $sId = intval( $cookieId );
947 if ( $sessId !== null && $cookieId != $sessId ) {
948 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
949 cookie user ID ($sId) don't match!" );
950 return false;
952 $request->setSessionData( 'wsUserID', $sId );
953 } elseif ( $sessId !== null && $sessId != 0 ) {
954 $sId = $sessId;
955 } else {
956 return false;
959 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
960 $sName = $request->getSessionData( 'wsUserName' );
961 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
962 $sName = $request->getCookie( 'UserName' );
963 $request->setSessionData( 'wsUserName', $sName );
964 } else {
965 return false;
968 $proposedUser = User::newFromId( $sId );
969 if ( !$proposedUser->isLoggedIn() ) {
970 // Not a valid ID
971 return false;
974 global $wgBlockDisablesLogin;
975 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
976 // User blocked and we've disabled blocked user logins
977 return false;
980 if ( $request->getSessionData( 'wsToken' ) ) {
981 $passwordCorrect = ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
982 $from = 'session';
983 } elseif ( $request->getCookie( 'Token' ) ) {
984 # Get the token from DB/cache and clean it up to remove garbage padding.
985 # This deals with historical problems with bugs and the default column value.
986 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
987 $passwordCorrect = ( strlen( $token ) && $token === $request->getCookie( 'Token' ) );
988 $from = 'cookie';
989 } else {
990 // No session or persistent login cookie
991 return false;
994 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
995 $this->loadFromUserObject( $proposedUser );
996 $request->setSessionData( 'wsToken', $this->mToken );
997 wfDebug( "User: logged in from $from\n" );
998 return true;
999 } else {
1000 // Invalid credentials
1001 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1002 return false;
1007 * Load user and user_group data from the database.
1008 * $this->mId must be set, this is how the user is identified.
1010 * @return bool True if the user exists, false if the user is anonymous
1012 public function loadFromDatabase() {
1013 // Paranoia
1014 $this->mId = intval( $this->mId );
1016 // Anonymous user
1017 if ( !$this->mId ) {
1018 $this->loadDefaults();
1019 return false;
1022 $dbr = wfGetDB( DB_MASTER );
1023 $s = $dbr->selectRow( 'user', self::selectFields(), array( 'user_id' => $this->mId ), __METHOD__ );
1025 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1027 if ( $s !== false ) {
1028 // Initialise user table data
1029 $this->loadFromRow( $s );
1030 $this->mGroups = null; // deferred
1031 $this->getEditCount(); // revalidation for nulls
1032 return true;
1033 } else {
1034 // Invalid user_id
1035 $this->mId = 0;
1036 $this->loadDefaults();
1037 return false;
1042 * Initialize this object from a row from the user table.
1044 * @param array $row Row from the user table to load.
1045 * @param array $data Further user data to load into the object
1047 * user_groups Array with groups out of the user_groups table
1048 * user_properties Array with properties out of the user_properties table
1050 public function loadFromRow( $row, $data = null ) {
1051 $all = true;
1053 $this->mGroups = null; // deferred
1055 if ( isset( $row->user_name ) ) {
1056 $this->mName = $row->user_name;
1057 $this->mFrom = 'name';
1058 $this->setItemLoaded( 'name' );
1059 } else {
1060 $all = false;
1063 if ( isset( $row->user_real_name ) ) {
1064 $this->mRealName = $row->user_real_name;
1065 $this->setItemLoaded( 'realname' );
1066 } else {
1067 $all = false;
1070 if ( isset( $row->user_id ) ) {
1071 $this->mId = intval( $row->user_id );
1072 $this->mFrom = 'id';
1073 $this->setItemLoaded( 'id' );
1074 } else {
1075 $all = false;
1078 if ( isset( $row->user_editcount ) ) {
1079 $this->mEditCount = $row->user_editcount;
1080 } else {
1081 $all = false;
1084 if ( isset( $row->user_password ) ) {
1085 $this->mPassword = $row->user_password;
1086 $this->mNewpassword = $row->user_newpassword;
1087 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
1088 $this->mEmail = $row->user_email;
1089 if ( isset( $row->user_options ) ) {
1090 $this->decodeOptions( $row->user_options );
1092 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1093 $this->mToken = $row->user_token;
1094 if ( $this->mToken == '' ) {
1095 $this->mToken = null;
1097 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1098 $this->mEmailToken = $row->user_email_token;
1099 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1100 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1101 } else {
1102 $all = false;
1105 if ( $all ) {
1106 $this->mLoadedItems = true;
1109 if ( is_array( $data ) ) {
1110 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1111 $this->mGroups = $data['user_groups'];
1113 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1114 $this->loadOptions( $data['user_properties'] );
1120 * Load the data for this user object from another user object.
1122 * @param $user User
1124 protected function loadFromUserObject( $user ) {
1125 $user->load();
1126 $user->loadGroups();
1127 $user->loadOptions();
1128 foreach ( self::$mCacheVars as $var ) {
1129 $this->$var = $user->$var;
1134 * Load the groups from the database if they aren't already loaded.
1136 private function loadGroups() {
1137 if ( is_null( $this->mGroups ) ) {
1138 $dbr = wfGetDB( DB_MASTER );
1139 $res = $dbr->select( 'user_groups',
1140 array( 'ug_group' ),
1141 array( 'ug_user' => $this->mId ),
1142 __METHOD__ );
1143 $this->mGroups = array();
1144 foreach ( $res as $row ) {
1145 $this->mGroups[] = $row->ug_group;
1151 * Add the user to the group if he/she meets given criteria.
1153 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1154 * possible to remove manually via Special:UserRights. In such case it
1155 * will not be re-added automatically. The user will also not lose the
1156 * group if they no longer meet the criteria.
1158 * @param string $event key in $wgAutopromoteOnce (each one has groups/criteria)
1160 * @return array Array of groups the user has been promoted to.
1162 * @see $wgAutopromoteOnce
1164 public function addAutopromoteOnceGroups( $event ) {
1165 global $wgAutopromoteOnceLogInRC, $wgAuth;
1167 $toPromote = array();
1168 if ( $this->getId() ) {
1169 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1170 if ( count( $toPromote ) ) {
1171 $oldGroups = $this->getGroups(); // previous groups
1173 foreach ( $toPromote as $group ) {
1174 $this->addGroup( $group );
1176 // update groups in external authentication database
1177 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1179 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1181 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1182 $logEntry->setPerformer( $this );
1183 $logEntry->setTarget( $this->getUserPage() );
1184 $logEntry->setParameters( array(
1185 '4::oldgroups' => $oldGroups,
1186 '5::newgroups' => $newGroups,
1187 ) );
1188 $logid = $logEntry->insert();
1189 if ( $wgAutopromoteOnceLogInRC ) {
1190 $logEntry->publish( $logid );
1194 return $toPromote;
1198 * Clear various cached data stored in this object. The cache of the user table
1199 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1201 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1202 * given source. May be "name", "id", "defaults", "session", or false for
1203 * no reload.
1205 public function clearInstanceCache( $reloadFrom = false ) {
1206 $this->mNewtalk = -1;
1207 $this->mDatePreference = null;
1208 $this->mBlockedby = -1; # Unset
1209 $this->mHash = false;
1210 $this->mRights = null;
1211 $this->mEffectiveGroups = null;
1212 $this->mImplicitGroups = null;
1213 $this->mGroups = null;
1214 $this->mOptions = null;
1215 $this->mOptionsLoaded = false;
1216 $this->mEditCount = null;
1218 if ( $reloadFrom ) {
1219 $this->mLoadedItems = array();
1220 $this->mFrom = $reloadFrom;
1225 * Combine the language default options with any site-specific options
1226 * and add the default language variants.
1228 * @return Array of String options
1230 public static function getDefaultOptions() {
1231 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1233 static $defOpt = null;
1234 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1235 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1236 // mid-request and see that change reflected in the return value of this function.
1237 // Which is insane and would never happen during normal MW operation
1238 return $defOpt;
1241 $defOpt = $wgDefaultUserOptions;
1242 // Default language setting
1243 $defOpt['language'] = $defOpt['variant'] = $wgContLang->getCode();
1244 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1245 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1247 $defOpt['skin'] = $wgDefaultSkin;
1249 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1251 return $defOpt;
1255 * Get a given default option value.
1257 * @param string $opt Name of option to retrieve
1258 * @return string Default option value
1260 public static function getDefaultOption( $opt ) {
1261 $defOpts = self::getDefaultOptions();
1262 if ( isset( $defOpts[$opt] ) ) {
1263 return $defOpts[$opt];
1264 } else {
1265 return null;
1270 * Get blocking information
1271 * @param bool $bFromSlave Whether to check the slave database first. To
1272 * improve performance, non-critical checks are done
1273 * against slaves. Check when actually saving should be
1274 * done against master.
1276 private function getBlockedStatus( $bFromSlave = true ) {
1277 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1279 if ( -1 != $this->mBlockedby ) {
1280 return;
1283 wfProfileIn( __METHOD__ );
1284 wfDebug( __METHOD__ . ": checking...\n" );
1286 // Initialize data...
1287 // Otherwise something ends up stomping on $this->mBlockedby when
1288 // things get lazy-loaded later, causing false positive block hits
1289 // due to -1 !== 0. Probably session-related... Nothing should be
1290 // overwriting mBlockedby, surely?
1291 $this->load();
1293 # We only need to worry about passing the IP address to the Block generator if the
1294 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1295 # know which IP address they're actually coming from
1296 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1297 $ip = $this->getRequest()->getIP();
1298 } else {
1299 $ip = null;
1302 // User/IP blocking
1303 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1305 // Proxy blocking
1306 if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1307 && !in_array( $ip, $wgProxyWhitelist ) )
1309 // Local list
1310 if ( self::isLocallyBlockedProxy( $ip ) ) {
1311 $block = new Block;
1312 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1313 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1314 $block->setTarget( $ip );
1315 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1316 $block = new Block;
1317 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1318 $block->mReason = wfMessage( 'sorbsreason' )->text();
1319 $block->setTarget( $ip );
1323 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1324 if ( !$block instanceof Block
1325 && $wgApplyIpBlocksToXff
1326 && $ip !== null
1327 && !$this->isAllowed( 'proxyunbannable' )
1328 && !in_array( $ip, $wgProxyWhitelist )
1330 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1331 $xff = array_map( 'trim', explode( ',', $xff ) );
1332 $xff = array_diff( $xff, array( $ip ) );
1333 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1334 $block = Block::chooseBlock( $xffblocks, $xff );
1335 if ( $block instanceof Block ) {
1336 # Mangle the reason to alert the user that the block
1337 # originated from matching the X-Forwarded-For header.
1338 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1342 if ( $block instanceof Block ) {
1343 wfDebug( __METHOD__ . ": Found block.\n" );
1344 $this->mBlock = $block;
1345 $this->mBlockedby = $block->getByName();
1346 $this->mBlockreason = $block->mReason;
1347 $this->mHideName = $block->mHideName;
1348 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1349 } else {
1350 $this->mBlockedby = '';
1351 $this->mHideName = 0;
1352 $this->mAllowUsertalk = false;
1355 // Extensions
1356 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1358 wfProfileOut( __METHOD__ );
1362 * Whether the given IP is in a DNS blacklist.
1364 * @param string $ip IP to check
1365 * @param bool $checkWhitelist whether to check the whitelist first
1366 * @return bool True if blacklisted.
1368 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1369 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1370 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1372 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs ) {
1373 return false;
1376 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1377 return false;
1380 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1381 return $this->inDnsBlacklist( $ip, $urls );
1385 * Whether the given IP is in a given DNS blacklist.
1387 * @param string $ip IP to check
1388 * @param string|array $bases of Strings: URL of the DNS blacklist
1389 * @return bool True if blacklisted.
1391 public function inDnsBlacklist( $ip, $bases ) {
1392 wfProfileIn( __METHOD__ );
1394 $found = false;
1395 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1396 if ( IP::isIPv4( $ip ) ) {
1397 // Reverse IP, bug 21255
1398 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1400 foreach ( (array)$bases as $base ) {
1401 // Make hostname
1402 // If we have an access key, use that too (ProjectHoneypot, etc.)
1403 if ( is_array( $base ) ) {
1404 if ( count( $base ) >= 2 ) {
1405 // Access key is 1, base URL is 0
1406 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1407 } else {
1408 $host = "$ipReversed.{$base[0]}";
1410 } else {
1411 $host = "$ipReversed.$base";
1414 // Send query
1415 $ipList = gethostbynamel( $host );
1417 if ( $ipList ) {
1418 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1419 $found = true;
1420 break;
1421 } else {
1422 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base.\n" );
1427 wfProfileOut( __METHOD__ );
1428 return $found;
1432 * Check if an IP address is in the local proxy list
1434 * @param $ip string
1436 * @return bool
1438 public static function isLocallyBlockedProxy( $ip ) {
1439 global $wgProxyList;
1441 if ( !$wgProxyList ) {
1442 return false;
1444 wfProfileIn( __METHOD__ );
1446 if ( !is_array( $wgProxyList ) ) {
1447 // Load from the specified file
1448 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1451 if ( !is_array( $wgProxyList ) ) {
1452 $ret = false;
1453 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1454 $ret = true;
1455 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1456 // Old-style flipped proxy list
1457 $ret = true;
1458 } else {
1459 $ret = false;
1461 wfProfileOut( __METHOD__ );
1462 return $ret;
1466 * Is this user subject to rate limiting?
1468 * @return bool True if rate limited
1470 public function isPingLimitable() {
1471 global $wgRateLimitsExcludedIPs;
1472 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1473 // No other good way currently to disable rate limits
1474 // for specific IPs. :P
1475 // But this is a crappy hack and should die.
1476 return false;
1478 return !$this->isAllowed( 'noratelimit' );
1482 * Primitive rate limits: enforce maximum actions per time period
1483 * to put a brake on flooding.
1485 * @note When using a shared cache like memcached, IP-address
1486 * last-hit counters will be shared across wikis.
1488 * @param string $action Action to enforce; 'edit' if unspecified
1489 * @return bool True if a rate limiter was tripped
1491 public function pingLimiter( $action = 'edit' ) {
1492 // Call the 'PingLimiter' hook
1493 $result = false;
1494 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result ) ) ) {
1495 return $result;
1498 global $wgRateLimits;
1499 if ( !isset( $wgRateLimits[$action] ) ) {
1500 return false;
1503 // Some groups shouldn't trigger the ping limiter, ever
1504 if ( !$this->isPingLimitable() ) {
1505 return false;
1508 global $wgMemc, $wgRateLimitLog;
1509 wfProfileIn( __METHOD__ );
1511 $limits = $wgRateLimits[$action];
1512 $keys = array();
1513 $id = $this->getId();
1514 $userLimit = false;
1516 if ( isset( $limits['anon'] ) && $id == 0 ) {
1517 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1520 if ( isset( $limits['user'] ) && $id != 0 ) {
1521 $userLimit = $limits['user'];
1523 if ( $this->isNewbie() ) {
1524 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1525 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1527 if ( isset( $limits['ip'] ) ) {
1528 $ip = $this->getRequest()->getIP();
1529 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1531 if ( isset( $limits['subnet'] ) ) {
1532 $ip = $this->getRequest()->getIP();
1533 $matches = array();
1534 $subnet = false;
1535 if ( IP::isIPv6( $ip ) ) {
1536 $parts = IP::parseRange( "$ip/64" );
1537 $subnet = $parts[0];
1538 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1539 // IPv4
1540 $subnet = $matches[1];
1542 if ( $subnet !== false ) {
1543 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1547 // Check for group-specific permissions
1548 // If more than one group applies, use the group with the highest limit
1549 foreach ( $this->getGroups() as $group ) {
1550 if ( isset( $limits[$group] ) ) {
1551 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1552 $userLimit = $limits[$group];
1556 // Set the user limit key
1557 if ( $userLimit !== false ) {
1558 list( $max, $period ) = $userLimit;
1559 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1560 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1563 $triggered = false;
1564 foreach ( $keys as $key => $limit ) {
1565 list( $max, $period ) = $limit;
1566 $summary = "(limit $max in {$period}s)";
1567 $count = $wgMemc->get( $key );
1568 // Already pinged?
1569 if ( $count ) {
1570 if ( $count >= $max ) {
1571 wfDebug( __METHOD__ . ": tripped! $key at $count $summary\n" );
1572 if ( $wgRateLimitLog ) {
1573 wfSuppressWarnings();
1574 file_put_contents( $wgRateLimitLog, wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", FILE_APPEND );
1575 wfRestoreWarnings();
1577 $triggered = true;
1578 } else {
1579 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1581 } else {
1582 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1583 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1585 $wgMemc->incr( $key );
1588 wfProfileOut( __METHOD__ );
1589 return $triggered;
1593 * Check if user is blocked
1595 * @param bool $bFromSlave Whether to check the slave database instead of the master
1596 * @return bool True if blocked, false otherwise
1598 public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1599 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1603 * Get the block affecting the user, or null if the user is not blocked
1605 * @param bool $bFromSlave Whether to check the slave database instead of the master
1606 * @return Block|null
1608 public function getBlock( $bFromSlave = true ) {
1609 $this->getBlockedStatus( $bFromSlave );
1610 return $this->mBlock instanceof Block ? $this->mBlock : null;
1614 * Check if user is blocked from editing a particular article
1616 * @param Title $title Title to check
1617 * @param bool $bFromSlave whether to check the slave database instead of the master
1618 * @return bool
1620 function isBlockedFrom( $title, $bFromSlave = false ) {
1621 global $wgBlockAllowsUTEdit;
1622 wfProfileIn( __METHOD__ );
1624 $blocked = $this->isBlocked( $bFromSlave );
1625 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1626 // If a user's name is suppressed, they cannot make edits anywhere
1627 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName() &&
1628 $title->getNamespace() == NS_USER_TALK ) {
1629 $blocked = false;
1630 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1633 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1635 wfProfileOut( __METHOD__ );
1636 return $blocked;
1640 * If user is blocked, return the name of the user who placed the block
1641 * @return string Name of blocker
1643 public function blockedBy() {
1644 $this->getBlockedStatus();
1645 return $this->mBlockedby;
1649 * If user is blocked, return the specified reason for the block
1650 * @return string Blocking reason
1652 public function blockedFor() {
1653 $this->getBlockedStatus();
1654 return $this->mBlockreason;
1658 * If user is blocked, return the ID for the block
1659 * @return int Block ID
1661 public function getBlockId() {
1662 $this->getBlockedStatus();
1663 return ( $this->mBlock ? $this->mBlock->getId() : false );
1667 * Check if user is blocked on all wikis.
1668 * Do not use for actual edit permission checks!
1669 * This is intended for quick UI checks.
1671 * @param string $ip IP address, uses current client if none given
1672 * @return bool True if blocked, false otherwise
1674 public function isBlockedGlobally( $ip = '' ) {
1675 if ( $this->mBlockedGlobally !== null ) {
1676 return $this->mBlockedGlobally;
1678 // User is already an IP?
1679 if ( IP::isIPAddress( $this->getName() ) ) {
1680 $ip = $this->getName();
1681 } elseif ( !$ip ) {
1682 $ip = $this->getRequest()->getIP();
1684 $blocked = false;
1685 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1686 $this->mBlockedGlobally = (bool)$blocked;
1687 return $this->mBlockedGlobally;
1691 * Check if user account is locked
1693 * @return bool True if locked, false otherwise
1695 public function isLocked() {
1696 if ( $this->mLocked !== null ) {
1697 return $this->mLocked;
1699 global $wgAuth;
1700 $authUser = $wgAuth->getUserInstance( $this );
1701 $this->mLocked = (bool)$authUser->isLocked();
1702 return $this->mLocked;
1706 * Check if user account is hidden
1708 * @return bool True if hidden, false otherwise
1710 public function isHidden() {
1711 if ( $this->mHideName !== null ) {
1712 return $this->mHideName;
1714 $this->getBlockedStatus();
1715 if ( !$this->mHideName ) {
1716 global $wgAuth;
1717 $authUser = $wgAuth->getUserInstance( $this );
1718 $this->mHideName = (bool)$authUser->isHidden();
1720 return $this->mHideName;
1724 * Get the user's ID.
1725 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1727 public function getId() {
1728 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
1729 // Special case, we know the user is anonymous
1730 return 0;
1731 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1732 // Don't load if this was initialized from an ID
1733 $this->load();
1735 return $this->mId;
1739 * Set the user and reload all fields according to a given ID
1740 * @param int $v User ID to reload
1742 public function setId( $v ) {
1743 $this->mId = $v;
1744 $this->clearInstanceCache( 'id' );
1748 * Get the user name, or the IP of an anonymous user
1749 * @return string User's name or IP address
1751 public function getName() {
1752 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1753 // Special case optimisation
1754 return $this->mName;
1755 } else {
1756 $this->load();
1757 if ( $this->mName === false ) {
1758 // Clean up IPs
1759 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
1761 return $this->mName;
1766 * Set the user name.
1768 * This does not reload fields from the database according to the given
1769 * name. Rather, it is used to create a temporary "nonexistent user" for
1770 * later addition to the database. It can also be used to set the IP
1771 * address for an anonymous user to something other than the current
1772 * remote IP.
1774 * @note User::newFromName() has roughly the same function, when the named user
1775 * does not exist.
1776 * @param string $str New user name to set
1778 public function setName( $str ) {
1779 $this->load();
1780 $this->mName = $str;
1784 * Get the user's name escaped by underscores.
1785 * @return string Username escaped by underscores.
1787 public function getTitleKey() {
1788 return str_replace( ' ', '_', $this->getName() );
1792 * Check if the user has new messages.
1793 * @return bool True if the user has new messages
1795 public function getNewtalk() {
1796 $this->load();
1798 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1799 if ( $this->mNewtalk === -1 ) {
1800 $this->mNewtalk = false; # reset talk page status
1802 // Check memcached separately for anons, who have no
1803 // entire User object stored in there.
1804 if ( !$this->mId ) {
1805 global $wgDisableAnonTalk;
1806 if ( $wgDisableAnonTalk ) {
1807 // Anon newtalk disabled by configuration.
1808 $this->mNewtalk = false;
1809 } else {
1810 global $wgMemc;
1811 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1812 $newtalk = $wgMemc->get( $key );
1813 if ( strval( $newtalk ) !== '' ) {
1814 $this->mNewtalk = (bool)$newtalk;
1815 } else {
1816 // Since we are caching this, make sure it is up to date by getting it
1817 // from the master
1818 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1819 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1822 } else {
1823 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1827 return (bool)$this->mNewtalk;
1831 * Return the revision and link for the oldest new talk page message for
1832 * this user.
1833 * @note This function was designed to accomodate multiple talk pages, but
1834 * currently only returns a single link and revision.
1835 * @return Array
1837 public function getNewMessageLinks() {
1838 $talks = array();
1839 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
1840 return $talks;
1841 } elseif ( !$this->getNewtalk() ) {
1842 return array();
1844 $utp = $this->getTalkPage();
1845 $dbr = wfGetDB( DB_SLAVE );
1846 // Get the "last viewed rev" timestamp from the oldest message notification
1847 $timestamp = $dbr->selectField( 'user_newtalk',
1848 'MIN(user_last_timestamp)',
1849 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
1850 __METHOD__ );
1851 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
1852 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
1856 * Get the revision ID for the oldest new talk page message for this user
1857 * @return int|null Revision id or null if there are no new messages
1859 public function getNewMessageRevisionId() {
1860 $newMessageRevisionId = null;
1861 $newMessageLinks = $this->getNewMessageLinks();
1862 if ( $newMessageLinks ) {
1863 // Note: getNewMessageLinks() never returns more than a single link
1864 // and it is always for the same wiki, but we double-check here in
1865 // case that changes some time in the future.
1866 if ( count( $newMessageLinks ) === 1
1867 && $newMessageLinks[0]['wiki'] === wfWikiID()
1868 && $newMessageLinks[0]['rev']
1870 $newMessageRevision = $newMessageLinks[0]['rev'];
1871 $newMessageRevisionId = $newMessageRevision->getId();
1874 return $newMessageRevisionId;
1878 * Internal uncached check for new messages
1880 * @see getNewtalk()
1881 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1882 * @param string|int $id User's IP address for anonymous users, User ID otherwise
1883 * @param bool $fromMaster true to fetch from the master, false for a slave
1884 * @return bool True if the user has new messages
1886 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
1887 if ( $fromMaster ) {
1888 $db = wfGetDB( DB_MASTER );
1889 } else {
1890 $db = wfGetDB( DB_SLAVE );
1892 $ok = $db->selectField( 'user_newtalk', $field,
1893 array( $field => $id ), __METHOD__ );
1894 return $ok !== false;
1898 * Add or update the new messages flag
1899 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1900 * @param string|int $id User's IP address for anonymous users, User ID otherwise
1901 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null.
1902 * @return bool True if successful, false otherwise
1904 protected function updateNewtalk( $field, $id, $curRev = null ) {
1905 // Get timestamp of the talk page revision prior to the current one
1906 $prevRev = $curRev ? $curRev->getPrevious() : false;
1907 $ts = $prevRev ? $prevRev->getTimestamp() : null;
1908 // Mark the user as having new messages since this revision
1909 $dbw = wfGetDB( DB_MASTER );
1910 $dbw->insert( 'user_newtalk',
1911 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
1912 __METHOD__,
1913 'IGNORE' );
1914 if ( $dbw->affectedRows() ) {
1915 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
1916 return true;
1917 } else {
1918 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
1919 return false;
1924 * Clear the new messages flag for the given user
1925 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1926 * @param string|int $id User's IP address for anonymous users, User ID otherwise
1927 * @return bool True if successful, false otherwise
1929 protected function deleteNewtalk( $field, $id ) {
1930 $dbw = wfGetDB( DB_MASTER );
1931 $dbw->delete( 'user_newtalk',
1932 array( $field => $id ),
1933 __METHOD__ );
1934 if ( $dbw->affectedRows() ) {
1935 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
1936 return true;
1937 } else {
1938 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
1939 return false;
1944 * Update the 'You have new messages!' status.
1945 * @param bool $val Whether the user has new messages
1946 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null or !$val.
1948 public function setNewtalk( $val, $curRev = null ) {
1949 if ( wfReadOnly() ) {
1950 return;
1953 $this->load();
1954 $this->mNewtalk = $val;
1956 if ( $this->isAnon() ) {
1957 $field = 'user_ip';
1958 $id = $this->getName();
1959 } else {
1960 $field = 'user_id';
1961 $id = $this->getId();
1963 global $wgMemc;
1965 if ( $val ) {
1966 $changed = $this->updateNewtalk( $field, $id, $curRev );
1967 } else {
1968 $changed = $this->deleteNewtalk( $field, $id );
1971 if ( $this->isAnon() ) {
1972 // Anons have a separate memcached space, since
1973 // user records aren't kept for them.
1974 $key = wfMemcKey( 'newtalk', 'ip', $id );
1975 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
1977 if ( $changed ) {
1978 $this->invalidateCache();
1983 * Generate a current or new-future timestamp to be stored in the
1984 * user_touched field when we update things.
1985 * @return string Timestamp in TS_MW format
1987 private static function newTouchedTimestamp() {
1988 global $wgClockSkewFudge;
1989 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1993 * Clear user data from memcached.
1994 * Use after applying fun updates to the database; caller's
1995 * responsibility to update user_touched if appropriate.
1997 * Called implicitly from invalidateCache() and saveSettings().
1999 private function clearSharedCache() {
2000 $this->load();
2001 if ( $this->mId ) {
2002 global $wgMemc;
2003 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
2008 * Immediately touch the user data cache for this account.
2009 * Updates user_touched field, and removes account data from memcached
2010 * for reload on the next hit.
2012 public function invalidateCache() {
2013 if ( wfReadOnly() ) {
2014 return;
2016 $this->load();
2017 if ( $this->mId ) {
2018 $this->mTouched = self::newTouchedTimestamp();
2020 $dbw = wfGetDB( DB_MASTER );
2021 $userid = $this->mId;
2022 $touched = $this->mTouched;
2023 $method = __METHOD__;
2024 $dbw->onTransactionIdle( function() use ( $dbw, $userid, $touched, $method ) {
2025 // Prevent contention slams by checking user_touched first
2026 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2027 $needsPurge = $dbw->selectField( 'user', '1',
2028 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2029 if ( $needsPurge ) {
2030 $dbw->update( 'user',
2031 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2032 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2033 $method
2036 } );
2037 $this->clearSharedCache();
2042 * Validate the cache for this account.
2043 * @param string $timestamp A timestamp in TS_MW format
2044 * @return bool
2046 public function validateCache( $timestamp ) {
2047 $this->load();
2048 return ( $timestamp >= $this->mTouched );
2052 * Get the user touched timestamp
2053 * @return string timestamp
2055 public function getTouched() {
2056 $this->load();
2057 return $this->mTouched;
2061 * Set the password and reset the random token.
2062 * Calls through to authentication plugin if necessary;
2063 * will have no effect if the auth plugin refuses to
2064 * pass the change through or if the legal password
2065 * checks fail.
2067 * As a special case, setting the password to null
2068 * wipes it, so the account cannot be logged in until
2069 * a new password is set, for instance via e-mail.
2071 * @param string $str New password to set
2072 * @throws PasswordError on failure
2074 * @return bool
2076 public function setPassword( $str ) {
2077 global $wgAuth;
2079 if ( $str !== null ) {
2080 if ( !$wgAuth->allowPasswordChange() ) {
2081 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2084 if ( !$this->isValidPassword( $str ) ) {
2085 global $wgMinimalPasswordLength;
2086 $valid = $this->getPasswordValidity( $str );
2087 if ( is_array( $valid ) ) {
2088 $message = array_shift( $valid );
2089 $params = $valid;
2090 } else {
2091 $message = $valid;
2092 $params = array( $wgMinimalPasswordLength );
2094 throw new PasswordError( wfMessage( $message, $params )->text() );
2098 if ( !$wgAuth->setPassword( $this, $str ) ) {
2099 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2102 $this->setInternalPassword( $str );
2104 return true;
2108 * Set the password and reset the random token unconditionally.
2110 * @param string|null $str New password to set or null to set an invalid
2111 * password hash meaning that the user will not be able to log in
2112 * through the web interface.
2114 public function setInternalPassword( $str ) {
2115 $this->load();
2116 $this->setToken();
2118 if ( $str === null ) {
2119 // Save an invalid hash...
2120 $this->mPassword = '';
2121 } else {
2122 $this->mPassword = self::crypt( $str );
2124 $this->mNewpassword = '';
2125 $this->mNewpassTime = null;
2129 * Get the user's current token.
2130 * @param bool $forceCreation Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility)
2131 * @return string Token
2133 public function getToken( $forceCreation = true ) {
2134 $this->load();
2135 if ( !$this->mToken && $forceCreation ) {
2136 $this->setToken();
2138 return $this->mToken;
2142 * Set the random token (used for persistent authentication)
2143 * Called from loadDefaults() among other places.
2145 * @param string|bool $token If specified, set the token to this value
2147 public function setToken( $token = false ) {
2148 $this->load();
2149 if ( !$token ) {
2150 $this->mToken = MWCryptRand::generateHex( USER_TOKEN_LENGTH );
2151 } else {
2152 $this->mToken = $token;
2157 * Set the password for a password reminder or new account email
2159 * @param string $str New password to set
2160 * @param bool $throttle If true, reset the throttle timestamp to the present
2162 public function setNewpassword( $str, $throttle = true ) {
2163 $this->load();
2164 $this->mNewpassword = self::crypt( $str );
2165 if ( $throttle ) {
2166 $this->mNewpassTime = wfTimestampNow();
2171 * Has password reminder email been sent within the last
2172 * $wgPasswordReminderResendTime hours?
2173 * @return bool
2175 public function isPasswordReminderThrottled() {
2176 global $wgPasswordReminderResendTime;
2177 $this->load();
2178 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
2179 return false;
2181 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
2182 return time() < $expiry;
2186 * Get the user's e-mail address
2187 * @return string User's email address
2189 public function getEmail() {
2190 $this->load();
2191 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
2192 return $this->mEmail;
2196 * Get the timestamp of the user's e-mail authentication
2197 * @return string TS_MW timestamp
2199 public function getEmailAuthenticationTimestamp() {
2200 $this->load();
2201 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2202 return $this->mEmailAuthenticated;
2206 * Set the user's e-mail address
2207 * @param string $str New e-mail address
2209 public function setEmail( $str ) {
2210 $this->load();
2211 if ( $str == $this->mEmail ) {
2212 return;
2214 $this->mEmail = $str;
2215 $this->invalidateEmail();
2216 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
2220 * Set the user's e-mail address and a confirmation mail if needed.
2222 * @since 1.20
2223 * @param string $str New e-mail address
2224 * @return Status
2226 public function setEmailWithConfirmation( $str ) {
2227 global $wgEnableEmail, $wgEmailAuthentication;
2229 if ( !$wgEnableEmail ) {
2230 return Status::newFatal( 'emaildisabled' );
2233 $oldaddr = $this->getEmail();
2234 if ( $str === $oldaddr ) {
2235 return Status::newGood( true );
2238 $this->setEmail( $str );
2240 if ( $str !== '' && $wgEmailAuthentication ) {
2241 // Send a confirmation request to the new address if needed
2242 $type = $oldaddr != '' ? 'changed' : 'set';
2243 $result = $this->sendConfirmationMail( $type );
2244 if ( $result->isGood() ) {
2245 // Say the the caller that a confirmation mail has been sent
2246 $result->value = 'eauth';
2248 } else {
2249 $result = Status::newGood( true );
2252 return $result;
2256 * Get the user's real name
2257 * @return string User's real name
2259 public function getRealName() {
2260 if ( !$this->isItemLoaded( 'realname' ) ) {
2261 $this->load();
2264 return $this->mRealName;
2268 * Set the user's real name
2269 * @param string $str New real name
2271 public function setRealName( $str ) {
2272 $this->load();
2273 $this->mRealName = $str;
2277 * Get the user's current setting for a given option.
2279 * @param string $oname The option to check
2280 * @param string $defaultOverride A default value returned if the option does not exist
2281 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2282 * @return string User's current value for the option
2283 * @see getBoolOption()
2284 * @see getIntOption()
2286 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2287 global $wgHiddenPrefs;
2288 $this->loadOptions();
2290 # We want 'disabled' preferences to always behave as the default value for
2291 # users, even if they have set the option explicitly in their settings (ie they
2292 # set it, and then it was disabled removing their ability to change it). But
2293 # we don't want to erase the preferences in the database in case the preference
2294 # is re-enabled again. So don't touch $mOptions, just override the returned value
2295 if ( in_array( $oname, $wgHiddenPrefs ) && !$ignoreHidden ) {
2296 return self::getDefaultOption( $oname );
2299 if ( array_key_exists( $oname, $this->mOptions ) ) {
2300 return $this->mOptions[$oname];
2301 } else {
2302 return $defaultOverride;
2307 * Get all user's options
2309 * @return array
2311 public function getOptions() {
2312 global $wgHiddenPrefs;
2313 $this->loadOptions();
2314 $options = $this->mOptions;
2316 # We want 'disabled' preferences to always behave as the default value for
2317 # users, even if they have set the option explicitly in their settings (ie they
2318 # set it, and then it was disabled removing their ability to change it). But
2319 # we don't want to erase the preferences in the database in case the preference
2320 # is re-enabled again. So don't touch $mOptions, just override the returned value
2321 foreach ( $wgHiddenPrefs as $pref ) {
2322 $default = self::getDefaultOption( $pref );
2323 if ( $default !== null ) {
2324 $options[$pref] = $default;
2328 return $options;
2332 * Get the user's current setting for a given option, as a boolean value.
2334 * @param string $oname The option to check
2335 * @return bool User's current value for the option
2336 * @see getOption()
2338 public function getBoolOption( $oname ) {
2339 return (bool)$this->getOption( $oname );
2343 * Get the user's current setting for a given option, as a boolean value.
2345 * @param string $oname The option to check
2346 * @param int $defaultOverride A default value returned if the option does not exist
2347 * @return int User's current value for the option
2348 * @see getOption()
2350 public function getIntOption( $oname, $defaultOverride = 0 ) {
2351 $val = $this->getOption( $oname );
2352 if ( $val == '' ) {
2353 $val = $defaultOverride;
2355 return intval( $val );
2359 * Set the given option for a user.
2361 * @param string $oname The option to set
2362 * @param mixed $val New value to set
2364 public function setOption( $oname, $val ) {
2365 $this->loadOptions();
2367 // Explicitly NULL values should refer to defaults
2368 if ( is_null( $val ) ) {
2369 $val = self::getDefaultOption( $oname );
2372 $this->mOptions[$oname] = $val;
2376 * Return a list of the types of user options currently returned by
2377 * User::getOptionKinds().
2379 * Currently, the option kinds are:
2380 * - 'registered' - preferences which are registered in core MediaWiki or
2381 * by extensions using the UserGetDefaultOptions hook.
2382 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2383 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2384 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2385 * be used by user scripts.
2386 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2387 * These are usually legacy options, removed in newer versions.
2389 * The API (and possibly others) use this function to determine the possible
2390 * option types for validation purposes, so make sure to update this when a
2391 * new option kind is added.
2393 * @see User::getOptionKinds
2394 * @return array Option kinds
2396 public static function listOptionKinds() {
2397 return array(
2398 'registered',
2399 'registered-multiselect',
2400 'registered-checkmatrix',
2401 'userjs',
2402 'unused'
2407 * Return an associative array mapping preferences keys to the kind of a preference they're
2408 * used for. Different kinds are handled differently when setting or reading preferences.
2410 * See User::listOptionKinds for the list of valid option types that can be provided.
2412 * @see User::listOptionKinds
2413 * @param $context IContextSource
2414 * @param array $options assoc. array with options keys to check as keys. Defaults to $this->mOptions.
2415 * @return array the key => kind mapping data
2417 public function getOptionKinds( IContextSource $context, $options = null ) {
2418 $this->loadOptions();
2419 if ( $options === null ) {
2420 $options = $this->mOptions;
2423 $prefs = Preferences::getPreferences( $this, $context );
2424 $mapping = array();
2426 // Multiselect and checkmatrix options are stored in the database with
2427 // one key per option, each having a boolean value. Extract those keys.
2428 $multiselectOptions = array();
2429 foreach ( $prefs as $name => $info ) {
2430 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2431 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2432 $opts = HTMLFormField::flattenOptions( $info['options'] );
2433 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2435 foreach ( $opts as $value ) {
2436 $multiselectOptions["$prefix$value"] = true;
2439 unset( $prefs[$name] );
2442 $checkmatrixOptions = array();
2443 foreach ( $prefs as $name => $info ) {
2444 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2445 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2446 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2447 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2448 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2450 foreach ( $columns as $column ) {
2451 foreach ( $rows as $row ) {
2452 $checkmatrixOptions["$prefix-$column-$row"] = true;
2456 unset( $prefs[$name] );
2460 // $value is ignored
2461 foreach ( $options as $key => $value ) {
2462 if ( isset( $prefs[$key] ) ) {
2463 $mapping[$key] = 'registered';
2464 } elseif ( isset( $multiselectOptions[$key] ) ) {
2465 $mapping[$key] = 'registered-multiselect';
2466 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2467 $mapping[$key] = 'registered-checkmatrix';
2468 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2469 $mapping[$key] = 'userjs';
2470 } else {
2471 $mapping[$key] = 'unused';
2475 return $mapping;
2479 * Reset certain (or all) options to the site defaults
2481 * The optional parameter determines which kinds of preferences will be reset.
2482 * Supported values are everything that can be reported by getOptionKinds()
2483 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2485 * @param array|string $resetKinds which kinds of preferences to reset. Defaults to
2486 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2487 * for backwards-compatibility.
2488 * @param $context IContextSource|null context source used when $resetKinds
2489 * does not contain 'all', passed to getOptionKinds().
2490 * Defaults to RequestContext::getMain() when null.
2492 public function resetOptions(
2493 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2494 IContextSource $context = null
2496 $this->load();
2497 $defaultOptions = self::getDefaultOptions();
2499 if ( !is_array( $resetKinds ) ) {
2500 $resetKinds = array( $resetKinds );
2503 if ( in_array( 'all', $resetKinds ) ) {
2504 $newOptions = $defaultOptions;
2505 } else {
2506 if ( $context === null ) {
2507 $context = RequestContext::getMain();
2510 $optionKinds = $this->getOptionKinds( $context );
2511 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2512 $newOptions = array();
2514 // Use default values for the options that should be deleted, and
2515 // copy old values for the ones that shouldn't.
2516 foreach ( $this->mOptions as $key => $value ) {
2517 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2518 if ( array_key_exists( $key, $defaultOptions ) ) {
2519 $newOptions[$key] = $defaultOptions[$key];
2521 } else {
2522 $newOptions[$key] = $value;
2527 $this->mOptions = $newOptions;
2528 $this->mOptionsLoaded = true;
2532 * Get the user's preferred date format.
2533 * @return string User's preferred date format
2535 public function getDatePreference() {
2536 // Important migration for old data rows
2537 if ( is_null( $this->mDatePreference ) ) {
2538 global $wgLang;
2539 $value = $this->getOption( 'date' );
2540 $map = $wgLang->getDatePreferenceMigrationMap();
2541 if ( isset( $map[$value] ) ) {
2542 $value = $map[$value];
2544 $this->mDatePreference = $value;
2546 return $this->mDatePreference;
2550 * Get the user preferred stub threshold
2552 * @return int
2554 public function getStubThreshold() {
2555 global $wgMaxArticleSize; # Maximum article size, in Kb
2556 $threshold = $this->getIntOption( 'stubthreshold' );
2557 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2558 // If they have set an impossible value, disable the preference
2559 // so we can use the parser cache again.
2560 $threshold = 0;
2562 return $threshold;
2566 * Get the permissions this user has.
2567 * @return Array of String permission names
2569 public function getRights() {
2570 if ( is_null( $this->mRights ) ) {
2571 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2572 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2573 // Force reindexation of rights when a hook has unset one of them
2574 $this->mRights = array_values( array_unique( $this->mRights ) );
2576 return $this->mRights;
2580 * Get the list of explicit group memberships this user has.
2581 * The implicit * and user groups are not included.
2582 * @return Array of String internal group names
2584 public function getGroups() {
2585 $this->load();
2586 $this->loadGroups();
2587 return $this->mGroups;
2591 * Get the list of implicit group memberships this user has.
2592 * This includes all explicit groups, plus 'user' if logged in,
2593 * '*' for all accounts, and autopromoted groups
2594 * @param bool $recache Whether to avoid the cache
2595 * @return Array of String internal group names
2597 public function getEffectiveGroups( $recache = false ) {
2598 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2599 wfProfileIn( __METHOD__ );
2600 $this->mEffectiveGroups = array_unique( array_merge(
2601 $this->getGroups(), // explicit groups
2602 $this->getAutomaticGroups( $recache ) // implicit groups
2603 ) );
2604 // Hook for additional groups
2605 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2606 // Force reindexation of groups when a hook has unset one of them
2607 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
2608 wfProfileOut( __METHOD__ );
2610 return $this->mEffectiveGroups;
2614 * Get the list of implicit group memberships this user has.
2615 * This includes 'user' if logged in, '*' for all accounts,
2616 * and autopromoted groups
2617 * @param bool $recache Whether to avoid the cache
2618 * @return Array of String internal group names
2620 public function getAutomaticGroups( $recache = false ) {
2621 if ( $recache || is_null( $this->mImplicitGroups ) ) {
2622 wfProfileIn( __METHOD__ );
2623 $this->mImplicitGroups = array( '*' );
2624 if ( $this->getId() ) {
2625 $this->mImplicitGroups[] = 'user';
2627 $this->mImplicitGroups = array_unique( array_merge(
2628 $this->mImplicitGroups,
2629 Autopromote::getAutopromoteGroups( $this )
2630 ) );
2632 if ( $recache ) {
2633 // Assure data consistency with rights/groups,
2634 // as getEffectiveGroups() depends on this function
2635 $this->mEffectiveGroups = null;
2637 wfProfileOut( __METHOD__ );
2639 return $this->mImplicitGroups;
2643 * Returns the groups the user has belonged to.
2645 * The user may still belong to the returned groups. Compare with getGroups().
2647 * The function will not return groups the user had belonged to before MW 1.17
2649 * @return array Names of the groups the user has belonged to.
2651 public function getFormerGroups() {
2652 if ( is_null( $this->mFormerGroups ) ) {
2653 $dbr = wfGetDB( DB_MASTER );
2654 $res = $dbr->select( 'user_former_groups',
2655 array( 'ufg_group' ),
2656 array( 'ufg_user' => $this->mId ),
2657 __METHOD__ );
2658 $this->mFormerGroups = array();
2659 foreach ( $res as $row ) {
2660 $this->mFormerGroups[] = $row->ufg_group;
2663 return $this->mFormerGroups;
2667 * Get the user's edit count.
2668 * @return int
2670 public function getEditCount() {
2671 if ( !$this->getId() ) {
2672 return null;
2675 if ( !isset( $this->mEditCount ) ) {
2676 /* Populate the count, if it has not been populated yet */
2677 wfProfileIn( __METHOD__ );
2678 $dbr = wfGetDB( DB_SLAVE );
2679 // check if the user_editcount field has been initialized
2680 $count = $dbr->selectField(
2681 'user', 'user_editcount',
2682 array( 'user_id' => $this->mId ),
2683 __METHOD__
2686 if ( $count === null ) {
2687 // it has not been initialized. do so.
2688 $count = $this->initEditCount();
2690 $this->mEditCount = intval( $count );
2691 wfProfileOut( __METHOD__ );
2693 return $this->mEditCount;
2697 * Add the user to the given group.
2698 * This takes immediate effect.
2699 * @param string $group Name of the group to add
2701 public function addGroup( $group ) {
2702 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2703 $dbw = wfGetDB( DB_MASTER );
2704 if ( $this->getId() ) {
2705 $dbw->insert( 'user_groups',
2706 array(
2707 'ug_user' => $this->getID(),
2708 'ug_group' => $group,
2710 __METHOD__,
2711 array( 'IGNORE' ) );
2714 $this->loadGroups();
2715 $this->mGroups[] = $group;
2716 // In case loadGroups was not called before, we now have the right twice.
2717 // Get rid of the duplicate.
2718 $this->mGroups = array_unique( $this->mGroups );
2720 // Refresh the groups caches, and clear the rights cache so it will be
2721 // refreshed on the next call to $this->getRights().
2722 $this->getEffectiveGroups( true );
2723 $this->mRights = null;
2725 $this->invalidateCache();
2729 * Remove the user from the given group.
2730 * This takes immediate effect.
2731 * @param string $group Name of the group to remove
2733 public function removeGroup( $group ) {
2734 $this->load();
2735 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2736 $dbw = wfGetDB( DB_MASTER );
2737 $dbw->delete( 'user_groups',
2738 array(
2739 'ug_user' => $this->getID(),
2740 'ug_group' => $group,
2741 ), __METHOD__ );
2742 // Remember that the user was in this group
2743 $dbw->insert( 'user_former_groups',
2744 array(
2745 'ufg_user' => $this->getID(),
2746 'ufg_group' => $group,
2748 __METHOD__,
2749 array( 'IGNORE' ) );
2751 $this->loadGroups();
2752 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2754 // Refresh the groups caches, and clear the rights cache so it will be
2755 // refreshed on the next call to $this->getRights().
2756 $this->getEffectiveGroups( true );
2757 $this->mRights = null;
2759 $this->invalidateCache();
2763 * Get whether the user is logged in
2764 * @return bool
2766 public function isLoggedIn() {
2767 return $this->getID() != 0;
2771 * Get whether the user is anonymous
2772 * @return bool
2774 public function isAnon() {
2775 return !$this->isLoggedIn();
2779 * Check if user is allowed to access a feature / make an action
2781 * @internal param \String $varargs permissions to test
2782 * @return boolean: True if user is allowed to perform *any* of the given actions
2784 * @return bool
2786 public function isAllowedAny( /*...*/ ) {
2787 $permissions = func_get_args();
2788 foreach ( $permissions as $permission ) {
2789 if ( $this->isAllowed( $permission ) ) {
2790 return true;
2793 return false;
2798 * @internal param $varargs string
2799 * @return bool True if the user is allowed to perform *all* of the given actions
2801 public function isAllowedAll( /*...*/ ) {
2802 $permissions = func_get_args();
2803 foreach ( $permissions as $permission ) {
2804 if ( !$this->isAllowed( $permission ) ) {
2805 return false;
2808 return true;
2812 * Internal mechanics of testing a permission
2813 * @param string $action
2814 * @return bool
2816 public function isAllowed( $action = '' ) {
2817 if ( $action === '' ) {
2818 return true; // In the spirit of DWIM
2820 // Patrolling may not be enabled
2821 if ( $action === 'patrol' || $action === 'autopatrol' ) {
2822 global $wgUseRCPatrol, $wgUseNPPatrol;
2823 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
2824 return false;
2827 // Use strict parameter to avoid matching numeric 0 accidentally inserted
2828 // by misconfiguration: 0 == 'foo'
2829 return in_array( $action, $this->getRights(), true );
2833 * Check whether to enable recent changes patrol features for this user
2834 * @return boolean: True or false
2836 public function useRCPatrol() {
2837 global $wgUseRCPatrol;
2838 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
2842 * Check whether to enable new pages patrol features for this user
2843 * @return bool True or false
2845 public function useNPPatrol() {
2846 global $wgUseRCPatrol, $wgUseNPPatrol;
2847 return (
2848 ( $wgUseRCPatrol || $wgUseNPPatrol )
2849 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
2854 * Get the WebRequest object to use with this object
2856 * @return WebRequest
2858 public function getRequest() {
2859 if ( $this->mRequest ) {
2860 return $this->mRequest;
2861 } else {
2862 global $wgRequest;
2863 return $wgRequest;
2868 * Get the current skin, loading it if required
2869 * @return Skin The current skin
2870 * @todo FIXME: Need to check the old failback system [AV]
2871 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
2873 public function getSkin() {
2874 wfDeprecated( __METHOD__, '1.18' );
2875 return RequestContext::getMain()->getSkin();
2879 * Get a WatchedItem for this user and $title.
2881 * @since 1.22 $checkRights parameter added
2882 * @param $title Title
2883 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
2884 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
2885 * @return WatchedItem
2887 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
2888 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
2890 if ( isset( $this->mWatchedItems[$key] ) ) {
2891 return $this->mWatchedItems[$key];
2894 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
2895 $this->mWatchedItems = array();
2898 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
2899 return $this->mWatchedItems[$key];
2903 * Check the watched status of an article.
2904 * @since 1.22 $checkRights parameter added
2905 * @param $title Title of the article to look at
2906 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
2907 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
2908 * @return bool
2910 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
2911 return $this->getWatchedItem( $title, $checkRights )->isWatched();
2915 * Watch an article.
2916 * @since 1.22 $checkRights parameter added
2917 * @param $title Title of the article to look at
2918 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
2919 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
2921 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
2922 $this->getWatchedItem( $title, $checkRights )->addWatch();
2923 $this->invalidateCache();
2927 * Stop watching an article.
2928 * @since 1.22 $checkRights parameter added
2929 * @param $title Title of the article to look at
2930 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
2931 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
2933 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
2934 $this->getWatchedItem( $title, $checkRights )->removeWatch();
2935 $this->invalidateCache();
2939 * Clear the user's notification timestamp for the given title.
2940 * If e-notif e-mails are on, they will receive notification mails on
2941 * the next change of the page if it's watched etc.
2942 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
2943 * @param $title Title of the article to look at
2945 public function clearNotification( &$title ) {
2946 global $wgUseEnotif, $wgShowUpdatedMarker;
2948 // Do nothing if the database is locked to writes
2949 if ( wfReadOnly() ) {
2950 return;
2953 // Do nothing if not allowed to edit the watchlist
2954 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
2955 return;
2958 if ( $title->getNamespace() == NS_USER_TALK &&
2959 $title->getText() == $this->getName() ) {
2960 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) ) {
2961 return;
2963 $this->setNewtalk( false );
2966 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2967 return;
2970 if ( $this->isAnon() ) {
2971 // Nothing else to do...
2972 return;
2975 // Only update the timestamp if the page is being watched.
2976 // The query to find out if it is watched is cached both in memcached and per-invocation,
2977 // and when it does have to be executed, it can be on a slave
2978 // If this is the user's newtalk page, we always update the timestamp
2979 $force = '';
2980 if ( $title->getNamespace() == NS_USER_TALK &&
2981 $title->getText() == $this->getName() )
2983 $force = 'force';
2986 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force );
2990 * Resets all of the given user's page-change notification timestamps.
2991 * If e-notif e-mails are on, they will receive notification mails on
2992 * the next change of any watched page.
2993 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
2995 public function clearAllNotifications() {
2996 if ( wfReadOnly() ) {
2997 return;
3000 // Do nothing if not allowed to edit the watchlist
3001 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3002 return;
3005 global $wgUseEnotif, $wgShowUpdatedMarker;
3006 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3007 $this->setNewtalk( false );
3008 return;
3010 $id = $this->getId();
3011 if ( $id != 0 ) {
3012 $dbw = wfGetDB( DB_MASTER );
3013 $dbw->update( 'watchlist',
3014 array( /* SET */
3015 'wl_notificationtimestamp' => null
3016 ), array( /* WHERE */
3017 'wl_user' => $id
3018 ), __METHOD__
3020 # We also need to clear here the "you have new message" notification for the own user_talk page
3021 # This is cleared one page view later in Article::viewUpdates();
3026 * Set this user's options from an encoded string
3027 * @param string $str Encoded options to import
3029 * @deprecated in 1.19 due to removal of user_options from the user table
3031 private function decodeOptions( $str ) {
3032 wfDeprecated( __METHOD__, '1.19' );
3033 if ( !$str ) {
3034 return;
3037 $this->mOptionsLoaded = true;
3038 $this->mOptionOverrides = array();
3040 // If an option is not set in $str, use the default value
3041 $this->mOptions = self::getDefaultOptions();
3043 $a = explode( "\n", $str );
3044 foreach ( $a as $s ) {
3045 $m = array();
3046 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
3047 $this->mOptions[$m[1]] = $m[2];
3048 $this->mOptionOverrides[$m[1]] = $m[2];
3054 * Set a cookie on the user's client. Wrapper for
3055 * WebResponse::setCookie
3056 * @param string $name Name of the cookie to set
3057 * @param string $value Value to set
3058 * @param int $exp Expiration time, as a UNIX time value;
3059 * if 0 or not specified, use the default $wgCookieExpiration
3060 * @param bool $secure
3061 * true: Force setting the secure attribute when setting the cookie
3062 * false: Force NOT setting the secure attribute when setting the cookie
3063 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3065 protected function setCookie( $name, $value, $exp = 0, $secure = null ) {
3066 $this->getRequest()->response()->setcookie( $name, $value, $exp, null, null, $secure );
3070 * Clear a cookie on the user's client
3071 * @param string $name Name of the cookie to clear
3073 protected function clearCookie( $name ) {
3074 $this->setCookie( $name, '', time() - 86400 );
3078 * Set the default cookies for this session on the user's client.
3080 * @param $request WebRequest object to use; $wgRequest will be used if null
3081 * is passed.
3082 * @param bool $secure Whether to force secure/insecure cookies or use default
3084 public function setCookies( $request = null, $secure = null ) {
3085 if ( $request === null ) {
3086 $request = $this->getRequest();
3089 $this->load();
3090 if ( 0 == $this->mId ) {
3091 return;
3093 if ( !$this->mToken ) {
3094 // When token is empty or NULL generate a new one and then save it to the database
3095 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3096 // Simply by setting every cell in the user_token column to NULL and letting them be
3097 // regenerated as users log back into the wiki.
3098 $this->setToken();
3099 $this->saveSettings();
3101 $session = array(
3102 'wsUserID' => $this->mId,
3103 'wsToken' => $this->mToken,
3104 'wsUserName' => $this->getName()
3106 $cookies = array(
3107 'UserID' => $this->mId,
3108 'UserName' => $this->getName(),
3110 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
3111 $cookies['Token'] = $this->mToken;
3112 } else {
3113 $cookies['Token'] = false;
3116 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3118 foreach ( $session as $name => $value ) {
3119 $request->setSessionData( $name, $value );
3121 foreach ( $cookies as $name => $value ) {
3122 if ( $value === false ) {
3123 $this->clearCookie( $name );
3124 } else {
3125 $this->setCookie( $name, $value, 0, $secure );
3130 * If wpStickHTTPS was selected, also set an insecure cookie that
3131 * will cause the site to redirect the user to HTTPS, if they access
3132 * it over HTTP. Bug 29898.
3134 if ( $request->getCheck( 'wpStickHTTPS' ) ) {
3135 $this->setCookie( 'forceHTTPS', 'true', time() + 2592000, false ); //30 days
3140 * Log this user out.
3142 public function logout() {
3143 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3144 $this->doLogout();
3149 * Clear the user's cookies and session, and reset the instance cache.
3150 * @see logout()
3152 public function doLogout() {
3153 $this->clearInstanceCache( 'defaults' );
3155 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3157 $this->clearCookie( 'UserID' );
3158 $this->clearCookie( 'Token' );
3159 $this->clearCookie( 'forceHTTPS' );
3161 // Remember when user logged out, to prevent seeing cached pages
3162 $this->setCookie( 'LoggedOut', time(), time() + 86400 );
3166 * Save this user's settings into the database.
3167 * @todo Only rarely do all these fields need to be set!
3169 public function saveSettings() {
3170 global $wgAuth;
3172 $this->load();
3173 if ( wfReadOnly() ) {
3174 return;
3176 if ( 0 == $this->mId ) {
3177 return;
3180 $this->mTouched = self::newTouchedTimestamp();
3181 if ( !$wgAuth->allowSetLocalPassword() ) {
3182 $this->mPassword = '';
3185 $dbw = wfGetDB( DB_MASTER );
3186 $dbw->update( 'user',
3187 array( /* SET */
3188 'user_name' => $this->mName,
3189 'user_password' => $this->mPassword,
3190 'user_newpassword' => $this->mNewpassword,
3191 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3192 'user_real_name' => $this->mRealName,
3193 'user_email' => $this->mEmail,
3194 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3195 'user_touched' => $dbw->timestamp( $this->mTouched ),
3196 'user_token' => strval( $this->mToken ),
3197 'user_email_token' => $this->mEmailToken,
3198 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3199 ), array( /* WHERE */
3200 'user_id' => $this->mId
3201 ), __METHOD__
3204 $this->saveOptions();
3206 wfRunHooks( 'UserSaveSettings', array( $this ) );
3207 $this->clearSharedCache();
3208 $this->getUserPage()->invalidateCache();
3212 * If only this user's username is known, and it exists, return the user ID.
3213 * @return int
3215 public function idForName() {
3216 $s = trim( $this->getName() );
3217 if ( $s === '' ) {
3218 return 0;
3221 $dbr = wfGetDB( DB_SLAVE );
3222 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
3223 if ( $id === false ) {
3224 $id = 0;
3226 return $id;
3230 * Add a user to the database, return the user object
3232 * @param string $name Username to add
3233 * @param array $params of Strings Non-default parameters to save to the database as user_* fields:
3234 * - password The user's password hash. Password logins will be disabled if this is omitted.
3235 * - newpassword Hash for a temporary password that has been mailed to the user
3236 * - email The user's email address
3237 * - email_authenticated The email authentication timestamp
3238 * - real_name The user's real name
3239 * - options An associative array of non-default options
3240 * - token Random authentication token. Do not set.
3241 * - registration Registration timestamp. Do not set.
3243 * @return User object, or null if the username already exists
3245 public static function createNew( $name, $params = array() ) {
3246 $user = new User;
3247 $user->load();
3248 $user->setToken(); // init token
3249 if ( isset( $params['options'] ) ) {
3250 $user->mOptions = $params['options'] + (array)$user->mOptions;
3251 unset( $params['options'] );
3253 $dbw = wfGetDB( DB_MASTER );
3254 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3256 $fields = array(
3257 'user_id' => $seqVal,
3258 'user_name' => $name,
3259 'user_password' => $user->mPassword,
3260 'user_newpassword' => $user->mNewpassword,
3261 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3262 'user_email' => $user->mEmail,
3263 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3264 'user_real_name' => $user->mRealName,
3265 'user_token' => strval( $user->mToken ),
3266 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3267 'user_editcount' => 0,
3268 'user_touched' => $dbw->timestamp( self::newTouchedTimestamp() ),
3270 foreach ( $params as $name => $value ) {
3271 $fields["user_$name"] = $value;
3273 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3274 if ( $dbw->affectedRows() ) {
3275 $newUser = User::newFromId( $dbw->insertId() );
3276 } else {
3277 $newUser = null;
3279 return $newUser;
3283 * Add this existing user object to the database. If the user already
3284 * exists, a fatal status object is returned, and the user object is
3285 * initialised with the data from the database.
3287 * Previously, this function generated a DB error due to a key conflict
3288 * if the user already existed. Many extension callers use this function
3289 * in code along the lines of:
3291 * $user = User::newFromName( $name );
3292 * if ( !$user->isLoggedIn() ) {
3293 * $user->addToDatabase();
3295 * // do something with $user...
3297 * However, this was vulnerable to a race condition (bug 16020). By
3298 * initialising the user object if the user exists, we aim to support this
3299 * calling sequence as far as possible.
3301 * Note that if the user exists, this function will acquire a write lock,
3302 * so it is still advisable to make the call conditional on isLoggedIn(),
3303 * and to commit the transaction after calling.
3305 * @throws MWException
3306 * @return Status
3308 public function addToDatabase() {
3309 $this->load();
3310 if ( !$this->mToken ) {
3311 $this->setToken(); // init token
3314 $this->mTouched = self::newTouchedTimestamp();
3316 $dbw = wfGetDB( DB_MASTER );
3317 $inWrite = $dbw->writesOrCallbacksPending();
3318 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3319 $dbw->insert( 'user',
3320 array(
3321 'user_id' => $seqVal,
3322 'user_name' => $this->mName,
3323 'user_password' => $this->mPassword,
3324 'user_newpassword' => $this->mNewpassword,
3325 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3326 'user_email' => $this->mEmail,
3327 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3328 'user_real_name' => $this->mRealName,
3329 'user_token' => strval( $this->mToken ),
3330 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3331 'user_editcount' => 0,
3332 'user_touched' => $dbw->timestamp( $this->mTouched ),
3333 ), __METHOD__,
3334 array( 'IGNORE' )
3336 if ( !$dbw->affectedRows() ) {
3337 if ( !$inWrite ) {
3338 // XXX: Get out of REPEATABLE-READ so the SELECT below works.
3339 // Often this case happens early in views before any writes.
3340 // This shows up at least with CentralAuth.
3341 $dbw->commit( __METHOD__, 'flush' );
3343 $this->mId = $dbw->selectField( 'user', 'user_id',
3344 array( 'user_name' => $this->mName ), __METHOD__ );
3345 $loaded = false;
3346 if ( $this->mId ) {
3347 if ( $this->loadFromDatabase() ) {
3348 $loaded = true;
3351 if ( !$loaded ) {
3352 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3353 "to insert user '{$this->mName}' row, but it was not present in select!" );
3355 return Status::newFatal( 'userexists' );
3357 $this->mId = $dbw->insertId();
3359 // Clear instance cache other than user table data, which is already accurate
3360 $this->clearInstanceCache();
3362 $this->saveOptions();
3363 return Status::newGood();
3367 * If this user is logged-in and blocked,
3368 * block any IP address they've successfully logged in from.
3369 * @return bool A block was spread
3371 public function spreadAnyEditBlock() {
3372 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3373 return $this->spreadBlock();
3375 return false;
3379 * If this (non-anonymous) user is blocked,
3380 * block the IP address they've successfully logged in from.
3381 * @return bool A block was spread
3383 protected function spreadBlock() {
3384 wfDebug( __METHOD__ . "()\n" );
3385 $this->load();
3386 if ( $this->mId == 0 ) {
3387 return false;
3390 $userblock = Block::newFromTarget( $this->getName() );
3391 if ( !$userblock ) {
3392 return false;
3395 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3399 * Generate a string which will be different for any combination of
3400 * user options which would produce different parser output.
3401 * This will be used as part of the hash key for the parser cache,
3402 * so users with the same options can share the same cached data
3403 * safely.
3405 * Extensions which require it should install 'PageRenderingHash' hook,
3406 * which will give them a chance to modify this key based on their own
3407 * settings.
3409 * @deprecated since 1.17 use the ParserOptions object to get the relevant options
3410 * @return string Page rendering hash
3412 public function getPageRenderingHash() {
3413 wfDeprecated( __METHOD__, '1.17' );
3415 global $wgRenderHashAppend, $wgLang, $wgContLang;
3416 if ( $this->mHash ) {
3417 return $this->mHash;
3420 // stubthreshold is only included below for completeness,
3421 // since it disables the parser cache, its value will always
3422 // be 0 when this function is called by parsercache.
3424 $confstr = $this->getOption( 'math' );
3425 $confstr .= '!' . $this->getStubThreshold();
3426 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ? '1' : '' );
3427 $confstr .= '!' . $wgLang->getCode();
3428 $confstr .= '!' . $this->getOption( 'thumbsize' );
3429 // add in language specific options, if any
3430 $extra = $wgContLang->getExtraHashOptions();
3431 $confstr .= $extra;
3433 // Since the skin could be overloading link(), it should be
3434 // included here but in practice, none of our skins do that.
3436 $confstr .= $wgRenderHashAppend;
3438 // Give a chance for extensions to modify the hash, if they have
3439 // extra options or other effects on the parser cache.
3440 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
3442 // Make it a valid memcached key fragment
3443 $confstr = str_replace( ' ', '_', $confstr );
3444 $this->mHash = $confstr;
3445 return $confstr;
3449 * Get whether the user is explicitly blocked from account creation.
3450 * @return bool|Block
3452 public function isBlockedFromCreateAccount() {
3453 $this->getBlockedStatus();
3454 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3455 return $this->mBlock;
3458 # bug 13611: if the IP address the user is trying to create an account from is
3459 # blocked with createaccount disabled, prevent new account creation there even
3460 # when the user is logged in
3461 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3462 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3464 return $this->mBlockedFromCreateAccount instanceof Block && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3465 ? $this->mBlockedFromCreateAccount
3466 : false;
3470 * Get whether the user is blocked from using Special:Emailuser.
3471 * @return bool
3473 public function isBlockedFromEmailuser() {
3474 $this->getBlockedStatus();
3475 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3479 * Get whether the user is allowed to create an account.
3480 * @return bool
3482 function isAllowedToCreateAccount() {
3483 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3487 * Get this user's personal page title.
3489 * @return Title: User's personal page title
3491 public function getUserPage() {
3492 return Title::makeTitle( NS_USER, $this->getName() );
3496 * Get this user's talk page title.
3498 * @return Title: User's talk page title
3500 public function getTalkPage() {
3501 $title = $this->getUserPage();
3502 return $title->getTalkPage();
3506 * Determine whether the user is a newbie. Newbies are either
3507 * anonymous IPs, or the most recently created accounts.
3508 * @return bool
3510 public function isNewbie() {
3511 return !$this->isAllowed( 'autoconfirmed' );
3515 * Check to see if the given clear-text password is one of the accepted passwords
3516 * @param string $password user password.
3517 * @return boolean: True if the given password is correct, otherwise False.
3519 public function checkPassword( $password ) {
3520 global $wgAuth, $wgLegacyEncoding;
3521 $this->load();
3523 // Even though we stop people from creating passwords that
3524 // are shorter than this, doesn't mean people wont be able
3525 // to. Certain authentication plugins do NOT want to save
3526 // domain passwords in a mysql database, so we should
3527 // check this (in case $wgAuth->strict() is false).
3528 if ( !$this->isValidPassword( $password ) ) {
3529 return false;
3532 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3533 return true;
3534 } elseif ( $wgAuth->strict() ) {
3535 // Auth plugin doesn't allow local authentication
3536 return false;
3537 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3538 // Auth plugin doesn't allow local authentication for this user name
3539 return false;
3541 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
3542 return true;
3543 } elseif ( $wgLegacyEncoding ) {
3544 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3545 // Check for this with iconv
3546 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3547 if ( $cp1252Password != $password &&
3548 self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) )
3550 return true;
3553 return false;
3557 * Check if the given clear-text password matches the temporary password
3558 * sent by e-mail for password reset operations.
3560 * @param $plaintext string
3562 * @return boolean: True if matches, false otherwise
3564 public function checkTemporaryPassword( $plaintext ) {
3565 global $wgNewPasswordExpiry;
3567 $this->load();
3568 if ( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
3569 if ( is_null( $this->mNewpassTime ) ) {
3570 return true;
3572 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
3573 return ( time() < $expiry );
3574 } else {
3575 return false;
3580 * Alias for getEditToken.
3581 * @deprecated since 1.19, use getEditToken instead.
3583 * @param string|array $salt of Strings Optional function-specific data for hashing
3584 * @param $request WebRequest object to use or null to use $wgRequest
3585 * @return string The new edit token
3587 public function editToken( $salt = '', $request = null ) {
3588 wfDeprecated( __METHOD__, '1.19' );
3589 return $this->getEditToken( $salt, $request );
3593 * Initialize (if necessary) and return a session token value
3594 * which can be used in edit forms to show that the user's
3595 * login credentials aren't being hijacked with a foreign form
3596 * submission.
3598 * @since 1.19
3600 * @param string|array $salt of Strings Optional function-specific data for hashing
3601 * @param $request WebRequest object to use or null to use $wgRequest
3602 * @return string The new edit token
3604 public function getEditToken( $salt = '', $request = null ) {
3605 if ( $request == null ) {
3606 $request = $this->getRequest();
3609 if ( $this->isAnon() ) {
3610 return EDIT_TOKEN_SUFFIX;
3611 } else {
3612 $token = $request->getSessionData( 'wsEditToken' );
3613 if ( $token === null ) {
3614 $token = MWCryptRand::generateHex( 32 );
3615 $request->setSessionData( 'wsEditToken', $token );
3617 if ( is_array( $salt ) ) {
3618 $salt = implode( '|', $salt );
3620 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
3625 * Generate a looking random token for various uses.
3627 * @return string The new random token
3628 * @deprecated since 1.20: Use MWCryptRand for secure purposes or wfRandomString for pseudo-randomness
3630 public static function generateToken() {
3631 return MWCryptRand::generateHex( 32 );
3635 * Check given value against the token value stored in the session.
3636 * A match should confirm that the form was submitted from the
3637 * user's own login session, not a form submission from a third-party
3638 * site.
3640 * @param string $val Input value to compare
3641 * @param string $salt Optional function-specific data for hashing
3642 * @param WebRequest $request Object to use or null to use $wgRequest
3643 * @return boolean: Whether the token matches
3645 public function matchEditToken( $val, $salt = '', $request = null ) {
3646 $sessionToken = $this->getEditToken( $salt, $request );
3647 if ( $val != $sessionToken ) {
3648 wfDebug( "User::matchEditToken: broken session data\n" );
3650 return $val == $sessionToken;
3654 * Check given value against the token value stored in the session,
3655 * ignoring the suffix.
3657 * @param string $val Input value to compare
3658 * @param string $salt Optional function-specific data for hashing
3659 * @param WebRequest $request object to use or null to use $wgRequest
3660 * @return boolean: Whether the token matches
3662 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3663 $sessionToken = $this->getEditToken( $salt, $request );
3664 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3668 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3669 * mail to the user's given address.
3671 * @param string $type message to send, either "created", "changed" or "set"
3672 * @return Status object
3674 public function sendConfirmationMail( $type = 'created' ) {
3675 global $wgLang;
3676 $expiration = null; // gets passed-by-ref and defined in next line.
3677 $token = $this->confirmationToken( $expiration );
3678 $url = $this->confirmationTokenUrl( $token );
3679 $invalidateURL = $this->invalidationTokenUrl( $token );
3680 $this->saveSettings();
3682 if ( $type == 'created' || $type === false ) {
3683 $message = 'confirmemail_body';
3684 } elseif ( $type === true ) {
3685 $message = 'confirmemail_body_changed';
3686 } else {
3687 $message = 'confirmemail_body_' . $type;
3690 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3691 wfMessage( $message,
3692 $this->getRequest()->getIP(),
3693 $this->getName(),
3694 $url,
3695 $wgLang->timeanddate( $expiration, false ),
3696 $invalidateURL,
3697 $wgLang->date( $expiration, false ),
3698 $wgLang->time( $expiration, false ) )->text() );
3702 * Send an e-mail to this user's account. Does not check for
3703 * confirmed status or validity.
3705 * @param string $subject Message subject
3706 * @param string $body Message body
3707 * @param string $from Optional From address; if unspecified, default $wgPasswordSender will be used
3708 * @param string $replyto Reply-To address
3709 * @return Status
3711 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3712 if ( is_null( $from ) ) {
3713 global $wgPasswordSender, $wgPasswordSenderName;
3714 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
3715 } else {
3716 $sender = new MailAddress( $from );
3719 $to = new MailAddress( $this );
3720 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
3724 * Generate, store, and return a new e-mail confirmation code.
3725 * A hash (unsalted, since it's used as a key) is stored.
3727 * @note Call saveSettings() after calling this function to commit
3728 * this change to the database.
3730 * @param &$expiration \mixed Accepts the expiration time
3731 * @return string New token
3733 protected function confirmationToken( &$expiration ) {
3734 global $wgUserEmailConfirmationTokenExpiry;
3735 $now = time();
3736 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
3737 $expiration = wfTimestamp( TS_MW, $expires );
3738 $this->load();
3739 $token = MWCryptRand::generateHex( 32 );
3740 $hash = md5( $token );
3741 $this->mEmailToken = $hash;
3742 $this->mEmailTokenExpires = $expiration;
3743 return $token;
3747 * Return a URL the user can use to confirm their email address.
3748 * @param string $token Accepts the email confirmation token
3749 * @return string New token URL
3751 protected function confirmationTokenUrl( $token ) {
3752 return $this->getTokenUrl( 'ConfirmEmail', $token );
3756 * Return a URL the user can use to invalidate their email address.
3757 * @param string $token Accepts the email confirmation token
3758 * @return string New token URL
3760 protected function invalidationTokenUrl( $token ) {
3761 return $this->getTokenUrl( 'InvalidateEmail', $token );
3765 * Internal function to format the e-mail validation/invalidation URLs.
3766 * This uses a quickie hack to use the
3767 * hardcoded English names of the Special: pages, for ASCII safety.
3769 * @note Since these URLs get dropped directly into emails, using the
3770 * short English names avoids insanely long URL-encoded links, which
3771 * also sometimes can get corrupted in some browsers/mailers
3772 * (bug 6957 with Gmail and Internet Explorer).
3774 * @param string $page Special page
3775 * @param string $token Token
3776 * @return string Formatted URL
3778 protected function getTokenUrl( $page, $token ) {
3779 // Hack to bypass localization of 'Special:'
3780 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
3781 return $title->getCanonicalURL();
3785 * Mark the e-mail address confirmed.
3787 * @note Call saveSettings() after calling this function to commit the change.
3789 * @return bool
3791 public function confirmEmail() {
3792 // Check if it's already confirmed, so we don't touch the database
3793 // and fire the ConfirmEmailComplete hook on redundant confirmations.
3794 if ( !$this->isEmailConfirmed() ) {
3795 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3796 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3798 return true;
3802 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3803 * address if it was already confirmed.
3805 * @note Call saveSettings() after calling this function to commit the change.
3806 * @return bool Returns true
3808 function invalidateEmail() {
3809 $this->load();
3810 $this->mEmailToken = null;
3811 $this->mEmailTokenExpires = null;
3812 $this->setEmailAuthenticationTimestamp( null );
3813 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3814 return true;
3818 * Set the e-mail authentication timestamp.
3819 * @param string $timestamp TS_MW timestamp
3821 function setEmailAuthenticationTimestamp( $timestamp ) {
3822 $this->load();
3823 $this->mEmailAuthenticated = $timestamp;
3824 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
3828 * Is this user allowed to send e-mails within limits of current
3829 * site configuration?
3830 * @return bool
3832 public function canSendEmail() {
3833 global $wgEnableEmail, $wgEnableUserEmail;
3834 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
3835 return false;
3837 $canSend = $this->isEmailConfirmed();
3838 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3839 return $canSend;
3843 * Is this user allowed to receive e-mails within limits of current
3844 * site configuration?
3845 * @return bool
3847 public function canReceiveEmail() {
3848 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3852 * Is this user's e-mail address valid-looking and confirmed within
3853 * limits of the current site configuration?
3855 * @note If $wgEmailAuthentication is on, this may require the user to have
3856 * confirmed their address by returning a code or using a password
3857 * sent to the address from the wiki.
3859 * @return bool
3861 public function isEmailConfirmed() {
3862 global $wgEmailAuthentication;
3863 $this->load();
3864 $confirmed = true;
3865 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3866 if ( $this->isAnon() ) {
3867 return false;
3869 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
3870 return false;
3872 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
3873 return false;
3875 return true;
3876 } else {
3877 return $confirmed;
3882 * Check whether there is an outstanding request for e-mail confirmation.
3883 * @return bool
3885 public function isEmailConfirmationPending() {
3886 global $wgEmailAuthentication;
3887 return $wgEmailAuthentication &&
3888 !$this->isEmailConfirmed() &&
3889 $this->mEmailToken &&
3890 $this->mEmailTokenExpires > wfTimestamp();
3894 * Get the timestamp of account creation.
3896 * @return string|bool|null Timestamp of account creation, false for
3897 * non-existent/anonymous user accounts, or null if existing account
3898 * but information is not in database.
3900 public function getRegistration() {
3901 if ( $this->isAnon() ) {
3902 return false;
3904 $this->load();
3905 return $this->mRegistration;
3909 * Get the timestamp of the first edit
3911 * @return string|bool Timestamp of first edit, or false for
3912 * non-existent/anonymous user accounts.
3914 public function getFirstEditTimestamp() {
3915 if ( $this->getId() == 0 ) {
3916 return false; // anons
3918 $dbr = wfGetDB( DB_SLAVE );
3919 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3920 array( 'rev_user' => $this->getId() ),
3921 __METHOD__,
3922 array( 'ORDER BY' => 'rev_timestamp ASC' )
3924 if ( !$time ) {
3925 return false; // no edits
3927 return wfTimestamp( TS_MW, $time );
3931 * Get the permissions associated with a given list of groups
3933 * @param array $groups of Strings List of internal group names
3934 * @return Array of Strings List of permission key names for given groups combined
3936 public static function getGroupPermissions( $groups ) {
3937 global $wgGroupPermissions, $wgRevokePermissions;
3938 $rights = array();
3939 // grant every granted permission first
3940 foreach ( $groups as $group ) {
3941 if ( isset( $wgGroupPermissions[$group] ) ) {
3942 $rights = array_merge( $rights,
3943 // array_filter removes empty items
3944 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3947 // now revoke the revoked permissions
3948 foreach ( $groups as $group ) {
3949 if ( isset( $wgRevokePermissions[$group] ) ) {
3950 $rights = array_diff( $rights,
3951 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3954 return array_unique( $rights );
3958 * Get all the groups who have a given permission
3960 * @param string $role Role to check
3961 * @return Array of Strings List of internal group names with the given permission
3963 public static function getGroupsWithPermission( $role ) {
3964 global $wgGroupPermissions;
3965 $allowedGroups = array();
3966 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
3967 if ( self::groupHasPermission( $group, $role ) ) {
3968 $allowedGroups[] = $group;
3971 return $allowedGroups;
3975 * Check, if the given group has the given permission
3977 * If you're wanting to check whether all users have a permission, use
3978 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
3979 * from anyone.
3981 * @since 1.21
3982 * @param string $group Group to check
3983 * @param string $role Role to check
3984 * @return bool
3986 public static function groupHasPermission( $group, $role ) {
3987 global $wgGroupPermissions, $wgRevokePermissions;
3988 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
3989 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
3993 * Check if all users have the given permission
3995 * @since 1.22
3996 * @param string $right Right to check
3997 * @return bool
3999 public static function isEveryoneAllowed( $right ) {
4000 global $wgGroupPermissions, $wgRevokePermissions;
4001 static $cache = array();
4003 // Use the cached results, except in unit tests which rely on
4004 // being able change the permission mid-request
4005 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4006 return $cache[$right];
4009 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4010 $cache[$right] = false;
4011 return false;
4014 // If it's revoked anywhere, then everyone doesn't have it
4015 foreach ( $wgRevokePermissions as $rights ) {
4016 if ( isset( $rights[$right] ) && $rights[$right] ) {
4017 $cache[$right] = false;
4018 return false;
4022 // Allow extensions (e.g. OAuth) to say false
4023 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4024 $cache[$right] = false;
4025 return false;
4028 $cache[$right] = true;
4029 return true;
4033 * Get the localized descriptive name for a group, if it exists
4035 * @param string $group Internal group name
4036 * @return string Localized descriptive group name
4038 public static function getGroupName( $group ) {
4039 $msg = wfMessage( "group-$group" );
4040 return $msg->isBlank() ? $group : $msg->text();
4044 * Get the localized descriptive name for a member of a group, if it exists
4046 * @param string $group Internal group name
4047 * @param string $username Username for gender (since 1.19)
4048 * @return string Localized name for group member
4050 public static function getGroupMember( $group, $username = '#' ) {
4051 $msg = wfMessage( "group-$group-member", $username );
4052 return $msg->isBlank() ? $group : $msg->text();
4056 * Return the set of defined explicit groups.
4057 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4058 * are not included, as they are defined automatically, not in the database.
4059 * @return Array of internal group names
4061 public static function getAllGroups() {
4062 global $wgGroupPermissions, $wgRevokePermissions;
4063 return array_diff(
4064 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4065 self::getImplicitGroups()
4070 * Get a list of all available permissions.
4071 * @return Array of permission names
4073 public static function getAllRights() {
4074 if ( self::$mAllRights === false ) {
4075 global $wgAvailableRights;
4076 if ( count( $wgAvailableRights ) ) {
4077 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4078 } else {
4079 self::$mAllRights = self::$mCoreRights;
4081 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
4083 return self::$mAllRights;
4087 * Get a list of implicit groups
4088 * @return Array of Strings Array of internal group names
4090 public static function getImplicitGroups() {
4091 global $wgImplicitGroups;
4092 $groups = $wgImplicitGroups;
4093 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
4094 return $groups;
4098 * Get the title of a page describing a particular group
4100 * @param string $group Internal group name
4101 * @return Title|bool Title of the page if it exists, false otherwise
4103 public static function getGroupPage( $group ) {
4104 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4105 if ( $msg->exists() ) {
4106 $title = Title::newFromText( $msg->text() );
4107 if ( is_object( $title ) ) {
4108 return $title;
4111 return false;
4115 * Create a link to the group in HTML, if available;
4116 * else return the group name.
4118 * @param string $group Internal name of the group
4119 * @param string $text The text of the link
4120 * @return string HTML link to the group
4122 public static function makeGroupLinkHTML( $group, $text = '' ) {
4123 if ( $text == '' ) {
4124 $text = self::getGroupName( $group );
4126 $title = self::getGroupPage( $group );
4127 if ( $title ) {
4128 return Linker::link( $title, htmlspecialchars( $text ) );
4129 } else {
4130 return $text;
4135 * Create a link to the group in Wikitext, if available;
4136 * else return the group name.
4138 * @param string $group Internal name of the group
4139 * @param string $text The text of the link
4140 * @return string Wikilink to the group
4142 public static function makeGroupLinkWiki( $group, $text = '' ) {
4143 if ( $text == '' ) {
4144 $text = self::getGroupName( $group );
4146 $title = self::getGroupPage( $group );
4147 if ( $title ) {
4148 $page = $title->getPrefixedText();
4149 return "[[$page|$text]]";
4150 } else {
4151 return $text;
4156 * Returns an array of the groups that a particular group can add/remove.
4158 * @param string $group the group to check for whether it can add/remove
4159 * @return Array array( 'add' => array( addablegroups ),
4160 * 'remove' => array( removablegroups ),
4161 * 'add-self' => array( addablegroups to self),
4162 * 'remove-self' => array( removable groups from self) )
4164 public static function changeableByGroup( $group ) {
4165 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4167 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
4168 if ( empty( $wgAddGroups[$group] ) ) {
4169 // Don't add anything to $groups
4170 } elseif ( $wgAddGroups[$group] === true ) {
4171 // You get everything
4172 $groups['add'] = self::getAllGroups();
4173 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4174 $groups['add'] = $wgAddGroups[$group];
4177 // Same thing for remove
4178 if ( empty( $wgRemoveGroups[$group] ) ) {
4179 } elseif ( $wgRemoveGroups[$group] === true ) {
4180 $groups['remove'] = self::getAllGroups();
4181 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4182 $groups['remove'] = $wgRemoveGroups[$group];
4185 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4186 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4187 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4188 if ( is_int( $key ) ) {
4189 $wgGroupsAddToSelf['user'][] = $value;
4194 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4195 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4196 if ( is_int( $key ) ) {
4197 $wgGroupsRemoveFromSelf['user'][] = $value;
4202 // Now figure out what groups the user can add to him/herself
4203 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4204 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4205 // No idea WHY this would be used, but it's there
4206 $groups['add-self'] = User::getAllGroups();
4207 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4208 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4211 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4212 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4213 $groups['remove-self'] = User::getAllGroups();
4214 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4215 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4218 return $groups;
4222 * Returns an array of groups that this user can add and remove
4223 * @return Array array( 'add' => array( addablegroups ),
4224 * 'remove' => array( removablegroups ),
4225 * 'add-self' => array( addablegroups to self),
4226 * 'remove-self' => array( removable groups from self) )
4228 public function changeableGroups() {
4229 if ( $this->isAllowed( 'userrights' ) ) {
4230 // This group gives the right to modify everything (reverse-
4231 // compatibility with old "userrights lets you change
4232 // everything")
4233 // Using array_merge to make the groups reindexed
4234 $all = array_merge( User::getAllGroups() );
4235 return array(
4236 'add' => $all,
4237 'remove' => $all,
4238 'add-self' => array(),
4239 'remove-self' => array()
4243 // Okay, it's not so simple, we will have to go through the arrays
4244 $groups = array(
4245 'add' => array(),
4246 'remove' => array(),
4247 'add-self' => array(),
4248 'remove-self' => array()
4250 $addergroups = $this->getEffectiveGroups();
4252 foreach ( $addergroups as $addergroup ) {
4253 $groups = array_merge_recursive(
4254 $groups, $this->changeableByGroup( $addergroup )
4256 $groups['add'] = array_unique( $groups['add'] );
4257 $groups['remove'] = array_unique( $groups['remove'] );
4258 $groups['add-self'] = array_unique( $groups['add-self'] );
4259 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4261 return $groups;
4265 * Increment the user's edit-count field.
4266 * Will have no effect for anonymous users.
4268 public function incEditCount() {
4269 if ( !$this->isAnon() ) {
4270 $dbw = wfGetDB( DB_MASTER );
4271 $dbw->update(
4272 'user',
4273 array( 'user_editcount=user_editcount+1' ),
4274 array( 'user_id' => $this->getId() ),
4275 __METHOD__
4278 // Lazy initialization check...
4279 if ( $dbw->affectedRows() == 0 ) {
4280 // Now here's a goddamn hack...
4281 $dbr = wfGetDB( DB_SLAVE );
4282 if ( $dbr !== $dbw ) {
4283 // If we actually have a slave server, the count is
4284 // at least one behind because the current transaction
4285 // has not been committed and replicated.
4286 $this->initEditCount( 1 );
4287 } else {
4288 // But if DB_SLAVE is selecting the master, then the
4289 // count we just read includes the revision that was
4290 // just added in the working transaction.
4291 $this->initEditCount();
4295 // edit count in user cache too
4296 $this->invalidateCache();
4300 * Initialize user_editcount from data out of the revision table
4302 * @param $add Integer Edits to add to the count from the revision table
4303 * @return integer Number of edits
4305 protected function initEditCount( $add = 0 ) {
4306 // Pull from a slave to be less cruel to servers
4307 // Accuracy isn't the point anyway here
4308 $dbr = wfGetDB( DB_SLAVE );
4309 $count = (int) $dbr->selectField(
4310 'revision',
4311 'COUNT(rev_user)',
4312 array( 'rev_user' => $this->getId() ),
4313 __METHOD__
4315 $count = $count + $add;
4317 $dbw = wfGetDB( DB_MASTER );
4318 $dbw->update(
4319 'user',
4320 array( 'user_editcount' => $count ),
4321 array( 'user_id' => $this->getId() ),
4322 __METHOD__
4325 return $count;
4329 * Get the description of a given right
4331 * @param string $right Right to query
4332 * @return string Localized description of the right
4334 public static function getRightDescription( $right ) {
4335 $key = "right-$right";
4336 $msg = wfMessage( $key );
4337 return $msg->isBlank() ? $right : $msg->text();
4341 * Make an old-style password hash
4343 * @param string $password Plain-text password
4344 * @param string $userId User ID
4345 * @return string Password hash
4347 public static function oldCrypt( $password, $userId ) {
4348 global $wgPasswordSalt;
4349 if ( $wgPasswordSalt ) {
4350 return md5( $userId . '-' . md5( $password ) );
4351 } else {
4352 return md5( $password );
4357 * Make a new-style password hash
4359 * @param string $password Plain-text password
4360 * @param bool|string $salt Optional salt, may be random or the user ID.
4361 * If unspecified or false, will generate one automatically
4362 * @return string Password hash
4364 public static function crypt( $password, $salt = false ) {
4365 global $wgPasswordSalt;
4367 $hash = '';
4368 if ( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4369 return $hash;
4372 if ( $wgPasswordSalt ) {
4373 if ( $salt === false ) {
4374 $salt = MWCryptRand::generateHex( 8 );
4376 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4377 } else {
4378 return ':A:' . md5( $password );
4383 * Compare a password hash with a plain-text password. Requires the user
4384 * ID if there's a chance that the hash is an old-style hash.
4386 * @param string $hash Password hash
4387 * @param string $password Plain-text password to compare
4388 * @param string|bool $userId User ID for old-style password salt
4390 * @return boolean
4392 public static function comparePasswords( $hash, $password, $userId = false ) {
4393 $type = substr( $hash, 0, 3 );
4395 $result = false;
4396 if ( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4397 return $result;
4400 if ( $type == ':A:' ) {
4401 // Unsalted
4402 return md5( $password ) === substr( $hash, 3 );
4403 } elseif ( $type == ':B:' ) {
4404 // Salted
4405 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4406 return md5( $salt . '-' . md5( $password ) ) === $realHash;
4407 } else {
4408 // Old-style
4409 return self::oldCrypt( $password, $userId ) === $hash;
4414 * Add a newuser log entry for this user.
4415 * Before 1.19 the return value was always true.
4417 * @param string|bool $action account creation type.
4418 * - String, one of the following values:
4419 * - 'create' for an anonymous user creating an account for himself.
4420 * This will force the action's performer to be the created user itself,
4421 * no matter the value of $wgUser
4422 * - 'create2' for a logged in user creating an account for someone else
4423 * - 'byemail' when the created user will receive its password by e-mail
4424 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4425 * - Boolean means whether the account was created by e-mail (deprecated):
4426 * - true will be converted to 'byemail'
4427 * - false will be converted to 'create' if this object is the same as
4428 * $wgUser and to 'create2' otherwise
4430 * @param string $reason user supplied reason
4432 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4434 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4435 global $wgUser, $wgNewUserLog;
4436 if ( empty( $wgNewUserLog ) ) {
4437 return true; // disabled
4440 if ( $action === true ) {
4441 $action = 'byemail';
4442 } elseif ( $action === false ) {
4443 if ( $this->getName() == $wgUser->getName() ) {
4444 $action = 'create';
4445 } else {
4446 $action = 'create2';
4450 if ( $action === 'create' || $action === 'autocreate' ) {
4451 $performer = $this;
4452 } else {
4453 $performer = $wgUser;
4456 $logEntry = new ManualLogEntry( 'newusers', $action );
4457 $logEntry->setPerformer( $performer );
4458 $logEntry->setTarget( $this->getUserPage() );
4459 $logEntry->setComment( $reason );
4460 $logEntry->setParameters( array(
4461 '4::userid' => $this->getId(),
4462 ) );
4463 $logid = $logEntry->insert();
4465 if ( $action !== 'autocreate' ) {
4466 $logEntry->publish( $logid );
4469 return (int)$logid;
4473 * Add an autocreate newuser log entry for this user
4474 * Used by things like CentralAuth and perhaps other authplugins.
4475 * Consider calling addNewUserLogEntry() directly instead.
4477 * @return bool
4479 public function addNewUserLogEntryAutoCreate() {
4480 $this->addNewUserLogEntry( 'autocreate' );
4482 return true;
4486 * Load the user options either from cache, the database or an array
4488 * @param array $data Rows for the current user out of the user_properties table
4490 protected function loadOptions( $data = null ) {
4491 global $wgContLang;
4493 $this->load();
4495 if ( $this->mOptionsLoaded ) {
4496 return;
4499 $this->mOptions = self::getDefaultOptions();
4501 if ( !$this->getId() ) {
4502 // For unlogged-in users, load language/variant options from request.
4503 // There's no need to do it for logged-in users: they can set preferences,
4504 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4505 // so don't override user's choice (especially when the user chooses site default).
4506 $variant = $wgContLang->getDefaultVariant();
4507 $this->mOptions['variant'] = $variant;
4508 $this->mOptions['language'] = $variant;
4509 $this->mOptionsLoaded = true;
4510 return;
4513 // Maybe load from the object
4514 if ( !is_null( $this->mOptionOverrides ) ) {
4515 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4516 foreach ( $this->mOptionOverrides as $key => $value ) {
4517 $this->mOptions[$key] = $value;
4519 } else {
4520 if ( !is_array( $data ) ) {
4521 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4522 // Load from database
4523 $dbr = wfGetDB( DB_SLAVE );
4525 $res = $dbr->select(
4526 'user_properties',
4527 array( 'up_property', 'up_value' ),
4528 array( 'up_user' => $this->getId() ),
4529 __METHOD__
4532 $this->mOptionOverrides = array();
4533 $data = array();
4534 foreach ( $res as $row ) {
4535 $data[$row->up_property] = $row->up_value;
4538 foreach ( $data as $property => $value ) {
4539 $this->mOptionOverrides[$property] = $value;
4540 $this->mOptions[$property] = $value;
4544 $this->mOptionsLoaded = true;
4546 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
4550 * @todo document
4552 protected function saveOptions() {
4553 $this->loadOptions();
4555 // Not using getOptions(), to keep hidden preferences in database
4556 $saveOptions = $this->mOptions;
4558 // Allow hooks to abort, for instance to save to a global profile.
4559 // Reset options to default state before saving.
4560 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4561 return;
4564 $userId = $this->getId();
4565 $insert_rows = array();
4566 foreach ( $saveOptions as $key => $value ) {
4567 // Don't bother storing default values
4568 $defaultOption = self::getDefaultOption( $key );
4569 if ( ( is_null( $defaultOption ) &&
4570 !( $value === false || is_null( $value ) ) ) ||
4571 $value != $defaultOption ) {
4572 $insert_rows[] = array(
4573 'up_user' => $userId,
4574 'up_property' => $key,
4575 'up_value' => $value,
4580 $dbw = wfGetDB( DB_MASTER );
4581 $hasRows = $dbw->selectField( 'user_properties', '1',
4582 array( 'up_user' => $userId ), __METHOD__ );
4584 if ( $hasRows ) {
4585 // Only do this delete if there is something there. A very large portion of
4586 // calls to this function are for setting 'rememberpassword' for new accounts.
4587 // Doing this delete for new accounts with no rows in the table rougly causes
4588 // gap locks on [max user ID,+infinity) which causes high contention since many
4589 // updates will pile up on each other since they are for higher (newer) user IDs.
4590 $dbw->delete( 'user_properties', array( 'up_user' => $userId ), __METHOD__ );
4592 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
4596 * Provide an array of HTML5 attributes to put on an input element
4597 * intended for the user to enter a new password. This may include
4598 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4600 * Do *not* use this when asking the user to enter his current password!
4601 * Regardless of configuration, users may have invalid passwords for whatever
4602 * reason (e.g., they were set before requirements were tightened up).
4603 * Only use it when asking for a new password, like on account creation or
4604 * ResetPass.
4606 * Obviously, you still need to do server-side checking.
4608 * NOTE: A combination of bugs in various browsers means that this function
4609 * actually just returns array() unconditionally at the moment. May as
4610 * well keep it around for when the browser bugs get fixed, though.
4612 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4614 * @return array Array of HTML attributes suitable for feeding to
4615 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4616 * That will get confused by the boolean attribute syntax used.)
4618 public static function passwordChangeInputAttribs() {
4619 global $wgMinimalPasswordLength;
4621 if ( $wgMinimalPasswordLength == 0 ) {
4622 return array();
4625 # Note that the pattern requirement will always be satisfied if the
4626 # input is empty, so we need required in all cases.
4628 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4629 # if e-mail confirmation is being used. Since HTML5 input validation
4630 # is b0rked anyway in some browsers, just return nothing. When it's
4631 # re-enabled, fix this code to not output required for e-mail
4632 # registration.
4633 #$ret = array( 'required' );
4634 $ret = array();
4636 # We can't actually do this right now, because Opera 9.6 will print out
4637 # the entered password visibly in its error message! When other
4638 # browsers add support for this attribute, or Opera fixes its support,
4639 # we can add support with a version check to avoid doing this on Opera
4640 # versions where it will be a problem. Reported to Opera as
4641 # DSK-262266, but they don't have a public bug tracker for us to follow.
4643 if ( $wgMinimalPasswordLength > 1 ) {
4644 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4645 $ret['title'] = wfMessage( 'passwordtooshort' )
4646 ->numParams( $wgMinimalPasswordLength )->text();
4650 return $ret;
4654 * Return the list of user fields that should be selected to create
4655 * a new user object.
4656 * @return array
4658 public static function selectFields() {
4659 return array(
4660 'user_id',
4661 'user_name',
4662 'user_real_name',
4663 'user_password',
4664 'user_newpassword',
4665 'user_newpass_time',
4666 'user_email',
4667 'user_touched',
4668 'user_token',
4669 'user_email_authenticated',
4670 'user_email_token',
4671 'user_email_token_expires',
4672 'user_registration',
4673 'user_editcount',
4678 * Factory function for fatal permission-denied errors
4680 * @since 1.22
4681 * @param string $permission User right required
4682 * @return Status
4684 static function newFatalPermissionDeniedStatus( $permission ) {
4685 global $wgLang;
4687 $groups = array_map(
4688 array( 'User', 'makeGroupLinkWiki' ),
4689 User::getGroupsWithPermission( $permission )
4692 if ( $groups ) {
4693 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4694 } else {
4695 return Status::newFatal( 'badaccess-group0' );