SessionManager: Save user name to metadata even if the user doesn't exist locally
[mediawiki.git] / includes / user / User.php
blob7c2924240c67e8e4fffb37388d540953ec84a759
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 * Load the user table data for this object from the source given by mFrom.
315 * @param integer $flags User::READ_* constant bitfield
317 public function load( $flags = self::READ_NORMAL ) {
318 global $wgFullyInitialised;
320 if ( $this->mLoadedItems === true ) {
321 return;
324 // Set it now to avoid infinite recursion in accessors
325 $oldLoadedItems = $this->mLoadedItems;
326 $this->mLoadedItems = true;
327 $this->queryFlagsUsed = $flags;
329 // If this is called too early, things are likely to break.
330 if ( $this->mFrom === 'session' && empty( $wgFullyInitialised ) ) {
331 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
332 ->warning( 'User::loadFromSession called before the end of Setup.php', array(
333 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
334 ) );
335 $this->loadDefaults();
336 $this->mLoadedItems = $oldLoadedItems;
337 return;
340 switch ( $this->mFrom ) {
341 case 'defaults':
342 $this->loadDefaults();
343 break;
344 case 'name':
345 // Make sure this thread sees its own changes
346 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
347 $flags |= self::READ_LATEST;
348 $this->queryFlagsUsed = $flags;
351 $this->mId = self::idFromName( $this->mName, $flags );
352 if ( !$this->mId ) {
353 // Nonexistent user placeholder object
354 $this->loadDefaults( $this->mName );
355 } else {
356 $this->loadFromId( $flags );
358 break;
359 case 'id':
360 $this->loadFromId( $flags );
361 break;
362 case 'session':
363 if ( !$this->loadFromSession() ) {
364 // Loading from session failed. Load defaults.
365 $this->loadDefaults();
367 Hooks::run( 'UserLoadAfterLoadFromSession', array( $this ) );
368 break;
369 default:
370 throw new UnexpectedValueException(
371 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
376 * Load user table data, given mId has already been set.
377 * @param integer $flags User::READ_* constant bitfield
378 * @return bool False if the ID does not exist, true otherwise
380 public function loadFromId( $flags = self::READ_NORMAL ) {
381 if ( $this->mId == 0 ) {
382 $this->loadDefaults();
383 return false;
386 // Try cache (unless this needs data from the master DB).
387 // NOTE: if this thread called saveSettings(), the cache was cleared.
388 $latest = DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST );
389 if ( $latest || !$this->loadFromCache() ) {
390 wfDebug( "User: cache miss for user {$this->mId}\n" );
391 // Load from DB (make sure this thread sees its own changes)
392 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
393 $flags |= self::READ_LATEST;
395 if ( !$this->loadFromDatabase( $flags ) ) {
396 // Can't load from ID, user is anonymous
397 return false;
399 $this->saveToCache();
402 $this->mLoadedItems = true;
403 $this->queryFlagsUsed = $flags;
405 return true;
409 * @since 1.27
410 * @param string $wikiId
411 * @param integer $userId
413 public static function purge( $wikiId, $userId ) {
414 $cache = ObjectCache::getMainWANInstance();
415 $cache->delete( $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId ) );
419 * @since 1.27
420 * @param WANObjectCache $cache
421 * @return string
423 protected function getCacheKey( WANObjectCache $cache ) {
424 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId );
428 * Load user data from shared cache, given mId has already been set.
430 * @return bool false if the ID does not exist or data is invalid, true otherwise
431 * @since 1.25
433 protected function loadFromCache() {
434 if ( $this->mId == 0 ) {
435 $this->loadDefaults();
436 return false;
439 $cache = ObjectCache::getMainWANInstance();
440 $data = $cache->get( $this->getCacheKey( $cache ) );
441 if ( !is_array( $data ) || $data['mVersion'] < self::VERSION ) {
442 // Object is expired
443 return false;
446 wfDebug( "User: got user {$this->mId} from cache\n" );
448 // Restore from cache
449 foreach ( self::$mCacheVars as $name ) {
450 $this->$name = $data[$name];
453 return true;
457 * Save user data to the shared cache
459 * This method should not be called outside the User class
461 public function saveToCache() {
462 $this->load();
463 $this->loadGroups();
464 $this->loadOptions();
466 if ( $this->isAnon() ) {
467 // Anonymous users are uncached
468 return;
471 $data = array();
472 foreach ( self::$mCacheVars as $name ) {
473 $data[$name] = $this->$name;
475 $data['mVersion'] = self::VERSION;
476 $opts = Database::getCacheSetOptions( wfGetDB( DB_SLAVE ) );
478 $cache = ObjectCache::getMainWANInstance();
479 $key = $this->getCacheKey( $cache );
480 $cache->set( $key, $data, $cache::TTL_HOUR, $opts );
483 /** @name newFrom*() static factory methods */
484 // @{
487 * Static factory method for creation from username.
489 * This is slightly less efficient than newFromId(), so use newFromId() if
490 * you have both an ID and a name handy.
492 * @param string $name Username, validated by Title::newFromText()
493 * @param string|bool $validate Validate username. Takes the same parameters as
494 * User::getCanonicalName(), except that true is accepted as an alias
495 * for 'valid', for BC.
497 * @return User|bool User object, or false if the username is invalid
498 * (e.g. if it contains illegal characters or is an IP address). If the
499 * username is not present in the database, the result will be a user object
500 * with a name, zero user ID and default settings.
502 public static function newFromName( $name, $validate = 'valid' ) {
503 if ( $validate === true ) {
504 $validate = 'valid';
506 $name = self::getCanonicalName( $name, $validate );
507 if ( $name === false ) {
508 return false;
509 } else {
510 // Create unloaded user object
511 $u = new User;
512 $u->mName = $name;
513 $u->mFrom = 'name';
514 $u->setItemLoaded( 'name' );
515 return $u;
520 * Static factory method for creation from a given user ID.
522 * @param int $id Valid user ID
523 * @return User The corresponding User object
525 public static function newFromId( $id ) {
526 $u = new User;
527 $u->mId = $id;
528 $u->mFrom = 'id';
529 $u->setItemLoaded( 'id' );
530 return $u;
534 * Factory method to fetch whichever user has a given email confirmation code.
535 * This code is generated when an account is created or its e-mail address
536 * has changed.
538 * If the code is invalid or has expired, returns NULL.
540 * @param string $code Confirmation code
541 * @param int $flags User::READ_* bitfield
542 * @return User|null
544 public static function newFromConfirmationCode( $code, $flags = 0 ) {
545 $db = ( $flags & self::READ_LATEST ) == self::READ_LATEST
546 ? wfGetDB( DB_MASTER )
547 : wfGetDB( DB_SLAVE );
549 $id = $db->selectField(
550 'user',
551 'user_id',
552 array(
553 'user_email_token' => md5( $code ),
554 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
558 return $id ? User::newFromId( $id ) : null;
562 * Create a new user object using data from session. If the login
563 * credentials are invalid, the result is an anonymous user.
565 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
566 * @return User
568 public static function newFromSession( WebRequest $request = null ) {
569 $user = new User;
570 $user->mFrom = 'session';
571 $user->mRequest = $request;
572 return $user;
576 * Create a new user object from a user row.
577 * The row should have the following fields from the user table in it:
578 * - either user_name or user_id to load further data if needed (or both)
579 * - user_real_name
580 * - all other fields (email, etc.)
581 * It is useless to provide the remaining fields if either user_id,
582 * user_name and user_real_name are not provided because the whole row
583 * will be loaded once more from the database when accessing them.
585 * @param stdClass $row A row from the user table
586 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
587 * @return User
589 public static function newFromRow( $row, $data = null ) {
590 $user = new User;
591 $user->loadFromRow( $row, $data );
592 return $user;
596 * Static factory method for creation of a "system" user from username.
598 * A "system" user is an account that's used to attribute logged actions
599 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
600 * might include the 'Maintenance script' or 'Conversion script' accounts
601 * used by various scripts in the maintenance/ directory or accounts such
602 * as 'MediaWiki message delivery' used by the MassMessage extension.
604 * This can optionally create the user if it doesn't exist, and "steal" the
605 * account if it does exist.
607 * @param string $name Username
608 * @param array $options Options are:
609 * - validate: As for User::getCanonicalName(), default 'valid'
610 * - create: Whether to create the user if it doesn't already exist, default true
611 * - steal: Whether to reset the account's password and email if it
612 * already exists, default false
613 * @return User|null
615 public static function newSystemUser( $name, $options = array() ) {
616 $options += array(
617 'validate' => 'valid',
618 'create' => true,
619 'steal' => false,
622 $name = self::getCanonicalName( $name, $options['validate'] );
623 if ( $name === false ) {
624 return null;
627 $dbw = wfGetDB( DB_MASTER );
628 $row = $dbw->selectRow(
629 'user',
630 array_merge(
631 self::selectFields(),
632 array( 'user_password', 'user_newpassword' )
634 array( 'user_name' => $name ),
635 __METHOD__
637 if ( !$row ) {
638 // No user. Create it?
639 return $options['create'] ? self::createNew( $name ) : null;
641 $user = self::newFromRow( $row );
643 // A user is considered to exist as a non-system user if it has a
644 // password set, or a temporary password set, or an email set.
645 $passwordFactory = new PasswordFactory();
646 $passwordFactory->init( RequestContext::getMain()->getConfig() );
647 try {
648 $password = $passwordFactory->newFromCiphertext( $row->user_password );
649 } catch ( PasswordError $e ) {
650 wfDebug( 'Invalid password hash found in database.' );
651 $password = PasswordFactory::newInvalidPassword();
653 try {
654 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword );
655 } catch ( PasswordError $e ) {
656 wfDebug( 'Invalid password hash found in database.' );
657 $newpassword = PasswordFactory::newInvalidPassword();
659 if ( !$password instanceof InvalidPassword || !$newpassword instanceof InvalidPassword
660 || $user->mEmail
662 // User exists. Steal it?
663 if ( !$options['steal'] ) {
664 return null;
667 $nopass = PasswordFactory::newInvalidPassword()->toString();
669 $dbw->update(
670 'user',
671 array(
672 'user_password' => $nopass,
673 'user_newpassword' => $nopass,
674 'user_newpass_time' => null,
676 array( 'user_id' => $user->getId() ),
677 __METHOD__
679 $user->invalidateEmail();
680 $user->saveSettings();
683 SessionManager::singleton()->preventSessionsForUser( $user->getName() );
685 return $user;
688 // @}
691 * Get the username corresponding to a given user ID
692 * @param int $id User ID
693 * @return string|bool The corresponding username
695 public static function whoIs( $id ) {
696 return UserCache::singleton()->getProp( $id, 'name' );
700 * Get the real name of a user given their user ID
702 * @param int $id User ID
703 * @return string|bool The corresponding user's real name
705 public static function whoIsReal( $id ) {
706 return UserCache::singleton()->getProp( $id, 'real_name' );
710 * Get database id given a user name
711 * @param string $name Username
712 * @param integer $flags User::READ_* constant bitfield
713 * @return int|null The corresponding user's ID, or null if user is nonexistent
715 public static function idFromName( $name, $flags = self::READ_NORMAL ) {
716 $nt = Title::makeTitleSafe( NS_USER, $name );
717 if ( is_null( $nt ) ) {
718 // Illegal name
719 return null;
722 if ( !( $flags & self::READ_LATEST ) && isset( self::$idCacheByName[$name] ) ) {
723 return self::$idCacheByName[$name];
726 $db = ( $flags & self::READ_LATEST )
727 ? wfGetDB( DB_MASTER )
728 : wfGetDB( DB_SLAVE );
730 $s = $db->selectRow(
731 'user',
732 array( 'user_id' ),
733 array( 'user_name' => $nt->getText() ),
734 __METHOD__
737 if ( $s === false ) {
738 $result = null;
739 } else {
740 $result = $s->user_id;
743 self::$idCacheByName[$name] = $result;
745 if ( count( self::$idCacheByName ) > 1000 ) {
746 self::$idCacheByName = array();
749 return $result;
753 * Reset the cache used in idFromName(). For use in tests.
755 public static function resetIdByNameCache() {
756 self::$idCacheByName = array();
760 * Does the string match an anonymous IPv4 address?
762 * This function exists for username validation, in order to reject
763 * usernames which are similar in form to IP addresses. Strings such
764 * as 300.300.300.300 will return true because it looks like an IP
765 * address, despite not being strictly valid.
767 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
768 * address because the usemod software would "cloak" anonymous IP
769 * addresses like this, if we allowed accounts like this to be created
770 * new users could get the old edits of these anonymous users.
772 * @param string $name Name to match
773 * @return bool
775 public static function isIP( $name ) {
776 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
777 || IP::isIPv6( $name );
781 * Is the input a valid username?
783 * Checks if the input is a valid username, we don't want an empty string,
784 * an IP address, anything that contains slashes (would mess up subpages),
785 * is longer than the maximum allowed username size or doesn't begin with
786 * a capital letter.
788 * @param string $name Name to match
789 * @return bool
791 public static function isValidUserName( $name ) {
792 global $wgContLang, $wgMaxNameChars;
794 if ( $name == ''
795 || User::isIP( $name )
796 || strpos( $name, '/' ) !== false
797 || strlen( $name ) > $wgMaxNameChars
798 || $name != $wgContLang->ucfirst( $name )
800 wfDebugLog( 'username', __METHOD__ .
801 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
802 return false;
805 // Ensure that the name can't be misresolved as a different title,
806 // such as with extra namespace keys at the start.
807 $parsed = Title::newFromText( $name );
808 if ( is_null( $parsed )
809 || $parsed->getNamespace()
810 || strcmp( $name, $parsed->getPrefixedText() ) ) {
811 wfDebugLog( 'username', __METHOD__ .
812 ": '$name' invalid due to ambiguous prefixes" );
813 return false;
816 // Check an additional blacklist of troublemaker characters.
817 // Should these be merged into the title char list?
818 $unicodeBlacklist = '/[' .
819 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
820 '\x{00a0}' . # non-breaking space
821 '\x{2000}-\x{200f}' . # various whitespace
822 '\x{2028}-\x{202f}' . # breaks and control chars
823 '\x{3000}' . # ideographic space
824 '\x{e000}-\x{f8ff}' . # private use
825 ']/u';
826 if ( preg_match( $unicodeBlacklist, $name ) ) {
827 wfDebugLog( 'username', __METHOD__ .
828 ": '$name' invalid due to blacklisted characters" );
829 return false;
832 return true;
836 * Usernames which fail to pass this function will be blocked
837 * from user login and new account registrations, but may be used
838 * internally by batch processes.
840 * If an account already exists in this form, login will be blocked
841 * by a failure to pass this function.
843 * @param string $name Name to match
844 * @return bool
846 public static function isUsableName( $name ) {
847 global $wgReservedUsernames;
848 // Must be a valid username, obviously ;)
849 if ( !self::isValidUserName( $name ) ) {
850 return false;
853 static $reservedUsernames = false;
854 if ( !$reservedUsernames ) {
855 $reservedUsernames = $wgReservedUsernames;
856 Hooks::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
859 // Certain names may be reserved for batch processes.
860 foreach ( $reservedUsernames as $reserved ) {
861 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
862 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
864 if ( $reserved == $name ) {
865 return false;
868 return true;
872 * Usernames which fail to pass this function will be blocked
873 * from new account registrations, but may be used internally
874 * either by batch processes or by user accounts which have
875 * already been created.
877 * Additional blacklisting may be added here rather than in
878 * isValidUserName() to avoid disrupting existing accounts.
880 * @param string $name String to match
881 * @return bool
883 public static function isCreatableName( $name ) {
884 global $wgInvalidUsernameCharacters;
886 // Ensure that the username isn't longer than 235 bytes, so that
887 // (at least for the builtin skins) user javascript and css files
888 // will work. (bug 23080)
889 if ( strlen( $name ) > 235 ) {
890 wfDebugLog( 'username', __METHOD__ .
891 ": '$name' invalid due to length" );
892 return false;
895 // Preg yells if you try to give it an empty string
896 if ( $wgInvalidUsernameCharacters !== '' ) {
897 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
898 wfDebugLog( 'username', __METHOD__ .
899 ": '$name' invalid due to wgInvalidUsernameCharacters" );
900 return false;
904 return self::isUsableName( $name );
908 * Is the input a valid password for this user?
910 * @param string $password Desired password
911 * @return bool
913 public function isValidPassword( $password ) {
914 // simple boolean wrapper for getPasswordValidity
915 return $this->getPasswordValidity( $password ) === true;
919 * Given unvalidated password input, return error message on failure.
921 * @param string $password Desired password
922 * @return bool|string|array True on success, string or array of error message on failure
924 public function getPasswordValidity( $password ) {
925 $result = $this->checkPasswordValidity( $password );
926 if ( $result->isGood() ) {
927 return true;
928 } else {
929 $messages = array();
930 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
931 $messages[] = $error['message'];
933 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
934 $messages[] = $warning['message'];
936 if ( count( $messages ) === 1 ) {
937 return $messages[0];
939 return $messages;
944 * Check if this is a valid password for this user
946 * Create a Status object based on the password's validity.
947 * The Status should be set to fatal if the user should not
948 * be allowed to log in, and should have any errors that
949 * would block changing the password.
951 * If the return value of this is not OK, the password
952 * should not be checked. If the return value is not Good,
953 * the password can be checked, but the user should not be
954 * able to set their password to this.
956 * @param string $password Desired password
957 * @param string $purpose one of 'login', 'create', 'reset'
958 * @return Status
959 * @since 1.23
961 public function checkPasswordValidity( $password, $purpose = 'login' ) {
962 global $wgPasswordPolicy;
964 $upp = new UserPasswordPolicy(
965 $wgPasswordPolicy['policies'],
966 $wgPasswordPolicy['checks']
969 $status = Status::newGood();
970 $result = false; // init $result to false for the internal checks
972 if ( !Hooks::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
973 $status->error( $result );
974 return $status;
977 if ( $result === false ) {
978 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
979 return $status;
980 } elseif ( $result === true ) {
981 return $status;
982 } else {
983 $status->error( $result );
984 return $status; // the isValidPassword hook set a string $result and returned true
989 * Given unvalidated user input, return a canonical username, or false if
990 * the username is invalid.
991 * @param string $name User input
992 * @param string|bool $validate Type of validation to use:
993 * - false No validation
994 * - 'valid' Valid for batch processes
995 * - 'usable' Valid for batch processes and login
996 * - 'creatable' Valid for batch processes, login and account creation
998 * @throws InvalidArgumentException
999 * @return bool|string
1001 public static function getCanonicalName( $name, $validate = 'valid' ) {
1002 // Force usernames to capital
1003 global $wgContLang;
1004 $name = $wgContLang->ucfirst( $name );
1006 # Reject names containing '#'; these will be cleaned up
1007 # with title normalisation, but then it's too late to
1008 # check elsewhere
1009 if ( strpos( $name, '#' ) !== false ) {
1010 return false;
1013 // Clean up name according to title rules,
1014 // but only when validation is requested (bug 12654)
1015 $t = ( $validate !== false ) ?
1016 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
1017 // Check for invalid titles
1018 if ( is_null( $t ) ) {
1019 return false;
1022 // Reject various classes of invalid names
1023 global $wgAuth;
1024 $name = $wgAuth->getCanonicalName( $t->getText() );
1026 switch ( $validate ) {
1027 case false:
1028 break;
1029 case 'valid':
1030 if ( !User::isValidUserName( $name ) ) {
1031 $name = false;
1033 break;
1034 case 'usable':
1035 if ( !User::isUsableName( $name ) ) {
1036 $name = false;
1038 break;
1039 case 'creatable':
1040 if ( !User::isCreatableName( $name ) ) {
1041 $name = false;
1043 break;
1044 default:
1045 throw new InvalidArgumentException(
1046 'Invalid parameter value for $validate in ' . __METHOD__ );
1048 return $name;
1052 * Count the number of edits of a user
1054 * @param int $uid User ID to check
1055 * @return int The user's edit count
1057 * @deprecated since 1.21 in favour of User::getEditCount
1059 public static function edits( $uid ) {
1060 wfDeprecated( __METHOD__, '1.21' );
1061 $user = self::newFromId( $uid );
1062 return $user->getEditCount();
1066 * Return a random password.
1068 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1069 * @return string New random password
1071 public static function randomPassword() {
1072 global $wgMinimalPasswordLength;
1073 return PasswordFactory::generateRandomPasswordString( $wgMinimalPasswordLength );
1077 * Set cached properties to default.
1079 * @note This no longer clears uncached lazy-initialised properties;
1080 * the constructor does that instead.
1082 * @param string|bool $name
1084 public function loadDefaults( $name = false ) {
1085 $this->mId = 0;
1086 $this->mName = $name;
1087 $this->mRealName = '';
1088 $this->mEmail = '';
1089 $this->mOptionOverrides = null;
1090 $this->mOptionsLoaded = false;
1092 $loggedOut = $this->mRequest ? $this->mRequest->getSession()->getLoggedOutTimestamp() : 0;
1093 if ( $loggedOut !== 0 ) {
1094 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
1095 } else {
1096 $this->mTouched = '1'; # Allow any pages to be cached
1099 $this->mToken = null; // Don't run cryptographic functions till we need a token
1100 $this->mEmailAuthenticated = null;
1101 $this->mEmailToken = '';
1102 $this->mEmailTokenExpires = null;
1103 $this->mRegistration = wfTimestamp( TS_MW );
1104 $this->mGroups = array();
1106 Hooks::run( 'UserLoadDefaults', array( $this, $name ) );
1110 * Return whether an item has been loaded.
1112 * @param string $item Item to check. Current possibilities:
1113 * - id
1114 * - name
1115 * - realname
1116 * @param string $all 'all' to check if the whole object has been loaded
1117 * or any other string to check if only the item is available (e.g.
1118 * for optimisation)
1119 * @return bool
1121 public function isItemLoaded( $item, $all = 'all' ) {
1122 return ( $this->mLoadedItems === true && $all === 'all' ) ||
1123 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1127 * Set that an item has been loaded
1129 * @param string $item
1131 protected function setItemLoaded( $item ) {
1132 if ( is_array( $this->mLoadedItems ) ) {
1133 $this->mLoadedItems[$item] = true;
1138 * Load user data from the session.
1140 * @return bool True if the user is logged in, false otherwise.
1142 private function loadFromSession() {
1143 // Deprecated hook
1144 $result = null;
1145 Hooks::run( 'UserLoadFromSession', array( $this, &$result ), '1.27' );
1146 if ( $result !== null ) {
1147 return $result;
1150 // MediaWiki\Session\Session already did the necessary authentication of the user
1151 // returned here, so just use it if applicable.
1152 $session = $this->getRequest()->getSession();
1153 $user = $session->getUser();
1154 if ( $user->isLoggedIn() ) {
1155 $this->loadFromUserObject( $user );
1156 // Other code expects these to be set in the session, so set them.
1157 $session->set( 'wsUserID', $this->getId() );
1158 $session->set( 'wsUserName', $this->getName() );
1159 $session->set( 'wsToken', $this->mToken );
1160 return true;
1163 return false;
1167 * Load user and user_group data from the database.
1168 * $this->mId must be set, this is how the user is identified.
1170 * @param integer $flags User::READ_* constant bitfield
1171 * @return bool True if the user exists, false if the user is anonymous
1173 public function loadFromDatabase( $flags = self::READ_LATEST ) {
1174 // Paranoia
1175 $this->mId = intval( $this->mId );
1177 // Anonymous user
1178 if ( !$this->mId ) {
1179 $this->loadDefaults();
1180 return false;
1183 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
1184 $db = wfGetDB( $index );
1186 $s = $db->selectRow(
1187 'user',
1188 self::selectFields(),
1189 array( 'user_id' => $this->mId ),
1190 __METHOD__,
1191 $options
1194 $this->queryFlagsUsed = $flags;
1195 Hooks::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1197 if ( $s !== false ) {
1198 // Initialise user table data
1199 $this->loadFromRow( $s );
1200 $this->mGroups = null; // deferred
1201 $this->getEditCount(); // revalidation for nulls
1202 return true;
1203 } else {
1204 // Invalid user_id
1205 $this->mId = 0;
1206 $this->loadDefaults();
1207 return false;
1212 * Initialize this object from a row from the user table.
1214 * @param stdClass $row Row from the user table to load.
1215 * @param array $data Further user data to load into the object
1217 * user_groups Array with groups out of the user_groups table
1218 * user_properties Array with properties out of the user_properties table
1220 protected function loadFromRow( $row, $data = null ) {
1221 $all = true;
1223 $this->mGroups = null; // deferred
1225 if ( isset( $row->user_name ) ) {
1226 $this->mName = $row->user_name;
1227 $this->mFrom = 'name';
1228 $this->setItemLoaded( 'name' );
1229 } else {
1230 $all = false;
1233 if ( isset( $row->user_real_name ) ) {
1234 $this->mRealName = $row->user_real_name;
1235 $this->setItemLoaded( 'realname' );
1236 } else {
1237 $all = false;
1240 if ( isset( $row->user_id ) ) {
1241 $this->mId = intval( $row->user_id );
1242 $this->mFrom = 'id';
1243 $this->setItemLoaded( 'id' );
1244 } else {
1245 $all = false;
1248 if ( isset( $row->user_id ) && isset( $row->user_name ) ) {
1249 self::$idCacheByName[$row->user_name] = $row->user_id;
1252 if ( isset( $row->user_editcount ) ) {
1253 $this->mEditCount = $row->user_editcount;
1254 } else {
1255 $all = false;
1258 if ( isset( $row->user_touched ) ) {
1259 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1260 } else {
1261 $all = false;
1264 if ( isset( $row->user_token ) ) {
1265 // The definition for the column is binary(32), so trim the NULs
1266 // that appends. The previous definition was char(32), so trim
1267 // spaces too.
1268 $this->mToken = rtrim( $row->user_token, " \0" );
1269 if ( $this->mToken === '' ) {
1270 $this->mToken = null;
1272 } else {
1273 $all = false;
1276 if ( isset( $row->user_email ) ) {
1277 $this->mEmail = $row->user_email;
1278 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1279 $this->mEmailToken = $row->user_email_token;
1280 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1281 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1282 } else {
1283 $all = false;
1286 if ( $all ) {
1287 $this->mLoadedItems = true;
1290 if ( is_array( $data ) ) {
1291 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1292 $this->mGroups = $data['user_groups'];
1294 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1295 $this->loadOptions( $data['user_properties'] );
1301 * Load the data for this user object from another user object.
1303 * @param User $user
1305 protected function loadFromUserObject( $user ) {
1306 $user->load();
1307 $user->loadGroups();
1308 $user->loadOptions();
1309 foreach ( self::$mCacheVars as $var ) {
1310 $this->$var = $user->$var;
1315 * Load the groups from the database if they aren't already loaded.
1317 private function loadGroups() {
1318 if ( is_null( $this->mGroups ) ) {
1319 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
1320 ? wfGetDB( DB_MASTER )
1321 : wfGetDB( DB_SLAVE );
1322 $res = $db->select( 'user_groups',
1323 array( 'ug_group' ),
1324 array( 'ug_user' => $this->mId ),
1325 __METHOD__ );
1326 $this->mGroups = array();
1327 foreach ( $res as $row ) {
1328 $this->mGroups[] = $row->ug_group;
1334 * Add the user to the group if he/she meets given criteria.
1336 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1337 * possible to remove manually via Special:UserRights. In such case it
1338 * will not be re-added automatically. The user will also not lose the
1339 * group if they no longer meet the criteria.
1341 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1343 * @return array Array of groups the user has been promoted to.
1345 * @see $wgAutopromoteOnce
1347 public function addAutopromoteOnceGroups( $event ) {
1348 global $wgAutopromoteOnceLogInRC, $wgAuth;
1350 if ( wfReadOnly() || !$this->getId() ) {
1351 return array();
1354 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1355 if ( !count( $toPromote ) ) {
1356 return array();
1359 if ( !$this->checkAndSetTouched() ) {
1360 return array(); // raced out (bug T48834)
1363 $oldGroups = $this->getGroups(); // previous groups
1364 foreach ( $toPromote as $group ) {
1365 $this->addGroup( $group );
1367 // update groups in external authentication database
1368 Hooks::run( 'UserGroupsChanged', array( $this, $toPromote, array(), false ) );
1369 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1371 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1373 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1374 $logEntry->setPerformer( $this );
1375 $logEntry->setTarget( $this->getUserPage() );
1376 $logEntry->setParameters( array(
1377 '4::oldgroups' => $oldGroups,
1378 '5::newgroups' => $newGroups,
1379 ) );
1380 $logid = $logEntry->insert();
1381 if ( $wgAutopromoteOnceLogInRC ) {
1382 $logEntry->publish( $logid );
1385 return $toPromote;
1389 * Bump user_touched if it didn't change since this object was loaded
1391 * On success, the mTouched field is updated.
1392 * The user serialization cache is always cleared.
1394 * @return bool Whether user_touched was actually updated
1395 * @since 1.26
1397 protected function checkAndSetTouched() {
1398 $this->load();
1400 if ( !$this->mId ) {
1401 return false; // anon
1404 // Get a new user_touched that is higher than the old one
1405 $oldTouched = $this->mTouched;
1406 $newTouched = $this->newTouchedTimestamp();
1408 $dbw = wfGetDB( DB_MASTER );
1409 $dbw->update( 'user',
1410 array( 'user_touched' => $dbw->timestamp( $newTouched ) ),
1411 array(
1412 'user_id' => $this->mId,
1413 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1415 __METHOD__
1417 $success = ( $dbw->affectedRows() > 0 );
1419 if ( $success ) {
1420 $this->mTouched = $newTouched;
1421 $this->clearSharedCache();
1422 } else {
1423 // Clears on failure too since that is desired if the cache is stale
1424 $this->clearSharedCache( 'refresh' );
1427 return $success;
1431 * Clear various cached data stored in this object. The cache of the user table
1432 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1434 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1435 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1437 public function clearInstanceCache( $reloadFrom = false ) {
1438 $this->mNewtalk = -1;
1439 $this->mDatePreference = null;
1440 $this->mBlockedby = -1; # Unset
1441 $this->mHash = false;
1442 $this->mRights = null;
1443 $this->mEffectiveGroups = null;
1444 $this->mImplicitGroups = null;
1445 $this->mGroups = null;
1446 $this->mOptions = null;
1447 $this->mOptionsLoaded = false;
1448 $this->mEditCount = null;
1450 if ( $reloadFrom ) {
1451 $this->mLoadedItems = array();
1452 $this->mFrom = $reloadFrom;
1457 * Combine the language default options with any site-specific options
1458 * and add the default language variants.
1460 * @return array Array of String options
1462 public static function getDefaultOptions() {
1463 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1465 static $defOpt = null;
1466 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1467 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1468 // mid-request and see that change reflected in the return value of this function.
1469 // Which is insane and would never happen during normal MW operation
1470 return $defOpt;
1473 $defOpt = $wgDefaultUserOptions;
1474 // Default language setting
1475 $defOpt['language'] = $wgContLang->getCode();
1476 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1477 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1479 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1480 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1482 $defOpt['skin'] = Skin::normalizeKey( $wgDefaultSkin );
1484 Hooks::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1486 return $defOpt;
1490 * Get a given default option value.
1492 * @param string $opt Name of option to retrieve
1493 * @return string Default option value
1495 public static function getDefaultOption( $opt ) {
1496 $defOpts = self::getDefaultOptions();
1497 if ( isset( $defOpts[$opt] ) ) {
1498 return $defOpts[$opt];
1499 } else {
1500 return null;
1505 * Get blocking information
1506 * @param bool $bFromSlave Whether to check the slave database first.
1507 * To improve performance, non-critical checks are done against slaves.
1508 * Check when actually saving should be done against master.
1510 private function getBlockedStatus( $bFromSlave = true ) {
1511 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1513 if ( -1 != $this->mBlockedby ) {
1514 return;
1517 wfDebug( __METHOD__ . ": checking...\n" );
1519 // Initialize data...
1520 // Otherwise something ends up stomping on $this->mBlockedby when
1521 // things get lazy-loaded later, causing false positive block hits
1522 // due to -1 !== 0. Probably session-related... Nothing should be
1523 // overwriting mBlockedby, surely?
1524 $this->load();
1526 # We only need to worry about passing the IP address to the Block generator if the
1527 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1528 # know which IP address they're actually coming from
1529 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->equals( $wgUser ) ) {
1530 $ip = $this->getRequest()->getIP();
1531 } else {
1532 $ip = null;
1535 // User/IP blocking
1536 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1538 // Proxy blocking
1539 if ( !$block instanceof Block && $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1540 // Local list
1541 if ( self::isLocallyBlockedProxy( $ip ) ) {
1542 $block = new Block;
1543 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1544 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1545 $block->setTarget( $ip );
1546 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1547 $block = new Block;
1548 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1549 $block->mReason = wfMessage( 'sorbsreason' )->text();
1550 $block->setTarget( $ip );
1554 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1555 if ( !$block instanceof Block
1556 && $wgApplyIpBlocksToXff
1557 && $ip !== null
1558 && !in_array( $ip, $wgProxyWhitelist )
1560 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1561 $xff = array_map( 'trim', explode( ',', $xff ) );
1562 $xff = array_diff( $xff, array( $ip ) );
1563 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1564 $block = Block::chooseBlock( $xffblocks, $xff );
1565 if ( $block instanceof Block ) {
1566 # Mangle the reason to alert the user that the block
1567 # originated from matching the X-Forwarded-For header.
1568 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1572 if ( $block instanceof Block ) {
1573 wfDebug( __METHOD__ . ": Found block.\n" );
1574 $this->mBlock = $block;
1575 $this->mBlockedby = $block->getByName();
1576 $this->mBlockreason = $block->mReason;
1577 $this->mHideName = $block->mHideName;
1578 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1579 } else {
1580 $this->mBlockedby = '';
1581 $this->mHideName = 0;
1582 $this->mAllowUsertalk = false;
1585 // Extensions
1586 Hooks::run( 'GetBlockedStatus', array( &$this ) );
1591 * Whether the given IP is in a DNS blacklist.
1593 * @param string $ip IP to check
1594 * @param bool $checkWhitelist Whether to check the whitelist first
1595 * @return bool True if blacklisted.
1597 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1598 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1600 if ( !$wgEnableDnsBlacklist ) {
1601 return false;
1604 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1605 return false;
1608 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1612 * Whether the given IP is in a given DNS blacklist.
1614 * @param string $ip IP to check
1615 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1616 * @return bool True if blacklisted.
1618 public function inDnsBlacklist( $ip, $bases ) {
1620 $found = false;
1621 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1622 if ( IP::isIPv4( $ip ) ) {
1623 // Reverse IP, bug 21255
1624 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1626 foreach ( (array)$bases as $base ) {
1627 // Make hostname
1628 // If we have an access key, use that too (ProjectHoneypot, etc.)
1629 $basename = $base;
1630 if ( is_array( $base ) ) {
1631 if ( count( $base ) >= 2 ) {
1632 // Access key is 1, base URL is 0
1633 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1634 } else {
1635 $host = "$ipReversed.{$base[0]}";
1637 $basename = $base[0];
1638 } else {
1639 $host = "$ipReversed.$base";
1642 // Send query
1643 $ipList = gethostbynamel( $host );
1645 if ( $ipList ) {
1646 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1647 $found = true;
1648 break;
1649 } else {
1650 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1655 return $found;
1659 * Check if an IP address is in the local proxy list
1661 * @param string $ip
1663 * @return bool
1665 public static function isLocallyBlockedProxy( $ip ) {
1666 global $wgProxyList;
1668 if ( !$wgProxyList ) {
1669 return false;
1672 if ( !is_array( $wgProxyList ) ) {
1673 // Load from the specified file
1674 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1677 if ( !is_array( $wgProxyList ) ) {
1678 $ret = false;
1679 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1680 $ret = true;
1681 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1682 // Old-style flipped proxy list
1683 $ret = true;
1684 } else {
1685 $ret = false;
1687 return $ret;
1691 * Is this user subject to rate limiting?
1693 * @return bool True if rate limited
1695 public function isPingLimitable() {
1696 global $wgRateLimitsExcludedIPs;
1697 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1698 // No other good way currently to disable rate limits
1699 // for specific IPs. :P
1700 // But this is a crappy hack and should die.
1701 return false;
1703 return !$this->isAllowed( 'noratelimit' );
1707 * Primitive rate limits: enforce maximum actions per time period
1708 * to put a brake on flooding.
1710 * The method generates both a generic profiling point and a per action one
1711 * (suffix being "-$action".
1713 * @note When using a shared cache like memcached, IP-address
1714 * last-hit counters will be shared across wikis.
1716 * @param string $action Action to enforce; 'edit' if unspecified
1717 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1718 * @return bool True if a rate limiter was tripped
1720 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1721 // Call the 'PingLimiter' hook
1722 $result = false;
1723 if ( !Hooks::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1724 return $result;
1727 global $wgRateLimits;
1728 if ( !isset( $wgRateLimits[$action] ) ) {
1729 return false;
1732 // Some groups shouldn't trigger the ping limiter, ever
1733 if ( !$this->isPingLimitable() ) {
1734 return false;
1737 $limits = $wgRateLimits[$action];
1738 $keys = array();
1739 $id = $this->getId();
1740 $userLimit = false;
1742 if ( isset( $limits['anon'] ) && $id == 0 ) {
1743 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1746 if ( isset( $limits['user'] ) && $id != 0 ) {
1747 $userLimit = $limits['user'];
1749 if ( $this->isNewbie() ) {
1750 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1751 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1753 if ( isset( $limits['ip'] ) ) {
1754 $ip = $this->getRequest()->getIP();
1755 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1757 if ( isset( $limits['subnet'] ) ) {
1758 $ip = $this->getRequest()->getIP();
1759 $matches = array();
1760 $subnet = false;
1761 if ( IP::isIPv6( $ip ) ) {
1762 $parts = IP::parseRange( "$ip/64" );
1763 $subnet = $parts[0];
1764 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1765 // IPv4
1766 $subnet = $matches[1];
1768 if ( $subnet !== false ) {
1769 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1773 // Check for group-specific permissions
1774 // If more than one group applies, use the group with the highest limit
1775 foreach ( $this->getGroups() as $group ) {
1776 if ( isset( $limits[$group] ) ) {
1777 if ( $userLimit === false
1778 || $limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1780 $userLimit = $limits[$group];
1784 // Set the user limit key
1785 if ( $userLimit !== false ) {
1786 list( $max, $period ) = $userLimit;
1787 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1788 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1791 $cache = ObjectCache::getLocalClusterInstance();
1793 $triggered = false;
1794 foreach ( $keys as $key => $limit ) {
1795 list( $max, $period ) = $limit;
1796 $summary = "(limit $max in {$period}s)";
1797 $count = $cache->get( $key );
1798 // Already pinged?
1799 if ( $count ) {
1800 if ( $count >= $max ) {
1801 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1802 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1803 $triggered = true;
1804 } else {
1805 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1807 } else {
1808 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1809 if ( $incrBy > 0 ) {
1810 $cache->add( $key, 0, intval( $period ) ); // first ping
1813 if ( $incrBy > 0 ) {
1814 $cache->incr( $key, $incrBy );
1818 return $triggered;
1822 * Check if user is blocked
1824 * @param bool $bFromSlave Whether to check the slave database instead of
1825 * the master. Hacked from false due to horrible probs on site.
1826 * @return bool True if blocked, false otherwise
1828 public function isBlocked( $bFromSlave = true ) {
1829 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1833 * Get the block affecting the user, or null if the user is not blocked
1835 * @param bool $bFromSlave Whether to check the slave database instead of the master
1836 * @return Block|null
1838 public function getBlock( $bFromSlave = true ) {
1839 $this->getBlockedStatus( $bFromSlave );
1840 return $this->mBlock instanceof Block ? $this->mBlock : null;
1844 * Check if user is blocked from editing a particular article
1846 * @param Title $title Title to check
1847 * @param bool $bFromSlave Whether to check the slave database instead of the master
1848 * @return bool
1850 public function isBlockedFrom( $title, $bFromSlave = false ) {
1851 global $wgBlockAllowsUTEdit;
1853 $blocked = $this->isBlocked( $bFromSlave );
1854 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1855 // If a user's name is suppressed, they cannot make edits anywhere
1856 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
1857 && $title->getNamespace() == NS_USER_TALK ) {
1858 $blocked = false;
1859 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1862 Hooks::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1864 return $blocked;
1868 * If user is blocked, return the name of the user who placed the block
1869 * @return string Name of blocker
1871 public function blockedBy() {
1872 $this->getBlockedStatus();
1873 return $this->mBlockedby;
1877 * If user is blocked, return the specified reason for the block
1878 * @return string Blocking reason
1880 public function blockedFor() {
1881 $this->getBlockedStatus();
1882 return $this->mBlockreason;
1886 * If user is blocked, return the ID for the block
1887 * @return int Block ID
1889 public function getBlockId() {
1890 $this->getBlockedStatus();
1891 return ( $this->mBlock ? $this->mBlock->getId() : false );
1895 * Check if user is blocked on all wikis.
1896 * Do not use for actual edit permission checks!
1897 * This is intended for quick UI checks.
1899 * @param string $ip IP address, uses current client if none given
1900 * @return bool True if blocked, false otherwise
1902 public function isBlockedGlobally( $ip = '' ) {
1903 if ( $this->mBlockedGlobally !== null ) {
1904 return $this->mBlockedGlobally;
1906 // User is already an IP?
1907 if ( IP::isIPAddress( $this->getName() ) ) {
1908 $ip = $this->getName();
1909 } elseif ( !$ip ) {
1910 $ip = $this->getRequest()->getIP();
1912 $blocked = false;
1913 Hooks::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1914 $this->mBlockedGlobally = (bool)$blocked;
1915 return $this->mBlockedGlobally;
1919 * Check if user account is locked
1921 * @return bool True if locked, false otherwise
1923 public function isLocked() {
1924 if ( $this->mLocked !== null ) {
1925 return $this->mLocked;
1927 global $wgAuth;
1928 $authUser = $wgAuth->getUserInstance( $this );
1929 $this->mLocked = (bool)$authUser->isLocked();
1930 Hooks::run( 'UserIsLocked', array( $this, &$this->mLocked ) );
1931 return $this->mLocked;
1935 * Check if user account is hidden
1937 * @return bool True if hidden, false otherwise
1939 public function isHidden() {
1940 if ( $this->mHideName !== null ) {
1941 return $this->mHideName;
1943 $this->getBlockedStatus();
1944 if ( !$this->mHideName ) {
1945 global $wgAuth;
1946 $authUser = $wgAuth->getUserInstance( $this );
1947 $this->mHideName = (bool)$authUser->isHidden();
1948 Hooks::run( 'UserIsHidden', array( $this, &$this->mHideName ) );
1950 return $this->mHideName;
1954 * Get the user's ID.
1955 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1957 public function getId() {
1958 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
1959 // Special case, we know the user is anonymous
1960 return 0;
1961 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1962 // Don't load if this was initialized from an ID
1963 $this->load();
1965 return $this->mId;
1969 * Set the user and reload all fields according to a given ID
1970 * @param int $v User ID to reload
1972 public function setId( $v ) {
1973 $this->mId = $v;
1974 $this->clearInstanceCache( 'id' );
1978 * Get the user name, or the IP of an anonymous user
1979 * @return string User's name or IP address
1981 public function getName() {
1982 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1983 // Special case optimisation
1984 return $this->mName;
1985 } else {
1986 $this->load();
1987 if ( $this->mName === false ) {
1988 // Clean up IPs
1989 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
1991 return $this->mName;
1996 * Set the user name.
1998 * This does not reload fields from the database according to the given
1999 * name. Rather, it is used to create a temporary "nonexistent user" for
2000 * later addition to the database. It can also be used to set the IP
2001 * address for an anonymous user to something other than the current
2002 * remote IP.
2004 * @note User::newFromName() has roughly the same function, when the named user
2005 * does not exist.
2006 * @param string $str New user name to set
2008 public function setName( $str ) {
2009 $this->load();
2010 $this->mName = $str;
2014 * Get the user's name escaped by underscores.
2015 * @return string Username escaped by underscores.
2017 public function getTitleKey() {
2018 return str_replace( ' ', '_', $this->getName() );
2022 * Check if the user has new messages.
2023 * @return bool True if the user has new messages
2025 public function getNewtalk() {
2026 $this->load();
2028 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2029 if ( $this->mNewtalk === -1 ) {
2030 $this->mNewtalk = false; # reset talk page status
2032 // Check memcached separately for anons, who have no
2033 // entire User object stored in there.
2034 if ( !$this->mId ) {
2035 global $wgDisableAnonTalk;
2036 if ( $wgDisableAnonTalk ) {
2037 // Anon newtalk disabled by configuration.
2038 $this->mNewtalk = false;
2039 } else {
2040 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName() );
2042 } else {
2043 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
2047 return (bool)$this->mNewtalk;
2051 * Return the data needed to construct links for new talk page message
2052 * alerts. If there are new messages, this will return an associative array
2053 * with the following data:
2054 * wiki: The database name of the wiki
2055 * link: Root-relative link to the user's talk page
2056 * rev: The last talk page revision that the user has seen or null. This
2057 * is useful for building diff links.
2058 * If there are no new messages, it returns an empty array.
2059 * @note This function was designed to accomodate multiple talk pages, but
2060 * currently only returns a single link and revision.
2061 * @return array
2063 public function getNewMessageLinks() {
2064 $talks = array();
2065 if ( !Hooks::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2066 return $talks;
2067 } elseif ( !$this->getNewtalk() ) {
2068 return array();
2070 $utp = $this->getTalkPage();
2071 $dbr = wfGetDB( DB_SLAVE );
2072 // Get the "last viewed rev" timestamp from the oldest message notification
2073 $timestamp = $dbr->selectField( 'user_newtalk',
2074 'MIN(user_last_timestamp)',
2075 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2076 __METHOD__ );
2077 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2078 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2082 * Get the revision ID for the last talk page revision viewed by the talk
2083 * page owner.
2084 * @return int|null Revision ID or null
2086 public function getNewMessageRevisionId() {
2087 $newMessageRevisionId = null;
2088 $newMessageLinks = $this->getNewMessageLinks();
2089 if ( $newMessageLinks ) {
2090 // Note: getNewMessageLinks() never returns more than a single link
2091 // and it is always for the same wiki, but we double-check here in
2092 // case that changes some time in the future.
2093 if ( count( $newMessageLinks ) === 1
2094 && $newMessageLinks[0]['wiki'] === wfWikiID()
2095 && $newMessageLinks[0]['rev']
2097 /** @var Revision $newMessageRevision */
2098 $newMessageRevision = $newMessageLinks[0]['rev'];
2099 $newMessageRevisionId = $newMessageRevision->getId();
2102 return $newMessageRevisionId;
2106 * Internal uncached check for new messages
2108 * @see getNewtalk()
2109 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2110 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2111 * @return bool True if the user has new messages
2113 protected function checkNewtalk( $field, $id ) {
2114 $dbr = wfGetDB( DB_SLAVE );
2116 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__ );
2118 return $ok !== false;
2122 * Add or update the new messages flag
2123 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2124 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2125 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2126 * @return bool True if successful, false otherwise
2128 protected function updateNewtalk( $field, $id, $curRev = null ) {
2129 // Get timestamp of the talk page revision prior to the current one
2130 $prevRev = $curRev ? $curRev->getPrevious() : false;
2131 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2132 // Mark the user as having new messages since this revision
2133 $dbw = wfGetDB( DB_MASTER );
2134 $dbw->insert( 'user_newtalk',
2135 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2136 __METHOD__,
2137 'IGNORE' );
2138 if ( $dbw->affectedRows() ) {
2139 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2140 return true;
2141 } else {
2142 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2143 return false;
2148 * Clear the new messages flag for the given user
2149 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2150 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2151 * @return bool True if successful, false otherwise
2153 protected function deleteNewtalk( $field, $id ) {
2154 $dbw = wfGetDB( DB_MASTER );
2155 $dbw->delete( 'user_newtalk',
2156 array( $field => $id ),
2157 __METHOD__ );
2158 if ( $dbw->affectedRows() ) {
2159 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2160 return true;
2161 } else {
2162 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2163 return false;
2168 * Update the 'You have new messages!' status.
2169 * @param bool $val Whether the user has new messages
2170 * @param Revision $curRev New, as yet unseen revision of the user talk
2171 * page. Ignored if null or !$val.
2173 public function setNewtalk( $val, $curRev = null ) {
2174 if ( wfReadOnly() ) {
2175 return;
2178 $this->load();
2179 $this->mNewtalk = $val;
2181 if ( $this->isAnon() ) {
2182 $field = 'user_ip';
2183 $id = $this->getName();
2184 } else {
2185 $field = 'user_id';
2186 $id = $this->getId();
2189 if ( $val ) {
2190 $changed = $this->updateNewtalk( $field, $id, $curRev );
2191 } else {
2192 $changed = $this->deleteNewtalk( $field, $id );
2195 if ( $changed ) {
2196 $this->invalidateCache();
2201 * Generate a current or new-future timestamp to be stored in the
2202 * user_touched field when we update things.
2203 * @return string Timestamp in TS_MW format
2205 private function newTouchedTimestamp() {
2206 global $wgClockSkewFudge;
2208 $time = wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2209 if ( $this->mTouched && $time <= $this->mTouched ) {
2210 $time = wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $this->mTouched ) + 1 );
2213 return $time;
2217 * Clear user data from memcached
2219 * Use after applying updates to the database; caller's
2220 * responsibility to update user_touched if appropriate.
2222 * Called implicitly from invalidateCache() and saveSettings().
2224 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2226 public function clearSharedCache( $mode = 'changed' ) {
2227 if ( !$this->getId() ) {
2228 return;
2231 $cache = ObjectCache::getMainWANInstance();
2232 $key = $this->getCacheKey( $cache );
2233 if ( $mode === 'refresh' ) {
2234 $cache->delete( $key, 1 );
2235 } else {
2236 wfGetDB( DB_MASTER )->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
2237 $cache->delete( $key );
2238 } );
2243 * Immediately touch the user data cache for this account
2245 * Calls touch() and removes account data from memcached
2247 public function invalidateCache() {
2248 $this->touch();
2249 $this->clearSharedCache();
2253 * Update the "touched" timestamp for the user
2255 * This is useful on various login/logout events when making sure that
2256 * a browser or proxy that has multiple tenants does not suffer cache
2257 * pollution where the new user sees the old users content. The value
2258 * of getTouched() is checked when determining 304 vs 200 responses.
2259 * Unlike invalidateCache(), this preserves the User object cache and
2260 * avoids database writes.
2262 * @since 1.25
2264 public function touch() {
2265 $id = $this->getId();
2266 if ( $id ) {
2267 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2268 ObjectCache::getMainWANInstance()->touchCheckKey( $key );
2269 $this->mQuickTouched = null;
2274 * Validate the cache for this account.
2275 * @param string $timestamp A timestamp in TS_MW format
2276 * @return bool
2278 public function validateCache( $timestamp ) {
2279 return ( $timestamp >= $this->getTouched() );
2283 * Get the user touched timestamp
2285 * Use this value only to validate caches via inequalities
2286 * such as in the case of HTTP If-Modified-Since response logic
2288 * @return string TS_MW Timestamp
2290 public function getTouched() {
2291 $this->load();
2293 if ( $this->mId ) {
2294 if ( $this->mQuickTouched === null ) {
2295 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId );
2296 $cache = ObjectCache::getMainWANInstance();
2298 $this->mQuickTouched = wfTimestamp( TS_MW, $cache->getCheckKeyTime( $key ) );
2301 return max( $this->mTouched, $this->mQuickTouched );
2304 return $this->mTouched;
2308 * Get the user_touched timestamp field (time of last DB updates)
2309 * @return string TS_MW Timestamp
2310 * @since 1.26
2312 public function getDBTouched() {
2313 $this->load();
2315 return $this->mTouched;
2319 * @deprecated Removed in 1.27.
2320 * @return Password
2321 * @since 1.24
2323 public function getPassword() {
2324 throw new BadMethodCallException( __METHOD__ . ' has been removed in 1.27' );
2328 * @deprecated Removed in 1.27.
2329 * @return Password
2330 * @since 1.24
2332 public function getTemporaryPassword() {
2333 throw new BadMethodCallException( __METHOD__ . ' has been removed in 1.27' );
2337 * Set the password and reset the random token.
2338 * Calls through to authentication plugin if necessary;
2339 * will have no effect if the auth plugin refuses to
2340 * pass the change through or if the legal password
2341 * checks fail.
2343 * As a special case, setting the password to null
2344 * wipes it, so the account cannot be logged in until
2345 * a new password is set, for instance via e-mail.
2347 * @deprecated since 1.27. AuthManager is coming.
2348 * @param string $str New password to set
2349 * @throws PasswordError On failure
2350 * @return bool
2352 public function setPassword( $str ) {
2353 global $wgAuth;
2355 if ( $str !== null ) {
2356 if ( !$wgAuth->allowPasswordChange() ) {
2357 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2360 $status = $this->checkPasswordValidity( $str );
2361 if ( !$status->isGood() ) {
2362 throw new PasswordError( $status->getMessage()->text() );
2366 if ( !$wgAuth->setPassword( $this, $str ) ) {
2367 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2370 $this->setToken();
2371 $this->setOption( 'watchlisttoken', false );
2372 $this->setPasswordInternal( $str );
2374 return true;
2378 * Set the password and reset the random token unconditionally.
2380 * @deprecated since 1.27. AuthManager is coming.
2381 * @param string|null $str New password to set or null to set an invalid
2382 * password hash meaning that the user will not be able to log in
2383 * through the web interface.
2385 public function setInternalPassword( $str ) {
2386 global $wgAuth;
2388 if ( $wgAuth->allowSetLocalPassword() ) {
2389 $this->setToken();
2390 $this->setOption( 'watchlisttoken', false );
2391 $this->setPasswordInternal( $str );
2396 * Actually set the password and such
2397 * @since 1.27 cannot set a password for a user not in the database
2398 * @param string|null $str New password to set or null to set an invalid
2399 * password hash meaning that the user will not be able to log in
2400 * through the web interface.
2402 private function setPasswordInternal( $str ) {
2403 $id = self::idFromName( $this->getName(), self::READ_LATEST );
2404 if ( $id == 0 ) {
2405 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2408 $passwordFactory = new PasswordFactory();
2409 $passwordFactory->init( RequestContext::getMain()->getConfig() );
2410 $dbw = wfGetDB( DB_MASTER );
2411 $dbw->update(
2412 'user',
2413 array(
2414 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2415 'user_newpassword' => PasswordFactory::newInvalidPassword()->toString(),
2416 'user_newpass_time' => $dbw->timestampOrNull( null ),
2418 array(
2419 'user_id' => $id,
2421 __METHOD__
2424 // When the main password is changed, invalidate all bot passwords too
2425 BotPassword::invalidateAllPasswordsForUser( $this->getName() );
2429 * Get the user's current token.
2430 * @param bool $forceCreation Force the generation of a new token if the
2431 * user doesn't have one (default=true for backwards compatibility).
2432 * @return string Token
2434 public function getToken( $forceCreation = true ) {
2435 $this->load();
2436 if ( !$this->mToken && $forceCreation ) {
2437 $this->setToken();
2439 return $this->mToken;
2443 * Set the random token (used for persistent authentication)
2444 * Called from loadDefaults() among other places.
2446 * @param string|bool $token If specified, set the token to this value
2448 public function setToken( $token = false ) {
2449 $this->load();
2450 if ( !$token ) {
2451 $this->mToken = MWCryptRand::generateHex( self::TOKEN_LENGTH );
2452 } else {
2453 $this->mToken = $token;
2458 * Set the password for a password reminder or new account email
2460 * @deprecated since 1.27, AuthManager is coming
2461 * @param string $str New password to set or null to set an invalid
2462 * password hash meaning that the user will not be able to use it
2463 * @param bool $throttle If true, reset the throttle timestamp to the present
2465 public function setNewpassword( $str, $throttle = true ) {
2466 $id = $this->getId();
2467 if ( $id == 0 ) {
2468 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2471 $dbw = wfGetDB( DB_MASTER );
2473 $passwordFactory = new PasswordFactory();
2474 $passwordFactory->init( RequestContext::getMain()->getConfig() );
2475 $update = array(
2476 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2479 if ( $str === null ) {
2480 $update['user_newpass_time'] = null;
2481 } elseif ( $throttle ) {
2482 $update['user_newpass_time'] = $dbw->timestamp();
2485 $dbw->update( 'user', $update, array( 'user_id' => $id ), __METHOD__ );
2489 * Has password reminder email been sent within the last
2490 * $wgPasswordReminderResendTime hours?
2491 * @return bool
2493 public function isPasswordReminderThrottled() {
2494 global $wgPasswordReminderResendTime;
2496 if ( !$wgPasswordReminderResendTime ) {
2497 return false;
2500 $this->load();
2502 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
2503 ? wfGetDB( DB_MASTER )
2504 : wfGetDB( DB_SLAVE );
2505 $newpassTime = $db->selectField(
2506 'user',
2507 'user_newpass_time',
2508 array( 'user_id' => $this->getId() ),
2509 __METHOD__
2512 if ( $newpassTime === null ) {
2513 return false;
2515 $expiry = wfTimestamp( TS_UNIX, $newpassTime ) + $wgPasswordReminderResendTime * 3600;
2516 return time() < $expiry;
2520 * Get the user's e-mail address
2521 * @return string User's email address
2523 public function getEmail() {
2524 $this->load();
2525 Hooks::run( 'UserGetEmail', array( $this, &$this->mEmail ) );
2526 return $this->mEmail;
2530 * Get the timestamp of the user's e-mail authentication
2531 * @return string TS_MW timestamp
2533 public function getEmailAuthenticationTimestamp() {
2534 $this->load();
2535 Hooks::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2536 return $this->mEmailAuthenticated;
2540 * Set the user's e-mail address
2541 * @param string $str New e-mail address
2543 public function setEmail( $str ) {
2544 $this->load();
2545 if ( $str == $this->mEmail ) {
2546 return;
2548 $this->invalidateEmail();
2549 $this->mEmail = $str;
2550 Hooks::run( 'UserSetEmail', array( $this, &$this->mEmail ) );
2554 * Set the user's e-mail address and a confirmation mail if needed.
2556 * @since 1.20
2557 * @param string $str New e-mail address
2558 * @return Status
2560 public function setEmailWithConfirmation( $str ) {
2561 global $wgEnableEmail, $wgEmailAuthentication;
2563 if ( !$wgEnableEmail ) {
2564 return Status::newFatal( 'emaildisabled' );
2567 $oldaddr = $this->getEmail();
2568 if ( $str === $oldaddr ) {
2569 return Status::newGood( true );
2572 $this->setEmail( $str );
2574 if ( $str !== '' && $wgEmailAuthentication ) {
2575 // Send a confirmation request to the new address if needed
2576 $type = $oldaddr != '' ? 'changed' : 'set';
2577 $result = $this->sendConfirmationMail( $type );
2578 if ( $result->isGood() ) {
2579 // Say to the caller that a confirmation mail has been sent
2580 $result->value = 'eauth';
2582 } else {
2583 $result = Status::newGood( true );
2586 return $result;
2590 * Get the user's real name
2591 * @return string User's real name
2593 public function getRealName() {
2594 if ( !$this->isItemLoaded( 'realname' ) ) {
2595 $this->load();
2598 return $this->mRealName;
2602 * Set the user's real name
2603 * @param string $str New real name
2605 public function setRealName( $str ) {
2606 $this->load();
2607 $this->mRealName = $str;
2611 * Get the user's current setting for a given option.
2613 * @param string $oname The option to check
2614 * @param string $defaultOverride A default value returned if the option does not exist
2615 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2616 * @return string User's current value for the option
2617 * @see getBoolOption()
2618 * @see getIntOption()
2620 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2621 global $wgHiddenPrefs;
2622 $this->loadOptions();
2624 # We want 'disabled' preferences to always behave as the default value for
2625 # users, even if they have set the option explicitly in their settings (ie they
2626 # set it, and then it was disabled removing their ability to change it). But
2627 # we don't want to erase the preferences in the database in case the preference
2628 # is re-enabled again. So don't touch $mOptions, just override the returned value
2629 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2630 return self::getDefaultOption( $oname );
2633 if ( array_key_exists( $oname, $this->mOptions ) ) {
2634 return $this->mOptions[$oname];
2635 } else {
2636 return $defaultOverride;
2641 * Get all user's options
2643 * @param int $flags Bitwise combination of:
2644 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2645 * to the default value. (Since 1.25)
2646 * @return array
2648 public function getOptions( $flags = 0 ) {
2649 global $wgHiddenPrefs;
2650 $this->loadOptions();
2651 $options = $this->mOptions;
2653 # We want 'disabled' preferences to always behave as the default value for
2654 # users, even if they have set the option explicitly in their settings (ie they
2655 # set it, and then it was disabled removing their ability to change it). But
2656 # we don't want to erase the preferences in the database in case the preference
2657 # is re-enabled again. So don't touch $mOptions, just override the returned value
2658 foreach ( $wgHiddenPrefs as $pref ) {
2659 $default = self::getDefaultOption( $pref );
2660 if ( $default !== null ) {
2661 $options[$pref] = $default;
2665 if ( $flags & self::GETOPTIONS_EXCLUDE_DEFAULTS ) {
2666 $options = array_diff_assoc( $options, self::getDefaultOptions() );
2669 return $options;
2673 * Get the user's current setting for a given option, as a boolean value.
2675 * @param string $oname The option to check
2676 * @return bool User's current value for the option
2677 * @see getOption()
2679 public function getBoolOption( $oname ) {
2680 return (bool)$this->getOption( $oname );
2684 * Get the user's current setting for a given option, as an integer value.
2686 * @param string $oname The option to check
2687 * @param int $defaultOverride A default value returned if the option does not exist
2688 * @return int User's current value for the option
2689 * @see getOption()
2691 public function getIntOption( $oname, $defaultOverride = 0 ) {
2692 $val = $this->getOption( $oname );
2693 if ( $val == '' ) {
2694 $val = $defaultOverride;
2696 return intval( $val );
2700 * Set the given option for a user.
2702 * You need to call saveSettings() to actually write to the database.
2704 * @param string $oname The option to set
2705 * @param mixed $val New value to set
2707 public function setOption( $oname, $val ) {
2708 $this->loadOptions();
2710 // Explicitly NULL values should refer to defaults
2711 if ( is_null( $val ) ) {
2712 $val = self::getDefaultOption( $oname );
2715 $this->mOptions[$oname] = $val;
2719 * Get a token stored in the preferences (like the watchlist one),
2720 * resetting it if it's empty (and saving changes).
2722 * @param string $oname The option name to retrieve the token from
2723 * @return string|bool User's current value for the option, or false if this option is disabled.
2724 * @see resetTokenFromOption()
2725 * @see getOption()
2726 * @deprecated 1.26 Applications should use the OAuth extension
2728 public function getTokenFromOption( $oname ) {
2729 global $wgHiddenPrefs;
2731 $id = $this->getId();
2732 if ( !$id || in_array( $oname, $wgHiddenPrefs ) ) {
2733 return false;
2736 $token = $this->getOption( $oname );
2737 if ( !$token ) {
2738 // Default to a value based on the user token to avoid space
2739 // wasted on storing tokens for all users. When this option
2740 // is set manually by the user, only then is it stored.
2741 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2744 return $token;
2748 * Reset a token stored in the preferences (like the watchlist one).
2749 * *Does not* save user's preferences (similarly to setOption()).
2751 * @param string $oname The option name to reset the token in
2752 * @return string|bool New token value, or false if this option is disabled.
2753 * @see getTokenFromOption()
2754 * @see setOption()
2756 public function resetTokenFromOption( $oname ) {
2757 global $wgHiddenPrefs;
2758 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2759 return false;
2762 $token = MWCryptRand::generateHex( 40 );
2763 $this->setOption( $oname, $token );
2764 return $token;
2768 * Return a list of the types of user options currently returned by
2769 * User::getOptionKinds().
2771 * Currently, the option kinds are:
2772 * - 'registered' - preferences which are registered in core MediaWiki or
2773 * by extensions using the UserGetDefaultOptions hook.
2774 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2775 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2776 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2777 * be used by user scripts.
2778 * - 'special' - "preferences" that are not accessible via User::getOptions
2779 * or User::setOptions.
2780 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2781 * These are usually legacy options, removed in newer versions.
2783 * The API (and possibly others) use this function to determine the possible
2784 * option types for validation purposes, so make sure to update this when a
2785 * new option kind is added.
2787 * @see User::getOptionKinds
2788 * @return array Option kinds
2790 public static function listOptionKinds() {
2791 return array(
2792 'registered',
2793 'registered-multiselect',
2794 'registered-checkmatrix',
2795 'userjs',
2796 'special',
2797 'unused'
2802 * Return an associative array mapping preferences keys to the kind of a preference they're
2803 * used for. Different kinds are handled differently when setting or reading preferences.
2805 * See User::listOptionKinds for the list of valid option types that can be provided.
2807 * @see User::listOptionKinds
2808 * @param IContextSource $context
2809 * @param array $options Assoc. array with options keys to check as keys.
2810 * Defaults to $this->mOptions.
2811 * @return array The key => kind mapping data
2813 public function getOptionKinds( IContextSource $context, $options = null ) {
2814 $this->loadOptions();
2815 if ( $options === null ) {
2816 $options = $this->mOptions;
2819 $prefs = Preferences::getPreferences( $this, $context );
2820 $mapping = array();
2822 // Pull out the "special" options, so they don't get converted as
2823 // multiselect or checkmatrix.
2824 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
2825 foreach ( $specialOptions as $name => $value ) {
2826 unset( $prefs[$name] );
2829 // Multiselect and checkmatrix options are stored in the database with
2830 // one key per option, each having a boolean value. Extract those keys.
2831 $multiselectOptions = array();
2832 foreach ( $prefs as $name => $info ) {
2833 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2834 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2835 $opts = HTMLFormField::flattenOptions( $info['options'] );
2836 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2838 foreach ( $opts as $value ) {
2839 $multiselectOptions["$prefix$value"] = true;
2842 unset( $prefs[$name] );
2845 $checkmatrixOptions = array();
2846 foreach ( $prefs as $name => $info ) {
2847 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2848 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2849 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2850 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2851 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2853 foreach ( $columns as $column ) {
2854 foreach ( $rows as $row ) {
2855 $checkmatrixOptions["$prefix$column-$row"] = true;
2859 unset( $prefs[$name] );
2863 // $value is ignored
2864 foreach ( $options as $key => $value ) {
2865 if ( isset( $prefs[$key] ) ) {
2866 $mapping[$key] = 'registered';
2867 } elseif ( isset( $multiselectOptions[$key] ) ) {
2868 $mapping[$key] = 'registered-multiselect';
2869 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2870 $mapping[$key] = 'registered-checkmatrix';
2871 } elseif ( isset( $specialOptions[$key] ) ) {
2872 $mapping[$key] = 'special';
2873 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2874 $mapping[$key] = 'userjs';
2875 } else {
2876 $mapping[$key] = 'unused';
2880 return $mapping;
2884 * Reset certain (or all) options to the site defaults
2886 * The optional parameter determines which kinds of preferences will be reset.
2887 * Supported values are everything that can be reported by getOptionKinds()
2888 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2890 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2891 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2892 * for backwards-compatibility.
2893 * @param IContextSource|null $context Context source used when $resetKinds
2894 * does not contain 'all', passed to getOptionKinds().
2895 * Defaults to RequestContext::getMain() when null.
2897 public function resetOptions(
2898 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2899 IContextSource $context = null
2901 $this->load();
2902 $defaultOptions = self::getDefaultOptions();
2904 if ( !is_array( $resetKinds ) ) {
2905 $resetKinds = array( $resetKinds );
2908 if ( in_array( 'all', $resetKinds ) ) {
2909 $newOptions = $defaultOptions;
2910 } else {
2911 if ( $context === null ) {
2912 $context = RequestContext::getMain();
2915 $optionKinds = $this->getOptionKinds( $context );
2916 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2917 $newOptions = array();
2919 // Use default values for the options that should be deleted, and
2920 // copy old values for the ones that shouldn't.
2921 foreach ( $this->mOptions as $key => $value ) {
2922 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2923 if ( array_key_exists( $key, $defaultOptions ) ) {
2924 $newOptions[$key] = $defaultOptions[$key];
2926 } else {
2927 $newOptions[$key] = $value;
2932 Hooks::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions, $resetKinds ) );
2934 $this->mOptions = $newOptions;
2935 $this->mOptionsLoaded = true;
2939 * Get the user's preferred date format.
2940 * @return string User's preferred date format
2942 public function getDatePreference() {
2943 // Important migration for old data rows
2944 if ( is_null( $this->mDatePreference ) ) {
2945 global $wgLang;
2946 $value = $this->getOption( 'date' );
2947 $map = $wgLang->getDatePreferenceMigrationMap();
2948 if ( isset( $map[$value] ) ) {
2949 $value = $map[$value];
2951 $this->mDatePreference = $value;
2953 return $this->mDatePreference;
2957 * Determine based on the wiki configuration and the user's options,
2958 * whether this user must be over HTTPS no matter what.
2960 * @return bool
2962 public function requiresHTTPS() {
2963 global $wgSecureLogin;
2964 if ( !$wgSecureLogin ) {
2965 return false;
2966 } else {
2967 $https = $this->getBoolOption( 'prefershttps' );
2968 Hooks::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2969 if ( $https ) {
2970 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2972 return $https;
2977 * Get the user preferred stub threshold
2979 * @return int
2981 public function getStubThreshold() {
2982 global $wgMaxArticleSize; # Maximum article size, in Kb
2983 $threshold = $this->getIntOption( 'stubthreshold' );
2984 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2985 // If they have set an impossible value, disable the preference
2986 // so we can use the parser cache again.
2987 $threshold = 0;
2989 return $threshold;
2993 * Get the permissions this user has.
2994 * @return array Array of String permission names
2996 public function getRights() {
2997 if ( is_null( $this->mRights ) ) {
2998 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
3000 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3001 if ( $allowedRights !== null ) {
3002 $this->mRights = array_intersect( $this->mRights, $allowedRights );
3005 Hooks::run( 'UserGetRights', array( $this, &$this->mRights ) );
3006 // Force reindexation of rights when a hook has unset one of them
3007 $this->mRights = array_values( array_unique( $this->mRights ) );
3009 return $this->mRights;
3013 * Get the list of explicit group memberships this user has.
3014 * The implicit * and user groups are not included.
3015 * @return array Array of String internal group names
3017 public function getGroups() {
3018 $this->load();
3019 $this->loadGroups();
3020 return $this->mGroups;
3024 * Get the list of implicit group memberships this user has.
3025 * This includes all explicit groups, plus 'user' if logged in,
3026 * '*' for all accounts, and autopromoted groups
3027 * @param bool $recache Whether to avoid the cache
3028 * @return array Array of String internal group names
3030 public function getEffectiveGroups( $recache = false ) {
3031 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
3032 $this->mEffectiveGroups = array_unique( array_merge(
3033 $this->getGroups(), // explicit groups
3034 $this->getAutomaticGroups( $recache ) // implicit groups
3035 ) );
3036 // Hook for additional groups
3037 Hooks::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
3038 // Force reindexation of groups when a hook has unset one of them
3039 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
3041 return $this->mEffectiveGroups;
3045 * Get the list of implicit group memberships this user has.
3046 * This includes 'user' if logged in, '*' for all accounts,
3047 * and autopromoted groups
3048 * @param bool $recache Whether to avoid the cache
3049 * @return array Array of String internal group names
3051 public function getAutomaticGroups( $recache = false ) {
3052 if ( $recache || is_null( $this->mImplicitGroups ) ) {
3053 $this->mImplicitGroups = array( '*' );
3054 if ( $this->getId() ) {
3055 $this->mImplicitGroups[] = 'user';
3057 $this->mImplicitGroups = array_unique( array_merge(
3058 $this->mImplicitGroups,
3059 Autopromote::getAutopromoteGroups( $this )
3060 ) );
3062 if ( $recache ) {
3063 // Assure data consistency with rights/groups,
3064 // as getEffectiveGroups() depends on this function
3065 $this->mEffectiveGroups = null;
3068 return $this->mImplicitGroups;
3072 * Returns the groups the user has belonged to.
3074 * The user may still belong to the returned groups. Compare with getGroups().
3076 * The function will not return groups the user had belonged to before MW 1.17
3078 * @return array Names of the groups the user has belonged to.
3080 public function getFormerGroups() {
3081 $this->load();
3083 if ( is_null( $this->mFormerGroups ) ) {
3084 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
3085 ? wfGetDB( DB_MASTER )
3086 : wfGetDB( DB_SLAVE );
3087 $res = $db->select( 'user_former_groups',
3088 array( 'ufg_group' ),
3089 array( 'ufg_user' => $this->mId ),
3090 __METHOD__ );
3091 $this->mFormerGroups = array();
3092 foreach ( $res as $row ) {
3093 $this->mFormerGroups[] = $row->ufg_group;
3097 return $this->mFormerGroups;
3101 * Get the user's edit count.
3102 * @return int|null Null for anonymous users
3104 public function getEditCount() {
3105 if ( !$this->getId() ) {
3106 return null;
3109 if ( $this->mEditCount === null ) {
3110 /* Populate the count, if it has not been populated yet */
3111 $dbr = wfGetDB( DB_SLAVE );
3112 // check if the user_editcount field has been initialized
3113 $count = $dbr->selectField(
3114 'user', 'user_editcount',
3115 array( 'user_id' => $this->mId ),
3116 __METHOD__
3119 if ( $count === null ) {
3120 // it has not been initialized. do so.
3121 $count = $this->initEditCount();
3123 $this->mEditCount = $count;
3125 return (int)$this->mEditCount;
3129 * Add the user to the given group.
3130 * This takes immediate effect.
3131 * @param string $group Name of the group to add
3132 * @return bool
3134 public function addGroup( $group ) {
3135 $this->load();
3137 if ( !Hooks::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3138 return false;
3141 $dbw = wfGetDB( DB_MASTER );
3142 if ( $this->getId() ) {
3143 $dbw->insert( 'user_groups',
3144 array(
3145 'ug_user' => $this->getID(),
3146 'ug_group' => $group,
3148 __METHOD__,
3149 array( 'IGNORE' ) );
3152 $this->loadGroups();
3153 $this->mGroups[] = $group;
3154 // In case loadGroups was not called before, we now have the right twice.
3155 // Get rid of the duplicate.
3156 $this->mGroups = array_unique( $this->mGroups );
3158 // Refresh the groups caches, and clear the rights cache so it will be
3159 // refreshed on the next call to $this->getRights().
3160 $this->getEffectiveGroups( true );
3161 $this->mRights = null;
3163 $this->invalidateCache();
3165 return true;
3169 * Remove the user from the given group.
3170 * This takes immediate effect.
3171 * @param string $group Name of the group to remove
3172 * @return bool
3174 public function removeGroup( $group ) {
3175 $this->load();
3176 if ( !Hooks::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3177 return false;
3180 $dbw = wfGetDB( DB_MASTER );
3181 $dbw->delete( 'user_groups',
3182 array(
3183 'ug_user' => $this->getID(),
3184 'ug_group' => $group,
3185 ), __METHOD__
3187 // Remember that the user was in this group
3188 $dbw->insert( 'user_former_groups',
3189 array(
3190 'ufg_user' => $this->getID(),
3191 'ufg_group' => $group,
3193 __METHOD__,
3194 array( 'IGNORE' )
3197 $this->loadGroups();
3198 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
3200 // Refresh the groups caches, and clear the rights cache so it will be
3201 // refreshed on the next call to $this->getRights().
3202 $this->getEffectiveGroups( true );
3203 $this->mRights = null;
3205 $this->invalidateCache();
3207 return true;
3211 * Get whether the user is logged in
3212 * @return bool
3214 public function isLoggedIn() {
3215 return $this->getID() != 0;
3219 * Get whether the user is anonymous
3220 * @return bool
3222 public function isAnon() {
3223 return !$this->isLoggedIn();
3227 * Check if user is allowed to access a feature / make an action
3229 * @param string ... Permissions to test
3230 * @return bool True if user is allowed to perform *any* of the given actions
3232 public function isAllowedAny() {
3233 $permissions = func_get_args();
3234 foreach ( $permissions as $permission ) {
3235 if ( $this->isAllowed( $permission ) ) {
3236 return true;
3239 return false;
3244 * @param string ... Permissions to test
3245 * @return bool True if the user is allowed to perform *all* of the given actions
3247 public function isAllowedAll() {
3248 $permissions = func_get_args();
3249 foreach ( $permissions as $permission ) {
3250 if ( !$this->isAllowed( $permission ) ) {
3251 return false;
3254 return true;
3258 * Internal mechanics of testing a permission
3259 * @param string $action
3260 * @return bool
3262 public function isAllowed( $action = '' ) {
3263 if ( $action === '' ) {
3264 return true; // In the spirit of DWIM
3266 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3267 // by misconfiguration: 0 == 'foo'
3268 return in_array( $action, $this->getRights(), true );
3272 * Check whether to enable recent changes patrol features for this user
3273 * @return bool True or false
3275 public function useRCPatrol() {
3276 global $wgUseRCPatrol;
3277 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3281 * Check whether to enable new pages patrol features for this user
3282 * @return bool True or false
3284 public function useNPPatrol() {
3285 global $wgUseRCPatrol, $wgUseNPPatrol;
3286 return (
3287 ( $wgUseRCPatrol || $wgUseNPPatrol )
3288 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3293 * Check whether to enable new files patrol features for this user
3294 * @return bool True or false
3296 public function useFilePatrol() {
3297 global $wgUseRCPatrol, $wgUseFilePatrol;
3298 return (
3299 ( $wgUseRCPatrol || $wgUseFilePatrol )
3300 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3305 * Get the WebRequest object to use with this object
3307 * @return WebRequest
3309 public function getRequest() {
3310 if ( $this->mRequest ) {
3311 return $this->mRequest;
3312 } else {
3313 global $wgRequest;
3314 return $wgRequest;
3319 * Get a WatchedItem for this user and $title.
3321 * @since 1.22 $checkRights parameter added
3322 * @param Title $title
3323 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3324 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3325 * @return WatchedItem
3327 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3328 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3330 if ( isset( $this->mWatchedItems[$key] ) ) {
3331 return $this->mWatchedItems[$key];
3334 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
3335 $this->mWatchedItems = array();
3338 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
3339 return $this->mWatchedItems[$key];
3343 * Check the watched status of an article.
3344 * @since 1.22 $checkRights parameter added
3345 * @param Title $title Title of the article to look at
3346 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3347 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3348 * @return bool
3350 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3351 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3355 * Watch an article.
3356 * @since 1.22 $checkRights parameter added
3357 * @param Title $title Title of the article to look at
3358 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3359 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3361 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3362 $this->getWatchedItem( $title, $checkRights )->addWatch();
3363 $this->invalidateCache();
3367 * Stop watching an article.
3368 * @since 1.22 $checkRights parameter added
3369 * @param Title $title Title of the article to look at
3370 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3371 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3373 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3374 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3375 $this->invalidateCache();
3379 * Clear the user's notification timestamp for the given title.
3380 * If e-notif e-mails are on, they will receive notification mails on
3381 * the next change of the page if it's watched etc.
3382 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3383 * @param Title $title Title of the article to look at
3384 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3386 public function clearNotification( &$title, $oldid = 0 ) {
3387 global $wgUseEnotif, $wgShowUpdatedMarker;
3389 // Do nothing if the database is locked to writes
3390 if ( wfReadOnly() ) {
3391 return;
3394 // Do nothing if not allowed to edit the watchlist
3395 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3396 return;
3399 // If we're working on user's talk page, we should update the talk page message indicator
3400 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3401 if ( !Hooks::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3402 return;
3405 $that = $this;
3406 // Try to update the DB post-send and only if needed...
3407 DeferredUpdates::addCallableUpdate( function() use ( $that, $title, $oldid ) {
3408 if ( !$that->getNewtalk() ) {
3409 return; // no notifications to clear
3412 // Delete the last notifications (they stack up)
3413 $that->setNewtalk( false );
3415 // If there is a new, unseen, revision, use its timestamp
3416 $nextid = $oldid
3417 ? $title->getNextRevisionID( $oldid, Title::GAID_FOR_UPDATE )
3418 : null;
3419 if ( $nextid ) {
3420 $that->setNewtalk( true, Revision::newFromId( $nextid ) );
3422 } );
3425 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3426 return;
3429 if ( $this->isAnon() ) {
3430 // Nothing else to do...
3431 return;
3434 // Only update the timestamp if the page is being watched.
3435 // The query to find out if it is watched is cached both in memcached and per-invocation,
3436 // and when it does have to be executed, it can be on a slave
3437 // If this is the user's newtalk page, we always update the timestamp
3438 $force = '';
3439 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3440 $force = 'force';
3443 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3444 $force, $oldid, WatchedItem::DEFERRED
3449 * Resets all of the given user's page-change notification timestamps.
3450 * If e-notif e-mails are on, they will receive notification mails on
3451 * the next change of any watched page.
3452 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3454 public function clearAllNotifications() {
3455 if ( wfReadOnly() ) {
3456 return;
3459 // Do nothing if not allowed to edit the watchlist
3460 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3461 return;
3464 global $wgUseEnotif, $wgShowUpdatedMarker;
3465 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3466 $this->setNewtalk( false );
3467 return;
3469 $id = $this->getId();
3470 if ( $id != 0 ) {
3471 $dbw = wfGetDB( DB_MASTER );
3472 $dbw->update( 'watchlist',
3473 array( /* SET */ 'wl_notificationtimestamp' => null ),
3474 array( /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ),
3475 __METHOD__
3477 // We also need to clear here the "you have new message" notification for the own user_talk page;
3478 // it's cleared one page view later in WikiPage::doViewUpdates().
3483 * Set a cookie on the user's client. Wrapper for
3484 * WebResponse::setCookie
3485 * @deprecated since 1.27
3486 * @param string $name Name of the cookie to set
3487 * @param string $value Value to set
3488 * @param int $exp Expiration time, as a UNIX time value;
3489 * if 0 or not specified, use the default $wgCookieExpiration
3490 * @param bool $secure
3491 * true: Force setting the secure attribute when setting the cookie
3492 * false: Force NOT setting the secure attribute when setting the cookie
3493 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3494 * @param array $params Array of options sent passed to WebResponse::setcookie()
3495 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3496 * is passed.
3498 protected function setCookie(
3499 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3501 wfDeprecated( __METHOD__, '1.27' );
3502 if ( $request === null ) {
3503 $request = $this->getRequest();
3505 $params['secure'] = $secure;
3506 $request->response()->setCookie( $name, $value, $exp, $params );
3510 * Clear a cookie on the user's client
3511 * @deprecated since 1.27
3512 * @param string $name Name of the cookie to clear
3513 * @param bool $secure
3514 * true: Force setting the secure attribute when setting the cookie
3515 * false: Force NOT setting the secure attribute when setting the cookie
3516 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3517 * @param array $params Array of options sent passed to WebResponse::setcookie()
3519 protected function clearCookie( $name, $secure = null, $params = array() ) {
3520 wfDeprecated( __METHOD__, '1.27' );
3521 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3525 * Set an extended login cookie on the user's client. The expiry of the cookie
3526 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3527 * variable.
3529 * @see User::setCookie
3531 * @deprecated since 1.27
3532 * @param string $name Name of the cookie to set
3533 * @param string $value Value to set
3534 * @param bool $secure
3535 * true: Force setting the secure attribute when setting the cookie
3536 * false: Force NOT setting the secure attribute when setting the cookie
3537 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3539 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3540 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3542 wfDeprecated( __METHOD__, '1.27' );
3544 $exp = time();
3545 $exp += $wgExtendedLoginCookieExpiration !== null
3546 ? $wgExtendedLoginCookieExpiration
3547 : $wgCookieExpiration;
3549 $this->setCookie( $name, $value, $exp, $secure );
3553 * Persist this user's session (e.g. set cookies)
3555 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3556 * is passed.
3557 * @param bool $secure Whether to force secure/insecure cookies or use default
3558 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3560 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3561 $this->load();
3562 if ( 0 == $this->mId ) {
3563 return;
3566 $session = $this->getRequest()->getSession();
3567 if ( $request && $session->getRequest() !== $request ) {
3568 $session = $session->sessionWithRequest( $request );
3570 $delay = $session->delaySave();
3572 if ( !$session->getUser()->equals( $this ) ) {
3573 if ( !$session->canSetUser() ) {
3574 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3575 ->warning( __METHOD__ .
3576 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3578 return;
3580 $session->setUser( $this );
3583 $session->setRememberUser( $rememberMe );
3584 if ( $secure !== null ) {
3585 $session->setForceHTTPS( $secure );
3588 $session->persist();
3590 ScopedCallback::consume( $delay );
3594 * Log this user out.
3596 public function logout() {
3597 if ( Hooks::run( 'UserLogout', array( &$this ) ) ) {
3598 $this->doLogout();
3603 * Clear the user's session, and reset the instance cache.
3604 * @see logout()
3606 public function doLogout() {
3607 $session = $this->getRequest()->getSession();
3608 if ( !$session->canSetUser() ) {
3609 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3610 ->warning( __METHOD__ . ": Cannot log out of an immutable session" );
3611 } elseif ( !$session->getUser()->equals( $this ) ) {
3612 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3613 ->warning( __METHOD__ .
3614 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3616 // But we still may as well make this user object anon
3617 $this->clearInstanceCache( 'defaults' );
3618 } else {
3619 $this->clearInstanceCache( 'defaults' );
3620 $delay = $session->delaySave();
3621 $session->setLoggedOutTimestamp( time() );
3622 $session->setUser( new User );
3623 $session->set( 'wsUserID', 0 ); // Other code expects this
3624 ScopedCallback::consume( $delay );
3629 * Save this user's settings into the database.
3630 * @todo Only rarely do all these fields need to be set!
3632 public function saveSettings() {
3633 if ( wfReadOnly() ) {
3634 // @TODO: caller should deal with this instead!
3635 // This should really just be an exception.
3636 MWExceptionHandler::logException( new DBExpectedError(
3637 null,
3638 "Could not update user with ID '{$this->mId}'; DB is read-only."
3639 ) );
3640 return;
3643 $this->load();
3644 if ( 0 == $this->mId ) {
3645 return; // anon
3648 // Get a new user_touched that is higher than the old one.
3649 // This will be used for a CAS check as a last-resort safety
3650 // check against race conditions and slave lag.
3651 $oldTouched = $this->mTouched;
3652 $newTouched = $this->newTouchedTimestamp();
3654 $dbw = wfGetDB( DB_MASTER );
3655 $dbw->update( 'user',
3656 array( /* SET */
3657 'user_name' => $this->mName,
3658 'user_real_name' => $this->mRealName,
3659 'user_email' => $this->mEmail,
3660 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3661 'user_touched' => $dbw->timestamp( $newTouched ),
3662 'user_token' => strval( $this->mToken ),
3663 'user_email_token' => $this->mEmailToken,
3664 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3665 ), array( /* WHERE */
3666 'user_id' => $this->mId,
3667 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3668 ), __METHOD__
3671 if ( !$dbw->affectedRows() ) {
3672 // Maybe the problem was a missed cache update; clear it to be safe
3673 $this->clearSharedCache( 'refresh' );
3674 // User was changed in the meantime or loaded with stale data
3675 $from = ( $this->queryFlagsUsed & self::READ_LATEST ) ? 'master' : 'slave';
3676 throw new MWException(
3677 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3678 " the version of the user to be saved is older than the current version."
3682 $this->mTouched = $newTouched;
3683 $this->saveOptions();
3685 Hooks::run( 'UserSaveSettings', array( $this ) );
3686 $this->clearSharedCache();
3687 $this->getUserPage()->invalidateCache();
3691 * If only this user's username is known, and it exists, return the user ID.
3693 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3694 * @return int
3696 public function idForName( $flags = 0 ) {
3697 $s = trim( $this->getName() );
3698 if ( $s === '' ) {
3699 return 0;
3702 $db = ( ( $flags & self::READ_LATEST ) == self::READ_LATEST )
3703 ? wfGetDB( DB_MASTER )
3704 : wfGetDB( DB_SLAVE );
3706 $options = ( ( $flags & self::READ_LOCKING ) == self::READ_LOCKING )
3707 ? array( 'LOCK IN SHARE MODE' )
3708 : array();
3710 $id = $db->selectField( 'user',
3711 'user_id', array( 'user_name' => $s ), __METHOD__, $options );
3713 return (int)$id;
3717 * Add a user to the database, return the user object
3719 * @param string $name Username to add
3720 * @param array $params Array of Strings Non-default parameters to save to
3721 * the database as user_* fields:
3722 * - email: The user's email address.
3723 * - email_authenticated: The email authentication timestamp.
3724 * - real_name: The user's real name.
3725 * - options: An associative array of non-default options.
3726 * - token: Random authentication token. Do not set.
3727 * - registration: Registration timestamp. Do not set.
3729 * @return User|null User object, or null if the username already exists.
3731 public static function createNew( $name, $params = array() ) {
3732 foreach ( array( 'password', 'newpassword', 'newpass_time', 'password_expires' ) as $field ) {
3733 if ( isset( $params[$field] ) ) {
3734 wfDeprecated( __METHOD__ . " with param '$field'", '1.27' );
3735 unset( $params[$field] );
3739 $user = new User;
3740 $user->load();
3741 $user->setToken(); // init token
3742 if ( isset( $params['options'] ) ) {
3743 $user->mOptions = $params['options'] + (array)$user->mOptions;
3744 unset( $params['options'] );
3746 $dbw = wfGetDB( DB_MASTER );
3747 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3749 $noPass = PasswordFactory::newInvalidPassword()->toString();
3751 $fields = array(
3752 'user_id' => $seqVal,
3753 'user_name' => $name,
3754 'user_password' => $noPass,
3755 'user_newpassword' => $noPass,
3756 'user_email' => $user->mEmail,
3757 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3758 'user_real_name' => $user->mRealName,
3759 'user_token' => strval( $user->mToken ),
3760 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3761 'user_editcount' => 0,
3762 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3764 foreach ( $params as $name => $value ) {
3765 $fields["user_$name"] = $value;
3767 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3768 if ( $dbw->affectedRows() ) {
3769 $newUser = User::newFromId( $dbw->insertId() );
3770 } else {
3771 $newUser = null;
3773 return $newUser;
3777 * Add this existing user object to the database. If the user already
3778 * exists, a fatal status object is returned, and the user object is
3779 * initialised with the data from the database.
3781 * Previously, this function generated a DB error due to a key conflict
3782 * if the user already existed. Many extension callers use this function
3783 * in code along the lines of:
3785 * $user = User::newFromName( $name );
3786 * if ( !$user->isLoggedIn() ) {
3787 * $user->addToDatabase();
3789 * // do something with $user...
3791 * However, this was vulnerable to a race condition (bug 16020). By
3792 * initialising the user object if the user exists, we aim to support this
3793 * calling sequence as far as possible.
3795 * Note that if the user exists, this function will acquire a write lock,
3796 * so it is still advisable to make the call conditional on isLoggedIn(),
3797 * and to commit the transaction after calling.
3799 * @throws MWException
3800 * @return Status
3802 public function addToDatabase() {
3803 $this->load();
3804 if ( !$this->mToken ) {
3805 $this->setToken(); // init token
3808 $this->mTouched = $this->newTouchedTimestamp();
3810 $noPass = PasswordFactory::newInvalidPassword()->toString();
3812 $dbw = wfGetDB( DB_MASTER );
3813 $inWrite = $dbw->writesOrCallbacksPending();
3814 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3815 $dbw->insert( 'user',
3816 array(
3817 'user_id' => $seqVal,
3818 'user_name' => $this->mName,
3819 'user_password' => $noPass,
3820 'user_newpassword' => $noPass,
3821 'user_email' => $this->mEmail,
3822 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3823 'user_real_name' => $this->mRealName,
3824 'user_token' => strval( $this->mToken ),
3825 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3826 'user_editcount' => 0,
3827 'user_touched' => $dbw->timestamp( $this->mTouched ),
3828 ), __METHOD__,
3829 array( 'IGNORE' )
3831 if ( !$dbw->affectedRows() ) {
3832 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3833 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3834 if ( $inWrite ) {
3835 // Can't commit due to pending writes that may need atomicity.
3836 // This may cause some lock contention unlike the case below.
3837 $options = array( 'LOCK IN SHARE MODE' );
3838 $flags = self::READ_LOCKING;
3839 } else {
3840 // Often, this case happens early in views before any writes when
3841 // using CentralAuth. It's should be OK to commit and break the snapshot.
3842 $dbw->commit( __METHOD__, 'flush' );
3843 $options = array();
3844 $flags = self::READ_LATEST;
3846 $this->mId = $dbw->selectField( 'user', 'user_id',
3847 array( 'user_name' => $this->mName ), __METHOD__, $options );
3848 $loaded = false;
3849 if ( $this->mId ) {
3850 if ( $this->loadFromDatabase( $flags ) ) {
3851 $loaded = true;
3854 if ( !$loaded ) {
3855 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3856 "to insert user '{$this->mName}' row, but it was not present in select!" );
3858 return Status::newFatal( 'userexists' );
3860 $this->mId = $dbw->insertId();
3861 self::$idCacheByName[$this->mName] = $this->mId;
3863 // Clear instance cache other than user table data, which is already accurate
3864 $this->clearInstanceCache();
3866 $this->saveOptions();
3867 return Status::newGood();
3871 * If this user is logged-in and blocked,
3872 * block any IP address they've successfully logged in from.
3873 * @return bool A block was spread
3875 public function spreadAnyEditBlock() {
3876 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3877 return $this->spreadBlock();
3879 return false;
3883 * If this (non-anonymous) user is blocked,
3884 * block the IP address they've successfully logged in from.
3885 * @return bool A block was spread
3887 protected function spreadBlock() {
3888 wfDebug( __METHOD__ . "()\n" );
3889 $this->load();
3890 if ( $this->mId == 0 ) {
3891 return false;
3894 $userblock = Block::newFromTarget( $this->getName() );
3895 if ( !$userblock ) {
3896 return false;
3899 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3903 * Get whether the user is explicitly blocked from account creation.
3904 * @return bool|Block
3906 public function isBlockedFromCreateAccount() {
3907 $this->getBlockedStatus();
3908 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3909 return $this->mBlock;
3912 # bug 13611: if the IP address the user is trying to create an account from is
3913 # blocked with createaccount disabled, prevent new account creation there even
3914 # when the user is logged in
3915 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3916 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3918 return $this->mBlockedFromCreateAccount instanceof Block
3919 && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3920 ? $this->mBlockedFromCreateAccount
3921 : false;
3925 * Get whether the user is blocked from using Special:Emailuser.
3926 * @return bool
3928 public function isBlockedFromEmailuser() {
3929 $this->getBlockedStatus();
3930 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3934 * Get whether the user is allowed to create an account.
3935 * @return bool
3937 public function isAllowedToCreateAccount() {
3938 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3942 * Get this user's personal page title.
3944 * @return Title User's personal page title
3946 public function getUserPage() {
3947 return Title::makeTitle( NS_USER, $this->getName() );
3951 * Get this user's talk page title.
3953 * @return Title User's talk page title
3955 public function getTalkPage() {
3956 $title = $this->getUserPage();
3957 return $title->getTalkPage();
3961 * Determine whether the user is a newbie. Newbies are either
3962 * anonymous IPs, or the most recently created accounts.
3963 * @return bool
3965 public function isNewbie() {
3966 return !$this->isAllowed( 'autoconfirmed' );
3970 * Check to see if the given clear-text password is one of the accepted passwords
3971 * @deprecated since 1.27. AuthManager is coming.
3972 * @param string $password User password
3973 * @return bool True if the given password is correct, otherwise False
3975 public function checkPassword( $password ) {
3976 global $wgAuth, $wgLegacyEncoding;
3978 $this->load();
3980 // Some passwords will give a fatal Status, which means there is
3981 // some sort of technical or security reason for this password to
3982 // be completely invalid and should never be checked (e.g., T64685)
3983 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
3984 return false;
3987 // Certain authentication plugins do NOT want to save
3988 // domain passwords in a mysql database, so we should
3989 // check this (in case $wgAuth->strict() is false).
3990 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3991 return true;
3992 } elseif ( $wgAuth->strict() ) {
3993 // Auth plugin doesn't allow local authentication
3994 return false;
3995 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3996 // Auth plugin doesn't allow local authentication for this user name
3997 return false;
4000 $passwordFactory = new PasswordFactory();
4001 $passwordFactory->init( RequestContext::getMain()->getConfig() );
4002 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
4003 ? wfGetDB( DB_MASTER )
4004 : wfGetDB( DB_SLAVE );
4006 try {
4007 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4008 'user', 'user_password', array( 'user_id' => $this->getId() ), __METHOD__
4009 ) );
4010 } catch ( PasswordError $e ) {
4011 wfDebug( 'Invalid password hash found in database.' );
4012 $mPassword = PasswordFactory::newInvalidPassword();
4015 if ( !$mPassword->equals( $password ) ) {
4016 if ( $wgLegacyEncoding ) {
4017 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4018 // Check for this with iconv
4019 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4020 if ( $cp1252Password === $password || !$mPassword->equals( $cp1252Password ) ) {
4021 return false;
4023 } else {
4024 return false;
4028 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4029 $this->setPasswordInternal( $password );
4032 return true;
4036 * Check if the given clear-text password matches the temporary password
4037 * sent by e-mail for password reset operations.
4039 * @deprecated since 1.27. AuthManager is coming.
4040 * @param string $plaintext
4041 * @return bool True if matches, false otherwise
4043 public function checkTemporaryPassword( $plaintext ) {
4044 global $wgNewPasswordExpiry;
4046 $this->load();
4048 $passwordFactory = new PasswordFactory();
4049 $passwordFactory->init( RequestContext::getMain()->getConfig() );
4050 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
4051 ? wfGetDB( DB_MASTER )
4052 : wfGetDB( DB_SLAVE );
4054 $row = $db->selectRow(
4055 'user',
4056 array( 'user_newpassword', 'user_newpass_time' ),
4057 array( 'user_id' => $this->getId() ),
4058 __METHOD__
4060 try {
4061 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword );
4062 } catch ( PasswordError $e ) {
4063 wfDebug( 'Invalid password hash found in database.' );
4064 $newPassword = PasswordFactory::newInvalidPassword();
4067 if ( $newPassword->equals( $plaintext ) ) {
4068 if ( is_null( $row->user_newpass_time ) ) {
4069 return true;
4071 $expiry = wfTimestamp( TS_UNIX, $row->user_newpass_time ) + $wgNewPasswordExpiry;
4072 return ( time() < $expiry );
4073 } else {
4074 return false;
4079 * Initialize (if necessary) and return a session token value
4080 * which can be used in edit forms to show that the user's
4081 * login credentials aren't being hijacked with a foreign form
4082 * submission.
4084 * @since 1.27
4085 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4086 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4087 * @return MediaWiki\\Session\\Token The new edit token
4089 public function getEditTokenObject( $salt = '', $request = null ) {
4090 if ( $this->isAnon() ) {
4091 return new LoggedOutEditToken();
4094 if ( !$request ) {
4095 $request = $this->getRequest();
4097 return $request->getSession()->getToken( $salt );
4101 * Initialize (if necessary) and return a session token value
4102 * which can be used in edit forms to show that the user's
4103 * login credentials aren't being hijacked with a foreign form
4104 * submission.
4106 * @since 1.19
4107 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4108 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4109 * @return string The new edit token
4111 public function getEditToken( $salt = '', $request = null ) {
4112 return $this->getEditTokenObject( $salt, $request )->toString();
4116 * Get the embedded timestamp from a token.
4117 * @deprecated since 1.27, use \\MediaWiki\\Session\\Token::getTimestamp instead.
4118 * @param string $val Input token
4119 * @return int|null
4121 public static function getEditTokenTimestamp( $val ) {
4122 wfDeprecated( __METHOD__, '1.27' );
4123 return MediaWiki\Session\Token::getTimestamp( $val );
4127 * Check given value against the token value stored in the session.
4128 * A match should confirm that the form was submitted from the
4129 * user's own login session, not a form submission from a third-party
4130 * site.
4132 * @param string $val Input value to compare
4133 * @param string $salt Optional function-specific data for hashing
4134 * @param WebRequest|null $request Object to use or null to use $wgRequest
4135 * @param int $maxage Fail tokens older than this, in seconds
4136 * @return bool Whether the token matches
4138 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4139 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4143 * Check given value against the token value stored in the session,
4144 * ignoring the suffix.
4146 * @param string $val Input value to compare
4147 * @param string $salt Optional function-specific data for hashing
4148 * @param WebRequest|null $request Object to use or null to use $wgRequest
4149 * @param int $maxage Fail tokens older than this, in seconds
4150 * @return bool Whether the token matches
4152 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4153 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self::EDIT_TOKEN_SUFFIX;
4154 return $this->matchEditToken( $val, $salt, $request, $maxage );
4158 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4159 * mail to the user's given address.
4161 * @param string $type Message to send, either "created", "changed" or "set"
4162 * @return Status
4164 public function sendConfirmationMail( $type = 'created' ) {
4165 global $wgLang;
4166 $expiration = null; // gets passed-by-ref and defined in next line.
4167 $token = $this->confirmationToken( $expiration );
4168 $url = $this->confirmationTokenUrl( $token );
4169 $invalidateURL = $this->invalidationTokenUrl( $token );
4170 $this->saveSettings();
4172 if ( $type == 'created' || $type === false ) {
4173 $message = 'confirmemail_body';
4174 } elseif ( $type === true ) {
4175 $message = 'confirmemail_body_changed';
4176 } else {
4177 // Messages: confirmemail_body_changed, confirmemail_body_set
4178 $message = 'confirmemail_body_' . $type;
4181 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4182 wfMessage( $message,
4183 $this->getRequest()->getIP(),
4184 $this->getName(),
4185 $url,
4186 $wgLang->userTimeAndDate( $expiration, $this ),
4187 $invalidateURL,
4188 $wgLang->userDate( $expiration, $this ),
4189 $wgLang->userTime( $expiration, $this ) )->text() );
4193 * Send an e-mail to this user's account. Does not check for
4194 * confirmed status or validity.
4196 * @param string $subject Message subject
4197 * @param string $body Message body
4198 * @param User|null $from Optional sending user; if unspecified, default
4199 * $wgPasswordSender will be used.
4200 * @param string $replyto Reply-To address
4201 * @return Status
4203 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4204 global $wgPasswordSender;
4206 if ( $from instanceof User ) {
4207 $sender = MailAddress::newFromUser( $from );
4208 } else {
4209 $sender = new MailAddress( $wgPasswordSender,
4210 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4212 $to = MailAddress::newFromUser( $this );
4214 return UserMailer::send( $to, $sender, $subject, $body, array(
4215 'replyTo' => $replyto,
4216 ) );
4220 * Generate, store, and return a new e-mail confirmation code.
4221 * A hash (unsalted, since it's used as a key) is stored.
4223 * @note Call saveSettings() after calling this function to commit
4224 * this change to the database.
4226 * @param string &$expiration Accepts the expiration time
4227 * @return string New token
4229 protected function confirmationToken( &$expiration ) {
4230 global $wgUserEmailConfirmationTokenExpiry;
4231 $now = time();
4232 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
4233 $expiration = wfTimestamp( TS_MW, $expires );
4234 $this->load();
4235 $token = MWCryptRand::generateHex( 32 );
4236 $hash = md5( $token );
4237 $this->mEmailToken = $hash;
4238 $this->mEmailTokenExpires = $expiration;
4239 return $token;
4243 * Return a URL the user can use to confirm their email address.
4244 * @param string $token Accepts the email confirmation token
4245 * @return string New token URL
4247 protected function confirmationTokenUrl( $token ) {
4248 return $this->getTokenUrl( 'ConfirmEmail', $token );
4252 * Return a URL the user can use to invalidate their email address.
4253 * @param string $token Accepts the email confirmation token
4254 * @return string New token URL
4256 protected function invalidationTokenUrl( $token ) {
4257 return $this->getTokenUrl( 'InvalidateEmail', $token );
4261 * Internal function to format the e-mail validation/invalidation URLs.
4262 * This uses a quickie hack to use the
4263 * hardcoded English names of the Special: pages, for ASCII safety.
4265 * @note Since these URLs get dropped directly into emails, using the
4266 * short English names avoids insanely long URL-encoded links, which
4267 * also sometimes can get corrupted in some browsers/mailers
4268 * (bug 6957 with Gmail and Internet Explorer).
4270 * @param string $page Special page
4271 * @param string $token Token
4272 * @return string Formatted URL
4274 protected function getTokenUrl( $page, $token ) {
4275 // Hack to bypass localization of 'Special:'
4276 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
4277 return $title->getCanonicalURL();
4281 * Mark the e-mail address confirmed.
4283 * @note Call saveSettings() after calling this function to commit the change.
4285 * @return bool
4287 public function confirmEmail() {
4288 // Check if it's already confirmed, so we don't touch the database
4289 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4290 if ( !$this->isEmailConfirmed() ) {
4291 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4292 Hooks::run( 'ConfirmEmailComplete', array( $this ) );
4294 return true;
4298 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4299 * address if it was already confirmed.
4301 * @note Call saveSettings() after calling this function to commit the change.
4302 * @return bool Returns true
4304 public function invalidateEmail() {
4305 $this->load();
4306 $this->mEmailToken = null;
4307 $this->mEmailTokenExpires = null;
4308 $this->setEmailAuthenticationTimestamp( null );
4309 $this->mEmail = '';
4310 Hooks::run( 'InvalidateEmailComplete', array( $this ) );
4311 return true;
4315 * Set the e-mail authentication timestamp.
4316 * @param string $timestamp TS_MW timestamp
4318 public function setEmailAuthenticationTimestamp( $timestamp ) {
4319 $this->load();
4320 $this->mEmailAuthenticated = $timestamp;
4321 Hooks::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
4325 * Is this user allowed to send e-mails within limits of current
4326 * site configuration?
4327 * @return bool
4329 public function canSendEmail() {
4330 global $wgEnableEmail, $wgEnableUserEmail;
4331 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4332 return false;
4334 $canSend = $this->isEmailConfirmed();
4335 Hooks::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4336 return $canSend;
4340 * Is this user allowed to receive e-mails within limits of current
4341 * site configuration?
4342 * @return bool
4344 public function canReceiveEmail() {
4345 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4349 * Is this user's e-mail address valid-looking and confirmed within
4350 * limits of the current site configuration?
4352 * @note If $wgEmailAuthentication is on, this may require the user to have
4353 * confirmed their address by returning a code or using a password
4354 * sent to the address from the wiki.
4356 * @return bool
4358 public function isEmailConfirmed() {
4359 global $wgEmailAuthentication;
4360 $this->load();
4361 $confirmed = true;
4362 if ( Hooks::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4363 if ( $this->isAnon() ) {
4364 return false;
4366 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4367 return false;
4369 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4370 return false;
4372 return true;
4373 } else {
4374 return $confirmed;
4379 * Check whether there is an outstanding request for e-mail confirmation.
4380 * @return bool
4382 public function isEmailConfirmationPending() {
4383 global $wgEmailAuthentication;
4384 return $wgEmailAuthentication &&
4385 !$this->isEmailConfirmed() &&
4386 $this->mEmailToken &&
4387 $this->mEmailTokenExpires > wfTimestamp();
4391 * Get the timestamp of account creation.
4393 * @return string|bool|null Timestamp of account creation, false for
4394 * non-existent/anonymous user accounts, or null if existing account
4395 * but information is not in database.
4397 public function getRegistration() {
4398 if ( $this->isAnon() ) {
4399 return false;
4401 $this->load();
4402 return $this->mRegistration;
4406 * Get the timestamp of the first edit
4408 * @return string|bool Timestamp of first edit, or false for
4409 * non-existent/anonymous user accounts.
4411 public function getFirstEditTimestamp() {
4412 if ( $this->getId() == 0 ) {
4413 return false; // anons
4415 $dbr = wfGetDB( DB_SLAVE );
4416 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4417 array( 'rev_user' => $this->getId() ),
4418 __METHOD__,
4419 array( 'ORDER BY' => 'rev_timestamp ASC' )
4421 if ( !$time ) {
4422 return false; // no edits
4424 return wfTimestamp( TS_MW, $time );
4428 * Get the permissions associated with a given list of groups
4430 * @param array $groups Array of Strings List of internal group names
4431 * @return array Array of Strings List of permission key names for given groups combined
4433 public static function getGroupPermissions( $groups ) {
4434 global $wgGroupPermissions, $wgRevokePermissions;
4435 $rights = array();
4436 // grant every granted permission first
4437 foreach ( $groups as $group ) {
4438 if ( isset( $wgGroupPermissions[$group] ) ) {
4439 $rights = array_merge( $rights,
4440 // array_filter removes empty items
4441 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4444 // now revoke the revoked permissions
4445 foreach ( $groups as $group ) {
4446 if ( isset( $wgRevokePermissions[$group] ) ) {
4447 $rights = array_diff( $rights,
4448 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4451 return array_unique( $rights );
4455 * Get all the groups who have a given permission
4457 * @param string $role Role to check
4458 * @return array Array of Strings List of internal group names with the given permission
4460 public static function getGroupsWithPermission( $role ) {
4461 global $wgGroupPermissions;
4462 $allowedGroups = array();
4463 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4464 if ( self::groupHasPermission( $group, $role ) ) {
4465 $allowedGroups[] = $group;
4468 return $allowedGroups;
4472 * Check, if the given group has the given permission
4474 * If you're wanting to check whether all users have a permission, use
4475 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4476 * from anyone.
4478 * @since 1.21
4479 * @param string $group Group to check
4480 * @param string $role Role to check
4481 * @return bool
4483 public static function groupHasPermission( $group, $role ) {
4484 global $wgGroupPermissions, $wgRevokePermissions;
4485 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4486 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4490 * Check if all users may be assumed to have the given permission
4492 * We generally assume so if the right is granted to '*' and isn't revoked
4493 * on any group. It doesn't attempt to take grants or other extension
4494 * limitations on rights into account in the general case, though, as that
4495 * would require it to always return false and defeat the purpose.
4496 * Specifically, session-based rights restrictions (such as OAuth or bot
4497 * passwords) are applied based on the current session.
4499 * @since 1.22
4500 * @param string $right Right to check
4501 * @return bool
4503 public static function isEveryoneAllowed( $right ) {
4504 global $wgGroupPermissions, $wgRevokePermissions;
4505 static $cache = array();
4507 // Use the cached results, except in unit tests which rely on
4508 // being able change the permission mid-request
4509 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4510 return $cache[$right];
4513 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4514 $cache[$right] = false;
4515 return false;
4518 // If it's revoked anywhere, then everyone doesn't have it
4519 foreach ( $wgRevokePermissions as $rights ) {
4520 if ( isset( $rights[$right] ) && $rights[$right] ) {
4521 $cache[$right] = false;
4522 return false;
4526 // Remove any rights that aren't allowed to the global-session user
4527 $allowedRights = SessionManager::getGlobalSession()->getAllowedUserRights();
4528 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4529 $cache[$right] = false;
4530 return false;
4533 // Allow extensions to say false
4534 if ( !Hooks::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4535 $cache[$right] = false;
4536 return false;
4539 $cache[$right] = true;
4540 return true;
4544 * Get the localized descriptive name for a group, if it exists
4546 * @param string $group Internal group name
4547 * @return string Localized descriptive group name
4549 public static function getGroupName( $group ) {
4550 $msg = wfMessage( "group-$group" );
4551 return $msg->isBlank() ? $group : $msg->text();
4555 * Get the localized descriptive name for a member of a group, if it exists
4557 * @param string $group Internal group name
4558 * @param string $username Username for gender (since 1.19)
4559 * @return string Localized name for group member
4561 public static function getGroupMember( $group, $username = '#' ) {
4562 $msg = wfMessage( "group-$group-member", $username );
4563 return $msg->isBlank() ? $group : $msg->text();
4567 * Return the set of defined explicit groups.
4568 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4569 * are not included, as they are defined automatically, not in the database.
4570 * @return array Array of internal group names
4572 public static function getAllGroups() {
4573 global $wgGroupPermissions, $wgRevokePermissions;
4574 return array_diff(
4575 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4576 self::getImplicitGroups()
4581 * Get a list of all available permissions.
4582 * @return string[] Array of permission names
4584 public static function getAllRights() {
4585 if ( self::$mAllRights === false ) {
4586 global $wgAvailableRights;
4587 if ( count( $wgAvailableRights ) ) {
4588 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4589 } else {
4590 self::$mAllRights = self::$mCoreRights;
4592 Hooks::run( 'UserGetAllRights', array( &self::$mAllRights ) );
4594 return self::$mAllRights;
4598 * Get a list of implicit groups
4599 * @return array Array of Strings Array of internal group names
4601 public static function getImplicitGroups() {
4602 global $wgImplicitGroups;
4604 $groups = $wgImplicitGroups;
4605 # Deprecated, use $wgImplicitGroups instead
4606 Hooks::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4608 return $groups;
4612 * Get the title of a page describing a particular group
4614 * @param string $group Internal group name
4615 * @return Title|bool Title of the page if it exists, false otherwise
4617 public static function getGroupPage( $group ) {
4618 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4619 if ( $msg->exists() ) {
4620 $title = Title::newFromText( $msg->text() );
4621 if ( is_object( $title ) ) {
4622 return $title;
4625 return false;
4629 * Create a link to the group in HTML, if available;
4630 * else return the group name.
4632 * @param string $group Internal name of the group
4633 * @param string $text The text of the link
4634 * @return string HTML link to the group
4636 public static function makeGroupLinkHTML( $group, $text = '' ) {
4637 if ( $text == '' ) {
4638 $text = self::getGroupName( $group );
4640 $title = self::getGroupPage( $group );
4641 if ( $title ) {
4642 return Linker::link( $title, htmlspecialchars( $text ) );
4643 } else {
4644 return htmlspecialchars( $text );
4649 * Create a link to the group in Wikitext, if available;
4650 * else return the group name.
4652 * @param string $group Internal name of the group
4653 * @param string $text The text of the link
4654 * @return string Wikilink to the group
4656 public static function makeGroupLinkWiki( $group, $text = '' ) {
4657 if ( $text == '' ) {
4658 $text = self::getGroupName( $group );
4660 $title = self::getGroupPage( $group );
4661 if ( $title ) {
4662 $page = $title->getFullText();
4663 return "[[$page|$text]]";
4664 } else {
4665 return $text;
4670 * Returns an array of the groups that a particular group can add/remove.
4672 * @param string $group The group to check for whether it can add/remove
4673 * @return array Array( 'add' => array( addablegroups ),
4674 * 'remove' => array( removablegroups ),
4675 * 'add-self' => array( addablegroups to self),
4676 * 'remove-self' => array( removable groups from self) )
4678 public static function changeableByGroup( $group ) {
4679 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4681 $groups = array(
4682 'add' => array(),
4683 'remove' => array(),
4684 'add-self' => array(),
4685 'remove-self' => array()
4688 if ( empty( $wgAddGroups[$group] ) ) {
4689 // Don't add anything to $groups
4690 } elseif ( $wgAddGroups[$group] === true ) {
4691 // You get everything
4692 $groups['add'] = self::getAllGroups();
4693 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4694 $groups['add'] = $wgAddGroups[$group];
4697 // Same thing for remove
4698 if ( empty( $wgRemoveGroups[$group] ) ) {
4699 // Do nothing
4700 } elseif ( $wgRemoveGroups[$group] === true ) {
4701 $groups['remove'] = self::getAllGroups();
4702 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4703 $groups['remove'] = $wgRemoveGroups[$group];
4706 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4707 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4708 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4709 if ( is_int( $key ) ) {
4710 $wgGroupsAddToSelf['user'][] = $value;
4715 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4716 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4717 if ( is_int( $key ) ) {
4718 $wgGroupsRemoveFromSelf['user'][] = $value;
4723 // Now figure out what groups the user can add to him/herself
4724 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4725 // Do nothing
4726 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4727 // No idea WHY this would be used, but it's there
4728 $groups['add-self'] = User::getAllGroups();
4729 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4730 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4733 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4734 // Do nothing
4735 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4736 $groups['remove-self'] = User::getAllGroups();
4737 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4738 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4741 return $groups;
4745 * Returns an array of groups that this user can add and remove
4746 * @return array Array( 'add' => array( addablegroups ),
4747 * 'remove' => array( removablegroups ),
4748 * 'add-self' => array( addablegroups to self),
4749 * 'remove-self' => array( removable groups from self) )
4751 public function changeableGroups() {
4752 if ( $this->isAllowed( 'userrights' ) ) {
4753 // This group gives the right to modify everything (reverse-
4754 // compatibility with old "userrights lets you change
4755 // everything")
4756 // Using array_merge to make the groups reindexed
4757 $all = array_merge( User::getAllGroups() );
4758 return array(
4759 'add' => $all,
4760 'remove' => $all,
4761 'add-self' => array(),
4762 'remove-self' => array()
4766 // Okay, it's not so simple, we will have to go through the arrays
4767 $groups = array(
4768 'add' => array(),
4769 'remove' => array(),
4770 'add-self' => array(),
4771 'remove-self' => array()
4773 $addergroups = $this->getEffectiveGroups();
4775 foreach ( $addergroups as $addergroup ) {
4776 $groups = array_merge_recursive(
4777 $groups, $this->changeableByGroup( $addergroup )
4779 $groups['add'] = array_unique( $groups['add'] );
4780 $groups['remove'] = array_unique( $groups['remove'] );
4781 $groups['add-self'] = array_unique( $groups['add-self'] );
4782 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4784 return $groups;
4788 * Deferred version of incEditCountImmediate()
4790 public function incEditCount() {
4791 $that = $this;
4792 wfGetDB( DB_MASTER )->onTransactionPreCommitOrIdle( function() use ( $that ) {
4793 $that->incEditCountImmediate();
4794 } );
4798 * Increment the user's edit-count field.
4799 * Will have no effect for anonymous users.
4800 * @since 1.26
4802 public function incEditCountImmediate() {
4803 if ( $this->isAnon() ) {
4804 return;
4807 $dbw = wfGetDB( DB_MASTER );
4808 // No rows will be "affected" if user_editcount is NULL
4809 $dbw->update(
4810 'user',
4811 array( 'user_editcount=user_editcount+1' ),
4812 array( 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ),
4813 __METHOD__
4815 // Lazy initialization check...
4816 if ( $dbw->affectedRows() == 0 ) {
4817 // Now here's a goddamn hack...
4818 $dbr = wfGetDB( DB_SLAVE );
4819 if ( $dbr !== $dbw ) {
4820 // If we actually have a slave server, the count is
4821 // at least one behind because the current transaction
4822 // has not been committed and replicated.
4823 $this->initEditCount( 1 );
4824 } else {
4825 // But if DB_SLAVE is selecting the master, then the
4826 // count we just read includes the revision that was
4827 // just added in the working transaction.
4828 $this->initEditCount();
4831 // Edit count in user cache too
4832 $this->invalidateCache();
4836 * Initialize user_editcount from data out of the revision table
4838 * @param int $add Edits to add to the count from the revision table
4839 * @return int Number of edits
4841 protected function initEditCount( $add = 0 ) {
4842 // Pull from a slave to be less cruel to servers
4843 // Accuracy isn't the point anyway here
4844 $dbr = wfGetDB( DB_SLAVE );
4845 $count = (int)$dbr->selectField(
4846 'revision',
4847 'COUNT(rev_user)',
4848 array( 'rev_user' => $this->getId() ),
4849 __METHOD__
4851 $count = $count + $add;
4853 $dbw = wfGetDB( DB_MASTER );
4854 $dbw->update(
4855 'user',
4856 array( 'user_editcount' => $count ),
4857 array( 'user_id' => $this->getId() ),
4858 __METHOD__
4861 return $count;
4865 * Get the description of a given right
4867 * @param string $right Right to query
4868 * @return string Localized description of the right
4870 public static function getRightDescription( $right ) {
4871 $key = "right-$right";
4872 $msg = wfMessage( $key );
4873 return $msg->isBlank() ? $right : $msg->text();
4877 * Make a new-style password hash
4879 * @param string $password Plain-text password
4880 * @param bool|string $salt Optional salt, may be random or the user ID.
4881 * If unspecified or false, will generate one automatically
4882 * @return string Password hash
4883 * @deprecated since 1.24, use Password class
4885 public static function crypt( $password, $salt = false ) {
4886 wfDeprecated( __METHOD__, '1.24' );
4887 $passwordFactory = new PasswordFactory();
4888 $passwordFactory->init( RequestContext::getMain()->getConfig() );
4889 $hash = $passwordFactory->newFromPlaintext( $password );
4890 return $hash->toString();
4894 * Compare a password hash with a plain-text password. Requires the user
4895 * ID if there's a chance that the hash is an old-style hash.
4897 * @param string $hash Password hash
4898 * @param string $password Plain-text password to compare
4899 * @param string|bool $userId User ID for old-style password salt
4901 * @return bool
4902 * @deprecated since 1.24, use Password class
4904 public static function comparePasswords( $hash, $password, $userId = false ) {
4905 wfDeprecated( __METHOD__, '1.24' );
4907 // Check for *really* old password hashes that don't even have a type
4908 // The old hash format was just an md5 hex hash, with no type information
4909 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4910 global $wgPasswordSalt;
4911 if ( $wgPasswordSalt ) {
4912 $password = ":B:{$userId}:{$hash}";
4913 } else {
4914 $password = ":A:{$hash}";
4918 $passwordFactory = new PasswordFactory();
4919 $passwordFactory->init( RequestContext::getMain()->getConfig() );
4920 $hash = $passwordFactory->newFromCiphertext( $hash );
4921 return $hash->equals( $password );
4925 * Add a newuser log entry for this user.
4926 * Before 1.19 the return value was always true.
4928 * @param string|bool $action Account creation type.
4929 * - String, one of the following values:
4930 * - 'create' for an anonymous user creating an account for himself.
4931 * This will force the action's performer to be the created user itself,
4932 * no matter the value of $wgUser
4933 * - 'create2' for a logged in user creating an account for someone else
4934 * - 'byemail' when the created user will receive its password by e-mail
4935 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4936 * - Boolean means whether the account was created by e-mail (deprecated):
4937 * - true will be converted to 'byemail'
4938 * - false will be converted to 'create' if this object is the same as
4939 * $wgUser and to 'create2' otherwise
4941 * @param string $reason User supplied reason
4943 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4945 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4946 global $wgUser, $wgNewUserLog;
4947 if ( empty( $wgNewUserLog ) ) {
4948 return true; // disabled
4951 if ( $action === true ) {
4952 $action = 'byemail';
4953 } elseif ( $action === false ) {
4954 if ( $this->equals( $wgUser ) ) {
4955 $action = 'create';
4956 } else {
4957 $action = 'create2';
4961 if ( $action === 'create' || $action === 'autocreate' ) {
4962 $performer = $this;
4963 } else {
4964 $performer = $wgUser;
4967 $logEntry = new ManualLogEntry( 'newusers', $action );
4968 $logEntry->setPerformer( $performer );
4969 $logEntry->setTarget( $this->getUserPage() );
4970 $logEntry->setComment( $reason );
4971 $logEntry->setParameters( array(
4972 '4::userid' => $this->getId(),
4973 ) );
4974 $logid = $logEntry->insert();
4976 if ( $action !== 'autocreate' ) {
4977 $logEntry->publish( $logid );
4980 return (int)$logid;
4984 * Add an autocreate newuser log entry for this user
4985 * Used by things like CentralAuth and perhaps other authplugins.
4986 * Consider calling addNewUserLogEntry() directly instead.
4988 * @return bool
4990 public function addNewUserLogEntryAutoCreate() {
4991 $this->addNewUserLogEntry( 'autocreate' );
4993 return true;
4997 * Load the user options either from cache, the database or an array
4999 * @param array $data Rows for the current user out of the user_properties table
5001 protected function loadOptions( $data = null ) {
5002 global $wgContLang;
5004 $this->load();
5006 if ( $this->mOptionsLoaded ) {
5007 return;
5010 $this->mOptions = self::getDefaultOptions();
5012 if ( !$this->getId() ) {
5013 // For unlogged-in users, load language/variant options from request.
5014 // There's no need to do it for logged-in users: they can set preferences,
5015 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5016 // so don't override user's choice (especially when the user chooses site default).
5017 $variant = $wgContLang->getDefaultVariant();
5018 $this->mOptions['variant'] = $variant;
5019 $this->mOptions['language'] = $variant;
5020 $this->mOptionsLoaded = true;
5021 return;
5024 // Maybe load from the object
5025 if ( !is_null( $this->mOptionOverrides ) ) {
5026 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5027 foreach ( $this->mOptionOverrides as $key => $value ) {
5028 $this->mOptions[$key] = $value;
5030 } else {
5031 if ( !is_array( $data ) ) {
5032 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5033 // Load from database
5034 $dbr = ( $this->queryFlagsUsed & self::READ_LATEST )
5035 ? wfGetDB( DB_MASTER )
5036 : wfGetDB( DB_SLAVE );
5038 $res = $dbr->select(
5039 'user_properties',
5040 array( 'up_property', 'up_value' ),
5041 array( 'up_user' => $this->getId() ),
5042 __METHOD__
5045 $this->mOptionOverrides = array();
5046 $data = array();
5047 foreach ( $res as $row ) {
5048 $data[$row->up_property] = $row->up_value;
5051 foreach ( $data as $property => $value ) {
5052 $this->mOptionOverrides[$property] = $value;
5053 $this->mOptions[$property] = $value;
5057 $this->mOptionsLoaded = true;
5059 Hooks::run( 'UserLoadOptions', array( $this, &$this->mOptions ) );
5063 * Saves the non-default options for this user, as previously set e.g. via
5064 * setOption(), in the database's "user_properties" (preferences) table.
5065 * Usually used via saveSettings().
5067 protected function saveOptions() {
5068 $this->loadOptions();
5070 // Not using getOptions(), to keep hidden preferences in database
5071 $saveOptions = $this->mOptions;
5073 // Allow hooks to abort, for instance to save to a global profile.
5074 // Reset options to default state before saving.
5075 if ( !Hooks::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5076 return;
5079 $userId = $this->getId();
5081 $insert_rows = array(); // all the new preference rows
5082 foreach ( $saveOptions as $key => $value ) {
5083 // Don't bother storing default values
5084 $defaultOption = self::getDefaultOption( $key );
5085 if ( ( $defaultOption === null && $value !== false && $value !== null )
5086 || $value != $defaultOption
5088 $insert_rows[] = array(
5089 'up_user' => $userId,
5090 'up_property' => $key,
5091 'up_value' => $value,
5096 $dbw = wfGetDB( DB_MASTER );
5098 $res = $dbw->select( 'user_properties',
5099 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__ );
5101 // Find prior rows that need to be removed or updated. These rows will
5102 // all be deleted (the later so that INSERT IGNORE applies the new values).
5103 $keysDelete = array();
5104 foreach ( $res as $row ) {
5105 if ( !isset( $saveOptions[$row->up_property] )
5106 || strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
5108 $keysDelete[] = $row->up_property;
5112 if ( count( $keysDelete ) ) {
5113 // Do the DELETE by PRIMARY KEY for prior rows.
5114 // In the past a very large portion of calls to this function are for setting
5115 // 'rememberpassword' for new accounts (a preference that has since been removed).
5116 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5117 // caused gap locks on [max user ID,+infinity) which caused high contention since
5118 // updates would pile up on each other as they are for higher (newer) user IDs.
5119 // It might not be necessary these days, but it shouldn't hurt either.
5120 $dbw->delete( 'user_properties',
5121 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__ );
5123 // Insert the new preference rows
5124 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
5128 * Lazily instantiate and return a factory object for making passwords
5130 * @deprecated since 1.27, create a PasswordFactory directly instead
5131 * @return PasswordFactory
5133 public static function getPasswordFactory() {
5134 wfDeprecated( __METHOD__, '1.27' );
5135 $ret = new PasswordFactory();
5136 $ret->init( RequestContext::getMain()->getConfig() );
5137 return $ret;
5141 * Provide an array of HTML5 attributes to put on an input element
5142 * intended for the user to enter a new password. This may include
5143 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5145 * Do *not* use this when asking the user to enter his current password!
5146 * Regardless of configuration, users may have invalid passwords for whatever
5147 * reason (e.g., they were set before requirements were tightened up).
5148 * Only use it when asking for a new password, like on account creation or
5149 * ResetPass.
5151 * Obviously, you still need to do server-side checking.
5153 * NOTE: A combination of bugs in various browsers means that this function
5154 * actually just returns array() unconditionally at the moment. May as
5155 * well keep it around for when the browser bugs get fixed, though.
5157 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5159 * @deprecated since 1.27
5160 * @return array Array of HTML attributes suitable for feeding to
5161 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5162 * That will get confused by the boolean attribute syntax used.)
5164 public static function passwordChangeInputAttribs() {
5165 global $wgMinimalPasswordLength;
5167 if ( $wgMinimalPasswordLength == 0 ) {
5168 return array();
5171 # Note that the pattern requirement will always be satisfied if the
5172 # input is empty, so we need required in all cases.
5174 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5175 # if e-mail confirmation is being used. Since HTML5 input validation
5176 # is b0rked anyway in some browsers, just return nothing. When it's
5177 # re-enabled, fix this code to not output required for e-mail
5178 # registration.
5179 # $ret = array( 'required' );
5180 $ret = array();
5182 # We can't actually do this right now, because Opera 9.6 will print out
5183 # the entered password visibly in its error message! When other
5184 # browsers add support for this attribute, or Opera fixes its support,
5185 # we can add support with a version check to avoid doing this on Opera
5186 # versions where it will be a problem. Reported to Opera as
5187 # DSK-262266, but they don't have a public bug tracker for us to follow.
5189 if ( $wgMinimalPasswordLength > 1 ) {
5190 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5191 $ret['title'] = wfMessage( 'passwordtooshort' )
5192 ->numParams( $wgMinimalPasswordLength )->text();
5196 return $ret;
5200 * Return the list of user fields that should be selected to create
5201 * a new user object.
5202 * @return array
5204 public static function selectFields() {
5205 return array(
5206 'user_id',
5207 'user_name',
5208 'user_real_name',
5209 'user_email',
5210 'user_touched',
5211 'user_token',
5212 'user_email_authenticated',
5213 'user_email_token',
5214 'user_email_token_expires',
5215 'user_registration',
5216 'user_editcount',
5221 * Factory function for fatal permission-denied errors
5223 * @since 1.22
5224 * @param string $permission User right required
5225 * @return Status
5227 static function newFatalPermissionDeniedStatus( $permission ) {
5228 global $wgLang;
5230 $groups = array_map(
5231 array( 'User', 'makeGroupLinkWiki' ),
5232 User::getGroupsWithPermission( $permission )
5235 if ( $groups ) {
5236 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5237 } else {
5238 return Status::newFatal( 'badaccess-group0' );
5243 * Get a new instance of this user that was loaded from the master via a locking read
5245 * Use this instead of the main context User when updating that user. This avoids races
5246 * where that user was loaded from a slave or even the master but without proper locks.
5248 * @return User|null Returns null if the user was not found in the DB
5249 * @since 1.27
5251 public function getInstanceForUpdate() {
5252 if ( !$this->getId() ) {
5253 return null; // anon
5256 $user = self::newFromId( $this->getId() );
5257 if ( !$user->loadFromId( self::READ_EXCLUSIVE ) ) {
5258 return null;
5261 return $user;
5265 * Checks if two user objects point to the same user.
5267 * @since 1.25
5268 * @param User $user
5269 * @return bool
5271 public function equals( User $user ) {
5272 return $this->getName() === $user->getName();