Merge "Default is not necessary for toggle fields"
[mediawiki.git] / includes / User.php
blob29230265ad077964a184b97ac1fb0d2d36378908
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'] = $wgContLang->getCode();
1244 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1245 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1247 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1248 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1250 $defOpt['skin'] = $wgDefaultSkin;
1252 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1254 return $defOpt;
1258 * Get a given default option value.
1260 * @param string $opt Name of option to retrieve
1261 * @return string Default option value
1263 public static function getDefaultOption( $opt ) {
1264 $defOpts = self::getDefaultOptions();
1265 if ( isset( $defOpts[$opt] ) ) {
1266 return $defOpts[$opt];
1267 } else {
1268 return null;
1273 * Get blocking information
1274 * @param bool $bFromSlave Whether to check the slave database first. To
1275 * improve performance, non-critical checks are done
1276 * against slaves. Check when actually saving should be
1277 * done against master.
1279 private function getBlockedStatus( $bFromSlave = true ) {
1280 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1282 if ( -1 != $this->mBlockedby ) {
1283 return;
1286 wfProfileIn( __METHOD__ );
1287 wfDebug( __METHOD__ . ": checking...\n" );
1289 // Initialize data...
1290 // Otherwise something ends up stomping on $this->mBlockedby when
1291 // things get lazy-loaded later, causing false positive block hits
1292 // due to -1 !== 0. Probably session-related... Nothing should be
1293 // overwriting mBlockedby, surely?
1294 $this->load();
1296 # We only need to worry about passing the IP address to the Block generator if the
1297 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1298 # know which IP address they're actually coming from
1299 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1300 $ip = $this->getRequest()->getIP();
1301 } else {
1302 $ip = null;
1305 // User/IP blocking
1306 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1308 // Proxy blocking
1309 if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1310 && !in_array( $ip, $wgProxyWhitelist ) )
1312 // Local list
1313 if ( self::isLocallyBlockedProxy( $ip ) ) {
1314 $block = new Block;
1315 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1316 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1317 $block->setTarget( $ip );
1318 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1319 $block = new Block;
1320 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1321 $block->mReason = wfMessage( 'sorbsreason' )->text();
1322 $block->setTarget( $ip );
1326 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1327 if ( !$block instanceof Block
1328 && $wgApplyIpBlocksToXff
1329 && $ip !== null
1330 && !$this->isAllowed( 'proxyunbannable' )
1331 && !in_array( $ip, $wgProxyWhitelist )
1333 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1334 $xff = array_map( 'trim', explode( ',', $xff ) );
1335 $xff = array_diff( $xff, array( $ip ) );
1336 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1337 $block = Block::chooseBlock( $xffblocks, $xff );
1338 if ( $block instanceof Block ) {
1339 # Mangle the reason to alert the user that the block
1340 # originated from matching the X-Forwarded-For header.
1341 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1345 if ( $block instanceof Block ) {
1346 wfDebug( __METHOD__ . ": Found block.\n" );
1347 $this->mBlock = $block;
1348 $this->mBlockedby = $block->getByName();
1349 $this->mBlockreason = $block->mReason;
1350 $this->mHideName = $block->mHideName;
1351 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1352 } else {
1353 $this->mBlockedby = '';
1354 $this->mHideName = 0;
1355 $this->mAllowUsertalk = false;
1358 // Extensions
1359 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1361 wfProfileOut( __METHOD__ );
1365 * Whether the given IP is in a DNS blacklist.
1367 * @param string $ip IP to check
1368 * @param bool $checkWhitelist whether to check the whitelist first
1369 * @return bool True if blacklisted.
1371 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1372 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1373 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1375 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs ) {
1376 return false;
1379 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1380 return false;
1383 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1384 return $this->inDnsBlacklist( $ip, $urls );
1388 * Whether the given IP is in a given DNS blacklist.
1390 * @param string $ip IP to check
1391 * @param string|array $bases of Strings: URL of the DNS blacklist
1392 * @return bool True if blacklisted.
1394 public function inDnsBlacklist( $ip, $bases ) {
1395 wfProfileIn( __METHOD__ );
1397 $found = false;
1398 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1399 if ( IP::isIPv4( $ip ) ) {
1400 // Reverse IP, bug 21255
1401 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1403 foreach ( (array)$bases as $base ) {
1404 // Make hostname
1405 // If we have an access key, use that too (ProjectHoneypot, etc.)
1406 if ( is_array( $base ) ) {
1407 if ( count( $base ) >= 2 ) {
1408 // Access key is 1, base URL is 0
1409 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1410 } else {
1411 $host = "$ipReversed.{$base[0]}";
1413 } else {
1414 $host = "$ipReversed.$base";
1417 // Send query
1418 $ipList = gethostbynamel( $host );
1420 if ( $ipList ) {
1421 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1422 $found = true;
1423 break;
1424 } else {
1425 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base.\n" );
1430 wfProfileOut( __METHOD__ );
1431 return $found;
1435 * Check if an IP address is in the local proxy list
1437 * @param $ip string
1439 * @return bool
1441 public static function isLocallyBlockedProxy( $ip ) {
1442 global $wgProxyList;
1444 if ( !$wgProxyList ) {
1445 return false;
1447 wfProfileIn( __METHOD__ );
1449 if ( !is_array( $wgProxyList ) ) {
1450 // Load from the specified file
1451 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1454 if ( !is_array( $wgProxyList ) ) {
1455 $ret = false;
1456 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1457 $ret = true;
1458 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1459 // Old-style flipped proxy list
1460 $ret = true;
1461 } else {
1462 $ret = false;
1464 wfProfileOut( __METHOD__ );
1465 return $ret;
1469 * Is this user subject to rate limiting?
1471 * @return bool True if rate limited
1473 public function isPingLimitable() {
1474 global $wgRateLimitsExcludedIPs;
1475 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1476 // No other good way currently to disable rate limits
1477 // for specific IPs. :P
1478 // But this is a crappy hack and should die.
1479 return false;
1481 return !$this->isAllowed( 'noratelimit' );
1485 * Primitive rate limits: enforce maximum actions per time period
1486 * to put a brake on flooding.
1488 * @note When using a shared cache like memcached, IP-address
1489 * last-hit counters will be shared across wikis.
1491 * @param string $action Action to enforce; 'edit' if unspecified
1492 * @return bool True if a rate limiter was tripped
1494 public function pingLimiter( $action = 'edit' ) {
1495 // Call the 'PingLimiter' hook
1496 $result = false;
1497 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result ) ) ) {
1498 return $result;
1501 global $wgRateLimits;
1502 if ( !isset( $wgRateLimits[$action] ) ) {
1503 return false;
1506 // Some groups shouldn't trigger the ping limiter, ever
1507 if ( !$this->isPingLimitable() ) {
1508 return false;
1511 global $wgMemc, $wgRateLimitLog;
1512 wfProfileIn( __METHOD__ );
1514 $limits = $wgRateLimits[$action];
1515 $keys = array();
1516 $id = $this->getId();
1517 $userLimit = false;
1519 if ( isset( $limits['anon'] ) && $id == 0 ) {
1520 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1523 if ( isset( $limits['user'] ) && $id != 0 ) {
1524 $userLimit = $limits['user'];
1526 if ( $this->isNewbie() ) {
1527 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1528 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1530 if ( isset( $limits['ip'] ) ) {
1531 $ip = $this->getRequest()->getIP();
1532 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1534 if ( isset( $limits['subnet'] ) ) {
1535 $ip = $this->getRequest()->getIP();
1536 $matches = array();
1537 $subnet = false;
1538 if ( IP::isIPv6( $ip ) ) {
1539 $parts = IP::parseRange( "$ip/64" );
1540 $subnet = $parts[0];
1541 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1542 // IPv4
1543 $subnet = $matches[1];
1545 if ( $subnet !== false ) {
1546 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1550 // Check for group-specific permissions
1551 // If more than one group applies, use the group with the highest limit
1552 foreach ( $this->getGroups() as $group ) {
1553 if ( isset( $limits[$group] ) ) {
1554 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1555 $userLimit = $limits[$group];
1559 // Set the user limit key
1560 if ( $userLimit !== false ) {
1561 list( $max, $period ) = $userLimit;
1562 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1563 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1566 $triggered = false;
1567 foreach ( $keys as $key => $limit ) {
1568 list( $max, $period ) = $limit;
1569 $summary = "(limit $max in {$period}s)";
1570 $count = $wgMemc->get( $key );
1571 // Already pinged?
1572 if ( $count ) {
1573 if ( $count >= $max ) {
1574 wfDebug( __METHOD__ . ": tripped! $key at $count $summary\n" );
1575 if ( $wgRateLimitLog ) {
1576 wfSuppressWarnings();
1577 file_put_contents( $wgRateLimitLog, wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", FILE_APPEND );
1578 wfRestoreWarnings();
1580 $triggered = true;
1581 } else {
1582 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1584 } else {
1585 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1586 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1588 $wgMemc->incr( $key );
1591 wfProfileOut( __METHOD__ );
1592 return $triggered;
1596 * Check if user is blocked
1598 * @param bool $bFromSlave Whether to check the slave database instead of the master
1599 * @return bool True if blocked, false otherwise
1601 public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1602 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1606 * Get the block affecting the user, or null if the user is not blocked
1608 * @param bool $bFromSlave Whether to check the slave database instead of the master
1609 * @return Block|null
1611 public function getBlock( $bFromSlave = true ) {
1612 $this->getBlockedStatus( $bFromSlave );
1613 return $this->mBlock instanceof Block ? $this->mBlock : null;
1617 * Check if user is blocked from editing a particular article
1619 * @param Title $title Title to check
1620 * @param bool $bFromSlave whether to check the slave database instead of the master
1621 * @return bool
1623 function isBlockedFrom( $title, $bFromSlave = false ) {
1624 global $wgBlockAllowsUTEdit;
1625 wfProfileIn( __METHOD__ );
1627 $blocked = $this->isBlocked( $bFromSlave );
1628 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1629 // If a user's name is suppressed, they cannot make edits anywhere
1630 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName() &&
1631 $title->getNamespace() == NS_USER_TALK ) {
1632 $blocked = false;
1633 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1636 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1638 wfProfileOut( __METHOD__ );
1639 return $blocked;
1643 * If user is blocked, return the name of the user who placed the block
1644 * @return string Name of blocker
1646 public function blockedBy() {
1647 $this->getBlockedStatus();
1648 return $this->mBlockedby;
1652 * If user is blocked, return the specified reason for the block
1653 * @return string Blocking reason
1655 public function blockedFor() {
1656 $this->getBlockedStatus();
1657 return $this->mBlockreason;
1661 * If user is blocked, return the ID for the block
1662 * @return int Block ID
1664 public function getBlockId() {
1665 $this->getBlockedStatus();
1666 return ( $this->mBlock ? $this->mBlock->getId() : false );
1670 * Check if user is blocked on all wikis.
1671 * Do not use for actual edit permission checks!
1672 * This is intended for quick UI checks.
1674 * @param string $ip IP address, uses current client if none given
1675 * @return bool True if blocked, false otherwise
1677 public function isBlockedGlobally( $ip = '' ) {
1678 if ( $this->mBlockedGlobally !== null ) {
1679 return $this->mBlockedGlobally;
1681 // User is already an IP?
1682 if ( IP::isIPAddress( $this->getName() ) ) {
1683 $ip = $this->getName();
1684 } elseif ( !$ip ) {
1685 $ip = $this->getRequest()->getIP();
1687 $blocked = false;
1688 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1689 $this->mBlockedGlobally = (bool)$blocked;
1690 return $this->mBlockedGlobally;
1694 * Check if user account is locked
1696 * @return bool True if locked, false otherwise
1698 public function isLocked() {
1699 if ( $this->mLocked !== null ) {
1700 return $this->mLocked;
1702 global $wgAuth;
1703 $authUser = $wgAuth->getUserInstance( $this );
1704 $this->mLocked = (bool)$authUser->isLocked();
1705 return $this->mLocked;
1709 * Check if user account is hidden
1711 * @return bool True if hidden, false otherwise
1713 public function isHidden() {
1714 if ( $this->mHideName !== null ) {
1715 return $this->mHideName;
1717 $this->getBlockedStatus();
1718 if ( !$this->mHideName ) {
1719 global $wgAuth;
1720 $authUser = $wgAuth->getUserInstance( $this );
1721 $this->mHideName = (bool)$authUser->isHidden();
1723 return $this->mHideName;
1727 * Get the user's ID.
1728 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1730 public function getId() {
1731 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
1732 // Special case, we know the user is anonymous
1733 return 0;
1734 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1735 // Don't load if this was initialized from an ID
1736 $this->load();
1738 return $this->mId;
1742 * Set the user and reload all fields according to a given ID
1743 * @param int $v User ID to reload
1745 public function setId( $v ) {
1746 $this->mId = $v;
1747 $this->clearInstanceCache( 'id' );
1751 * Get the user name, or the IP of an anonymous user
1752 * @return string User's name or IP address
1754 public function getName() {
1755 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1756 // Special case optimisation
1757 return $this->mName;
1758 } else {
1759 $this->load();
1760 if ( $this->mName === false ) {
1761 // Clean up IPs
1762 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
1764 return $this->mName;
1769 * Set the user name.
1771 * This does not reload fields from the database according to the given
1772 * name. Rather, it is used to create a temporary "nonexistent user" for
1773 * later addition to the database. It can also be used to set the IP
1774 * address for an anonymous user to something other than the current
1775 * remote IP.
1777 * @note User::newFromName() has roughly the same function, when the named user
1778 * does not exist.
1779 * @param string $str New user name to set
1781 public function setName( $str ) {
1782 $this->load();
1783 $this->mName = $str;
1787 * Get the user's name escaped by underscores.
1788 * @return string Username escaped by underscores.
1790 public function getTitleKey() {
1791 return str_replace( ' ', '_', $this->getName() );
1795 * Check if the user has new messages.
1796 * @return bool True if the user has new messages
1798 public function getNewtalk() {
1799 $this->load();
1801 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1802 if ( $this->mNewtalk === -1 ) {
1803 $this->mNewtalk = false; # reset talk page status
1805 // Check memcached separately for anons, who have no
1806 // entire User object stored in there.
1807 if ( !$this->mId ) {
1808 global $wgDisableAnonTalk;
1809 if ( $wgDisableAnonTalk ) {
1810 // Anon newtalk disabled by configuration.
1811 $this->mNewtalk = false;
1812 } else {
1813 global $wgMemc;
1814 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1815 $newtalk = $wgMemc->get( $key );
1816 if ( strval( $newtalk ) !== '' ) {
1817 $this->mNewtalk = (bool)$newtalk;
1818 } else {
1819 // Since we are caching this, make sure it is up to date by getting it
1820 // from the master
1821 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1822 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1825 } else {
1826 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1830 return (bool)$this->mNewtalk;
1834 * Return the data needed to construct links for new talk page message
1835 * alerts. If there are new messages, this will return an associative array
1836 * with the following data:
1837 * wiki: The database name of the wiki
1838 * link: Root-relative link to the user's talk page
1839 * rev: The last talk page revision that the user has seen or null. This
1840 * is useful for building diff links.
1841 * If there are no new messages, it returns an empty array.
1842 * @note This function was designed to accomodate multiple talk pages, but
1843 * currently only returns a single link and revision.
1844 * @return Array
1846 public function getNewMessageLinks() {
1847 $talks = array();
1848 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
1849 return $talks;
1850 } elseif ( !$this->getNewtalk() ) {
1851 return array();
1853 $utp = $this->getTalkPage();
1854 $dbr = wfGetDB( DB_SLAVE );
1855 // Get the "last viewed rev" timestamp from the oldest message notification
1856 $timestamp = $dbr->selectField( 'user_newtalk',
1857 'MIN(user_last_timestamp)',
1858 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
1859 __METHOD__ );
1860 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
1861 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
1865 * Get the revision ID for the last talk page revision viewed by the talk
1866 * page owner.
1867 * @return int|null Revision ID or null
1869 public function getNewMessageRevisionId() {
1870 $newMessageRevisionId = null;
1871 $newMessageLinks = $this->getNewMessageLinks();
1872 if ( $newMessageLinks ) {
1873 // Note: getNewMessageLinks() never returns more than a single link
1874 // and it is always for the same wiki, but we double-check here in
1875 // case that changes some time in the future.
1876 if ( count( $newMessageLinks ) === 1
1877 && $newMessageLinks[0]['wiki'] === wfWikiID()
1878 && $newMessageLinks[0]['rev']
1880 $newMessageRevision = $newMessageLinks[0]['rev'];
1881 $newMessageRevisionId = $newMessageRevision->getId();
1884 return $newMessageRevisionId;
1888 * Internal uncached check for new messages
1890 * @see getNewtalk()
1891 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1892 * @param string|int $id User's IP address for anonymous users, User ID otherwise
1893 * @param bool $fromMaster true to fetch from the master, false for a slave
1894 * @return bool True if the user has new messages
1896 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
1897 if ( $fromMaster ) {
1898 $db = wfGetDB( DB_MASTER );
1899 } else {
1900 $db = wfGetDB( DB_SLAVE );
1902 $ok = $db->selectField( 'user_newtalk', $field,
1903 array( $field => $id ), __METHOD__ );
1904 return $ok !== false;
1908 * Add or update the new messages flag
1909 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1910 * @param string|int $id User's IP address for anonymous users, User ID otherwise
1911 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null.
1912 * @return bool True if successful, false otherwise
1914 protected function updateNewtalk( $field, $id, $curRev = null ) {
1915 // Get timestamp of the talk page revision prior to the current one
1916 $prevRev = $curRev ? $curRev->getPrevious() : false;
1917 $ts = $prevRev ? $prevRev->getTimestamp() : null;
1918 // Mark the user as having new messages since this revision
1919 $dbw = wfGetDB( DB_MASTER );
1920 $dbw->insert( 'user_newtalk',
1921 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
1922 __METHOD__,
1923 'IGNORE' );
1924 if ( $dbw->affectedRows() ) {
1925 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
1926 return true;
1927 } else {
1928 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
1929 return false;
1934 * Clear the new messages flag for the given user
1935 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1936 * @param string|int $id User's IP address for anonymous users, User ID otherwise
1937 * @return bool True if successful, false otherwise
1939 protected function deleteNewtalk( $field, $id ) {
1940 $dbw = wfGetDB( DB_MASTER );
1941 $dbw->delete( 'user_newtalk',
1942 array( $field => $id ),
1943 __METHOD__ );
1944 if ( $dbw->affectedRows() ) {
1945 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
1946 return true;
1947 } else {
1948 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
1949 return false;
1954 * Update the 'You have new messages!' status.
1955 * @param bool $val Whether the user has new messages
1956 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null or !$val.
1958 public function setNewtalk( $val, $curRev = null ) {
1959 if ( wfReadOnly() ) {
1960 return;
1963 $this->load();
1964 $this->mNewtalk = $val;
1966 if ( $this->isAnon() ) {
1967 $field = 'user_ip';
1968 $id = $this->getName();
1969 } else {
1970 $field = 'user_id';
1971 $id = $this->getId();
1973 global $wgMemc;
1975 if ( $val ) {
1976 $changed = $this->updateNewtalk( $field, $id, $curRev );
1977 } else {
1978 $changed = $this->deleteNewtalk( $field, $id );
1981 if ( $this->isAnon() ) {
1982 // Anons have a separate memcached space, since
1983 // user records aren't kept for them.
1984 $key = wfMemcKey( 'newtalk', 'ip', $id );
1985 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
1987 if ( $changed ) {
1988 $this->invalidateCache();
1993 * Generate a current or new-future timestamp to be stored in the
1994 * user_touched field when we update things.
1995 * @return string Timestamp in TS_MW format
1997 private static function newTouchedTimestamp() {
1998 global $wgClockSkewFudge;
1999 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2003 * Clear user data from memcached.
2004 * Use after applying fun updates to the database; caller's
2005 * responsibility to update user_touched if appropriate.
2007 * Called implicitly from invalidateCache() and saveSettings().
2009 private function clearSharedCache() {
2010 $this->load();
2011 if ( $this->mId ) {
2012 global $wgMemc;
2013 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
2018 * Immediately touch the user data cache for this account.
2019 * Updates user_touched field, and removes account data from memcached
2020 * for reload on the next hit.
2022 public function invalidateCache() {
2023 if ( wfReadOnly() ) {
2024 return;
2026 $this->load();
2027 if ( $this->mId ) {
2028 $this->mTouched = self::newTouchedTimestamp();
2030 $dbw = wfGetDB( DB_MASTER );
2031 $userid = $this->mId;
2032 $touched = $this->mTouched;
2033 $method = __METHOD__;
2034 $dbw->onTransactionIdle( function() use ( $dbw, $userid, $touched, $method ) {
2035 // Prevent contention slams by checking user_touched first
2036 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2037 $needsPurge = $dbw->selectField( 'user', '1',
2038 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2039 if ( $needsPurge ) {
2040 $dbw->update( 'user',
2041 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2042 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2043 $method
2046 } );
2047 $this->clearSharedCache();
2052 * Validate the cache for this account.
2053 * @param string $timestamp A timestamp in TS_MW format
2054 * @return bool
2056 public function validateCache( $timestamp ) {
2057 $this->load();
2058 return ( $timestamp >= $this->mTouched );
2062 * Get the user touched timestamp
2063 * @return string timestamp
2065 public function getTouched() {
2066 $this->load();
2067 return $this->mTouched;
2071 * Set the password and reset the random token.
2072 * Calls through to authentication plugin if necessary;
2073 * will have no effect if the auth plugin refuses to
2074 * pass the change through or if the legal password
2075 * checks fail.
2077 * As a special case, setting the password to null
2078 * wipes it, so the account cannot be logged in until
2079 * a new password is set, for instance via e-mail.
2081 * @param string $str New password to set
2082 * @throws PasswordError on failure
2084 * @return bool
2086 public function setPassword( $str ) {
2087 global $wgAuth;
2089 if ( $str !== null ) {
2090 if ( !$wgAuth->allowPasswordChange() ) {
2091 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2094 if ( !$this->isValidPassword( $str ) ) {
2095 global $wgMinimalPasswordLength;
2096 $valid = $this->getPasswordValidity( $str );
2097 if ( is_array( $valid ) ) {
2098 $message = array_shift( $valid );
2099 $params = $valid;
2100 } else {
2101 $message = $valid;
2102 $params = array( $wgMinimalPasswordLength );
2104 throw new PasswordError( wfMessage( $message, $params )->text() );
2108 if ( !$wgAuth->setPassword( $this, $str ) ) {
2109 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2112 $this->setInternalPassword( $str );
2114 return true;
2118 * Set the password and reset the random token unconditionally.
2120 * @param string|null $str New password to set or null to set an invalid
2121 * password hash meaning that the user will not be able to log in
2122 * through the web interface.
2124 public function setInternalPassword( $str ) {
2125 $this->load();
2126 $this->setToken();
2128 if ( $str === null ) {
2129 // Save an invalid hash...
2130 $this->mPassword = '';
2131 } else {
2132 $this->mPassword = self::crypt( $str );
2134 $this->mNewpassword = '';
2135 $this->mNewpassTime = null;
2139 * Get the user's current token.
2140 * @param bool $forceCreation Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility)
2141 * @return string Token
2143 public function getToken( $forceCreation = true ) {
2144 $this->load();
2145 if ( !$this->mToken && $forceCreation ) {
2146 $this->setToken();
2148 return $this->mToken;
2152 * Set the random token (used for persistent authentication)
2153 * Called from loadDefaults() among other places.
2155 * @param string|bool $token If specified, set the token to this value
2157 public function setToken( $token = false ) {
2158 $this->load();
2159 if ( !$token ) {
2160 $this->mToken = MWCryptRand::generateHex( USER_TOKEN_LENGTH );
2161 } else {
2162 $this->mToken = $token;
2167 * Set the password for a password reminder or new account email
2169 * @param string $str New password to set
2170 * @param bool $throttle If true, reset the throttle timestamp to the present
2172 public function setNewpassword( $str, $throttle = true ) {
2173 $this->load();
2174 $this->mNewpassword = self::crypt( $str );
2175 if ( $throttle ) {
2176 $this->mNewpassTime = wfTimestampNow();
2181 * Has password reminder email been sent within the last
2182 * $wgPasswordReminderResendTime hours?
2183 * @return bool
2185 public function isPasswordReminderThrottled() {
2186 global $wgPasswordReminderResendTime;
2187 $this->load();
2188 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
2189 return false;
2191 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
2192 return time() < $expiry;
2196 * Get the user's e-mail address
2197 * @return string User's email address
2199 public function getEmail() {
2200 $this->load();
2201 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
2202 return $this->mEmail;
2206 * Get the timestamp of the user's e-mail authentication
2207 * @return string TS_MW timestamp
2209 public function getEmailAuthenticationTimestamp() {
2210 $this->load();
2211 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2212 return $this->mEmailAuthenticated;
2216 * Set the user's e-mail address
2217 * @param string $str New e-mail address
2219 public function setEmail( $str ) {
2220 $this->load();
2221 if ( $str == $this->mEmail ) {
2222 return;
2224 $this->mEmail = $str;
2225 $this->invalidateEmail();
2226 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
2230 * Set the user's e-mail address and a confirmation mail if needed.
2232 * @since 1.20
2233 * @param string $str New e-mail address
2234 * @return Status
2236 public function setEmailWithConfirmation( $str ) {
2237 global $wgEnableEmail, $wgEmailAuthentication;
2239 if ( !$wgEnableEmail ) {
2240 return Status::newFatal( 'emaildisabled' );
2243 $oldaddr = $this->getEmail();
2244 if ( $str === $oldaddr ) {
2245 return Status::newGood( true );
2248 $this->setEmail( $str );
2250 if ( $str !== '' && $wgEmailAuthentication ) {
2251 // Send a confirmation request to the new address if needed
2252 $type = $oldaddr != '' ? 'changed' : 'set';
2253 $result = $this->sendConfirmationMail( $type );
2254 if ( $result->isGood() ) {
2255 // Say the the caller that a confirmation mail has been sent
2256 $result->value = 'eauth';
2258 } else {
2259 $result = Status::newGood( true );
2262 return $result;
2266 * Get the user's real name
2267 * @return string User's real name
2269 public function getRealName() {
2270 if ( !$this->isItemLoaded( 'realname' ) ) {
2271 $this->load();
2274 return $this->mRealName;
2278 * Set the user's real name
2279 * @param string $str New real name
2281 public function setRealName( $str ) {
2282 $this->load();
2283 $this->mRealName = $str;
2287 * Get the user's current setting for a given option.
2289 * @param string $oname The option to check
2290 * @param string $defaultOverride A default value returned if the option does not exist
2291 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2292 * @return string User's current value for the option
2293 * @see getBoolOption()
2294 * @see getIntOption()
2296 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2297 global $wgHiddenPrefs;
2298 $this->loadOptions();
2300 # We want 'disabled' preferences to always behave as the default value for
2301 # users, even if they have set the option explicitly in their settings (ie they
2302 # set it, and then it was disabled removing their ability to change it). But
2303 # we don't want to erase the preferences in the database in case the preference
2304 # is re-enabled again. So don't touch $mOptions, just override the returned value
2305 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2306 return self::getDefaultOption( $oname );
2309 if ( array_key_exists( $oname, $this->mOptions ) ) {
2310 return $this->mOptions[$oname];
2311 } else {
2312 return $defaultOverride;
2317 * Get all user's options
2319 * @return array
2321 public function getOptions() {
2322 global $wgHiddenPrefs;
2323 $this->loadOptions();
2324 $options = $this->mOptions;
2326 # We want 'disabled' preferences to always behave as the default value for
2327 # users, even if they have set the option explicitly in their settings (ie they
2328 # set it, and then it was disabled removing their ability to change it). But
2329 # we don't want to erase the preferences in the database in case the preference
2330 # is re-enabled again. So don't touch $mOptions, just override the returned value
2331 foreach ( $wgHiddenPrefs as $pref ) {
2332 $default = self::getDefaultOption( $pref );
2333 if ( $default !== null ) {
2334 $options[$pref] = $default;
2338 return $options;
2342 * Get the user's current setting for a given option, as a boolean value.
2344 * @param string $oname The option to check
2345 * @return bool User's current value for the option
2346 * @see getOption()
2348 public function getBoolOption( $oname ) {
2349 return (bool)$this->getOption( $oname );
2353 * Get the user's current setting for a given option, as an integer value.
2355 * @param string $oname The option to check
2356 * @param int $defaultOverride A default value returned if the option does not exist
2357 * @return int User's current value for the option
2358 * @see getOption()
2360 public function getIntOption( $oname, $defaultOverride = 0 ) {
2361 $val = $this->getOption( $oname );
2362 if ( $val == '' ) {
2363 $val = $defaultOverride;
2365 return intval( $val );
2369 * Set the given option for a user.
2371 * @param string $oname The option to set
2372 * @param mixed $val New value to set
2374 public function setOption( $oname, $val ) {
2375 $this->loadOptions();
2377 // Explicitly NULL values should refer to defaults
2378 if ( is_null( $val ) ) {
2379 $val = self::getDefaultOption( $oname );
2382 $this->mOptions[$oname] = $val;
2386 * Get a token stored in the preferences (like the watchlist one),
2387 * resetting it if it's empty (and saving changes).
2389 * @param string $oname The option name to retrieve the token from
2390 * @return string|bool User's current value for the option, or false if this option is disabled.
2391 * @see resetTokenFromOption()
2392 * @see getOption()
2394 public function getTokenFromOption( $oname ) {
2395 global $wgHiddenPrefs;
2396 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2397 return false;
2400 $token = $this->getOption( $oname );
2401 if ( !$token ) {
2402 $token = $this->resetTokenFromOption( $oname );
2403 $this->saveSettings();
2405 return $token;
2409 * Reset a token stored in the preferences (like the watchlist one).
2410 * *Does not* save user's preferences (similarly to setOption()).
2412 * @param string $oname The option name to reset the token in
2413 * @return string|bool New token value, or false if this option is disabled.
2414 * @see getTokenFromOption()
2415 * @see setOption()
2417 public function resetTokenFromOption( $oname ) {
2418 global $wgHiddenPrefs;
2419 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2420 return false;
2423 $token = MWCryptRand::generateHex( 40 );
2424 $this->setOption( $oname, $token );
2425 return $token;
2429 * Return a list of the types of user options currently returned by
2430 * User::getOptionKinds().
2432 * Currently, the option kinds are:
2433 * - 'registered' - preferences which are registered in core MediaWiki or
2434 * by extensions using the UserGetDefaultOptions hook.
2435 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2436 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2437 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2438 * be used by user scripts.
2439 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2440 * These are usually legacy options, removed in newer versions.
2442 * The API (and possibly others) use this function to determine the possible
2443 * option types for validation purposes, so make sure to update this when a
2444 * new option kind is added.
2446 * @see User::getOptionKinds
2447 * @return array Option kinds
2449 public static function listOptionKinds() {
2450 return array(
2451 'registered',
2452 'registered-multiselect',
2453 'registered-checkmatrix',
2454 'userjs',
2455 'unused'
2460 * Return an associative array mapping preferences keys to the kind of a preference they're
2461 * used for. Different kinds are handled differently when setting or reading preferences.
2463 * See User::listOptionKinds for the list of valid option types that can be provided.
2465 * @see User::listOptionKinds
2466 * @param $context IContextSource
2467 * @param array $options assoc. array with options keys to check as keys. Defaults to $this->mOptions.
2468 * @return array the key => kind mapping data
2470 public function getOptionKinds( IContextSource $context, $options = null ) {
2471 $this->loadOptions();
2472 if ( $options === null ) {
2473 $options = $this->mOptions;
2476 $prefs = Preferences::getPreferences( $this, $context );
2477 $mapping = array();
2479 // Multiselect and checkmatrix options are stored in the database with
2480 // one key per option, each having a boolean value. Extract those keys.
2481 $multiselectOptions = array();
2482 foreach ( $prefs as $name => $info ) {
2483 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2484 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2485 $opts = HTMLFormField::flattenOptions( $info['options'] );
2486 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2488 foreach ( $opts as $value ) {
2489 $multiselectOptions["$prefix$value"] = true;
2492 unset( $prefs[$name] );
2495 $checkmatrixOptions = array();
2496 foreach ( $prefs as $name => $info ) {
2497 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2498 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2499 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2500 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2501 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2503 foreach ( $columns as $column ) {
2504 foreach ( $rows as $row ) {
2505 $checkmatrixOptions["$prefix-$column-$row"] = true;
2509 unset( $prefs[$name] );
2513 // $value is ignored
2514 foreach ( $options as $key => $value ) {
2515 if ( isset( $prefs[$key] ) ) {
2516 $mapping[$key] = 'registered';
2517 } elseif ( isset( $multiselectOptions[$key] ) ) {
2518 $mapping[$key] = 'registered-multiselect';
2519 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2520 $mapping[$key] = 'registered-checkmatrix';
2521 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2522 $mapping[$key] = 'userjs';
2523 } else {
2524 $mapping[$key] = 'unused';
2528 return $mapping;
2532 * Reset certain (or all) options to the site defaults
2534 * The optional parameter determines which kinds of preferences will be reset.
2535 * Supported values are everything that can be reported by getOptionKinds()
2536 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2538 * @param array|string $resetKinds which kinds of preferences to reset. Defaults to
2539 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2540 * for backwards-compatibility.
2541 * @param $context IContextSource|null context source used when $resetKinds
2542 * does not contain 'all', passed to getOptionKinds().
2543 * Defaults to RequestContext::getMain() when null.
2545 public function resetOptions(
2546 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2547 IContextSource $context = null
2549 $this->load();
2550 $defaultOptions = self::getDefaultOptions();
2552 if ( !is_array( $resetKinds ) ) {
2553 $resetKinds = array( $resetKinds );
2556 if ( in_array( 'all', $resetKinds ) ) {
2557 $newOptions = $defaultOptions;
2558 } else {
2559 if ( $context === null ) {
2560 $context = RequestContext::getMain();
2563 $optionKinds = $this->getOptionKinds( $context );
2564 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2565 $newOptions = array();
2567 // Use default values for the options that should be deleted, and
2568 // copy old values for the ones that shouldn't.
2569 foreach ( $this->mOptions as $key => $value ) {
2570 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2571 if ( array_key_exists( $key, $defaultOptions ) ) {
2572 $newOptions[$key] = $defaultOptions[$key];
2574 } else {
2575 $newOptions[$key] = $value;
2580 $this->mOptions = $newOptions;
2581 $this->mOptionsLoaded = true;
2585 * Get the user's preferred date format.
2586 * @return string User's preferred date format
2588 public function getDatePreference() {
2589 // Important migration for old data rows
2590 if ( is_null( $this->mDatePreference ) ) {
2591 global $wgLang;
2592 $value = $this->getOption( 'date' );
2593 $map = $wgLang->getDatePreferenceMigrationMap();
2594 if ( isset( $map[$value] ) ) {
2595 $value = $map[$value];
2597 $this->mDatePreference = $value;
2599 return $this->mDatePreference;
2603 * Determine based on the wiki configuration and the user's options,
2604 * whether this user must be over HTTPS no matter what.
2606 * @return bool
2608 public function requiresHTTPS() {
2609 global $wgSecureLogin;
2610 if ( !$wgSecureLogin ) {
2611 return false;
2612 } else {
2613 $https = $this->getBoolOption( 'prefershttps' );
2614 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2615 return $https;
2620 * Get the user preferred stub threshold
2622 * @return int
2624 public function getStubThreshold() {
2625 global $wgMaxArticleSize; # Maximum article size, in Kb
2626 $threshold = $this->getIntOption( 'stubthreshold' );
2627 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2628 // If they have set an impossible value, disable the preference
2629 // so we can use the parser cache again.
2630 $threshold = 0;
2632 return $threshold;
2636 * Get the permissions this user has.
2637 * @return Array of String permission names
2639 public function getRights() {
2640 if ( is_null( $this->mRights ) ) {
2641 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2642 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2643 // Force reindexation of rights when a hook has unset one of them
2644 $this->mRights = array_values( array_unique( $this->mRights ) );
2646 return $this->mRights;
2650 * Get the list of explicit group memberships this user has.
2651 * The implicit * and user groups are not included.
2652 * @return Array of String internal group names
2654 public function getGroups() {
2655 $this->load();
2656 $this->loadGroups();
2657 return $this->mGroups;
2661 * Get the list of implicit group memberships this user has.
2662 * This includes all explicit groups, plus 'user' if logged in,
2663 * '*' for all accounts, and autopromoted groups
2664 * @param bool $recache Whether to avoid the cache
2665 * @return Array of String internal group names
2667 public function getEffectiveGroups( $recache = false ) {
2668 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2669 wfProfileIn( __METHOD__ );
2670 $this->mEffectiveGroups = array_unique( array_merge(
2671 $this->getGroups(), // explicit groups
2672 $this->getAutomaticGroups( $recache ) // implicit groups
2673 ) );
2674 // Hook for additional groups
2675 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2676 // Force reindexation of groups when a hook has unset one of them
2677 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
2678 wfProfileOut( __METHOD__ );
2680 return $this->mEffectiveGroups;
2684 * Get the list of implicit group memberships this user has.
2685 * This includes 'user' if logged in, '*' for all accounts,
2686 * and autopromoted groups
2687 * @param bool $recache Whether to avoid the cache
2688 * @return Array of String internal group names
2690 public function getAutomaticGroups( $recache = false ) {
2691 if ( $recache || is_null( $this->mImplicitGroups ) ) {
2692 wfProfileIn( __METHOD__ );
2693 $this->mImplicitGroups = array( '*' );
2694 if ( $this->getId() ) {
2695 $this->mImplicitGroups[] = 'user';
2697 $this->mImplicitGroups = array_unique( array_merge(
2698 $this->mImplicitGroups,
2699 Autopromote::getAutopromoteGroups( $this )
2700 ) );
2702 if ( $recache ) {
2703 // Assure data consistency with rights/groups,
2704 // as getEffectiveGroups() depends on this function
2705 $this->mEffectiveGroups = null;
2707 wfProfileOut( __METHOD__ );
2709 return $this->mImplicitGroups;
2713 * Returns the groups the user has belonged to.
2715 * The user may still belong to the returned groups. Compare with getGroups().
2717 * The function will not return groups the user had belonged to before MW 1.17
2719 * @return array Names of the groups the user has belonged to.
2721 public function getFormerGroups() {
2722 if ( is_null( $this->mFormerGroups ) ) {
2723 $dbr = wfGetDB( DB_MASTER );
2724 $res = $dbr->select( 'user_former_groups',
2725 array( 'ufg_group' ),
2726 array( 'ufg_user' => $this->mId ),
2727 __METHOD__ );
2728 $this->mFormerGroups = array();
2729 foreach ( $res as $row ) {
2730 $this->mFormerGroups[] = $row->ufg_group;
2733 return $this->mFormerGroups;
2737 * Get the user's edit count.
2738 * @return int, null for anonymous users
2740 public function getEditCount() {
2741 if ( !$this->getId() ) {
2742 return null;
2745 if ( !isset( $this->mEditCount ) ) {
2746 /* Populate the count, if it has not been populated yet */
2747 wfProfileIn( __METHOD__ );
2748 $dbr = wfGetDB( DB_SLAVE );
2749 // check if the user_editcount field has been initialized
2750 $count = $dbr->selectField(
2751 'user', 'user_editcount',
2752 array( 'user_id' => $this->mId ),
2753 __METHOD__
2756 if ( $count === null ) {
2757 // it has not been initialized. do so.
2758 $count = $this->initEditCount();
2760 $this->mEditCount = $count;
2761 wfProfileOut( __METHOD__ );
2763 return (int) $this->mEditCount;
2767 * Add the user to the given group.
2768 * This takes immediate effect.
2769 * @param string $group Name of the group to add
2771 public function addGroup( $group ) {
2772 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2773 $dbw = wfGetDB( DB_MASTER );
2774 if ( $this->getId() ) {
2775 $dbw->insert( 'user_groups',
2776 array(
2777 'ug_user' => $this->getID(),
2778 'ug_group' => $group,
2780 __METHOD__,
2781 array( 'IGNORE' ) );
2784 $this->loadGroups();
2785 $this->mGroups[] = $group;
2786 // In case loadGroups was not called before, we now have the right twice.
2787 // Get rid of the duplicate.
2788 $this->mGroups = array_unique( $this->mGroups );
2790 // Refresh the groups caches, and clear the rights cache so it will be
2791 // refreshed on the next call to $this->getRights().
2792 $this->getEffectiveGroups( true );
2793 $this->mRights = null;
2795 $this->invalidateCache();
2799 * Remove the user from the given group.
2800 * This takes immediate effect.
2801 * @param string $group Name of the group to remove
2803 public function removeGroup( $group ) {
2804 $this->load();
2805 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2806 $dbw = wfGetDB( DB_MASTER );
2807 $dbw->delete( 'user_groups',
2808 array(
2809 'ug_user' => $this->getID(),
2810 'ug_group' => $group,
2811 ), __METHOD__ );
2812 // Remember that the user was in this group
2813 $dbw->insert( 'user_former_groups',
2814 array(
2815 'ufg_user' => $this->getID(),
2816 'ufg_group' => $group,
2818 __METHOD__,
2819 array( 'IGNORE' ) );
2821 $this->loadGroups();
2822 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2824 // Refresh the groups caches, and clear the rights cache so it will be
2825 // refreshed on the next call to $this->getRights().
2826 $this->getEffectiveGroups( true );
2827 $this->mRights = null;
2829 $this->invalidateCache();
2833 * Get whether the user is logged in
2834 * @return bool
2836 public function isLoggedIn() {
2837 return $this->getID() != 0;
2841 * Get whether the user is anonymous
2842 * @return bool
2844 public function isAnon() {
2845 return !$this->isLoggedIn();
2849 * Check if user is allowed to access a feature / make an action
2851 * @internal param \String $varargs permissions to test
2852 * @return boolean: True if user is allowed to perform *any* of the given actions
2854 * @return bool
2856 public function isAllowedAny( /*...*/ ) {
2857 $permissions = func_get_args();
2858 foreach ( $permissions as $permission ) {
2859 if ( $this->isAllowed( $permission ) ) {
2860 return true;
2863 return false;
2868 * @internal param $varargs string
2869 * @return bool True if the user is allowed to perform *all* of the given actions
2871 public function isAllowedAll( /*...*/ ) {
2872 $permissions = func_get_args();
2873 foreach ( $permissions as $permission ) {
2874 if ( !$this->isAllowed( $permission ) ) {
2875 return false;
2878 return true;
2882 * Internal mechanics of testing a permission
2883 * @param string $action
2884 * @return bool
2886 public function isAllowed( $action = '' ) {
2887 if ( $action === '' ) {
2888 return true; // In the spirit of DWIM
2890 // Patrolling may not be enabled
2891 if ( $action === 'patrol' || $action === 'autopatrol' ) {
2892 global $wgUseRCPatrol, $wgUseNPPatrol;
2893 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
2894 return false;
2897 // Use strict parameter to avoid matching numeric 0 accidentally inserted
2898 // by misconfiguration: 0 == 'foo'
2899 return in_array( $action, $this->getRights(), true );
2903 * Check whether to enable recent changes patrol features for this user
2904 * @return boolean: True or false
2906 public function useRCPatrol() {
2907 global $wgUseRCPatrol;
2908 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
2912 * Check whether to enable new pages patrol features for this user
2913 * @return bool True or false
2915 public function useNPPatrol() {
2916 global $wgUseRCPatrol, $wgUseNPPatrol;
2917 return (
2918 ( $wgUseRCPatrol || $wgUseNPPatrol )
2919 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
2924 * Get the WebRequest object to use with this object
2926 * @return WebRequest
2928 public function getRequest() {
2929 if ( $this->mRequest ) {
2930 return $this->mRequest;
2931 } else {
2932 global $wgRequest;
2933 return $wgRequest;
2938 * Get the current skin, loading it if required
2939 * @return Skin The current skin
2940 * @todo FIXME: Need to check the old failback system [AV]
2941 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
2943 public function getSkin() {
2944 wfDeprecated( __METHOD__, '1.18' );
2945 return RequestContext::getMain()->getSkin();
2949 * Get a WatchedItem for this user and $title.
2951 * @since 1.22 $checkRights parameter added
2952 * @param $title Title
2953 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
2954 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
2955 * @return WatchedItem
2957 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
2958 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
2960 if ( isset( $this->mWatchedItems[$key] ) ) {
2961 return $this->mWatchedItems[$key];
2964 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
2965 $this->mWatchedItems = array();
2968 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
2969 return $this->mWatchedItems[$key];
2973 * Check the watched status of an article.
2974 * @since 1.22 $checkRights parameter added
2975 * @param $title Title of the article to look at
2976 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
2977 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
2978 * @return bool
2980 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
2981 return $this->getWatchedItem( $title, $checkRights )->isWatched();
2985 * Watch an article.
2986 * @since 1.22 $checkRights parameter added
2987 * @param $title Title of the article to look at
2988 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
2989 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
2991 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
2992 $this->getWatchedItem( $title, $checkRights )->addWatch();
2993 $this->invalidateCache();
2997 * Stop watching an article.
2998 * @since 1.22 $checkRights parameter added
2999 * @param $title Title of the article to look at
3000 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3001 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3003 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3004 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3005 $this->invalidateCache();
3009 * Clear the user's notification timestamp for the given title.
3010 * If e-notif e-mails are on, they will receive notification mails on
3011 * the next change of the page if it's watched etc.
3012 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3013 * @param $title Title of the article to look at
3015 public function clearNotification( &$title ) {
3016 global $wgUseEnotif, $wgShowUpdatedMarker;
3018 // Do nothing if the database is locked to writes
3019 if ( wfReadOnly() ) {
3020 return;
3023 // Do nothing if not allowed to edit the watchlist
3024 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3025 return;
3028 if ( $title->getNamespace() == NS_USER_TALK &&
3029 $title->getText() == $this->getName() ) {
3030 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) ) {
3031 return;
3033 $this->setNewtalk( false );
3036 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3037 return;
3040 if ( $this->isAnon() ) {
3041 // Nothing else to do...
3042 return;
3045 // Only update the timestamp if the page is being watched.
3046 // The query to find out if it is watched is cached both in memcached and per-invocation,
3047 // and when it does have to be executed, it can be on a slave
3048 // If this is the user's newtalk page, we always update the timestamp
3049 $force = '';
3050 if ( $title->getNamespace() == NS_USER_TALK &&
3051 $title->getText() == $this->getName() )
3053 $force = 'force';
3056 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force );
3060 * Resets all of the given user's page-change notification timestamps.
3061 * If e-notif e-mails are on, they will receive notification mails on
3062 * the next change of any watched page.
3063 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3065 public function clearAllNotifications() {
3066 if ( wfReadOnly() ) {
3067 return;
3070 // Do nothing if not allowed to edit the watchlist
3071 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3072 return;
3075 global $wgUseEnotif, $wgShowUpdatedMarker;
3076 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3077 $this->setNewtalk( false );
3078 return;
3080 $id = $this->getId();
3081 if ( $id != 0 ) {
3082 $dbw = wfGetDB( DB_MASTER );
3083 $dbw->update( 'watchlist',
3084 array( /* SET */
3085 'wl_notificationtimestamp' => null
3086 ), array( /* WHERE */
3087 'wl_user' => $id
3088 ), __METHOD__
3090 # We also need to clear here the "you have new message" notification for the own user_talk page
3091 # This is cleared one page view later in Article::viewUpdates();
3096 * Set this user's options from an encoded string
3097 * @param string $str Encoded options to import
3099 * @deprecated in 1.19 due to removal of user_options from the user table
3101 private function decodeOptions( $str ) {
3102 wfDeprecated( __METHOD__, '1.19' );
3103 if ( !$str ) {
3104 return;
3107 $this->mOptionsLoaded = true;
3108 $this->mOptionOverrides = array();
3110 // If an option is not set in $str, use the default value
3111 $this->mOptions = self::getDefaultOptions();
3113 $a = explode( "\n", $str );
3114 foreach ( $a as $s ) {
3115 $m = array();
3116 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
3117 $this->mOptions[$m[1]] = $m[2];
3118 $this->mOptionOverrides[$m[1]] = $m[2];
3124 * Set a cookie on the user's client. Wrapper for
3125 * WebResponse::setCookie
3126 * @param string $name Name of the cookie to set
3127 * @param string $value Value to set
3128 * @param int $exp Expiration time, as a UNIX time value;
3129 * if 0 or not specified, use the default $wgCookieExpiration
3130 * @param bool $secure
3131 * true: Force setting the secure attribute when setting the cookie
3132 * false: Force NOT setting the secure attribute when setting the cookie
3133 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3135 protected function setCookie( $name, $value, $exp = 0, $secure = null ) {
3136 $this->getRequest()->response()->setcookie( $name, $value, $exp, array(
3137 'secure' => $secure,
3138 ) );
3142 * Clear a cookie on the user's client
3143 * @param string $name Name of the cookie to clear
3145 protected function clearCookie( $name ) {
3146 $this->setCookie( $name, '', time() - 86400 );
3150 * Set the default cookies for this session on the user's client.
3152 * @param $request WebRequest object to use; $wgRequest will be used if null
3153 * is passed.
3154 * @param bool $secure Whether to force secure/insecure cookies or use default
3156 public function setCookies( $request = null, $secure = null ) {
3157 if ( $request === null ) {
3158 $request = $this->getRequest();
3161 $this->load();
3162 if ( 0 == $this->mId ) {
3163 return;
3165 if ( !$this->mToken ) {
3166 // When token is empty or NULL generate a new one and then save it to the database
3167 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3168 // Simply by setting every cell in the user_token column to NULL and letting them be
3169 // regenerated as users log back into the wiki.
3170 $this->setToken();
3171 $this->saveSettings();
3173 $session = array(
3174 'wsUserID' => $this->mId,
3175 'wsToken' => $this->mToken,
3176 'wsUserName' => $this->getName()
3178 $cookies = array(
3179 'UserID' => $this->mId,
3180 'UserName' => $this->getName(),
3182 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
3183 $cookies['Token'] = $this->mToken;
3184 } else {
3185 $cookies['Token'] = false;
3188 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3190 foreach ( $session as $name => $value ) {
3191 $request->setSessionData( $name, $value );
3193 foreach ( $cookies as $name => $value ) {
3194 if ( $value === false ) {
3195 $this->clearCookie( $name );
3196 } else {
3197 $this->setCookie( $name, $value, 0, $secure );
3202 * If wpStickHTTPS was selected, also set an insecure cookie that
3203 * will cause the site to redirect the user to HTTPS, if they access
3204 * it over HTTP. Bug 29898.
3206 if ( $request->getCheck( 'wpStickHTTPS' ) || $this->requiresHTTPS() ) {
3207 $this->setCookie( 'forceHTTPS', 'true', time() + 2592000, false ); //30 days
3212 * Log this user out.
3214 public function logout() {
3215 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3216 $this->doLogout();
3221 * Clear the user's cookies and session, and reset the instance cache.
3222 * @see logout()
3224 public function doLogout() {
3225 $this->clearInstanceCache( 'defaults' );
3227 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3229 $this->clearCookie( 'UserID' );
3230 $this->clearCookie( 'Token' );
3231 $this->clearCookie( 'forceHTTPS' );
3233 // Remember when user logged out, to prevent seeing cached pages
3234 $this->setCookie( 'LoggedOut', time(), time() + 86400 );
3238 * Save this user's settings into the database.
3239 * @todo Only rarely do all these fields need to be set!
3241 public function saveSettings() {
3242 global $wgAuth;
3244 $this->load();
3245 if ( wfReadOnly() ) {
3246 return;
3248 if ( 0 == $this->mId ) {
3249 return;
3252 $this->mTouched = self::newTouchedTimestamp();
3253 if ( !$wgAuth->allowSetLocalPassword() ) {
3254 $this->mPassword = '';
3257 $dbw = wfGetDB( DB_MASTER );
3258 $dbw->update( 'user',
3259 array( /* SET */
3260 'user_name' => $this->mName,
3261 'user_password' => $this->mPassword,
3262 'user_newpassword' => $this->mNewpassword,
3263 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3264 'user_real_name' => $this->mRealName,
3265 'user_email' => $this->mEmail,
3266 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3267 'user_touched' => $dbw->timestamp( $this->mTouched ),
3268 'user_token' => strval( $this->mToken ),
3269 'user_email_token' => $this->mEmailToken,
3270 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3271 ), array( /* WHERE */
3272 'user_id' => $this->mId
3273 ), __METHOD__
3276 $this->saveOptions();
3278 wfRunHooks( 'UserSaveSettings', array( $this ) );
3279 $this->clearSharedCache();
3280 $this->getUserPage()->invalidateCache();
3284 * If only this user's username is known, and it exists, return the user ID.
3285 * @return int
3287 public function idForName() {
3288 $s = trim( $this->getName() );
3289 if ( $s === '' ) {
3290 return 0;
3293 $dbr = wfGetDB( DB_SLAVE );
3294 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
3295 if ( $id === false ) {
3296 $id = 0;
3298 return $id;
3302 * Add a user to the database, return the user object
3304 * @param string $name Username to add
3305 * @param array $params of Strings Non-default parameters to save to the database as user_* fields:
3306 * - password The user's password hash. Password logins will be disabled if this is omitted.
3307 * - newpassword Hash for a temporary password that has been mailed to the user
3308 * - email The user's email address
3309 * - email_authenticated The email authentication timestamp
3310 * - real_name The user's real name
3311 * - options An associative array of non-default options
3312 * - token Random authentication token. Do not set.
3313 * - registration Registration timestamp. Do not set.
3315 * @return User object, or null if the username already exists
3317 public static function createNew( $name, $params = array() ) {
3318 $user = new User;
3319 $user->load();
3320 $user->setToken(); // init token
3321 if ( isset( $params['options'] ) ) {
3322 $user->mOptions = $params['options'] + (array)$user->mOptions;
3323 unset( $params['options'] );
3325 $dbw = wfGetDB( DB_MASTER );
3326 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3328 $fields = array(
3329 'user_id' => $seqVal,
3330 'user_name' => $name,
3331 'user_password' => $user->mPassword,
3332 'user_newpassword' => $user->mNewpassword,
3333 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3334 'user_email' => $user->mEmail,
3335 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3336 'user_real_name' => $user->mRealName,
3337 'user_token' => strval( $user->mToken ),
3338 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3339 'user_editcount' => 0,
3340 'user_touched' => $dbw->timestamp( self::newTouchedTimestamp() ),
3342 foreach ( $params as $name => $value ) {
3343 $fields["user_$name"] = $value;
3345 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3346 if ( $dbw->affectedRows() ) {
3347 $newUser = User::newFromId( $dbw->insertId() );
3348 } else {
3349 $newUser = null;
3351 return $newUser;
3355 * Add this existing user object to the database. If the user already
3356 * exists, a fatal status object is returned, and the user object is
3357 * initialised with the data from the database.
3359 * Previously, this function generated a DB error due to a key conflict
3360 * if the user already existed. Many extension callers use this function
3361 * in code along the lines of:
3363 * $user = User::newFromName( $name );
3364 * if ( !$user->isLoggedIn() ) {
3365 * $user->addToDatabase();
3367 * // do something with $user...
3369 * However, this was vulnerable to a race condition (bug 16020). By
3370 * initialising the user object if the user exists, we aim to support this
3371 * calling sequence as far as possible.
3373 * Note that if the user exists, this function will acquire a write lock,
3374 * so it is still advisable to make the call conditional on isLoggedIn(),
3375 * and to commit the transaction after calling.
3377 * @throws MWException
3378 * @return Status
3380 public function addToDatabase() {
3381 $this->load();
3382 if ( !$this->mToken ) {
3383 $this->setToken(); // init token
3386 $this->mTouched = self::newTouchedTimestamp();
3388 $dbw = wfGetDB( DB_MASTER );
3389 $inWrite = $dbw->writesOrCallbacksPending();
3390 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3391 $dbw->insert( 'user',
3392 array(
3393 'user_id' => $seqVal,
3394 'user_name' => $this->mName,
3395 'user_password' => $this->mPassword,
3396 'user_newpassword' => $this->mNewpassword,
3397 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3398 'user_email' => $this->mEmail,
3399 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3400 'user_real_name' => $this->mRealName,
3401 'user_token' => strval( $this->mToken ),
3402 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3403 'user_editcount' => 0,
3404 'user_touched' => $dbw->timestamp( $this->mTouched ),
3405 ), __METHOD__,
3406 array( 'IGNORE' )
3408 if ( !$dbw->affectedRows() ) {
3409 if ( !$inWrite ) {
3410 // XXX: Get out of REPEATABLE-READ so the SELECT below works.
3411 // Often this case happens early in views before any writes.
3412 // This shows up at least with CentralAuth.
3413 $dbw->commit( __METHOD__, 'flush' );
3415 $this->mId = $dbw->selectField( 'user', 'user_id',
3416 array( 'user_name' => $this->mName ), __METHOD__ );
3417 $loaded = false;
3418 if ( $this->mId ) {
3419 if ( $this->loadFromDatabase() ) {
3420 $loaded = true;
3423 if ( !$loaded ) {
3424 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3425 "to insert user '{$this->mName}' row, but it was not present in select!" );
3427 return Status::newFatal( 'userexists' );
3429 $this->mId = $dbw->insertId();
3431 // Clear instance cache other than user table data, which is already accurate
3432 $this->clearInstanceCache();
3434 $this->saveOptions();
3435 return Status::newGood();
3439 * If this user is logged-in and blocked,
3440 * block any IP address they've successfully logged in from.
3441 * @return bool A block was spread
3443 public function spreadAnyEditBlock() {
3444 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3445 return $this->spreadBlock();
3447 return false;
3451 * If this (non-anonymous) user is blocked,
3452 * block the IP address they've successfully logged in from.
3453 * @return bool A block was spread
3455 protected function spreadBlock() {
3456 wfDebug( __METHOD__ . "()\n" );
3457 $this->load();
3458 if ( $this->mId == 0 ) {
3459 return false;
3462 $userblock = Block::newFromTarget( $this->getName() );
3463 if ( !$userblock ) {
3464 return false;
3467 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3471 * Generate a string which will be different for any combination of
3472 * user options which would produce different parser output.
3473 * This will be used as part of the hash key for the parser cache,
3474 * so users with the same options can share the same cached data
3475 * safely.
3477 * Extensions which require it should install 'PageRenderingHash' hook,
3478 * which will give them a chance to modify this key based on their own
3479 * settings.
3481 * @deprecated since 1.17 use the ParserOptions object to get the relevant options
3482 * @return string Page rendering hash
3484 public function getPageRenderingHash() {
3485 wfDeprecated( __METHOD__, '1.17' );
3487 global $wgRenderHashAppend, $wgLang, $wgContLang;
3488 if ( $this->mHash ) {
3489 return $this->mHash;
3492 // stubthreshold is only included below for completeness,
3493 // since it disables the parser cache, its value will always
3494 // be 0 when this function is called by parsercache.
3496 $confstr = $this->getOption( 'math' );
3497 $confstr .= '!' . $this->getStubThreshold();
3498 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ? '1' : '' );
3499 $confstr .= '!' . $wgLang->getCode();
3500 $confstr .= '!' . $this->getOption( 'thumbsize' );
3501 // add in language specific options, if any
3502 $extra = $wgContLang->getExtraHashOptions();
3503 $confstr .= $extra;
3505 // Since the skin could be overloading link(), it should be
3506 // included here but in practice, none of our skins do that.
3508 $confstr .= $wgRenderHashAppend;
3510 // Give a chance for extensions to modify the hash, if they have
3511 // extra options or other effects on the parser cache.
3512 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
3514 // Make it a valid memcached key fragment
3515 $confstr = str_replace( ' ', '_', $confstr );
3516 $this->mHash = $confstr;
3517 return $confstr;
3521 * Get whether the user is explicitly blocked from account creation.
3522 * @return bool|Block
3524 public function isBlockedFromCreateAccount() {
3525 $this->getBlockedStatus();
3526 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3527 return $this->mBlock;
3530 # bug 13611: if the IP address the user is trying to create an account from is
3531 # blocked with createaccount disabled, prevent new account creation there even
3532 # when the user is logged in
3533 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3534 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3536 return $this->mBlockedFromCreateAccount instanceof Block && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3537 ? $this->mBlockedFromCreateAccount
3538 : false;
3542 * Get whether the user is blocked from using Special:Emailuser.
3543 * @return bool
3545 public function isBlockedFromEmailuser() {
3546 $this->getBlockedStatus();
3547 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3551 * Get whether the user is allowed to create an account.
3552 * @return bool
3554 function isAllowedToCreateAccount() {
3555 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3559 * Get this user's personal page title.
3561 * @return Title: User's personal page title
3563 public function getUserPage() {
3564 return Title::makeTitle( NS_USER, $this->getName() );
3568 * Get this user's talk page title.
3570 * @return Title: User's talk page title
3572 public function getTalkPage() {
3573 $title = $this->getUserPage();
3574 return $title->getTalkPage();
3578 * Determine whether the user is a newbie. Newbies are either
3579 * anonymous IPs, or the most recently created accounts.
3580 * @return bool
3582 public function isNewbie() {
3583 return !$this->isAllowed( 'autoconfirmed' );
3587 * Check to see if the given clear-text password is one of the accepted passwords
3588 * @param string $password user password.
3589 * @return boolean: True if the given password is correct, otherwise False.
3591 public function checkPassword( $password ) {
3592 global $wgAuth, $wgLegacyEncoding;
3593 $this->load();
3595 // Even though we stop people from creating passwords that
3596 // are shorter than this, doesn't mean people wont be able
3597 // to. Certain authentication plugins do NOT want to save
3598 // domain passwords in a mysql database, so we should
3599 // check this (in case $wgAuth->strict() is false).
3600 if ( !$this->isValidPassword( $password ) ) {
3601 return false;
3604 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3605 return true;
3606 } elseif ( $wgAuth->strict() ) {
3607 // Auth plugin doesn't allow local authentication
3608 return false;
3609 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3610 // Auth plugin doesn't allow local authentication for this user name
3611 return false;
3613 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
3614 return true;
3615 } elseif ( $wgLegacyEncoding ) {
3616 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3617 // Check for this with iconv
3618 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3619 if ( $cp1252Password != $password &&
3620 self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) )
3622 return true;
3625 return false;
3629 * Check if the given clear-text password matches the temporary password
3630 * sent by e-mail for password reset operations.
3632 * @param $plaintext string
3634 * @return boolean: True if matches, false otherwise
3636 public function checkTemporaryPassword( $plaintext ) {
3637 global $wgNewPasswordExpiry;
3639 $this->load();
3640 if ( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
3641 if ( is_null( $this->mNewpassTime ) ) {
3642 return true;
3644 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
3645 return ( time() < $expiry );
3646 } else {
3647 return false;
3652 * Alias for getEditToken.
3653 * @deprecated since 1.19, use getEditToken instead.
3655 * @param string|array $salt of Strings Optional function-specific data for hashing
3656 * @param $request WebRequest object to use or null to use $wgRequest
3657 * @return string The new edit token
3659 public function editToken( $salt = '', $request = null ) {
3660 wfDeprecated( __METHOD__, '1.19' );
3661 return $this->getEditToken( $salt, $request );
3665 * Initialize (if necessary) and return a session token value
3666 * which can be used in edit forms to show that the user's
3667 * login credentials aren't being hijacked with a foreign form
3668 * submission.
3670 * @since 1.19
3672 * @param string|array $salt of Strings Optional function-specific data for hashing
3673 * @param $request WebRequest object to use or null to use $wgRequest
3674 * @return string The new edit token
3676 public function getEditToken( $salt = '', $request = null ) {
3677 if ( $request == null ) {
3678 $request = $this->getRequest();
3681 if ( $this->isAnon() ) {
3682 return EDIT_TOKEN_SUFFIX;
3683 } else {
3684 $token = $request->getSessionData( 'wsEditToken' );
3685 if ( $token === null ) {
3686 $token = MWCryptRand::generateHex( 32 );
3687 $request->setSessionData( 'wsEditToken', $token );
3689 if ( is_array( $salt ) ) {
3690 $salt = implode( '|', $salt );
3692 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
3697 * Generate a looking random token for various uses.
3699 * @return string The new random token
3700 * @deprecated since 1.20: Use MWCryptRand for secure purposes or wfRandomString for pseudo-randomness
3702 public static function generateToken() {
3703 return MWCryptRand::generateHex( 32 );
3707 * Check given value against the token value stored in the session.
3708 * A match should confirm that the form was submitted from the
3709 * user's own login session, not a form submission from a third-party
3710 * site.
3712 * @param string $val Input value to compare
3713 * @param string $salt Optional function-specific data for hashing
3714 * @param WebRequest $request Object to use or null to use $wgRequest
3715 * @return boolean: Whether the token matches
3717 public function matchEditToken( $val, $salt = '', $request = null ) {
3718 $sessionToken = $this->getEditToken( $salt, $request );
3719 if ( $val != $sessionToken ) {
3720 wfDebug( "User::matchEditToken: broken session data\n" );
3722 return $val == $sessionToken;
3726 * Check given value against the token value stored in the session,
3727 * ignoring the suffix.
3729 * @param string $val Input value to compare
3730 * @param string $salt Optional function-specific data for hashing
3731 * @param WebRequest $request object to use or null to use $wgRequest
3732 * @return boolean: Whether the token matches
3734 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3735 $sessionToken = $this->getEditToken( $salt, $request );
3736 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3740 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3741 * mail to the user's given address.
3743 * @param string $type message to send, either "created", "changed" or "set"
3744 * @return Status object
3746 public function sendConfirmationMail( $type = 'created' ) {
3747 global $wgLang;
3748 $expiration = null; // gets passed-by-ref and defined in next line.
3749 $token = $this->confirmationToken( $expiration );
3750 $url = $this->confirmationTokenUrl( $token );
3751 $invalidateURL = $this->invalidationTokenUrl( $token );
3752 $this->saveSettings();
3754 if ( $type == 'created' || $type === false ) {
3755 $message = 'confirmemail_body';
3756 } elseif ( $type === true ) {
3757 $message = 'confirmemail_body_changed';
3758 } else {
3759 // Give grep a chance to find the usages:
3760 // confirmemail_body_changed, confirmemail_body_set
3761 $message = 'confirmemail_body_' . $type;
3764 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3765 wfMessage( $message,
3766 $this->getRequest()->getIP(),
3767 $this->getName(),
3768 $url,
3769 $wgLang->timeanddate( $expiration, false ),
3770 $invalidateURL,
3771 $wgLang->date( $expiration, false ),
3772 $wgLang->time( $expiration, false ) )->text() );
3776 * Send an e-mail to this user's account. Does not check for
3777 * confirmed status or validity.
3779 * @param string $subject Message subject
3780 * @param string $body Message body
3781 * @param string $from Optional From address; if unspecified, default $wgPasswordSender will be used
3782 * @param string $replyto Reply-To address
3783 * @return Status
3785 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3786 if ( is_null( $from ) ) {
3787 global $wgPasswordSender, $wgPasswordSenderName;
3788 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
3789 } else {
3790 $sender = new MailAddress( $from );
3793 $to = new MailAddress( $this );
3794 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
3798 * Generate, store, and return a new e-mail confirmation code.
3799 * A hash (unsalted, since it's used as a key) is stored.
3801 * @note Call saveSettings() after calling this function to commit
3802 * this change to the database.
3804 * @param &$expiration \mixed Accepts the expiration time
3805 * @return string New token
3807 protected function confirmationToken( &$expiration ) {
3808 global $wgUserEmailConfirmationTokenExpiry;
3809 $now = time();
3810 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
3811 $expiration = wfTimestamp( TS_MW, $expires );
3812 $this->load();
3813 $token = MWCryptRand::generateHex( 32 );
3814 $hash = md5( $token );
3815 $this->mEmailToken = $hash;
3816 $this->mEmailTokenExpires = $expiration;
3817 return $token;
3821 * Return a URL the user can use to confirm their email address.
3822 * @param string $token Accepts the email confirmation token
3823 * @return string New token URL
3825 protected function confirmationTokenUrl( $token ) {
3826 return $this->getTokenUrl( 'ConfirmEmail', $token );
3830 * Return a URL the user can use to invalidate their email address.
3831 * @param string $token Accepts the email confirmation token
3832 * @return string New token URL
3834 protected function invalidationTokenUrl( $token ) {
3835 return $this->getTokenUrl( 'InvalidateEmail', $token );
3839 * Internal function to format the e-mail validation/invalidation URLs.
3840 * This uses a quickie hack to use the
3841 * hardcoded English names of the Special: pages, for ASCII safety.
3843 * @note Since these URLs get dropped directly into emails, using the
3844 * short English names avoids insanely long URL-encoded links, which
3845 * also sometimes can get corrupted in some browsers/mailers
3846 * (bug 6957 with Gmail and Internet Explorer).
3848 * @param string $page Special page
3849 * @param string $token Token
3850 * @return string Formatted URL
3852 protected function getTokenUrl( $page, $token ) {
3853 // Hack to bypass localization of 'Special:'
3854 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
3855 return $title->getCanonicalURL();
3859 * Mark the e-mail address confirmed.
3861 * @note Call saveSettings() after calling this function to commit the change.
3863 * @return bool
3865 public function confirmEmail() {
3866 // Check if it's already confirmed, so we don't touch the database
3867 // and fire the ConfirmEmailComplete hook on redundant confirmations.
3868 if ( !$this->isEmailConfirmed() ) {
3869 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3870 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3872 return true;
3876 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3877 * address if it was already confirmed.
3879 * @note Call saveSettings() after calling this function to commit the change.
3880 * @return bool Returns true
3882 function invalidateEmail() {
3883 $this->load();
3884 $this->mEmailToken = null;
3885 $this->mEmailTokenExpires = null;
3886 $this->setEmailAuthenticationTimestamp( null );
3887 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3888 return true;
3892 * Set the e-mail authentication timestamp.
3893 * @param string $timestamp TS_MW timestamp
3895 function setEmailAuthenticationTimestamp( $timestamp ) {
3896 $this->load();
3897 $this->mEmailAuthenticated = $timestamp;
3898 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
3902 * Is this user allowed to send e-mails within limits of current
3903 * site configuration?
3904 * @return bool
3906 public function canSendEmail() {
3907 global $wgEnableEmail, $wgEnableUserEmail;
3908 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
3909 return false;
3911 $canSend = $this->isEmailConfirmed();
3912 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3913 return $canSend;
3917 * Is this user allowed to receive e-mails within limits of current
3918 * site configuration?
3919 * @return bool
3921 public function canReceiveEmail() {
3922 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3926 * Is this user's e-mail address valid-looking and confirmed within
3927 * limits of the current site configuration?
3929 * @note If $wgEmailAuthentication is on, this may require the user to have
3930 * confirmed their address by returning a code or using a password
3931 * sent to the address from the wiki.
3933 * @return bool
3935 public function isEmailConfirmed() {
3936 global $wgEmailAuthentication;
3937 $this->load();
3938 $confirmed = true;
3939 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3940 if ( $this->isAnon() ) {
3941 return false;
3943 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
3944 return false;
3946 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
3947 return false;
3949 return true;
3950 } else {
3951 return $confirmed;
3956 * Check whether there is an outstanding request for e-mail confirmation.
3957 * @return bool
3959 public function isEmailConfirmationPending() {
3960 global $wgEmailAuthentication;
3961 return $wgEmailAuthentication &&
3962 !$this->isEmailConfirmed() &&
3963 $this->mEmailToken &&
3964 $this->mEmailTokenExpires > wfTimestamp();
3968 * Get the timestamp of account creation.
3970 * @return string|bool|null Timestamp of account creation, false for
3971 * non-existent/anonymous user accounts, or null if existing account
3972 * but information is not in database.
3974 public function getRegistration() {
3975 if ( $this->isAnon() ) {
3976 return false;
3978 $this->load();
3979 return $this->mRegistration;
3983 * Get the timestamp of the first edit
3985 * @return string|bool Timestamp of first edit, or false for
3986 * non-existent/anonymous user accounts.
3988 public function getFirstEditTimestamp() {
3989 if ( $this->getId() == 0 ) {
3990 return false; // anons
3992 $dbr = wfGetDB( DB_SLAVE );
3993 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3994 array( 'rev_user' => $this->getId() ),
3995 __METHOD__,
3996 array( 'ORDER BY' => 'rev_timestamp ASC' )
3998 if ( !$time ) {
3999 return false; // no edits
4001 return wfTimestamp( TS_MW, $time );
4005 * Get the permissions associated with a given list of groups
4007 * @param array $groups of Strings List of internal group names
4008 * @return Array of Strings List of permission key names for given groups combined
4010 public static function getGroupPermissions( $groups ) {
4011 global $wgGroupPermissions, $wgRevokePermissions;
4012 $rights = array();
4013 // grant every granted permission first
4014 foreach ( $groups as $group ) {
4015 if ( isset( $wgGroupPermissions[$group] ) ) {
4016 $rights = array_merge( $rights,
4017 // array_filter removes empty items
4018 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4021 // now revoke the revoked permissions
4022 foreach ( $groups as $group ) {
4023 if ( isset( $wgRevokePermissions[$group] ) ) {
4024 $rights = array_diff( $rights,
4025 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4028 return array_unique( $rights );
4032 * Get all the groups who have a given permission
4034 * @param string $role Role to check
4035 * @return Array of Strings List of internal group names with the given permission
4037 public static function getGroupsWithPermission( $role ) {
4038 global $wgGroupPermissions;
4039 $allowedGroups = array();
4040 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4041 if ( self::groupHasPermission( $group, $role ) ) {
4042 $allowedGroups[] = $group;
4045 return $allowedGroups;
4049 * Check, if the given group has the given permission
4051 * If you're wanting to check whether all users have a permission, use
4052 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4053 * from anyone.
4055 * @since 1.21
4056 * @param string $group Group to check
4057 * @param string $role Role to check
4058 * @return bool
4060 public static function groupHasPermission( $group, $role ) {
4061 global $wgGroupPermissions, $wgRevokePermissions;
4062 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4063 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4067 * Check if all users have the given permission
4069 * @since 1.22
4070 * @param string $right Right to check
4071 * @return bool
4073 public static function isEveryoneAllowed( $right ) {
4074 global $wgGroupPermissions, $wgRevokePermissions;
4075 static $cache = array();
4077 // Use the cached results, except in unit tests which rely on
4078 // being able change the permission mid-request
4079 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4080 return $cache[$right];
4083 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4084 $cache[$right] = false;
4085 return false;
4088 // If it's revoked anywhere, then everyone doesn't have it
4089 foreach ( $wgRevokePermissions as $rights ) {
4090 if ( isset( $rights[$right] ) && $rights[$right] ) {
4091 $cache[$right] = false;
4092 return false;
4096 // Allow extensions (e.g. OAuth) to say false
4097 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4098 $cache[$right] = false;
4099 return false;
4102 $cache[$right] = true;
4103 return true;
4107 * Get the localized descriptive name for a group, if it exists
4109 * @param string $group Internal group name
4110 * @return string Localized descriptive group name
4112 public static function getGroupName( $group ) {
4113 $msg = wfMessage( "group-$group" );
4114 return $msg->isBlank() ? $group : $msg->text();
4118 * Get the localized descriptive name for a member of a group, if it exists
4120 * @param string $group Internal group name
4121 * @param string $username Username for gender (since 1.19)
4122 * @return string Localized name for group member
4124 public static function getGroupMember( $group, $username = '#' ) {
4125 $msg = wfMessage( "group-$group-member", $username );
4126 return $msg->isBlank() ? $group : $msg->text();
4130 * Return the set of defined explicit groups.
4131 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4132 * are not included, as they are defined automatically, not in the database.
4133 * @return Array of internal group names
4135 public static function getAllGroups() {
4136 global $wgGroupPermissions, $wgRevokePermissions;
4137 return array_diff(
4138 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4139 self::getImplicitGroups()
4144 * Get a list of all available permissions.
4145 * @return Array of permission names
4147 public static function getAllRights() {
4148 if ( self::$mAllRights === false ) {
4149 global $wgAvailableRights;
4150 if ( count( $wgAvailableRights ) ) {
4151 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4152 } else {
4153 self::$mAllRights = self::$mCoreRights;
4155 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
4157 return self::$mAllRights;
4161 * Get a list of implicit groups
4162 * @return Array of Strings Array of internal group names
4164 public static function getImplicitGroups() {
4165 global $wgImplicitGroups;
4166 $groups = $wgImplicitGroups;
4167 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
4168 return $groups;
4172 * Get the title of a page describing a particular group
4174 * @param string $group Internal group name
4175 * @return Title|bool Title of the page if it exists, false otherwise
4177 public static function getGroupPage( $group ) {
4178 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4179 if ( $msg->exists() ) {
4180 $title = Title::newFromText( $msg->text() );
4181 if ( is_object( $title ) ) {
4182 return $title;
4185 return false;
4189 * Create a link to the group in HTML, if available;
4190 * else return the group name.
4192 * @param string $group Internal name of the group
4193 * @param string $text The text of the link
4194 * @return string HTML link to the group
4196 public static function makeGroupLinkHTML( $group, $text = '' ) {
4197 if ( $text == '' ) {
4198 $text = self::getGroupName( $group );
4200 $title = self::getGroupPage( $group );
4201 if ( $title ) {
4202 return Linker::link( $title, htmlspecialchars( $text ) );
4203 } else {
4204 return $text;
4209 * Create a link to the group in Wikitext, if available;
4210 * else return the group name.
4212 * @param string $group Internal name of the group
4213 * @param string $text The text of the link
4214 * @return string Wikilink to the group
4216 public static function makeGroupLinkWiki( $group, $text = '' ) {
4217 if ( $text == '' ) {
4218 $text = self::getGroupName( $group );
4220 $title = self::getGroupPage( $group );
4221 if ( $title ) {
4222 $page = $title->getPrefixedText();
4223 return "[[$page|$text]]";
4224 } else {
4225 return $text;
4230 * Returns an array of the groups that a particular group can add/remove.
4232 * @param string $group the group to check for whether it can add/remove
4233 * @return Array array( 'add' => array( addablegroups ),
4234 * 'remove' => array( removablegroups ),
4235 * 'add-self' => array( addablegroups to self),
4236 * 'remove-self' => array( removable groups from self) )
4238 public static function changeableByGroup( $group ) {
4239 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4241 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
4242 if ( empty( $wgAddGroups[$group] ) ) {
4243 // Don't add anything to $groups
4244 } elseif ( $wgAddGroups[$group] === true ) {
4245 // You get everything
4246 $groups['add'] = self::getAllGroups();
4247 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4248 $groups['add'] = $wgAddGroups[$group];
4251 // Same thing for remove
4252 if ( empty( $wgRemoveGroups[$group] ) ) {
4253 } elseif ( $wgRemoveGroups[$group] === true ) {
4254 $groups['remove'] = self::getAllGroups();
4255 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4256 $groups['remove'] = $wgRemoveGroups[$group];
4259 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4260 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4261 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4262 if ( is_int( $key ) ) {
4263 $wgGroupsAddToSelf['user'][] = $value;
4268 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4269 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4270 if ( is_int( $key ) ) {
4271 $wgGroupsRemoveFromSelf['user'][] = $value;
4276 // Now figure out what groups the user can add to him/herself
4277 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4278 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4279 // No idea WHY this would be used, but it's there
4280 $groups['add-self'] = User::getAllGroups();
4281 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4282 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4285 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4286 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4287 $groups['remove-self'] = User::getAllGroups();
4288 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4289 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4292 return $groups;
4296 * Returns an array of groups that this user can add and remove
4297 * @return Array array( 'add' => array( addablegroups ),
4298 * 'remove' => array( removablegroups ),
4299 * 'add-self' => array( addablegroups to self),
4300 * 'remove-self' => array( removable groups from self) )
4302 public function changeableGroups() {
4303 if ( $this->isAllowed( 'userrights' ) ) {
4304 // This group gives the right to modify everything (reverse-
4305 // compatibility with old "userrights lets you change
4306 // everything")
4307 // Using array_merge to make the groups reindexed
4308 $all = array_merge( User::getAllGroups() );
4309 return array(
4310 'add' => $all,
4311 'remove' => $all,
4312 'add-self' => array(),
4313 'remove-self' => array()
4317 // Okay, it's not so simple, we will have to go through the arrays
4318 $groups = array(
4319 'add' => array(),
4320 'remove' => array(),
4321 'add-self' => array(),
4322 'remove-self' => array()
4324 $addergroups = $this->getEffectiveGroups();
4326 foreach ( $addergroups as $addergroup ) {
4327 $groups = array_merge_recursive(
4328 $groups, $this->changeableByGroup( $addergroup )
4330 $groups['add'] = array_unique( $groups['add'] );
4331 $groups['remove'] = array_unique( $groups['remove'] );
4332 $groups['add-self'] = array_unique( $groups['add-self'] );
4333 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4335 return $groups;
4339 * Increment the user's edit-count field.
4340 * Will have no effect for anonymous users.
4342 public function incEditCount() {
4343 if ( !$this->isAnon() ) {
4344 $dbw = wfGetDB( DB_MASTER );
4345 $dbw->update(
4346 'user',
4347 array( 'user_editcount=user_editcount+1' ),
4348 array( 'user_id' => $this->getId() ),
4349 __METHOD__
4352 // Lazy initialization check...
4353 if ( $dbw->affectedRows() == 0 ) {
4354 // Now here's a goddamn hack...
4355 $dbr = wfGetDB( DB_SLAVE );
4356 if ( $dbr !== $dbw ) {
4357 // If we actually have a slave server, the count is
4358 // at least one behind because the current transaction
4359 // has not been committed and replicated.
4360 $this->initEditCount( 1 );
4361 } else {
4362 // But if DB_SLAVE is selecting the master, then the
4363 // count we just read includes the revision that was
4364 // just added in the working transaction.
4365 $this->initEditCount();
4369 // edit count in user cache too
4370 $this->invalidateCache();
4374 * Initialize user_editcount from data out of the revision table
4376 * @param $add Integer Edits to add to the count from the revision table
4377 * @return integer Number of edits
4379 protected function initEditCount( $add = 0 ) {
4380 // Pull from a slave to be less cruel to servers
4381 // Accuracy isn't the point anyway here
4382 $dbr = wfGetDB( DB_SLAVE );
4383 $count = (int) $dbr->selectField(
4384 'revision',
4385 'COUNT(rev_user)',
4386 array( 'rev_user' => $this->getId() ),
4387 __METHOD__
4389 $count = $count + $add;
4391 $dbw = wfGetDB( DB_MASTER );
4392 $dbw->update(
4393 'user',
4394 array( 'user_editcount' => $count ),
4395 array( 'user_id' => $this->getId() ),
4396 __METHOD__
4399 return $count;
4403 * Get the description of a given right
4405 * @param string $right Right to query
4406 * @return string Localized description of the right
4408 public static function getRightDescription( $right ) {
4409 $key = "right-$right";
4410 $msg = wfMessage( $key );
4411 return $msg->isBlank() ? $right : $msg->text();
4415 * Make an old-style password hash
4417 * @param string $password Plain-text password
4418 * @param string $userId User ID
4419 * @return string Password hash
4421 public static function oldCrypt( $password, $userId ) {
4422 global $wgPasswordSalt;
4423 if ( $wgPasswordSalt ) {
4424 return md5( $userId . '-' . md5( $password ) );
4425 } else {
4426 return md5( $password );
4431 * Make a new-style password hash
4433 * @param string $password Plain-text password
4434 * @param bool|string $salt Optional salt, may be random or the user ID.
4435 * If unspecified or false, will generate one automatically
4436 * @return string Password hash
4438 public static function crypt( $password, $salt = false ) {
4439 global $wgPasswordSalt;
4441 $hash = '';
4442 if ( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4443 return $hash;
4446 if ( $wgPasswordSalt ) {
4447 if ( $salt === false ) {
4448 $salt = MWCryptRand::generateHex( 8 );
4450 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4451 } else {
4452 return ':A:' . md5( $password );
4457 * Compare a password hash with a plain-text password. Requires the user
4458 * ID if there's a chance that the hash is an old-style hash.
4460 * @param string $hash Password hash
4461 * @param string $password Plain-text password to compare
4462 * @param string|bool $userId User ID for old-style password salt
4464 * @return boolean
4466 public static function comparePasswords( $hash, $password, $userId = false ) {
4467 $type = substr( $hash, 0, 3 );
4469 $result = false;
4470 if ( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4471 return $result;
4474 if ( $type == ':A:' ) {
4475 // Unsalted
4476 return md5( $password ) === substr( $hash, 3 );
4477 } elseif ( $type == ':B:' ) {
4478 // Salted
4479 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4480 return md5( $salt . '-' . md5( $password ) ) === $realHash;
4481 } else {
4482 // Old-style
4483 return self::oldCrypt( $password, $userId ) === $hash;
4488 * Add a newuser log entry for this user.
4489 * Before 1.19 the return value was always true.
4491 * @param string|bool $action account creation type.
4492 * - String, one of the following values:
4493 * - 'create' for an anonymous user creating an account for himself.
4494 * This will force the action's performer to be the created user itself,
4495 * no matter the value of $wgUser
4496 * - 'create2' for a logged in user creating an account for someone else
4497 * - 'byemail' when the created user will receive its password by e-mail
4498 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4499 * - Boolean means whether the account was created by e-mail (deprecated):
4500 * - true will be converted to 'byemail'
4501 * - false will be converted to 'create' if this object is the same as
4502 * $wgUser and to 'create2' otherwise
4504 * @param string $reason user supplied reason
4506 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4508 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4509 global $wgUser, $wgNewUserLog;
4510 if ( empty( $wgNewUserLog ) ) {
4511 return true; // disabled
4514 if ( $action === true ) {
4515 $action = 'byemail';
4516 } elseif ( $action === false ) {
4517 if ( $this->getName() == $wgUser->getName() ) {
4518 $action = 'create';
4519 } else {
4520 $action = 'create2';
4524 if ( $action === 'create' || $action === 'autocreate' ) {
4525 $performer = $this;
4526 } else {
4527 $performer = $wgUser;
4530 $logEntry = new ManualLogEntry( 'newusers', $action );
4531 $logEntry->setPerformer( $performer );
4532 $logEntry->setTarget( $this->getUserPage() );
4533 $logEntry->setComment( $reason );
4534 $logEntry->setParameters( array(
4535 '4::userid' => $this->getId(),
4536 ) );
4537 $logid = $logEntry->insert();
4539 if ( $action !== 'autocreate' ) {
4540 $logEntry->publish( $logid );
4543 return (int)$logid;
4547 * Add an autocreate newuser log entry for this user
4548 * Used by things like CentralAuth and perhaps other authplugins.
4549 * Consider calling addNewUserLogEntry() directly instead.
4551 * @return bool
4553 public function addNewUserLogEntryAutoCreate() {
4554 $this->addNewUserLogEntry( 'autocreate' );
4556 return true;
4560 * Load the user options either from cache, the database or an array
4562 * @param array $data Rows for the current user out of the user_properties table
4564 protected function loadOptions( $data = null ) {
4565 global $wgContLang;
4567 $this->load();
4569 if ( $this->mOptionsLoaded ) {
4570 return;
4573 $this->mOptions = self::getDefaultOptions();
4575 if ( !$this->getId() ) {
4576 // For unlogged-in users, load language/variant options from request.
4577 // There's no need to do it for logged-in users: they can set preferences,
4578 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4579 // so don't override user's choice (especially when the user chooses site default).
4580 $variant = $wgContLang->getDefaultVariant();
4581 $this->mOptions['variant'] = $variant;
4582 $this->mOptions['language'] = $variant;
4583 $this->mOptionsLoaded = true;
4584 return;
4587 // Maybe load from the object
4588 if ( !is_null( $this->mOptionOverrides ) ) {
4589 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4590 foreach ( $this->mOptionOverrides as $key => $value ) {
4591 $this->mOptions[$key] = $value;
4593 } else {
4594 if ( !is_array( $data ) ) {
4595 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4596 // Load from database
4597 $dbr = wfGetDB( DB_SLAVE );
4599 $res = $dbr->select(
4600 'user_properties',
4601 array( 'up_property', 'up_value' ),
4602 array( 'up_user' => $this->getId() ),
4603 __METHOD__
4606 $this->mOptionOverrides = array();
4607 $data = array();
4608 foreach ( $res as $row ) {
4609 $data[$row->up_property] = $row->up_value;
4612 foreach ( $data as $property => $value ) {
4613 $this->mOptionOverrides[$property] = $value;
4614 $this->mOptions[$property] = $value;
4618 $this->mOptionsLoaded = true;
4620 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
4624 * @todo document
4626 protected function saveOptions() {
4627 $this->loadOptions();
4629 // Not using getOptions(), to keep hidden preferences in database
4630 $saveOptions = $this->mOptions;
4632 // Allow hooks to abort, for instance to save to a global profile.
4633 // Reset options to default state before saving.
4634 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4635 return;
4638 $userId = $this->getId();
4639 $insert_rows = array();
4640 foreach ( $saveOptions as $key => $value ) {
4641 // Don't bother storing default values
4642 $defaultOption = self::getDefaultOption( $key );
4643 if ( ( is_null( $defaultOption ) &&
4644 !( $value === false || is_null( $value ) ) ) ||
4645 $value != $defaultOption ) {
4646 $insert_rows[] = array(
4647 'up_user' => $userId,
4648 'up_property' => $key,
4649 'up_value' => $value,
4654 $dbw = wfGetDB( DB_MASTER );
4655 $hasRows = $dbw->selectField( 'user_properties', '1',
4656 array( 'up_user' => $userId ), __METHOD__ );
4658 if ( $hasRows ) {
4659 // Only do this delete if there is something there. A very large portion of
4660 // calls to this function are for setting 'rememberpassword' for new accounts.
4661 // Doing this delete for new accounts with no rows in the table rougly causes
4662 // gap locks on [max user ID,+infinity) which causes high contention since many
4663 // updates will pile up on each other since they are for higher (newer) user IDs.
4664 $dbw->delete( 'user_properties', array( 'up_user' => $userId ), __METHOD__ );
4666 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
4670 * Provide an array of HTML5 attributes to put on an input element
4671 * intended for the user to enter a new password. This may include
4672 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4674 * Do *not* use this when asking the user to enter his current password!
4675 * Regardless of configuration, users may have invalid passwords for whatever
4676 * reason (e.g., they were set before requirements were tightened up).
4677 * Only use it when asking for a new password, like on account creation or
4678 * ResetPass.
4680 * Obviously, you still need to do server-side checking.
4682 * NOTE: A combination of bugs in various browsers means that this function
4683 * actually just returns array() unconditionally at the moment. May as
4684 * well keep it around for when the browser bugs get fixed, though.
4686 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4688 * @return array Array of HTML attributes suitable for feeding to
4689 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4690 * That will get confused by the boolean attribute syntax used.)
4692 public static function passwordChangeInputAttribs() {
4693 global $wgMinimalPasswordLength;
4695 if ( $wgMinimalPasswordLength == 0 ) {
4696 return array();
4699 # Note that the pattern requirement will always be satisfied if the
4700 # input is empty, so we need required in all cases.
4702 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4703 # if e-mail confirmation is being used. Since HTML5 input validation
4704 # is b0rked anyway in some browsers, just return nothing. When it's
4705 # re-enabled, fix this code to not output required for e-mail
4706 # registration.
4707 #$ret = array( 'required' );
4708 $ret = array();
4710 # We can't actually do this right now, because Opera 9.6 will print out
4711 # the entered password visibly in its error message! When other
4712 # browsers add support for this attribute, or Opera fixes its support,
4713 # we can add support with a version check to avoid doing this on Opera
4714 # versions where it will be a problem. Reported to Opera as
4715 # DSK-262266, but they don't have a public bug tracker for us to follow.
4717 if ( $wgMinimalPasswordLength > 1 ) {
4718 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4719 $ret['title'] = wfMessage( 'passwordtooshort' )
4720 ->numParams( $wgMinimalPasswordLength )->text();
4724 return $ret;
4728 * Return the list of user fields that should be selected to create
4729 * a new user object.
4730 * @return array
4732 public static function selectFields() {
4733 return array(
4734 'user_id',
4735 'user_name',
4736 'user_real_name',
4737 'user_password',
4738 'user_newpassword',
4739 'user_newpass_time',
4740 'user_email',
4741 'user_touched',
4742 'user_token',
4743 'user_email_authenticated',
4744 'user_email_token',
4745 'user_email_token_expires',
4746 'user_registration',
4747 'user_editcount',
4752 * Factory function for fatal permission-denied errors
4754 * @since 1.22
4755 * @param string $permission User right required
4756 * @return Status
4758 static function newFatalPermissionDeniedStatus( $permission ) {
4759 global $wgLang;
4761 $groups = array_map(
4762 array( 'User', 'makeGroupLinkWiki' ),
4763 User::getGroupsWithPermission( $permission )
4766 if ( $groups ) {
4767 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4768 } else {
4769 return Status::newFatal( 'badaccess-group0' );