Installer: Remove wgResourceLoaderMaxQueryLength in LocalSettings
[mediawiki.git] / includes / User.php
blob699ea671c61a0d66e4167a783bbc8326d6cc7132
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 'editusercssjs', #deprecated
128 'editusercss',
129 'edituserjs',
130 'hideuser',
131 'import',
132 'importupload',
133 'ipblock-exempt',
134 'markbotedits',
135 'mergehistory',
136 'minoredit',
137 'move',
138 'movefile',
139 'move-rootuserpages',
140 'move-subpages',
141 'nominornewtalk',
142 'noratelimit',
143 'override-export-depth',
144 'passwordreset',
145 'patrol',
146 'patrolmarks',
147 'protect',
148 'proxyunbannable',
149 'purge',
150 'read',
151 'reupload',
152 'reupload-own',
153 'reupload-shared',
154 'rollback',
155 'sendemail',
156 'siteadmin',
157 'suppressionlog',
158 'suppressredirect',
159 'suppressrevision',
160 'unblockself',
161 'undelete',
162 'unwatchedpages',
163 'upload',
164 'upload_by_url',
165 'userrights',
166 'userrights-interwiki',
167 'writeapi',
170 * String Cached results of getAllRights()
172 static $mAllRights = false;
174 /** @name Cache variables */
175 //@{
176 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
177 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
178 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mEditCount,
179 $mGroups, $mOptionOverrides;
180 //@}
183 * Bool Whether the cache variables have been loaded.
185 //@{
186 var $mOptionsLoaded;
189 * Array with already loaded items or true if all items have been loaded.
191 private $mLoadedItems = array();
192 //@}
195 * String Initialization data source if mLoadedItems!==true. May be one of:
196 * - 'defaults' anonymous user initialised from class defaults
197 * - 'name' initialise from mName
198 * - 'id' initialise from mId
199 * - 'session' log in from cookies or session if possible
201 * Use the User::newFrom*() family of functions to set this.
203 var $mFrom;
206 * Lazy-initialized variables, invalidated with clearInstanceCache
208 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mRights,
209 $mBlockreason, $mEffectiveGroups, $mImplicitGroups, $mFormerGroups, $mBlockedGlobally,
210 $mLocked, $mHideName, $mOptions;
213 * @var WebRequest
215 private $mRequest;
218 * @var Block
220 var $mBlock;
223 * @var bool
225 var $mAllowUsertalk;
228 * @var Block
230 private $mBlockedFromCreateAccount = false;
233 * @var Array
235 private $mWatchedItems = array();
237 static $idCacheByName = array();
240 * Lightweight constructor for an anonymous user.
241 * Use the User::newFrom* factory functions for other kinds of users.
243 * @see newFromName()
244 * @see newFromId()
245 * @see newFromConfirmationCode()
246 * @see newFromSession()
247 * @see newFromRow()
249 function __construct() {
250 $this->clearInstanceCache( 'defaults' );
254 * @return string
256 function __toString() {
257 return $this->getName();
261 * Load the user table data for this object from the source given by mFrom.
263 public function load() {
264 if ( $this->mLoadedItems === true ) {
265 return;
267 wfProfileIn( __METHOD__ );
269 // Set it now to avoid infinite recursion in accessors
270 $this->mLoadedItems = true;
272 switch ( $this->mFrom ) {
273 case 'defaults':
274 $this->loadDefaults();
275 break;
276 case 'name':
277 $this->mId = self::idFromName( $this->mName );
278 if ( !$this->mId ) {
279 // Nonexistent user placeholder object
280 $this->loadDefaults( $this->mName );
281 } else {
282 $this->loadFromId();
284 break;
285 case 'id':
286 $this->loadFromId();
287 break;
288 case 'session':
289 if ( !$this->loadFromSession() ) {
290 // Loading from session failed. Load defaults.
291 $this->loadDefaults();
293 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
294 break;
295 default:
296 wfProfileOut( __METHOD__ );
297 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
299 wfProfileOut( __METHOD__ );
303 * Load user table data, given mId has already been set.
304 * @return bool false if the ID does not exist, true otherwise
306 public function loadFromId() {
307 global $wgMemc;
308 if ( $this->mId == 0 ) {
309 $this->loadDefaults();
310 return false;
313 // Try cache
314 $key = wfMemcKey( 'user', 'id', $this->mId );
315 $data = $wgMemc->get( $key );
316 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
317 // Object is expired, load from DB
318 $data = false;
321 if ( !$data ) {
322 wfDebug( "User: cache miss for user {$this->mId}\n" );
323 // Load from DB
324 if ( !$this->loadFromDatabase() ) {
325 // Can't load from ID, user is anonymous
326 return false;
328 $this->saveToCache();
329 } else {
330 wfDebug( "User: got user {$this->mId} from cache\n" );
331 // Restore from cache
332 foreach ( self::$mCacheVars as $name ) {
333 $this->$name = $data[$name];
337 $this->mLoadedItems = true;
339 return true;
343 * Save user data to the shared cache
345 public function saveToCache() {
346 $this->load();
347 $this->loadGroups();
348 $this->loadOptions();
349 if ( $this->isAnon() ) {
350 // Anonymous users are uncached
351 return;
353 $data = array();
354 foreach ( self::$mCacheVars as $name ) {
355 $data[$name] = $this->$name;
357 $data['mVersion'] = MW_USER_VERSION;
358 $key = wfMemcKey( 'user', 'id', $this->mId );
359 global $wgMemc;
360 $wgMemc->set( $key, $data );
363 /** @name newFrom*() static factory methods */
364 //@{
367 * Static factory method for creation from username.
369 * This is slightly less efficient than newFromId(), so use newFromId() if
370 * you have both an ID and a name handy.
372 * @param string $name Username, validated by Title::newFromText()
373 * @param string|bool $validate Validate username. Takes the same parameters as
374 * User::getCanonicalName(), except that true is accepted as an alias
375 * for 'valid', for BC.
377 * @return User|bool User object, or false if the username is invalid
378 * (e.g. if it contains illegal characters or is an IP address). If the
379 * username is not present in the database, the result will be a user object
380 * with a name, zero user ID and default settings.
382 public static function newFromName( $name, $validate = 'valid' ) {
383 if ( $validate === true ) {
384 $validate = 'valid';
386 $name = self::getCanonicalName( $name, $validate );
387 if ( $name === false ) {
388 return false;
389 } else {
390 // Create unloaded user object
391 $u = new User;
392 $u->mName = $name;
393 $u->mFrom = 'name';
394 $u->setItemLoaded( 'name' );
395 return $u;
400 * Static factory method for creation from a given user ID.
402 * @param int $id Valid user ID
403 * @return User The corresponding User object
405 public static function newFromId( $id ) {
406 $u = new User;
407 $u->mId = $id;
408 $u->mFrom = 'id';
409 $u->setItemLoaded( 'id' );
410 return $u;
414 * Factory method to fetch whichever user has a given email confirmation code.
415 * This code is generated when an account is created or its e-mail address
416 * has changed.
418 * If the code is invalid or has expired, returns NULL.
420 * @param string $code Confirmation code
421 * @return User|null
423 public static function newFromConfirmationCode( $code ) {
424 $dbr = wfGetDB( DB_SLAVE );
425 $id = $dbr->selectField( 'user', 'user_id', array(
426 'user_email_token' => md5( $code ),
427 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
428 ) );
429 if ( $id !== false ) {
430 return User::newFromId( $id );
431 } else {
432 return null;
437 * Create a new user object using data from session or cookies. If the
438 * login credentials are invalid, the result is an anonymous user.
440 * @param WebRequest $request Object to use; $wgRequest will be used if omitted.
441 * @return User object
443 public static function newFromSession( WebRequest $request = null ) {
444 $user = new User;
445 $user->mFrom = 'session';
446 $user->mRequest = $request;
447 return $user;
451 * Create a new user object from a user row.
452 * The row should have the following fields from the user table in it:
453 * - either user_name or user_id to load further data if needed (or both)
454 * - user_real_name
455 * - all other fields (email, password, etc.)
456 * It is useless to provide the remaining fields if either user_id,
457 * user_name and user_real_name are not provided because the whole row
458 * will be loaded once more from the database when accessing them.
460 * @param array $row A row from the user table
461 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
462 * @return User
464 public static function newFromRow( $row, $data = null ) {
465 $user = new User;
466 $user->loadFromRow( $row, $data );
467 return $user;
470 //@}
473 * Get the username corresponding to a given user ID
474 * @param int $id User ID
475 * @return string|bool The corresponding username
477 public static function whoIs( $id ) {
478 return UserCache::singleton()->getProp( $id, 'name' );
482 * Get the real name of a user given their user ID
484 * @param int $id User ID
485 * @return string|bool The corresponding user's real name
487 public static function whoIsReal( $id ) {
488 return UserCache::singleton()->getProp( $id, 'real_name' );
492 * Get database id given a user name
493 * @param string $name Username
494 * @return int|null The corresponding user's ID, or null if user is nonexistent
496 public static function idFromName( $name ) {
497 $nt = Title::makeTitleSafe( NS_USER, $name );
498 if ( is_null( $nt ) ) {
499 // Illegal name
500 return null;
503 if ( isset( self::$idCacheByName[$name] ) ) {
504 return self::$idCacheByName[$name];
507 $dbr = wfGetDB( DB_SLAVE );
508 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
510 if ( $s === false ) {
511 $result = null;
512 } else {
513 $result = $s->user_id;
516 self::$idCacheByName[$name] = $result;
518 if ( count( self::$idCacheByName ) > 1000 ) {
519 self::$idCacheByName = array();
522 return $result;
526 * Reset the cache used in idFromName(). For use in tests.
528 public static function resetIdByNameCache() {
529 self::$idCacheByName = array();
533 * Does the string match an anonymous IPv4 address?
535 * This function exists for username validation, in order to reject
536 * usernames which are similar in form to IP addresses. Strings such
537 * as 300.300.300.300 will return true because it looks like an IP
538 * address, despite not being strictly valid.
540 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
541 * address because the usemod software would "cloak" anonymous IP
542 * addresses like this, if we allowed accounts like this to be created
543 * new users could get the old edits of these anonymous users.
545 * @param string $name Name to match
546 * @return bool
548 public static function isIP( $name ) {
549 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name ) || IP::isIPv6( $name );
553 * Is the input a valid username?
555 * Checks if the input is a valid username, we don't want an empty string,
556 * an IP address, anything that contains slashes (would mess up subpages),
557 * is longer than the maximum allowed username size or doesn't begin with
558 * a capital letter.
560 * @param string $name Name to match
561 * @return bool
563 public static function isValidUserName( $name ) {
564 global $wgContLang, $wgMaxNameChars;
566 if ( $name == ''
567 || User::isIP( $name )
568 || strpos( $name, '/' ) !== false
569 || strlen( $name ) > $wgMaxNameChars
570 || $name != $wgContLang->ucfirst( $name ) ) {
571 wfDebugLog( 'username', __METHOD__ .
572 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
573 return false;
576 // Ensure that the name can't be misresolved as a different title,
577 // such as with extra namespace keys at the start.
578 $parsed = Title::newFromText( $name );
579 if ( is_null( $parsed )
580 || $parsed->getNamespace()
581 || strcmp( $name, $parsed->getPrefixedText() ) ) {
582 wfDebugLog( 'username', __METHOD__ .
583 ": '$name' invalid due to ambiguous prefixes" );
584 return false;
587 // Check an additional blacklist of troublemaker characters.
588 // Should these be merged into the title char list?
589 $unicodeBlacklist = '/[' .
590 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
591 '\x{00a0}' . # non-breaking space
592 '\x{2000}-\x{200f}' . # various whitespace
593 '\x{2028}-\x{202f}' . # breaks and control chars
594 '\x{3000}' . # ideographic space
595 '\x{e000}-\x{f8ff}' . # private use
596 ']/u';
597 if ( preg_match( $unicodeBlacklist, $name ) ) {
598 wfDebugLog( 'username', __METHOD__ .
599 ": '$name' invalid due to blacklisted characters" );
600 return false;
603 return true;
607 * Usernames which fail to pass this function will be blocked
608 * from user login and new account registrations, but may be used
609 * internally by batch processes.
611 * If an account already exists in this form, login will be blocked
612 * by a failure to pass this function.
614 * @param string $name Name to match
615 * @return bool
617 public static function isUsableName( $name ) {
618 global $wgReservedUsernames;
619 // Must be a valid username, obviously ;)
620 if ( !self::isValidUserName( $name ) ) {
621 return false;
624 static $reservedUsernames = false;
625 if ( !$reservedUsernames ) {
626 $reservedUsernames = $wgReservedUsernames;
627 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
630 // Certain names may be reserved for batch processes.
631 foreach ( $reservedUsernames as $reserved ) {
632 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
633 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
635 if ( $reserved == $name ) {
636 return false;
639 return true;
643 * Usernames which fail to pass this function will be blocked
644 * from new account registrations, but may be used internally
645 * either by batch processes or by user accounts which have
646 * already been created.
648 * Additional blacklisting may be added here rather than in
649 * isValidUserName() to avoid disrupting existing accounts.
651 * @param string $name to match
652 * @return bool
654 public static function isCreatableName( $name ) {
655 global $wgInvalidUsernameCharacters;
657 // Ensure that the username isn't longer than 235 bytes, so that
658 // (at least for the builtin skins) user javascript and css files
659 // will work. (bug 23080)
660 if ( strlen( $name ) > 235 ) {
661 wfDebugLog( 'username', __METHOD__ .
662 ": '$name' invalid due to length" );
663 return false;
666 // Preg yells if you try to give it an empty string
667 if ( $wgInvalidUsernameCharacters !== '' ) {
668 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
669 wfDebugLog( 'username', __METHOD__ .
670 ": '$name' invalid due to wgInvalidUsernameCharacters" );
671 return false;
675 return self::isUsableName( $name );
679 * Is the input a valid password for this user?
681 * @param string $password Desired password
682 * @return bool
684 public function isValidPassword( $password ) {
685 //simple boolean wrapper for getPasswordValidity
686 return $this->getPasswordValidity( $password ) === true;
690 * Given unvalidated password input, return error message on failure.
692 * @param string $password Desired password
693 * @return mixed: true on success, string or array of error message on failure
695 public function getPasswordValidity( $password ) {
696 global $wgMinimalPasswordLength, $wgContLang;
698 static $blockedLogins = array(
699 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
700 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
703 $result = false; //init $result to false for the internal checks
705 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
706 return $result;
709 if ( $result === false ) {
710 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
711 return 'passwordtooshort';
712 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) {
713 return 'password-name-match';
714 } elseif ( isset( $blockedLogins[$this->getName()] ) && $password == $blockedLogins[$this->getName()] ) {
715 return 'password-login-forbidden';
716 } else {
717 //it seems weird returning true here, but this is because of the
718 //initialization of $result to false above. If the hook is never run or it
719 //doesn't modify $result, then we will likely get down into this if with
720 //a valid password.
721 return true;
723 } elseif ( $result === true ) {
724 return true;
725 } else {
726 return $result; //the isValidPassword hook set a string $result and returned true
731 * Does a string look like an e-mail address?
733 * This validates an email address using an HTML5 specification found at:
734 * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
735 * Which as of 2011-01-24 says:
737 * A valid e-mail address is a string that matches the ABNF production
738 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
739 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
740 * 3.5.
742 * This function is an implementation of the specification as requested in
743 * bug 22449.
745 * Client-side forms will use the same standard validation rules via JS or
746 * HTML 5 validation; additional restrictions can be enforced server-side
747 * by extensions via the 'isValidEmailAddr' hook.
749 * Note that this validation doesn't 100% match RFC 2822, but is believed
750 * to be liberal enough for wide use. Some invalid addresses will still
751 * pass validation here.
753 * @param string $addr E-mail address
754 * @return bool
755 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
757 public static function isValidEmailAddr( $addr ) {
758 wfDeprecated( __METHOD__, '1.18' );
759 return Sanitizer::validateEmail( $addr );
763 * Given unvalidated user input, return a canonical username, or false if
764 * the username is invalid.
765 * @param string $name User input
766 * @param string|bool $validate type of validation to use:
767 * - false No validation
768 * - 'valid' Valid for batch processes
769 * - 'usable' Valid for batch processes and login
770 * - 'creatable' Valid for batch processes, login and account creation
772 * @throws MWException
773 * @return bool|string
775 public static function getCanonicalName( $name, $validate = 'valid' ) {
776 // Force usernames to capital
777 global $wgContLang;
778 $name = $wgContLang->ucfirst( $name );
780 # Reject names containing '#'; these will be cleaned up
781 # with title normalisation, but then it's too late to
782 # check elsewhere
783 if ( strpos( $name, '#' ) !== false ) {
784 return false;
787 // Clean up name according to title rules
788 $t = ( $validate === 'valid' ) ?
789 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
790 // Check for invalid titles
791 if ( is_null( $t ) ) {
792 return false;
795 // Reject various classes of invalid names
796 global $wgAuth;
797 $name = $wgAuth->getCanonicalName( $t->getText() );
799 switch ( $validate ) {
800 case false:
801 break;
802 case 'valid':
803 if ( !User::isValidUserName( $name ) ) {
804 $name = false;
806 break;
807 case 'usable':
808 if ( !User::isUsableName( $name ) ) {
809 $name = false;
811 break;
812 case 'creatable':
813 if ( !User::isCreatableName( $name ) ) {
814 $name = false;
816 break;
817 default:
818 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
820 return $name;
824 * Count the number of edits of a user
826 * @param int $uid User ID to check
827 * @return int The user's edit count
829 * @deprecated since 1.21 in favour of User::getEditCount
831 public static function edits( $uid ) {
832 wfDeprecated( __METHOD__, '1.21' );
833 $user = self::newFromId( $uid );
834 return $user->getEditCount();
838 * Return a random password.
840 * @return string New random password
842 public static function randomPassword() {
843 global $wgMinimalPasswordLength;
844 // Decide the final password length based on our min password length, stopping at a minimum of 10 chars
845 $length = max( 10, $wgMinimalPasswordLength );
846 // Multiply by 1.25 to get the number of hex characters we need
847 $length = $length * 1.25;
848 // Generate random hex chars
849 $hex = MWCryptRand::generateHex( $length );
850 // Convert from base 16 to base 32 to get a proper password like string
851 return wfBaseConvert( $hex, 16, 32 );
855 * Set cached properties to default.
857 * @note This no longer clears uncached lazy-initialised properties;
858 * the constructor does that instead.
860 * @param $name string|bool
862 public function loadDefaults( $name = false ) {
863 wfProfileIn( __METHOD__ );
865 $this->mId = 0;
866 $this->mName = $name;
867 $this->mRealName = '';
868 $this->mPassword = $this->mNewpassword = '';
869 $this->mNewpassTime = null;
870 $this->mEmail = '';
871 $this->mOptionOverrides = null;
872 $this->mOptionsLoaded = false;
874 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
875 if ( $loggedOut !== null ) {
876 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
877 } else {
878 $this->mTouched = '1'; # Allow any pages to be cached
881 $this->mToken = null; // Don't run cryptographic functions till we need a token
882 $this->mEmailAuthenticated = null;
883 $this->mEmailToken = '';
884 $this->mEmailTokenExpires = null;
885 $this->mRegistration = wfTimestamp( TS_MW );
886 $this->mGroups = array();
888 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
890 wfProfileOut( __METHOD__ );
894 * Return whether an item has been loaded.
896 * @param string $item item to check. Current possibilities:
897 * - id
898 * - name
899 * - realname
900 * @param string $all 'all' to check if the whole object has been loaded
901 * or any other string to check if only the item is available (e.g.
902 * for optimisation)
903 * @return boolean
905 public function isItemLoaded( $item, $all = 'all' ) {
906 return ( $this->mLoadedItems === true && $all === 'all' ) ||
907 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
911 * Set that an item has been loaded
913 * @param string $item
915 protected function setItemLoaded( $item ) {
916 if ( is_array( $this->mLoadedItems ) ) {
917 $this->mLoadedItems[$item] = true;
922 * Load user data from the session or login cookie.
923 * @return bool True if the user is logged in, false otherwise.
925 private function loadFromSession() {
926 $result = null;
927 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
928 if ( $result !== null ) {
929 return $result;
932 $request = $this->getRequest();
934 $cookieId = $request->getCookie( 'UserID' );
935 $sessId = $request->getSessionData( 'wsUserID' );
937 if ( $cookieId !== null ) {
938 $sId = intval( $cookieId );
939 if ( $sessId !== null && $cookieId != $sessId ) {
940 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
941 cookie user ID ($sId) don't match!" );
942 return false;
944 $request->setSessionData( 'wsUserID', $sId );
945 } elseif ( $sessId !== null && $sessId != 0 ) {
946 $sId = $sessId;
947 } else {
948 return false;
951 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
952 $sName = $request->getSessionData( 'wsUserName' );
953 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
954 $sName = $request->getCookie( 'UserName' );
955 $request->setSessionData( 'wsUserName', $sName );
956 } else {
957 return false;
960 $proposedUser = User::newFromId( $sId );
961 if ( !$proposedUser->isLoggedIn() ) {
962 // Not a valid ID
963 return false;
966 global $wgBlockDisablesLogin;
967 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
968 // User blocked and we've disabled blocked user logins
969 return false;
972 if ( $request->getSessionData( 'wsToken' ) ) {
973 $passwordCorrect = ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
974 $from = 'session';
975 } elseif ( $request->getCookie( 'Token' ) ) {
976 # Get the token from DB/cache and clean it up to remove garbage padding.
977 # This deals with historical problems with bugs and the default column value.
978 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
979 $passwordCorrect = ( strlen( $token ) && $token === $request->getCookie( 'Token' ) );
980 $from = 'cookie';
981 } else {
982 // No session or persistent login cookie
983 return false;
986 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
987 $this->loadFromUserObject( $proposedUser );
988 $request->setSessionData( 'wsToken', $this->mToken );
989 wfDebug( "User: logged in from $from\n" );
990 return true;
991 } else {
992 // Invalid credentials
993 wfDebug( "User: can't log in from $from, invalid credentials\n" );
994 return false;
999 * Load user and user_group data from the database.
1000 * $this->mId must be set, this is how the user is identified.
1002 * @return bool True if the user exists, false if the user is anonymous
1004 public function loadFromDatabase() {
1005 // Paranoia
1006 $this->mId = intval( $this->mId );
1008 // Anonymous user
1009 if ( !$this->mId ) {
1010 $this->loadDefaults();
1011 return false;
1014 $dbr = wfGetDB( DB_MASTER );
1015 $s = $dbr->selectRow( 'user', self::selectFields(), array( 'user_id' => $this->mId ), __METHOD__ );
1017 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1019 if ( $s !== false ) {
1020 // Initialise user table data
1021 $this->loadFromRow( $s );
1022 $this->mGroups = null; // deferred
1023 $this->getEditCount(); // revalidation for nulls
1024 return true;
1025 } else {
1026 // Invalid user_id
1027 $this->mId = 0;
1028 $this->loadDefaults();
1029 return false;
1034 * Initialize this object from a row from the user table.
1036 * @param array $row Row from the user table to load.
1037 * @param array $data Further user data to load into the object
1039 * user_groups Array with groups out of the user_groups table
1040 * user_properties Array with properties out of the user_properties table
1042 public function loadFromRow( $row, $data = null ) {
1043 $all = true;
1045 $this->mGroups = null; // deferred
1047 if ( isset( $row->user_name ) ) {
1048 $this->mName = $row->user_name;
1049 $this->mFrom = 'name';
1050 $this->setItemLoaded( 'name' );
1051 } else {
1052 $all = false;
1055 if ( isset( $row->user_real_name ) ) {
1056 $this->mRealName = $row->user_real_name;
1057 $this->setItemLoaded( 'realname' );
1058 } else {
1059 $all = false;
1062 if ( isset( $row->user_id ) ) {
1063 $this->mId = intval( $row->user_id );
1064 $this->mFrom = 'id';
1065 $this->setItemLoaded( 'id' );
1066 } else {
1067 $all = false;
1070 if ( isset( $row->user_editcount ) ) {
1071 $this->mEditCount = $row->user_editcount;
1072 } else {
1073 $all = false;
1076 if ( isset( $row->user_password ) ) {
1077 $this->mPassword = $row->user_password;
1078 $this->mNewpassword = $row->user_newpassword;
1079 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
1080 $this->mEmail = $row->user_email;
1081 if ( isset( $row->user_options ) ) {
1082 $this->decodeOptions( $row->user_options );
1084 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1085 $this->mToken = $row->user_token;
1086 if ( $this->mToken == '' ) {
1087 $this->mToken = null;
1089 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1090 $this->mEmailToken = $row->user_email_token;
1091 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1092 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1093 } else {
1094 $all = false;
1097 if ( $all ) {
1098 $this->mLoadedItems = true;
1101 if ( is_array( $data ) ) {
1102 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1103 $this->mGroups = $data['user_groups'];
1105 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1106 $this->loadOptions( $data['user_properties'] );
1112 * Load the data for this user object from another user object.
1114 * @param $user User
1116 protected function loadFromUserObject( $user ) {
1117 $user->load();
1118 $user->loadGroups();
1119 $user->loadOptions();
1120 foreach ( self::$mCacheVars as $var ) {
1121 $this->$var = $user->$var;
1126 * Load the groups from the database if they aren't already loaded.
1128 private function loadGroups() {
1129 if ( is_null( $this->mGroups ) ) {
1130 $dbr = wfGetDB( DB_MASTER );
1131 $res = $dbr->select( 'user_groups',
1132 array( 'ug_group' ),
1133 array( 'ug_user' => $this->mId ),
1134 __METHOD__ );
1135 $this->mGroups = array();
1136 foreach ( $res as $row ) {
1137 $this->mGroups[] = $row->ug_group;
1143 * Add the user to the group if he/she meets given criteria.
1145 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1146 * possible to remove manually via Special:UserRights. In such case it
1147 * will not be re-added automatically. The user will also not lose the
1148 * group if they no longer meet the criteria.
1150 * @param string $event key in $wgAutopromoteOnce (each one has groups/criteria)
1152 * @return array Array of groups the user has been promoted to.
1154 * @see $wgAutopromoteOnce
1156 public function addAutopromoteOnceGroups( $event ) {
1157 global $wgAutopromoteOnceLogInRC;
1159 $toPromote = array();
1160 if ( $this->getId() ) {
1161 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1162 if ( count( $toPromote ) ) {
1163 $oldGroups = $this->getGroups(); // previous groups
1164 foreach ( $toPromote as $group ) {
1165 $this->addGroup( $group );
1167 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1169 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1170 $logEntry->setPerformer( $this );
1171 $logEntry->setTarget( $this->getUserPage() );
1172 $logEntry->setParameters( array(
1173 '4::oldgroups' => $oldGroups,
1174 '5::newgroups' => $newGroups,
1175 ) );
1176 $logid = $logEntry->insert();
1177 if ( $wgAutopromoteOnceLogInRC ) {
1178 $logEntry->publish( $logid );
1182 return $toPromote;
1186 * Clear various cached data stored in this object. The cache of the user table
1187 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1189 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1190 * given source. May be "name", "id", "defaults", "session", or false for
1191 * no reload.
1193 public function clearInstanceCache( $reloadFrom = false ) {
1194 $this->mNewtalk = -1;
1195 $this->mDatePreference = null;
1196 $this->mBlockedby = -1; # Unset
1197 $this->mHash = false;
1198 $this->mRights = null;
1199 $this->mEffectiveGroups = null;
1200 $this->mImplicitGroups = null;
1201 $this->mGroups = null;
1202 $this->mOptions = null;
1203 $this->mOptionsLoaded = false;
1204 $this->mEditCount = null;
1206 if ( $reloadFrom ) {
1207 $this->mLoadedItems = array();
1208 $this->mFrom = $reloadFrom;
1213 * Combine the language default options with any site-specific options
1214 * and add the default language variants.
1216 * @return Array of String options
1218 public static function getDefaultOptions() {
1219 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1221 static $defOpt = null;
1222 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1223 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1224 // mid-request and see that change reflected in the return value of this function.
1225 // Which is insane and would never happen during normal MW operation
1226 return $defOpt;
1229 $defOpt = $wgDefaultUserOptions;
1230 // Default language setting
1231 $defOpt['language'] = $defOpt['variant'] = $wgContLang->getCode();
1232 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1233 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1235 $defOpt['skin'] = $wgDefaultSkin;
1237 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1239 return $defOpt;
1243 * Get a given default option value.
1245 * @param string $opt Name of option to retrieve
1246 * @return string Default option value
1248 public static function getDefaultOption( $opt ) {
1249 $defOpts = self::getDefaultOptions();
1250 if ( isset( $defOpts[$opt] ) ) {
1251 return $defOpts[$opt];
1252 } else {
1253 return null;
1258 * Get blocking information
1259 * @param bool $bFromSlave Whether to check the slave database first. To
1260 * improve performance, non-critical checks are done
1261 * against slaves. Check when actually saving should be
1262 * done against master.
1264 private function getBlockedStatus( $bFromSlave = true ) {
1265 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1267 if ( -1 != $this->mBlockedby ) {
1268 return;
1271 wfProfileIn( __METHOD__ );
1272 wfDebug( __METHOD__ . ": checking...\n" );
1274 // Initialize data...
1275 // Otherwise something ends up stomping on $this->mBlockedby when
1276 // things get lazy-loaded later, causing false positive block hits
1277 // due to -1 !== 0. Probably session-related... Nothing should be
1278 // overwriting mBlockedby, surely?
1279 $this->load();
1281 # We only need to worry about passing the IP address to the Block generator if the
1282 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1283 # know which IP address they're actually coming from
1284 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1285 $ip = $this->getRequest()->getIP();
1286 } else {
1287 $ip = null;
1290 // User/IP blocking
1291 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1293 // Proxy blocking
1294 if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1295 && !in_array( $ip, $wgProxyWhitelist ) )
1297 // Local list
1298 if ( self::isLocallyBlockedProxy( $ip ) ) {
1299 $block = new Block;
1300 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1301 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1302 $block->setTarget( $ip );
1303 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1304 $block = new Block;
1305 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1306 $block->mReason = wfMessage( 'sorbsreason' )->text();
1307 $block->setTarget( $ip );
1311 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1312 if ( !$block instanceof Block
1313 && $wgApplyIpBlocksToXff
1314 && $ip !== null
1315 && !$this->isAllowed( 'proxyunbannable' )
1316 && !in_array( $ip, $wgProxyWhitelist )
1318 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1319 $xff = array_map( 'trim', explode( ',', $xff ) );
1320 $xff = array_diff( $xff, array( $ip ) );
1321 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1322 $block = Block::chooseBlock( $xffblocks, $xff );
1323 if ( $block instanceof Block ) {
1324 # Mangle the reason to alert the user that the block
1325 # originated from matching the X-Forwarded-For header.
1326 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1330 if ( $block instanceof Block ) {
1331 wfDebug( __METHOD__ . ": Found block.\n" );
1332 $this->mBlock = $block;
1333 $this->mBlockedby = $block->getByName();
1334 $this->mBlockreason = $block->mReason;
1335 $this->mHideName = $block->mHideName;
1336 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1337 } else {
1338 $this->mBlockedby = '';
1339 $this->mHideName = 0;
1340 $this->mAllowUsertalk = false;
1343 // Extensions
1344 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1346 wfProfileOut( __METHOD__ );
1350 * Whether the given IP is in a DNS blacklist.
1352 * @param string $ip IP to check
1353 * @param bool $checkWhitelist whether to check the whitelist first
1354 * @return bool True if blacklisted.
1356 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1357 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1358 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1360 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs ) {
1361 return false;
1364 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1365 return false;
1368 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1369 return $this->inDnsBlacklist( $ip, $urls );
1373 * Whether the given IP is in a given DNS blacklist.
1375 * @param string $ip IP to check
1376 * @param string|array $bases of Strings: URL of the DNS blacklist
1377 * @return bool True if blacklisted.
1379 public function inDnsBlacklist( $ip, $bases ) {
1380 wfProfileIn( __METHOD__ );
1382 $found = false;
1383 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1384 if ( IP::isIPv4( $ip ) ) {
1385 // Reverse IP, bug 21255
1386 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1388 foreach ( (array)$bases as $base ) {
1389 // Make hostname
1390 // If we have an access key, use that too (ProjectHoneypot, etc.)
1391 if ( is_array( $base ) ) {
1392 if ( count( $base ) >= 2 ) {
1393 // Access key is 1, base URL is 0
1394 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1395 } else {
1396 $host = "$ipReversed.{$base[0]}";
1398 } else {
1399 $host = "$ipReversed.$base";
1402 // Send query
1403 $ipList = gethostbynamel( $host );
1405 if ( $ipList ) {
1406 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1407 $found = true;
1408 break;
1409 } else {
1410 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base.\n" );
1415 wfProfileOut( __METHOD__ );
1416 return $found;
1420 * Check if an IP address is in the local proxy list
1422 * @param $ip string
1424 * @return bool
1426 public static function isLocallyBlockedProxy( $ip ) {
1427 global $wgProxyList;
1429 if ( !$wgProxyList ) {
1430 return false;
1432 wfProfileIn( __METHOD__ );
1434 if ( !is_array( $wgProxyList ) ) {
1435 // Load from the specified file
1436 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1439 if ( !is_array( $wgProxyList ) ) {
1440 $ret = false;
1441 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1442 $ret = true;
1443 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1444 // Old-style flipped proxy list
1445 $ret = true;
1446 } else {
1447 $ret = false;
1449 wfProfileOut( __METHOD__ );
1450 return $ret;
1454 * Is this user subject to rate limiting?
1456 * @return bool True if rate limited
1458 public function isPingLimitable() {
1459 global $wgRateLimitsExcludedIPs;
1460 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1461 // No other good way currently to disable rate limits
1462 // for specific IPs. :P
1463 // But this is a crappy hack and should die.
1464 return false;
1466 return !$this->isAllowed( 'noratelimit' );
1470 * Primitive rate limits: enforce maximum actions per time period
1471 * to put a brake on flooding.
1473 * @note When using a shared cache like memcached, IP-address
1474 * last-hit counters will be shared across wikis.
1476 * @param string $action Action to enforce; 'edit' if unspecified
1477 * @return bool True if a rate limiter was tripped
1479 public function pingLimiter( $action = 'edit' ) {
1480 // Call the 'PingLimiter' hook
1481 $result = false;
1482 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result ) ) ) {
1483 return $result;
1486 global $wgRateLimits;
1487 if ( !isset( $wgRateLimits[$action] ) ) {
1488 return false;
1491 // Some groups shouldn't trigger the ping limiter, ever
1492 if ( !$this->isPingLimitable() ) {
1493 return false;
1496 global $wgMemc, $wgRateLimitLog;
1497 wfProfileIn( __METHOD__ );
1499 $limits = $wgRateLimits[$action];
1500 $keys = array();
1501 $id = $this->getId();
1502 $userLimit = false;
1504 if ( isset( $limits['anon'] ) && $id == 0 ) {
1505 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1508 if ( isset( $limits['user'] ) && $id != 0 ) {
1509 $userLimit = $limits['user'];
1511 if ( $this->isNewbie() ) {
1512 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1513 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1515 if ( isset( $limits['ip'] ) ) {
1516 $ip = $this->getRequest()->getIP();
1517 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1519 if ( isset( $limits['subnet'] ) ) {
1520 $ip = $this->getRequest()->getIP();
1521 $matches = array();
1522 $subnet = false;
1523 if ( IP::isIPv6( $ip ) ) {
1524 $parts = IP::parseRange( "$ip/64" );
1525 $subnet = $parts[0];
1526 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1527 // IPv4
1528 $subnet = $matches[1];
1530 if ( $subnet !== false ) {
1531 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1535 // Check for group-specific permissions
1536 // If more than one group applies, use the group with the highest limit
1537 foreach ( $this->getGroups() as $group ) {
1538 if ( isset( $limits[$group] ) ) {
1539 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1540 $userLimit = $limits[$group];
1544 // Set the user limit key
1545 if ( $userLimit !== false ) {
1546 list( $max, $period ) = $userLimit;
1547 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1548 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1551 $triggered = false;
1552 foreach ( $keys as $key => $limit ) {
1553 list( $max, $period ) = $limit;
1554 $summary = "(limit $max in {$period}s)";
1555 $count = $wgMemc->get( $key );
1556 // Already pinged?
1557 if ( $count ) {
1558 if ( $count >= $max ) {
1559 wfDebug( __METHOD__ . ": tripped! $key at $count $summary\n" );
1560 if ( $wgRateLimitLog ) {
1561 wfSuppressWarnings();
1562 file_put_contents( $wgRateLimitLog, wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", FILE_APPEND );
1563 wfRestoreWarnings();
1565 $triggered = true;
1566 } else {
1567 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1569 } else {
1570 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1571 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1573 $wgMemc->incr( $key );
1576 wfProfileOut( __METHOD__ );
1577 return $triggered;
1581 * Check if user is blocked
1583 * @param bool $bFromSlave Whether to check the slave database instead of the master
1584 * @return bool True if blocked, false otherwise
1586 public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1587 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1591 * Get the block affecting the user, or null if the user is not blocked
1593 * @param bool $bFromSlave Whether to check the slave database instead of the master
1594 * @return Block|null
1596 public function getBlock( $bFromSlave = true ) {
1597 $this->getBlockedStatus( $bFromSlave );
1598 return $this->mBlock instanceof Block ? $this->mBlock : null;
1602 * Check if user is blocked from editing a particular article
1604 * @param Title $title Title to check
1605 * @param bool $bFromSlave whether to check the slave database instead of the master
1606 * @return bool
1608 function isBlockedFrom( $title, $bFromSlave = false ) {
1609 global $wgBlockAllowsUTEdit;
1610 wfProfileIn( __METHOD__ );
1612 $blocked = $this->isBlocked( $bFromSlave );
1613 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1614 // If a user's name is suppressed, they cannot make edits anywhere
1615 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName() &&
1616 $title->getNamespace() == NS_USER_TALK ) {
1617 $blocked = false;
1618 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1621 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1623 wfProfileOut( __METHOD__ );
1624 return $blocked;
1628 * If user is blocked, return the name of the user who placed the block
1629 * @return string Name of blocker
1631 public function blockedBy() {
1632 $this->getBlockedStatus();
1633 return $this->mBlockedby;
1637 * If user is blocked, return the specified reason for the block
1638 * @return string Blocking reason
1640 public function blockedFor() {
1641 $this->getBlockedStatus();
1642 return $this->mBlockreason;
1646 * If user is blocked, return the ID for the block
1647 * @return int Block ID
1649 public function getBlockId() {
1650 $this->getBlockedStatus();
1651 return ( $this->mBlock ? $this->mBlock->getId() : false );
1655 * Check if user is blocked on all wikis.
1656 * Do not use for actual edit permission checks!
1657 * This is intended for quick UI checks.
1659 * @param string $ip IP address, uses current client if none given
1660 * @return bool True if blocked, false otherwise
1662 public function isBlockedGlobally( $ip = '' ) {
1663 if ( $this->mBlockedGlobally !== null ) {
1664 return $this->mBlockedGlobally;
1666 // User is already an IP?
1667 if ( IP::isIPAddress( $this->getName() ) ) {
1668 $ip = $this->getName();
1669 } elseif ( !$ip ) {
1670 $ip = $this->getRequest()->getIP();
1672 $blocked = false;
1673 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1674 $this->mBlockedGlobally = (bool)$blocked;
1675 return $this->mBlockedGlobally;
1679 * Check if user account is locked
1681 * @return bool True if locked, false otherwise
1683 public function isLocked() {
1684 if ( $this->mLocked !== null ) {
1685 return $this->mLocked;
1687 global $wgAuth;
1688 $authUser = $wgAuth->getUserInstance( $this );
1689 $this->mLocked = (bool)$authUser->isLocked();
1690 return $this->mLocked;
1694 * Check if user account is hidden
1696 * @return bool True if hidden, false otherwise
1698 public function isHidden() {
1699 if ( $this->mHideName !== null ) {
1700 return $this->mHideName;
1702 $this->getBlockedStatus();
1703 if ( !$this->mHideName ) {
1704 global $wgAuth;
1705 $authUser = $wgAuth->getUserInstance( $this );
1706 $this->mHideName = (bool)$authUser->isHidden();
1708 return $this->mHideName;
1712 * Get the user's ID.
1713 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1715 public function getId() {
1716 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
1717 // Special case, we know the user is anonymous
1718 return 0;
1719 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1720 // Don't load if this was initialized from an ID
1721 $this->load();
1723 return $this->mId;
1727 * Set the user and reload all fields according to a given ID
1728 * @param int $v User ID to reload
1730 public function setId( $v ) {
1731 $this->mId = $v;
1732 $this->clearInstanceCache( 'id' );
1736 * Get the user name, or the IP of an anonymous user
1737 * @return string User's name or IP address
1739 public function getName() {
1740 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1741 // Special case optimisation
1742 return $this->mName;
1743 } else {
1744 $this->load();
1745 if ( $this->mName === false ) {
1746 // Clean up IPs
1747 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
1749 return $this->mName;
1754 * Set the user name.
1756 * This does not reload fields from the database according to the given
1757 * name. Rather, it is used to create a temporary "nonexistent user" for
1758 * later addition to the database. It can also be used to set the IP
1759 * address for an anonymous user to something other than the current
1760 * remote IP.
1762 * @note User::newFromName() has roughly the same function, when the named user
1763 * does not exist.
1764 * @param string $str New user name to set
1766 public function setName( $str ) {
1767 $this->load();
1768 $this->mName = $str;
1772 * Get the user's name escaped by underscores.
1773 * @return string Username escaped by underscores.
1775 public function getTitleKey() {
1776 return str_replace( ' ', '_', $this->getName() );
1780 * Check if the user has new messages.
1781 * @return bool True if the user has new messages
1783 public function getNewtalk() {
1784 $this->load();
1786 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1787 if ( $this->mNewtalk === -1 ) {
1788 $this->mNewtalk = false; # reset talk page status
1790 // Check memcached separately for anons, who have no
1791 // entire User object stored in there.
1792 if ( !$this->mId ) {
1793 global $wgDisableAnonTalk;
1794 if ( $wgDisableAnonTalk ) {
1795 // Anon newtalk disabled by configuration.
1796 $this->mNewtalk = false;
1797 } else {
1798 global $wgMemc;
1799 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1800 $newtalk = $wgMemc->get( $key );
1801 if ( strval( $newtalk ) !== '' ) {
1802 $this->mNewtalk = (bool)$newtalk;
1803 } else {
1804 // Since we are caching this, make sure it is up to date by getting it
1805 // from the master
1806 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1807 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1810 } else {
1811 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1815 return (bool)$this->mNewtalk;
1819 * Return the revision and link for the oldest new talk page message for
1820 * this user.
1821 * @note This function was designed to accomodate multiple talk pages, but
1822 * currently only returns a single link and revision.
1823 * @return Array
1825 public function getNewMessageLinks() {
1826 $talks = array();
1827 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
1828 return $talks;
1829 } elseif ( !$this->getNewtalk() ) {
1830 return array();
1832 $utp = $this->getTalkPage();
1833 $dbr = wfGetDB( DB_SLAVE );
1834 // Get the "last viewed rev" timestamp from the oldest message notification
1835 $timestamp = $dbr->selectField( 'user_newtalk',
1836 'MIN(user_last_timestamp)',
1837 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
1838 __METHOD__ );
1839 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
1840 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
1844 * Get the revision ID for the oldest new talk page message for this user
1845 * @return int|null Revision id or null if there are no new messages
1847 public function getNewMessageRevisionId() {
1848 $newMessageRevisionId = null;
1849 $newMessageLinks = $this->getNewMessageLinks();
1850 if ( $newMessageLinks ) {
1851 // Note: getNewMessageLinks() never returns more than a single link
1852 // and it is always for the same wiki, but we double-check here in
1853 // case that changes some time in the future.
1854 if ( count( $newMessageLinks ) === 1
1855 && $newMessageLinks[0]['wiki'] === wfWikiID()
1856 && $newMessageLinks[0]['rev']
1858 $newMessageRevision = $newMessageLinks[0]['rev'];
1859 $newMessageRevisionId = $newMessageRevision->getId();
1862 return $newMessageRevisionId;
1866 * Internal uncached check for new messages
1868 * @see getNewtalk()
1869 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1870 * @param string|int $id User's IP address for anonymous users, User ID otherwise
1871 * @param bool $fromMaster true to fetch from the master, false for a slave
1872 * @return bool True if the user has new messages
1874 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
1875 if ( $fromMaster ) {
1876 $db = wfGetDB( DB_MASTER );
1877 } else {
1878 $db = wfGetDB( DB_SLAVE );
1880 $ok = $db->selectField( 'user_newtalk', $field,
1881 array( $field => $id ), __METHOD__ );
1882 return $ok !== false;
1886 * Add or update the new messages flag
1887 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1888 * @param string|int $id User's IP address for anonymous users, User ID otherwise
1889 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null.
1890 * @return bool True if successful, false otherwise
1892 protected function updateNewtalk( $field, $id, $curRev = null ) {
1893 // Get timestamp of the talk page revision prior to the current one
1894 $prevRev = $curRev ? $curRev->getPrevious() : false;
1895 $ts = $prevRev ? $prevRev->getTimestamp() : null;
1896 // Mark the user as having new messages since this revision
1897 $dbw = wfGetDB( DB_MASTER );
1898 $dbw->insert( 'user_newtalk',
1899 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
1900 __METHOD__,
1901 'IGNORE' );
1902 if ( $dbw->affectedRows() ) {
1903 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
1904 return true;
1905 } else {
1906 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
1907 return false;
1912 * Clear the new messages flag for the given user
1913 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1914 * @param string|int $id User's IP address for anonymous users, User ID otherwise
1915 * @return bool True if successful, false otherwise
1917 protected function deleteNewtalk( $field, $id ) {
1918 $dbw = wfGetDB( DB_MASTER );
1919 $dbw->delete( 'user_newtalk',
1920 array( $field => $id ),
1921 __METHOD__ );
1922 if ( $dbw->affectedRows() ) {
1923 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
1924 return true;
1925 } else {
1926 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
1927 return false;
1932 * Update the 'You have new messages!' status.
1933 * @param bool $val Whether the user has new messages
1934 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null or !$val.
1936 public function setNewtalk( $val, $curRev = null ) {
1937 if ( wfReadOnly() ) {
1938 return;
1941 $this->load();
1942 $this->mNewtalk = $val;
1944 if ( $this->isAnon() ) {
1945 $field = 'user_ip';
1946 $id = $this->getName();
1947 } else {
1948 $field = 'user_id';
1949 $id = $this->getId();
1951 global $wgMemc;
1953 if ( $val ) {
1954 $changed = $this->updateNewtalk( $field, $id, $curRev );
1955 } else {
1956 $changed = $this->deleteNewtalk( $field, $id );
1959 if ( $this->isAnon() ) {
1960 // Anons have a separate memcached space, since
1961 // user records aren't kept for them.
1962 $key = wfMemcKey( 'newtalk', 'ip', $id );
1963 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
1965 if ( $changed ) {
1966 $this->invalidateCache();
1971 * Generate a current or new-future timestamp to be stored in the
1972 * user_touched field when we update things.
1973 * @return string Timestamp in TS_MW format
1975 private static function newTouchedTimestamp() {
1976 global $wgClockSkewFudge;
1977 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1981 * Clear user data from memcached.
1982 * Use after applying fun updates to the database; caller's
1983 * responsibility to update user_touched if appropriate.
1985 * Called implicitly from invalidateCache() and saveSettings().
1987 private function clearSharedCache() {
1988 $this->load();
1989 if ( $this->mId ) {
1990 global $wgMemc;
1991 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1996 * Immediately touch the user data cache for this account.
1997 * Updates user_touched field, and removes account data from memcached
1998 * for reload on the next hit.
2000 public function invalidateCache() {
2001 if ( wfReadOnly() ) {
2002 return;
2004 $this->load();
2005 if ( $this->mId ) {
2006 $this->mTouched = self::newTouchedTimestamp();
2008 $dbw = wfGetDB( DB_MASTER );
2009 $userid = $this->mId;
2010 $touched = $this->mTouched;
2011 $method = __METHOD__;
2012 $dbw->onTransactionIdle( function() use ( $dbw, $userid, $touched, $method ) {
2013 // Prevent contention slams by checking user_touched first
2014 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2015 $needsPurge = $dbw->selectField( 'user', '1',
2016 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2017 if ( $needsPurge ) {
2018 $dbw->update( 'user',
2019 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2020 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2021 $method
2024 } );
2025 $this->clearSharedCache();
2030 * Validate the cache for this account.
2031 * @param string $timestamp A timestamp in TS_MW format
2032 * @return bool
2034 public function validateCache( $timestamp ) {
2035 $this->load();
2036 return ( $timestamp >= $this->mTouched );
2040 * Get the user touched timestamp
2041 * @return string timestamp
2043 public function getTouched() {
2044 $this->load();
2045 return $this->mTouched;
2049 * Set the password and reset the random token.
2050 * Calls through to authentication plugin if necessary;
2051 * will have no effect if the auth plugin refuses to
2052 * pass the change through or if the legal password
2053 * checks fail.
2055 * As a special case, setting the password to null
2056 * wipes it, so the account cannot be logged in until
2057 * a new password is set, for instance via e-mail.
2059 * @param string $str New password to set
2060 * @throws PasswordError on failure
2062 * @return bool
2064 public function setPassword( $str ) {
2065 global $wgAuth;
2067 if ( $str !== null ) {
2068 if ( !$wgAuth->allowPasswordChange() ) {
2069 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2072 if ( !$this->isValidPassword( $str ) ) {
2073 global $wgMinimalPasswordLength;
2074 $valid = $this->getPasswordValidity( $str );
2075 if ( is_array( $valid ) ) {
2076 $message = array_shift( $valid );
2077 $params = $valid;
2078 } else {
2079 $message = $valid;
2080 $params = array( $wgMinimalPasswordLength );
2082 throw new PasswordError( wfMessage( $message, $params )->text() );
2086 if ( !$wgAuth->setPassword( $this, $str ) ) {
2087 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2090 $this->setInternalPassword( $str );
2092 return true;
2096 * Set the password and reset the random token unconditionally.
2098 * @param string|null $str New password to set or null to set an invalid
2099 * password hash meaning that the user will not be able to log in
2100 * through the web interface.
2102 public function setInternalPassword( $str ) {
2103 $this->load();
2104 $this->setToken();
2106 if ( $str === null ) {
2107 // Save an invalid hash...
2108 $this->mPassword = '';
2109 } else {
2110 $this->mPassword = self::crypt( $str );
2112 $this->mNewpassword = '';
2113 $this->mNewpassTime = null;
2117 * Get the user's current token.
2118 * @param bool $forceCreation Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility)
2119 * @return string Token
2121 public function getToken( $forceCreation = true ) {
2122 $this->load();
2123 if ( !$this->mToken && $forceCreation ) {
2124 $this->setToken();
2126 return $this->mToken;
2130 * Set the random token (used for persistent authentication)
2131 * Called from loadDefaults() among other places.
2133 * @param string|bool $token If specified, set the token to this value
2135 public function setToken( $token = false ) {
2136 $this->load();
2137 if ( !$token ) {
2138 $this->mToken = MWCryptRand::generateHex( USER_TOKEN_LENGTH );
2139 } else {
2140 $this->mToken = $token;
2145 * Set the password for a password reminder or new account email
2147 * @param string $str New password to set
2148 * @param bool $throttle If true, reset the throttle timestamp to the present
2150 public function setNewpassword( $str, $throttle = true ) {
2151 $this->load();
2152 $this->mNewpassword = self::crypt( $str );
2153 if ( $throttle ) {
2154 $this->mNewpassTime = wfTimestampNow();
2159 * Has password reminder email been sent within the last
2160 * $wgPasswordReminderResendTime hours?
2161 * @return bool
2163 public function isPasswordReminderThrottled() {
2164 global $wgPasswordReminderResendTime;
2165 $this->load();
2166 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
2167 return false;
2169 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
2170 return time() < $expiry;
2174 * Get the user's e-mail address
2175 * @return string User's email address
2177 public function getEmail() {
2178 $this->load();
2179 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
2180 return $this->mEmail;
2184 * Get the timestamp of the user's e-mail authentication
2185 * @return string TS_MW timestamp
2187 public function getEmailAuthenticationTimestamp() {
2188 $this->load();
2189 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2190 return $this->mEmailAuthenticated;
2194 * Set the user's e-mail address
2195 * @param string $str New e-mail address
2197 public function setEmail( $str ) {
2198 $this->load();
2199 if ( $str == $this->mEmail ) {
2200 return;
2202 $this->mEmail = $str;
2203 $this->invalidateEmail();
2204 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
2208 * Set the user's e-mail address and a confirmation mail if needed.
2210 * @since 1.20
2211 * @param string $str New e-mail address
2212 * @return Status
2214 public function setEmailWithConfirmation( $str ) {
2215 global $wgEnableEmail, $wgEmailAuthentication;
2217 if ( !$wgEnableEmail ) {
2218 return Status::newFatal( 'emaildisabled' );
2221 $oldaddr = $this->getEmail();
2222 if ( $str === $oldaddr ) {
2223 return Status::newGood( true );
2226 $this->setEmail( $str );
2228 if ( $str !== '' && $wgEmailAuthentication ) {
2229 // Send a confirmation request to the new address if needed
2230 $type = $oldaddr != '' ? 'changed' : 'set';
2231 $result = $this->sendConfirmationMail( $type );
2232 if ( $result->isGood() ) {
2233 // Say the the caller that a confirmation mail has been sent
2234 $result->value = 'eauth';
2236 } else {
2237 $result = Status::newGood( true );
2240 return $result;
2244 * Get the user's real name
2245 * @return string User's real name
2247 public function getRealName() {
2248 if ( !$this->isItemLoaded( 'realname' ) ) {
2249 $this->load();
2252 return $this->mRealName;
2256 * Set the user's real name
2257 * @param string $str New real name
2259 public function setRealName( $str ) {
2260 $this->load();
2261 $this->mRealName = $str;
2265 * Get the user's current setting for a given option.
2267 * @param string $oname The option to check
2268 * @param string $defaultOverride A default value returned if the option does not exist
2269 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2270 * @return string User's current value for the option
2271 * @see getBoolOption()
2272 * @see getIntOption()
2274 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2275 global $wgHiddenPrefs;
2276 $this->loadOptions();
2278 # We want 'disabled' preferences to always behave as the default value for
2279 # users, even if they have set the option explicitly in their settings (ie they
2280 # set it, and then it was disabled removing their ability to change it). But
2281 # we don't want to erase the preferences in the database in case the preference
2282 # is re-enabled again. So don't touch $mOptions, just override the returned value
2283 if ( in_array( $oname, $wgHiddenPrefs ) && !$ignoreHidden ) {
2284 return self::getDefaultOption( $oname );
2287 if ( array_key_exists( $oname, $this->mOptions ) ) {
2288 return $this->mOptions[$oname];
2289 } else {
2290 return $defaultOverride;
2295 * Get all user's options
2297 * @return array
2299 public function getOptions() {
2300 global $wgHiddenPrefs;
2301 $this->loadOptions();
2302 $options = $this->mOptions;
2304 # We want 'disabled' preferences to always behave as the default value for
2305 # users, even if they have set the option explicitly in their settings (ie they
2306 # set it, and then it was disabled removing their ability to change it). But
2307 # we don't want to erase the preferences in the database in case the preference
2308 # is re-enabled again. So don't touch $mOptions, just override the returned value
2309 foreach ( $wgHiddenPrefs as $pref ) {
2310 $default = self::getDefaultOption( $pref );
2311 if ( $default !== null ) {
2312 $options[$pref] = $default;
2316 return $options;
2320 * Get the user's current setting for a given option, as a boolean value.
2322 * @param string $oname The option to check
2323 * @return bool User's current value for the option
2324 * @see getOption()
2326 public function getBoolOption( $oname ) {
2327 return (bool)$this->getOption( $oname );
2331 * Get the user's current setting for a given option, as a boolean value.
2333 * @param string $oname The option to check
2334 * @param int $defaultOverride A default value returned if the option does not exist
2335 * @return int User's current value for the option
2336 * @see getOption()
2338 public function getIntOption( $oname, $defaultOverride = 0 ) {
2339 $val = $this->getOption( $oname );
2340 if ( $val == '' ) {
2341 $val = $defaultOverride;
2343 return intval( $val );
2347 * Set the given option for a user.
2349 * @param string $oname The option to set
2350 * @param mixed $val New value to set
2352 public function setOption( $oname, $val ) {
2353 $this->loadOptions();
2355 // Explicitly NULL values should refer to defaults
2356 if ( is_null( $val ) ) {
2357 $val = self::getDefaultOption( $oname );
2360 $this->mOptions[$oname] = $val;
2364 * Return a list of the types of user options currently returned by
2365 * User::getOptionKinds().
2367 * Currently, the option kinds are:
2368 * - 'registered' - preferences which are registered in core MediaWiki or
2369 * by extensions using the UserGetDefaultOptions hook.
2370 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2371 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2372 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2373 * be used by user scripts.
2374 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2375 * These are usually legacy options, removed in newer versions.
2377 * The API (and possibly others) use this function to determine the possible
2378 * option types for validation purposes, so make sure to update this when a
2379 * new option kind is added.
2381 * @see User::getOptionKinds
2382 * @return array Option kinds
2384 public static function listOptionKinds() {
2385 return array(
2386 'registered',
2387 'registered-multiselect',
2388 'registered-checkmatrix',
2389 'userjs',
2390 'unused'
2395 * Return an associative array mapping preferences keys to the kind of a preference they're
2396 * used for. Different kinds are handled differently when setting or reading preferences.
2398 * See User::listOptionKinds for the list of valid option types that can be provided.
2400 * @see User::listOptionKinds
2401 * @param $context IContextSource
2402 * @param array $options assoc. array with options keys to check as keys. Defaults to $this->mOptions.
2403 * @return array the key => kind mapping data
2405 public function getOptionKinds( IContextSource $context, $options = null ) {
2406 $this->loadOptions();
2407 if ( $options === null ) {
2408 $options = $this->mOptions;
2411 $prefs = Preferences::getPreferences( $this, $context );
2412 $mapping = array();
2414 // Multiselect and checkmatrix options are stored in the database with
2415 // one key per option, each having a boolean value. Extract those keys.
2416 $multiselectOptions = array();
2417 foreach ( $prefs as $name => $info ) {
2418 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2419 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2420 $opts = HTMLFormField::flattenOptions( $info['options'] );
2421 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2423 foreach ( $opts as $value ) {
2424 $multiselectOptions["$prefix$value"] = true;
2427 unset( $prefs[$name] );
2430 $checkmatrixOptions = array();
2431 foreach ( $prefs as $name => $info ) {
2432 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2433 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2434 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2435 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2436 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2438 foreach ( $columns as $column ) {
2439 foreach ( $rows as $row ) {
2440 $checkmatrixOptions["$prefix-$column-$row"] = true;
2444 unset( $prefs[$name] );
2448 // $value is ignored
2449 foreach ( $options as $key => $value ) {
2450 if ( isset( $prefs[$key] ) ) {
2451 $mapping[$key] = 'registered';
2452 } elseif ( isset( $multiselectOptions[$key] ) ) {
2453 $mapping[$key] = 'registered-multiselect';
2454 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2455 $mapping[$key] = 'registered-checkmatrix';
2456 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2457 $mapping[$key] = 'userjs';
2458 } else {
2459 $mapping[$key] = 'unused';
2463 return $mapping;
2467 * Reset certain (or all) options to the site defaults
2469 * The optional parameter determines which kinds of preferences will be reset.
2470 * Supported values are everything that can be reported by getOptionKinds()
2471 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2473 * @param array|string $resetKinds which kinds of preferences to reset. Defaults to
2474 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2475 * for backwards-compatibility.
2476 * @param $context IContextSource|null context source used when $resetKinds
2477 * does not contain 'all', passed to getOptionKinds().
2478 * Defaults to RequestContext::getMain() when null.
2480 public function resetOptions(
2481 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2482 IContextSource $context = null
2484 $this->load();
2485 $defaultOptions = self::getDefaultOptions();
2487 if ( !is_array( $resetKinds ) ) {
2488 $resetKinds = array( $resetKinds );
2491 if ( in_array( 'all', $resetKinds ) ) {
2492 $newOptions = $defaultOptions;
2493 } else {
2494 if ( $context === null ) {
2495 $context = RequestContext::getMain();
2498 $optionKinds = $this->getOptionKinds( $context );
2499 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2500 $newOptions = array();
2502 // Use default values for the options that should be deleted, and
2503 // copy old values for the ones that shouldn't.
2504 foreach ( $this->mOptions as $key => $value ) {
2505 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2506 if ( array_key_exists( $key, $defaultOptions ) ) {
2507 $newOptions[$key] = $defaultOptions[$key];
2509 } else {
2510 $newOptions[$key] = $value;
2515 $this->mOptions = $newOptions;
2516 $this->mOptionsLoaded = true;
2520 * Get the user's preferred date format.
2521 * @return string User's preferred date format
2523 public function getDatePreference() {
2524 // Important migration for old data rows
2525 if ( is_null( $this->mDatePreference ) ) {
2526 global $wgLang;
2527 $value = $this->getOption( 'date' );
2528 $map = $wgLang->getDatePreferenceMigrationMap();
2529 if ( isset( $map[$value] ) ) {
2530 $value = $map[$value];
2532 $this->mDatePreference = $value;
2534 return $this->mDatePreference;
2538 * Get the user preferred stub threshold
2540 * @return int
2542 public function getStubThreshold() {
2543 global $wgMaxArticleSize; # Maximum article size, in Kb
2544 $threshold = $this->getIntOption( 'stubthreshold' );
2545 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2546 // If they have set an impossible value, disable the preference
2547 // so we can use the parser cache again.
2548 $threshold = 0;
2550 return $threshold;
2554 * Get the permissions this user has.
2555 * @return Array of String permission names
2557 public function getRights() {
2558 if ( is_null( $this->mRights ) ) {
2559 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2560 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2561 // Force reindexation of rights when a hook has unset one of them
2562 $this->mRights = array_values( array_unique( $this->mRights ) );
2564 return $this->mRights;
2568 * Get the list of explicit group memberships this user has.
2569 * The implicit * and user groups are not included.
2570 * @return Array of String internal group names
2572 public function getGroups() {
2573 $this->load();
2574 $this->loadGroups();
2575 return $this->mGroups;
2579 * Get the list of implicit group memberships this user has.
2580 * This includes all explicit groups, plus 'user' if logged in,
2581 * '*' for all accounts, and autopromoted groups
2582 * @param bool $recache Whether to avoid the cache
2583 * @return Array of String internal group names
2585 public function getEffectiveGroups( $recache = false ) {
2586 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2587 wfProfileIn( __METHOD__ );
2588 $this->mEffectiveGroups = array_unique( array_merge(
2589 $this->getGroups(), // explicit groups
2590 $this->getAutomaticGroups( $recache ) // implicit groups
2591 ) );
2592 // Hook for additional groups
2593 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2594 // Force reindexation of groups when a hook has unset one of them
2595 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
2596 wfProfileOut( __METHOD__ );
2598 return $this->mEffectiveGroups;
2602 * Get the list of implicit group memberships this user has.
2603 * This includes 'user' if logged in, '*' for all accounts,
2604 * and autopromoted groups
2605 * @param bool $recache Whether to avoid the cache
2606 * @return Array of String internal group names
2608 public function getAutomaticGroups( $recache = false ) {
2609 if ( $recache || is_null( $this->mImplicitGroups ) ) {
2610 wfProfileIn( __METHOD__ );
2611 $this->mImplicitGroups = array( '*' );
2612 if ( $this->getId() ) {
2613 $this->mImplicitGroups[] = 'user';
2615 $this->mImplicitGroups = array_unique( array_merge(
2616 $this->mImplicitGroups,
2617 Autopromote::getAutopromoteGroups( $this )
2618 ) );
2620 if ( $recache ) {
2621 // Assure data consistency with rights/groups,
2622 // as getEffectiveGroups() depends on this function
2623 $this->mEffectiveGroups = null;
2625 wfProfileOut( __METHOD__ );
2627 return $this->mImplicitGroups;
2631 * Returns the groups the user has belonged to.
2633 * The user may still belong to the returned groups. Compare with getGroups().
2635 * The function will not return groups the user had belonged to before MW 1.17
2637 * @return array Names of the groups the user has belonged to.
2639 public function getFormerGroups() {
2640 if ( is_null( $this->mFormerGroups ) ) {
2641 $dbr = wfGetDB( DB_MASTER );
2642 $res = $dbr->select( 'user_former_groups',
2643 array( 'ufg_group' ),
2644 array( 'ufg_user' => $this->mId ),
2645 __METHOD__ );
2646 $this->mFormerGroups = array();
2647 foreach ( $res as $row ) {
2648 $this->mFormerGroups[] = $row->ufg_group;
2651 return $this->mFormerGroups;
2655 * Get the user's edit count.
2656 * @return int
2658 public function getEditCount() {
2659 if ( !$this->getId() ) {
2660 return null;
2663 if ( !isset( $this->mEditCount ) ) {
2664 /* Populate the count, if it has not been populated yet */
2665 wfProfileIn( __METHOD__ );
2666 $dbr = wfGetDB( DB_SLAVE );
2667 // check if the user_editcount field has been initialized
2668 $count = $dbr->selectField(
2669 'user', 'user_editcount',
2670 array( 'user_id' => $this->mId ),
2671 __METHOD__
2674 if ( $count === null ) {
2675 // it has not been initialized. do so.
2676 $count = $this->initEditCount();
2678 $this->mEditCount = intval( $count );
2679 wfProfileOut( __METHOD__ );
2681 return $this->mEditCount;
2685 * Add the user to the given group.
2686 * This takes immediate effect.
2687 * @param string $group Name of the group to add
2689 public function addGroup( $group ) {
2690 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2691 $dbw = wfGetDB( DB_MASTER );
2692 if ( $this->getId() ) {
2693 $dbw->insert( 'user_groups',
2694 array(
2695 'ug_user' => $this->getID(),
2696 'ug_group' => $group,
2698 __METHOD__,
2699 array( 'IGNORE' ) );
2702 $this->loadGroups();
2703 $this->mGroups[] = $group;
2704 // In case loadGroups was not called before, we now have the right twice.
2705 // Get rid of the duplicate.
2706 $this->mGroups = array_unique( $this->mGroups );
2707 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2709 $this->invalidateCache();
2713 * Remove the user from the given group.
2714 * This takes immediate effect.
2715 * @param string $group Name of the group to remove
2717 public function removeGroup( $group ) {
2718 $this->load();
2719 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2720 $dbw = wfGetDB( DB_MASTER );
2721 $dbw->delete( 'user_groups',
2722 array(
2723 'ug_user' => $this->getID(),
2724 'ug_group' => $group,
2725 ), __METHOD__ );
2726 // Remember that the user was in this group
2727 $dbw->insert( 'user_former_groups',
2728 array(
2729 'ufg_user' => $this->getID(),
2730 'ufg_group' => $group,
2732 __METHOD__,
2733 array( 'IGNORE' ) );
2735 $this->loadGroups();
2736 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2737 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2739 $this->invalidateCache();
2743 * Get whether the user is logged in
2744 * @return bool
2746 public function isLoggedIn() {
2747 return $this->getID() != 0;
2751 * Get whether the user is anonymous
2752 * @return bool
2754 public function isAnon() {
2755 return !$this->isLoggedIn();
2759 * Check if user is allowed to access a feature / make an action
2761 * @internal param \String $varargs permissions to test
2762 * @return boolean: True if user is allowed to perform *any* of the given actions
2764 * @return bool
2766 public function isAllowedAny( /*...*/ ) {
2767 $permissions = func_get_args();
2768 foreach ( $permissions as $permission ) {
2769 if ( $this->isAllowed( $permission ) ) {
2770 return true;
2773 return false;
2778 * @internal param $varargs string
2779 * @return bool True if the user is allowed to perform *all* of the given actions
2781 public function isAllowedAll( /*...*/ ) {
2782 $permissions = func_get_args();
2783 foreach ( $permissions as $permission ) {
2784 if ( !$this->isAllowed( $permission ) ) {
2785 return false;
2788 return true;
2792 * Internal mechanics of testing a permission
2793 * @param string $action
2794 * @return bool
2796 public function isAllowed( $action = '' ) {
2797 if ( $action === '' ) {
2798 return true; // In the spirit of DWIM
2800 // Patrolling may not be enabled
2801 if ( $action === 'patrol' || $action === 'autopatrol' ) {
2802 global $wgUseRCPatrol, $wgUseNPPatrol;
2803 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
2804 return false;
2807 // Use strict parameter to avoid matching numeric 0 accidentally inserted
2808 // by misconfiguration: 0 == 'foo'
2809 return in_array( $action, $this->getRights(), true );
2813 * Check whether to enable recent changes patrol features for this user
2814 * @return boolean: True or false
2816 public function useRCPatrol() {
2817 global $wgUseRCPatrol;
2818 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
2822 * Check whether to enable new pages patrol features for this user
2823 * @return bool True or false
2825 public function useNPPatrol() {
2826 global $wgUseRCPatrol, $wgUseNPPatrol;
2827 return (
2828 ( $wgUseRCPatrol || $wgUseNPPatrol )
2829 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
2834 * Get the WebRequest object to use with this object
2836 * @return WebRequest
2838 public function getRequest() {
2839 if ( $this->mRequest ) {
2840 return $this->mRequest;
2841 } else {
2842 global $wgRequest;
2843 return $wgRequest;
2848 * Get the current skin, loading it if required
2849 * @return Skin The current skin
2850 * @todo FIXME: Need to check the old failback system [AV]
2851 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
2853 public function getSkin() {
2854 wfDeprecated( __METHOD__, '1.18' );
2855 return RequestContext::getMain()->getSkin();
2859 * Get a WatchedItem for this user and $title.
2861 * @param $title Title
2862 * @return WatchedItem
2864 public function getWatchedItem( $title ) {
2865 $key = $title->getNamespace() . ':' . $title->getDBkey();
2867 if ( isset( $this->mWatchedItems[$key] ) ) {
2868 return $this->mWatchedItems[$key];
2871 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
2872 $this->mWatchedItems = array();
2875 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title );
2876 return $this->mWatchedItems[$key];
2880 * Check the watched status of an article.
2881 * @param $title Title of the article to look at
2882 * @return bool
2884 public function isWatched( $title ) {
2885 return $this->getWatchedItem( $title )->isWatched();
2889 * Watch an article.
2890 * @param $title Title of the article to look at
2892 public function addWatch( $title ) {
2893 $this->getWatchedItem( $title )->addWatch();
2894 $this->invalidateCache();
2898 * Stop watching an article.
2899 * @param $title Title of the article to look at
2901 public function removeWatch( $title ) {
2902 $this->getWatchedItem( $title )->removeWatch();
2903 $this->invalidateCache();
2907 * Clear the user's notification timestamp for the given title.
2908 * If e-notif e-mails are on, they will receive notification mails on
2909 * the next change of the page if it's watched etc.
2910 * @param $title Title of the article to look at
2912 public function clearNotification( &$title ) {
2913 global $wgUseEnotif, $wgShowUpdatedMarker;
2915 // Do nothing if the database is locked to writes
2916 if ( wfReadOnly() ) {
2917 return;
2920 if ( $title->getNamespace() == NS_USER_TALK &&
2921 $title->getText() == $this->getName() ) {
2922 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) ) {
2923 return;
2925 $this->setNewtalk( false );
2928 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2929 return;
2932 if ( $this->isAnon() ) {
2933 // Nothing else to do...
2934 return;
2937 // Only update the timestamp if the page is being watched.
2938 // The query to find out if it is watched is cached both in memcached and per-invocation,
2939 // and when it does have to be executed, it can be on a slave
2940 // If this is the user's newtalk page, we always update the timestamp
2941 $force = '';
2942 if ( $title->getNamespace() == NS_USER_TALK &&
2943 $title->getText() == $this->getName() )
2945 $force = 'force';
2948 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force );
2952 * Resets all of the given user's page-change notification timestamps.
2953 * If e-notif e-mails are on, they will receive notification mails on
2954 * the next change of any watched page.
2956 public function clearAllNotifications() {
2957 if ( wfReadOnly() ) {
2958 return;
2961 global $wgUseEnotif, $wgShowUpdatedMarker;
2962 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2963 $this->setNewtalk( false );
2964 return;
2966 $id = $this->getId();
2967 if ( $id != 0 ) {
2968 $dbw = wfGetDB( DB_MASTER );
2969 $dbw->update( 'watchlist',
2970 array( /* SET */
2971 'wl_notificationtimestamp' => null
2972 ), array( /* WHERE */
2973 'wl_user' => $id
2974 ), __METHOD__
2976 # We also need to clear here the "you have new message" notification for the own user_talk page
2977 # This is cleared one page view later in Article::viewUpdates();
2982 * Set this user's options from an encoded string
2983 * @param string $str Encoded options to import
2985 * @deprecated in 1.19 due to removal of user_options from the user table
2987 private function decodeOptions( $str ) {
2988 wfDeprecated( __METHOD__, '1.19' );
2989 if ( !$str ) {
2990 return;
2993 $this->mOptionsLoaded = true;
2994 $this->mOptionOverrides = array();
2996 // If an option is not set in $str, use the default value
2997 $this->mOptions = self::getDefaultOptions();
2999 $a = explode( "\n", $str );
3000 foreach ( $a as $s ) {
3001 $m = array();
3002 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
3003 $this->mOptions[$m[1]] = $m[2];
3004 $this->mOptionOverrides[$m[1]] = $m[2];
3010 * Set a cookie on the user's client. Wrapper for
3011 * WebResponse::setCookie
3012 * @param string $name Name of the cookie to set
3013 * @param string $value Value to set
3014 * @param int $exp Expiration time, as a UNIX time value;
3015 * if 0 or not specified, use the default $wgCookieExpiration
3016 * @param bool $secure
3017 * true: Force setting the secure attribute when setting the cookie
3018 * false: Force NOT setting the secure attribute when setting the cookie
3019 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3021 protected function setCookie( $name, $value, $exp = 0, $secure = null ) {
3022 $this->getRequest()->response()->setcookie( $name, $value, $exp, null, null, $secure );
3026 * Clear a cookie on the user's client
3027 * @param string $name Name of the cookie to clear
3029 protected function clearCookie( $name ) {
3030 $this->setCookie( $name, '', time() - 86400 );
3034 * Set the default cookies for this session on the user's client.
3036 * @param $request WebRequest object to use; $wgRequest will be used if null
3037 * is passed.
3038 * @param bool $secure Whether to force secure/insecure cookies or use default
3040 public function setCookies( $request = null, $secure = null ) {
3041 if ( $request === null ) {
3042 $request = $this->getRequest();
3045 $this->load();
3046 if ( 0 == $this->mId ) {
3047 return;
3049 if ( !$this->mToken ) {
3050 // When token is empty or NULL generate a new one and then save it to the database
3051 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3052 // Simply by setting every cell in the user_token column to NULL and letting them be
3053 // regenerated as users log back into the wiki.
3054 $this->setToken();
3055 $this->saveSettings();
3057 $session = array(
3058 'wsUserID' => $this->mId,
3059 'wsToken' => $this->mToken,
3060 'wsUserName' => $this->getName()
3062 $cookies = array(
3063 'UserID' => $this->mId,
3064 'UserName' => $this->getName(),
3066 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
3067 $cookies['Token'] = $this->mToken;
3068 } else {
3069 $cookies['Token'] = false;
3072 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3074 foreach ( $session as $name => $value ) {
3075 $request->setSessionData( $name, $value );
3077 foreach ( $cookies as $name => $value ) {
3078 if ( $value === false ) {
3079 $this->clearCookie( $name );
3080 } else {
3081 $this->setCookie( $name, $value, 0, $secure );
3086 * If wpStickHTTPS was selected, also set an insecure cookie that
3087 * will cause the site to redirect the user to HTTPS, if they access
3088 * it over HTTP. Bug 29898.
3090 if ( $request->getCheck( 'wpStickHTTPS' ) ) {
3091 $this->setCookie( 'forceHTTPS', 'true', time() + 2592000, false ); //30 days
3096 * Log this user out.
3098 public function logout() {
3099 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3100 $this->doLogout();
3105 * Clear the user's cookies and session, and reset the instance cache.
3106 * @see logout()
3108 public function doLogout() {
3109 $this->clearInstanceCache( 'defaults' );
3111 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3113 $this->clearCookie( 'UserID' );
3114 $this->clearCookie( 'Token' );
3115 $this->clearCookie( 'forceHTTPS' );
3117 // Remember when user logged out, to prevent seeing cached pages
3118 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
3122 * Save this user's settings into the database.
3123 * @todo Only rarely do all these fields need to be set!
3125 public function saveSettings() {
3126 global $wgAuth;
3128 $this->load();
3129 if ( wfReadOnly() ) {
3130 return;
3132 if ( 0 == $this->mId ) {
3133 return;
3136 $this->mTouched = self::newTouchedTimestamp();
3137 if ( !$wgAuth->allowSetLocalPassword() ) {
3138 $this->mPassword = '';
3141 $dbw = wfGetDB( DB_MASTER );
3142 $dbw->update( 'user',
3143 array( /* SET */
3144 'user_name' => $this->mName,
3145 'user_password' => $this->mPassword,
3146 'user_newpassword' => $this->mNewpassword,
3147 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3148 'user_real_name' => $this->mRealName,
3149 'user_email' => $this->mEmail,
3150 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3151 'user_touched' => $dbw->timestamp( $this->mTouched ),
3152 'user_token' => strval( $this->mToken ),
3153 'user_email_token' => $this->mEmailToken,
3154 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3155 ), array( /* WHERE */
3156 'user_id' => $this->mId
3157 ), __METHOD__
3160 $this->saveOptions();
3162 wfRunHooks( 'UserSaveSettings', array( $this ) );
3163 $this->clearSharedCache();
3164 $this->getUserPage()->invalidateCache();
3168 * If only this user's username is known, and it exists, return the user ID.
3169 * @return int
3171 public function idForName() {
3172 $s = trim( $this->getName() );
3173 if ( $s === '' ) {
3174 return 0;
3177 $dbr = wfGetDB( DB_SLAVE );
3178 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
3179 if ( $id === false ) {
3180 $id = 0;
3182 return $id;
3186 * Add a user to the database, return the user object
3188 * @param string $name Username to add
3189 * @param array $params of Strings Non-default parameters to save to the database as user_* fields:
3190 * - password The user's password hash. Password logins will be disabled if this is omitted.
3191 * - newpassword Hash for a temporary password that has been mailed to the user
3192 * - email The user's email address
3193 * - email_authenticated The email authentication timestamp
3194 * - real_name The user's real name
3195 * - options An associative array of non-default options
3196 * - token Random authentication token. Do not set.
3197 * - registration Registration timestamp. Do not set.
3199 * @return User object, or null if the username already exists
3201 public static function createNew( $name, $params = array() ) {
3202 $user = new User;
3203 $user->load();
3204 $user->setToken(); // init token
3205 if ( isset( $params['options'] ) ) {
3206 $user->mOptions = $params['options'] + (array)$user->mOptions;
3207 unset( $params['options'] );
3209 $dbw = wfGetDB( DB_MASTER );
3210 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3212 $fields = array(
3213 'user_id' => $seqVal,
3214 'user_name' => $name,
3215 'user_password' => $user->mPassword,
3216 'user_newpassword' => $user->mNewpassword,
3217 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3218 'user_email' => $user->mEmail,
3219 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3220 'user_real_name' => $user->mRealName,
3221 'user_token' => strval( $user->mToken ),
3222 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3223 'user_editcount' => 0,
3224 'user_touched' => $dbw->timestamp( self::newTouchedTimestamp() ),
3226 foreach ( $params as $name => $value ) {
3227 $fields["user_$name"] = $value;
3229 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3230 if ( $dbw->affectedRows() ) {
3231 $newUser = User::newFromId( $dbw->insertId() );
3232 } else {
3233 $newUser = null;
3235 return $newUser;
3239 * Add this existing user object to the database. If the user already
3240 * exists, a fatal status object is returned, and the user object is
3241 * initialised with the data from the database.
3243 * Previously, this function generated a DB error due to a key conflict
3244 * if the user already existed. Many extension callers use this function
3245 * in code along the lines of:
3247 * $user = User::newFromName( $name );
3248 * if ( !$user->isLoggedIn() ) {
3249 * $user->addToDatabase();
3251 * // do something with $user...
3253 * However, this was vulnerable to a race condition (bug 16020). By
3254 * initialising the user object if the user exists, we aim to support this
3255 * calling sequence as far as possible.
3257 * Note that if the user exists, this function will acquire a write lock,
3258 * so it is still advisable to make the call conditional on isLoggedIn(),
3259 * and to commit the transaction after calling.
3261 * @throws MWException
3262 * @return Status
3264 public function addToDatabase() {
3265 $this->load();
3266 if ( !$this->mToken ) {
3267 $this->setToken(); // init token
3270 $this->mTouched = self::newTouchedTimestamp();
3272 $dbw = wfGetDB( DB_MASTER );
3273 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3274 $dbw->insert( 'user',
3275 array(
3276 'user_id' => $seqVal,
3277 'user_name' => $this->mName,
3278 'user_password' => $this->mPassword,
3279 'user_newpassword' => $this->mNewpassword,
3280 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3281 'user_email' => $this->mEmail,
3282 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3283 'user_real_name' => $this->mRealName,
3284 'user_token' => strval( $this->mToken ),
3285 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3286 'user_editcount' => 0,
3287 'user_touched' => $dbw->timestamp( $this->mTouched ),
3288 ), __METHOD__,
3289 array( 'IGNORE' )
3291 if ( !$dbw->affectedRows() ) {
3292 $this->mId = $dbw->selectField( 'user', 'user_id',
3293 array( 'user_name' => $this->mName ), __METHOD__ );
3294 $loaded = false;
3295 if ( $this->mId ) {
3296 if ( $this->loadFromDatabase() ) {
3297 $loaded = true;
3300 if ( !$loaded ) {
3301 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3302 "to insert user '{$this->mName}' row, but it was not present in select!" );
3304 return Status::newFatal( 'userexists' );
3306 $this->mId = $dbw->insertId();
3308 // Clear instance cache other than user table data, which is already accurate
3309 $this->clearInstanceCache();
3311 $this->saveOptions();
3312 return Status::newGood();
3316 * If this user is logged-in and blocked,
3317 * block any IP address they've successfully logged in from.
3318 * @return bool A block was spread
3320 public function spreadAnyEditBlock() {
3321 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3322 return $this->spreadBlock();
3324 return false;
3328 * If this (non-anonymous) user is blocked,
3329 * block the IP address they've successfully logged in from.
3330 * @return bool A block was spread
3332 protected function spreadBlock() {
3333 wfDebug( __METHOD__ . "()\n" );
3334 $this->load();
3335 if ( $this->mId == 0 ) {
3336 return false;
3339 $userblock = Block::newFromTarget( $this->getName() );
3340 if ( !$userblock ) {
3341 return false;
3344 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3348 * Generate a string which will be different for any combination of
3349 * user options which would produce different parser output.
3350 * This will be used as part of the hash key for the parser cache,
3351 * so users with the same options can share the same cached data
3352 * safely.
3354 * Extensions which require it should install 'PageRenderingHash' hook,
3355 * which will give them a chance to modify this key based on their own
3356 * settings.
3358 * @deprecated since 1.17 use the ParserOptions object to get the relevant options
3359 * @return string Page rendering hash
3361 public function getPageRenderingHash() {
3362 wfDeprecated( __METHOD__, '1.17' );
3364 global $wgRenderHashAppend, $wgLang, $wgContLang;
3365 if ( $this->mHash ) {
3366 return $this->mHash;
3369 // stubthreshold is only included below for completeness,
3370 // since it disables the parser cache, its value will always
3371 // be 0 when this function is called by parsercache.
3373 $confstr = $this->getOption( 'math' );
3374 $confstr .= '!' . $this->getStubThreshold();
3375 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ? '1' : '' );
3376 $confstr .= '!' . $wgLang->getCode();
3377 $confstr .= '!' . $this->getOption( 'thumbsize' );
3378 // add in language specific options, if any
3379 $extra = $wgContLang->getExtraHashOptions();
3380 $confstr .= $extra;
3382 // Since the skin could be overloading link(), it should be
3383 // included here but in practice, none of our skins do that.
3385 $confstr .= $wgRenderHashAppend;
3387 // Give a chance for extensions to modify the hash, if they have
3388 // extra options or other effects on the parser cache.
3389 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
3391 // Make it a valid memcached key fragment
3392 $confstr = str_replace( ' ', '_', $confstr );
3393 $this->mHash = $confstr;
3394 return $confstr;
3398 * Get whether the user is explicitly blocked from account creation.
3399 * @return bool|Block
3401 public function isBlockedFromCreateAccount() {
3402 $this->getBlockedStatus();
3403 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3404 return $this->mBlock;
3407 # bug 13611: if the IP address the user is trying to create an account from is
3408 # blocked with createaccount disabled, prevent new account creation there even
3409 # when the user is logged in
3410 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3411 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3413 return $this->mBlockedFromCreateAccount instanceof Block && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3414 ? $this->mBlockedFromCreateAccount
3415 : false;
3419 * Get whether the user is blocked from using Special:Emailuser.
3420 * @return bool
3422 public function isBlockedFromEmailuser() {
3423 $this->getBlockedStatus();
3424 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3428 * Get whether the user is allowed to create an account.
3429 * @return bool
3431 function isAllowedToCreateAccount() {
3432 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3436 * Get this user's personal page title.
3438 * @return Title: User's personal page title
3440 public function getUserPage() {
3441 return Title::makeTitle( NS_USER, $this->getName() );
3445 * Get this user's talk page title.
3447 * @return Title: User's talk page title
3449 public function getTalkPage() {
3450 $title = $this->getUserPage();
3451 return $title->getTalkPage();
3455 * Determine whether the user is a newbie. Newbies are either
3456 * anonymous IPs, or the most recently created accounts.
3457 * @return bool
3459 public function isNewbie() {
3460 return !$this->isAllowed( 'autoconfirmed' );
3464 * Check to see if the given clear-text password is one of the accepted passwords
3465 * @param string $password user password.
3466 * @return boolean: True if the given password is correct, otherwise False.
3468 public function checkPassword( $password ) {
3469 global $wgAuth, $wgLegacyEncoding;
3470 $this->load();
3472 // Even though we stop people from creating passwords that
3473 // are shorter than this, doesn't mean people wont be able
3474 // to. Certain authentication plugins do NOT want to save
3475 // domain passwords in a mysql database, so we should
3476 // check this (in case $wgAuth->strict() is false).
3477 if ( !$this->isValidPassword( $password ) ) {
3478 return false;
3481 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3482 return true;
3483 } elseif ( $wgAuth->strict() ) {
3484 // Auth plugin doesn't allow local authentication
3485 return false;
3486 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3487 // Auth plugin doesn't allow local authentication for this user name
3488 return false;
3490 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
3491 return true;
3492 } elseif ( $wgLegacyEncoding ) {
3493 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3494 // Check for this with iconv
3495 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3496 if ( $cp1252Password != $password &&
3497 self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) )
3499 return true;
3502 return false;
3506 * Check if the given clear-text password matches the temporary password
3507 * sent by e-mail for password reset operations.
3509 * @param $plaintext string
3511 * @return boolean: True if matches, false otherwise
3513 public function checkTemporaryPassword( $plaintext ) {
3514 global $wgNewPasswordExpiry;
3516 $this->load();
3517 if ( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
3518 if ( is_null( $this->mNewpassTime ) ) {
3519 return true;
3521 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
3522 return ( time() < $expiry );
3523 } else {
3524 return false;
3529 * Alias for getEditToken.
3530 * @deprecated since 1.19, use getEditToken instead.
3532 * @param string|array $salt of Strings Optional function-specific data for hashing
3533 * @param $request WebRequest object to use or null to use $wgRequest
3534 * @return string The new edit token
3536 public function editToken( $salt = '', $request = null ) {
3537 wfDeprecated( __METHOD__, '1.19' );
3538 return $this->getEditToken( $salt, $request );
3542 * Initialize (if necessary) and return a session token value
3543 * which can be used in edit forms to show that the user's
3544 * login credentials aren't being hijacked with a foreign form
3545 * submission.
3547 * @since 1.19
3549 * @param string|array $salt of Strings Optional function-specific data for hashing
3550 * @param $request WebRequest object to use or null to use $wgRequest
3551 * @return string The new edit token
3553 public function getEditToken( $salt = '', $request = null ) {
3554 if ( $request == null ) {
3555 $request = $this->getRequest();
3558 if ( $this->isAnon() ) {
3559 return EDIT_TOKEN_SUFFIX;
3560 } else {
3561 $token = $request->getSessionData( 'wsEditToken' );
3562 if ( $token === null ) {
3563 $token = MWCryptRand::generateHex( 32 );
3564 $request->setSessionData( 'wsEditToken', $token );
3566 if ( is_array( $salt ) ) {
3567 $salt = implode( '|', $salt );
3569 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
3574 * Generate a looking random token for various uses.
3576 * @return string The new random token
3577 * @deprecated since 1.20: Use MWCryptRand for secure purposes or wfRandomString for pseudo-randomness
3579 public static function generateToken() {
3580 return MWCryptRand::generateHex( 32 );
3584 * Check given value against the token value stored in the session.
3585 * A match should confirm that the form was submitted from the
3586 * user's own login session, not a form submission from a third-party
3587 * site.
3589 * @param string $val Input value to compare
3590 * @param string $salt Optional function-specific data for hashing
3591 * @param WebRequest $request Object to use or null to use $wgRequest
3592 * @return boolean: Whether the token matches
3594 public function matchEditToken( $val, $salt = '', $request = null ) {
3595 $sessionToken = $this->getEditToken( $salt, $request );
3596 if ( $val != $sessionToken ) {
3597 wfDebug( "User::matchEditToken: broken session data\n" );
3599 return $val == $sessionToken;
3603 * Check given value against the token value stored in the session,
3604 * ignoring the suffix.
3606 * @param string $val Input value to compare
3607 * @param string $salt Optional function-specific data for hashing
3608 * @param WebRequest $request object to use or null to use $wgRequest
3609 * @return boolean: Whether the token matches
3611 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3612 $sessionToken = $this->getEditToken( $salt, $request );
3613 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3617 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3618 * mail to the user's given address.
3620 * @param string $type message to send, either "created", "changed" or "set"
3621 * @return Status object
3623 public function sendConfirmationMail( $type = 'created' ) {
3624 global $wgLang;
3625 $expiration = null; // gets passed-by-ref and defined in next line.
3626 $token = $this->confirmationToken( $expiration );
3627 $url = $this->confirmationTokenUrl( $token );
3628 $invalidateURL = $this->invalidationTokenUrl( $token );
3629 $this->saveSettings();
3631 if ( $type == 'created' || $type === false ) {
3632 $message = 'confirmemail_body';
3633 } elseif ( $type === true ) {
3634 $message = 'confirmemail_body_changed';
3635 } else {
3636 $message = 'confirmemail_body_' . $type;
3639 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3640 wfMessage( $message,
3641 $this->getRequest()->getIP(),
3642 $this->getName(),
3643 $url,
3644 $wgLang->timeanddate( $expiration, false ),
3645 $invalidateURL,
3646 $wgLang->date( $expiration, false ),
3647 $wgLang->time( $expiration, false ) )->text() );
3651 * Send an e-mail to this user's account. Does not check for
3652 * confirmed status or validity.
3654 * @param string $subject Message subject
3655 * @param string $body Message body
3656 * @param string $from Optional From address; if unspecified, default $wgPasswordSender will be used
3657 * @param string $replyto Reply-To address
3658 * @return Status
3660 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3661 if ( is_null( $from ) ) {
3662 global $wgPasswordSender, $wgPasswordSenderName;
3663 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
3664 } else {
3665 $sender = new MailAddress( $from );
3668 $to = new MailAddress( $this );
3669 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
3673 * Generate, store, and return a new e-mail confirmation code.
3674 * A hash (unsalted, since it's used as a key) is stored.
3676 * @note Call saveSettings() after calling this function to commit
3677 * this change to the database.
3679 * @param &$expiration \mixed Accepts the expiration time
3680 * @return string New token
3682 protected function confirmationToken( &$expiration ) {
3683 global $wgUserEmailConfirmationTokenExpiry;
3684 $now = time();
3685 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
3686 $expiration = wfTimestamp( TS_MW, $expires );
3687 $this->load();
3688 $token = MWCryptRand::generateHex( 32 );
3689 $hash = md5( $token );
3690 $this->mEmailToken = $hash;
3691 $this->mEmailTokenExpires = $expiration;
3692 return $token;
3696 * Return a URL the user can use to confirm their email address.
3697 * @param string $token Accepts the email confirmation token
3698 * @return string New token URL
3700 protected function confirmationTokenUrl( $token ) {
3701 return $this->getTokenUrl( 'ConfirmEmail', $token );
3705 * Return a URL the user can use to invalidate their email address.
3706 * @param string $token Accepts the email confirmation token
3707 * @return string New token URL
3709 protected function invalidationTokenUrl( $token ) {
3710 return $this->getTokenUrl( 'InvalidateEmail', $token );
3714 * Internal function to format the e-mail validation/invalidation URLs.
3715 * This uses a quickie hack to use the
3716 * hardcoded English names of the Special: pages, for ASCII safety.
3718 * @note Since these URLs get dropped directly into emails, using the
3719 * short English names avoids insanely long URL-encoded links, which
3720 * also sometimes can get corrupted in some browsers/mailers
3721 * (bug 6957 with Gmail and Internet Explorer).
3723 * @param string $page Special page
3724 * @param string $token Token
3725 * @return string Formatted URL
3727 protected function getTokenUrl( $page, $token ) {
3728 // Hack to bypass localization of 'Special:'
3729 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
3730 return $title->getCanonicalURL();
3734 * Mark the e-mail address confirmed.
3736 * @note Call saveSettings() after calling this function to commit the change.
3738 * @return bool
3740 public function confirmEmail() {
3741 // Check if it's already confirmed, so we don't touch the database
3742 // and fire the ConfirmEmailComplete hook on redundant confirmations.
3743 if ( !$this->isEmailConfirmed() ) {
3744 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3745 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3747 return true;
3751 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3752 * address if it was already confirmed.
3754 * @note Call saveSettings() after calling this function to commit the change.
3755 * @return bool Returns true
3757 function invalidateEmail() {
3758 $this->load();
3759 $this->mEmailToken = null;
3760 $this->mEmailTokenExpires = null;
3761 $this->setEmailAuthenticationTimestamp( null );
3762 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3763 return true;
3767 * Set the e-mail authentication timestamp.
3768 * @param string $timestamp TS_MW timestamp
3770 function setEmailAuthenticationTimestamp( $timestamp ) {
3771 $this->load();
3772 $this->mEmailAuthenticated = $timestamp;
3773 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
3777 * Is this user allowed to send e-mails within limits of current
3778 * site configuration?
3779 * @return bool
3781 public function canSendEmail() {
3782 global $wgEnableEmail, $wgEnableUserEmail;
3783 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
3784 return false;
3786 $canSend = $this->isEmailConfirmed();
3787 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3788 return $canSend;
3792 * Is this user allowed to receive e-mails within limits of current
3793 * site configuration?
3794 * @return bool
3796 public function canReceiveEmail() {
3797 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3801 * Is this user's e-mail address valid-looking and confirmed within
3802 * limits of the current site configuration?
3804 * @note If $wgEmailAuthentication is on, this may require the user to have
3805 * confirmed their address by returning a code or using a password
3806 * sent to the address from the wiki.
3808 * @return bool
3810 public function isEmailConfirmed() {
3811 global $wgEmailAuthentication;
3812 $this->load();
3813 $confirmed = true;
3814 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3815 if ( $this->isAnon() ) {
3816 return false;
3818 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
3819 return false;
3821 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
3822 return false;
3824 return true;
3825 } else {
3826 return $confirmed;
3831 * Check whether there is an outstanding request for e-mail confirmation.
3832 * @return bool
3834 public function isEmailConfirmationPending() {
3835 global $wgEmailAuthentication;
3836 return $wgEmailAuthentication &&
3837 !$this->isEmailConfirmed() &&
3838 $this->mEmailToken &&
3839 $this->mEmailTokenExpires > wfTimestamp();
3843 * Get the timestamp of account creation.
3845 * @return string|bool|null Timestamp of account creation, false for
3846 * non-existent/anonymous user accounts, or null if existing account
3847 * but information is not in database.
3849 public function getRegistration() {
3850 if ( $this->isAnon() ) {
3851 return false;
3853 $this->load();
3854 return $this->mRegistration;
3858 * Get the timestamp of the first edit
3860 * @return string|bool Timestamp of first edit, or false for
3861 * non-existent/anonymous user accounts.
3863 public function getFirstEditTimestamp() {
3864 if ( $this->getId() == 0 ) {
3865 return false; // anons
3867 $dbr = wfGetDB( DB_SLAVE );
3868 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3869 array( 'rev_user' => $this->getId() ),
3870 __METHOD__,
3871 array( 'ORDER BY' => 'rev_timestamp ASC' )
3873 if ( !$time ) {
3874 return false; // no edits
3876 return wfTimestamp( TS_MW, $time );
3880 * Get the permissions associated with a given list of groups
3882 * @param array $groups of Strings List of internal group names
3883 * @return Array of Strings List of permission key names for given groups combined
3885 public static function getGroupPermissions( $groups ) {
3886 global $wgGroupPermissions, $wgRevokePermissions;
3887 $rights = array();
3888 // grant every granted permission first
3889 foreach ( $groups as $group ) {
3890 if ( isset( $wgGroupPermissions[$group] ) ) {
3891 $rights = array_merge( $rights,
3892 // array_filter removes empty items
3893 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3896 // now revoke the revoked permissions
3897 foreach ( $groups as $group ) {
3898 if ( isset( $wgRevokePermissions[$group] ) ) {
3899 $rights = array_diff( $rights,
3900 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3903 return array_unique( $rights );
3907 * Get all the groups who have a given permission
3909 * @param string $role Role to check
3910 * @return Array of Strings List of internal group names with the given permission
3912 public static function getGroupsWithPermission( $role ) {
3913 global $wgGroupPermissions;
3914 $allowedGroups = array();
3915 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
3916 if ( self::groupHasPermission( $group, $role ) ) {
3917 $allowedGroups[] = $group;
3920 return $allowedGroups;
3924 * Check, if the given group has the given permission
3926 * @since 1.21
3927 * @param string $group Group to check
3928 * @param string $role Role to check
3929 * @return bool
3931 public static function groupHasPermission( $group, $role ) {
3932 global $wgGroupPermissions, $wgRevokePermissions;
3933 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
3934 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
3938 * Get the localized descriptive name for a group, if it exists
3940 * @param string $group Internal group name
3941 * @return string Localized descriptive group name
3943 public static function getGroupName( $group ) {
3944 $msg = wfMessage( "group-$group" );
3945 return $msg->isBlank() ? $group : $msg->text();
3949 * Get the localized descriptive name for a member of a group, if it exists
3951 * @param string $group Internal group name
3952 * @param string $username Username for gender (since 1.19)
3953 * @return string Localized name for group member
3955 public static function getGroupMember( $group, $username = '#' ) {
3956 $msg = wfMessage( "group-$group-member", $username );
3957 return $msg->isBlank() ? $group : $msg->text();
3961 * Return the set of defined explicit groups.
3962 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3963 * are not included, as they are defined automatically, not in the database.
3964 * @return Array of internal group names
3966 public static function getAllGroups() {
3967 global $wgGroupPermissions, $wgRevokePermissions;
3968 return array_diff(
3969 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3970 self::getImplicitGroups()
3975 * Get a list of all available permissions.
3976 * @return Array of permission names
3978 public static function getAllRights() {
3979 if ( self::$mAllRights === false ) {
3980 global $wgAvailableRights;
3981 if ( count( $wgAvailableRights ) ) {
3982 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
3983 } else {
3984 self::$mAllRights = self::$mCoreRights;
3986 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
3988 return self::$mAllRights;
3992 * Get a list of implicit groups
3993 * @return Array of Strings Array of internal group names
3995 public static function getImplicitGroups() {
3996 global $wgImplicitGroups;
3997 $groups = $wgImplicitGroups;
3998 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3999 return $groups;
4003 * Get the title of a page describing a particular group
4005 * @param string $group Internal group name
4006 * @return Title|bool Title of the page if it exists, false otherwise
4008 public static function getGroupPage( $group ) {
4009 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4010 if ( $msg->exists() ) {
4011 $title = Title::newFromText( $msg->text() );
4012 if ( is_object( $title ) ) {
4013 return $title;
4016 return false;
4020 * Create a link to the group in HTML, if available;
4021 * else return the group name.
4023 * @param string $group Internal name of the group
4024 * @param string $text The text of the link
4025 * @return string HTML link to the group
4027 public static function makeGroupLinkHTML( $group, $text = '' ) {
4028 if ( $text == '' ) {
4029 $text = self::getGroupName( $group );
4031 $title = self::getGroupPage( $group );
4032 if ( $title ) {
4033 return Linker::link( $title, htmlspecialchars( $text ) );
4034 } else {
4035 return $text;
4040 * Create a link to the group in Wikitext, if available;
4041 * else return the group name.
4043 * @param string $group Internal name of the group
4044 * @param string $text The text of the link
4045 * @return string Wikilink to the group
4047 public static function makeGroupLinkWiki( $group, $text = '' ) {
4048 if ( $text == '' ) {
4049 $text = self::getGroupName( $group );
4051 $title = self::getGroupPage( $group );
4052 if ( $title ) {
4053 $page = $title->getPrefixedText();
4054 return "[[$page|$text]]";
4055 } else {
4056 return $text;
4061 * Returns an array of the groups that a particular group can add/remove.
4063 * @param string $group the group to check for whether it can add/remove
4064 * @return Array array( 'add' => array( addablegroups ),
4065 * 'remove' => array( removablegroups ),
4066 * 'add-self' => array( addablegroups to self),
4067 * 'remove-self' => array( removable groups from self) )
4069 public static function changeableByGroup( $group ) {
4070 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4072 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
4073 if ( empty( $wgAddGroups[$group] ) ) {
4074 // Don't add anything to $groups
4075 } elseif ( $wgAddGroups[$group] === true ) {
4076 // You get everything
4077 $groups['add'] = self::getAllGroups();
4078 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4079 $groups['add'] = $wgAddGroups[$group];
4082 // Same thing for remove
4083 if ( empty( $wgRemoveGroups[$group] ) ) {
4084 } elseif ( $wgRemoveGroups[$group] === true ) {
4085 $groups['remove'] = self::getAllGroups();
4086 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4087 $groups['remove'] = $wgRemoveGroups[$group];
4090 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4091 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4092 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4093 if ( is_int( $key ) ) {
4094 $wgGroupsAddToSelf['user'][] = $value;
4099 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4100 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4101 if ( is_int( $key ) ) {
4102 $wgGroupsRemoveFromSelf['user'][] = $value;
4107 // Now figure out what groups the user can add to him/herself
4108 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4109 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4110 // No idea WHY this would be used, but it's there
4111 $groups['add-self'] = User::getAllGroups();
4112 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4113 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4116 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4117 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4118 $groups['remove-self'] = User::getAllGroups();
4119 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4120 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4123 return $groups;
4127 * Returns an array of groups that this user can add and remove
4128 * @return Array array( 'add' => array( addablegroups ),
4129 * 'remove' => array( removablegroups ),
4130 * 'add-self' => array( addablegroups to self),
4131 * 'remove-self' => array( removable groups from self) )
4133 public function changeableGroups() {
4134 if ( $this->isAllowed( 'userrights' ) ) {
4135 // This group gives the right to modify everything (reverse-
4136 // compatibility with old "userrights lets you change
4137 // everything")
4138 // Using array_merge to make the groups reindexed
4139 $all = array_merge( User::getAllGroups() );
4140 return array(
4141 'add' => $all,
4142 'remove' => $all,
4143 'add-self' => array(),
4144 'remove-self' => array()
4148 // Okay, it's not so simple, we will have to go through the arrays
4149 $groups = array(
4150 'add' => array(),
4151 'remove' => array(),
4152 'add-self' => array(),
4153 'remove-self' => array()
4155 $addergroups = $this->getEffectiveGroups();
4157 foreach ( $addergroups as $addergroup ) {
4158 $groups = array_merge_recursive(
4159 $groups, $this->changeableByGroup( $addergroup )
4161 $groups['add'] = array_unique( $groups['add'] );
4162 $groups['remove'] = array_unique( $groups['remove'] );
4163 $groups['add-self'] = array_unique( $groups['add-self'] );
4164 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4166 return $groups;
4170 * Increment the user's edit-count field.
4171 * Will have no effect for anonymous users.
4173 public function incEditCount() {
4174 if ( !$this->isAnon() ) {
4175 $dbw = wfGetDB( DB_MASTER );
4176 $dbw->update(
4177 'user',
4178 array( 'user_editcount=user_editcount+1' ),
4179 array( 'user_id' => $this->getId() ),
4180 __METHOD__
4183 // Lazy initialization check...
4184 if ( $dbw->affectedRows() == 0 ) {
4185 // Now here's a goddamn hack...
4186 $dbr = wfGetDB( DB_SLAVE );
4187 if ( $dbr !== $dbw ) {
4188 // If we actually have a slave server, the count is
4189 // at least one behind because the current transaction
4190 // has not been committed and replicated.
4191 $this->initEditCount( 1 );
4192 } else {
4193 // But if DB_SLAVE is selecting the master, then the
4194 // count we just read includes the revision that was
4195 // just added in the working transaction.
4196 $this->initEditCount();
4200 // edit count in user cache too
4201 $this->invalidateCache();
4205 * Initialize user_editcount from data out of the revision table
4207 * @param $add Integer Edits to add to the count from the revision table
4208 * @return integer Number of edits
4210 protected function initEditCount( $add = 0 ) {
4211 // Pull from a slave to be less cruel to servers
4212 // Accuracy isn't the point anyway here
4213 $dbr = wfGetDB( DB_SLAVE );
4214 $count = (int) $dbr->selectField(
4215 'revision',
4216 'COUNT(rev_user)',
4217 array( 'rev_user' => $this->getId() ),
4218 __METHOD__
4220 $count = $count + $add;
4222 $dbw = wfGetDB( DB_MASTER );
4223 $dbw->update(
4224 'user',
4225 array( 'user_editcount' => $count ),
4226 array( 'user_id' => $this->getId() ),
4227 __METHOD__
4230 return $count;
4234 * Get the description of a given right
4236 * @param string $right Right to query
4237 * @return string Localized description of the right
4239 public static function getRightDescription( $right ) {
4240 $key = "right-$right";
4241 $msg = wfMessage( $key );
4242 return $msg->isBlank() ? $right : $msg->text();
4246 * Make an old-style password hash
4248 * @param string $password Plain-text password
4249 * @param string $userId User ID
4250 * @return string Password hash
4252 public static function oldCrypt( $password, $userId ) {
4253 global $wgPasswordSalt;
4254 if ( $wgPasswordSalt ) {
4255 return md5( $userId . '-' . md5( $password ) );
4256 } else {
4257 return md5( $password );
4262 * Make a new-style password hash
4264 * @param string $password Plain-text password
4265 * @param bool|string $salt Optional salt, may be random or the user ID.
4266 * If unspecified or false, will generate one automatically
4267 * @return string Password hash
4269 public static function crypt( $password, $salt = false ) {
4270 global $wgPasswordSalt;
4272 $hash = '';
4273 if ( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4274 return $hash;
4277 if ( $wgPasswordSalt ) {
4278 if ( $salt === false ) {
4279 $salt = MWCryptRand::generateHex( 8 );
4281 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4282 } else {
4283 return ':A:' . md5( $password );
4288 * Compare a password hash with a plain-text password. Requires the user
4289 * ID if there's a chance that the hash is an old-style hash.
4291 * @param string $hash Password hash
4292 * @param string $password Plain-text password to compare
4293 * @param string|bool $userId User ID for old-style password salt
4295 * @return boolean
4297 public static function comparePasswords( $hash, $password, $userId = false ) {
4298 $type = substr( $hash, 0, 3 );
4300 $result = false;
4301 if ( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4302 return $result;
4305 if ( $type == ':A:' ) {
4306 // Unsalted
4307 return md5( $password ) === substr( $hash, 3 );
4308 } elseif ( $type == ':B:' ) {
4309 // Salted
4310 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4311 return md5( $salt . '-' . md5( $password ) ) === $realHash;
4312 } else {
4313 // Old-style
4314 return self::oldCrypt( $password, $userId ) === $hash;
4319 * Add a newuser log entry for this user.
4320 * Before 1.19 the return value was always true.
4322 * @param string|bool $action account creation type.
4323 * - String, one of the following values:
4324 * - 'create' for an anonymous user creating an account for himself.
4325 * This will force the action's performer to be the created user itself,
4326 * no matter the value of $wgUser
4327 * - 'create2' for a logged in user creating an account for someone else
4328 * - 'byemail' when the created user will receive its password by e-mail
4329 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4330 * - Boolean means whether the account was created by e-mail (deprecated):
4331 * - true will be converted to 'byemail'
4332 * - false will be converted to 'create' if this object is the same as
4333 * $wgUser and to 'create2' otherwise
4335 * @param string $reason user supplied reason
4337 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4339 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4340 global $wgUser, $wgNewUserLog;
4341 if ( empty( $wgNewUserLog ) ) {
4342 return true; // disabled
4345 if ( $action === true ) {
4346 $action = 'byemail';
4347 } elseif ( $action === false ) {
4348 if ( $this->getName() == $wgUser->getName() ) {
4349 $action = 'create';
4350 } else {
4351 $action = 'create2';
4355 if ( $action === 'create' || $action === 'autocreate' ) {
4356 $performer = $this;
4357 } else {
4358 $performer = $wgUser;
4361 $logEntry = new ManualLogEntry( 'newusers', $action );
4362 $logEntry->setPerformer( $performer );
4363 $logEntry->setTarget( $this->getUserPage() );
4364 $logEntry->setComment( $reason );
4365 $logEntry->setParameters( array(
4366 '4::userid' => $this->getId(),
4367 ) );
4368 $logid = $logEntry->insert();
4370 if ( $action !== 'autocreate' ) {
4371 $logEntry->publish( $logid );
4374 return (int)$logid;
4378 * Add an autocreate newuser log entry for this user
4379 * Used by things like CentralAuth and perhaps other authplugins.
4380 * Consider calling addNewUserLogEntry() directly instead.
4382 * @return bool
4384 public function addNewUserLogEntryAutoCreate() {
4385 $this->addNewUserLogEntry( 'autocreate' );
4387 return true;
4391 * Load the user options either from cache, the database or an array
4393 * @param array $data Rows for the current user out of the user_properties table
4395 protected function loadOptions( $data = null ) {
4396 global $wgContLang;
4398 $this->load();
4400 if ( $this->mOptionsLoaded ) {
4401 return;
4404 $this->mOptions = self::getDefaultOptions();
4406 if ( !$this->getId() ) {
4407 // For unlogged-in users, load language/variant options from request.
4408 // There's no need to do it for logged-in users: they can set preferences,
4409 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4410 // so don't override user's choice (especially when the user chooses site default).
4411 $variant = $wgContLang->getDefaultVariant();
4412 $this->mOptions['variant'] = $variant;
4413 $this->mOptions['language'] = $variant;
4414 $this->mOptionsLoaded = true;
4415 return;
4418 // Maybe load from the object
4419 if ( !is_null( $this->mOptionOverrides ) ) {
4420 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4421 foreach ( $this->mOptionOverrides as $key => $value ) {
4422 $this->mOptions[$key] = $value;
4424 } else {
4425 if ( !is_array( $data ) ) {
4426 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4427 // Load from database
4428 $dbr = wfGetDB( DB_SLAVE );
4430 $res = $dbr->select(
4431 'user_properties',
4432 array( 'up_property', 'up_value' ),
4433 array( 'up_user' => $this->getId() ),
4434 __METHOD__
4437 $this->mOptionOverrides = array();
4438 $data = array();
4439 foreach ( $res as $row ) {
4440 $data[$row->up_property] = $row->up_value;
4443 foreach ( $data as $property => $value ) {
4444 $this->mOptionOverrides[$property] = $value;
4445 $this->mOptions[$property] = $value;
4449 $this->mOptionsLoaded = true;
4451 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
4455 * @todo document
4457 protected function saveOptions() {
4458 $this->loadOptions();
4460 // Not using getOptions(), to keep hidden preferences in database
4461 $saveOptions = $this->mOptions;
4463 // Allow hooks to abort, for instance to save to a global profile.
4464 // Reset options to default state before saving.
4465 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4466 return;
4469 $userId = $this->getId();
4470 $insert_rows = array();
4471 foreach ( $saveOptions as $key => $value ) {
4472 // Don't bother storing default values
4473 $defaultOption = self::getDefaultOption( $key );
4474 if ( ( is_null( $defaultOption ) &&
4475 !( $value === false || is_null( $value ) ) ) ||
4476 $value != $defaultOption ) {
4477 $insert_rows[] = array(
4478 'up_user' => $userId,
4479 'up_property' => $key,
4480 'up_value' => $value,
4485 $dbw = wfGetDB( DB_MASTER );
4486 $hasRows = $dbw->selectField( 'user_properties', '1',
4487 array( 'up_user' => $userId ), __METHOD__ );
4489 if ( $hasRows ) {
4490 // Only do this delete if there is something there. A very large portion of
4491 // calls to this function are for setting 'rememberpassword' for new accounts.
4492 // Doing this delete for new accounts with no rows in the table rougly causes
4493 // gap locks on [max user ID,+infinity) which causes high contention since many
4494 // updates will pile up on each other since they are for higher (newer) user IDs.
4495 $dbw->delete( 'user_properties', array( 'up_user' => $userId ), __METHOD__ );
4497 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
4501 * Provide an array of HTML5 attributes to put on an input element
4502 * intended for the user to enter a new password. This may include
4503 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4505 * Do *not* use this when asking the user to enter his current password!
4506 * Regardless of configuration, users may have invalid passwords for whatever
4507 * reason (e.g., they were set before requirements were tightened up).
4508 * Only use it when asking for a new password, like on account creation or
4509 * ResetPass.
4511 * Obviously, you still need to do server-side checking.
4513 * NOTE: A combination of bugs in various browsers means that this function
4514 * actually just returns array() unconditionally at the moment. May as
4515 * well keep it around for when the browser bugs get fixed, though.
4517 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4519 * @return array Array of HTML attributes suitable for feeding to
4520 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4521 * That will get confused by the boolean attribute syntax used.)
4523 public static function passwordChangeInputAttribs() {
4524 global $wgMinimalPasswordLength;
4526 if ( $wgMinimalPasswordLength == 0 ) {
4527 return array();
4530 # Note that the pattern requirement will always be satisfied if the
4531 # input is empty, so we need required in all cases.
4533 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4534 # if e-mail confirmation is being used. Since HTML5 input validation
4535 # is b0rked anyway in some browsers, just return nothing. When it's
4536 # re-enabled, fix this code to not output required for e-mail
4537 # registration.
4538 #$ret = array( 'required' );
4539 $ret = array();
4541 # We can't actually do this right now, because Opera 9.6 will print out
4542 # the entered password visibly in its error message! When other
4543 # browsers add support for this attribute, or Opera fixes its support,
4544 # we can add support with a version check to avoid doing this on Opera
4545 # versions where it will be a problem. Reported to Opera as
4546 # DSK-262266, but they don't have a public bug tracker for us to follow.
4548 if ( $wgMinimalPasswordLength > 1 ) {
4549 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4550 $ret['title'] = wfMessage( 'passwordtooshort' )
4551 ->numParams( $wgMinimalPasswordLength )->text();
4555 return $ret;
4559 * Return the list of user fields that should be selected to create
4560 * a new user object.
4561 * @return array
4563 public static function selectFields() {
4564 return array(
4565 'user_id',
4566 'user_name',
4567 'user_real_name',
4568 'user_password',
4569 'user_newpassword',
4570 'user_newpass_time',
4571 'user_email',
4572 'user_touched',
4573 'user_token',
4574 'user_email_authenticated',
4575 'user_email_token',
4576 'user_email_token_expires',
4577 'user_registration',
4578 'user_editcount',