Merge "jquery.makeCollapsible: cleanup"
[mediawiki.git] / includes / User.php
blob1c13211cd73e2d0055ad4fab9e8e9063643460cf
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 'editmyusercss',
128 'editmyuserjs',
129 'editusercssjs', #deprecated
130 'editusercss',
131 'edituserjs',
132 'hideuser',
133 'import',
134 'importupload',
135 'ipblock-exempt',
136 'markbotedits',
137 'mergehistory',
138 'minoredit',
139 'move',
140 'movefile',
141 'move-rootuserpages',
142 'move-subpages',
143 'nominornewtalk',
144 'noratelimit',
145 'override-export-depth',
146 'passwordreset',
147 'patrol',
148 'patrolmarks',
149 'protect',
150 'proxyunbannable',
151 'purge',
152 'read',
153 'reupload',
154 'reupload-own',
155 'reupload-shared',
156 'rollback',
157 'sendemail',
158 'siteadmin',
159 'suppressionlog',
160 'suppressredirect',
161 'suppressrevision',
162 'unblockself',
163 'undelete',
164 'unwatchedpages',
165 'upload',
166 'upload_by_url',
167 'userrights',
168 'userrights-interwiki',
169 'writeapi',
172 * String Cached results of getAllRights()
174 static $mAllRights = false;
176 /** @name Cache variables */
177 //@{
178 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
179 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
180 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mEditCount,
181 $mGroups, $mOptionOverrides;
182 //@}
185 * Bool Whether the cache variables have been loaded.
187 //@{
188 var $mOptionsLoaded;
191 * Array with already loaded items or true if all items have been loaded.
193 private $mLoadedItems = array();
194 //@}
197 * String Initialization data source if mLoadedItems!==true. May be one of:
198 * - 'defaults' anonymous user initialised from class defaults
199 * - 'name' initialise from mName
200 * - 'id' initialise from mId
201 * - 'session' log in from cookies or session if possible
203 * Use the User::newFrom*() family of functions to set this.
205 var $mFrom;
208 * Lazy-initialized variables, invalidated with clearInstanceCache
210 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mRights,
211 $mBlockreason, $mEffectiveGroups, $mImplicitGroups, $mFormerGroups, $mBlockedGlobally,
212 $mLocked, $mHideName, $mOptions;
215 * @var WebRequest
217 private $mRequest;
220 * @var Block
222 var $mBlock;
225 * @var bool
227 var $mAllowUsertalk;
230 * @var Block
232 private $mBlockedFromCreateAccount = false;
235 * @var Array
237 private $mWatchedItems = array();
239 static $idCacheByName = array();
242 * Lightweight constructor for an anonymous user.
243 * Use the User::newFrom* factory functions for other kinds of users.
245 * @see newFromName()
246 * @see newFromId()
247 * @see newFromConfirmationCode()
248 * @see newFromSession()
249 * @see newFromRow()
251 function __construct() {
252 $this->clearInstanceCache( 'defaults' );
256 * @return string
258 function __toString() {
259 return $this->getName();
263 * Load the user table data for this object from the source given by mFrom.
265 public function load() {
266 if ( $this->mLoadedItems === true ) {
267 return;
269 wfProfileIn( __METHOD__ );
271 // Set it now to avoid infinite recursion in accessors
272 $this->mLoadedItems = true;
274 switch ( $this->mFrom ) {
275 case 'defaults':
276 $this->loadDefaults();
277 break;
278 case 'name':
279 $this->mId = self::idFromName( $this->mName );
280 if ( !$this->mId ) {
281 // Nonexistent user placeholder object
282 $this->loadDefaults( $this->mName );
283 } else {
284 $this->loadFromId();
286 break;
287 case 'id':
288 $this->loadFromId();
289 break;
290 case 'session':
291 if ( !$this->loadFromSession() ) {
292 // Loading from session failed. Load defaults.
293 $this->loadDefaults();
295 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
296 break;
297 default:
298 wfProfileOut( __METHOD__ );
299 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
301 wfProfileOut( __METHOD__ );
305 * Load user table data, given mId has already been set.
306 * @return bool false if the ID does not exist, true otherwise
308 public function loadFromId() {
309 global $wgMemc;
310 if ( $this->mId == 0 ) {
311 $this->loadDefaults();
312 return false;
315 // Try cache
316 $key = wfMemcKey( 'user', 'id', $this->mId );
317 $data = $wgMemc->get( $key );
318 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
319 // Object is expired, load from DB
320 $data = false;
323 if ( !$data ) {
324 wfDebug( "User: cache miss for user {$this->mId}\n" );
325 // Load from DB
326 if ( !$this->loadFromDatabase() ) {
327 // Can't load from ID, user is anonymous
328 return false;
330 $this->saveToCache();
331 } else {
332 wfDebug( "User: got user {$this->mId} from cache\n" );
333 // Restore from cache
334 foreach ( self::$mCacheVars as $name ) {
335 $this->$name = $data[$name];
339 $this->mLoadedItems = true;
341 return true;
345 * Save user data to the shared cache
347 public function saveToCache() {
348 $this->load();
349 $this->loadGroups();
350 $this->loadOptions();
351 if ( $this->isAnon() ) {
352 // Anonymous users are uncached
353 return;
355 $data = array();
356 foreach ( self::$mCacheVars as $name ) {
357 $data[$name] = $this->$name;
359 $data['mVersion'] = MW_USER_VERSION;
360 $key = wfMemcKey( 'user', 'id', $this->mId );
361 global $wgMemc;
362 $wgMemc->set( $key, $data );
365 /** @name newFrom*() static factory methods */
366 //@{
369 * Static factory method for creation from username.
371 * This is slightly less efficient than newFromId(), so use newFromId() if
372 * you have both an ID and a name handy.
374 * @param string $name Username, validated by Title::newFromText()
375 * @param string|bool $validate Validate username. Takes the same parameters as
376 * User::getCanonicalName(), except that true is accepted as an alias
377 * for 'valid', for BC.
379 * @return User|bool User object, or false if the username is invalid
380 * (e.g. if it contains illegal characters or is an IP address). If the
381 * username is not present in the database, the result will be a user object
382 * with a name, zero user ID and default settings.
384 public static function newFromName( $name, $validate = 'valid' ) {
385 if ( $validate === true ) {
386 $validate = 'valid';
388 $name = self::getCanonicalName( $name, $validate );
389 if ( $name === false ) {
390 return false;
391 } else {
392 // Create unloaded user object
393 $u = new User;
394 $u->mName = $name;
395 $u->mFrom = 'name';
396 $u->setItemLoaded( 'name' );
397 return $u;
402 * Static factory method for creation from a given user ID.
404 * @param int $id Valid user ID
405 * @return User The corresponding User object
407 public static function newFromId( $id ) {
408 $u = new User;
409 $u->mId = $id;
410 $u->mFrom = 'id';
411 $u->setItemLoaded( 'id' );
412 return $u;
416 * Factory method to fetch whichever user has a given email confirmation code.
417 * This code is generated when an account is created or its e-mail address
418 * has changed.
420 * If the code is invalid or has expired, returns NULL.
422 * @param string $code Confirmation code
423 * @return User|null
425 public static function newFromConfirmationCode( $code ) {
426 $dbr = wfGetDB( DB_SLAVE );
427 $id = $dbr->selectField( 'user', 'user_id', array(
428 'user_email_token' => md5( $code ),
429 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
430 ) );
431 if ( $id !== false ) {
432 return User::newFromId( $id );
433 } else {
434 return null;
439 * Create a new user object using data from session or cookies. If the
440 * login credentials are invalid, the result is an anonymous user.
442 * @param WebRequest $request Object to use; $wgRequest will be used if omitted.
443 * @return User object
445 public static function newFromSession( WebRequest $request = null ) {
446 $user = new User;
447 $user->mFrom = 'session';
448 $user->mRequest = $request;
449 return $user;
453 * Create a new user object from a user row.
454 * The row should have the following fields from the user table in it:
455 * - either user_name or user_id to load further data if needed (or both)
456 * - user_real_name
457 * - all other fields (email, password, etc.)
458 * It is useless to provide the remaining fields if either user_id,
459 * user_name and user_real_name are not provided because the whole row
460 * will be loaded once more from the database when accessing them.
462 * @param array $row A row from the user table
463 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
464 * @return User
466 public static function newFromRow( $row, $data = null ) {
467 $user = new User;
468 $user->loadFromRow( $row, $data );
469 return $user;
472 //@}
475 * Get the username corresponding to a given user ID
476 * @param int $id User ID
477 * @return string|bool The corresponding username
479 public static function whoIs( $id ) {
480 return UserCache::singleton()->getProp( $id, 'name' );
484 * Get the real name of a user given their user ID
486 * @param int $id User ID
487 * @return string|bool The corresponding user's real name
489 public static function whoIsReal( $id ) {
490 return UserCache::singleton()->getProp( $id, 'real_name' );
494 * Get database id given a user name
495 * @param string $name Username
496 * @return int|null The corresponding user's ID, or null if user is nonexistent
498 public static function idFromName( $name ) {
499 $nt = Title::makeTitleSafe( NS_USER, $name );
500 if ( is_null( $nt ) ) {
501 // Illegal name
502 return null;
505 if ( isset( self::$idCacheByName[$name] ) ) {
506 return self::$idCacheByName[$name];
509 $dbr = wfGetDB( DB_SLAVE );
510 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
512 if ( $s === false ) {
513 $result = null;
514 } else {
515 $result = $s->user_id;
518 self::$idCacheByName[$name] = $result;
520 if ( count( self::$idCacheByName ) > 1000 ) {
521 self::$idCacheByName = array();
524 return $result;
528 * Reset the cache used in idFromName(). For use in tests.
530 public static function resetIdByNameCache() {
531 self::$idCacheByName = array();
535 * Does the string match an anonymous IPv4 address?
537 * This function exists for username validation, in order to reject
538 * usernames which are similar in form to IP addresses. Strings such
539 * as 300.300.300.300 will return true because it looks like an IP
540 * address, despite not being strictly valid.
542 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
543 * address because the usemod software would "cloak" anonymous IP
544 * addresses like this, if we allowed accounts like this to be created
545 * new users could get the old edits of these anonymous users.
547 * @param string $name Name to match
548 * @return bool
550 public static function isIP( $name ) {
551 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name ) || IP::isIPv6( $name );
555 * Is the input a valid username?
557 * Checks if the input is a valid username, we don't want an empty string,
558 * an IP address, anything that contains slashes (would mess up subpages),
559 * is longer than the maximum allowed username size or doesn't begin with
560 * a capital letter.
562 * @param string $name Name to match
563 * @return bool
565 public static function isValidUserName( $name ) {
566 global $wgContLang, $wgMaxNameChars;
568 if ( $name == ''
569 || User::isIP( $name )
570 || strpos( $name, '/' ) !== false
571 || strlen( $name ) > $wgMaxNameChars
572 || $name != $wgContLang->ucfirst( $name ) ) {
573 wfDebugLog( 'username', __METHOD__ .
574 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
575 return false;
578 // Ensure that the name can't be misresolved as a different title,
579 // such as with extra namespace keys at the start.
580 $parsed = Title::newFromText( $name );
581 if ( is_null( $parsed )
582 || $parsed->getNamespace()
583 || strcmp( $name, $parsed->getPrefixedText() ) ) {
584 wfDebugLog( 'username', __METHOD__ .
585 ": '$name' invalid due to ambiguous prefixes" );
586 return false;
589 // Check an additional blacklist of troublemaker characters.
590 // Should these be merged into the title char list?
591 $unicodeBlacklist = '/[' .
592 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
593 '\x{00a0}' . # non-breaking space
594 '\x{2000}-\x{200f}' . # various whitespace
595 '\x{2028}-\x{202f}' . # breaks and control chars
596 '\x{3000}' . # ideographic space
597 '\x{e000}-\x{f8ff}' . # private use
598 ']/u';
599 if ( preg_match( $unicodeBlacklist, $name ) ) {
600 wfDebugLog( 'username', __METHOD__ .
601 ": '$name' invalid due to blacklisted characters" );
602 return false;
605 return true;
609 * Usernames which fail to pass this function will be blocked
610 * from user login and new account registrations, but may be used
611 * internally by batch processes.
613 * If an account already exists in this form, login will be blocked
614 * by a failure to pass this function.
616 * @param string $name Name to match
617 * @return bool
619 public static function isUsableName( $name ) {
620 global $wgReservedUsernames;
621 // Must be a valid username, obviously ;)
622 if ( !self::isValidUserName( $name ) ) {
623 return false;
626 static $reservedUsernames = false;
627 if ( !$reservedUsernames ) {
628 $reservedUsernames = $wgReservedUsernames;
629 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
632 // Certain names may be reserved for batch processes.
633 foreach ( $reservedUsernames as $reserved ) {
634 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
635 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
637 if ( $reserved == $name ) {
638 return false;
641 return true;
645 * Usernames which fail to pass this function will be blocked
646 * from new account registrations, but may be used internally
647 * either by batch processes or by user accounts which have
648 * already been created.
650 * Additional blacklisting may be added here rather than in
651 * isValidUserName() to avoid disrupting existing accounts.
653 * @param string $name to match
654 * @return bool
656 public static function isCreatableName( $name ) {
657 global $wgInvalidUsernameCharacters;
659 // Ensure that the username isn't longer than 235 bytes, so that
660 // (at least for the builtin skins) user javascript and css files
661 // will work. (bug 23080)
662 if ( strlen( $name ) > 235 ) {
663 wfDebugLog( 'username', __METHOD__ .
664 ": '$name' invalid due to length" );
665 return false;
668 // Preg yells if you try to give it an empty string
669 if ( $wgInvalidUsernameCharacters !== '' ) {
670 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
671 wfDebugLog( 'username', __METHOD__ .
672 ": '$name' invalid due to wgInvalidUsernameCharacters" );
673 return false;
677 return self::isUsableName( $name );
681 * Is the input a valid password for this user?
683 * @param string $password Desired password
684 * @return bool
686 public function isValidPassword( $password ) {
687 //simple boolean wrapper for getPasswordValidity
688 return $this->getPasswordValidity( $password ) === true;
692 * Given unvalidated password input, return error message on failure.
694 * @param string $password Desired password
695 * @return mixed: true on success, string or array of error message on failure
697 public function getPasswordValidity( $password ) {
698 global $wgMinimalPasswordLength, $wgContLang;
700 static $blockedLogins = array(
701 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
702 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
705 $result = false; //init $result to false for the internal checks
707 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
708 return $result;
711 if ( $result === false ) {
712 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
713 return 'passwordtooshort';
714 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) {
715 return 'password-name-match';
716 } elseif ( isset( $blockedLogins[$this->getName()] ) && $password == $blockedLogins[$this->getName()] ) {
717 return 'password-login-forbidden';
718 } else {
719 //it seems weird returning true here, but this is because of the
720 //initialization of $result to false above. If the hook is never run or it
721 //doesn't modify $result, then we will likely get down into this if with
722 //a valid password.
723 return true;
725 } elseif ( $result === true ) {
726 return true;
727 } else {
728 return $result; //the isValidPassword hook set a string $result and returned true
733 * Does a string look like an e-mail address?
735 * This validates an email address using an HTML5 specification found at:
736 * http://www.whatwg.org/html/states-of-the-type-attribute.html#valid-e-mail-address
737 * Which as of 2011-01-24 says:
739 * A valid e-mail address is a string that matches the ABNF production
740 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
741 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
742 * 3.5.
744 * This function is an implementation of the specification as requested in
745 * bug 22449.
747 * Client-side forms will use the same standard validation rules via JS or
748 * HTML 5 validation; additional restrictions can be enforced server-side
749 * by extensions via the 'isValidEmailAddr' hook.
751 * Note that this validation doesn't 100% match RFC 2822, but is believed
752 * to be liberal enough for wide use. Some invalid addresses will still
753 * pass validation here.
755 * @param string $addr E-mail address
756 * @return bool
757 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
759 public static function isValidEmailAddr( $addr ) {
760 wfDeprecated( __METHOD__, '1.18' );
761 return Sanitizer::validateEmail( $addr );
765 * Given unvalidated user input, return a canonical username, or false if
766 * the username is invalid.
767 * @param string $name User input
768 * @param string|bool $validate type of validation to use:
769 * - false No validation
770 * - 'valid' Valid for batch processes
771 * - 'usable' Valid for batch processes and login
772 * - 'creatable' Valid for batch processes, login and account creation
774 * @throws MWException
775 * @return bool|string
777 public static function getCanonicalName( $name, $validate = 'valid' ) {
778 // Force usernames to capital
779 global $wgContLang;
780 $name = $wgContLang->ucfirst( $name );
782 # Reject names containing '#'; these will be cleaned up
783 # with title normalisation, but then it's too late to
784 # check elsewhere
785 if ( strpos( $name, '#' ) !== false ) {
786 return false;
789 // Clean up name according to title rules
790 $t = ( $validate === 'valid' ) ?
791 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
792 // Check for invalid titles
793 if ( is_null( $t ) ) {
794 return false;
797 // Reject various classes of invalid names
798 global $wgAuth;
799 $name = $wgAuth->getCanonicalName( $t->getText() );
801 switch ( $validate ) {
802 case false:
803 break;
804 case 'valid':
805 if ( !User::isValidUserName( $name ) ) {
806 $name = false;
808 break;
809 case 'usable':
810 if ( !User::isUsableName( $name ) ) {
811 $name = false;
813 break;
814 case 'creatable':
815 if ( !User::isCreatableName( $name ) ) {
816 $name = false;
818 break;
819 default:
820 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
822 return $name;
826 * Count the number of edits of a user
828 * @param int $uid User ID to check
829 * @return int The user's edit count
831 * @deprecated since 1.21 in favour of User::getEditCount
833 public static function edits( $uid ) {
834 wfDeprecated( __METHOD__, '1.21' );
835 $user = self::newFromId( $uid );
836 return $user->getEditCount();
840 * Return a random password.
842 * @return string New random password
844 public static function randomPassword() {
845 global $wgMinimalPasswordLength;
846 // Decide the final password length based on our min password length, stopping at a minimum of 10 chars
847 $length = max( 10, $wgMinimalPasswordLength );
848 // Multiply by 1.25 to get the number of hex characters we need
849 $length = $length * 1.25;
850 // Generate random hex chars
851 $hex = MWCryptRand::generateHex( $length );
852 // Convert from base 16 to base 32 to get a proper password like string
853 return wfBaseConvert( $hex, 16, 32 );
857 * Set cached properties to default.
859 * @note This no longer clears uncached lazy-initialised properties;
860 * the constructor does that instead.
862 * @param $name string|bool
864 public function loadDefaults( $name = false ) {
865 wfProfileIn( __METHOD__ );
867 $this->mId = 0;
868 $this->mName = $name;
869 $this->mRealName = '';
870 $this->mPassword = $this->mNewpassword = '';
871 $this->mNewpassTime = null;
872 $this->mEmail = '';
873 $this->mOptionOverrides = null;
874 $this->mOptionsLoaded = false;
876 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
877 if ( $loggedOut !== null ) {
878 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
879 } else {
880 $this->mTouched = '1'; # Allow any pages to be cached
883 $this->mToken = null; // Don't run cryptographic functions till we need a token
884 $this->mEmailAuthenticated = null;
885 $this->mEmailToken = '';
886 $this->mEmailTokenExpires = null;
887 $this->mRegistration = wfTimestamp( TS_MW );
888 $this->mGroups = array();
890 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
892 wfProfileOut( __METHOD__ );
896 * Return whether an item has been loaded.
898 * @param string $item item to check. Current possibilities:
899 * - id
900 * - name
901 * - realname
902 * @param string $all 'all' to check if the whole object has been loaded
903 * or any other string to check if only the item is available (e.g.
904 * for optimisation)
905 * @return boolean
907 public function isItemLoaded( $item, $all = 'all' ) {
908 return ( $this->mLoadedItems === true && $all === 'all' ) ||
909 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
913 * Set that an item has been loaded
915 * @param string $item
917 protected function setItemLoaded( $item ) {
918 if ( is_array( $this->mLoadedItems ) ) {
919 $this->mLoadedItems[$item] = true;
924 * Load user data from the session or login cookie.
925 * @return bool True if the user is logged in, false otherwise.
927 private function loadFromSession() {
928 $result = null;
929 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
930 if ( $result !== null ) {
931 return $result;
934 $request = $this->getRequest();
936 $cookieId = $request->getCookie( 'UserID' );
937 $sessId = $request->getSessionData( 'wsUserID' );
939 if ( $cookieId !== null ) {
940 $sId = intval( $cookieId );
941 if ( $sessId !== null && $cookieId != $sessId ) {
942 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
943 cookie user ID ($sId) don't match!" );
944 return false;
946 $request->setSessionData( 'wsUserID', $sId );
947 } elseif ( $sessId !== null && $sessId != 0 ) {
948 $sId = $sessId;
949 } else {
950 return false;
953 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
954 $sName = $request->getSessionData( 'wsUserName' );
955 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
956 $sName = $request->getCookie( 'UserName' );
957 $request->setSessionData( 'wsUserName', $sName );
958 } else {
959 return false;
962 $proposedUser = User::newFromId( $sId );
963 if ( !$proposedUser->isLoggedIn() ) {
964 // Not a valid ID
965 return false;
968 global $wgBlockDisablesLogin;
969 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
970 // User blocked and we've disabled blocked user logins
971 return false;
974 if ( $request->getSessionData( 'wsToken' ) ) {
975 $passwordCorrect = ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
976 $from = 'session';
977 } elseif ( $request->getCookie( 'Token' ) ) {
978 # Get the token from DB/cache and clean it up to remove garbage padding.
979 # This deals with historical problems with bugs and the default column value.
980 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
981 $passwordCorrect = ( strlen( $token ) && $token === $request->getCookie( 'Token' ) );
982 $from = 'cookie';
983 } else {
984 // No session or persistent login cookie
985 return false;
988 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
989 $this->loadFromUserObject( $proposedUser );
990 $request->setSessionData( 'wsToken', $this->mToken );
991 wfDebug( "User: logged in from $from\n" );
992 return true;
993 } else {
994 // Invalid credentials
995 wfDebug( "User: can't log in from $from, invalid credentials\n" );
996 return false;
1001 * Load user and user_group data from the database.
1002 * $this->mId must be set, this is how the user is identified.
1004 * @return bool True if the user exists, false if the user is anonymous
1006 public function loadFromDatabase() {
1007 // Paranoia
1008 $this->mId = intval( $this->mId );
1010 // Anonymous user
1011 if ( !$this->mId ) {
1012 $this->loadDefaults();
1013 return false;
1016 $dbr = wfGetDB( DB_MASTER );
1017 $s = $dbr->selectRow( 'user', self::selectFields(), array( 'user_id' => $this->mId ), __METHOD__ );
1019 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1021 if ( $s !== false ) {
1022 // Initialise user table data
1023 $this->loadFromRow( $s );
1024 $this->mGroups = null; // deferred
1025 $this->getEditCount(); // revalidation for nulls
1026 return true;
1027 } else {
1028 // Invalid user_id
1029 $this->mId = 0;
1030 $this->loadDefaults();
1031 return false;
1036 * Initialize this object from a row from the user table.
1038 * @param array $row Row from the user table to load.
1039 * @param array $data Further user data to load into the object
1041 * user_groups Array with groups out of the user_groups table
1042 * user_properties Array with properties out of the user_properties table
1044 public function loadFromRow( $row, $data = null ) {
1045 $all = true;
1047 $this->mGroups = null; // deferred
1049 if ( isset( $row->user_name ) ) {
1050 $this->mName = $row->user_name;
1051 $this->mFrom = 'name';
1052 $this->setItemLoaded( 'name' );
1053 } else {
1054 $all = false;
1057 if ( isset( $row->user_real_name ) ) {
1058 $this->mRealName = $row->user_real_name;
1059 $this->setItemLoaded( 'realname' );
1060 } else {
1061 $all = false;
1064 if ( isset( $row->user_id ) ) {
1065 $this->mId = intval( $row->user_id );
1066 $this->mFrom = 'id';
1067 $this->setItemLoaded( 'id' );
1068 } else {
1069 $all = false;
1072 if ( isset( $row->user_editcount ) ) {
1073 $this->mEditCount = $row->user_editcount;
1074 } else {
1075 $all = false;
1078 if ( isset( $row->user_password ) ) {
1079 $this->mPassword = $row->user_password;
1080 $this->mNewpassword = $row->user_newpassword;
1081 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
1082 $this->mEmail = $row->user_email;
1083 if ( isset( $row->user_options ) ) {
1084 $this->decodeOptions( $row->user_options );
1086 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1087 $this->mToken = $row->user_token;
1088 if ( $this->mToken == '' ) {
1089 $this->mToken = null;
1091 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1092 $this->mEmailToken = $row->user_email_token;
1093 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1094 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1095 } else {
1096 $all = false;
1099 if ( $all ) {
1100 $this->mLoadedItems = true;
1103 if ( is_array( $data ) ) {
1104 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1105 $this->mGroups = $data['user_groups'];
1107 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1108 $this->loadOptions( $data['user_properties'] );
1114 * Load the data for this user object from another user object.
1116 * @param $user User
1118 protected function loadFromUserObject( $user ) {
1119 $user->load();
1120 $user->loadGroups();
1121 $user->loadOptions();
1122 foreach ( self::$mCacheVars as $var ) {
1123 $this->$var = $user->$var;
1128 * Load the groups from the database if they aren't already loaded.
1130 private function loadGroups() {
1131 if ( is_null( $this->mGroups ) ) {
1132 $dbr = wfGetDB( DB_MASTER );
1133 $res = $dbr->select( 'user_groups',
1134 array( 'ug_group' ),
1135 array( 'ug_user' => $this->mId ),
1136 __METHOD__ );
1137 $this->mGroups = array();
1138 foreach ( $res as $row ) {
1139 $this->mGroups[] = $row->ug_group;
1145 * Add the user to the group if he/she meets given criteria.
1147 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1148 * possible to remove manually via Special:UserRights. In such case it
1149 * will not be re-added automatically. The user will also not lose the
1150 * group if they no longer meet the criteria.
1152 * @param string $event key in $wgAutopromoteOnce (each one has groups/criteria)
1154 * @return array Array of groups the user has been promoted to.
1156 * @see $wgAutopromoteOnce
1158 public function addAutopromoteOnceGroups( $event ) {
1159 global $wgAutopromoteOnceLogInRC;
1161 $toPromote = array();
1162 if ( $this->getId() ) {
1163 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1164 if ( count( $toPromote ) ) {
1165 $oldGroups = $this->getGroups(); // previous groups
1166 foreach ( $toPromote as $group ) {
1167 $this->addGroup( $group );
1169 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1171 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1172 $logEntry->setPerformer( $this );
1173 $logEntry->setTarget( $this->getUserPage() );
1174 $logEntry->setParameters( array(
1175 '4::oldgroups' => $oldGroups,
1176 '5::newgroups' => $newGroups,
1177 ) );
1178 $logid = $logEntry->insert();
1179 if ( $wgAutopromoteOnceLogInRC ) {
1180 $logEntry->publish( $logid );
1184 return $toPromote;
1188 * Clear various cached data stored in this object. The cache of the user table
1189 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1191 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1192 * given source. May be "name", "id", "defaults", "session", or false for
1193 * no reload.
1195 public function clearInstanceCache( $reloadFrom = false ) {
1196 $this->mNewtalk = -1;
1197 $this->mDatePreference = null;
1198 $this->mBlockedby = -1; # Unset
1199 $this->mHash = false;
1200 $this->mRights = null;
1201 $this->mEffectiveGroups = null;
1202 $this->mImplicitGroups = null;
1203 $this->mGroups = null;
1204 $this->mOptions = null;
1205 $this->mOptionsLoaded = false;
1206 $this->mEditCount = null;
1208 if ( $reloadFrom ) {
1209 $this->mLoadedItems = array();
1210 $this->mFrom = $reloadFrom;
1215 * Combine the language default options with any site-specific options
1216 * and add the default language variants.
1218 * @return Array of String options
1220 public static function getDefaultOptions() {
1221 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1223 static $defOpt = null;
1224 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1225 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1226 // mid-request and see that change reflected in the return value of this function.
1227 // Which is insane and would never happen during normal MW operation
1228 return $defOpt;
1231 $defOpt = $wgDefaultUserOptions;
1232 // Default language setting
1233 $defOpt['language'] = $defOpt['variant'] = $wgContLang->getCode();
1234 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1235 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1237 $defOpt['skin'] = $wgDefaultSkin;
1239 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1241 return $defOpt;
1245 * Get a given default option value.
1247 * @param string $opt Name of option to retrieve
1248 * @return string Default option value
1250 public static function getDefaultOption( $opt ) {
1251 $defOpts = self::getDefaultOptions();
1252 if ( isset( $defOpts[$opt] ) ) {
1253 return $defOpts[$opt];
1254 } else {
1255 return null;
1260 * Get blocking information
1261 * @param bool $bFromSlave Whether to check the slave database first. To
1262 * improve performance, non-critical checks are done
1263 * against slaves. Check when actually saving should be
1264 * done against master.
1266 private function getBlockedStatus( $bFromSlave = true ) {
1267 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1269 if ( -1 != $this->mBlockedby ) {
1270 return;
1273 wfProfileIn( __METHOD__ );
1274 wfDebug( __METHOD__ . ": checking...\n" );
1276 // Initialize data...
1277 // Otherwise something ends up stomping on $this->mBlockedby when
1278 // things get lazy-loaded later, causing false positive block hits
1279 // due to -1 !== 0. Probably session-related... Nothing should be
1280 // overwriting mBlockedby, surely?
1281 $this->load();
1283 # We only need to worry about passing the IP address to the Block generator if the
1284 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1285 # know which IP address they're actually coming from
1286 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1287 $ip = $this->getRequest()->getIP();
1288 } else {
1289 $ip = null;
1292 // User/IP blocking
1293 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1295 // Proxy blocking
1296 if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1297 && !in_array( $ip, $wgProxyWhitelist ) )
1299 // Local list
1300 if ( self::isLocallyBlockedProxy( $ip ) ) {
1301 $block = new Block;
1302 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1303 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1304 $block->setTarget( $ip );
1305 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1306 $block = new Block;
1307 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1308 $block->mReason = wfMessage( 'sorbsreason' )->text();
1309 $block->setTarget( $ip );
1313 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1314 if ( !$block instanceof Block
1315 && $wgApplyIpBlocksToXff
1316 && $ip !== null
1317 && !$this->isAllowed( 'proxyunbannable' )
1318 && !in_array( $ip, $wgProxyWhitelist )
1320 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1321 $xff = array_map( 'trim', explode( ',', $xff ) );
1322 $xff = array_diff( $xff, array( $ip ) );
1323 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1324 $block = Block::chooseBlock( $xffblocks, $xff );
1325 if ( $block instanceof Block ) {
1326 # Mangle the reason to alert the user that the block
1327 # originated from matching the X-Forwarded-For header.
1328 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1332 if ( $block instanceof Block ) {
1333 wfDebug( __METHOD__ . ": Found block.\n" );
1334 $this->mBlock = $block;
1335 $this->mBlockedby = $block->getByName();
1336 $this->mBlockreason = $block->mReason;
1337 $this->mHideName = $block->mHideName;
1338 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1339 } else {
1340 $this->mBlockedby = '';
1341 $this->mHideName = 0;
1342 $this->mAllowUsertalk = false;
1345 // Extensions
1346 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1348 wfProfileOut( __METHOD__ );
1352 * Whether the given IP is in a DNS blacklist.
1354 * @param string $ip IP to check
1355 * @param bool $checkWhitelist whether to check the whitelist first
1356 * @return bool True if blacklisted.
1358 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1359 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1360 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1362 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs ) {
1363 return false;
1366 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1367 return false;
1370 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1371 return $this->inDnsBlacklist( $ip, $urls );
1375 * Whether the given IP is in a given DNS blacklist.
1377 * @param string $ip IP to check
1378 * @param string|array $bases of Strings: URL of the DNS blacklist
1379 * @return bool True if blacklisted.
1381 public function inDnsBlacklist( $ip, $bases ) {
1382 wfProfileIn( __METHOD__ );
1384 $found = false;
1385 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1386 if ( IP::isIPv4( $ip ) ) {
1387 // Reverse IP, bug 21255
1388 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1390 foreach ( (array)$bases as $base ) {
1391 // Make hostname
1392 // If we have an access key, use that too (ProjectHoneypot, etc.)
1393 if ( is_array( $base ) ) {
1394 if ( count( $base ) >= 2 ) {
1395 // Access key is 1, base URL is 0
1396 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1397 } else {
1398 $host = "$ipReversed.{$base[0]}";
1400 } else {
1401 $host = "$ipReversed.$base";
1404 // Send query
1405 $ipList = gethostbynamel( $host );
1407 if ( $ipList ) {
1408 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1409 $found = true;
1410 break;
1411 } else {
1412 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base.\n" );
1417 wfProfileOut( __METHOD__ );
1418 return $found;
1422 * Check if an IP address is in the local proxy list
1424 * @param $ip string
1426 * @return bool
1428 public static function isLocallyBlockedProxy( $ip ) {
1429 global $wgProxyList;
1431 if ( !$wgProxyList ) {
1432 return false;
1434 wfProfileIn( __METHOD__ );
1436 if ( !is_array( $wgProxyList ) ) {
1437 // Load from the specified file
1438 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1441 if ( !is_array( $wgProxyList ) ) {
1442 $ret = false;
1443 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1444 $ret = true;
1445 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1446 // Old-style flipped proxy list
1447 $ret = true;
1448 } else {
1449 $ret = false;
1451 wfProfileOut( __METHOD__ );
1452 return $ret;
1456 * Is this user subject to rate limiting?
1458 * @return bool True if rate limited
1460 public function isPingLimitable() {
1461 global $wgRateLimitsExcludedIPs;
1462 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1463 // No other good way currently to disable rate limits
1464 // for specific IPs. :P
1465 // But this is a crappy hack and should die.
1466 return false;
1468 return !$this->isAllowed( 'noratelimit' );
1472 * Primitive rate limits: enforce maximum actions per time period
1473 * to put a brake on flooding.
1475 * @note When using a shared cache like memcached, IP-address
1476 * last-hit counters will be shared across wikis.
1478 * @param string $action Action to enforce; 'edit' if unspecified
1479 * @return bool True if a rate limiter was tripped
1481 public function pingLimiter( $action = 'edit' ) {
1482 // Call the 'PingLimiter' hook
1483 $result = false;
1484 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result ) ) ) {
1485 return $result;
1488 global $wgRateLimits;
1489 if ( !isset( $wgRateLimits[$action] ) ) {
1490 return false;
1493 // Some groups shouldn't trigger the ping limiter, ever
1494 if ( !$this->isPingLimitable() ) {
1495 return false;
1498 global $wgMemc, $wgRateLimitLog;
1499 wfProfileIn( __METHOD__ );
1501 $limits = $wgRateLimits[$action];
1502 $keys = array();
1503 $id = $this->getId();
1504 $userLimit = false;
1506 if ( isset( $limits['anon'] ) && $id == 0 ) {
1507 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1510 if ( isset( $limits['user'] ) && $id != 0 ) {
1511 $userLimit = $limits['user'];
1513 if ( $this->isNewbie() ) {
1514 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1515 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1517 if ( isset( $limits['ip'] ) ) {
1518 $ip = $this->getRequest()->getIP();
1519 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1521 if ( isset( $limits['subnet'] ) ) {
1522 $ip = $this->getRequest()->getIP();
1523 $matches = array();
1524 $subnet = false;
1525 if ( IP::isIPv6( $ip ) ) {
1526 $parts = IP::parseRange( "$ip/64" );
1527 $subnet = $parts[0];
1528 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1529 // IPv4
1530 $subnet = $matches[1];
1532 if ( $subnet !== false ) {
1533 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1537 // Check for group-specific permissions
1538 // If more than one group applies, use the group with the highest limit
1539 foreach ( $this->getGroups() as $group ) {
1540 if ( isset( $limits[$group] ) ) {
1541 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1542 $userLimit = $limits[$group];
1546 // Set the user limit key
1547 if ( $userLimit !== false ) {
1548 list( $max, $period ) = $userLimit;
1549 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1550 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1553 $triggered = false;
1554 foreach ( $keys as $key => $limit ) {
1555 list( $max, $period ) = $limit;
1556 $summary = "(limit $max in {$period}s)";
1557 $count = $wgMemc->get( $key );
1558 // Already pinged?
1559 if ( $count ) {
1560 if ( $count >= $max ) {
1561 wfDebug( __METHOD__ . ": tripped! $key at $count $summary\n" );
1562 if ( $wgRateLimitLog ) {
1563 wfSuppressWarnings();
1564 file_put_contents( $wgRateLimitLog, wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", FILE_APPEND );
1565 wfRestoreWarnings();
1567 $triggered = true;
1568 } else {
1569 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1571 } else {
1572 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1573 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1575 $wgMemc->incr( $key );
1578 wfProfileOut( __METHOD__ );
1579 return $triggered;
1583 * Check if user is blocked
1585 * @param bool $bFromSlave Whether to check the slave database instead of the master
1586 * @return bool True if blocked, false otherwise
1588 public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1589 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1593 * Get the block affecting the user, or null if the user is not blocked
1595 * @param bool $bFromSlave Whether to check the slave database instead of the master
1596 * @return Block|null
1598 public function getBlock( $bFromSlave = true ) {
1599 $this->getBlockedStatus( $bFromSlave );
1600 return $this->mBlock instanceof Block ? $this->mBlock : null;
1604 * Check if user is blocked from editing a particular article
1606 * @param Title $title Title to check
1607 * @param bool $bFromSlave whether to check the slave database instead of the master
1608 * @return bool
1610 function isBlockedFrom( $title, $bFromSlave = false ) {
1611 global $wgBlockAllowsUTEdit;
1612 wfProfileIn( __METHOD__ );
1614 $blocked = $this->isBlocked( $bFromSlave );
1615 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1616 // If a user's name is suppressed, they cannot make edits anywhere
1617 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName() &&
1618 $title->getNamespace() == NS_USER_TALK ) {
1619 $blocked = false;
1620 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1623 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1625 wfProfileOut( __METHOD__ );
1626 return $blocked;
1630 * If user is blocked, return the name of the user who placed the block
1631 * @return string Name of blocker
1633 public function blockedBy() {
1634 $this->getBlockedStatus();
1635 return $this->mBlockedby;
1639 * If user is blocked, return the specified reason for the block
1640 * @return string Blocking reason
1642 public function blockedFor() {
1643 $this->getBlockedStatus();
1644 return $this->mBlockreason;
1648 * If user is blocked, return the ID for the block
1649 * @return int Block ID
1651 public function getBlockId() {
1652 $this->getBlockedStatus();
1653 return ( $this->mBlock ? $this->mBlock->getId() : false );
1657 * Check if user is blocked on all wikis.
1658 * Do not use for actual edit permission checks!
1659 * This is intended for quick UI checks.
1661 * @param string $ip IP address, uses current client if none given
1662 * @return bool True if blocked, false otherwise
1664 public function isBlockedGlobally( $ip = '' ) {
1665 if ( $this->mBlockedGlobally !== null ) {
1666 return $this->mBlockedGlobally;
1668 // User is already an IP?
1669 if ( IP::isIPAddress( $this->getName() ) ) {
1670 $ip = $this->getName();
1671 } elseif ( !$ip ) {
1672 $ip = $this->getRequest()->getIP();
1674 $blocked = false;
1675 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1676 $this->mBlockedGlobally = (bool)$blocked;
1677 return $this->mBlockedGlobally;
1681 * Check if user account is locked
1683 * @return bool True if locked, false otherwise
1685 public function isLocked() {
1686 if ( $this->mLocked !== null ) {
1687 return $this->mLocked;
1689 global $wgAuth;
1690 $authUser = $wgAuth->getUserInstance( $this );
1691 $this->mLocked = (bool)$authUser->isLocked();
1692 return $this->mLocked;
1696 * Check if user account is hidden
1698 * @return bool True if hidden, false otherwise
1700 public function isHidden() {
1701 if ( $this->mHideName !== null ) {
1702 return $this->mHideName;
1704 $this->getBlockedStatus();
1705 if ( !$this->mHideName ) {
1706 global $wgAuth;
1707 $authUser = $wgAuth->getUserInstance( $this );
1708 $this->mHideName = (bool)$authUser->isHidden();
1710 return $this->mHideName;
1714 * Get the user's ID.
1715 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1717 public function getId() {
1718 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
1719 // Special case, we know the user is anonymous
1720 return 0;
1721 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1722 // Don't load if this was initialized from an ID
1723 $this->load();
1725 return $this->mId;
1729 * Set the user and reload all fields according to a given ID
1730 * @param int $v User ID to reload
1732 public function setId( $v ) {
1733 $this->mId = $v;
1734 $this->clearInstanceCache( 'id' );
1738 * Get the user name, or the IP of an anonymous user
1739 * @return string User's name or IP address
1741 public function getName() {
1742 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1743 // Special case optimisation
1744 return $this->mName;
1745 } else {
1746 $this->load();
1747 if ( $this->mName === false ) {
1748 // Clean up IPs
1749 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
1751 return $this->mName;
1756 * Set the user name.
1758 * This does not reload fields from the database according to the given
1759 * name. Rather, it is used to create a temporary "nonexistent user" for
1760 * later addition to the database. It can also be used to set the IP
1761 * address for an anonymous user to something other than the current
1762 * remote IP.
1764 * @note User::newFromName() has roughly the same function, when the named user
1765 * does not exist.
1766 * @param string $str New user name to set
1768 public function setName( $str ) {
1769 $this->load();
1770 $this->mName = $str;
1774 * Get the user's name escaped by underscores.
1775 * @return string Username escaped by underscores.
1777 public function getTitleKey() {
1778 return str_replace( ' ', '_', $this->getName() );
1782 * Check if the user has new messages.
1783 * @return bool True if the user has new messages
1785 public function getNewtalk() {
1786 $this->load();
1788 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1789 if ( $this->mNewtalk === -1 ) {
1790 $this->mNewtalk = false; # reset talk page status
1792 // Check memcached separately for anons, who have no
1793 // entire User object stored in there.
1794 if ( !$this->mId ) {
1795 global $wgDisableAnonTalk;
1796 if ( $wgDisableAnonTalk ) {
1797 // Anon newtalk disabled by configuration.
1798 $this->mNewtalk = false;
1799 } else {
1800 global $wgMemc;
1801 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1802 $newtalk = $wgMemc->get( $key );
1803 if ( strval( $newtalk ) !== '' ) {
1804 $this->mNewtalk = (bool)$newtalk;
1805 } else {
1806 // Since we are caching this, make sure it is up to date by getting it
1807 // from the master
1808 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1809 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1812 } else {
1813 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1817 return (bool)$this->mNewtalk;
1821 * Return the revision and link for the oldest new talk page message for
1822 * this user.
1823 * @note This function was designed to accomodate multiple talk pages, but
1824 * currently only returns a single link and revision.
1825 * @return Array
1827 public function getNewMessageLinks() {
1828 $talks = array();
1829 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
1830 return $talks;
1831 } elseif ( !$this->getNewtalk() ) {
1832 return array();
1834 $utp = $this->getTalkPage();
1835 $dbr = wfGetDB( DB_SLAVE );
1836 // Get the "last viewed rev" timestamp from the oldest message notification
1837 $timestamp = $dbr->selectField( 'user_newtalk',
1838 'MIN(user_last_timestamp)',
1839 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
1840 __METHOD__ );
1841 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
1842 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
1846 * Get the revision ID for the oldest new talk page message for this user
1847 * @return int|null Revision id or null if there are no new messages
1849 public function getNewMessageRevisionId() {
1850 $newMessageRevisionId = null;
1851 $newMessageLinks = $this->getNewMessageLinks();
1852 if ( $newMessageLinks ) {
1853 // Note: getNewMessageLinks() never returns more than a single link
1854 // and it is always for the same wiki, but we double-check here in
1855 // case that changes some time in the future.
1856 if ( count( $newMessageLinks ) === 1
1857 && $newMessageLinks[0]['wiki'] === wfWikiID()
1858 && $newMessageLinks[0]['rev']
1860 $newMessageRevision = $newMessageLinks[0]['rev'];
1861 $newMessageRevisionId = $newMessageRevision->getId();
1864 return $newMessageRevisionId;
1868 * Internal uncached check for new messages
1870 * @see getNewtalk()
1871 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1872 * @param string|int $id User's IP address for anonymous users, User ID otherwise
1873 * @param bool $fromMaster true to fetch from the master, false for a slave
1874 * @return bool True if the user has new messages
1876 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
1877 if ( $fromMaster ) {
1878 $db = wfGetDB( DB_MASTER );
1879 } else {
1880 $db = wfGetDB( DB_SLAVE );
1882 $ok = $db->selectField( 'user_newtalk', $field,
1883 array( $field => $id ), __METHOD__ );
1884 return $ok !== false;
1888 * Add or update the new messages flag
1889 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1890 * @param string|int $id User's IP address for anonymous users, User ID otherwise
1891 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null.
1892 * @return bool True if successful, false otherwise
1894 protected function updateNewtalk( $field, $id, $curRev = null ) {
1895 // Get timestamp of the talk page revision prior to the current one
1896 $prevRev = $curRev ? $curRev->getPrevious() : false;
1897 $ts = $prevRev ? $prevRev->getTimestamp() : null;
1898 // Mark the user as having new messages since this revision
1899 $dbw = wfGetDB( DB_MASTER );
1900 $dbw->insert( 'user_newtalk',
1901 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
1902 __METHOD__,
1903 'IGNORE' );
1904 if ( $dbw->affectedRows() ) {
1905 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
1906 return true;
1907 } else {
1908 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
1909 return false;
1914 * Clear the new messages flag for the given user
1915 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1916 * @param string|int $id User's IP address for anonymous users, User ID otherwise
1917 * @return bool True if successful, false otherwise
1919 protected function deleteNewtalk( $field, $id ) {
1920 $dbw = wfGetDB( DB_MASTER );
1921 $dbw->delete( 'user_newtalk',
1922 array( $field => $id ),
1923 __METHOD__ );
1924 if ( $dbw->affectedRows() ) {
1925 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
1926 return true;
1927 } else {
1928 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
1929 return false;
1934 * Update the 'You have new messages!' status.
1935 * @param bool $val Whether the user has new messages
1936 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null or !$val.
1938 public function setNewtalk( $val, $curRev = null ) {
1939 if ( wfReadOnly() ) {
1940 return;
1943 $this->load();
1944 $this->mNewtalk = $val;
1946 if ( $this->isAnon() ) {
1947 $field = 'user_ip';
1948 $id = $this->getName();
1949 } else {
1950 $field = 'user_id';
1951 $id = $this->getId();
1953 global $wgMemc;
1955 if ( $val ) {
1956 $changed = $this->updateNewtalk( $field, $id, $curRev );
1957 } else {
1958 $changed = $this->deleteNewtalk( $field, $id );
1961 if ( $this->isAnon() ) {
1962 // Anons have a separate memcached space, since
1963 // user records aren't kept for them.
1964 $key = wfMemcKey( 'newtalk', 'ip', $id );
1965 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
1967 if ( $changed ) {
1968 $this->invalidateCache();
1973 * Generate a current or new-future timestamp to be stored in the
1974 * user_touched field when we update things.
1975 * @return string Timestamp in TS_MW format
1977 private static function newTouchedTimestamp() {
1978 global $wgClockSkewFudge;
1979 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1983 * Clear user data from memcached.
1984 * Use after applying fun updates to the database; caller's
1985 * responsibility to update user_touched if appropriate.
1987 * Called implicitly from invalidateCache() and saveSettings().
1989 private function clearSharedCache() {
1990 $this->load();
1991 if ( $this->mId ) {
1992 global $wgMemc;
1993 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1998 * Immediately touch the user data cache for this account.
1999 * Updates user_touched field, and removes account data from memcached
2000 * for reload on the next hit.
2002 public function invalidateCache() {
2003 if ( wfReadOnly() ) {
2004 return;
2006 $this->load();
2007 if ( $this->mId ) {
2008 $this->mTouched = self::newTouchedTimestamp();
2010 $dbw = wfGetDB( DB_MASTER );
2011 $userid = $this->mId;
2012 $touched = $this->mTouched;
2013 $method = __METHOD__;
2014 $dbw->onTransactionIdle( function() use ( $dbw, $userid, $touched, $method ) {
2015 // Prevent contention slams by checking user_touched first
2016 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2017 $needsPurge = $dbw->selectField( 'user', '1',
2018 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2019 if ( $needsPurge ) {
2020 $dbw->update( 'user',
2021 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2022 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2023 $method
2026 } );
2027 $this->clearSharedCache();
2032 * Validate the cache for this account.
2033 * @param string $timestamp A timestamp in TS_MW format
2034 * @return bool
2036 public function validateCache( $timestamp ) {
2037 $this->load();
2038 return ( $timestamp >= $this->mTouched );
2042 * Get the user touched timestamp
2043 * @return string timestamp
2045 public function getTouched() {
2046 $this->load();
2047 return $this->mTouched;
2051 * Set the password and reset the random token.
2052 * Calls through to authentication plugin if necessary;
2053 * will have no effect if the auth plugin refuses to
2054 * pass the change through or if the legal password
2055 * checks fail.
2057 * As a special case, setting the password to null
2058 * wipes it, so the account cannot be logged in until
2059 * a new password is set, for instance via e-mail.
2061 * @param string $str New password to set
2062 * @throws PasswordError on failure
2064 * @return bool
2066 public function setPassword( $str ) {
2067 global $wgAuth;
2069 if ( $str !== null ) {
2070 if ( !$wgAuth->allowPasswordChange() ) {
2071 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2074 if ( !$this->isValidPassword( $str ) ) {
2075 global $wgMinimalPasswordLength;
2076 $valid = $this->getPasswordValidity( $str );
2077 if ( is_array( $valid ) ) {
2078 $message = array_shift( $valid );
2079 $params = $valid;
2080 } else {
2081 $message = $valid;
2082 $params = array( $wgMinimalPasswordLength );
2084 throw new PasswordError( wfMessage( $message, $params )->text() );
2088 if ( !$wgAuth->setPassword( $this, $str ) ) {
2089 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2092 $this->setInternalPassword( $str );
2094 return true;
2098 * Set the password and reset the random token unconditionally.
2100 * @param string|null $str New password to set or null to set an invalid
2101 * password hash meaning that the user will not be able to log in
2102 * through the web interface.
2104 public function setInternalPassword( $str ) {
2105 $this->load();
2106 $this->setToken();
2108 if ( $str === null ) {
2109 // Save an invalid hash...
2110 $this->mPassword = '';
2111 } else {
2112 $this->mPassword = self::crypt( $str );
2114 $this->mNewpassword = '';
2115 $this->mNewpassTime = null;
2119 * Get the user's current token.
2120 * @param bool $forceCreation Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility)
2121 * @return string Token
2123 public function getToken( $forceCreation = true ) {
2124 $this->load();
2125 if ( !$this->mToken && $forceCreation ) {
2126 $this->setToken();
2128 return $this->mToken;
2132 * Set the random token (used for persistent authentication)
2133 * Called from loadDefaults() among other places.
2135 * @param string|bool $token If specified, set the token to this value
2137 public function setToken( $token = false ) {
2138 $this->load();
2139 if ( !$token ) {
2140 $this->mToken = MWCryptRand::generateHex( USER_TOKEN_LENGTH );
2141 } else {
2142 $this->mToken = $token;
2147 * Set the password for a password reminder or new account email
2149 * @param string $str New password to set
2150 * @param bool $throttle If true, reset the throttle timestamp to the present
2152 public function setNewpassword( $str, $throttle = true ) {
2153 $this->load();
2154 $this->mNewpassword = self::crypt( $str );
2155 if ( $throttle ) {
2156 $this->mNewpassTime = wfTimestampNow();
2161 * Has password reminder email been sent within the last
2162 * $wgPasswordReminderResendTime hours?
2163 * @return bool
2165 public function isPasswordReminderThrottled() {
2166 global $wgPasswordReminderResendTime;
2167 $this->load();
2168 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
2169 return false;
2171 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
2172 return time() < $expiry;
2176 * Get the user's e-mail address
2177 * @return string User's email address
2179 public function getEmail() {
2180 $this->load();
2181 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
2182 return $this->mEmail;
2186 * Get the timestamp of the user's e-mail authentication
2187 * @return string TS_MW timestamp
2189 public function getEmailAuthenticationTimestamp() {
2190 $this->load();
2191 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2192 return $this->mEmailAuthenticated;
2196 * Set the user's e-mail address
2197 * @param string $str New e-mail address
2199 public function setEmail( $str ) {
2200 $this->load();
2201 if ( $str == $this->mEmail ) {
2202 return;
2204 $this->mEmail = $str;
2205 $this->invalidateEmail();
2206 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
2210 * Set the user's e-mail address and a confirmation mail if needed.
2212 * @since 1.20
2213 * @param string $str New e-mail address
2214 * @return Status
2216 public function setEmailWithConfirmation( $str ) {
2217 global $wgEnableEmail, $wgEmailAuthentication;
2219 if ( !$wgEnableEmail ) {
2220 return Status::newFatal( 'emaildisabled' );
2223 $oldaddr = $this->getEmail();
2224 if ( $str === $oldaddr ) {
2225 return Status::newGood( true );
2228 $this->setEmail( $str );
2230 if ( $str !== '' && $wgEmailAuthentication ) {
2231 // Send a confirmation request to the new address if needed
2232 $type = $oldaddr != '' ? 'changed' : 'set';
2233 $result = $this->sendConfirmationMail( $type );
2234 if ( $result->isGood() ) {
2235 // Say the the caller that a confirmation mail has been sent
2236 $result->value = 'eauth';
2238 } else {
2239 $result = Status::newGood( true );
2242 return $result;
2246 * Get the user's real name
2247 * @return string User's real name
2249 public function getRealName() {
2250 if ( !$this->isItemLoaded( 'realname' ) ) {
2251 $this->load();
2254 return $this->mRealName;
2258 * Set the user's real name
2259 * @param string $str New real name
2261 public function setRealName( $str ) {
2262 $this->load();
2263 $this->mRealName = $str;
2267 * Get the user's current setting for a given option.
2269 * @param string $oname The option to check
2270 * @param string $defaultOverride A default value returned if the option does not exist
2271 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2272 * @return string User's current value for the option
2273 * @see getBoolOption()
2274 * @see getIntOption()
2276 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2277 global $wgHiddenPrefs;
2278 $this->loadOptions();
2280 # We want 'disabled' preferences to always behave as the default value for
2281 # users, even if they have set the option explicitly in their settings (ie they
2282 # set it, and then it was disabled removing their ability to change it). But
2283 # we don't want to erase the preferences in the database in case the preference
2284 # is re-enabled again. So don't touch $mOptions, just override the returned value
2285 if ( in_array( $oname, $wgHiddenPrefs ) && !$ignoreHidden ) {
2286 return self::getDefaultOption( $oname );
2289 if ( array_key_exists( $oname, $this->mOptions ) ) {
2290 return $this->mOptions[$oname];
2291 } else {
2292 return $defaultOverride;
2297 * Get all user's options
2299 * @return array
2301 public function getOptions() {
2302 global $wgHiddenPrefs;
2303 $this->loadOptions();
2304 $options = $this->mOptions;
2306 # We want 'disabled' preferences to always behave as the default value for
2307 # users, even if they have set the option explicitly in their settings (ie they
2308 # set it, and then it was disabled removing their ability to change it). But
2309 # we don't want to erase the preferences in the database in case the preference
2310 # is re-enabled again. So don't touch $mOptions, just override the returned value
2311 foreach ( $wgHiddenPrefs as $pref ) {
2312 $default = self::getDefaultOption( $pref );
2313 if ( $default !== null ) {
2314 $options[$pref] = $default;
2318 return $options;
2322 * Get the user's current setting for a given option, as a boolean value.
2324 * @param string $oname The option to check
2325 * @return bool User's current value for the option
2326 * @see getOption()
2328 public function getBoolOption( $oname ) {
2329 return (bool)$this->getOption( $oname );
2333 * Get the user's current setting for a given option, as a boolean value.
2335 * @param string $oname The option to check
2336 * @param int $defaultOverride A default value returned if the option does not exist
2337 * @return int User's current value for the option
2338 * @see getOption()
2340 public function getIntOption( $oname, $defaultOverride = 0 ) {
2341 $val = $this->getOption( $oname );
2342 if ( $val == '' ) {
2343 $val = $defaultOverride;
2345 return intval( $val );
2349 * Set the given option for a user.
2351 * @param string $oname The option to set
2352 * @param mixed $val New value to set
2354 public function setOption( $oname, $val ) {
2355 $this->loadOptions();
2357 // Explicitly NULL values should refer to defaults
2358 if ( is_null( $val ) ) {
2359 $val = self::getDefaultOption( $oname );
2362 $this->mOptions[$oname] = $val;
2366 * Return a list of the types of user options currently returned by
2367 * User::getOptionKinds().
2369 * Currently, the option kinds are:
2370 * - 'registered' - preferences which are registered in core MediaWiki or
2371 * by extensions using the UserGetDefaultOptions hook.
2372 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2373 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2374 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2375 * be used by user scripts.
2376 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2377 * These are usually legacy options, removed in newer versions.
2379 * The API (and possibly others) use this function to determine the possible
2380 * option types for validation purposes, so make sure to update this when a
2381 * new option kind is added.
2383 * @see User::getOptionKinds
2384 * @return array Option kinds
2386 public static function listOptionKinds() {
2387 return array(
2388 'registered',
2389 'registered-multiselect',
2390 'registered-checkmatrix',
2391 'userjs',
2392 'unused'
2397 * Return an associative array mapping preferences keys to the kind of a preference they're
2398 * used for. Different kinds are handled differently when setting or reading preferences.
2400 * See User::listOptionKinds for the list of valid option types that can be provided.
2402 * @see User::listOptionKinds
2403 * @param $context IContextSource
2404 * @param array $options assoc. array with options keys to check as keys. Defaults to $this->mOptions.
2405 * @return array the key => kind mapping data
2407 public function getOptionKinds( IContextSource $context, $options = null ) {
2408 $this->loadOptions();
2409 if ( $options === null ) {
2410 $options = $this->mOptions;
2413 $prefs = Preferences::getPreferences( $this, $context );
2414 $mapping = array();
2416 // Multiselect and checkmatrix options are stored in the database with
2417 // one key per option, each having a boolean value. Extract those keys.
2418 $multiselectOptions = array();
2419 foreach ( $prefs as $name => $info ) {
2420 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2421 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2422 $opts = HTMLFormField::flattenOptions( $info['options'] );
2423 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2425 foreach ( $opts as $value ) {
2426 $multiselectOptions["$prefix$value"] = true;
2429 unset( $prefs[$name] );
2432 $checkmatrixOptions = array();
2433 foreach ( $prefs as $name => $info ) {
2434 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2435 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2436 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2437 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2438 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2440 foreach ( $columns as $column ) {
2441 foreach ( $rows as $row ) {
2442 $checkmatrixOptions["$prefix-$column-$row"] = true;
2446 unset( $prefs[$name] );
2450 // $value is ignored
2451 foreach ( $options as $key => $value ) {
2452 if ( isset( $prefs[$key] ) ) {
2453 $mapping[$key] = 'registered';
2454 } elseif ( isset( $multiselectOptions[$key] ) ) {
2455 $mapping[$key] = 'registered-multiselect';
2456 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2457 $mapping[$key] = 'registered-checkmatrix';
2458 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2459 $mapping[$key] = 'userjs';
2460 } else {
2461 $mapping[$key] = 'unused';
2465 return $mapping;
2469 * Reset certain (or all) options to the site defaults
2471 * The optional parameter determines which kinds of preferences will be reset.
2472 * Supported values are everything that can be reported by getOptionKinds()
2473 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2475 * @param array|string $resetKinds which kinds of preferences to reset. Defaults to
2476 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2477 * for backwards-compatibility.
2478 * @param $context IContextSource|null context source used when $resetKinds
2479 * does not contain 'all', passed to getOptionKinds().
2480 * Defaults to RequestContext::getMain() when null.
2482 public function resetOptions(
2483 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2484 IContextSource $context = null
2486 $this->load();
2487 $defaultOptions = self::getDefaultOptions();
2489 if ( !is_array( $resetKinds ) ) {
2490 $resetKinds = array( $resetKinds );
2493 if ( in_array( 'all', $resetKinds ) ) {
2494 $newOptions = $defaultOptions;
2495 } else {
2496 if ( $context === null ) {
2497 $context = RequestContext::getMain();
2500 $optionKinds = $this->getOptionKinds( $context );
2501 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2502 $newOptions = array();
2504 // Use default values for the options that should be deleted, and
2505 // copy old values for the ones that shouldn't.
2506 foreach ( $this->mOptions as $key => $value ) {
2507 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2508 if ( array_key_exists( $key, $defaultOptions ) ) {
2509 $newOptions[$key] = $defaultOptions[$key];
2511 } else {
2512 $newOptions[$key] = $value;
2517 $this->mOptions = $newOptions;
2518 $this->mOptionsLoaded = true;
2522 * Get the user's preferred date format.
2523 * @return string User's preferred date format
2525 public function getDatePreference() {
2526 // Important migration for old data rows
2527 if ( is_null( $this->mDatePreference ) ) {
2528 global $wgLang;
2529 $value = $this->getOption( 'date' );
2530 $map = $wgLang->getDatePreferenceMigrationMap();
2531 if ( isset( $map[$value] ) ) {
2532 $value = $map[$value];
2534 $this->mDatePreference = $value;
2536 return $this->mDatePreference;
2540 * Get the user preferred stub threshold
2542 * @return int
2544 public function getStubThreshold() {
2545 global $wgMaxArticleSize; # Maximum article size, in Kb
2546 $threshold = $this->getIntOption( 'stubthreshold' );
2547 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2548 // If they have set an impossible value, disable the preference
2549 // so we can use the parser cache again.
2550 $threshold = 0;
2552 return $threshold;
2556 * Get the permissions this user has.
2557 * @return Array of String permission names
2559 public function getRights() {
2560 if ( is_null( $this->mRights ) ) {
2561 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2562 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2563 // Force reindexation of rights when a hook has unset one of them
2564 $this->mRights = array_values( array_unique( $this->mRights ) );
2566 return $this->mRights;
2570 * Get the list of explicit group memberships this user has.
2571 * The implicit * and user groups are not included.
2572 * @return Array of String internal group names
2574 public function getGroups() {
2575 $this->load();
2576 $this->loadGroups();
2577 return $this->mGroups;
2581 * Get the list of implicit group memberships this user has.
2582 * This includes all explicit groups, plus 'user' if logged in,
2583 * '*' for all accounts, and autopromoted groups
2584 * @param bool $recache Whether to avoid the cache
2585 * @return Array of String internal group names
2587 public function getEffectiveGroups( $recache = false ) {
2588 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2589 wfProfileIn( __METHOD__ );
2590 $this->mEffectiveGroups = array_unique( array_merge(
2591 $this->getGroups(), // explicit groups
2592 $this->getAutomaticGroups( $recache ) // implicit groups
2593 ) );
2594 // Hook for additional groups
2595 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2596 // Force reindexation of groups when a hook has unset one of them
2597 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
2598 wfProfileOut( __METHOD__ );
2600 return $this->mEffectiveGroups;
2604 * Get the list of implicit group memberships this user has.
2605 * This includes 'user' if logged in, '*' for all accounts,
2606 * and autopromoted groups
2607 * @param bool $recache Whether to avoid the cache
2608 * @return Array of String internal group names
2610 public function getAutomaticGroups( $recache = false ) {
2611 if ( $recache || is_null( $this->mImplicitGroups ) ) {
2612 wfProfileIn( __METHOD__ );
2613 $this->mImplicitGroups = array( '*' );
2614 if ( $this->getId() ) {
2615 $this->mImplicitGroups[] = 'user';
2617 $this->mImplicitGroups = array_unique( array_merge(
2618 $this->mImplicitGroups,
2619 Autopromote::getAutopromoteGroups( $this )
2620 ) );
2622 if ( $recache ) {
2623 // Assure data consistency with rights/groups,
2624 // as getEffectiveGroups() depends on this function
2625 $this->mEffectiveGroups = null;
2627 wfProfileOut( __METHOD__ );
2629 return $this->mImplicitGroups;
2633 * Returns the groups the user has belonged to.
2635 * The user may still belong to the returned groups. Compare with getGroups().
2637 * The function will not return groups the user had belonged to before MW 1.17
2639 * @return array Names of the groups the user has belonged to.
2641 public function getFormerGroups() {
2642 if ( is_null( $this->mFormerGroups ) ) {
2643 $dbr = wfGetDB( DB_MASTER );
2644 $res = $dbr->select( 'user_former_groups',
2645 array( 'ufg_group' ),
2646 array( 'ufg_user' => $this->mId ),
2647 __METHOD__ );
2648 $this->mFormerGroups = array();
2649 foreach ( $res as $row ) {
2650 $this->mFormerGroups[] = $row->ufg_group;
2653 return $this->mFormerGroups;
2657 * Get the user's edit count.
2658 * @return int
2660 public function getEditCount() {
2661 if ( !$this->getId() ) {
2662 return null;
2665 if ( !isset( $this->mEditCount ) ) {
2666 /* Populate the count, if it has not been populated yet */
2667 wfProfileIn( __METHOD__ );
2668 $dbr = wfGetDB( DB_SLAVE );
2669 // check if the user_editcount field has been initialized
2670 $count = $dbr->selectField(
2671 'user', 'user_editcount',
2672 array( 'user_id' => $this->mId ),
2673 __METHOD__
2676 if ( $count === null ) {
2677 // it has not been initialized. do so.
2678 $count = $this->initEditCount();
2680 $this->mEditCount = intval( $count );
2681 wfProfileOut( __METHOD__ );
2683 return $this->mEditCount;
2687 * Add the user to the given group.
2688 * This takes immediate effect.
2689 * @param string $group Name of the group to add
2691 public function addGroup( $group ) {
2692 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2693 $dbw = wfGetDB( DB_MASTER );
2694 if ( $this->getId() ) {
2695 $dbw->insert( 'user_groups',
2696 array(
2697 'ug_user' => $this->getID(),
2698 'ug_group' => $group,
2700 __METHOD__,
2701 array( 'IGNORE' ) );
2704 $this->loadGroups();
2705 $this->mGroups[] = $group;
2706 // In case loadGroups was not called before, we now have the right twice.
2707 // Get rid of the duplicate.
2708 $this->mGroups = array_unique( $this->mGroups );
2709 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2711 $this->invalidateCache();
2715 * Remove the user from the given group.
2716 * This takes immediate effect.
2717 * @param string $group Name of the group to remove
2719 public function removeGroup( $group ) {
2720 $this->load();
2721 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2722 $dbw = wfGetDB( DB_MASTER );
2723 $dbw->delete( 'user_groups',
2724 array(
2725 'ug_user' => $this->getID(),
2726 'ug_group' => $group,
2727 ), __METHOD__ );
2728 // Remember that the user was in this group
2729 $dbw->insert( 'user_former_groups',
2730 array(
2731 'ufg_user' => $this->getID(),
2732 'ufg_group' => $group,
2734 __METHOD__,
2735 array( 'IGNORE' ) );
2737 $this->loadGroups();
2738 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2739 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2741 $this->invalidateCache();
2745 * Get whether the user is logged in
2746 * @return bool
2748 public function isLoggedIn() {
2749 return $this->getID() != 0;
2753 * Get whether the user is anonymous
2754 * @return bool
2756 public function isAnon() {
2757 return !$this->isLoggedIn();
2761 * Check if user is allowed to access a feature / make an action
2763 * @internal param \String $varargs permissions to test
2764 * @return boolean: True if user is allowed to perform *any* of the given actions
2766 * @return bool
2768 public function isAllowedAny( /*...*/ ) {
2769 $permissions = func_get_args();
2770 foreach ( $permissions as $permission ) {
2771 if ( $this->isAllowed( $permission ) ) {
2772 return true;
2775 return false;
2780 * @internal param $varargs string
2781 * @return bool True if the user is allowed to perform *all* of the given actions
2783 public function isAllowedAll( /*...*/ ) {
2784 $permissions = func_get_args();
2785 foreach ( $permissions as $permission ) {
2786 if ( !$this->isAllowed( $permission ) ) {
2787 return false;
2790 return true;
2794 * Internal mechanics of testing a permission
2795 * @param string $action
2796 * @return bool
2798 public function isAllowed( $action = '' ) {
2799 if ( $action === '' ) {
2800 return true; // In the spirit of DWIM
2802 // Patrolling may not be enabled
2803 if ( $action === 'patrol' || $action === 'autopatrol' ) {
2804 global $wgUseRCPatrol, $wgUseNPPatrol;
2805 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
2806 return false;
2809 // Use strict parameter to avoid matching numeric 0 accidentally inserted
2810 // by misconfiguration: 0 == 'foo'
2811 return in_array( $action, $this->getRights(), true );
2815 * Check whether to enable recent changes patrol features for this user
2816 * @return boolean: True or false
2818 public function useRCPatrol() {
2819 global $wgUseRCPatrol;
2820 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
2824 * Check whether to enable new pages patrol features for this user
2825 * @return bool True or false
2827 public function useNPPatrol() {
2828 global $wgUseRCPatrol, $wgUseNPPatrol;
2829 return (
2830 ( $wgUseRCPatrol || $wgUseNPPatrol )
2831 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
2836 * Get the WebRequest object to use with this object
2838 * @return WebRequest
2840 public function getRequest() {
2841 if ( $this->mRequest ) {
2842 return $this->mRequest;
2843 } else {
2844 global $wgRequest;
2845 return $wgRequest;
2850 * Get the current skin, loading it if required
2851 * @return Skin The current skin
2852 * @todo FIXME: Need to check the old failback system [AV]
2853 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
2855 public function getSkin() {
2856 wfDeprecated( __METHOD__, '1.18' );
2857 return RequestContext::getMain()->getSkin();
2861 * Get a WatchedItem for this user and $title.
2863 * @param $title Title
2864 * @return WatchedItem
2866 public function getWatchedItem( $title ) {
2867 $key = $title->getNamespace() . ':' . $title->getDBkey();
2869 if ( isset( $this->mWatchedItems[$key] ) ) {
2870 return $this->mWatchedItems[$key];
2873 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
2874 $this->mWatchedItems = array();
2877 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title );
2878 return $this->mWatchedItems[$key];
2882 * Check the watched status of an article.
2883 * @param $title Title of the article to look at
2884 * @return bool
2886 public function isWatched( $title ) {
2887 return $this->getWatchedItem( $title )->isWatched();
2891 * Watch an article.
2892 * @param $title Title of the article to look at
2894 public function addWatch( $title ) {
2895 $this->getWatchedItem( $title )->addWatch();
2896 $this->invalidateCache();
2900 * Stop watching an article.
2901 * @param $title Title of the article to look at
2903 public function removeWatch( $title ) {
2904 $this->getWatchedItem( $title )->removeWatch();
2905 $this->invalidateCache();
2909 * Clear the user's notification timestamp for the given title.
2910 * If e-notif e-mails are on, they will receive notification mails on
2911 * the next change of the page if it's watched etc.
2912 * @param $title Title of the article to look at
2914 public function clearNotification( &$title ) {
2915 global $wgUseEnotif, $wgShowUpdatedMarker;
2917 // Do nothing if the database is locked to writes
2918 if ( wfReadOnly() ) {
2919 return;
2922 if ( $title->getNamespace() == NS_USER_TALK &&
2923 $title->getText() == $this->getName() ) {
2924 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) ) {
2925 return;
2927 $this->setNewtalk( false );
2930 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2931 return;
2934 if ( $this->isAnon() ) {
2935 // Nothing else to do...
2936 return;
2939 // Only update the timestamp if the page is being watched.
2940 // The query to find out if it is watched is cached both in memcached and per-invocation,
2941 // and when it does have to be executed, it can be on a slave
2942 // If this is the user's newtalk page, we always update the timestamp
2943 $force = '';
2944 if ( $title->getNamespace() == NS_USER_TALK &&
2945 $title->getText() == $this->getName() )
2947 $force = 'force';
2950 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force );
2954 * Resets all of the given user's page-change notification timestamps.
2955 * If e-notif e-mails are on, they will receive notification mails on
2956 * the next change of any watched page.
2958 public function clearAllNotifications() {
2959 if ( wfReadOnly() ) {
2960 return;
2963 global $wgUseEnotif, $wgShowUpdatedMarker;
2964 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2965 $this->setNewtalk( false );
2966 return;
2968 $id = $this->getId();
2969 if ( $id != 0 ) {
2970 $dbw = wfGetDB( DB_MASTER );
2971 $dbw->update( 'watchlist',
2972 array( /* SET */
2973 'wl_notificationtimestamp' => null
2974 ), array( /* WHERE */
2975 'wl_user' => $id
2976 ), __METHOD__
2978 # We also need to clear here the "you have new message" notification for the own user_talk page
2979 # This is cleared one page view later in Article::viewUpdates();
2984 * Set this user's options from an encoded string
2985 * @param string $str Encoded options to import
2987 * @deprecated in 1.19 due to removal of user_options from the user table
2989 private function decodeOptions( $str ) {
2990 wfDeprecated( __METHOD__, '1.19' );
2991 if ( !$str ) {
2992 return;
2995 $this->mOptionsLoaded = true;
2996 $this->mOptionOverrides = array();
2998 // If an option is not set in $str, use the default value
2999 $this->mOptions = self::getDefaultOptions();
3001 $a = explode( "\n", $str );
3002 foreach ( $a as $s ) {
3003 $m = array();
3004 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
3005 $this->mOptions[$m[1]] = $m[2];
3006 $this->mOptionOverrides[$m[1]] = $m[2];
3012 * Set a cookie on the user's client. Wrapper for
3013 * WebResponse::setCookie
3014 * @param string $name Name of the cookie to set
3015 * @param string $value Value to set
3016 * @param int $exp Expiration time, as a UNIX time value;
3017 * if 0 or not specified, use the default $wgCookieExpiration
3018 * @param bool $secure
3019 * true: Force setting the secure attribute when setting the cookie
3020 * false: Force NOT setting the secure attribute when setting the cookie
3021 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3023 protected function setCookie( $name, $value, $exp = 0, $secure = null ) {
3024 $this->getRequest()->response()->setcookie( $name, $value, $exp, null, null, $secure );
3028 * Clear a cookie on the user's client
3029 * @param string $name Name of the cookie to clear
3031 protected function clearCookie( $name ) {
3032 $this->setCookie( $name, '', time() - 86400 );
3036 * Set the default cookies for this session on the user's client.
3038 * @param $request WebRequest object to use; $wgRequest will be used if null
3039 * is passed.
3040 * @param bool $secure Whether to force secure/insecure cookies or use default
3042 public function setCookies( $request = null, $secure = null ) {
3043 if ( $request === null ) {
3044 $request = $this->getRequest();
3047 $this->load();
3048 if ( 0 == $this->mId ) {
3049 return;
3051 if ( !$this->mToken ) {
3052 // When token is empty or NULL generate a new one and then save it to the database
3053 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3054 // Simply by setting every cell in the user_token column to NULL and letting them be
3055 // regenerated as users log back into the wiki.
3056 $this->setToken();
3057 $this->saveSettings();
3059 $session = array(
3060 'wsUserID' => $this->mId,
3061 'wsToken' => $this->mToken,
3062 'wsUserName' => $this->getName()
3064 $cookies = array(
3065 'UserID' => $this->mId,
3066 'UserName' => $this->getName(),
3068 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
3069 $cookies['Token'] = $this->mToken;
3070 } else {
3071 $cookies['Token'] = false;
3074 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3076 foreach ( $session as $name => $value ) {
3077 $request->setSessionData( $name, $value );
3079 foreach ( $cookies as $name => $value ) {
3080 if ( $value === false ) {
3081 $this->clearCookie( $name );
3082 } else {
3083 $this->setCookie( $name, $value, 0, $secure );
3088 * If wpStickHTTPS was selected, also set an insecure cookie that
3089 * will cause the site to redirect the user to HTTPS, if they access
3090 * it over HTTP. Bug 29898.
3092 if ( $request->getCheck( 'wpStickHTTPS' ) ) {
3093 $this->setCookie( 'forceHTTPS', 'true', time() + 2592000, false ); //30 days
3098 * Log this user out.
3100 public function logout() {
3101 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3102 $this->doLogout();
3107 * Clear the user's cookies and session, and reset the instance cache.
3108 * @see logout()
3110 public function doLogout() {
3111 $this->clearInstanceCache( 'defaults' );
3113 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3115 $this->clearCookie( 'UserID' );
3116 $this->clearCookie( 'Token' );
3117 $this->clearCookie( 'forceHTTPS' );
3119 // Remember when user logged out, to prevent seeing cached pages
3120 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
3124 * Save this user's settings into the database.
3125 * @todo Only rarely do all these fields need to be set!
3127 public function saveSettings() {
3128 global $wgAuth;
3130 $this->load();
3131 if ( wfReadOnly() ) {
3132 return;
3134 if ( 0 == $this->mId ) {
3135 return;
3138 $this->mTouched = self::newTouchedTimestamp();
3139 if ( !$wgAuth->allowSetLocalPassword() ) {
3140 $this->mPassword = '';
3143 $dbw = wfGetDB( DB_MASTER );
3144 $dbw->update( 'user',
3145 array( /* SET */
3146 'user_name' => $this->mName,
3147 'user_password' => $this->mPassword,
3148 'user_newpassword' => $this->mNewpassword,
3149 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3150 'user_real_name' => $this->mRealName,
3151 'user_email' => $this->mEmail,
3152 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3153 'user_touched' => $dbw->timestamp( $this->mTouched ),
3154 'user_token' => strval( $this->mToken ),
3155 'user_email_token' => $this->mEmailToken,
3156 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3157 ), array( /* WHERE */
3158 'user_id' => $this->mId
3159 ), __METHOD__
3162 $this->saveOptions();
3164 wfRunHooks( 'UserSaveSettings', array( $this ) );
3165 $this->clearSharedCache();
3166 $this->getUserPage()->invalidateCache();
3170 * If only this user's username is known, and it exists, return the user ID.
3171 * @return int
3173 public function idForName() {
3174 $s = trim( $this->getName() );
3175 if ( $s === '' ) {
3176 return 0;
3179 $dbr = wfGetDB( DB_SLAVE );
3180 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
3181 if ( $id === false ) {
3182 $id = 0;
3184 return $id;
3188 * Add a user to the database, return the user object
3190 * @param string $name Username to add
3191 * @param array $params of Strings Non-default parameters to save to the database as user_* fields:
3192 * - password The user's password hash. Password logins will be disabled if this is omitted.
3193 * - newpassword Hash for a temporary password that has been mailed to the user
3194 * - email The user's email address
3195 * - email_authenticated The email authentication timestamp
3196 * - real_name The user's real name
3197 * - options An associative array of non-default options
3198 * - token Random authentication token. Do not set.
3199 * - registration Registration timestamp. Do not set.
3201 * @return User object, or null if the username already exists
3203 public static function createNew( $name, $params = array() ) {
3204 $user = new User;
3205 $user->load();
3206 $user->setToken(); // init token
3207 if ( isset( $params['options'] ) ) {
3208 $user->mOptions = $params['options'] + (array)$user->mOptions;
3209 unset( $params['options'] );
3211 $dbw = wfGetDB( DB_MASTER );
3212 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3214 $fields = array(
3215 'user_id' => $seqVal,
3216 'user_name' => $name,
3217 'user_password' => $user->mPassword,
3218 'user_newpassword' => $user->mNewpassword,
3219 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3220 'user_email' => $user->mEmail,
3221 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3222 'user_real_name' => $user->mRealName,
3223 'user_token' => strval( $user->mToken ),
3224 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3225 'user_editcount' => 0,
3226 'user_touched' => $dbw->timestamp( self::newTouchedTimestamp() ),
3228 foreach ( $params as $name => $value ) {
3229 $fields["user_$name"] = $value;
3231 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3232 if ( $dbw->affectedRows() ) {
3233 $newUser = User::newFromId( $dbw->insertId() );
3234 } else {
3235 $newUser = null;
3237 return $newUser;
3241 * Add this existing user object to the database. If the user already
3242 * exists, a fatal status object is returned, and the user object is
3243 * initialised with the data from the database.
3245 * Previously, this function generated a DB error due to a key conflict
3246 * if the user already existed. Many extension callers use this function
3247 * in code along the lines of:
3249 * $user = User::newFromName( $name );
3250 * if ( !$user->isLoggedIn() ) {
3251 * $user->addToDatabase();
3253 * // do something with $user...
3255 * However, this was vulnerable to a race condition (bug 16020). By
3256 * initialising the user object if the user exists, we aim to support this
3257 * calling sequence as far as possible.
3259 * Note that if the user exists, this function will acquire a write lock,
3260 * so it is still advisable to make the call conditional on isLoggedIn(),
3261 * and to commit the transaction after calling.
3263 * @throws MWException
3264 * @return Status
3266 public function addToDatabase() {
3267 $this->load();
3268 if ( !$this->mToken ) {
3269 $this->setToken(); // init token
3272 $this->mTouched = self::newTouchedTimestamp();
3274 $dbw = wfGetDB( DB_MASTER );
3275 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3276 $dbw->insert( 'user',
3277 array(
3278 'user_id' => $seqVal,
3279 'user_name' => $this->mName,
3280 'user_password' => $this->mPassword,
3281 'user_newpassword' => $this->mNewpassword,
3282 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3283 'user_email' => $this->mEmail,
3284 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3285 'user_real_name' => $this->mRealName,
3286 'user_token' => strval( $this->mToken ),
3287 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3288 'user_editcount' => 0,
3289 'user_touched' => $dbw->timestamp( $this->mTouched ),
3290 ), __METHOD__,
3291 array( 'IGNORE' )
3293 if ( !$dbw->affectedRows() ) {
3294 $this->mId = $dbw->selectField( 'user', 'user_id',
3295 array( 'user_name' => $this->mName ), __METHOD__ );
3296 $loaded = false;
3297 if ( $this->mId ) {
3298 if ( $this->loadFromDatabase() ) {
3299 $loaded = true;
3302 if ( !$loaded ) {
3303 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3304 "to insert user '{$this->mName}' row, but it was not present in select!" );
3306 return Status::newFatal( 'userexists' );
3308 $this->mId = $dbw->insertId();
3310 // Clear instance cache other than user table data, which is already accurate
3311 $this->clearInstanceCache();
3313 $this->saveOptions();
3314 return Status::newGood();
3318 * If this user is logged-in and blocked,
3319 * block any IP address they've successfully logged in from.
3320 * @return bool A block was spread
3322 public function spreadAnyEditBlock() {
3323 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3324 return $this->spreadBlock();
3326 return false;
3330 * If this (non-anonymous) user is blocked,
3331 * block the IP address they've successfully logged in from.
3332 * @return bool A block was spread
3334 protected function spreadBlock() {
3335 wfDebug( __METHOD__ . "()\n" );
3336 $this->load();
3337 if ( $this->mId == 0 ) {
3338 return false;
3341 $userblock = Block::newFromTarget( $this->getName() );
3342 if ( !$userblock ) {
3343 return false;
3346 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3350 * Generate a string which will be different for any combination of
3351 * user options which would produce different parser output.
3352 * This will be used as part of the hash key for the parser cache,
3353 * so users with the same options can share the same cached data
3354 * safely.
3356 * Extensions which require it should install 'PageRenderingHash' hook,
3357 * which will give them a chance to modify this key based on their own
3358 * settings.
3360 * @deprecated since 1.17 use the ParserOptions object to get the relevant options
3361 * @return string Page rendering hash
3363 public function getPageRenderingHash() {
3364 wfDeprecated( __METHOD__, '1.17' );
3366 global $wgRenderHashAppend, $wgLang, $wgContLang;
3367 if ( $this->mHash ) {
3368 return $this->mHash;
3371 // stubthreshold is only included below for completeness,
3372 // since it disables the parser cache, its value will always
3373 // be 0 when this function is called by parsercache.
3375 $confstr = $this->getOption( 'math' );
3376 $confstr .= '!' . $this->getStubThreshold();
3377 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ? '1' : '' );
3378 $confstr .= '!' . $wgLang->getCode();
3379 $confstr .= '!' . $this->getOption( 'thumbsize' );
3380 // add in language specific options, if any
3381 $extra = $wgContLang->getExtraHashOptions();
3382 $confstr .= $extra;
3384 // Since the skin could be overloading link(), it should be
3385 // included here but in practice, none of our skins do that.
3387 $confstr .= $wgRenderHashAppend;
3389 // Give a chance for extensions to modify the hash, if they have
3390 // extra options or other effects on the parser cache.
3391 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
3393 // Make it a valid memcached key fragment
3394 $confstr = str_replace( ' ', '_', $confstr );
3395 $this->mHash = $confstr;
3396 return $confstr;
3400 * Get whether the user is explicitly blocked from account creation.
3401 * @return bool|Block
3403 public function isBlockedFromCreateAccount() {
3404 $this->getBlockedStatus();
3405 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3406 return $this->mBlock;
3409 # bug 13611: if the IP address the user is trying to create an account from is
3410 # blocked with createaccount disabled, prevent new account creation there even
3411 # when the user is logged in
3412 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3413 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3415 return $this->mBlockedFromCreateAccount instanceof Block && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3416 ? $this->mBlockedFromCreateAccount
3417 : false;
3421 * Get whether the user is blocked from using Special:Emailuser.
3422 * @return bool
3424 public function isBlockedFromEmailuser() {
3425 $this->getBlockedStatus();
3426 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3430 * Get whether the user is allowed to create an account.
3431 * @return bool
3433 function isAllowedToCreateAccount() {
3434 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3438 * Get this user's personal page title.
3440 * @return Title: User's personal page title
3442 public function getUserPage() {
3443 return Title::makeTitle( NS_USER, $this->getName() );
3447 * Get this user's talk page title.
3449 * @return Title: User's talk page title
3451 public function getTalkPage() {
3452 $title = $this->getUserPage();
3453 return $title->getTalkPage();
3457 * Determine whether the user is a newbie. Newbies are either
3458 * anonymous IPs, or the most recently created accounts.
3459 * @return bool
3461 public function isNewbie() {
3462 return !$this->isAllowed( 'autoconfirmed' );
3466 * Check to see if the given clear-text password is one of the accepted passwords
3467 * @param string $password user password.
3468 * @return boolean: True if the given password is correct, otherwise False.
3470 public function checkPassword( $password ) {
3471 global $wgAuth, $wgLegacyEncoding;
3472 $this->load();
3474 // Even though we stop people from creating passwords that
3475 // are shorter than this, doesn't mean people wont be able
3476 // to. Certain authentication plugins do NOT want to save
3477 // domain passwords in a mysql database, so we should
3478 // check this (in case $wgAuth->strict() is false).
3479 if ( !$this->isValidPassword( $password ) ) {
3480 return false;
3483 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3484 return true;
3485 } elseif ( $wgAuth->strict() ) {
3486 // Auth plugin doesn't allow local authentication
3487 return false;
3488 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3489 // Auth plugin doesn't allow local authentication for this user name
3490 return false;
3492 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
3493 return true;
3494 } elseif ( $wgLegacyEncoding ) {
3495 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3496 // Check for this with iconv
3497 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3498 if ( $cp1252Password != $password &&
3499 self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) )
3501 return true;
3504 return false;
3508 * Check if the given clear-text password matches the temporary password
3509 * sent by e-mail for password reset operations.
3511 * @param $plaintext string
3513 * @return boolean: True if matches, false otherwise
3515 public function checkTemporaryPassword( $plaintext ) {
3516 global $wgNewPasswordExpiry;
3518 $this->load();
3519 if ( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
3520 if ( is_null( $this->mNewpassTime ) ) {
3521 return true;
3523 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
3524 return ( time() < $expiry );
3525 } else {
3526 return false;
3531 * Alias for getEditToken.
3532 * @deprecated since 1.19, use getEditToken instead.
3534 * @param string|array $salt of Strings Optional function-specific data for hashing
3535 * @param $request WebRequest object to use or null to use $wgRequest
3536 * @return string The new edit token
3538 public function editToken( $salt = '', $request = null ) {
3539 wfDeprecated( __METHOD__, '1.19' );
3540 return $this->getEditToken( $salt, $request );
3544 * Initialize (if necessary) and return a session token value
3545 * which can be used in edit forms to show that the user's
3546 * login credentials aren't being hijacked with a foreign form
3547 * submission.
3549 * @since 1.19
3551 * @param string|array $salt of Strings Optional function-specific data for hashing
3552 * @param $request WebRequest object to use or null to use $wgRequest
3553 * @return string The new edit token
3555 public function getEditToken( $salt = '', $request = null ) {
3556 if ( $request == null ) {
3557 $request = $this->getRequest();
3560 if ( $this->isAnon() ) {
3561 return EDIT_TOKEN_SUFFIX;
3562 } else {
3563 $token = $request->getSessionData( 'wsEditToken' );
3564 if ( $token === null ) {
3565 $token = MWCryptRand::generateHex( 32 );
3566 $request->setSessionData( 'wsEditToken', $token );
3568 if ( is_array( $salt ) ) {
3569 $salt = implode( '|', $salt );
3571 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
3576 * Generate a looking random token for various uses.
3578 * @return string The new random token
3579 * @deprecated since 1.20: Use MWCryptRand for secure purposes or wfRandomString for pseudo-randomness
3581 public static function generateToken() {
3582 return MWCryptRand::generateHex( 32 );
3586 * Check given value against the token value stored in the session.
3587 * A match should confirm that the form was submitted from the
3588 * user's own login session, not a form submission from a third-party
3589 * site.
3591 * @param string $val Input value to compare
3592 * @param string $salt Optional function-specific data for hashing
3593 * @param WebRequest $request Object to use or null to use $wgRequest
3594 * @return boolean: Whether the token matches
3596 public function matchEditToken( $val, $salt = '', $request = null ) {
3597 $sessionToken = $this->getEditToken( $salt, $request );
3598 if ( $val != $sessionToken ) {
3599 wfDebug( "User::matchEditToken: broken session data\n" );
3601 return $val == $sessionToken;
3605 * Check given value against the token value stored in the session,
3606 * ignoring the suffix.
3608 * @param string $val Input value to compare
3609 * @param string $salt Optional function-specific data for hashing
3610 * @param WebRequest $request object to use or null to use $wgRequest
3611 * @return boolean: Whether the token matches
3613 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3614 $sessionToken = $this->getEditToken( $salt, $request );
3615 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3619 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3620 * mail to the user's given address.
3622 * @param string $type message to send, either "created", "changed" or "set"
3623 * @return Status object
3625 public function sendConfirmationMail( $type = 'created' ) {
3626 global $wgLang;
3627 $expiration = null; // gets passed-by-ref and defined in next line.
3628 $token = $this->confirmationToken( $expiration );
3629 $url = $this->confirmationTokenUrl( $token );
3630 $invalidateURL = $this->invalidationTokenUrl( $token );
3631 $this->saveSettings();
3633 if ( $type == 'created' || $type === false ) {
3634 $message = 'confirmemail_body';
3635 } elseif ( $type === true ) {
3636 $message = 'confirmemail_body_changed';
3637 } else {
3638 $message = 'confirmemail_body_' . $type;
3641 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3642 wfMessage( $message,
3643 $this->getRequest()->getIP(),
3644 $this->getName(),
3645 $url,
3646 $wgLang->timeanddate( $expiration, false ),
3647 $invalidateURL,
3648 $wgLang->date( $expiration, false ),
3649 $wgLang->time( $expiration, false ) )->text() );
3653 * Send an e-mail to this user's account. Does not check for
3654 * confirmed status or validity.
3656 * @param string $subject Message subject
3657 * @param string $body Message body
3658 * @param string $from Optional From address; if unspecified, default $wgPasswordSender will be used
3659 * @param string $replyto Reply-To address
3660 * @return Status
3662 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3663 if ( is_null( $from ) ) {
3664 global $wgPasswordSender, $wgPasswordSenderName;
3665 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
3666 } else {
3667 $sender = new MailAddress( $from );
3670 $to = new MailAddress( $this );
3671 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
3675 * Generate, store, and return a new e-mail confirmation code.
3676 * A hash (unsalted, since it's used as a key) is stored.
3678 * @note Call saveSettings() after calling this function to commit
3679 * this change to the database.
3681 * @param &$expiration \mixed Accepts the expiration time
3682 * @return string New token
3684 protected function confirmationToken( &$expiration ) {
3685 global $wgUserEmailConfirmationTokenExpiry;
3686 $now = time();
3687 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
3688 $expiration = wfTimestamp( TS_MW, $expires );
3689 $this->load();
3690 $token = MWCryptRand::generateHex( 32 );
3691 $hash = md5( $token );
3692 $this->mEmailToken = $hash;
3693 $this->mEmailTokenExpires = $expiration;
3694 return $token;
3698 * Return a URL the user can use to confirm their email address.
3699 * @param string $token Accepts the email confirmation token
3700 * @return string New token URL
3702 protected function confirmationTokenUrl( $token ) {
3703 return $this->getTokenUrl( 'ConfirmEmail', $token );
3707 * Return a URL the user can use to invalidate their email address.
3708 * @param string $token Accepts the email confirmation token
3709 * @return string New token URL
3711 protected function invalidationTokenUrl( $token ) {
3712 return $this->getTokenUrl( 'InvalidateEmail', $token );
3716 * Internal function to format the e-mail validation/invalidation URLs.
3717 * This uses a quickie hack to use the
3718 * hardcoded English names of the Special: pages, for ASCII safety.
3720 * @note Since these URLs get dropped directly into emails, using the
3721 * short English names avoids insanely long URL-encoded links, which
3722 * also sometimes can get corrupted in some browsers/mailers
3723 * (bug 6957 with Gmail and Internet Explorer).
3725 * @param string $page Special page
3726 * @param string $token Token
3727 * @return string Formatted URL
3729 protected function getTokenUrl( $page, $token ) {
3730 // Hack to bypass localization of 'Special:'
3731 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
3732 return $title->getCanonicalURL();
3736 * Mark the e-mail address confirmed.
3738 * @note Call saveSettings() after calling this function to commit the change.
3740 * @return bool
3742 public function confirmEmail() {
3743 // Check if it's already confirmed, so we don't touch the database
3744 // and fire the ConfirmEmailComplete hook on redundant confirmations.
3745 if ( !$this->isEmailConfirmed() ) {
3746 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3747 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3749 return true;
3753 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3754 * address if it was already confirmed.
3756 * @note Call saveSettings() after calling this function to commit the change.
3757 * @return bool Returns true
3759 function invalidateEmail() {
3760 $this->load();
3761 $this->mEmailToken = null;
3762 $this->mEmailTokenExpires = null;
3763 $this->setEmailAuthenticationTimestamp( null );
3764 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3765 return true;
3769 * Set the e-mail authentication timestamp.
3770 * @param string $timestamp TS_MW timestamp
3772 function setEmailAuthenticationTimestamp( $timestamp ) {
3773 $this->load();
3774 $this->mEmailAuthenticated = $timestamp;
3775 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
3779 * Is this user allowed to send e-mails within limits of current
3780 * site configuration?
3781 * @return bool
3783 public function canSendEmail() {
3784 global $wgEnableEmail, $wgEnableUserEmail;
3785 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
3786 return false;
3788 $canSend = $this->isEmailConfirmed();
3789 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3790 return $canSend;
3794 * Is this user allowed to receive e-mails within limits of current
3795 * site configuration?
3796 * @return bool
3798 public function canReceiveEmail() {
3799 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3803 * Is this user's e-mail address valid-looking and confirmed within
3804 * limits of the current site configuration?
3806 * @note If $wgEmailAuthentication is on, this may require the user to have
3807 * confirmed their address by returning a code or using a password
3808 * sent to the address from the wiki.
3810 * @return bool
3812 public function isEmailConfirmed() {
3813 global $wgEmailAuthentication;
3814 $this->load();
3815 $confirmed = true;
3816 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3817 if ( $this->isAnon() ) {
3818 return false;
3820 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
3821 return false;
3823 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
3824 return false;
3826 return true;
3827 } else {
3828 return $confirmed;
3833 * Check whether there is an outstanding request for e-mail confirmation.
3834 * @return bool
3836 public function isEmailConfirmationPending() {
3837 global $wgEmailAuthentication;
3838 return $wgEmailAuthentication &&
3839 !$this->isEmailConfirmed() &&
3840 $this->mEmailToken &&
3841 $this->mEmailTokenExpires > wfTimestamp();
3845 * Get the timestamp of account creation.
3847 * @return string|bool|null Timestamp of account creation, false for
3848 * non-existent/anonymous user accounts, or null if existing account
3849 * but information is not in database.
3851 public function getRegistration() {
3852 if ( $this->isAnon() ) {
3853 return false;
3855 $this->load();
3856 return $this->mRegistration;
3860 * Get the timestamp of the first edit
3862 * @return string|bool Timestamp of first edit, or false for
3863 * non-existent/anonymous user accounts.
3865 public function getFirstEditTimestamp() {
3866 if ( $this->getId() == 0 ) {
3867 return false; // anons
3869 $dbr = wfGetDB( DB_SLAVE );
3870 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3871 array( 'rev_user' => $this->getId() ),
3872 __METHOD__,
3873 array( 'ORDER BY' => 'rev_timestamp ASC' )
3875 if ( !$time ) {
3876 return false; // no edits
3878 return wfTimestamp( TS_MW, $time );
3882 * Get the permissions associated with a given list of groups
3884 * @param array $groups of Strings List of internal group names
3885 * @return Array of Strings List of permission key names for given groups combined
3887 public static function getGroupPermissions( $groups ) {
3888 global $wgGroupPermissions, $wgRevokePermissions;
3889 $rights = array();
3890 // grant every granted permission first
3891 foreach ( $groups as $group ) {
3892 if ( isset( $wgGroupPermissions[$group] ) ) {
3893 $rights = array_merge( $rights,
3894 // array_filter removes empty items
3895 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3898 // now revoke the revoked permissions
3899 foreach ( $groups as $group ) {
3900 if ( isset( $wgRevokePermissions[$group] ) ) {
3901 $rights = array_diff( $rights,
3902 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3905 return array_unique( $rights );
3909 * Get all the groups who have a given permission
3911 * @param string $role Role to check
3912 * @return Array of Strings List of internal group names with the given permission
3914 public static function getGroupsWithPermission( $role ) {
3915 global $wgGroupPermissions;
3916 $allowedGroups = array();
3917 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
3918 if ( self::groupHasPermission( $group, $role ) ) {
3919 $allowedGroups[] = $group;
3922 return $allowedGroups;
3926 * Check, if the given group has the given permission
3928 * @since 1.21
3929 * @param string $group Group to check
3930 * @param string $role Role to check
3931 * @return bool
3933 public static function groupHasPermission( $group, $role ) {
3934 global $wgGroupPermissions, $wgRevokePermissions;
3935 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
3936 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
3940 * Get the localized descriptive name for a group, if it exists
3942 * @param string $group Internal group name
3943 * @return string Localized descriptive group name
3945 public static function getGroupName( $group ) {
3946 $msg = wfMessage( "group-$group" );
3947 return $msg->isBlank() ? $group : $msg->text();
3951 * Get the localized descriptive name for a member of a group, if it exists
3953 * @param string $group Internal group name
3954 * @param string $username Username for gender (since 1.19)
3955 * @return string Localized name for group member
3957 public static function getGroupMember( $group, $username = '#' ) {
3958 $msg = wfMessage( "group-$group-member", $username );
3959 return $msg->isBlank() ? $group : $msg->text();
3963 * Return the set of defined explicit groups.
3964 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3965 * are not included, as they are defined automatically, not in the database.
3966 * @return Array of internal group names
3968 public static function getAllGroups() {
3969 global $wgGroupPermissions, $wgRevokePermissions;
3970 return array_diff(
3971 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3972 self::getImplicitGroups()
3977 * Get a list of all available permissions.
3978 * @return Array of permission names
3980 public static function getAllRights() {
3981 if ( self::$mAllRights === false ) {
3982 global $wgAvailableRights;
3983 if ( count( $wgAvailableRights ) ) {
3984 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
3985 } else {
3986 self::$mAllRights = self::$mCoreRights;
3988 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
3990 return self::$mAllRights;
3994 * Get a list of implicit groups
3995 * @return Array of Strings Array of internal group names
3997 public static function getImplicitGroups() {
3998 global $wgImplicitGroups;
3999 $groups = $wgImplicitGroups;
4000 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
4001 return $groups;
4005 * Get the title of a page describing a particular group
4007 * @param string $group Internal group name
4008 * @return Title|bool Title of the page if it exists, false otherwise
4010 public static function getGroupPage( $group ) {
4011 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4012 if ( $msg->exists() ) {
4013 $title = Title::newFromText( $msg->text() );
4014 if ( is_object( $title ) ) {
4015 return $title;
4018 return false;
4022 * Create a link to the group in HTML, if available;
4023 * else return the group name.
4025 * @param string $group Internal name of the group
4026 * @param string $text The text of the link
4027 * @return string HTML link to the group
4029 public static function makeGroupLinkHTML( $group, $text = '' ) {
4030 if ( $text == '' ) {
4031 $text = self::getGroupName( $group );
4033 $title = self::getGroupPage( $group );
4034 if ( $title ) {
4035 return Linker::link( $title, htmlspecialchars( $text ) );
4036 } else {
4037 return $text;
4042 * Create a link to the group in Wikitext, if available;
4043 * else return the group name.
4045 * @param string $group Internal name of the group
4046 * @param string $text The text of the link
4047 * @return string Wikilink to the group
4049 public static function makeGroupLinkWiki( $group, $text = '' ) {
4050 if ( $text == '' ) {
4051 $text = self::getGroupName( $group );
4053 $title = self::getGroupPage( $group );
4054 if ( $title ) {
4055 $page = $title->getPrefixedText();
4056 return "[[$page|$text]]";
4057 } else {
4058 return $text;
4063 * Returns an array of the groups that a particular group can add/remove.
4065 * @param string $group the group to check for whether it can add/remove
4066 * @return Array array( 'add' => array( addablegroups ),
4067 * 'remove' => array( removablegroups ),
4068 * 'add-self' => array( addablegroups to self),
4069 * 'remove-self' => array( removable groups from self) )
4071 public static function changeableByGroup( $group ) {
4072 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4074 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
4075 if ( empty( $wgAddGroups[$group] ) ) {
4076 // Don't add anything to $groups
4077 } elseif ( $wgAddGroups[$group] === true ) {
4078 // You get everything
4079 $groups['add'] = self::getAllGroups();
4080 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4081 $groups['add'] = $wgAddGroups[$group];
4084 // Same thing for remove
4085 if ( empty( $wgRemoveGroups[$group] ) ) {
4086 } elseif ( $wgRemoveGroups[$group] === true ) {
4087 $groups['remove'] = self::getAllGroups();
4088 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4089 $groups['remove'] = $wgRemoveGroups[$group];
4092 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4093 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4094 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4095 if ( is_int( $key ) ) {
4096 $wgGroupsAddToSelf['user'][] = $value;
4101 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4102 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4103 if ( is_int( $key ) ) {
4104 $wgGroupsRemoveFromSelf['user'][] = $value;
4109 // Now figure out what groups the user can add to him/herself
4110 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4111 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4112 // No idea WHY this would be used, but it's there
4113 $groups['add-self'] = User::getAllGroups();
4114 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4115 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4118 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4119 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4120 $groups['remove-self'] = User::getAllGroups();
4121 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4122 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4125 return $groups;
4129 * Returns an array of groups that this user can add and remove
4130 * @return Array array( 'add' => array( addablegroups ),
4131 * 'remove' => array( removablegroups ),
4132 * 'add-self' => array( addablegroups to self),
4133 * 'remove-self' => array( removable groups from self) )
4135 public function changeableGroups() {
4136 if ( $this->isAllowed( 'userrights' ) ) {
4137 // This group gives the right to modify everything (reverse-
4138 // compatibility with old "userrights lets you change
4139 // everything")
4140 // Using array_merge to make the groups reindexed
4141 $all = array_merge( User::getAllGroups() );
4142 return array(
4143 'add' => $all,
4144 'remove' => $all,
4145 'add-self' => array(),
4146 'remove-self' => array()
4150 // Okay, it's not so simple, we will have to go through the arrays
4151 $groups = array(
4152 'add' => array(),
4153 'remove' => array(),
4154 'add-self' => array(),
4155 'remove-self' => array()
4157 $addergroups = $this->getEffectiveGroups();
4159 foreach ( $addergroups as $addergroup ) {
4160 $groups = array_merge_recursive(
4161 $groups, $this->changeableByGroup( $addergroup )
4163 $groups['add'] = array_unique( $groups['add'] );
4164 $groups['remove'] = array_unique( $groups['remove'] );
4165 $groups['add-self'] = array_unique( $groups['add-self'] );
4166 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4168 return $groups;
4172 * Increment the user's edit-count field.
4173 * Will have no effect for anonymous users.
4175 public function incEditCount() {
4176 if ( !$this->isAnon() ) {
4177 $dbw = wfGetDB( DB_MASTER );
4178 $dbw->update(
4179 'user',
4180 array( 'user_editcount=user_editcount+1' ),
4181 array( 'user_id' => $this->getId() ),
4182 __METHOD__
4185 // Lazy initialization check...
4186 if ( $dbw->affectedRows() == 0 ) {
4187 // Now here's a goddamn hack...
4188 $dbr = wfGetDB( DB_SLAVE );
4189 if ( $dbr !== $dbw ) {
4190 // If we actually have a slave server, the count is
4191 // at least one behind because the current transaction
4192 // has not been committed and replicated.
4193 $this->initEditCount( 1 );
4194 } else {
4195 // But if DB_SLAVE is selecting the master, then the
4196 // count we just read includes the revision that was
4197 // just added in the working transaction.
4198 $this->initEditCount();
4202 // edit count in user cache too
4203 $this->invalidateCache();
4207 * Initialize user_editcount from data out of the revision table
4209 * @param $add Integer Edits to add to the count from the revision table
4210 * @return integer Number of edits
4212 protected function initEditCount( $add = 0 ) {
4213 // Pull from a slave to be less cruel to servers
4214 // Accuracy isn't the point anyway here
4215 $dbr = wfGetDB( DB_SLAVE );
4216 $count = (int) $dbr->selectField(
4217 'revision',
4218 'COUNT(rev_user)',
4219 array( 'rev_user' => $this->getId() ),
4220 __METHOD__
4222 $count = $count + $add;
4224 $dbw = wfGetDB( DB_MASTER );
4225 $dbw->update(
4226 'user',
4227 array( 'user_editcount' => $count ),
4228 array( 'user_id' => $this->getId() ),
4229 __METHOD__
4232 return $count;
4236 * Get the description of a given right
4238 * @param string $right Right to query
4239 * @return string Localized description of the right
4241 public static function getRightDescription( $right ) {
4242 $key = "right-$right";
4243 $msg = wfMessage( $key );
4244 return $msg->isBlank() ? $right : $msg->text();
4248 * Make an old-style password hash
4250 * @param string $password Plain-text password
4251 * @param string $userId User ID
4252 * @return string Password hash
4254 public static function oldCrypt( $password, $userId ) {
4255 global $wgPasswordSalt;
4256 if ( $wgPasswordSalt ) {
4257 return md5( $userId . '-' . md5( $password ) );
4258 } else {
4259 return md5( $password );
4264 * Make a new-style password hash
4266 * @param string $password Plain-text password
4267 * @param bool|string $salt Optional salt, may be random or the user ID.
4268 * If unspecified or false, will generate one automatically
4269 * @return string Password hash
4271 public static function crypt( $password, $salt = false ) {
4272 global $wgPasswordSalt;
4274 $hash = '';
4275 if ( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4276 return $hash;
4279 if ( $wgPasswordSalt ) {
4280 if ( $salt === false ) {
4281 $salt = MWCryptRand::generateHex( 8 );
4283 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4284 } else {
4285 return ':A:' . md5( $password );
4290 * Compare a password hash with a plain-text password. Requires the user
4291 * ID if there's a chance that the hash is an old-style hash.
4293 * @param string $hash Password hash
4294 * @param string $password Plain-text password to compare
4295 * @param string|bool $userId User ID for old-style password salt
4297 * @return boolean
4299 public static function comparePasswords( $hash, $password, $userId = false ) {
4300 $type = substr( $hash, 0, 3 );
4302 $result = false;
4303 if ( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4304 return $result;
4307 if ( $type == ':A:' ) {
4308 // Unsalted
4309 return md5( $password ) === substr( $hash, 3 );
4310 } elseif ( $type == ':B:' ) {
4311 // Salted
4312 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4313 return md5( $salt . '-' . md5( $password ) ) === $realHash;
4314 } else {
4315 // Old-style
4316 return self::oldCrypt( $password, $userId ) === $hash;
4321 * Add a newuser log entry for this user.
4322 * Before 1.19 the return value was always true.
4324 * @param string|bool $action account creation type.
4325 * - String, one of the following values:
4326 * - 'create' for an anonymous user creating an account for himself.
4327 * This will force the action's performer to be the created user itself,
4328 * no matter the value of $wgUser
4329 * - 'create2' for a logged in user creating an account for someone else
4330 * - 'byemail' when the created user will receive its password by e-mail
4331 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4332 * - Boolean means whether the account was created by e-mail (deprecated):
4333 * - true will be converted to 'byemail'
4334 * - false will be converted to 'create' if this object is the same as
4335 * $wgUser and to 'create2' otherwise
4337 * @param string $reason user supplied reason
4339 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4341 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4342 global $wgUser, $wgNewUserLog;
4343 if ( empty( $wgNewUserLog ) ) {
4344 return true; // disabled
4347 if ( $action === true ) {
4348 $action = 'byemail';
4349 } elseif ( $action === false ) {
4350 if ( $this->getName() == $wgUser->getName() ) {
4351 $action = 'create';
4352 } else {
4353 $action = 'create2';
4357 if ( $action === 'create' || $action === 'autocreate' ) {
4358 $performer = $this;
4359 } else {
4360 $performer = $wgUser;
4363 $logEntry = new ManualLogEntry( 'newusers', $action );
4364 $logEntry->setPerformer( $performer );
4365 $logEntry->setTarget( $this->getUserPage() );
4366 $logEntry->setComment( $reason );
4367 $logEntry->setParameters( array(
4368 '4::userid' => $this->getId(),
4369 ) );
4370 $logid = $logEntry->insert();
4372 if ( $action !== 'autocreate' ) {
4373 $logEntry->publish( $logid );
4376 return (int)$logid;
4380 * Add an autocreate newuser log entry for this user
4381 * Used by things like CentralAuth and perhaps other authplugins.
4382 * Consider calling addNewUserLogEntry() directly instead.
4384 * @return bool
4386 public function addNewUserLogEntryAutoCreate() {
4387 $this->addNewUserLogEntry( 'autocreate' );
4389 return true;
4393 * Load the user options either from cache, the database or an array
4395 * @param array $data Rows for the current user out of the user_properties table
4397 protected function loadOptions( $data = null ) {
4398 global $wgContLang;
4400 $this->load();
4402 if ( $this->mOptionsLoaded ) {
4403 return;
4406 $this->mOptions = self::getDefaultOptions();
4408 if ( !$this->getId() ) {
4409 // For unlogged-in users, load language/variant options from request.
4410 // There's no need to do it for logged-in users: they can set preferences,
4411 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4412 // so don't override user's choice (especially when the user chooses site default).
4413 $variant = $wgContLang->getDefaultVariant();
4414 $this->mOptions['variant'] = $variant;
4415 $this->mOptions['language'] = $variant;
4416 $this->mOptionsLoaded = true;
4417 return;
4420 // Maybe load from the object
4421 if ( !is_null( $this->mOptionOverrides ) ) {
4422 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4423 foreach ( $this->mOptionOverrides as $key => $value ) {
4424 $this->mOptions[$key] = $value;
4426 } else {
4427 if ( !is_array( $data ) ) {
4428 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4429 // Load from database
4430 $dbr = wfGetDB( DB_SLAVE );
4432 $res = $dbr->select(
4433 'user_properties',
4434 array( 'up_property', 'up_value' ),
4435 array( 'up_user' => $this->getId() ),
4436 __METHOD__
4439 $this->mOptionOverrides = array();
4440 $data = array();
4441 foreach ( $res as $row ) {
4442 $data[$row->up_property] = $row->up_value;
4445 foreach ( $data as $property => $value ) {
4446 $this->mOptionOverrides[$property] = $value;
4447 $this->mOptions[$property] = $value;
4451 $this->mOptionsLoaded = true;
4453 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
4457 * @todo document
4459 protected function saveOptions() {
4460 $this->loadOptions();
4462 // Not using getOptions(), to keep hidden preferences in database
4463 $saveOptions = $this->mOptions;
4465 // Allow hooks to abort, for instance to save to a global profile.
4466 // Reset options to default state before saving.
4467 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4468 return;
4471 $userId = $this->getId();
4472 $insert_rows = array();
4473 foreach ( $saveOptions as $key => $value ) {
4474 // Don't bother storing default values
4475 $defaultOption = self::getDefaultOption( $key );
4476 if ( ( is_null( $defaultOption ) &&
4477 !( $value === false || is_null( $value ) ) ) ||
4478 $value != $defaultOption ) {
4479 $insert_rows[] = array(
4480 'up_user' => $userId,
4481 'up_property' => $key,
4482 'up_value' => $value,
4487 $dbw = wfGetDB( DB_MASTER );
4488 $hasRows = $dbw->selectField( 'user_properties', '1',
4489 array( 'up_user' => $userId ), __METHOD__ );
4491 if ( $hasRows ) {
4492 // Only do this delete if there is something there. A very large portion of
4493 // calls to this function are for setting 'rememberpassword' for new accounts.
4494 // Doing this delete for new accounts with no rows in the table rougly causes
4495 // gap locks on [max user ID,+infinity) which causes high contention since many
4496 // updates will pile up on each other since they are for higher (newer) user IDs.
4497 $dbw->delete( 'user_properties', array( 'up_user' => $userId ), __METHOD__ );
4499 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
4503 * Provide an array of HTML5 attributes to put on an input element
4504 * intended for the user to enter a new password. This may include
4505 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4507 * Do *not* use this when asking the user to enter his current password!
4508 * Regardless of configuration, users may have invalid passwords for whatever
4509 * reason (e.g., they were set before requirements were tightened up).
4510 * Only use it when asking for a new password, like on account creation or
4511 * ResetPass.
4513 * Obviously, you still need to do server-side checking.
4515 * NOTE: A combination of bugs in various browsers means that this function
4516 * actually just returns array() unconditionally at the moment. May as
4517 * well keep it around for when the browser bugs get fixed, though.
4519 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4521 * @return array Array of HTML attributes suitable for feeding to
4522 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4523 * That will get confused by the boolean attribute syntax used.)
4525 public static function passwordChangeInputAttribs() {
4526 global $wgMinimalPasswordLength;
4528 if ( $wgMinimalPasswordLength == 0 ) {
4529 return array();
4532 # Note that the pattern requirement will always be satisfied if the
4533 # input is empty, so we need required in all cases.
4535 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4536 # if e-mail confirmation is being used. Since HTML5 input validation
4537 # is b0rked anyway in some browsers, just return nothing. When it's
4538 # re-enabled, fix this code to not output required for e-mail
4539 # registration.
4540 #$ret = array( 'required' );
4541 $ret = array();
4543 # We can't actually do this right now, because Opera 9.6 will print out
4544 # the entered password visibly in its error message! When other
4545 # browsers add support for this attribute, or Opera fixes its support,
4546 # we can add support with a version check to avoid doing this on Opera
4547 # versions where it will be a problem. Reported to Opera as
4548 # DSK-262266, but they don't have a public bug tracker for us to follow.
4550 if ( $wgMinimalPasswordLength > 1 ) {
4551 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4552 $ret['title'] = wfMessage( 'passwordtooshort' )
4553 ->numParams( $wgMinimalPasswordLength )->text();
4557 return $ret;
4561 * Return the list of user fields that should be selected to create
4562 * a new user object.
4563 * @return array
4565 public static function selectFields() {
4566 return array(
4567 'user_id',
4568 'user_name',
4569 'user_real_name',
4570 'user_password',
4571 'user_newpassword',
4572 'user_newpass_time',
4573 'user_email',
4574 'user_touched',
4575 'user_token',
4576 'user_email_authenticated',
4577 'user_email_token',
4578 'user_email_token_expires',
4579 'user_registration',
4580 'user_editcount',