Don't try to auto-create users when MW_NO_SESSION is defined
[mediawiki.git] / includes / user / User.php
blobdccfd77ce304db334bb63bc27021b52e51b239b7
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 use MediaWiki\Session\SessionManager;
25 /**
26 * String Some punctuation to prevent editing from broken text-mangling proxies.
27 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::SUFFIX
28 * @ingroup Constants
30 define( 'EDIT_TOKEN_SUFFIX', MediaWiki\Session\Token::SUFFIX );
32 /**
33 * The User object encapsulates all of the user-specific settings (user_id,
34 * name, rights, email address, options, last login time). Client
35 * classes use the getXXX() functions to access these fields. These functions
36 * do all the work of determining whether the user is logged in,
37 * whether the requested option can be satisfied from cookies or
38 * whether a database query is needed. Most of the settings needed
39 * for rendering normal pages are set in the cookie to minimize use
40 * of the database.
42 class User implements IDBAccessObject {
43 /**
44 * @const int Number of characters in user_token field.
46 const TOKEN_LENGTH = 32;
48 /**
49 * Global constant made accessible as class constants so that autoloader
50 * magic can be used.
51 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::SUFFIX
53 const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
55 /**
56 * @const int Serialized record version.
58 const VERSION = 10;
60 /**
61 * Maximum items in $mWatchedItems
63 const MAX_WATCHED_ITEMS_CACHE = 100;
65 /**
66 * Exclude user options that are set to their default value.
67 * @since 1.25
69 const GETOPTIONS_EXCLUDE_DEFAULTS = 1;
71 /**
72 * Array of Strings List of member variables which are saved to the
73 * shared cache (memcached). Any operation which changes the
74 * corresponding database fields must call a cache-clearing function.
75 * @showinitializer
77 protected static $mCacheVars = array(
78 // user table
79 'mId',
80 'mName',
81 'mRealName',
82 'mEmail',
83 'mTouched',
84 'mToken',
85 'mEmailAuthenticated',
86 'mEmailToken',
87 'mEmailTokenExpires',
88 'mRegistration',
89 'mEditCount',
90 // user_groups table
91 'mGroups',
92 // user_properties table
93 'mOptionOverrides',
96 /**
97 * Array of Strings Core rights.
98 * Each of these should have a corresponding message of the form
99 * "right-$right".
100 * @showinitializer
102 protected static $mCoreRights = array(
103 'apihighlimits',
104 'applychangetags',
105 'autoconfirmed',
106 'autocreateaccount',
107 'autopatrol',
108 'bigdelete',
109 'block',
110 'blockemail',
111 'bot',
112 'browsearchive',
113 'changetags',
114 'createaccount',
115 'createpage',
116 'createtalk',
117 'delete',
118 'deletedhistory',
119 'deletedtext',
120 'deletelogentry',
121 'deleterevision',
122 'edit',
123 'editcontentmodel',
124 'editinterface',
125 'editprotected',
126 'editmyoptions',
127 'editmyprivateinfo',
128 'editmyusercss',
129 'editmyuserjs',
130 'editmywatchlist',
131 'editsemiprotected',
132 'editusercssjs', # deprecated
133 'editusercss',
134 'edituserjs',
135 'hideuser',
136 'import',
137 'importupload',
138 'ipblock-exempt',
139 'managechangetags',
140 'markbotedits',
141 'mergehistory',
142 'minoredit',
143 'move',
144 'movefile',
145 'move-categorypages',
146 'move-rootuserpages',
147 'move-subpages',
148 'nominornewtalk',
149 'noratelimit',
150 'override-export-depth',
151 'pagelang',
152 'passwordreset',
153 'patrol',
154 'patrolmarks',
155 'protect',
156 'purge',
157 'read',
158 'reupload',
159 'reupload-own',
160 'reupload-shared',
161 'rollback',
162 'sendemail',
163 'siteadmin',
164 'suppressionlog',
165 'suppressredirect',
166 'suppressrevision',
167 'unblockself',
168 'undelete',
169 'unwatchedpages',
170 'upload',
171 'upload_by_url',
172 'userrights',
173 'userrights-interwiki',
174 'viewmyprivateinfo',
175 'viewmywatchlist',
176 'viewsuppressed',
177 'writeapi',
181 * String Cached results of getAllRights()
183 protected static $mAllRights = false;
185 /** Cache variables */
186 // @{
187 public $mId;
188 /** @var string */
189 public $mName;
190 /** @var string */
191 public $mRealName;
193 /** @var string */
194 public $mEmail;
195 /** @var string TS_MW timestamp from the DB */
196 public $mTouched;
197 /** @var string TS_MW timestamp from cache */
198 protected $mQuickTouched;
199 /** @var string */
200 protected $mToken;
201 /** @var string */
202 public $mEmailAuthenticated;
203 /** @var string */
204 protected $mEmailToken;
205 /** @var string */
206 protected $mEmailTokenExpires;
207 /** @var string */
208 protected $mRegistration;
209 /** @var int */
210 protected $mEditCount;
211 /** @var array */
212 public $mGroups;
213 /** @var array */
214 protected $mOptionOverrides;
215 // @}
218 * Bool Whether the cache variables have been loaded.
220 // @{
221 public $mOptionsLoaded;
224 * Array with already loaded items or true if all items have been loaded.
226 protected $mLoadedItems = array();
227 // @}
230 * String Initialization data source if mLoadedItems!==true. May be one of:
231 * - 'defaults' anonymous user initialised from class defaults
232 * - 'name' initialise from mName
233 * - 'id' initialise from mId
234 * - 'session' log in from session if possible
236 * Use the User::newFrom*() family of functions to set this.
238 public $mFrom;
241 * Lazy-initialized variables, invalidated with clearInstanceCache
243 protected $mNewtalk;
244 /** @var string */
245 protected $mDatePreference;
246 /** @var string */
247 public $mBlockedby;
248 /** @var string */
249 protected $mHash;
250 /** @var array */
251 public $mRights;
252 /** @var string */
253 protected $mBlockreason;
254 /** @var array */
255 protected $mEffectiveGroups;
256 /** @var array */
257 protected $mImplicitGroups;
258 /** @var array */
259 protected $mFormerGroups;
260 /** @var bool */
261 protected $mBlockedGlobally;
262 /** @var bool */
263 protected $mLocked;
264 /** @var bool */
265 public $mHideName;
266 /** @var array */
267 public $mOptions;
270 * @var WebRequest
272 private $mRequest;
274 /** @var Block */
275 public $mBlock;
277 /** @var bool */
278 protected $mAllowUsertalk;
280 /** @var Block */
281 private $mBlockedFromCreateAccount = false;
283 /** @var array */
284 private $mWatchedItems = array();
286 /** @var integer User::READ_* constant bitfield used to load data */
287 protected $queryFlagsUsed = self::READ_NORMAL;
289 public static $idCacheByName = array();
292 * Lightweight constructor for an anonymous user.
293 * Use the User::newFrom* factory functions for other kinds of users.
295 * @see newFromName()
296 * @see newFromId()
297 * @see newFromConfirmationCode()
298 * @see newFromSession()
299 * @see newFromRow()
301 public function __construct() {
302 $this->clearInstanceCache( 'defaults' );
306 * @return string
308 public function __toString() {
309 return $this->getName();
313 * Test if it's safe to load this User object. You should typically check this before using
314 * $wgUser or RequestContext::getUser in a method that might be called before the system has
315 * been fully initialized. If the object is unsafe, you should use an anonymous user:
316 * \code
317 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
318 * \endcode
320 * @since 1.27
321 * @return bool
323 public function isSafeToLoad() {
324 global $wgFullyInitialised;
325 return $wgFullyInitialised || $this->mLoadedItems === true || $this->mFrom !== 'session';
329 * Load the user table data for this object from the source given by mFrom.
331 * @param integer $flags User::READ_* constant bitfield
333 public function load( $flags = self::READ_NORMAL ) {
334 global $wgFullyInitialised;
336 if ( $this->mLoadedItems === true ) {
337 return;
340 // Set it now to avoid infinite recursion in accessors
341 $oldLoadedItems = $this->mLoadedItems;
342 $this->mLoadedItems = true;
343 $this->queryFlagsUsed = $flags;
345 // If this is called too early, things are likely to break.
346 if ( !$wgFullyInitialised && $this->mFrom === 'session' ) {
347 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
348 ->warning( 'User::loadFromSession called before the end of Setup.php', array(
349 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
350 ) );
351 $this->loadDefaults();
352 $this->mLoadedItems = $oldLoadedItems;
353 return;
356 switch ( $this->mFrom ) {
357 case 'defaults':
358 $this->loadDefaults();
359 break;
360 case 'name':
361 // Make sure this thread sees its own changes
362 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
363 $flags |= self::READ_LATEST;
364 $this->queryFlagsUsed = $flags;
367 $this->mId = self::idFromName( $this->mName, $flags );
368 if ( !$this->mId ) {
369 // Nonexistent user placeholder object
370 $this->loadDefaults( $this->mName );
371 } else {
372 $this->loadFromId( $flags );
374 break;
375 case 'id':
376 $this->loadFromId( $flags );
377 break;
378 case 'session':
379 if ( !$this->loadFromSession() ) {
380 // Loading from session failed. Load defaults.
381 $this->loadDefaults();
383 Hooks::run( 'UserLoadAfterLoadFromSession', array( $this ) );
384 break;
385 default:
386 throw new UnexpectedValueException(
387 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
392 * Load user table data, given mId has already been set.
393 * @param integer $flags User::READ_* constant bitfield
394 * @return bool False if the ID does not exist, true otherwise
396 public function loadFromId( $flags = self::READ_NORMAL ) {
397 if ( $this->mId == 0 ) {
398 $this->loadDefaults();
399 return false;
402 // Try cache (unless this needs data from the master DB).
403 // NOTE: if this thread called saveSettings(), the cache was cleared.
404 $latest = DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST );
405 if ( $latest || !$this->loadFromCache() ) {
406 wfDebug( "User: cache miss for user {$this->mId}\n" );
407 // Load from DB (make sure this thread sees its own changes)
408 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
409 $flags |= self::READ_LATEST;
411 if ( !$this->loadFromDatabase( $flags ) ) {
412 // Can't load from ID, user is anonymous
413 return false;
415 $this->saveToCache();
418 $this->mLoadedItems = true;
419 $this->queryFlagsUsed = $flags;
421 return true;
425 * @since 1.27
426 * @param string $wikiId
427 * @param integer $userId
429 public static function purge( $wikiId, $userId ) {
430 $cache = ObjectCache::getMainWANInstance();
431 $cache->delete( $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId ) );
435 * @since 1.27
436 * @param WANObjectCache $cache
437 * @return string
439 protected function getCacheKey( WANObjectCache $cache ) {
440 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId );
444 * Load user data from shared cache, given mId has already been set.
446 * @return bool false if the ID does not exist or data is invalid, true otherwise
447 * @since 1.25
449 protected function loadFromCache() {
450 if ( $this->mId == 0 ) {
451 $this->loadDefaults();
452 return false;
455 $cache = ObjectCache::getMainWANInstance();
456 $data = $cache->get( $this->getCacheKey( $cache ) );
457 if ( !is_array( $data ) || $data['mVersion'] < self::VERSION ) {
458 // Object is expired
459 return false;
462 wfDebug( "User: got user {$this->mId} from cache\n" );
464 // Restore from cache
465 foreach ( self::$mCacheVars as $name ) {
466 $this->$name = $data[$name];
469 return true;
473 * Save user data to the shared cache
475 * This method should not be called outside the User class
477 public function saveToCache() {
478 $this->load();
479 $this->loadGroups();
480 $this->loadOptions();
482 if ( $this->isAnon() ) {
483 // Anonymous users are uncached
484 return;
487 $data = array();
488 foreach ( self::$mCacheVars as $name ) {
489 $data[$name] = $this->$name;
491 $data['mVersion'] = self::VERSION;
492 $opts = Database::getCacheSetOptions( wfGetDB( DB_SLAVE ) );
494 $cache = ObjectCache::getMainWANInstance();
495 $key = $this->getCacheKey( $cache );
496 $cache->set( $key, $data, $cache::TTL_HOUR, $opts );
499 /** @name newFrom*() static factory methods */
500 // @{
503 * Static factory method for creation from username.
505 * This is slightly less efficient than newFromId(), so use newFromId() if
506 * you have both an ID and a name handy.
508 * @param string $name Username, validated by Title::newFromText()
509 * @param string|bool $validate Validate username. Takes the same parameters as
510 * User::getCanonicalName(), except that true is accepted as an alias
511 * for 'valid', for BC.
513 * @return User|bool User object, or false if the username is invalid
514 * (e.g. if it contains illegal characters or is an IP address). If the
515 * username is not present in the database, the result will be a user object
516 * with a name, zero user ID and default settings.
518 public static function newFromName( $name, $validate = 'valid' ) {
519 if ( $validate === true ) {
520 $validate = 'valid';
522 $name = self::getCanonicalName( $name, $validate );
523 if ( $name === false ) {
524 return false;
525 } else {
526 // Create unloaded user object
527 $u = new User;
528 $u->mName = $name;
529 $u->mFrom = 'name';
530 $u->setItemLoaded( 'name' );
531 return $u;
536 * Static factory method for creation from a given user ID.
538 * @param int $id Valid user ID
539 * @return User The corresponding User object
541 public static function newFromId( $id ) {
542 $u = new User;
543 $u->mId = $id;
544 $u->mFrom = 'id';
545 $u->setItemLoaded( 'id' );
546 return $u;
550 * Factory method to fetch whichever user has a given email confirmation code.
551 * This code is generated when an account is created or its e-mail address
552 * has changed.
554 * If the code is invalid or has expired, returns NULL.
556 * @param string $code Confirmation code
557 * @param int $flags User::READ_* bitfield
558 * @return User|null
560 public static function newFromConfirmationCode( $code, $flags = 0 ) {
561 $db = ( $flags & self::READ_LATEST ) == self::READ_LATEST
562 ? wfGetDB( DB_MASTER )
563 : wfGetDB( DB_SLAVE );
565 $id = $db->selectField(
566 'user',
567 'user_id',
568 array(
569 'user_email_token' => md5( $code ),
570 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
574 return $id ? User::newFromId( $id ) : null;
578 * Create a new user object using data from session. If the login
579 * credentials are invalid, the result is an anonymous user.
581 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
582 * @return User
584 public static function newFromSession( WebRequest $request = null ) {
585 $user = new User;
586 $user->mFrom = 'session';
587 $user->mRequest = $request;
588 return $user;
592 * Create a new user object from a user row.
593 * The row should have the following fields from the user table in it:
594 * - either user_name or user_id to load further data if needed (or both)
595 * - user_real_name
596 * - all other fields (email, etc.)
597 * It is useless to provide the remaining fields if either user_id,
598 * user_name and user_real_name are not provided because the whole row
599 * will be loaded once more from the database when accessing them.
601 * @param stdClass $row A row from the user table
602 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
603 * @return User
605 public static function newFromRow( $row, $data = null ) {
606 $user = new User;
607 $user->loadFromRow( $row, $data );
608 return $user;
612 * Static factory method for creation of a "system" user from username.
614 * A "system" user is an account that's used to attribute logged actions
615 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
616 * might include the 'Maintenance script' or 'Conversion script' accounts
617 * used by various scripts in the maintenance/ directory or accounts such
618 * as 'MediaWiki message delivery' used by the MassMessage extension.
620 * This can optionally create the user if it doesn't exist, and "steal" the
621 * account if it does exist.
623 * @param string $name Username
624 * @param array $options Options are:
625 * - validate: As for User::getCanonicalName(), default 'valid'
626 * - create: Whether to create the user if it doesn't already exist, default true
627 * - steal: Whether to reset the account's password and email if it
628 * already exists, default false
629 * @return User|null
631 public static function newSystemUser( $name, $options = array() ) {
632 $options += array(
633 'validate' => 'valid',
634 'create' => true,
635 'steal' => false,
638 $name = self::getCanonicalName( $name, $options['validate'] );
639 if ( $name === false ) {
640 return null;
643 $dbw = wfGetDB( DB_MASTER );
644 $row = $dbw->selectRow(
645 'user',
646 array_merge(
647 self::selectFields(),
648 array( 'user_password', 'user_newpassword' )
650 array( 'user_name' => $name ),
651 __METHOD__
653 if ( !$row ) {
654 // No user. Create it?
655 return $options['create'] ? self::createNew( $name ) : null;
657 $user = self::newFromRow( $row );
659 // A user is considered to exist as a non-system user if it has a
660 // password set, or a temporary password set, or an email set.
661 $passwordFactory = new PasswordFactory();
662 $passwordFactory->init( RequestContext::getMain()->getConfig() );
663 try {
664 $password = $passwordFactory->newFromCiphertext( $row->user_password );
665 } catch ( PasswordError $e ) {
666 wfDebug( 'Invalid password hash found in database.' );
667 $password = PasswordFactory::newInvalidPassword();
669 try {
670 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword );
671 } catch ( PasswordError $e ) {
672 wfDebug( 'Invalid password hash found in database.' );
673 $newpassword = PasswordFactory::newInvalidPassword();
675 if ( !$password instanceof InvalidPassword || !$newpassword instanceof InvalidPassword
676 || $user->mEmail
678 // User exists. Steal it?
679 if ( !$options['steal'] ) {
680 return null;
683 $nopass = PasswordFactory::newInvalidPassword()->toString();
685 $dbw->update(
686 'user',
687 array(
688 'user_password' => $nopass,
689 'user_newpassword' => $nopass,
690 'user_newpass_time' => null,
692 array( 'user_id' => $user->getId() ),
693 __METHOD__
695 $user->invalidateEmail();
696 $user->saveSettings();
699 SessionManager::singleton()->preventSessionsForUser( $user->getName() );
701 return $user;
704 // @}
707 * Get the username corresponding to a given user ID
708 * @param int $id User ID
709 * @return string|bool The corresponding username
711 public static function whoIs( $id ) {
712 return UserCache::singleton()->getProp( $id, 'name' );
716 * Get the real name of a user given their user ID
718 * @param int $id User ID
719 * @return string|bool The corresponding user's real name
721 public static function whoIsReal( $id ) {
722 return UserCache::singleton()->getProp( $id, 'real_name' );
726 * Get database id given a user name
727 * @param string $name Username
728 * @param integer $flags User::READ_* constant bitfield
729 * @return int|null The corresponding user's ID, or null if user is nonexistent
731 public static function idFromName( $name, $flags = self::READ_NORMAL ) {
732 $nt = Title::makeTitleSafe( NS_USER, $name );
733 if ( is_null( $nt ) ) {
734 // Illegal name
735 return null;
738 if ( !( $flags & self::READ_LATEST ) && isset( self::$idCacheByName[$name] ) ) {
739 return self::$idCacheByName[$name];
742 $db = ( $flags & self::READ_LATEST )
743 ? wfGetDB( DB_MASTER )
744 : wfGetDB( DB_SLAVE );
746 $s = $db->selectRow(
747 'user',
748 array( 'user_id' ),
749 array( 'user_name' => $nt->getText() ),
750 __METHOD__
753 if ( $s === false ) {
754 $result = null;
755 } else {
756 $result = $s->user_id;
759 self::$idCacheByName[$name] = $result;
761 if ( count( self::$idCacheByName ) > 1000 ) {
762 self::$idCacheByName = array();
765 return $result;
769 * Reset the cache used in idFromName(). For use in tests.
771 public static function resetIdByNameCache() {
772 self::$idCacheByName = array();
776 * Does the string match an anonymous IPv4 address?
778 * This function exists for username validation, in order to reject
779 * usernames which are similar in form to IP addresses. Strings such
780 * as 300.300.300.300 will return true because it looks like an IP
781 * address, despite not being strictly valid.
783 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
784 * address because the usemod software would "cloak" anonymous IP
785 * addresses like this, if we allowed accounts like this to be created
786 * new users could get the old edits of these anonymous users.
788 * @param string $name Name to match
789 * @return bool
791 public static function isIP( $name ) {
792 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
793 || IP::isIPv6( $name );
797 * Is the input a valid username?
799 * Checks if the input is a valid username, we don't want an empty string,
800 * an IP address, anything that contains slashes (would mess up subpages),
801 * is longer than the maximum allowed username size or doesn't begin with
802 * a capital letter.
804 * @param string $name Name to match
805 * @return bool
807 public static function isValidUserName( $name ) {
808 global $wgContLang, $wgMaxNameChars;
810 if ( $name == ''
811 || User::isIP( $name )
812 || strpos( $name, '/' ) !== false
813 || strlen( $name ) > $wgMaxNameChars
814 || $name != $wgContLang->ucfirst( $name )
816 wfDebugLog( 'username', __METHOD__ .
817 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
818 return false;
821 // Ensure that the name can't be misresolved as a different title,
822 // such as with extra namespace keys at the start.
823 $parsed = Title::newFromText( $name );
824 if ( is_null( $parsed )
825 || $parsed->getNamespace()
826 || strcmp( $name, $parsed->getPrefixedText() ) ) {
827 wfDebugLog( 'username', __METHOD__ .
828 ": '$name' invalid due to ambiguous prefixes" );
829 return false;
832 // Check an additional blacklist of troublemaker characters.
833 // Should these be merged into the title char list?
834 $unicodeBlacklist = '/[' .
835 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
836 '\x{00a0}' . # non-breaking space
837 '\x{2000}-\x{200f}' . # various whitespace
838 '\x{2028}-\x{202f}' . # breaks and control chars
839 '\x{3000}' . # ideographic space
840 '\x{e000}-\x{f8ff}' . # private use
841 ']/u';
842 if ( preg_match( $unicodeBlacklist, $name ) ) {
843 wfDebugLog( 'username', __METHOD__ .
844 ": '$name' invalid due to blacklisted characters" );
845 return false;
848 return true;
852 * Usernames which fail to pass this function will be blocked
853 * from user login and new account registrations, but may be used
854 * internally by batch processes.
856 * If an account already exists in this form, login will be blocked
857 * by a failure to pass this function.
859 * @param string $name Name to match
860 * @return bool
862 public static function isUsableName( $name ) {
863 global $wgReservedUsernames;
864 // Must be a valid username, obviously ;)
865 if ( !self::isValidUserName( $name ) ) {
866 return false;
869 static $reservedUsernames = false;
870 if ( !$reservedUsernames ) {
871 $reservedUsernames = $wgReservedUsernames;
872 Hooks::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
875 // Certain names may be reserved for batch processes.
876 foreach ( $reservedUsernames as $reserved ) {
877 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
878 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
880 if ( $reserved == $name ) {
881 return false;
884 return true;
888 * Usernames which fail to pass this function will be blocked
889 * from new account registrations, but may be used internally
890 * either by batch processes or by user accounts which have
891 * already been created.
893 * Additional blacklisting may be added here rather than in
894 * isValidUserName() to avoid disrupting existing accounts.
896 * @param string $name String to match
897 * @return bool
899 public static function isCreatableName( $name ) {
900 global $wgInvalidUsernameCharacters;
902 // Ensure that the username isn't longer than 235 bytes, so that
903 // (at least for the builtin skins) user javascript and css files
904 // will work. (bug 23080)
905 if ( strlen( $name ) > 235 ) {
906 wfDebugLog( 'username', __METHOD__ .
907 ": '$name' invalid due to length" );
908 return false;
911 // Preg yells if you try to give it an empty string
912 if ( $wgInvalidUsernameCharacters !== '' ) {
913 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
914 wfDebugLog( 'username', __METHOD__ .
915 ": '$name' invalid due to wgInvalidUsernameCharacters" );
916 return false;
920 return self::isUsableName( $name );
924 * Is the input a valid password for this user?
926 * @param string $password Desired password
927 * @return bool
929 public function isValidPassword( $password ) {
930 // simple boolean wrapper for getPasswordValidity
931 return $this->getPasswordValidity( $password ) === true;
935 * Given unvalidated password input, return error message on failure.
937 * @param string $password Desired password
938 * @return bool|string|array True on success, string or array of error message on failure
940 public function getPasswordValidity( $password ) {
941 $result = $this->checkPasswordValidity( $password );
942 if ( $result->isGood() ) {
943 return true;
944 } else {
945 $messages = array();
946 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
947 $messages[] = $error['message'];
949 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
950 $messages[] = $warning['message'];
952 if ( count( $messages ) === 1 ) {
953 return $messages[0];
955 return $messages;
960 * Check if this is a valid password for this user
962 * Create a Status object based on the password's validity.
963 * The Status should be set to fatal if the user should not
964 * be allowed to log in, and should have any errors that
965 * would block changing the password.
967 * If the return value of this is not OK, the password
968 * should not be checked. If the return value is not Good,
969 * the password can be checked, but the user should not be
970 * able to set their password to this.
972 * @param string $password Desired password
973 * @param string $purpose one of 'login', 'create', 'reset'
974 * @return Status
975 * @since 1.23
977 public function checkPasswordValidity( $password, $purpose = 'login' ) {
978 global $wgPasswordPolicy;
980 $upp = new UserPasswordPolicy(
981 $wgPasswordPolicy['policies'],
982 $wgPasswordPolicy['checks']
985 $status = Status::newGood();
986 $result = false; // init $result to false for the internal checks
988 if ( !Hooks::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
989 $status->error( $result );
990 return $status;
993 if ( $result === false ) {
994 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
995 return $status;
996 } elseif ( $result === true ) {
997 return $status;
998 } else {
999 $status->error( $result );
1000 return $status; // the isValidPassword hook set a string $result and returned true
1005 * Given unvalidated user input, return a canonical username, or false if
1006 * the username is invalid.
1007 * @param string $name User input
1008 * @param string|bool $validate Type of validation to use:
1009 * - false No validation
1010 * - 'valid' Valid for batch processes
1011 * - 'usable' Valid for batch processes and login
1012 * - 'creatable' Valid for batch processes, login and account creation
1014 * @throws InvalidArgumentException
1015 * @return bool|string
1017 public static function getCanonicalName( $name, $validate = 'valid' ) {
1018 // Force usernames to capital
1019 global $wgContLang;
1020 $name = $wgContLang->ucfirst( $name );
1022 # Reject names containing '#'; these will be cleaned up
1023 # with title normalisation, but then it's too late to
1024 # check elsewhere
1025 if ( strpos( $name, '#' ) !== false ) {
1026 return false;
1029 // Clean up name according to title rules,
1030 // but only when validation is requested (bug 12654)
1031 $t = ( $validate !== false ) ?
1032 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
1033 // Check for invalid titles
1034 if ( is_null( $t ) ) {
1035 return false;
1038 // Reject various classes of invalid names
1039 global $wgAuth;
1040 $name = $wgAuth->getCanonicalName( $t->getText() );
1042 switch ( $validate ) {
1043 case false:
1044 break;
1045 case 'valid':
1046 if ( !User::isValidUserName( $name ) ) {
1047 $name = false;
1049 break;
1050 case 'usable':
1051 if ( !User::isUsableName( $name ) ) {
1052 $name = false;
1054 break;
1055 case 'creatable':
1056 if ( !User::isCreatableName( $name ) ) {
1057 $name = false;
1059 break;
1060 default:
1061 throw new InvalidArgumentException(
1062 'Invalid parameter value for $validate in ' . __METHOD__ );
1064 return $name;
1068 * Count the number of edits of a user
1070 * @param int $uid User ID to check
1071 * @return int The user's edit count
1073 * @deprecated since 1.21 in favour of User::getEditCount
1075 public static function edits( $uid ) {
1076 wfDeprecated( __METHOD__, '1.21' );
1077 $user = self::newFromId( $uid );
1078 return $user->getEditCount();
1082 * Return a random password.
1084 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1085 * @return string New random password
1087 public static function randomPassword() {
1088 global $wgMinimalPasswordLength;
1089 return PasswordFactory::generateRandomPasswordString( $wgMinimalPasswordLength );
1093 * Set cached properties to default.
1095 * @note This no longer clears uncached lazy-initialised properties;
1096 * the constructor does that instead.
1098 * @param string|bool $name
1100 public function loadDefaults( $name = false ) {
1101 $this->mId = 0;
1102 $this->mName = $name;
1103 $this->mRealName = '';
1104 $this->mEmail = '';
1105 $this->mOptionOverrides = null;
1106 $this->mOptionsLoaded = false;
1108 $loggedOut = $this->mRequest ? $this->mRequest->getSession()->getLoggedOutTimestamp() : 0;
1109 if ( $loggedOut !== 0 ) {
1110 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
1111 } else {
1112 $this->mTouched = '1'; # Allow any pages to be cached
1115 $this->mToken = null; // Don't run cryptographic functions till we need a token
1116 $this->mEmailAuthenticated = null;
1117 $this->mEmailToken = '';
1118 $this->mEmailTokenExpires = null;
1119 $this->mRegistration = wfTimestamp( TS_MW );
1120 $this->mGroups = array();
1122 Hooks::run( 'UserLoadDefaults', array( $this, $name ) );
1126 * Return whether an item has been loaded.
1128 * @param string $item Item to check. Current possibilities:
1129 * - id
1130 * - name
1131 * - realname
1132 * @param string $all 'all' to check if the whole object has been loaded
1133 * or any other string to check if only the item is available (e.g.
1134 * for optimisation)
1135 * @return bool
1137 public function isItemLoaded( $item, $all = 'all' ) {
1138 return ( $this->mLoadedItems === true && $all === 'all' ) ||
1139 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1143 * Set that an item has been loaded
1145 * @param string $item
1147 protected function setItemLoaded( $item ) {
1148 if ( is_array( $this->mLoadedItems ) ) {
1149 $this->mLoadedItems[$item] = true;
1154 * Load user data from the session.
1156 * @return bool True if the user is logged in, false otherwise.
1158 private function loadFromSession() {
1159 // Deprecated hook
1160 $result = null;
1161 Hooks::run( 'UserLoadFromSession', array( $this, &$result ), '1.27' );
1162 if ( $result !== null ) {
1163 return $result;
1166 // MediaWiki\Session\Session already did the necessary authentication of the user
1167 // returned here, so just use it if applicable.
1168 $session = $this->getRequest()->getSession();
1169 $user = $session->getUser();
1170 if ( $user->isLoggedIn() ) {
1171 $this->loadFromUserObject( $user );
1172 // Other code expects these to be set in the session, so set them.
1173 $session->set( 'wsUserID', $this->getId() );
1174 $session->set( 'wsUserName', $this->getName() );
1175 $session->set( 'wsToken', $this->getToken() );
1176 return true;
1179 return false;
1183 * Load user and user_group data from the database.
1184 * $this->mId must be set, this is how the user is identified.
1186 * @param integer $flags User::READ_* constant bitfield
1187 * @return bool True if the user exists, false if the user is anonymous
1189 public function loadFromDatabase( $flags = self::READ_LATEST ) {
1190 // Paranoia
1191 $this->mId = intval( $this->mId );
1193 // Anonymous user
1194 if ( !$this->mId ) {
1195 $this->loadDefaults();
1196 return false;
1199 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
1200 $db = wfGetDB( $index );
1202 $s = $db->selectRow(
1203 'user',
1204 self::selectFields(),
1205 array( 'user_id' => $this->mId ),
1206 __METHOD__,
1207 $options
1210 $this->queryFlagsUsed = $flags;
1211 Hooks::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1213 if ( $s !== false ) {
1214 // Initialise user table data
1215 $this->loadFromRow( $s );
1216 $this->mGroups = null; // deferred
1217 $this->getEditCount(); // revalidation for nulls
1218 return true;
1219 } else {
1220 // Invalid user_id
1221 $this->mId = 0;
1222 $this->loadDefaults();
1223 return false;
1228 * Initialize this object from a row from the user table.
1230 * @param stdClass $row Row from the user table to load.
1231 * @param array $data Further user data to load into the object
1233 * user_groups Array with groups out of the user_groups table
1234 * user_properties Array with properties out of the user_properties table
1236 protected function loadFromRow( $row, $data = null ) {
1237 $all = true;
1239 $this->mGroups = null; // deferred
1241 if ( isset( $row->user_name ) ) {
1242 $this->mName = $row->user_name;
1243 $this->mFrom = 'name';
1244 $this->setItemLoaded( 'name' );
1245 } else {
1246 $all = false;
1249 if ( isset( $row->user_real_name ) ) {
1250 $this->mRealName = $row->user_real_name;
1251 $this->setItemLoaded( 'realname' );
1252 } else {
1253 $all = false;
1256 if ( isset( $row->user_id ) ) {
1257 $this->mId = intval( $row->user_id );
1258 $this->mFrom = 'id';
1259 $this->setItemLoaded( 'id' );
1260 } else {
1261 $all = false;
1264 if ( isset( $row->user_id ) && isset( $row->user_name ) ) {
1265 self::$idCacheByName[$row->user_name] = $row->user_id;
1268 if ( isset( $row->user_editcount ) ) {
1269 $this->mEditCount = $row->user_editcount;
1270 } else {
1271 $all = false;
1274 if ( isset( $row->user_touched ) ) {
1275 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1276 } else {
1277 $all = false;
1280 if ( isset( $row->user_token ) ) {
1281 // The definition for the column is binary(32), so trim the NULs
1282 // that appends. The previous definition was char(32), so trim
1283 // spaces too.
1284 $this->mToken = rtrim( $row->user_token, " \0" );
1285 if ( $this->mToken === '' ) {
1286 $this->mToken = null;
1288 } else {
1289 $all = false;
1292 if ( isset( $row->user_email ) ) {
1293 $this->mEmail = $row->user_email;
1294 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1295 $this->mEmailToken = $row->user_email_token;
1296 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1297 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1298 } else {
1299 $all = false;
1302 if ( $all ) {
1303 $this->mLoadedItems = true;
1306 if ( is_array( $data ) ) {
1307 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1308 $this->mGroups = $data['user_groups'];
1310 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1311 $this->loadOptions( $data['user_properties'] );
1317 * Load the data for this user object from another user object.
1319 * @param User $user
1321 protected function loadFromUserObject( $user ) {
1322 $user->load();
1323 $user->loadGroups();
1324 $user->loadOptions();
1325 foreach ( self::$mCacheVars as $var ) {
1326 $this->$var = $user->$var;
1331 * Load the groups from the database if they aren't already loaded.
1333 private function loadGroups() {
1334 if ( is_null( $this->mGroups ) ) {
1335 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
1336 ? wfGetDB( DB_MASTER )
1337 : wfGetDB( DB_SLAVE );
1338 $res = $db->select( 'user_groups',
1339 array( 'ug_group' ),
1340 array( 'ug_user' => $this->mId ),
1341 __METHOD__ );
1342 $this->mGroups = array();
1343 foreach ( $res as $row ) {
1344 $this->mGroups[] = $row->ug_group;
1350 * Add the user to the group if he/she meets given criteria.
1352 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1353 * possible to remove manually via Special:UserRights. In such case it
1354 * will not be re-added automatically. The user will also not lose the
1355 * group if they no longer meet the criteria.
1357 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1359 * @return array Array of groups the user has been promoted to.
1361 * @see $wgAutopromoteOnce
1363 public function addAutopromoteOnceGroups( $event ) {
1364 global $wgAutopromoteOnceLogInRC, $wgAuth;
1366 if ( wfReadOnly() || !$this->getId() ) {
1367 return array();
1370 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1371 if ( !count( $toPromote ) ) {
1372 return array();
1375 if ( !$this->checkAndSetTouched() ) {
1376 return array(); // raced out (bug T48834)
1379 $oldGroups = $this->getGroups(); // previous groups
1380 foreach ( $toPromote as $group ) {
1381 $this->addGroup( $group );
1383 // update groups in external authentication database
1384 Hooks::run( 'UserGroupsChanged', array( $this, $toPromote, array(), false ) );
1385 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1387 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1389 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1390 $logEntry->setPerformer( $this );
1391 $logEntry->setTarget( $this->getUserPage() );
1392 $logEntry->setParameters( array(
1393 '4::oldgroups' => $oldGroups,
1394 '5::newgroups' => $newGroups,
1395 ) );
1396 $logid = $logEntry->insert();
1397 if ( $wgAutopromoteOnceLogInRC ) {
1398 $logEntry->publish( $logid );
1401 return $toPromote;
1405 * Bump user_touched if it didn't change since this object was loaded
1407 * On success, the mTouched field is updated.
1408 * The user serialization cache is always cleared.
1410 * @return bool Whether user_touched was actually updated
1411 * @since 1.26
1413 protected function checkAndSetTouched() {
1414 $this->load();
1416 if ( !$this->mId ) {
1417 return false; // anon
1420 // Get a new user_touched that is higher than the old one
1421 $oldTouched = $this->mTouched;
1422 $newTouched = $this->newTouchedTimestamp();
1424 $dbw = wfGetDB( DB_MASTER );
1425 $dbw->update( 'user',
1426 array( 'user_touched' => $dbw->timestamp( $newTouched ) ),
1427 array(
1428 'user_id' => $this->mId,
1429 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1431 __METHOD__
1433 $success = ( $dbw->affectedRows() > 0 );
1435 if ( $success ) {
1436 $this->mTouched = $newTouched;
1437 $this->clearSharedCache();
1438 } else {
1439 // Clears on failure too since that is desired if the cache is stale
1440 $this->clearSharedCache( 'refresh' );
1443 return $success;
1447 * Clear various cached data stored in this object. The cache of the user table
1448 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1450 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1451 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1453 public function clearInstanceCache( $reloadFrom = false ) {
1454 $this->mNewtalk = -1;
1455 $this->mDatePreference = null;
1456 $this->mBlockedby = -1; # Unset
1457 $this->mHash = false;
1458 $this->mRights = null;
1459 $this->mEffectiveGroups = null;
1460 $this->mImplicitGroups = null;
1461 $this->mGroups = null;
1462 $this->mOptions = null;
1463 $this->mOptionsLoaded = false;
1464 $this->mEditCount = null;
1466 if ( $reloadFrom ) {
1467 $this->mLoadedItems = array();
1468 $this->mFrom = $reloadFrom;
1473 * Combine the language default options with any site-specific options
1474 * and add the default language variants.
1476 * @return array Array of String options
1478 public static function getDefaultOptions() {
1479 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1481 static $defOpt = null;
1482 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1483 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1484 // mid-request and see that change reflected in the return value of this function.
1485 // Which is insane and would never happen during normal MW operation
1486 return $defOpt;
1489 $defOpt = $wgDefaultUserOptions;
1490 // Default language setting
1491 $defOpt['language'] = $wgContLang->getCode();
1492 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1493 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1495 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1496 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1498 $defOpt['skin'] = Skin::normalizeKey( $wgDefaultSkin );
1500 Hooks::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1502 return $defOpt;
1506 * Get a given default option value.
1508 * @param string $opt Name of option to retrieve
1509 * @return string Default option value
1511 public static function getDefaultOption( $opt ) {
1512 $defOpts = self::getDefaultOptions();
1513 if ( isset( $defOpts[$opt] ) ) {
1514 return $defOpts[$opt];
1515 } else {
1516 return null;
1521 * Get blocking information
1522 * @param bool $bFromSlave Whether to check the slave database first.
1523 * To improve performance, non-critical checks are done against slaves.
1524 * Check when actually saving should be done against master.
1526 private function getBlockedStatus( $bFromSlave = true ) {
1527 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1529 if ( -1 != $this->mBlockedby ) {
1530 return;
1533 wfDebug( __METHOD__ . ": checking...\n" );
1535 // Initialize data...
1536 // Otherwise something ends up stomping on $this->mBlockedby when
1537 // things get lazy-loaded later, causing false positive block hits
1538 // due to -1 !== 0. Probably session-related... Nothing should be
1539 // overwriting mBlockedby, surely?
1540 $this->load();
1542 # We only need to worry about passing the IP address to the Block generator if the
1543 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1544 # know which IP address they're actually coming from
1545 $ip = null;
1546 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1547 // $wgUser->getName() only works after the end of Setup.php. Until
1548 // then, assume it's a logged-out user.
1549 $globalUserName = $wgUser->isSafeToLoad()
1550 ? $wgUser->getName()
1551 : IP::sanitizeIP( $wgUser->getRequest()->getIP() );
1552 if ( $this->getName() === $globalUserName ) {
1553 $ip = $this->getRequest()->getIP();
1557 // User/IP blocking
1558 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1560 // Proxy blocking
1561 if ( !$block instanceof Block && $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1562 // Local list
1563 if ( self::isLocallyBlockedProxy( $ip ) ) {
1564 $block = new Block;
1565 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1566 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1567 $block->setTarget( $ip );
1568 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1569 $block = new Block;
1570 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1571 $block->mReason = wfMessage( 'sorbsreason' )->text();
1572 $block->setTarget( $ip );
1576 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1577 if ( !$block instanceof Block
1578 && $wgApplyIpBlocksToXff
1579 && $ip !== null
1580 && !in_array( $ip, $wgProxyWhitelist )
1582 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1583 $xff = array_map( 'trim', explode( ',', $xff ) );
1584 $xff = array_diff( $xff, array( $ip ) );
1585 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1586 $block = Block::chooseBlock( $xffblocks, $xff );
1587 if ( $block instanceof Block ) {
1588 # Mangle the reason to alert the user that the block
1589 # originated from matching the X-Forwarded-For header.
1590 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1594 if ( $block instanceof Block ) {
1595 wfDebug( __METHOD__ . ": Found block.\n" );
1596 $this->mBlock = $block;
1597 $this->mBlockedby = $block->getByName();
1598 $this->mBlockreason = $block->mReason;
1599 $this->mHideName = $block->mHideName;
1600 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1601 } else {
1602 $this->mBlockedby = '';
1603 $this->mHideName = 0;
1604 $this->mAllowUsertalk = false;
1607 // Extensions
1608 Hooks::run( 'GetBlockedStatus', array( &$this ) );
1613 * Whether the given IP is in a DNS blacklist.
1615 * @param string $ip IP to check
1616 * @param bool $checkWhitelist Whether to check the whitelist first
1617 * @return bool True if blacklisted.
1619 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1620 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1622 if ( !$wgEnableDnsBlacklist ) {
1623 return false;
1626 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1627 return false;
1630 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1634 * Whether the given IP is in a given DNS blacklist.
1636 * @param string $ip IP to check
1637 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1638 * @return bool True if blacklisted.
1640 public function inDnsBlacklist( $ip, $bases ) {
1642 $found = false;
1643 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1644 if ( IP::isIPv4( $ip ) ) {
1645 // Reverse IP, bug 21255
1646 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1648 foreach ( (array)$bases as $base ) {
1649 // Make hostname
1650 // If we have an access key, use that too (ProjectHoneypot, etc.)
1651 $basename = $base;
1652 if ( is_array( $base ) ) {
1653 if ( count( $base ) >= 2 ) {
1654 // Access key is 1, base URL is 0
1655 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1656 } else {
1657 $host = "$ipReversed.{$base[0]}";
1659 $basename = $base[0];
1660 } else {
1661 $host = "$ipReversed.$base";
1664 // Send query
1665 $ipList = gethostbynamel( $host );
1667 if ( $ipList ) {
1668 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1669 $found = true;
1670 break;
1671 } else {
1672 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1677 return $found;
1681 * Check if an IP address is in the local proxy list
1683 * @param string $ip
1685 * @return bool
1687 public static function isLocallyBlockedProxy( $ip ) {
1688 global $wgProxyList;
1690 if ( !$wgProxyList ) {
1691 return false;
1694 if ( !is_array( $wgProxyList ) ) {
1695 // Load from the specified file
1696 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1699 if ( !is_array( $wgProxyList ) ) {
1700 $ret = false;
1701 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1702 $ret = true;
1703 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1704 // Old-style flipped proxy list
1705 $ret = true;
1706 } else {
1707 $ret = false;
1709 return $ret;
1713 * Is this user subject to rate limiting?
1715 * @return bool True if rate limited
1717 public function isPingLimitable() {
1718 global $wgRateLimitsExcludedIPs;
1719 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1720 // No other good way currently to disable rate limits
1721 // for specific IPs. :P
1722 // But this is a crappy hack and should die.
1723 return false;
1725 return !$this->isAllowed( 'noratelimit' );
1729 * Primitive rate limits: enforce maximum actions per time period
1730 * to put a brake on flooding.
1732 * The method generates both a generic profiling point and a per action one
1733 * (suffix being "-$action".
1735 * @note When using a shared cache like memcached, IP-address
1736 * last-hit counters will be shared across wikis.
1738 * @param string $action Action to enforce; 'edit' if unspecified
1739 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1740 * @return bool True if a rate limiter was tripped
1742 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1743 // Call the 'PingLimiter' hook
1744 $result = false;
1745 if ( !Hooks::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1746 return $result;
1749 global $wgRateLimits;
1750 if ( !isset( $wgRateLimits[$action] ) ) {
1751 return false;
1754 // Some groups shouldn't trigger the ping limiter, ever
1755 if ( !$this->isPingLimitable() ) {
1756 return false;
1759 $limits = $wgRateLimits[$action];
1760 $keys = array();
1761 $id = $this->getId();
1762 $userLimit = false;
1763 $isNewbie = $this->isNewbie();
1765 if ( $id == 0 ) {
1766 // limits for anons
1767 if ( isset( $limits['anon'] ) ) {
1768 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1770 } else {
1771 // limits for logged-in users
1772 if ( isset( $limits['user'] ) ) {
1773 $userLimit = $limits['user'];
1775 // limits for newbie logged-in users
1776 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1777 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1781 // limits for anons and for newbie logged-in users
1782 if ( $isNewbie ) {
1783 // ip-based limits
1784 if ( isset( $limits['ip'] ) ) {
1785 $ip = $this->getRequest()->getIP();
1786 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1788 // subnet-based limits
1789 if ( isset( $limits['subnet'] ) ) {
1790 $ip = $this->getRequest()->getIP();
1791 $subnet = IP::getSubnet( $ip );
1792 if ( $subnet !== false ) {
1793 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1798 // Check for group-specific permissions
1799 // If more than one group applies, use the group with the highest limit ratio (max/period)
1800 foreach ( $this->getGroups() as $group ) {
1801 if ( isset( $limits[$group] ) ) {
1802 if ( $userLimit === false
1803 || $limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1805 $userLimit = $limits[$group];
1810 // Set the user limit key
1811 if ( $userLimit !== false ) {
1812 list( $max, $period ) = $userLimit;
1813 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1814 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1817 // ip-based limits for all ping-limitable users
1818 if ( isset( $limits['ip-all'] ) ) {
1819 $ip = $this->getRequest()->getIP();
1820 // ignore if user limit is more permissive
1821 if ( $isNewbie || $userLimit === false
1822 || $limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1823 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1827 // subnet-based limits for all ping-limitable users
1828 if ( isset( $limits['subnet-all'] ) ) {
1829 $ip = $this->getRequest()->getIP();
1830 $subnet = IP::getSubnet( $ip );
1831 if ( $subnet !== false ) {
1832 // ignore if user limit is more permissive
1833 if ( $isNewbie || $userLimit === false
1834 || $limits['ip-all'][0] / $limits['ip-all'][1]
1835 > $userLimit[0] / $userLimit[1] ) {
1836 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1841 $cache = ObjectCache::getLocalClusterInstance();
1843 $triggered = false;
1844 foreach ( $keys as $key => $limit ) {
1845 list( $max, $period ) = $limit;
1846 $summary = "(limit $max in {$period}s)";
1847 $count = $cache->get( $key );
1848 // Already pinged?
1849 if ( $count ) {
1850 if ( $count >= $max ) {
1851 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1852 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1853 $triggered = true;
1854 } else {
1855 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1857 } else {
1858 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1859 if ( $incrBy > 0 ) {
1860 $cache->add( $key, 0, intval( $period ) ); // first ping
1863 if ( $incrBy > 0 ) {
1864 $cache->incr( $key, $incrBy );
1868 return $triggered;
1872 * Check if user is blocked
1874 * @param bool $bFromSlave Whether to check the slave database instead of
1875 * the master. Hacked from false due to horrible probs on site.
1876 * @return bool True if blocked, false otherwise
1878 public function isBlocked( $bFromSlave = true ) {
1879 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1883 * Get the block affecting the user, or null if the user is not blocked
1885 * @param bool $bFromSlave Whether to check the slave database instead of the master
1886 * @return Block|null
1888 public function getBlock( $bFromSlave = true ) {
1889 $this->getBlockedStatus( $bFromSlave );
1890 return $this->mBlock instanceof Block ? $this->mBlock : null;
1894 * Check if user is blocked from editing a particular article
1896 * @param Title $title Title to check
1897 * @param bool $bFromSlave Whether to check the slave database instead of the master
1898 * @return bool
1900 public function isBlockedFrom( $title, $bFromSlave = false ) {
1901 global $wgBlockAllowsUTEdit;
1903 $blocked = $this->isBlocked( $bFromSlave );
1904 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1905 // If a user's name is suppressed, they cannot make edits anywhere
1906 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
1907 && $title->getNamespace() == NS_USER_TALK ) {
1908 $blocked = false;
1909 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1912 Hooks::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1914 return $blocked;
1918 * If user is blocked, return the name of the user who placed the block
1919 * @return string Name of blocker
1921 public function blockedBy() {
1922 $this->getBlockedStatus();
1923 return $this->mBlockedby;
1927 * If user is blocked, return the specified reason for the block
1928 * @return string Blocking reason
1930 public function blockedFor() {
1931 $this->getBlockedStatus();
1932 return $this->mBlockreason;
1936 * If user is blocked, return the ID for the block
1937 * @return int Block ID
1939 public function getBlockId() {
1940 $this->getBlockedStatus();
1941 return ( $this->mBlock ? $this->mBlock->getId() : false );
1945 * Check if user is blocked on all wikis.
1946 * Do not use for actual edit permission checks!
1947 * This is intended for quick UI checks.
1949 * @param string $ip IP address, uses current client if none given
1950 * @return bool True if blocked, false otherwise
1952 public function isBlockedGlobally( $ip = '' ) {
1953 if ( $this->mBlockedGlobally !== null ) {
1954 return $this->mBlockedGlobally;
1956 // User is already an IP?
1957 if ( IP::isIPAddress( $this->getName() ) ) {
1958 $ip = $this->getName();
1959 } elseif ( !$ip ) {
1960 $ip = $this->getRequest()->getIP();
1962 $blocked = false;
1963 Hooks::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1964 $this->mBlockedGlobally = (bool)$blocked;
1965 return $this->mBlockedGlobally;
1969 * Check if user account is locked
1971 * @return bool True if locked, false otherwise
1973 public function isLocked() {
1974 if ( $this->mLocked !== null ) {
1975 return $this->mLocked;
1977 global $wgAuth;
1978 $authUser = $wgAuth->getUserInstance( $this );
1979 $this->mLocked = (bool)$authUser->isLocked();
1980 Hooks::run( 'UserIsLocked', array( $this, &$this->mLocked ) );
1981 return $this->mLocked;
1985 * Check if user account is hidden
1987 * @return bool True if hidden, false otherwise
1989 public function isHidden() {
1990 if ( $this->mHideName !== null ) {
1991 return $this->mHideName;
1993 $this->getBlockedStatus();
1994 if ( !$this->mHideName ) {
1995 global $wgAuth;
1996 $authUser = $wgAuth->getUserInstance( $this );
1997 $this->mHideName = (bool)$authUser->isHidden();
1998 Hooks::run( 'UserIsHidden', array( $this, &$this->mHideName ) );
2000 return $this->mHideName;
2004 * Get the user's ID.
2005 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2007 public function getId() {
2008 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
2009 // Special case, we know the user is anonymous
2010 return 0;
2011 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2012 // Don't load if this was initialized from an ID
2013 $this->load();
2015 return $this->mId;
2019 * Set the user and reload all fields according to a given ID
2020 * @param int $v User ID to reload
2022 public function setId( $v ) {
2023 $this->mId = $v;
2024 $this->clearInstanceCache( 'id' );
2028 * Get the user name, or the IP of an anonymous user
2029 * @return string User's name or IP address
2031 public function getName() {
2032 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2033 // Special case optimisation
2034 return $this->mName;
2035 } else {
2036 $this->load();
2037 if ( $this->mName === false ) {
2038 // Clean up IPs
2039 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
2041 return $this->mName;
2046 * Set the user name.
2048 * This does not reload fields from the database according to the given
2049 * name. Rather, it is used to create a temporary "nonexistent user" for
2050 * later addition to the database. It can also be used to set the IP
2051 * address for an anonymous user to something other than the current
2052 * remote IP.
2054 * @note User::newFromName() has roughly the same function, when the named user
2055 * does not exist.
2056 * @param string $str New user name to set
2058 public function setName( $str ) {
2059 $this->load();
2060 $this->mName = $str;
2064 * Get the user's name escaped by underscores.
2065 * @return string Username escaped by underscores.
2067 public function getTitleKey() {
2068 return str_replace( ' ', '_', $this->getName() );
2072 * Check if the user has new messages.
2073 * @return bool True if the user has new messages
2075 public function getNewtalk() {
2076 $this->load();
2078 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2079 if ( $this->mNewtalk === -1 ) {
2080 $this->mNewtalk = false; # reset talk page status
2082 // Check memcached separately for anons, who have no
2083 // entire User object stored in there.
2084 if ( !$this->mId ) {
2085 global $wgDisableAnonTalk;
2086 if ( $wgDisableAnonTalk ) {
2087 // Anon newtalk disabled by configuration.
2088 $this->mNewtalk = false;
2089 } else {
2090 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName() );
2092 } else {
2093 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
2097 return (bool)$this->mNewtalk;
2101 * Return the data needed to construct links for new talk page message
2102 * alerts. If there are new messages, this will return an associative array
2103 * with the following data:
2104 * wiki: The database name of the wiki
2105 * link: Root-relative link to the user's talk page
2106 * rev: The last talk page revision that the user has seen or null. This
2107 * is useful for building diff links.
2108 * If there are no new messages, it returns an empty array.
2109 * @note This function was designed to accomodate multiple talk pages, but
2110 * currently only returns a single link and revision.
2111 * @return array
2113 public function getNewMessageLinks() {
2114 $talks = array();
2115 if ( !Hooks::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2116 return $talks;
2117 } elseif ( !$this->getNewtalk() ) {
2118 return array();
2120 $utp = $this->getTalkPage();
2121 $dbr = wfGetDB( DB_SLAVE );
2122 // Get the "last viewed rev" timestamp from the oldest message notification
2123 $timestamp = $dbr->selectField( 'user_newtalk',
2124 'MIN(user_last_timestamp)',
2125 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2126 __METHOD__ );
2127 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2128 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2132 * Get the revision ID for the last talk page revision viewed by the talk
2133 * page owner.
2134 * @return int|null Revision ID or null
2136 public function getNewMessageRevisionId() {
2137 $newMessageRevisionId = null;
2138 $newMessageLinks = $this->getNewMessageLinks();
2139 if ( $newMessageLinks ) {
2140 // Note: getNewMessageLinks() never returns more than a single link
2141 // and it is always for the same wiki, but we double-check here in
2142 // case that changes some time in the future.
2143 if ( count( $newMessageLinks ) === 1
2144 && $newMessageLinks[0]['wiki'] === wfWikiID()
2145 && $newMessageLinks[0]['rev']
2147 /** @var Revision $newMessageRevision */
2148 $newMessageRevision = $newMessageLinks[0]['rev'];
2149 $newMessageRevisionId = $newMessageRevision->getId();
2152 return $newMessageRevisionId;
2156 * Internal uncached check for new messages
2158 * @see getNewtalk()
2159 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2160 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2161 * @return bool True if the user has new messages
2163 protected function checkNewtalk( $field, $id ) {
2164 $dbr = wfGetDB( DB_SLAVE );
2166 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__ );
2168 return $ok !== false;
2172 * Add or update the new messages flag
2173 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2174 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2175 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2176 * @return bool True if successful, false otherwise
2178 protected function updateNewtalk( $field, $id, $curRev = null ) {
2179 // Get timestamp of the talk page revision prior to the current one
2180 $prevRev = $curRev ? $curRev->getPrevious() : false;
2181 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2182 // Mark the user as having new messages since this revision
2183 $dbw = wfGetDB( DB_MASTER );
2184 $dbw->insert( 'user_newtalk',
2185 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2186 __METHOD__,
2187 'IGNORE' );
2188 if ( $dbw->affectedRows() ) {
2189 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2190 return true;
2191 } else {
2192 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2193 return false;
2198 * Clear the new messages flag for the given user
2199 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2200 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2201 * @return bool True if successful, false otherwise
2203 protected function deleteNewtalk( $field, $id ) {
2204 $dbw = wfGetDB( DB_MASTER );
2205 $dbw->delete( 'user_newtalk',
2206 array( $field => $id ),
2207 __METHOD__ );
2208 if ( $dbw->affectedRows() ) {
2209 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2210 return true;
2211 } else {
2212 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2213 return false;
2218 * Update the 'You have new messages!' status.
2219 * @param bool $val Whether the user has new messages
2220 * @param Revision $curRev New, as yet unseen revision of the user talk
2221 * page. Ignored if null or !$val.
2223 public function setNewtalk( $val, $curRev = null ) {
2224 if ( wfReadOnly() ) {
2225 return;
2228 $this->load();
2229 $this->mNewtalk = $val;
2231 if ( $this->isAnon() ) {
2232 $field = 'user_ip';
2233 $id = $this->getName();
2234 } else {
2235 $field = 'user_id';
2236 $id = $this->getId();
2239 if ( $val ) {
2240 $changed = $this->updateNewtalk( $field, $id, $curRev );
2241 } else {
2242 $changed = $this->deleteNewtalk( $field, $id );
2245 if ( $changed ) {
2246 $this->invalidateCache();
2251 * Generate a current or new-future timestamp to be stored in the
2252 * user_touched field when we update things.
2253 * @return string Timestamp in TS_MW format
2255 private function newTouchedTimestamp() {
2256 global $wgClockSkewFudge;
2258 $time = wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2259 if ( $this->mTouched && $time <= $this->mTouched ) {
2260 $time = wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $this->mTouched ) + 1 );
2263 return $time;
2267 * Clear user data from memcached
2269 * Use after applying updates to the database; caller's
2270 * responsibility to update user_touched if appropriate.
2272 * Called implicitly from invalidateCache() and saveSettings().
2274 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2276 public function clearSharedCache( $mode = 'changed' ) {
2277 if ( !$this->getId() ) {
2278 return;
2281 $cache = ObjectCache::getMainWANInstance();
2282 $key = $this->getCacheKey( $cache );
2283 if ( $mode === 'refresh' ) {
2284 $cache->delete( $key, 1 );
2285 } else {
2286 wfGetDB( DB_MASTER )->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
2287 $cache->delete( $key );
2288 } );
2293 * Immediately touch the user data cache for this account
2295 * Calls touch() and removes account data from memcached
2297 public function invalidateCache() {
2298 $this->touch();
2299 $this->clearSharedCache();
2303 * Update the "touched" timestamp for the user
2305 * This is useful on various login/logout events when making sure that
2306 * a browser or proxy that has multiple tenants does not suffer cache
2307 * pollution where the new user sees the old users content. The value
2308 * of getTouched() is checked when determining 304 vs 200 responses.
2309 * Unlike invalidateCache(), this preserves the User object cache and
2310 * avoids database writes.
2312 * @since 1.25
2314 public function touch() {
2315 $id = $this->getId();
2316 if ( $id ) {
2317 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2318 ObjectCache::getMainWANInstance()->touchCheckKey( $key );
2319 $this->mQuickTouched = null;
2324 * Validate the cache for this account.
2325 * @param string $timestamp A timestamp in TS_MW format
2326 * @return bool
2328 public function validateCache( $timestamp ) {
2329 return ( $timestamp >= $this->getTouched() );
2333 * Get the user touched timestamp
2335 * Use this value only to validate caches via inequalities
2336 * such as in the case of HTTP If-Modified-Since response logic
2338 * @return string TS_MW Timestamp
2340 public function getTouched() {
2341 $this->load();
2343 if ( $this->mId ) {
2344 if ( $this->mQuickTouched === null ) {
2345 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId );
2346 $cache = ObjectCache::getMainWANInstance();
2348 $this->mQuickTouched = wfTimestamp( TS_MW, $cache->getCheckKeyTime( $key ) );
2351 return max( $this->mTouched, $this->mQuickTouched );
2354 return $this->mTouched;
2358 * Get the user_touched timestamp field (time of last DB updates)
2359 * @return string TS_MW Timestamp
2360 * @since 1.26
2362 public function getDBTouched() {
2363 $this->load();
2365 return $this->mTouched;
2369 * @deprecated Removed in 1.27.
2370 * @return Password
2371 * @since 1.24
2373 public function getPassword() {
2374 throw new BadMethodCallException( __METHOD__ . ' has been removed in 1.27' );
2378 * @deprecated Removed in 1.27.
2379 * @return Password
2380 * @since 1.24
2382 public function getTemporaryPassword() {
2383 throw new BadMethodCallException( __METHOD__ . ' has been removed in 1.27' );
2387 * Set the password and reset the random token.
2388 * Calls through to authentication plugin if necessary;
2389 * will have no effect if the auth plugin refuses to
2390 * pass the change through or if the legal password
2391 * checks fail.
2393 * As a special case, setting the password to null
2394 * wipes it, so the account cannot be logged in until
2395 * a new password is set, for instance via e-mail.
2397 * @deprecated since 1.27. AuthManager is coming.
2398 * @param string $str New password to set
2399 * @throws PasswordError On failure
2400 * @return bool
2402 public function setPassword( $str ) {
2403 global $wgAuth;
2405 if ( $str !== null ) {
2406 if ( !$wgAuth->allowPasswordChange() ) {
2407 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2410 $status = $this->checkPasswordValidity( $str );
2411 if ( !$status->isGood() ) {
2412 throw new PasswordError( $status->getMessage()->text() );
2416 if ( !$wgAuth->setPassword( $this, $str ) ) {
2417 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2420 $this->setToken();
2421 $this->setOption( 'watchlisttoken', false );
2422 $this->setPasswordInternal( $str );
2424 return true;
2428 * Set the password and reset the random token unconditionally.
2430 * @deprecated since 1.27. AuthManager is coming.
2431 * @param string|null $str New password to set or null to set an invalid
2432 * password hash meaning that the user will not be able to log in
2433 * through the web interface.
2435 public function setInternalPassword( $str ) {
2436 global $wgAuth;
2438 if ( $wgAuth->allowSetLocalPassword() ) {
2439 $this->setToken();
2440 $this->setOption( 'watchlisttoken', false );
2441 $this->setPasswordInternal( $str );
2446 * Actually set the password and such
2447 * @since 1.27 cannot set a password for a user not in the database
2448 * @param string|null $str New password to set or null to set an invalid
2449 * password hash meaning that the user will not be able to log in
2450 * through the web interface.
2452 private function setPasswordInternal( $str ) {
2453 $id = self::idFromName( $this->getName(), self::READ_LATEST );
2454 if ( $id == 0 ) {
2455 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2458 $passwordFactory = new PasswordFactory();
2459 $passwordFactory->init( RequestContext::getMain()->getConfig() );
2460 $dbw = wfGetDB( DB_MASTER );
2461 $dbw->update(
2462 'user',
2463 array(
2464 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2465 'user_newpassword' => PasswordFactory::newInvalidPassword()->toString(),
2466 'user_newpass_time' => $dbw->timestampOrNull( null ),
2468 array(
2469 'user_id' => $id,
2471 __METHOD__
2474 // When the main password is changed, invalidate all bot passwords too
2475 BotPassword::invalidateAllPasswordsForUser( $this->getName() );
2479 * Get the user's current token.
2480 * @param bool $forceCreation Force the generation of a new token if the
2481 * user doesn't have one (default=true for backwards compatibility).
2482 * @return string|null Token
2484 public function getToken( $forceCreation = true ) {
2485 global $wgAuthenticationTokenVersion;
2487 $this->load();
2488 if ( !$this->mToken && $forceCreation ) {
2489 $this->setToken();
2492 // If the user doesn't have a token, return null to indicate that.
2493 // Otherwise, hmac the version with the secret if we have a version.
2494 if ( !$this->mToken ) {
2495 return null;
2496 } elseif ( $wgAuthenticationTokenVersion === null ) {
2497 return $this->mToken;
2498 } else {
2499 $ret = MWCryptHash::hmac( $wgAuthenticationTokenVersion, $this->mToken, false );
2501 // The raw hash can be overly long. Shorten it up.
2502 $len = max( 32, self::TOKEN_LENGTH );
2503 if ( strlen( $ret ) < $len ) {
2504 // Should never happen, even md5 is 128 bits
2505 throw new \UnexpectedValueException( 'Hmac returned less than 128 bits' );
2507 return substr( $ret, -$len );
2512 * Set the random token (used for persistent authentication)
2513 * Called from loadDefaults() among other places.
2515 * @param string|bool $token If specified, set the token to this value
2517 public function setToken( $token = false ) {
2518 $this->load();
2519 if ( !$token ) {
2520 $this->mToken = MWCryptRand::generateHex( self::TOKEN_LENGTH );
2521 } else {
2522 $this->mToken = $token;
2527 * Set the password for a password reminder or new account email
2529 * @deprecated since 1.27, AuthManager is coming
2530 * @param string $str New password to set or null to set an invalid
2531 * password hash meaning that the user will not be able to use it
2532 * @param bool $throttle If true, reset the throttle timestamp to the present
2534 public function setNewpassword( $str, $throttle = true ) {
2535 $id = $this->getId();
2536 if ( $id == 0 ) {
2537 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2540 $dbw = wfGetDB( DB_MASTER );
2542 $passwordFactory = new PasswordFactory();
2543 $passwordFactory->init( RequestContext::getMain()->getConfig() );
2544 $update = array(
2545 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2548 if ( $str === null ) {
2549 $update['user_newpass_time'] = null;
2550 } elseif ( $throttle ) {
2551 $update['user_newpass_time'] = $dbw->timestamp();
2554 $dbw->update( 'user', $update, array( 'user_id' => $id ), __METHOD__ );
2558 * Has password reminder email been sent within the last
2559 * $wgPasswordReminderResendTime hours?
2560 * @return bool
2562 public function isPasswordReminderThrottled() {
2563 global $wgPasswordReminderResendTime;
2565 if ( !$wgPasswordReminderResendTime ) {
2566 return false;
2569 $this->load();
2571 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
2572 ? wfGetDB( DB_MASTER )
2573 : wfGetDB( DB_SLAVE );
2574 $newpassTime = $db->selectField(
2575 'user',
2576 'user_newpass_time',
2577 array( 'user_id' => $this->getId() ),
2578 __METHOD__
2581 if ( $newpassTime === null ) {
2582 return false;
2584 $expiry = wfTimestamp( TS_UNIX, $newpassTime ) + $wgPasswordReminderResendTime * 3600;
2585 return time() < $expiry;
2589 * Get the user's e-mail address
2590 * @return string User's email address
2592 public function getEmail() {
2593 $this->load();
2594 Hooks::run( 'UserGetEmail', array( $this, &$this->mEmail ) );
2595 return $this->mEmail;
2599 * Get the timestamp of the user's e-mail authentication
2600 * @return string TS_MW timestamp
2602 public function getEmailAuthenticationTimestamp() {
2603 $this->load();
2604 Hooks::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2605 return $this->mEmailAuthenticated;
2609 * Set the user's e-mail address
2610 * @param string $str New e-mail address
2612 public function setEmail( $str ) {
2613 $this->load();
2614 if ( $str == $this->mEmail ) {
2615 return;
2617 $this->invalidateEmail();
2618 $this->mEmail = $str;
2619 Hooks::run( 'UserSetEmail', array( $this, &$this->mEmail ) );
2623 * Set the user's e-mail address and a confirmation mail if needed.
2625 * @since 1.20
2626 * @param string $str New e-mail address
2627 * @return Status
2629 public function setEmailWithConfirmation( $str ) {
2630 global $wgEnableEmail, $wgEmailAuthentication;
2632 if ( !$wgEnableEmail ) {
2633 return Status::newFatal( 'emaildisabled' );
2636 $oldaddr = $this->getEmail();
2637 if ( $str === $oldaddr ) {
2638 return Status::newGood( true );
2641 $this->setEmail( $str );
2643 if ( $str !== '' && $wgEmailAuthentication ) {
2644 // Send a confirmation request to the new address if needed
2645 $type = $oldaddr != '' ? 'changed' : 'set';
2646 $result = $this->sendConfirmationMail( $type );
2647 if ( $result->isGood() ) {
2648 // Say to the caller that a confirmation mail has been sent
2649 $result->value = 'eauth';
2651 } else {
2652 $result = Status::newGood( true );
2655 return $result;
2659 * Get the user's real name
2660 * @return string User's real name
2662 public function getRealName() {
2663 if ( !$this->isItemLoaded( 'realname' ) ) {
2664 $this->load();
2667 return $this->mRealName;
2671 * Set the user's real name
2672 * @param string $str New real name
2674 public function setRealName( $str ) {
2675 $this->load();
2676 $this->mRealName = $str;
2680 * Get the user's current setting for a given option.
2682 * @param string $oname The option to check
2683 * @param string $defaultOverride A default value returned if the option does not exist
2684 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2685 * @return string User's current value for the option
2686 * @see getBoolOption()
2687 * @see getIntOption()
2689 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2690 global $wgHiddenPrefs;
2691 $this->loadOptions();
2693 # We want 'disabled' preferences to always behave as the default value for
2694 # users, even if they have set the option explicitly in their settings (ie they
2695 # set it, and then it was disabled removing their ability to change it). But
2696 # we don't want to erase the preferences in the database in case the preference
2697 # is re-enabled again. So don't touch $mOptions, just override the returned value
2698 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2699 return self::getDefaultOption( $oname );
2702 if ( array_key_exists( $oname, $this->mOptions ) ) {
2703 return $this->mOptions[$oname];
2704 } else {
2705 return $defaultOverride;
2710 * Get all user's options
2712 * @param int $flags Bitwise combination of:
2713 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2714 * to the default value. (Since 1.25)
2715 * @return array
2717 public function getOptions( $flags = 0 ) {
2718 global $wgHiddenPrefs;
2719 $this->loadOptions();
2720 $options = $this->mOptions;
2722 # We want 'disabled' preferences to always behave as the default value for
2723 # users, even if they have set the option explicitly in their settings (ie they
2724 # set it, and then it was disabled removing their ability to change it). But
2725 # we don't want to erase the preferences in the database in case the preference
2726 # is re-enabled again. So don't touch $mOptions, just override the returned value
2727 foreach ( $wgHiddenPrefs as $pref ) {
2728 $default = self::getDefaultOption( $pref );
2729 if ( $default !== null ) {
2730 $options[$pref] = $default;
2734 if ( $flags & self::GETOPTIONS_EXCLUDE_DEFAULTS ) {
2735 $options = array_diff_assoc( $options, self::getDefaultOptions() );
2738 return $options;
2742 * Get the user's current setting for a given option, as a boolean value.
2744 * @param string $oname The option to check
2745 * @return bool User's current value for the option
2746 * @see getOption()
2748 public function getBoolOption( $oname ) {
2749 return (bool)$this->getOption( $oname );
2753 * Get the user's current setting for a given option, as an integer value.
2755 * @param string $oname The option to check
2756 * @param int $defaultOverride A default value returned if the option does not exist
2757 * @return int User's current value for the option
2758 * @see getOption()
2760 public function getIntOption( $oname, $defaultOverride = 0 ) {
2761 $val = $this->getOption( $oname );
2762 if ( $val == '' ) {
2763 $val = $defaultOverride;
2765 return intval( $val );
2769 * Set the given option for a user.
2771 * You need to call saveSettings() to actually write to the database.
2773 * @param string $oname The option to set
2774 * @param mixed $val New value to set
2776 public function setOption( $oname, $val ) {
2777 $this->loadOptions();
2779 // Explicitly NULL values should refer to defaults
2780 if ( is_null( $val ) ) {
2781 $val = self::getDefaultOption( $oname );
2784 $this->mOptions[$oname] = $val;
2788 * Get a token stored in the preferences (like the watchlist one),
2789 * resetting it if it's empty (and saving changes).
2791 * @param string $oname The option name to retrieve the token from
2792 * @return string|bool User's current value for the option, or false if this option is disabled.
2793 * @see resetTokenFromOption()
2794 * @see getOption()
2795 * @deprecated 1.26 Applications should use the OAuth extension
2797 public function getTokenFromOption( $oname ) {
2798 global $wgHiddenPrefs;
2800 $id = $this->getId();
2801 if ( !$id || in_array( $oname, $wgHiddenPrefs ) ) {
2802 return false;
2805 $token = $this->getOption( $oname );
2806 if ( !$token ) {
2807 // Default to a value based on the user token to avoid space
2808 // wasted on storing tokens for all users. When this option
2809 // is set manually by the user, only then is it stored.
2810 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2813 return $token;
2817 * Reset a token stored in the preferences (like the watchlist one).
2818 * *Does not* save user's preferences (similarly to setOption()).
2820 * @param string $oname The option name to reset the token in
2821 * @return string|bool New token value, or false if this option is disabled.
2822 * @see getTokenFromOption()
2823 * @see setOption()
2825 public function resetTokenFromOption( $oname ) {
2826 global $wgHiddenPrefs;
2827 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2828 return false;
2831 $token = MWCryptRand::generateHex( 40 );
2832 $this->setOption( $oname, $token );
2833 return $token;
2837 * Return a list of the types of user options currently returned by
2838 * User::getOptionKinds().
2840 * Currently, the option kinds are:
2841 * - 'registered' - preferences which are registered in core MediaWiki or
2842 * by extensions using the UserGetDefaultOptions hook.
2843 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2844 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2845 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2846 * be used by user scripts.
2847 * - 'special' - "preferences" that are not accessible via User::getOptions
2848 * or User::setOptions.
2849 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2850 * These are usually legacy options, removed in newer versions.
2852 * The API (and possibly others) use this function to determine the possible
2853 * option types for validation purposes, so make sure to update this when a
2854 * new option kind is added.
2856 * @see User::getOptionKinds
2857 * @return array Option kinds
2859 public static function listOptionKinds() {
2860 return array(
2861 'registered',
2862 'registered-multiselect',
2863 'registered-checkmatrix',
2864 'userjs',
2865 'special',
2866 'unused'
2871 * Return an associative array mapping preferences keys to the kind of a preference they're
2872 * used for. Different kinds are handled differently when setting or reading preferences.
2874 * See User::listOptionKinds for the list of valid option types that can be provided.
2876 * @see User::listOptionKinds
2877 * @param IContextSource $context
2878 * @param array $options Assoc. array with options keys to check as keys.
2879 * Defaults to $this->mOptions.
2880 * @return array The key => kind mapping data
2882 public function getOptionKinds( IContextSource $context, $options = null ) {
2883 $this->loadOptions();
2884 if ( $options === null ) {
2885 $options = $this->mOptions;
2888 $prefs = Preferences::getPreferences( $this, $context );
2889 $mapping = array();
2891 // Pull out the "special" options, so they don't get converted as
2892 // multiselect or checkmatrix.
2893 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
2894 foreach ( $specialOptions as $name => $value ) {
2895 unset( $prefs[$name] );
2898 // Multiselect and checkmatrix options are stored in the database with
2899 // one key per option, each having a boolean value. Extract those keys.
2900 $multiselectOptions = array();
2901 foreach ( $prefs as $name => $info ) {
2902 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2903 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2904 $opts = HTMLFormField::flattenOptions( $info['options'] );
2905 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2907 foreach ( $opts as $value ) {
2908 $multiselectOptions["$prefix$value"] = true;
2911 unset( $prefs[$name] );
2914 $checkmatrixOptions = array();
2915 foreach ( $prefs as $name => $info ) {
2916 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2917 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2918 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2919 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2920 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2922 foreach ( $columns as $column ) {
2923 foreach ( $rows as $row ) {
2924 $checkmatrixOptions["$prefix$column-$row"] = true;
2928 unset( $prefs[$name] );
2932 // $value is ignored
2933 foreach ( $options as $key => $value ) {
2934 if ( isset( $prefs[$key] ) ) {
2935 $mapping[$key] = 'registered';
2936 } elseif ( isset( $multiselectOptions[$key] ) ) {
2937 $mapping[$key] = 'registered-multiselect';
2938 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2939 $mapping[$key] = 'registered-checkmatrix';
2940 } elseif ( isset( $specialOptions[$key] ) ) {
2941 $mapping[$key] = 'special';
2942 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2943 $mapping[$key] = 'userjs';
2944 } else {
2945 $mapping[$key] = 'unused';
2949 return $mapping;
2953 * Reset certain (or all) options to the site defaults
2955 * The optional parameter determines which kinds of preferences will be reset.
2956 * Supported values are everything that can be reported by getOptionKinds()
2957 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2959 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2960 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2961 * for backwards-compatibility.
2962 * @param IContextSource|null $context Context source used when $resetKinds
2963 * does not contain 'all', passed to getOptionKinds().
2964 * Defaults to RequestContext::getMain() when null.
2966 public function resetOptions(
2967 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2968 IContextSource $context = null
2970 $this->load();
2971 $defaultOptions = self::getDefaultOptions();
2973 if ( !is_array( $resetKinds ) ) {
2974 $resetKinds = array( $resetKinds );
2977 if ( in_array( 'all', $resetKinds ) ) {
2978 $newOptions = $defaultOptions;
2979 } else {
2980 if ( $context === null ) {
2981 $context = RequestContext::getMain();
2984 $optionKinds = $this->getOptionKinds( $context );
2985 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2986 $newOptions = array();
2988 // Use default values for the options that should be deleted, and
2989 // copy old values for the ones that shouldn't.
2990 foreach ( $this->mOptions as $key => $value ) {
2991 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2992 if ( array_key_exists( $key, $defaultOptions ) ) {
2993 $newOptions[$key] = $defaultOptions[$key];
2995 } else {
2996 $newOptions[$key] = $value;
3001 Hooks::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions, $resetKinds ) );
3003 $this->mOptions = $newOptions;
3004 $this->mOptionsLoaded = true;
3008 * Get the user's preferred date format.
3009 * @return string User's preferred date format
3011 public function getDatePreference() {
3012 // Important migration for old data rows
3013 if ( is_null( $this->mDatePreference ) ) {
3014 global $wgLang;
3015 $value = $this->getOption( 'date' );
3016 $map = $wgLang->getDatePreferenceMigrationMap();
3017 if ( isset( $map[$value] ) ) {
3018 $value = $map[$value];
3020 $this->mDatePreference = $value;
3022 return $this->mDatePreference;
3026 * Determine based on the wiki configuration and the user's options,
3027 * whether this user must be over HTTPS no matter what.
3029 * @return bool
3031 public function requiresHTTPS() {
3032 global $wgSecureLogin;
3033 if ( !$wgSecureLogin ) {
3034 return false;
3035 } else {
3036 $https = $this->getBoolOption( 'prefershttps' );
3037 Hooks::run( 'UserRequiresHTTPS', array( $this, &$https ) );
3038 if ( $https ) {
3039 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3041 return $https;
3046 * Get the user preferred stub threshold
3048 * @return int
3050 public function getStubThreshold() {
3051 global $wgMaxArticleSize; # Maximum article size, in Kb
3052 $threshold = $this->getIntOption( 'stubthreshold' );
3053 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3054 // If they have set an impossible value, disable the preference
3055 // so we can use the parser cache again.
3056 $threshold = 0;
3058 return $threshold;
3062 * Get the permissions this user has.
3063 * @return array Array of String permission names
3065 public function getRights() {
3066 if ( is_null( $this->mRights ) ) {
3067 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
3069 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3070 if ( $allowedRights !== null ) {
3071 $this->mRights = array_intersect( $this->mRights, $allowedRights );
3074 Hooks::run( 'UserGetRights', array( $this, &$this->mRights ) );
3075 // Force reindexation of rights when a hook has unset one of them
3076 $this->mRights = array_values( array_unique( $this->mRights ) );
3078 return $this->mRights;
3082 * Get the list of explicit group memberships this user has.
3083 * The implicit * and user groups are not included.
3084 * @return array Array of String internal group names
3086 public function getGroups() {
3087 $this->load();
3088 $this->loadGroups();
3089 return $this->mGroups;
3093 * Get the list of implicit group memberships this user has.
3094 * This includes all explicit groups, plus 'user' if logged in,
3095 * '*' for all accounts, and autopromoted groups
3096 * @param bool $recache Whether to avoid the cache
3097 * @return array Array of String internal group names
3099 public function getEffectiveGroups( $recache = false ) {
3100 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
3101 $this->mEffectiveGroups = array_unique( array_merge(
3102 $this->getGroups(), // explicit groups
3103 $this->getAutomaticGroups( $recache ) // implicit groups
3104 ) );
3105 // Hook for additional groups
3106 Hooks::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
3107 // Force reindexation of groups when a hook has unset one of them
3108 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
3110 return $this->mEffectiveGroups;
3114 * Get the list of implicit group memberships this user has.
3115 * This includes 'user' if logged in, '*' for all accounts,
3116 * and autopromoted groups
3117 * @param bool $recache Whether to avoid the cache
3118 * @return array Array of String internal group names
3120 public function getAutomaticGroups( $recache = false ) {
3121 if ( $recache || is_null( $this->mImplicitGroups ) ) {
3122 $this->mImplicitGroups = array( '*' );
3123 if ( $this->getId() ) {
3124 $this->mImplicitGroups[] = 'user';
3126 $this->mImplicitGroups = array_unique( array_merge(
3127 $this->mImplicitGroups,
3128 Autopromote::getAutopromoteGroups( $this )
3129 ) );
3131 if ( $recache ) {
3132 // Assure data consistency with rights/groups,
3133 // as getEffectiveGroups() depends on this function
3134 $this->mEffectiveGroups = null;
3137 return $this->mImplicitGroups;
3141 * Returns the groups the user has belonged to.
3143 * The user may still belong to the returned groups. Compare with getGroups().
3145 * The function will not return groups the user had belonged to before MW 1.17
3147 * @return array Names of the groups the user has belonged to.
3149 public function getFormerGroups() {
3150 $this->load();
3152 if ( is_null( $this->mFormerGroups ) ) {
3153 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
3154 ? wfGetDB( DB_MASTER )
3155 : wfGetDB( DB_SLAVE );
3156 $res = $db->select( 'user_former_groups',
3157 array( 'ufg_group' ),
3158 array( 'ufg_user' => $this->mId ),
3159 __METHOD__ );
3160 $this->mFormerGroups = array();
3161 foreach ( $res as $row ) {
3162 $this->mFormerGroups[] = $row->ufg_group;
3166 return $this->mFormerGroups;
3170 * Get the user's edit count.
3171 * @return int|null Null for anonymous users
3173 public function getEditCount() {
3174 if ( !$this->getId() ) {
3175 return null;
3178 if ( $this->mEditCount === null ) {
3179 /* Populate the count, if it has not been populated yet */
3180 $dbr = wfGetDB( DB_SLAVE );
3181 // check if the user_editcount field has been initialized
3182 $count = $dbr->selectField(
3183 'user', 'user_editcount',
3184 array( 'user_id' => $this->mId ),
3185 __METHOD__
3188 if ( $count === null ) {
3189 // it has not been initialized. do so.
3190 $count = $this->initEditCount();
3192 $this->mEditCount = $count;
3194 return (int)$this->mEditCount;
3198 * Add the user to the given group.
3199 * This takes immediate effect.
3200 * @param string $group Name of the group to add
3201 * @return bool
3203 public function addGroup( $group ) {
3204 $this->load();
3206 if ( !Hooks::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3207 return false;
3210 $dbw = wfGetDB( DB_MASTER );
3211 if ( $this->getId() ) {
3212 $dbw->insert( 'user_groups',
3213 array(
3214 'ug_user' => $this->getID(),
3215 'ug_group' => $group,
3217 __METHOD__,
3218 array( 'IGNORE' ) );
3221 $this->loadGroups();
3222 $this->mGroups[] = $group;
3223 // In case loadGroups was not called before, we now have the right twice.
3224 // Get rid of the duplicate.
3225 $this->mGroups = array_unique( $this->mGroups );
3227 // Refresh the groups caches, and clear the rights cache so it will be
3228 // refreshed on the next call to $this->getRights().
3229 $this->getEffectiveGroups( true );
3230 $this->mRights = null;
3232 $this->invalidateCache();
3234 return true;
3238 * Remove the user from the given group.
3239 * This takes immediate effect.
3240 * @param string $group Name of the group to remove
3241 * @return bool
3243 public function removeGroup( $group ) {
3244 $this->load();
3245 if ( !Hooks::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3246 return false;
3249 $dbw = wfGetDB( DB_MASTER );
3250 $dbw->delete( 'user_groups',
3251 array(
3252 'ug_user' => $this->getID(),
3253 'ug_group' => $group,
3254 ), __METHOD__
3256 // Remember that the user was in this group
3257 $dbw->insert( 'user_former_groups',
3258 array(
3259 'ufg_user' => $this->getID(),
3260 'ufg_group' => $group,
3262 __METHOD__,
3263 array( 'IGNORE' )
3266 $this->loadGroups();
3267 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
3269 // Refresh the groups caches, and clear the rights cache so it will be
3270 // refreshed on the next call to $this->getRights().
3271 $this->getEffectiveGroups( true );
3272 $this->mRights = null;
3274 $this->invalidateCache();
3276 return true;
3280 * Get whether the user is logged in
3281 * @return bool
3283 public function isLoggedIn() {
3284 return $this->getID() != 0;
3288 * Get whether the user is anonymous
3289 * @return bool
3291 public function isAnon() {
3292 return !$this->isLoggedIn();
3296 * Check if user is allowed to access a feature / make an action
3298 * @param string ... Permissions to test
3299 * @return bool True if user is allowed to perform *any* of the given actions
3301 public function isAllowedAny() {
3302 $permissions = func_get_args();
3303 foreach ( $permissions as $permission ) {
3304 if ( $this->isAllowed( $permission ) ) {
3305 return true;
3308 return false;
3313 * @param string ... Permissions to test
3314 * @return bool True if the user is allowed to perform *all* of the given actions
3316 public function isAllowedAll() {
3317 $permissions = func_get_args();
3318 foreach ( $permissions as $permission ) {
3319 if ( !$this->isAllowed( $permission ) ) {
3320 return false;
3323 return true;
3327 * Internal mechanics of testing a permission
3328 * @param string $action
3329 * @return bool
3331 public function isAllowed( $action = '' ) {
3332 if ( $action === '' ) {
3333 return true; // In the spirit of DWIM
3335 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3336 // by misconfiguration: 0 == 'foo'
3337 return in_array( $action, $this->getRights(), true );
3341 * Check whether to enable recent changes patrol features for this user
3342 * @return bool True or false
3344 public function useRCPatrol() {
3345 global $wgUseRCPatrol;
3346 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3350 * Check whether to enable new pages patrol features for this user
3351 * @return bool True or false
3353 public function useNPPatrol() {
3354 global $wgUseRCPatrol, $wgUseNPPatrol;
3355 return (
3356 ( $wgUseRCPatrol || $wgUseNPPatrol )
3357 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3362 * Check whether to enable new files patrol features for this user
3363 * @return bool True or false
3365 public function useFilePatrol() {
3366 global $wgUseRCPatrol, $wgUseFilePatrol;
3367 return (
3368 ( $wgUseRCPatrol || $wgUseFilePatrol )
3369 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3374 * Get the WebRequest object to use with this object
3376 * @return WebRequest
3378 public function getRequest() {
3379 if ( $this->mRequest ) {
3380 return $this->mRequest;
3381 } else {
3382 global $wgRequest;
3383 return $wgRequest;
3388 * Get a WatchedItem for this user and $title.
3390 * @since 1.22 $checkRights parameter added
3391 * @param Title $title
3392 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3393 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3394 * @return WatchedItem
3396 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3397 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3399 if ( isset( $this->mWatchedItems[$key] ) ) {
3400 return $this->mWatchedItems[$key];
3403 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
3404 $this->mWatchedItems = array();
3407 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
3408 return $this->mWatchedItems[$key];
3412 * Check the watched status of an article.
3413 * @since 1.22 $checkRights parameter added
3414 * @param Title $title Title of the article to look at
3415 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3416 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3417 * @return bool
3419 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3420 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3424 * Watch an article.
3425 * @since 1.22 $checkRights parameter added
3426 * @param Title $title Title of the article to look at
3427 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3428 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3430 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3431 $this->getWatchedItem( $title, $checkRights )->addWatch();
3432 $this->invalidateCache();
3436 * Stop watching an article.
3437 * @since 1.22 $checkRights parameter added
3438 * @param Title $title Title of the article to look at
3439 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3440 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3442 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3443 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3444 $this->invalidateCache();
3448 * Clear the user's notification timestamp for the given title.
3449 * If e-notif e-mails are on, they will receive notification mails on
3450 * the next change of the page if it's watched etc.
3451 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3452 * @param Title $title Title of the article to look at
3453 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3455 public function clearNotification( &$title, $oldid = 0 ) {
3456 global $wgUseEnotif, $wgShowUpdatedMarker;
3458 // Do nothing if the database is locked to writes
3459 if ( wfReadOnly() ) {
3460 return;
3463 // Do nothing if not allowed to edit the watchlist
3464 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3465 return;
3468 // If we're working on user's talk page, we should update the talk page message indicator
3469 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3470 if ( !Hooks::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3471 return;
3474 $that = $this;
3475 // Try to update the DB post-send and only if needed...
3476 DeferredUpdates::addCallableUpdate( function() use ( $that, $title, $oldid ) {
3477 if ( !$that->getNewtalk() ) {
3478 return; // no notifications to clear
3481 // Delete the last notifications (they stack up)
3482 $that->setNewtalk( false );
3484 // If there is a new, unseen, revision, use its timestamp
3485 $nextid = $oldid
3486 ? $title->getNextRevisionID( $oldid, Title::GAID_FOR_UPDATE )
3487 : null;
3488 if ( $nextid ) {
3489 $that->setNewtalk( true, Revision::newFromId( $nextid ) );
3491 } );
3494 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3495 return;
3498 if ( $this->isAnon() ) {
3499 // Nothing else to do...
3500 return;
3503 // Only update the timestamp if the page is being watched.
3504 // The query to find out if it is watched is cached both in memcached and per-invocation,
3505 // and when it does have to be executed, it can be on a slave
3506 // If this is the user's newtalk page, we always update the timestamp
3507 $force = '';
3508 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3509 $force = 'force';
3512 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3513 $force, $oldid
3518 * Resets all of the given user's page-change notification timestamps.
3519 * If e-notif e-mails are on, they will receive notification mails on
3520 * the next change of any watched page.
3521 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3523 public function clearAllNotifications() {
3524 if ( wfReadOnly() ) {
3525 return;
3528 // Do nothing if not allowed to edit the watchlist
3529 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3530 return;
3533 global $wgUseEnotif, $wgShowUpdatedMarker;
3534 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3535 $this->setNewtalk( false );
3536 return;
3538 $id = $this->getId();
3539 if ( $id != 0 ) {
3540 $dbw = wfGetDB( DB_MASTER );
3541 $dbw->update( 'watchlist',
3542 array( /* SET */ 'wl_notificationtimestamp' => null ),
3543 array( /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ),
3544 __METHOD__
3546 // We also need to clear here the "you have new message" notification for the own user_talk page;
3547 // it's cleared one page view later in WikiPage::doViewUpdates().
3552 * Set a cookie on the user's client. Wrapper for
3553 * WebResponse::setCookie
3554 * @deprecated since 1.27
3555 * @param string $name Name of the cookie to set
3556 * @param string $value Value to set
3557 * @param int $exp Expiration time, as a UNIX time value;
3558 * if 0 or not specified, use the default $wgCookieExpiration
3559 * @param bool $secure
3560 * true: Force setting the secure attribute when setting the cookie
3561 * false: Force NOT setting the secure attribute when setting the cookie
3562 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3563 * @param array $params Array of options sent passed to WebResponse::setcookie()
3564 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3565 * is passed.
3567 protected function setCookie(
3568 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3570 wfDeprecated( __METHOD__, '1.27' );
3571 if ( $request === null ) {
3572 $request = $this->getRequest();
3574 $params['secure'] = $secure;
3575 $request->response()->setCookie( $name, $value, $exp, $params );
3579 * Clear a cookie on the user's client
3580 * @deprecated since 1.27
3581 * @param string $name Name of the cookie to clear
3582 * @param bool $secure
3583 * true: Force setting the secure attribute when setting the cookie
3584 * false: Force NOT setting the secure attribute when setting the cookie
3585 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3586 * @param array $params Array of options sent passed to WebResponse::setcookie()
3588 protected function clearCookie( $name, $secure = null, $params = array() ) {
3589 wfDeprecated( __METHOD__, '1.27' );
3590 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3594 * Set an extended login cookie on the user's client. The expiry of the cookie
3595 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3596 * variable.
3598 * @see User::setCookie
3600 * @deprecated since 1.27
3601 * @param string $name Name of the cookie to set
3602 * @param string $value Value to set
3603 * @param bool $secure
3604 * true: Force setting the secure attribute when setting the cookie
3605 * false: Force NOT setting the secure attribute when setting the cookie
3606 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3608 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3609 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3611 wfDeprecated( __METHOD__, '1.27' );
3613 $exp = time();
3614 $exp += $wgExtendedLoginCookieExpiration !== null
3615 ? $wgExtendedLoginCookieExpiration
3616 : $wgCookieExpiration;
3618 $this->setCookie( $name, $value, $exp, $secure );
3622 * Persist this user's session (e.g. set cookies)
3624 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3625 * is passed.
3626 * @param bool $secure Whether to force secure/insecure cookies or use default
3627 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3629 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3630 $this->load();
3631 if ( 0 == $this->mId ) {
3632 return;
3635 $session = $this->getRequest()->getSession();
3636 if ( $request && $session->getRequest() !== $request ) {
3637 $session = $session->sessionWithRequest( $request );
3639 $delay = $session->delaySave();
3641 if ( !$session->getUser()->equals( $this ) ) {
3642 if ( !$session->canSetUser() ) {
3643 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3644 ->warning( __METHOD__ .
3645 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3647 return;
3649 $session->setUser( $this );
3652 $session->setRememberUser( $rememberMe );
3653 if ( $secure !== null ) {
3654 $session->setForceHTTPS( $secure );
3657 $session->persist();
3659 ScopedCallback::consume( $delay );
3663 * Log this user out.
3665 public function logout() {
3666 if ( Hooks::run( 'UserLogout', array( &$this ) ) ) {
3667 $this->doLogout();
3672 * Clear the user's session, and reset the instance cache.
3673 * @see logout()
3675 public function doLogout() {
3676 $session = $this->getRequest()->getSession();
3677 if ( !$session->canSetUser() ) {
3678 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3679 ->warning( __METHOD__ . ": Cannot log out of an immutable session" );
3680 } elseif ( !$session->getUser()->equals( $this ) ) {
3681 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3682 ->warning( __METHOD__ .
3683 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3685 // But we still may as well make this user object anon
3686 $this->clearInstanceCache( 'defaults' );
3687 } else {
3688 $this->clearInstanceCache( 'defaults' );
3689 $delay = $session->delaySave();
3690 $session->setLoggedOutTimestamp( time() );
3691 $session->setUser( new User );
3692 $session->set( 'wsUserID', 0 ); // Other code expects this
3693 ScopedCallback::consume( $delay );
3698 * Save this user's settings into the database.
3699 * @todo Only rarely do all these fields need to be set!
3701 public function saveSettings() {
3702 if ( wfReadOnly() ) {
3703 // @TODO: caller should deal with this instead!
3704 // This should really just be an exception.
3705 MWExceptionHandler::logException( new DBExpectedError(
3706 null,
3707 "Could not update user with ID '{$this->mId}'; DB is read-only."
3708 ) );
3709 return;
3712 $this->load();
3713 if ( 0 == $this->mId ) {
3714 return; // anon
3717 // Get a new user_touched that is higher than the old one.
3718 // This will be used for a CAS check as a last-resort safety
3719 // check against race conditions and slave lag.
3720 $oldTouched = $this->mTouched;
3721 $newTouched = $this->newTouchedTimestamp();
3723 $dbw = wfGetDB( DB_MASTER );
3724 $dbw->update( 'user',
3725 array( /* SET */
3726 'user_name' => $this->mName,
3727 'user_real_name' => $this->mRealName,
3728 'user_email' => $this->mEmail,
3729 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3730 'user_touched' => $dbw->timestamp( $newTouched ),
3731 'user_token' => strval( $this->mToken ),
3732 'user_email_token' => $this->mEmailToken,
3733 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3734 ), array( /* WHERE */
3735 'user_id' => $this->mId,
3736 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3737 ), __METHOD__
3740 if ( !$dbw->affectedRows() ) {
3741 // Maybe the problem was a missed cache update; clear it to be safe
3742 $this->clearSharedCache( 'refresh' );
3743 // User was changed in the meantime or loaded with stale data
3744 $from = ( $this->queryFlagsUsed & self::READ_LATEST ) ? 'master' : 'slave';
3745 throw new MWException(
3746 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3747 " the version of the user to be saved is older than the current version."
3751 $this->mTouched = $newTouched;
3752 $this->saveOptions();
3754 Hooks::run( 'UserSaveSettings', array( $this ) );
3755 $this->clearSharedCache();
3756 $this->getUserPage()->invalidateCache();
3760 * If only this user's username is known, and it exists, return the user ID.
3762 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3763 * @return int
3765 public function idForName( $flags = 0 ) {
3766 $s = trim( $this->getName() );
3767 if ( $s === '' ) {
3768 return 0;
3771 $db = ( ( $flags & self::READ_LATEST ) == self::READ_LATEST )
3772 ? wfGetDB( DB_MASTER )
3773 : wfGetDB( DB_SLAVE );
3775 $options = ( ( $flags & self::READ_LOCKING ) == self::READ_LOCKING )
3776 ? array( 'LOCK IN SHARE MODE' )
3777 : array();
3779 $id = $db->selectField( 'user',
3780 'user_id', array( 'user_name' => $s ), __METHOD__, $options );
3782 return (int)$id;
3786 * Add a user to the database, return the user object
3788 * @param string $name Username to add
3789 * @param array $params Array of Strings Non-default parameters to save to
3790 * the database as user_* fields:
3791 * - email: The user's email address.
3792 * - email_authenticated: The email authentication timestamp.
3793 * - real_name: The user's real name.
3794 * - options: An associative array of non-default options.
3795 * - token: Random authentication token. Do not set.
3796 * - registration: Registration timestamp. Do not set.
3798 * @return User|null User object, or null if the username already exists.
3800 public static function createNew( $name, $params = array() ) {
3801 foreach ( array( 'password', 'newpassword', 'newpass_time', 'password_expires' ) as $field ) {
3802 if ( isset( $params[$field] ) ) {
3803 wfDeprecated( __METHOD__ . " with param '$field'", '1.27' );
3804 unset( $params[$field] );
3808 $user = new User;
3809 $user->load();
3810 $user->setToken(); // init token
3811 if ( isset( $params['options'] ) ) {
3812 $user->mOptions = $params['options'] + (array)$user->mOptions;
3813 unset( $params['options'] );
3815 $dbw = wfGetDB( DB_MASTER );
3816 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3818 $noPass = PasswordFactory::newInvalidPassword()->toString();
3820 $fields = array(
3821 'user_id' => $seqVal,
3822 'user_name' => $name,
3823 'user_password' => $noPass,
3824 'user_newpassword' => $noPass,
3825 'user_email' => $user->mEmail,
3826 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3827 'user_real_name' => $user->mRealName,
3828 'user_token' => strval( $user->mToken ),
3829 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3830 'user_editcount' => 0,
3831 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3833 foreach ( $params as $name => $value ) {
3834 $fields["user_$name"] = $value;
3836 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3837 if ( $dbw->affectedRows() ) {
3838 $newUser = User::newFromId( $dbw->insertId() );
3839 } else {
3840 $newUser = null;
3842 return $newUser;
3846 * Add this existing user object to the database. If the user already
3847 * exists, a fatal status object is returned, and the user object is
3848 * initialised with the data from the database.
3850 * Previously, this function generated a DB error due to a key conflict
3851 * if the user already existed. Many extension callers use this function
3852 * in code along the lines of:
3854 * $user = User::newFromName( $name );
3855 * if ( !$user->isLoggedIn() ) {
3856 * $user->addToDatabase();
3858 * // do something with $user...
3860 * However, this was vulnerable to a race condition (bug 16020). By
3861 * initialising the user object if the user exists, we aim to support this
3862 * calling sequence as far as possible.
3864 * Note that if the user exists, this function will acquire a write lock,
3865 * so it is still advisable to make the call conditional on isLoggedIn(),
3866 * and to commit the transaction after calling.
3868 * @throws MWException
3869 * @return Status
3871 public function addToDatabase() {
3872 $this->load();
3873 if ( !$this->mToken ) {
3874 $this->setToken(); // init token
3877 $this->mTouched = $this->newTouchedTimestamp();
3879 $noPass = PasswordFactory::newInvalidPassword()->toString();
3881 $dbw = wfGetDB( DB_MASTER );
3882 $inWrite = $dbw->writesOrCallbacksPending();
3883 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3884 $dbw->insert( 'user',
3885 array(
3886 'user_id' => $seqVal,
3887 'user_name' => $this->mName,
3888 'user_password' => $noPass,
3889 'user_newpassword' => $noPass,
3890 'user_email' => $this->mEmail,
3891 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3892 'user_real_name' => $this->mRealName,
3893 'user_token' => strval( $this->mToken ),
3894 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3895 'user_editcount' => 0,
3896 'user_touched' => $dbw->timestamp( $this->mTouched ),
3897 ), __METHOD__,
3898 array( 'IGNORE' )
3900 if ( !$dbw->affectedRows() ) {
3901 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3902 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3903 if ( $inWrite ) {
3904 // Can't commit due to pending writes that may need atomicity.
3905 // This may cause some lock contention unlike the case below.
3906 $options = array( 'LOCK IN SHARE MODE' );
3907 $flags = self::READ_LOCKING;
3908 } else {
3909 // Often, this case happens early in views before any writes when
3910 // using CentralAuth. It's should be OK to commit and break the snapshot.
3911 $dbw->commit( __METHOD__, 'flush' );
3912 $options = array();
3913 $flags = self::READ_LATEST;
3915 $this->mId = $dbw->selectField( 'user', 'user_id',
3916 array( 'user_name' => $this->mName ), __METHOD__, $options );
3917 $loaded = false;
3918 if ( $this->mId ) {
3919 if ( $this->loadFromDatabase( $flags ) ) {
3920 $loaded = true;
3923 if ( !$loaded ) {
3924 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3925 "to insert user '{$this->mName}' row, but it was not present in select!" );
3927 return Status::newFatal( 'userexists' );
3929 $this->mId = $dbw->insertId();
3930 self::$idCacheByName[$this->mName] = $this->mId;
3932 // Clear instance cache other than user table data, which is already accurate
3933 $this->clearInstanceCache();
3935 $this->saveOptions();
3936 return Status::newGood();
3940 * If this user is logged-in and blocked,
3941 * block any IP address they've successfully logged in from.
3942 * @return bool A block was spread
3944 public function spreadAnyEditBlock() {
3945 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3946 return $this->spreadBlock();
3948 return false;
3952 * If this (non-anonymous) user is blocked,
3953 * block the IP address they've successfully logged in from.
3954 * @return bool A block was spread
3956 protected function spreadBlock() {
3957 wfDebug( __METHOD__ . "()\n" );
3958 $this->load();
3959 if ( $this->mId == 0 ) {
3960 return false;
3963 $userblock = Block::newFromTarget( $this->getName() );
3964 if ( !$userblock ) {
3965 return false;
3968 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3972 * Get whether the user is explicitly blocked from account creation.
3973 * @return bool|Block
3975 public function isBlockedFromCreateAccount() {
3976 $this->getBlockedStatus();
3977 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3978 return $this->mBlock;
3981 # bug 13611: if the IP address the user is trying to create an account from is
3982 # blocked with createaccount disabled, prevent new account creation there even
3983 # when the user is logged in
3984 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3985 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3987 return $this->mBlockedFromCreateAccount instanceof Block
3988 && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3989 ? $this->mBlockedFromCreateAccount
3990 : false;
3994 * Get whether the user is blocked from using Special:Emailuser.
3995 * @return bool
3997 public function isBlockedFromEmailuser() {
3998 $this->getBlockedStatus();
3999 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
4003 * Get whether the user is allowed to create an account.
4004 * @return bool
4006 public function isAllowedToCreateAccount() {
4007 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4011 * Get this user's personal page title.
4013 * @return Title User's personal page title
4015 public function getUserPage() {
4016 return Title::makeTitle( NS_USER, $this->getName() );
4020 * Get this user's talk page title.
4022 * @return Title User's talk page title
4024 public function getTalkPage() {
4025 $title = $this->getUserPage();
4026 return $title->getTalkPage();
4030 * Determine whether the user is a newbie. Newbies are either
4031 * anonymous IPs, or the most recently created accounts.
4032 * @return bool
4034 public function isNewbie() {
4035 return !$this->isAllowed( 'autoconfirmed' );
4039 * Check to see if the given clear-text password is one of the accepted passwords
4040 * @deprecated since 1.27. AuthManager is coming.
4041 * @param string $password User password
4042 * @return bool True if the given password is correct, otherwise False
4044 public function checkPassword( $password ) {
4045 global $wgAuth, $wgLegacyEncoding;
4047 $this->load();
4049 // Some passwords will give a fatal Status, which means there is
4050 // some sort of technical or security reason for this password to
4051 // be completely invalid and should never be checked (e.g., T64685)
4052 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4053 return false;
4056 // Certain authentication plugins do NOT want to save
4057 // domain passwords in a mysql database, so we should
4058 // check this (in case $wgAuth->strict() is false).
4059 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4060 return true;
4061 } elseif ( $wgAuth->strict() ) {
4062 // Auth plugin doesn't allow local authentication
4063 return false;
4064 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4065 // Auth plugin doesn't allow local authentication for this user name
4066 return false;
4069 $passwordFactory = new PasswordFactory();
4070 $passwordFactory->init( RequestContext::getMain()->getConfig() );
4071 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
4072 ? wfGetDB( DB_MASTER )
4073 : wfGetDB( DB_SLAVE );
4075 try {
4076 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4077 'user', 'user_password', array( 'user_id' => $this->getId() ), __METHOD__
4078 ) );
4079 } catch ( PasswordError $e ) {
4080 wfDebug( 'Invalid password hash found in database.' );
4081 $mPassword = PasswordFactory::newInvalidPassword();
4084 if ( !$mPassword->equals( $password ) ) {
4085 if ( $wgLegacyEncoding ) {
4086 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4087 // Check for this with iconv
4088 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4089 if ( $cp1252Password === $password || !$mPassword->equals( $cp1252Password ) ) {
4090 return false;
4092 } else {
4093 return false;
4097 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4098 $this->setPasswordInternal( $password );
4101 return true;
4105 * Check if the given clear-text password matches the temporary password
4106 * sent by e-mail for password reset operations.
4108 * @deprecated since 1.27. AuthManager is coming.
4109 * @param string $plaintext
4110 * @return bool True if matches, false otherwise
4112 public function checkTemporaryPassword( $plaintext ) {
4113 global $wgNewPasswordExpiry;
4115 $this->load();
4117 $passwordFactory = new PasswordFactory();
4118 $passwordFactory->init( RequestContext::getMain()->getConfig() );
4119 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
4120 ? wfGetDB( DB_MASTER )
4121 : wfGetDB( DB_SLAVE );
4123 $row = $db->selectRow(
4124 'user',
4125 array( 'user_newpassword', 'user_newpass_time' ),
4126 array( 'user_id' => $this->getId() ),
4127 __METHOD__
4129 try {
4130 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword );
4131 } catch ( PasswordError $e ) {
4132 wfDebug( 'Invalid password hash found in database.' );
4133 $newPassword = PasswordFactory::newInvalidPassword();
4136 if ( $newPassword->equals( $plaintext ) ) {
4137 if ( is_null( $row->user_newpass_time ) ) {
4138 return true;
4140 $expiry = wfTimestamp( TS_UNIX, $row->user_newpass_time ) + $wgNewPasswordExpiry;
4141 return ( time() < $expiry );
4142 } else {
4143 return false;
4148 * Initialize (if necessary) and return a session token value
4149 * which can be used in edit forms to show that the user's
4150 * login credentials aren't being hijacked with a foreign form
4151 * submission.
4153 * @since 1.27
4154 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4155 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4156 * @return MediaWiki\\Session\\Token The new edit token
4158 public function getEditTokenObject( $salt = '', $request = null ) {
4159 if ( $this->isAnon() ) {
4160 return new LoggedOutEditToken();
4163 if ( !$request ) {
4164 $request = $this->getRequest();
4166 return $request->getSession()->getToken( $salt );
4170 * Initialize (if necessary) and return a session token value
4171 * which can be used in edit forms to show that the user's
4172 * login credentials aren't being hijacked with a foreign form
4173 * submission.
4175 * @since 1.19
4176 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4177 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4178 * @return string The new edit token
4180 public function getEditToken( $salt = '', $request = null ) {
4181 return $this->getEditTokenObject( $salt, $request )->toString();
4185 * Get the embedded timestamp from a token.
4186 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::getTimestamp instead.
4187 * @param string $val Input token
4188 * @return int|null
4190 public static function getEditTokenTimestamp( $val ) {
4191 wfDeprecated( __METHOD__, '1.27' );
4192 return MediaWiki\Session\Token::getTimestamp( $val );
4196 * Check given value against the token value stored in the session.
4197 * A match should confirm that the form was submitted from the
4198 * user's own login session, not a form submission from a third-party
4199 * site.
4201 * @param string $val Input value to compare
4202 * @param string $salt Optional function-specific data for hashing
4203 * @param WebRequest|null $request Object to use or null to use $wgRequest
4204 * @param int $maxage Fail tokens older than this, in seconds
4205 * @return bool Whether the token matches
4207 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4208 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4212 * Check given value against the token value stored in the session,
4213 * ignoring the suffix.
4215 * @param string $val Input value to compare
4216 * @param string $salt Optional function-specific data for hashing
4217 * @param WebRequest|null $request Object to use or null to use $wgRequest
4218 * @param int $maxage Fail tokens older than this, in seconds
4219 * @return bool Whether the token matches
4221 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4222 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self::EDIT_TOKEN_SUFFIX;
4223 return $this->matchEditToken( $val, $salt, $request, $maxage );
4227 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4228 * mail to the user's given address.
4230 * @param string $type Message to send, either "created", "changed" or "set"
4231 * @return Status
4233 public function sendConfirmationMail( $type = 'created' ) {
4234 global $wgLang;
4235 $expiration = null; // gets passed-by-ref and defined in next line.
4236 $token = $this->confirmationToken( $expiration );
4237 $url = $this->confirmationTokenUrl( $token );
4238 $invalidateURL = $this->invalidationTokenUrl( $token );
4239 $this->saveSettings();
4241 if ( $type == 'created' || $type === false ) {
4242 $message = 'confirmemail_body';
4243 } elseif ( $type === true ) {
4244 $message = 'confirmemail_body_changed';
4245 } else {
4246 // Messages: confirmemail_body_changed, confirmemail_body_set
4247 $message = 'confirmemail_body_' . $type;
4250 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4251 wfMessage( $message,
4252 $this->getRequest()->getIP(),
4253 $this->getName(),
4254 $url,
4255 $wgLang->userTimeAndDate( $expiration, $this ),
4256 $invalidateURL,
4257 $wgLang->userDate( $expiration, $this ),
4258 $wgLang->userTime( $expiration, $this ) )->text() );
4262 * Send an e-mail to this user's account. Does not check for
4263 * confirmed status or validity.
4265 * @param string $subject Message subject
4266 * @param string $body Message body
4267 * @param User|null $from Optional sending user; if unspecified, default
4268 * $wgPasswordSender will be used.
4269 * @param string $replyto Reply-To address
4270 * @return Status
4272 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4273 global $wgPasswordSender;
4275 if ( $from instanceof User ) {
4276 $sender = MailAddress::newFromUser( $from );
4277 } else {
4278 $sender = new MailAddress( $wgPasswordSender,
4279 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4281 $to = MailAddress::newFromUser( $this );
4283 return UserMailer::send( $to, $sender, $subject, $body, array(
4284 'replyTo' => $replyto,
4285 ) );
4289 * Generate, store, and return a new e-mail confirmation code.
4290 * A hash (unsalted, since it's used as a key) is stored.
4292 * @note Call saveSettings() after calling this function to commit
4293 * this change to the database.
4295 * @param string &$expiration Accepts the expiration time
4296 * @return string New token
4298 protected function confirmationToken( &$expiration ) {
4299 global $wgUserEmailConfirmationTokenExpiry;
4300 $now = time();
4301 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
4302 $expiration = wfTimestamp( TS_MW, $expires );
4303 $this->load();
4304 $token = MWCryptRand::generateHex( 32 );
4305 $hash = md5( $token );
4306 $this->mEmailToken = $hash;
4307 $this->mEmailTokenExpires = $expiration;
4308 return $token;
4312 * Return a URL the user can use to confirm their email address.
4313 * @param string $token Accepts the email confirmation token
4314 * @return string New token URL
4316 protected function confirmationTokenUrl( $token ) {
4317 return $this->getTokenUrl( 'ConfirmEmail', $token );
4321 * Return a URL the user can use to invalidate their email address.
4322 * @param string $token Accepts the email confirmation token
4323 * @return string New token URL
4325 protected function invalidationTokenUrl( $token ) {
4326 return $this->getTokenUrl( 'InvalidateEmail', $token );
4330 * Internal function to format the e-mail validation/invalidation URLs.
4331 * This uses a quickie hack to use the
4332 * hardcoded English names of the Special: pages, for ASCII safety.
4334 * @note Since these URLs get dropped directly into emails, using the
4335 * short English names avoids insanely long URL-encoded links, which
4336 * also sometimes can get corrupted in some browsers/mailers
4337 * (bug 6957 with Gmail and Internet Explorer).
4339 * @param string $page Special page
4340 * @param string $token Token
4341 * @return string Formatted URL
4343 protected function getTokenUrl( $page, $token ) {
4344 // Hack to bypass localization of 'Special:'
4345 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
4346 return $title->getCanonicalURL();
4350 * Mark the e-mail address confirmed.
4352 * @note Call saveSettings() after calling this function to commit the change.
4354 * @return bool
4356 public function confirmEmail() {
4357 // Check if it's already confirmed, so we don't touch the database
4358 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4359 if ( !$this->isEmailConfirmed() ) {
4360 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4361 Hooks::run( 'ConfirmEmailComplete', array( $this ) );
4363 return true;
4367 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4368 * address if it was already confirmed.
4370 * @note Call saveSettings() after calling this function to commit the change.
4371 * @return bool Returns true
4373 public function invalidateEmail() {
4374 $this->load();
4375 $this->mEmailToken = null;
4376 $this->mEmailTokenExpires = null;
4377 $this->setEmailAuthenticationTimestamp( null );
4378 $this->mEmail = '';
4379 Hooks::run( 'InvalidateEmailComplete', array( $this ) );
4380 return true;
4384 * Set the e-mail authentication timestamp.
4385 * @param string $timestamp TS_MW timestamp
4387 public function setEmailAuthenticationTimestamp( $timestamp ) {
4388 $this->load();
4389 $this->mEmailAuthenticated = $timestamp;
4390 Hooks::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
4394 * Is this user allowed to send e-mails within limits of current
4395 * site configuration?
4396 * @return bool
4398 public function canSendEmail() {
4399 global $wgEnableEmail, $wgEnableUserEmail;
4400 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4401 return false;
4403 $canSend = $this->isEmailConfirmed();
4404 Hooks::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4405 return $canSend;
4409 * Is this user allowed to receive e-mails within limits of current
4410 * site configuration?
4411 * @return bool
4413 public function canReceiveEmail() {
4414 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4418 * Is this user's e-mail address valid-looking and confirmed within
4419 * limits of the current site configuration?
4421 * @note If $wgEmailAuthentication is on, this may require the user to have
4422 * confirmed their address by returning a code or using a password
4423 * sent to the address from the wiki.
4425 * @return bool
4427 public function isEmailConfirmed() {
4428 global $wgEmailAuthentication;
4429 $this->load();
4430 $confirmed = true;
4431 if ( Hooks::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4432 if ( $this->isAnon() ) {
4433 return false;
4435 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4436 return false;
4438 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4439 return false;
4441 return true;
4442 } else {
4443 return $confirmed;
4448 * Check whether there is an outstanding request for e-mail confirmation.
4449 * @return bool
4451 public function isEmailConfirmationPending() {
4452 global $wgEmailAuthentication;
4453 return $wgEmailAuthentication &&
4454 !$this->isEmailConfirmed() &&
4455 $this->mEmailToken &&
4456 $this->mEmailTokenExpires > wfTimestamp();
4460 * Get the timestamp of account creation.
4462 * @return string|bool|null Timestamp of account creation, false for
4463 * non-existent/anonymous user accounts, or null if existing account
4464 * but information is not in database.
4466 public function getRegistration() {
4467 if ( $this->isAnon() ) {
4468 return false;
4470 $this->load();
4471 return $this->mRegistration;
4475 * Get the timestamp of the first edit
4477 * @return string|bool Timestamp of first edit, or false for
4478 * non-existent/anonymous user accounts.
4480 public function getFirstEditTimestamp() {
4481 if ( $this->getId() == 0 ) {
4482 return false; // anons
4484 $dbr = wfGetDB( DB_SLAVE );
4485 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4486 array( 'rev_user' => $this->getId() ),
4487 __METHOD__,
4488 array( 'ORDER BY' => 'rev_timestamp ASC' )
4490 if ( !$time ) {
4491 return false; // no edits
4493 return wfTimestamp( TS_MW, $time );
4497 * Get the permissions associated with a given list of groups
4499 * @param array $groups Array of Strings List of internal group names
4500 * @return array Array of Strings List of permission key names for given groups combined
4502 public static function getGroupPermissions( $groups ) {
4503 global $wgGroupPermissions, $wgRevokePermissions;
4504 $rights = array();
4505 // grant every granted permission first
4506 foreach ( $groups as $group ) {
4507 if ( isset( $wgGroupPermissions[$group] ) ) {
4508 $rights = array_merge( $rights,
4509 // array_filter removes empty items
4510 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4513 // now revoke the revoked permissions
4514 foreach ( $groups as $group ) {
4515 if ( isset( $wgRevokePermissions[$group] ) ) {
4516 $rights = array_diff( $rights,
4517 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4520 return array_unique( $rights );
4524 * Get all the groups who have a given permission
4526 * @param string $role Role to check
4527 * @return array Array of Strings List of internal group names with the given permission
4529 public static function getGroupsWithPermission( $role ) {
4530 global $wgGroupPermissions;
4531 $allowedGroups = array();
4532 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4533 if ( self::groupHasPermission( $group, $role ) ) {
4534 $allowedGroups[] = $group;
4537 return $allowedGroups;
4541 * Check, if the given group has the given permission
4543 * If you're wanting to check whether all users have a permission, use
4544 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4545 * from anyone.
4547 * @since 1.21
4548 * @param string $group Group to check
4549 * @param string $role Role to check
4550 * @return bool
4552 public static function groupHasPermission( $group, $role ) {
4553 global $wgGroupPermissions, $wgRevokePermissions;
4554 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4555 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4559 * Check if all users may be assumed to have the given permission
4561 * We generally assume so if the right is granted to '*' and isn't revoked
4562 * on any group. It doesn't attempt to take grants or other extension
4563 * limitations on rights into account in the general case, though, as that
4564 * would require it to always return false and defeat the purpose.
4565 * Specifically, session-based rights restrictions (such as OAuth or bot
4566 * passwords) are applied based on the current session.
4568 * @since 1.22
4569 * @param string $right Right to check
4570 * @return bool
4572 public static function isEveryoneAllowed( $right ) {
4573 global $wgGroupPermissions, $wgRevokePermissions;
4574 static $cache = array();
4576 // Use the cached results, except in unit tests which rely on
4577 // being able change the permission mid-request
4578 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4579 return $cache[$right];
4582 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4583 $cache[$right] = false;
4584 return false;
4587 // If it's revoked anywhere, then everyone doesn't have it
4588 foreach ( $wgRevokePermissions as $rights ) {
4589 if ( isset( $rights[$right] ) && $rights[$right] ) {
4590 $cache[$right] = false;
4591 return false;
4595 // Remove any rights that aren't allowed to the global-session user
4596 $allowedRights = SessionManager::getGlobalSession()->getAllowedUserRights();
4597 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4598 $cache[$right] = false;
4599 return false;
4602 // Allow extensions to say false
4603 if ( !Hooks::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4604 $cache[$right] = false;
4605 return false;
4608 $cache[$right] = true;
4609 return true;
4613 * Get the localized descriptive name for a group, if it exists
4615 * @param string $group Internal group name
4616 * @return string Localized descriptive group name
4618 public static function getGroupName( $group ) {
4619 $msg = wfMessage( "group-$group" );
4620 return $msg->isBlank() ? $group : $msg->text();
4624 * Get the localized descriptive name for a member of a group, if it exists
4626 * @param string $group Internal group name
4627 * @param string $username Username for gender (since 1.19)
4628 * @return string Localized name for group member
4630 public static function getGroupMember( $group, $username = '#' ) {
4631 $msg = wfMessage( "group-$group-member", $username );
4632 return $msg->isBlank() ? $group : $msg->text();
4636 * Return the set of defined explicit groups.
4637 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4638 * are not included, as they are defined automatically, not in the database.
4639 * @return array Array of internal group names
4641 public static function getAllGroups() {
4642 global $wgGroupPermissions, $wgRevokePermissions;
4643 return array_diff(
4644 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4645 self::getImplicitGroups()
4650 * Get a list of all available permissions.
4651 * @return string[] Array of permission names
4653 public static function getAllRights() {
4654 if ( self::$mAllRights === false ) {
4655 global $wgAvailableRights;
4656 if ( count( $wgAvailableRights ) ) {
4657 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4658 } else {
4659 self::$mAllRights = self::$mCoreRights;
4661 Hooks::run( 'UserGetAllRights', array( &self::$mAllRights ) );
4663 return self::$mAllRights;
4667 * Get a list of implicit groups
4668 * @return array Array of Strings Array of internal group names
4670 public static function getImplicitGroups() {
4671 global $wgImplicitGroups;
4673 $groups = $wgImplicitGroups;
4674 # Deprecated, use $wgImplicitGroups instead
4675 Hooks::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4677 return $groups;
4681 * Get the title of a page describing a particular group
4683 * @param string $group Internal group name
4684 * @return Title|bool Title of the page if it exists, false otherwise
4686 public static function getGroupPage( $group ) {
4687 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4688 if ( $msg->exists() ) {
4689 $title = Title::newFromText( $msg->text() );
4690 if ( is_object( $title ) ) {
4691 return $title;
4694 return false;
4698 * Create a link to the group in HTML, if available;
4699 * else return the group name.
4701 * @param string $group Internal name of the group
4702 * @param string $text The text of the link
4703 * @return string HTML link to the group
4705 public static function makeGroupLinkHTML( $group, $text = '' ) {
4706 if ( $text == '' ) {
4707 $text = self::getGroupName( $group );
4709 $title = self::getGroupPage( $group );
4710 if ( $title ) {
4711 return Linker::link( $title, htmlspecialchars( $text ) );
4712 } else {
4713 return htmlspecialchars( $text );
4718 * Create a link to the group in Wikitext, if available;
4719 * else return the group name.
4721 * @param string $group Internal name of the group
4722 * @param string $text The text of the link
4723 * @return string Wikilink to the group
4725 public static function makeGroupLinkWiki( $group, $text = '' ) {
4726 if ( $text == '' ) {
4727 $text = self::getGroupName( $group );
4729 $title = self::getGroupPage( $group );
4730 if ( $title ) {
4731 $page = $title->getFullText();
4732 return "[[$page|$text]]";
4733 } else {
4734 return $text;
4739 * Returns an array of the groups that a particular group can add/remove.
4741 * @param string $group The group to check for whether it can add/remove
4742 * @return array Array( 'add' => array( addablegroups ),
4743 * 'remove' => array( removablegroups ),
4744 * 'add-self' => array( addablegroups to self),
4745 * 'remove-self' => array( removable groups from self) )
4747 public static function changeableByGroup( $group ) {
4748 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4750 $groups = array(
4751 'add' => array(),
4752 'remove' => array(),
4753 'add-self' => array(),
4754 'remove-self' => array()
4757 if ( empty( $wgAddGroups[$group] ) ) {
4758 // Don't add anything to $groups
4759 } elseif ( $wgAddGroups[$group] === true ) {
4760 // You get everything
4761 $groups['add'] = self::getAllGroups();
4762 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4763 $groups['add'] = $wgAddGroups[$group];
4766 // Same thing for remove
4767 if ( empty( $wgRemoveGroups[$group] ) ) {
4768 // Do nothing
4769 } elseif ( $wgRemoveGroups[$group] === true ) {
4770 $groups['remove'] = self::getAllGroups();
4771 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4772 $groups['remove'] = $wgRemoveGroups[$group];
4775 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4776 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4777 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4778 if ( is_int( $key ) ) {
4779 $wgGroupsAddToSelf['user'][] = $value;
4784 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4785 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4786 if ( is_int( $key ) ) {
4787 $wgGroupsRemoveFromSelf['user'][] = $value;
4792 // Now figure out what groups the user can add to him/herself
4793 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4794 // Do nothing
4795 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4796 // No idea WHY this would be used, but it's there
4797 $groups['add-self'] = User::getAllGroups();
4798 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4799 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4802 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4803 // Do nothing
4804 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4805 $groups['remove-self'] = User::getAllGroups();
4806 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4807 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4810 return $groups;
4814 * Returns an array of groups that this user can add and remove
4815 * @return array Array( 'add' => array( addablegroups ),
4816 * 'remove' => array( removablegroups ),
4817 * 'add-self' => array( addablegroups to self),
4818 * 'remove-self' => array( removable groups from self) )
4820 public function changeableGroups() {
4821 if ( $this->isAllowed( 'userrights' ) ) {
4822 // This group gives the right to modify everything (reverse-
4823 // compatibility with old "userrights lets you change
4824 // everything")
4825 // Using array_merge to make the groups reindexed
4826 $all = array_merge( User::getAllGroups() );
4827 return array(
4828 'add' => $all,
4829 'remove' => $all,
4830 'add-self' => array(),
4831 'remove-self' => array()
4835 // Okay, it's not so simple, we will have to go through the arrays
4836 $groups = array(
4837 'add' => array(),
4838 'remove' => array(),
4839 'add-self' => array(),
4840 'remove-self' => array()
4842 $addergroups = $this->getEffectiveGroups();
4844 foreach ( $addergroups as $addergroup ) {
4845 $groups = array_merge_recursive(
4846 $groups, $this->changeableByGroup( $addergroup )
4848 $groups['add'] = array_unique( $groups['add'] );
4849 $groups['remove'] = array_unique( $groups['remove'] );
4850 $groups['add-self'] = array_unique( $groups['add-self'] );
4851 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4853 return $groups;
4857 * Deferred version of incEditCountImmediate()
4859 public function incEditCount() {
4860 $that = $this;
4861 wfGetDB( DB_MASTER )->onTransactionPreCommitOrIdle( function() use ( $that ) {
4862 $that->incEditCountImmediate();
4863 } );
4867 * Increment the user's edit-count field.
4868 * Will have no effect for anonymous users.
4869 * @since 1.26
4871 public function incEditCountImmediate() {
4872 if ( $this->isAnon() ) {
4873 return;
4876 $dbw = wfGetDB( DB_MASTER );
4877 // No rows will be "affected" if user_editcount is NULL
4878 $dbw->update(
4879 'user',
4880 array( 'user_editcount=user_editcount+1' ),
4881 array( 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ),
4882 __METHOD__
4884 // Lazy initialization check...
4885 if ( $dbw->affectedRows() == 0 ) {
4886 // Now here's a goddamn hack...
4887 $dbr = wfGetDB( DB_SLAVE );
4888 if ( $dbr !== $dbw ) {
4889 // If we actually have a slave server, the count is
4890 // at least one behind because the current transaction
4891 // has not been committed and replicated.
4892 $this->initEditCount( 1 );
4893 } else {
4894 // But if DB_SLAVE is selecting the master, then the
4895 // count we just read includes the revision that was
4896 // just added in the working transaction.
4897 $this->initEditCount();
4900 // Edit count in user cache too
4901 $this->invalidateCache();
4905 * Initialize user_editcount from data out of the revision table
4907 * @param int $add Edits to add to the count from the revision table
4908 * @return int Number of edits
4910 protected function initEditCount( $add = 0 ) {
4911 // Pull from a slave to be less cruel to servers
4912 // Accuracy isn't the point anyway here
4913 $dbr = wfGetDB( DB_SLAVE );
4914 $count = (int)$dbr->selectField(
4915 'revision',
4916 'COUNT(rev_user)',
4917 array( 'rev_user' => $this->getId() ),
4918 __METHOD__
4920 $count = $count + $add;
4922 $dbw = wfGetDB( DB_MASTER );
4923 $dbw->update(
4924 'user',
4925 array( 'user_editcount' => $count ),
4926 array( 'user_id' => $this->getId() ),
4927 __METHOD__
4930 return $count;
4934 * Get the description of a given right
4936 * @param string $right Right to query
4937 * @return string Localized description of the right
4939 public static function getRightDescription( $right ) {
4940 $key = "right-$right";
4941 $msg = wfMessage( $key );
4942 return $msg->isBlank() ? $right : $msg->text();
4946 * Make a new-style password hash
4948 * @param string $password Plain-text password
4949 * @param bool|string $salt Optional salt, may be random or the user ID.
4950 * If unspecified or false, will generate one automatically
4951 * @return string Password hash
4952 * @deprecated since 1.24, use Password class
4954 public static function crypt( $password, $salt = false ) {
4955 wfDeprecated( __METHOD__, '1.24' );
4956 $passwordFactory = new PasswordFactory();
4957 $passwordFactory->init( RequestContext::getMain()->getConfig() );
4958 $hash = $passwordFactory->newFromPlaintext( $password );
4959 return $hash->toString();
4963 * Compare a password hash with a plain-text password. Requires the user
4964 * ID if there's a chance that the hash is an old-style hash.
4966 * @param string $hash Password hash
4967 * @param string $password Plain-text password to compare
4968 * @param string|bool $userId User ID for old-style password salt
4970 * @return bool
4971 * @deprecated since 1.24, use Password class
4973 public static function comparePasswords( $hash, $password, $userId = false ) {
4974 wfDeprecated( __METHOD__, '1.24' );
4976 // Check for *really* old password hashes that don't even have a type
4977 // The old hash format was just an md5 hex hash, with no type information
4978 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4979 global $wgPasswordSalt;
4980 if ( $wgPasswordSalt ) {
4981 $password = ":B:{$userId}:{$hash}";
4982 } else {
4983 $password = ":A:{$hash}";
4987 $passwordFactory = new PasswordFactory();
4988 $passwordFactory->init( RequestContext::getMain()->getConfig() );
4989 $hash = $passwordFactory->newFromCiphertext( $hash );
4990 return $hash->equals( $password );
4994 * Add a newuser log entry for this user.
4995 * Before 1.19 the return value was always true.
4997 * @param string|bool $action Account creation type.
4998 * - String, one of the following values:
4999 * - 'create' for an anonymous user creating an account for himself.
5000 * This will force the action's performer to be the created user itself,
5001 * no matter the value of $wgUser
5002 * - 'create2' for a logged in user creating an account for someone else
5003 * - 'byemail' when the created user will receive its password by e-mail
5004 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5005 * - Boolean means whether the account was created by e-mail (deprecated):
5006 * - true will be converted to 'byemail'
5007 * - false will be converted to 'create' if this object is the same as
5008 * $wgUser and to 'create2' otherwise
5010 * @param string $reason User supplied reason
5012 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
5014 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5015 global $wgUser, $wgNewUserLog;
5016 if ( empty( $wgNewUserLog ) ) {
5017 return true; // disabled
5020 if ( $action === true ) {
5021 $action = 'byemail';
5022 } elseif ( $action === false ) {
5023 if ( $this->equals( $wgUser ) ) {
5024 $action = 'create';
5025 } else {
5026 $action = 'create2';
5030 if ( $action === 'create' || $action === 'autocreate' ) {
5031 $performer = $this;
5032 } else {
5033 $performer = $wgUser;
5036 $logEntry = new ManualLogEntry( 'newusers', $action );
5037 $logEntry->setPerformer( $performer );
5038 $logEntry->setTarget( $this->getUserPage() );
5039 $logEntry->setComment( $reason );
5040 $logEntry->setParameters( array(
5041 '4::userid' => $this->getId(),
5042 ) );
5043 $logid = $logEntry->insert();
5045 if ( $action !== 'autocreate' ) {
5046 $logEntry->publish( $logid );
5049 return (int)$logid;
5053 * Add an autocreate newuser log entry for this user
5054 * Used by things like CentralAuth and perhaps other authplugins.
5055 * Consider calling addNewUserLogEntry() directly instead.
5057 * @return bool
5059 public function addNewUserLogEntryAutoCreate() {
5060 $this->addNewUserLogEntry( 'autocreate' );
5062 return true;
5066 * Load the user options either from cache, the database or an array
5068 * @param array $data Rows for the current user out of the user_properties table
5070 protected function loadOptions( $data = null ) {
5071 global $wgContLang;
5073 $this->load();
5075 if ( $this->mOptionsLoaded ) {
5076 return;
5079 $this->mOptions = self::getDefaultOptions();
5081 if ( !$this->getId() ) {
5082 // For unlogged-in users, load language/variant options from request.
5083 // There's no need to do it for logged-in users: they can set preferences,
5084 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5085 // so don't override user's choice (especially when the user chooses site default).
5086 $variant = $wgContLang->getDefaultVariant();
5087 $this->mOptions['variant'] = $variant;
5088 $this->mOptions['language'] = $variant;
5089 $this->mOptionsLoaded = true;
5090 return;
5093 // Maybe load from the object
5094 if ( !is_null( $this->mOptionOverrides ) ) {
5095 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5096 foreach ( $this->mOptionOverrides as $key => $value ) {
5097 $this->mOptions[$key] = $value;
5099 } else {
5100 if ( !is_array( $data ) ) {
5101 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5102 // Load from database
5103 $dbr = ( $this->queryFlagsUsed & self::READ_LATEST )
5104 ? wfGetDB( DB_MASTER )
5105 : wfGetDB( DB_SLAVE );
5107 $res = $dbr->select(
5108 'user_properties',
5109 array( 'up_property', 'up_value' ),
5110 array( 'up_user' => $this->getId() ),
5111 __METHOD__
5114 $this->mOptionOverrides = array();
5115 $data = array();
5116 foreach ( $res as $row ) {
5117 $data[$row->up_property] = $row->up_value;
5120 foreach ( $data as $property => $value ) {
5121 $this->mOptionOverrides[$property] = $value;
5122 $this->mOptions[$property] = $value;
5126 $this->mOptionsLoaded = true;
5128 Hooks::run( 'UserLoadOptions', array( $this, &$this->mOptions ) );
5132 * Saves the non-default options for this user, as previously set e.g. via
5133 * setOption(), in the database's "user_properties" (preferences) table.
5134 * Usually used via saveSettings().
5136 protected function saveOptions() {
5137 $this->loadOptions();
5139 // Not using getOptions(), to keep hidden preferences in database
5140 $saveOptions = $this->mOptions;
5142 // Allow hooks to abort, for instance to save to a global profile.
5143 // Reset options to default state before saving.
5144 if ( !Hooks::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5145 return;
5148 $userId = $this->getId();
5150 $insert_rows = array(); // all the new preference rows
5151 foreach ( $saveOptions as $key => $value ) {
5152 // Don't bother storing default values
5153 $defaultOption = self::getDefaultOption( $key );
5154 if ( ( $defaultOption === null && $value !== false && $value !== null )
5155 || $value != $defaultOption
5157 $insert_rows[] = array(
5158 'up_user' => $userId,
5159 'up_property' => $key,
5160 'up_value' => $value,
5165 $dbw = wfGetDB( DB_MASTER );
5167 $res = $dbw->select( 'user_properties',
5168 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__ );
5170 // Find prior rows that need to be removed or updated. These rows will
5171 // all be deleted (the later so that INSERT IGNORE applies the new values).
5172 $keysDelete = array();
5173 foreach ( $res as $row ) {
5174 if ( !isset( $saveOptions[$row->up_property] )
5175 || strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
5177 $keysDelete[] = $row->up_property;
5181 if ( count( $keysDelete ) ) {
5182 // Do the DELETE by PRIMARY KEY for prior rows.
5183 // In the past a very large portion of calls to this function are for setting
5184 // 'rememberpassword' for new accounts (a preference that has since been removed).
5185 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5186 // caused gap locks on [max user ID,+infinity) which caused high contention since
5187 // updates would pile up on each other as they are for higher (newer) user IDs.
5188 // It might not be necessary these days, but it shouldn't hurt either.
5189 $dbw->delete( 'user_properties',
5190 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__ );
5192 // Insert the new preference rows
5193 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
5197 * Lazily instantiate and return a factory object for making passwords
5199 * @deprecated since 1.27, create a PasswordFactory directly instead
5200 * @return PasswordFactory
5202 public static function getPasswordFactory() {
5203 wfDeprecated( __METHOD__, '1.27' );
5204 $ret = new PasswordFactory();
5205 $ret->init( RequestContext::getMain()->getConfig() );
5206 return $ret;
5210 * Provide an array of HTML5 attributes to put on an input element
5211 * intended for the user to enter a new password. This may include
5212 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5214 * Do *not* use this when asking the user to enter his current password!
5215 * Regardless of configuration, users may have invalid passwords for whatever
5216 * reason (e.g., they were set before requirements were tightened up).
5217 * Only use it when asking for a new password, like on account creation or
5218 * ResetPass.
5220 * Obviously, you still need to do server-side checking.
5222 * NOTE: A combination of bugs in various browsers means that this function
5223 * actually just returns array() unconditionally at the moment. May as
5224 * well keep it around for when the browser bugs get fixed, though.
5226 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5228 * @deprecated since 1.27
5229 * @return array Array of HTML attributes suitable for feeding to
5230 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5231 * That will get confused by the boolean attribute syntax used.)
5233 public static function passwordChangeInputAttribs() {
5234 global $wgMinimalPasswordLength;
5236 if ( $wgMinimalPasswordLength == 0 ) {
5237 return array();
5240 # Note that the pattern requirement will always be satisfied if the
5241 # input is empty, so we need required in all cases.
5243 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5244 # if e-mail confirmation is being used. Since HTML5 input validation
5245 # is b0rked anyway in some browsers, just return nothing. When it's
5246 # re-enabled, fix this code to not output required for e-mail
5247 # registration.
5248 # $ret = array( 'required' );
5249 $ret = array();
5251 # We can't actually do this right now, because Opera 9.6 will print out
5252 # the entered password visibly in its error message! When other
5253 # browsers add support for this attribute, or Opera fixes its support,
5254 # we can add support with a version check to avoid doing this on Opera
5255 # versions where it will be a problem. Reported to Opera as
5256 # DSK-262266, but they don't have a public bug tracker for us to follow.
5258 if ( $wgMinimalPasswordLength > 1 ) {
5259 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5260 $ret['title'] = wfMessage( 'passwordtooshort' )
5261 ->numParams( $wgMinimalPasswordLength )->text();
5265 return $ret;
5269 * Return the list of user fields that should be selected to create
5270 * a new user object.
5271 * @return array
5273 public static function selectFields() {
5274 return array(
5275 'user_id',
5276 'user_name',
5277 'user_real_name',
5278 'user_email',
5279 'user_touched',
5280 'user_token',
5281 'user_email_authenticated',
5282 'user_email_token',
5283 'user_email_token_expires',
5284 'user_registration',
5285 'user_editcount',
5290 * Factory function for fatal permission-denied errors
5292 * @since 1.22
5293 * @param string $permission User right required
5294 * @return Status
5296 static function newFatalPermissionDeniedStatus( $permission ) {
5297 global $wgLang;
5299 $groups = array_map(
5300 array( 'User', 'makeGroupLinkWiki' ),
5301 User::getGroupsWithPermission( $permission )
5304 if ( $groups ) {
5305 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5306 } else {
5307 return Status::newFatal( 'badaccess-group0' );
5312 * Get a new instance of this user that was loaded from the master via a locking read
5314 * Use this instead of the main context User when updating that user. This avoids races
5315 * where that user was loaded from a slave or even the master but without proper locks.
5317 * @return User|null Returns null if the user was not found in the DB
5318 * @since 1.27
5320 public function getInstanceForUpdate() {
5321 if ( !$this->getId() ) {
5322 return null; // anon
5325 $user = self::newFromId( $this->getId() );
5326 if ( !$user->loadFromId( self::READ_EXCLUSIVE ) ) {
5327 return null;
5330 return $user;
5334 * Checks if two user objects point to the same user.
5336 * @since 1.25
5337 * @param User $user
5338 * @return bool
5340 public function equals( User $user ) {
5341 return $this->getName() === $user->getName();