ea72bdace9321381a6f0dd992acd9a79732d7336
[lhc/web/wiklou.git] / includes / user / User.php
1 <?php
2 /**
3 * Implements the User class for the %MediaWiki software.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22
23 use MediaWiki\MediaWikiServices;
24 use MediaWiki\Session\SessionManager;
25 use MediaWiki\Session\Token;
26 use MediaWiki\Auth\AuthManager;
27 use MediaWiki\Auth\AuthenticationResponse;
28 use MediaWiki\Auth\AuthenticationRequest;
29 use MediaWiki\User\UserIdentity;
30 use MediaWiki\Logger\LoggerFactory;
31 use Wikimedia\IPSet;
32 use Wikimedia\ScopedCallback;
33 use Wikimedia\Rdbms\Database;
34 use Wikimedia\Rdbms\DBExpectedError;
35 use Wikimedia\Rdbms\IDatabase;
36
37 /**
38 * The User object encapsulates all of the user-specific settings (user_id,
39 * name, rights, email address, options, last login time). Client
40 * classes use the getXXX() functions to access these fields. These functions
41 * do all the work of determining whether the user is logged in,
42 * whether the requested option can be satisfied from cookies or
43 * whether a database query is needed. Most of the settings needed
44 * for rendering normal pages are set in the cookie to minimize use
45 * of the database.
46 */
47 class User implements IDBAccessObject, UserIdentity {
48 /**
49 * @const int Number of characters in user_token field.
50 */
51 const TOKEN_LENGTH = 32;
52
53 /**
54 * @const string An invalid value for user_token
55 */
56 const INVALID_TOKEN = '*** INVALID ***';
57
58 /**
59 * @const int Serialized record version.
60 */
61 const VERSION = 13;
62
63 /**
64 * Exclude user options that are set to their default value.
65 * @since 1.25
66 */
67 const GETOPTIONS_EXCLUDE_DEFAULTS = 1;
68
69 /**
70 * @since 1.27
71 */
72 const CHECK_USER_RIGHTS = true;
73
74 /**
75 * @since 1.27
76 */
77 const IGNORE_USER_RIGHTS = false;
78
79 /**
80 * Array of Strings List of member variables which are saved to the
81 * shared cache (memcached). Any operation which changes the
82 * corresponding database fields must call a cache-clearing function.
83 * @showinitializer
84 */
85 protected static $mCacheVars = [
86 // user table
87 'mId',
88 'mName',
89 'mRealName',
90 'mEmail',
91 'mTouched',
92 'mToken',
93 'mEmailAuthenticated',
94 'mEmailToken',
95 'mEmailTokenExpires',
96 'mRegistration',
97 'mEditCount',
98 // user_groups table
99 'mGroupMemberships',
100 // user_properties table
101 'mOptionOverrides',
102 // actor table
103 'mActorId',
104 ];
105
106 /**
107 * Array of Strings Core rights.
108 * Each of these should have a corresponding message of the form
109 * "right-$right".
110 * @showinitializer
111 */
112 protected static $mCoreRights = [
113 'apihighlimits',
114 'applychangetags',
115 'autoconfirmed',
116 'autocreateaccount',
117 'autopatrol',
118 'bigdelete',
119 'block',
120 'blockemail',
121 'bot',
122 'browsearchive',
123 'changetags',
124 'createaccount',
125 'createpage',
126 'createtalk',
127 'delete',
128 'deletechangetags',
129 'deletedhistory',
130 'deletedtext',
131 'deletelogentry',
132 'deleterevision',
133 'edit',
134 'editcontentmodel',
135 'editinterface',
136 'editprotected',
137 'editmyoptions',
138 'editmyprivateinfo',
139 'editmyusercss',
140 'editmyuserjson',
141 'editmyuserjs',
142 'editmywatchlist',
143 'editsemiprotected',
144 'editsitecss',
145 'editsitejson',
146 'editsitejs',
147 'editusercss',
148 'edituserjson',
149 'edituserjs',
150 'hideuser',
151 'import',
152 'importupload',
153 'ipblock-exempt',
154 'managechangetags',
155 'markbotedits',
156 'mergehistory',
157 'minoredit',
158 'move',
159 'movefile',
160 'move-categorypages',
161 'move-rootuserpages',
162 'move-subpages',
163 'nominornewtalk',
164 'noratelimit',
165 'override-export-depth',
166 'pagelang',
167 'patrol',
168 'patrolmarks',
169 'protect',
170 'purge',
171 'read',
172 'reupload',
173 'reupload-own',
174 'reupload-shared',
175 'rollback',
176 'sendemail',
177 'siteadmin',
178 'suppressionlog',
179 'suppressredirect',
180 'suppressrevision',
181 'unblockself',
182 'undelete',
183 'unwatchedpages',
184 'upload',
185 'upload_by_url',
186 'userrights',
187 'userrights-interwiki',
188 'viewmyprivateinfo',
189 'viewmywatchlist',
190 'viewsuppressed',
191 'writeapi',
192 ];
193
194 /**
195 * String Cached results of getAllRights()
196 */
197 protected static $mAllRights = false;
198
199 /** Cache variables */
200 // @{
201 /** @var int */
202 public $mId;
203 /** @var string */
204 public $mName;
205 /** @var int|null */
206 protected $mActorId;
207 /** @var string */
208 public $mRealName;
209
210 /** @var string */
211 public $mEmail;
212 /** @var string TS_MW timestamp from the DB */
213 public $mTouched;
214 /** @var string TS_MW timestamp from cache */
215 protected $mQuickTouched;
216 /** @var string */
217 protected $mToken;
218 /** @var string */
219 public $mEmailAuthenticated;
220 /** @var string */
221 protected $mEmailToken;
222 /** @var string */
223 protected $mEmailTokenExpires;
224 /** @var string */
225 protected $mRegistration;
226 /** @var int */
227 protected $mEditCount;
228 /** @var UserGroupMembership[] Associative array of (group name => UserGroupMembership object) */
229 protected $mGroupMemberships;
230 /** @var array */
231 protected $mOptionOverrides;
232 // @}
233
234 /**
235 * Bool Whether the cache variables have been loaded.
236 */
237 // @{
238 public $mOptionsLoaded;
239
240 /**
241 * Array with already loaded items or true if all items have been loaded.
242 */
243 protected $mLoadedItems = [];
244 // @}
245
246 /**
247 * String Initialization data source if mLoadedItems!==true. May be one of:
248 * - 'defaults' anonymous user initialised from class defaults
249 * - 'name' initialise from mName
250 * - 'id' initialise from mId
251 * - 'actor' initialise from mActorId
252 * - 'session' log in from session if possible
253 *
254 * Use the User::newFrom*() family of functions to set this.
255 */
256 public $mFrom;
257
258 /**
259 * Lazy-initialized variables, invalidated with clearInstanceCache
260 */
261 protected $mNewtalk;
262 /** @var string */
263 protected $mDatePreference;
264 /** @var string */
265 public $mBlockedby;
266 /** @var string */
267 protected $mHash;
268 /** @var array */
269 public $mRights;
270 /** @var string */
271 protected $mBlockreason;
272 /** @var array */
273 protected $mEffectiveGroups;
274 /** @var array */
275 protected $mImplicitGroups;
276 /** @var array */
277 protected $mFormerGroups;
278 /** @var Block */
279 protected $mGlobalBlock;
280 /** @var bool */
281 protected $mLocked;
282 /** @var bool */
283 public $mHideName;
284 /** @var array */
285 public $mOptions;
286
287 /** @var WebRequest */
288 private $mRequest;
289
290 /** @var Block */
291 public $mBlock;
292
293 /** @var bool */
294 protected $mAllowUsertalk;
295
296 /** @var Block */
297 private $mBlockedFromCreateAccount = false;
298
299 /** @var int User::READ_* constant bitfield used to load data */
300 protected $queryFlagsUsed = self::READ_NORMAL;
301
302 public static $idCacheByName = [];
303
304 /**
305 * Lightweight constructor for an anonymous user.
306 * Use the User::newFrom* factory functions for other kinds of users.
307 *
308 * @see newFromName()
309 * @see newFromId()
310 * @see newFromActorId()
311 * @see newFromConfirmationCode()
312 * @see newFromSession()
313 * @see newFromRow()
314 */
315 public function __construct() {
316 $this->clearInstanceCache( 'defaults' );
317 }
318
319 /**
320 * @return string
321 */
322 public function __toString() {
323 return (string)$this->getName();
324 }
325
326 /**
327 * Test if it's safe to load this User object.
328 *
329 * You should typically check this before using $wgUser or
330 * RequestContext::getUser in a method that might be called before the
331 * system has been fully initialized. If the object is unsafe, you should
332 * use an anonymous user:
333 * \code
334 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
335 * \endcode
336 *
337 * @since 1.27
338 * @return bool
339 */
340 public function isSafeToLoad() {
341 global $wgFullyInitialised;
342
343 // The user is safe to load if:
344 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
345 // * mLoadedItems === true (already loaded)
346 // * mFrom !== 'session' (sessions not involved at all)
347
348 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
349 $this->mLoadedItems === true || $this->mFrom !== 'session';
350 }
351
352 /**
353 * Load the user table data for this object from the source given by mFrom.
354 *
355 * @param int $flags User::READ_* constant bitfield
356 */
357 public function load( $flags = self::READ_NORMAL ) {
358 global $wgFullyInitialised;
359
360 if ( $this->mLoadedItems === true ) {
361 return;
362 }
363
364 // Set it now to avoid infinite recursion in accessors
365 $oldLoadedItems = $this->mLoadedItems;
366 $this->mLoadedItems = true;
367 $this->queryFlagsUsed = $flags;
368
369 // If this is called too early, things are likely to break.
370 if ( !$wgFullyInitialised && $this->mFrom === 'session' ) {
371 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
372 ->warning( 'User::loadFromSession called before the end of Setup.php', [
373 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
374 ] );
375 $this->loadDefaults();
376 $this->mLoadedItems = $oldLoadedItems;
377 return;
378 }
379
380 switch ( $this->mFrom ) {
381 case 'defaults':
382 $this->loadDefaults();
383 break;
384 case 'name':
385 // Make sure this thread sees its own changes
386 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
387 if ( $lb->hasOrMadeRecentMasterChanges() ) {
388 $flags |= self::READ_LATEST;
389 $this->queryFlagsUsed = $flags;
390 }
391
392 $this->mId = self::idFromName( $this->mName, $flags );
393 if ( !$this->mId ) {
394 // Nonexistent user placeholder object
395 $this->loadDefaults( $this->mName );
396 } else {
397 $this->loadFromId( $flags );
398 }
399 break;
400 case 'id':
401 // Make sure this thread sees its own changes, if the ID isn't 0
402 if ( $this->mId != 0 ) {
403 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
404 if ( $lb->hasOrMadeRecentMasterChanges() ) {
405 $flags |= self::READ_LATEST;
406 $this->queryFlagsUsed = $flags;
407 }
408 }
409
410 $this->loadFromId( $flags );
411 break;
412 case 'actor':
413 // Make sure this thread sees its own changes
414 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
415 if ( $lb->hasOrMadeRecentMasterChanges() ) {
416 $flags |= self::READ_LATEST;
417 $this->queryFlagsUsed = $flags;
418 }
419
420 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
421 $row = wfGetDB( $index )->selectRow(
422 'actor',
423 [ 'actor_user', 'actor_name' ],
424 [ 'actor_id' => $this->mActorId ],
425 __METHOD__,
426 $options
427 );
428
429 if ( !$row ) {
430 // Ugh.
431 $this->loadDefaults();
432 } elseif ( $row->actor_user ) {
433 $this->mId = $row->actor_user;
434 $this->loadFromId( $flags );
435 } else {
436 $this->loadDefaults( $row->actor_name );
437 }
438 break;
439 case 'session':
440 if ( !$this->loadFromSession() ) {
441 // Loading from session failed. Load defaults.
442 $this->loadDefaults();
443 }
444 Hooks::run( 'UserLoadAfterLoadFromSession', [ $this ] );
445 break;
446 default:
447 throw new UnexpectedValueException(
448 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
449 }
450 }
451
452 /**
453 * Load user table data, given mId has already been set.
454 * @param int $flags User::READ_* constant bitfield
455 * @return bool False if the ID does not exist, true otherwise
456 */
457 public function loadFromId( $flags = self::READ_NORMAL ) {
458 if ( $this->mId == 0 ) {
459 // Anonymous users are not in the database (don't need cache)
460 $this->loadDefaults();
461 return false;
462 }
463
464 // Try cache (unless this needs data from the master DB).
465 // NOTE: if this thread called saveSettings(), the cache was cleared.
466 $latest = DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST );
467 if ( $latest ) {
468 if ( !$this->loadFromDatabase( $flags ) ) {
469 // Can't load from ID
470 return false;
471 }
472 } else {
473 $this->loadFromCache();
474 }
475
476 $this->mLoadedItems = true;
477 $this->queryFlagsUsed = $flags;
478
479 return true;
480 }
481
482 /**
483 * @since 1.27
484 * @param string $wikiId
485 * @param int $userId
486 */
487 public static function purge( $wikiId, $userId ) {
488 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
489 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
490 $cache->delete( $key );
491 }
492
493 /**
494 * @since 1.27
495 * @param WANObjectCache $cache
496 * @return string
497 */
498 protected function getCacheKey( WANObjectCache $cache ) {
499 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
500
501 return $cache->makeGlobalKey( 'user', 'id', $lbFactory->getLocalDomainID(), $this->mId );
502 }
503
504 /**
505 * @param WANObjectCache $cache
506 * @return string[]
507 * @since 1.28
508 */
509 public function getMutableCacheKeys( WANObjectCache $cache ) {
510 $id = $this->getId();
511
512 return $id ? [ $this->getCacheKey( $cache ) ] : [];
513 }
514
515 /**
516 * Load user data from shared cache, given mId has already been set.
517 *
518 * @return bool True
519 * @since 1.25
520 */
521 protected function loadFromCache() {
522 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
523 $data = $cache->getWithSetCallback(
524 $this->getCacheKey( $cache ),
525 $cache::TTL_HOUR,
526 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
527 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
528 wfDebug( "User: cache miss for user {$this->mId}\n" );
529
530 $this->loadFromDatabase( self::READ_NORMAL );
531 $this->loadGroups();
532 $this->loadOptions();
533
534 $data = [];
535 foreach ( self::$mCacheVars as $name ) {
536 $data[$name] = $this->$name;
537 }
538
539 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX, $this->mTouched ), $ttl );
540
541 // if a user group membership is about to expire, the cache needs to
542 // expire at that time (T163691)
543 foreach ( $this->mGroupMemberships as $ugm ) {
544 if ( $ugm->getExpiry() ) {
545 $secondsUntilExpiry = wfTimestamp( TS_UNIX, $ugm->getExpiry() ) - time();
546 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
547 $ttl = $secondsUntilExpiry;
548 }
549 }
550 }
551
552 return $data;
553 },
554 [ 'pcTTL' => $cache::TTL_PROC_LONG, 'version' => self::VERSION ]
555 );
556
557 // Restore from cache
558 foreach ( self::$mCacheVars as $name ) {
559 $this->$name = $data[$name];
560 }
561
562 return true;
563 }
564
565 /** @name newFrom*() static factory methods */
566 // @{
567
568 /**
569 * Static factory method for creation from username.
570 *
571 * This is slightly less efficient than newFromId(), so use newFromId() if
572 * you have both an ID and a name handy.
573 *
574 * @param string $name Username, validated by Title::newFromText()
575 * @param string|bool $validate Validate username. Takes the same parameters as
576 * User::getCanonicalName(), except that true is accepted as an alias
577 * for 'valid', for BC.
578 *
579 * @return User|bool User object, or false if the username is invalid
580 * (e.g. if it contains illegal characters or is an IP address). If the
581 * username is not present in the database, the result will be a user object
582 * with a name, zero user ID and default settings.
583 */
584 public static function newFromName( $name, $validate = 'valid' ) {
585 if ( $validate === true ) {
586 $validate = 'valid';
587 }
588 $name = self::getCanonicalName( $name, $validate );
589 if ( $name === false ) {
590 return false;
591 }
592
593 // Create unloaded user object
594 $u = new User;
595 $u->mName = $name;
596 $u->mFrom = 'name';
597 $u->setItemLoaded( 'name' );
598
599 return $u;
600 }
601
602 /**
603 * Static factory method for creation from a given user ID.
604 *
605 * @param int $id Valid user ID
606 * @return User The corresponding User object
607 */
608 public static function newFromId( $id ) {
609 $u = new User;
610 $u->mId = $id;
611 $u->mFrom = 'id';
612 $u->setItemLoaded( 'id' );
613 return $u;
614 }
615
616 /**
617 * Static factory method for creation from a given actor ID.
618 *
619 * @since 1.31
620 * @param int $id Valid actor ID
621 * @return User The corresponding User object
622 */
623 public static function newFromActorId( $id ) {
624 global $wgActorTableSchemaMigrationStage;
625
626 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
627 // but it does little harm and might be needed for write callers loading a User.
628 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW ) ) {
629 throw new BadMethodCallException(
630 'Cannot use ' . __METHOD__
631 . ' when $wgActorTableSchemaMigrationStage lacks SCHEMA_COMPAT_NEW'
632 );
633 }
634
635 $u = new User;
636 $u->mActorId = $id;
637 $u->mFrom = 'actor';
638 $u->setItemLoaded( 'actor' );
639 return $u;
640 }
641
642 /**
643 * Returns a User object corresponding to the given UserIdentity.
644 *
645 * @since 1.32
646 *
647 * @param UserIdentity $identity
648 *
649 * @return User
650 */
651 public static function newFromIdentity( UserIdentity $identity ) {
652 if ( $identity instanceof User ) {
653 return $identity;
654 }
655
656 return self::newFromAnyId(
657 $identity->getId() === 0 ? null : $identity->getId(),
658 $identity->getName() === '' ? null : $identity->getName(),
659 $identity->getActorId() === 0 ? null : $identity->getActorId()
660 );
661 }
662
663 /**
664 * Static factory method for creation from an ID, name, and/or actor ID
665 *
666 * This does not check that the ID, name, and actor ID all correspond to
667 * the same user.
668 *
669 * @since 1.31
670 * @param int|null $userId User ID, if known
671 * @param string|null $userName User name, if known
672 * @param int|null $actorId Actor ID, if known
673 * @return User
674 */
675 public static function newFromAnyId( $userId, $userName, $actorId ) {
676 global $wgActorTableSchemaMigrationStage;
677
678 $user = new User;
679 $user->mFrom = 'defaults';
680
681 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
682 // but it does little harm and might be needed for write callers loading a User.
683 if ( ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW ) && $actorId !== null ) {
684 $user->mActorId = (int)$actorId;
685 if ( $user->mActorId !== 0 ) {
686 $user->mFrom = 'actor';
687 }
688 $user->setItemLoaded( 'actor' );
689 }
690
691 if ( $userName !== null && $userName !== '' ) {
692 $user->mName = $userName;
693 $user->mFrom = 'name';
694 $user->setItemLoaded( 'name' );
695 }
696
697 if ( $userId !== null ) {
698 $user->mId = (int)$userId;
699 if ( $user->mId !== 0 ) {
700 $user->mFrom = 'id';
701 }
702 $user->setItemLoaded( 'id' );
703 }
704
705 if ( $user->mFrom === 'defaults' ) {
706 throw new InvalidArgumentException(
707 'Cannot create a user with no name, no ID, and no actor ID'
708 );
709 }
710
711 return $user;
712 }
713
714 /**
715 * Factory method to fetch whichever user has a given email confirmation code.
716 * This code is generated when an account is created or its e-mail address
717 * has changed.
718 *
719 * If the code is invalid or has expired, returns NULL.
720 *
721 * @param string $code Confirmation code
722 * @param int $flags User::READ_* bitfield
723 * @return User|null
724 */
725 public static function newFromConfirmationCode( $code, $flags = 0 ) {
726 $db = ( $flags & self::READ_LATEST ) == self::READ_LATEST
727 ? wfGetDB( DB_MASTER )
728 : wfGetDB( DB_REPLICA );
729
730 $id = $db->selectField(
731 'user',
732 'user_id',
733 [
734 'user_email_token' => md5( $code ),
735 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
736 ]
737 );
738
739 return $id ? self::newFromId( $id ) : null;
740 }
741
742 /**
743 * Create a new user object using data from session. If the login
744 * credentials are invalid, the result is an anonymous user.
745 *
746 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
747 * @return User
748 */
749 public static function newFromSession( WebRequest $request = null ) {
750 $user = new User;
751 $user->mFrom = 'session';
752 $user->mRequest = $request;
753 return $user;
754 }
755
756 /**
757 * Create a new user object from a user row.
758 * The row should have the following fields from the user table in it:
759 * - either user_name or user_id to load further data if needed (or both)
760 * - user_real_name
761 * - all other fields (email, etc.)
762 * It is useless to provide the remaining fields if either user_id,
763 * user_name and user_real_name are not provided because the whole row
764 * will be loaded once more from the database when accessing them.
765 *
766 * @param stdClass $row A row from the user table
767 * @param array|null $data Further data to load into the object
768 * (see User::loadFromRow for valid keys)
769 * @return User
770 */
771 public static function newFromRow( $row, $data = null ) {
772 $user = new User;
773 $user->loadFromRow( $row, $data );
774 return $user;
775 }
776
777 /**
778 * Static factory method for creation of a "system" user from username.
779 *
780 * A "system" user is an account that's used to attribute logged actions
781 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
782 * might include the 'Maintenance script' or 'Conversion script' accounts
783 * used by various scripts in the maintenance/ directory or accounts such
784 * as 'MediaWiki message delivery' used by the MassMessage extension.
785 *
786 * This can optionally create the user if it doesn't exist, and "steal" the
787 * account if it does exist.
788 *
789 * "Stealing" an existing user is intended to make it impossible for normal
790 * authentication processes to use the account, effectively disabling the
791 * account for normal use:
792 * - Email is invalidated, to prevent account recovery by emailing a
793 * temporary password and to disassociate the account from the existing
794 * human.
795 * - The token is set to a magic invalid value, to kill existing sessions
796 * and to prevent $this->setToken() calls from resetting the token to a
797 * valid value.
798 * - SessionManager is instructed to prevent new sessions for the user, to
799 * do things like deauthorizing OAuth consumers.
800 * - AuthManager is instructed to revoke access, to invalidate or remove
801 * passwords and other credentials.
802 *
803 * @param string $name Username
804 * @param array $options Options are:
805 * - validate: As for User::getCanonicalName(), default 'valid'
806 * - create: Whether to create the user if it doesn't already exist, default true
807 * - steal: Whether to "disable" the account for normal use if it already
808 * exists, default false
809 * @return User|null
810 * @since 1.27
811 */
812 public static function newSystemUser( $name, $options = [] ) {
813 $options += [
814 'validate' => 'valid',
815 'create' => true,
816 'steal' => false,
817 ];
818
819 $name = self::getCanonicalName( $name, $options['validate'] );
820 if ( $name === false ) {
821 return null;
822 }
823
824 $dbr = wfGetDB( DB_REPLICA );
825 $userQuery = self::getQueryInfo();
826 $row = $dbr->selectRow(
827 $userQuery['tables'],
828 $userQuery['fields'],
829 [ 'user_name' => $name ],
830 __METHOD__,
831 [],
832 $userQuery['joins']
833 );
834 if ( !$row ) {
835 // Try the master database...
836 $dbw = wfGetDB( DB_MASTER );
837 $row = $dbw->selectRow(
838 $userQuery['tables'],
839 $userQuery['fields'],
840 [ 'user_name' => $name ],
841 __METHOD__,
842 [],
843 $userQuery['joins']
844 );
845 }
846
847 if ( !$row ) {
848 // No user. Create it?
849 return $options['create']
850 ? self::createNew( $name, [ 'token' => self::INVALID_TOKEN ] )
851 : null;
852 }
853
854 $user = self::newFromRow( $row );
855
856 // A user is considered to exist as a non-system user if it can
857 // authenticate, or has an email set, or has a non-invalid token.
858 if ( $user->mEmail || $user->mToken !== self::INVALID_TOKEN ||
859 AuthManager::singleton()->userCanAuthenticate( $name )
860 ) {
861 // User exists. Steal it?
862 if ( !$options['steal'] ) {
863 return null;
864 }
865
866 AuthManager::singleton()->revokeAccessForUser( $name );
867
868 $user->invalidateEmail();
869 $user->mToken = self::INVALID_TOKEN;
870 $user->saveSettings();
871 SessionManager::singleton()->preventSessionsForUser( $user->getName() );
872 }
873
874 return $user;
875 }
876
877 // @}
878
879 /**
880 * Get the username corresponding to a given user ID
881 * @param int $id User ID
882 * @return string|bool The corresponding username
883 */
884 public static function whoIs( $id ) {
885 return UserCache::singleton()->getProp( $id, 'name' );
886 }
887
888 /**
889 * Get the real name of a user given their user ID
890 *
891 * @param int $id User ID
892 * @return string|bool The corresponding user's real name
893 */
894 public static function whoIsReal( $id ) {
895 return UserCache::singleton()->getProp( $id, 'real_name' );
896 }
897
898 /**
899 * Get database id given a user name
900 * @param string $name Username
901 * @param int $flags User::READ_* constant bitfield
902 * @return int|null The corresponding user's ID, or null if user is nonexistent
903 */
904 public static function idFromName( $name, $flags = self::READ_NORMAL ) {
905 // Don't explode on self::$idCacheByName[$name] if $name is not a string but e.g. a User object
906 $name = (string)$name;
907 $nt = Title::makeTitleSafe( NS_USER, $name );
908 if ( is_null( $nt ) ) {
909 // Illegal name
910 return null;
911 }
912
913 if ( !( $flags & self::READ_LATEST ) && array_key_exists( $name, self::$idCacheByName ) ) {
914 return self::$idCacheByName[$name];
915 }
916
917 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
918 $db = wfGetDB( $index );
919
920 $s = $db->selectRow(
921 'user',
922 [ 'user_id' ],
923 [ 'user_name' => $nt->getText() ],
924 __METHOD__,
925 $options
926 );
927
928 if ( $s === false ) {
929 $result = null;
930 } else {
931 $result = (int)$s->user_id;
932 }
933
934 self::$idCacheByName[$name] = $result;
935
936 if ( count( self::$idCacheByName ) > 1000 ) {
937 self::$idCacheByName = [];
938 }
939
940 return $result;
941 }
942
943 /**
944 * Reset the cache used in idFromName(). For use in tests.
945 */
946 public static function resetIdByNameCache() {
947 self::$idCacheByName = [];
948 }
949
950 /**
951 * Does the string match an anonymous IP address?
952 *
953 * This function exists for username validation, in order to reject
954 * usernames which are similar in form to IP addresses. Strings such
955 * as 300.300.300.300 will return true because it looks like an IP
956 * address, despite not being strictly valid.
957 *
958 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
959 * address because the usemod software would "cloak" anonymous IP
960 * addresses like this, if we allowed accounts like this to be created
961 * new users could get the old edits of these anonymous users.
962 *
963 * @param string $name Name to match
964 * @return bool
965 */
966 public static function isIP( $name ) {
967 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
968 || IP::isIPv6( $name );
969 }
970
971 /**
972 * Is the user an IP range?
973 *
974 * @since 1.30
975 * @return bool
976 */
977 public function isIPRange() {
978 return IP::isValidRange( $this->mName );
979 }
980
981 /**
982 * Is the input a valid username?
983 *
984 * Checks if the input is a valid username, we don't want an empty string,
985 * an IP address, anything that contains slashes (would mess up subpages),
986 * is longer than the maximum allowed username size or doesn't begin with
987 * a capital letter.
988 *
989 * @param string $name Name to match
990 * @return bool
991 */
992 public static function isValidUserName( $name ) {
993 global $wgMaxNameChars;
994
995 if ( $name == ''
996 || self::isIP( $name )
997 || strpos( $name, '/' ) !== false
998 || strlen( $name ) > $wgMaxNameChars
999 || $name != MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $name )
1000 ) {
1001 return false;
1002 }
1003
1004 // Ensure that the name can't be misresolved as a different title,
1005 // such as with extra namespace keys at the start.
1006 $parsed = Title::newFromText( $name );
1007 if ( is_null( $parsed )
1008 || $parsed->getNamespace()
1009 || strcmp( $name, $parsed->getPrefixedText() ) ) {
1010 return false;
1011 }
1012
1013 // Check an additional blacklist of troublemaker characters.
1014 // Should these be merged into the title char list?
1015 $unicodeBlacklist = '/[' .
1016 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
1017 '\x{00a0}' . # non-breaking space
1018 '\x{2000}-\x{200f}' . # various whitespace
1019 '\x{2028}-\x{202f}' . # breaks and control chars
1020 '\x{3000}' . # ideographic space
1021 '\x{e000}-\x{f8ff}' . # private use
1022 ']/u';
1023 if ( preg_match( $unicodeBlacklist, $name ) ) {
1024 return false;
1025 }
1026
1027 return true;
1028 }
1029
1030 /**
1031 * Usernames which fail to pass this function will be blocked
1032 * from user login and new account registrations, but may be used
1033 * internally by batch processes.
1034 *
1035 * If an account already exists in this form, login will be blocked
1036 * by a failure to pass this function.
1037 *
1038 * @param string $name Name to match
1039 * @return bool
1040 */
1041 public static function isUsableName( $name ) {
1042 global $wgReservedUsernames;
1043 // Must be a valid username, obviously ;)
1044 if ( !self::isValidUserName( $name ) ) {
1045 return false;
1046 }
1047
1048 static $reservedUsernames = false;
1049 if ( !$reservedUsernames ) {
1050 $reservedUsernames = $wgReservedUsernames;
1051 Hooks::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
1052 }
1053
1054 // Certain names may be reserved for batch processes.
1055 foreach ( $reservedUsernames as $reserved ) {
1056 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
1057 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->plain();
1058 }
1059 if ( $reserved == $name ) {
1060 return false;
1061 }
1062 }
1063 return true;
1064 }
1065
1066 /**
1067 * Return the users who are members of the given group(s). In case of multiple groups,
1068 * users who are members of at least one of them are returned.
1069 *
1070 * @param string|array $groups A single group name or an array of group names
1071 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
1072 * records; larger values are ignored.
1073 * @param int|null $after ID the user to start after
1074 * @return UserArrayFromResult
1075 */
1076 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
1077 if ( $groups === [] ) {
1078 return UserArrayFromResult::newFromIDs( [] );
1079 }
1080
1081 $groups = array_unique( (array)$groups );
1082 $limit = min( 5000, $limit );
1083
1084 $conds = [ 'ug_group' => $groups ];
1085 if ( $after !== null ) {
1086 $conds[] = 'ug_user > ' . (int)$after;
1087 }
1088
1089 $dbr = wfGetDB( DB_REPLICA );
1090 $ids = $dbr->selectFieldValues(
1091 'user_groups',
1092 'ug_user',
1093 $conds,
1094 __METHOD__,
1095 [
1096 'DISTINCT' => true,
1097 'ORDER BY' => 'ug_user',
1098 'LIMIT' => $limit,
1099 ]
1100 ) ?: [];
1101 return UserArray::newFromIDs( $ids );
1102 }
1103
1104 /**
1105 * Usernames which fail to pass this function will be blocked
1106 * from new account registrations, but may be used internally
1107 * either by batch processes or by user accounts which have
1108 * already been created.
1109 *
1110 * Additional blacklisting may be added here rather than in
1111 * isValidUserName() to avoid disrupting existing accounts.
1112 *
1113 * @param string $name String to match
1114 * @return bool
1115 */
1116 public static function isCreatableName( $name ) {
1117 global $wgInvalidUsernameCharacters;
1118
1119 // Ensure that the username isn't longer than 235 bytes, so that
1120 // (at least for the builtin skins) user javascript and css files
1121 // will work. (T25080)
1122 if ( strlen( $name ) > 235 ) {
1123 wfDebugLog( 'username', __METHOD__ .
1124 ": '$name' invalid due to length" );
1125 return false;
1126 }
1127
1128 // Preg yells if you try to give it an empty string
1129 if ( $wgInvalidUsernameCharacters !== '' &&
1130 preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name )
1131 ) {
1132 wfDebugLog( 'username', __METHOD__ .
1133 ": '$name' invalid due to wgInvalidUsernameCharacters" );
1134 return false;
1135 }
1136
1137 return self::isUsableName( $name );
1138 }
1139
1140 /**
1141 * Is the input a valid password for this user?
1142 *
1143 * @param string $password Desired password
1144 * @return bool
1145 */
1146 public function isValidPassword( $password ) {
1147 // simple boolean wrapper for checkPasswordValidity
1148 return $this->checkPasswordValidity( $password )->isGood();
1149 }
1150
1151 /**
1152 * Given unvalidated password input, return error message on failure.
1153 *
1154 * @param string $password Desired password
1155 * @return bool|string|array True on success, string or array of error message on failure
1156 * @deprecated since 1.33, use checkPasswordValidity
1157 */
1158 public function getPasswordValidity( $password ) {
1159 wfDeprecated( __METHOD__, '1.33' );
1160
1161 $result = $this->checkPasswordValidity( $password );
1162 if ( $result->isGood() ) {
1163 return true;
1164 }
1165
1166 $messages = [];
1167 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
1168 $messages[] = $error['message'];
1169 }
1170 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
1171 $messages[] = $warning['message'];
1172 }
1173 if ( count( $messages ) === 1 ) {
1174 return $messages[0];
1175 }
1176
1177 return $messages;
1178 }
1179
1180 /**
1181 * Check if this is a valid password for this user
1182 *
1183 * Returns a Status object with a set of messages describing
1184 * problems with the password. If the return status is fatal,
1185 * the action should be refused and the password should not be
1186 * checked at all (this is mainly meant for DoS mitigation).
1187 * If the return value is OK but not good, the password can be checked,
1188 * but the user should not be able to set their password to this.
1189 * The value of the returned Status object will be an array which
1190 * can have the following fields:
1191 * - forceChange (bool): if set to true, the user should not be
1192 * allowed to log with this password unless they change it during
1193 * the login process (see ResetPasswordSecondaryAuthenticationProvider).
1194 * - suggestChangeOnLogin (bool): if set to true, the user should be prompted for
1195 * a password change on login.
1196 *
1197 * @param string $password Desired password
1198 * @return Status
1199 * @since 1.23
1200 */
1201 public function checkPasswordValidity( $password ) {
1202 global $wgPasswordPolicy;
1203
1204 $upp = new UserPasswordPolicy(
1205 $wgPasswordPolicy['policies'],
1206 $wgPasswordPolicy['checks']
1207 );
1208
1209 $status = Status::newGood( [] );
1210 $result = false; // init $result to false for the internal checks
1211
1212 if ( !Hooks::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1213 $status->error( $result );
1214 return $status;
1215 }
1216
1217 if ( $result === false ) {
1218 $status->merge( $upp->checkUserPassword( $this, $password ), true );
1219 return $status;
1220 }
1221
1222 if ( $result === true ) {
1223 return $status;
1224 }
1225
1226 $status->error( $result );
1227 return $status; // the isValidPassword hook set a string $result and returned true
1228 }
1229
1230 /**
1231 * Given unvalidated user input, return a canonical username, or false if
1232 * the username is invalid.
1233 * @param string $name User input
1234 * @param string|bool $validate Type of validation to use:
1235 * - false No validation
1236 * - 'valid' Valid for batch processes
1237 * - 'usable' Valid for batch processes and login
1238 * - 'creatable' Valid for batch processes, login and account creation
1239 *
1240 * @throws InvalidArgumentException
1241 * @return bool|string
1242 */
1243 public static function getCanonicalName( $name, $validate = 'valid' ) {
1244 // Force usernames to capital
1245 $name = MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $name );
1246
1247 # Reject names containing '#'; these will be cleaned up
1248 # with title normalisation, but then it's too late to
1249 # check elsewhere
1250 if ( strpos( $name, '#' ) !== false ) {
1251 return false;
1252 }
1253
1254 // Clean up name according to title rules,
1255 // but only when validation is requested (T14654)
1256 $t = ( $validate !== false ) ?
1257 Title::newFromText( $name, NS_USER ) : Title::makeTitle( NS_USER, $name );
1258 // Check for invalid titles
1259 if ( is_null( $t ) || $t->getNamespace() !== NS_USER || $t->isExternal() ) {
1260 return false;
1261 }
1262
1263 $name = $t->getText();
1264
1265 switch ( $validate ) {
1266 case false:
1267 break;
1268 case 'valid':
1269 if ( !self::isValidUserName( $name ) ) {
1270 $name = false;
1271 }
1272 break;
1273 case 'usable':
1274 if ( !self::isUsableName( $name ) ) {
1275 $name = false;
1276 }
1277 break;
1278 case 'creatable':
1279 if ( !self::isCreatableName( $name ) ) {
1280 $name = false;
1281 }
1282 break;
1283 default:
1284 throw new InvalidArgumentException(
1285 'Invalid parameter value for $validate in ' . __METHOD__ );
1286 }
1287 return $name;
1288 }
1289
1290 /**
1291 * Return a random password.
1292 *
1293 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1294 * @return string New random password
1295 */
1296 public static function randomPassword() {
1297 global $wgMinimalPasswordLength;
1298 return PasswordFactory::generateRandomPasswordString( $wgMinimalPasswordLength );
1299 }
1300
1301 /**
1302 * Set cached properties to default.
1303 *
1304 * @note This no longer clears uncached lazy-initialised properties;
1305 * the constructor does that instead.
1306 *
1307 * @param string|bool $name
1308 */
1309 public function loadDefaults( $name = false ) {
1310 $this->mId = 0;
1311 $this->mName = $name;
1312 $this->mActorId = null;
1313 $this->mRealName = '';
1314 $this->mEmail = '';
1315 $this->mOptionOverrides = null;
1316 $this->mOptionsLoaded = false;
1317
1318 $loggedOut = $this->mRequest && !defined( 'MW_NO_SESSION' )
1319 ? $this->mRequest->getSession()->getLoggedOutTimestamp() : 0;
1320 if ( $loggedOut !== 0 ) {
1321 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
1322 } else {
1323 $this->mTouched = '1'; # Allow any pages to be cached
1324 }
1325
1326 $this->mToken = null; // Don't run cryptographic functions till we need a token
1327 $this->mEmailAuthenticated = null;
1328 $this->mEmailToken = '';
1329 $this->mEmailTokenExpires = null;
1330 $this->mRegistration = wfTimestamp( TS_MW );
1331 $this->mGroupMemberships = [];
1332
1333 Hooks::run( 'UserLoadDefaults', [ $this, $name ] );
1334 }
1335
1336 /**
1337 * Return whether an item has been loaded.
1338 *
1339 * @param string $item Item to check. Current possibilities:
1340 * - id
1341 * - name
1342 * - realname
1343 * @param string $all 'all' to check if the whole object has been loaded
1344 * or any other string to check if only the item is available (e.g.
1345 * for optimisation)
1346 * @return bool
1347 */
1348 public function isItemLoaded( $item, $all = 'all' ) {
1349 return ( $this->mLoadedItems === true && $all === 'all' ) ||
1350 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1351 }
1352
1353 /**
1354 * Set that an item has been loaded
1355 *
1356 * @param string $item
1357 */
1358 protected function setItemLoaded( $item ) {
1359 if ( is_array( $this->mLoadedItems ) ) {
1360 $this->mLoadedItems[$item] = true;
1361 }
1362 }
1363
1364 /**
1365 * Load user data from the session.
1366 *
1367 * @return bool True if the user is logged in, false otherwise.
1368 */
1369 private function loadFromSession() {
1370 // Deprecated hook
1371 $result = null;
1372 Hooks::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1373 if ( $result !== null ) {
1374 return $result;
1375 }
1376
1377 // MediaWiki\Session\Session already did the necessary authentication of the user
1378 // returned here, so just use it if applicable.
1379 $session = $this->getRequest()->getSession();
1380 $user = $session->getUser();
1381 if ( $user->isLoggedIn() ) {
1382 $this->loadFromUserObject( $user );
1383 if ( $user->isBlocked() ) {
1384 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1385 // every session load, because an autoblocked editor might not edit again from the same
1386 // IP address after being blocked.
1387 $this->trackBlockWithCookie();
1388 }
1389
1390 // Other code expects these to be set in the session, so set them.
1391 $session->set( 'wsUserID', $this->getId() );
1392 $session->set( 'wsUserName', $this->getName() );
1393 $session->set( 'wsToken', $this->getToken() );
1394
1395 return true;
1396 }
1397
1398 return false;
1399 }
1400
1401 /**
1402 * Set the 'BlockID' cookie depending on block type and user authentication status.
1403 */
1404 public function trackBlockWithCookie() {
1405 $block = $this->getBlock();
1406 if ( $block && $this->getRequest()->getCookie( 'BlockID' ) === null ) {
1407 $config = RequestContext::getMain()->getConfig();
1408 $shouldSetCookie = false;
1409
1410 if ( $this->isAnon() && $config->get( 'CookieSetOnIpBlock' ) ) {
1411 // If user is logged-out, set a cookie to track the Block
1412 $shouldSetCookie = in_array( $block->getType(), [
1413 Block::TYPE_IP, Block::TYPE_RANGE
1414 ] );
1415 if ( $shouldSetCookie ) {
1416 $block->setCookie( $this->getRequest()->response() );
1417
1418 // temporary measure the use of cookies on ip blocks
1419 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
1420 $stats->increment( 'block.ipblock.setCookie.success' );
1421 }
1422 } elseif ( $this->isLoggedIn() && $config->get( 'CookieSetOnAutoblock' ) ) {
1423 $shouldSetCookie = $block->getType() === Block::TYPE_USER && $block->isAutoblocking();
1424 if ( $shouldSetCookie ) {
1425 $block->setCookie( $this->getRequest()->response() );
1426 }
1427 }
1428 }
1429 }
1430
1431 /**
1432 * Load user and user_group data from the database.
1433 * $this->mId must be set, this is how the user is identified.
1434 *
1435 * @param int $flags User::READ_* constant bitfield
1436 * @return bool True if the user exists, false if the user is anonymous
1437 */
1438 public function loadFromDatabase( $flags = self::READ_LATEST ) {
1439 // Paranoia
1440 $this->mId = intval( $this->mId );
1441
1442 if ( !$this->mId ) {
1443 // Anonymous users are not in the database
1444 $this->loadDefaults();
1445 return false;
1446 }
1447
1448 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
1449 $db = wfGetDB( $index );
1450
1451 $userQuery = self::getQueryInfo();
1452 $s = $db->selectRow(
1453 $userQuery['tables'],
1454 $userQuery['fields'],
1455 [ 'user_id' => $this->mId ],
1456 __METHOD__,
1457 $options,
1458 $userQuery['joins']
1459 );
1460
1461 $this->queryFlagsUsed = $flags;
1462 Hooks::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1463
1464 if ( $s !== false ) {
1465 // Initialise user table data
1466 $this->loadFromRow( $s );
1467 $this->mGroupMemberships = null; // deferred
1468 $this->getEditCount(); // revalidation for nulls
1469 return true;
1470 }
1471
1472 // Invalid user_id
1473 $this->mId = 0;
1474 $this->loadDefaults();
1475
1476 return false;
1477 }
1478
1479 /**
1480 * Initialize this object from a row from the user table.
1481 *
1482 * @param stdClass $row Row from the user table to load.
1483 * @param array|null $data Further user data to load into the object
1484 *
1485 * user_groups Array of arrays or stdClass result rows out of the user_groups
1486 * table. Previously you were supposed to pass an array of strings
1487 * here, but we also need expiry info nowadays, so an array of
1488 * strings is ignored.
1489 * user_properties Array with properties out of the user_properties table
1490 */
1491 protected function loadFromRow( $row, $data = null ) {
1492 global $wgActorTableSchemaMigrationStage;
1493
1494 if ( !is_object( $row ) ) {
1495 throw new InvalidArgumentException( '$row must be an object' );
1496 }
1497
1498 $all = true;
1499
1500 $this->mGroupMemberships = null; // deferred
1501
1502 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
1503 // but it does little harm and might be needed for write callers loading a User.
1504 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW ) {
1505 if ( isset( $row->actor_id ) ) {
1506 $this->mActorId = (int)$row->actor_id;
1507 if ( $this->mActorId !== 0 ) {
1508 $this->mFrom = 'actor';
1509 }
1510 $this->setItemLoaded( 'actor' );
1511 } else {
1512 $all = false;
1513 }
1514 }
1515
1516 if ( isset( $row->user_name ) && $row->user_name !== '' ) {
1517 $this->mName = $row->user_name;
1518 $this->mFrom = 'name';
1519 $this->setItemLoaded( 'name' );
1520 } else {
1521 $all = false;
1522 }
1523
1524 if ( isset( $row->user_real_name ) ) {
1525 $this->mRealName = $row->user_real_name;
1526 $this->setItemLoaded( 'realname' );
1527 } else {
1528 $all = false;
1529 }
1530
1531 if ( isset( $row->user_id ) ) {
1532 $this->mId = intval( $row->user_id );
1533 if ( $this->mId !== 0 ) {
1534 $this->mFrom = 'id';
1535 }
1536 $this->setItemLoaded( 'id' );
1537 } else {
1538 $all = false;
1539 }
1540
1541 if ( isset( $row->user_id ) && isset( $row->user_name ) && $row->user_name !== '' ) {
1542 self::$idCacheByName[$row->user_name] = $row->user_id;
1543 }
1544
1545 if ( isset( $row->user_editcount ) ) {
1546 $this->mEditCount = $row->user_editcount;
1547 } else {
1548 $all = false;
1549 }
1550
1551 if ( isset( $row->user_touched ) ) {
1552 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1553 } else {
1554 $all = false;
1555 }
1556
1557 if ( isset( $row->user_token ) ) {
1558 // The definition for the column is binary(32), so trim the NULs
1559 // that appends. The previous definition was char(32), so trim
1560 // spaces too.
1561 $this->mToken = rtrim( $row->user_token, " \0" );
1562 if ( $this->mToken === '' ) {
1563 $this->mToken = null;
1564 }
1565 } else {
1566 $all = false;
1567 }
1568
1569 if ( isset( $row->user_email ) ) {
1570 $this->mEmail = $row->user_email;
1571 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1572 $this->mEmailToken = $row->user_email_token;
1573 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1574 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1575 } else {
1576 $all = false;
1577 }
1578
1579 if ( $all ) {
1580 $this->mLoadedItems = true;
1581 }
1582
1583 if ( is_array( $data ) ) {
1584 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1585 if ( $data['user_groups'] === [] ) {
1586 $this->mGroupMemberships = [];
1587 } else {
1588 $firstGroup = reset( $data['user_groups'] );
1589 if ( is_array( $firstGroup ) || is_object( $firstGroup ) ) {
1590 $this->mGroupMemberships = [];
1591 foreach ( $data['user_groups'] as $row ) {
1592 $ugm = UserGroupMembership::newFromRow( (object)$row );
1593 $this->mGroupMemberships[$ugm->getGroup()] = $ugm;
1594 }
1595 }
1596 }
1597 }
1598 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1599 $this->loadOptions( $data['user_properties'] );
1600 }
1601 }
1602 }
1603
1604 /**
1605 * Load the data for this user object from another user object.
1606 *
1607 * @param User $user
1608 */
1609 protected function loadFromUserObject( $user ) {
1610 $user->load();
1611 foreach ( self::$mCacheVars as $var ) {
1612 $this->$var = $user->$var;
1613 }
1614 }
1615
1616 /**
1617 * Load the groups from the database if they aren't already loaded.
1618 */
1619 private function loadGroups() {
1620 if ( is_null( $this->mGroupMemberships ) ) {
1621 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
1622 ? wfGetDB( DB_MASTER )
1623 : wfGetDB( DB_REPLICA );
1624 $this->mGroupMemberships = UserGroupMembership::getMembershipsForUser(
1625 $this->mId, $db );
1626 }
1627 }
1628
1629 /**
1630 * Add the user to the group if he/she meets given criteria.
1631 *
1632 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1633 * possible to remove manually via Special:UserRights. In such case it
1634 * will not be re-added automatically. The user will also not lose the
1635 * group if they no longer meet the criteria.
1636 *
1637 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1638 *
1639 * @return array Array of groups the user has been promoted to.
1640 *
1641 * @see $wgAutopromoteOnce
1642 */
1643 public function addAutopromoteOnceGroups( $event ) {
1644 global $wgAutopromoteOnceLogInRC;
1645
1646 if ( wfReadOnly() || !$this->getId() ) {
1647 return [];
1648 }
1649
1650 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1651 if ( $toPromote === [] ) {
1652 return [];
1653 }
1654
1655 if ( !$this->checkAndSetTouched() ) {
1656 return []; // raced out (bug T48834)
1657 }
1658
1659 $oldGroups = $this->getGroups(); // previous groups
1660 $oldUGMs = $this->getGroupMemberships();
1661 foreach ( $toPromote as $group ) {
1662 $this->addGroup( $group );
1663 }
1664 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1665 $newUGMs = $this->getGroupMemberships();
1666
1667 // update groups in external authentication database
1668 Hooks::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false, $oldUGMs, $newUGMs ] );
1669
1670 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1671 $logEntry->setPerformer( $this );
1672 $logEntry->setTarget( $this->getUserPage() );
1673 $logEntry->setParameters( [
1674 '4::oldgroups' => $oldGroups,
1675 '5::newgroups' => $newGroups,
1676 ] );
1677 $logid = $logEntry->insert();
1678 if ( $wgAutopromoteOnceLogInRC ) {
1679 $logEntry->publish( $logid );
1680 }
1681
1682 return $toPromote;
1683 }
1684
1685 /**
1686 * Builds update conditions. Additional conditions may be added to $conditions to
1687 * protected against race conditions using a compare-and-set (CAS) mechanism
1688 * based on comparing $this->mTouched with the user_touched field.
1689 *
1690 * @param Database $db
1691 * @param array $conditions WHERE conditions for use with Database::update
1692 * @return array WHERE conditions for use with Database::update
1693 */
1694 protected function makeUpdateConditions( Database $db, array $conditions ) {
1695 if ( $this->mTouched ) {
1696 // CAS check: only update if the row wasn't changed sicne it was loaded.
1697 $conditions['user_touched'] = $db->timestamp( $this->mTouched );
1698 }
1699
1700 return $conditions;
1701 }
1702
1703 /**
1704 * Bump user_touched if it didn't change since this object was loaded
1705 *
1706 * On success, the mTouched field is updated.
1707 * The user serialization cache is always cleared.
1708 *
1709 * @return bool Whether user_touched was actually updated
1710 * @since 1.26
1711 */
1712 protected function checkAndSetTouched() {
1713 $this->load();
1714
1715 if ( !$this->mId ) {
1716 return false; // anon
1717 }
1718
1719 // Get a new user_touched that is higher than the old one
1720 $newTouched = $this->newTouchedTimestamp();
1721
1722 $dbw = wfGetDB( DB_MASTER );
1723 $dbw->update( 'user',
1724 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1725 $this->makeUpdateConditions( $dbw, [
1726 'user_id' => $this->mId,
1727 ] ),
1728 __METHOD__
1729 );
1730 $success = ( $dbw->affectedRows() > 0 );
1731
1732 if ( $success ) {
1733 $this->mTouched = $newTouched;
1734 $this->clearSharedCache();
1735 } else {
1736 // Clears on failure too since that is desired if the cache is stale
1737 $this->clearSharedCache( 'refresh' );
1738 }
1739
1740 return $success;
1741 }
1742
1743 /**
1744 * Clear various cached data stored in this object. The cache of the user table
1745 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1746 *
1747 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1748 * given source. May be "name", "id", "actor", "defaults", "session", or false for no reload.
1749 */
1750 public function clearInstanceCache( $reloadFrom = false ) {
1751 $this->mNewtalk = -1;
1752 $this->mDatePreference = null;
1753 $this->mBlockedby = -1; # Unset
1754 $this->mHash = false;
1755 $this->mRights = null;
1756 $this->mEffectiveGroups = null;
1757 $this->mImplicitGroups = null;
1758 $this->mGroupMemberships = null;
1759 $this->mOptions = null;
1760 $this->mOptionsLoaded = false;
1761 $this->mEditCount = null;
1762
1763 if ( $reloadFrom ) {
1764 $this->mLoadedItems = [];
1765 $this->mFrom = $reloadFrom;
1766 }
1767 }
1768
1769 /**
1770 * Combine the language default options with any site-specific options
1771 * and add the default language variants.
1772 *
1773 * @return array Array of String options
1774 */
1775 public static function getDefaultOptions() {
1776 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgDefaultSkin;
1777
1778 static $defOpt = null;
1779 static $defOptLang = null;
1780
1781 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
1782 if ( $defOpt !== null && $defOptLang === $contLang->getCode() ) {
1783 // The content language does not change (and should not change) mid-request, but the
1784 // unit tests change it anyway, and expect this method to return values relevant to the
1785 // current content language.
1786 return $defOpt;
1787 }
1788
1789 $defOpt = $wgDefaultUserOptions;
1790 // Default language setting
1791 $defOptLang = $contLang->getCode();
1792 $defOpt['language'] = $defOptLang;
1793 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1794 if ( $langCode === $contLang->getCode() ) {
1795 $defOpt['variant'] = $langCode;
1796 } else {
1797 $defOpt["variant-$langCode"] = $langCode;
1798 }
1799 }
1800
1801 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1802 // since extensions may change the set of searchable namespaces depending
1803 // on user groups/permissions.
1804 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1805 $defOpt['searchNs' . $nsnum] = (bool)$val;
1806 }
1807 $defOpt['skin'] = Skin::normalizeKey( $wgDefaultSkin );
1808
1809 Hooks::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1810
1811 return $defOpt;
1812 }
1813
1814 /**
1815 * Get a given default option value.
1816 *
1817 * @param string $opt Name of option to retrieve
1818 * @return string Default option value
1819 */
1820 public static function getDefaultOption( $opt ) {
1821 $defOpts = self::getDefaultOptions();
1822 return $defOpts[$opt] ?? null;
1823 }
1824
1825 /**
1826 * Get blocking information
1827 * @param bool $bFromReplica Whether to check the replica DB first.
1828 * To improve performance, non-critical checks are done against replica DBs.
1829 * Check when actually saving should be done against master.
1830 */
1831 private function getBlockedStatus( $bFromReplica = true ) {
1832 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff, $wgSoftBlockRanges;
1833
1834 if ( $this->mBlockedby != -1 ) {
1835 return;
1836 }
1837
1838 wfDebug( __METHOD__ . ": checking...\n" );
1839
1840 // Initialize data...
1841 // Otherwise something ends up stomping on $this->mBlockedby when
1842 // things get lazy-loaded later, causing false positive block hits
1843 // due to -1 !== 0. Probably session-related... Nothing should be
1844 // overwriting mBlockedby, surely?
1845 $this->load();
1846
1847 # We only need to worry about passing the IP address to the Block generator if the
1848 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1849 # know which IP address they're actually coming from
1850 $ip = null;
1851 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1852 // $wgUser->getName() only works after the end of Setup.php. Until
1853 // then, assume it's a logged-out user.
1854 $globalUserName = $wgUser->isSafeToLoad()
1855 ? $wgUser->getName()
1856 : IP::sanitizeIP( $wgUser->getRequest()->getIP() );
1857 if ( $this->getName() === $globalUserName ) {
1858 $ip = $this->getRequest()->getIP();
1859 }
1860 }
1861
1862 // User/IP blocking
1863 $block = Block::newFromTarget( $this, $ip, !$bFromReplica );
1864
1865 // Cookie blocking
1866 if ( !$block instanceof Block ) {
1867 $block = $this->getBlockFromCookieValue( $this->getRequest()->getCookie( 'BlockID' ) );
1868 }
1869
1870 // Proxy blocking
1871 if ( !$block instanceof Block && $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1872 // Local list
1873 if ( self::isLocallyBlockedProxy( $ip ) ) {
1874 $block = new Block( [
1875 'byText' => wfMessage( 'proxyblocker' )->text(),
1876 'reason' => wfMessage( 'proxyblockreason' )->plain(),
1877 'address' => $ip,
1878 'systemBlock' => 'proxy',
1879 ] );
1880 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1881 $block = new Block( [
1882 'byText' => wfMessage( 'sorbs' )->text(),
1883 'reason' => wfMessage( 'sorbsreason' )->plain(),
1884 'address' => $ip,
1885 'systemBlock' => 'dnsbl',
1886 ] );
1887 }
1888 }
1889
1890 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
1891 if ( !$block instanceof Block
1892 && $wgApplyIpBlocksToXff
1893 && $ip !== null
1894 && !in_array( $ip, $wgProxyWhitelist )
1895 ) {
1896 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1897 $xff = array_map( 'trim', explode( ',', $xff ) );
1898 $xff = array_diff( $xff, [ $ip ] );
1899 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromReplica );
1900 $block = Block::chooseBlock( $xffblocks, $xff );
1901 if ( $block instanceof Block ) {
1902 # Mangle the reason to alert the user that the block
1903 # originated from matching the X-Forwarded-For header.
1904 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->plain();
1905 }
1906 }
1907
1908 if ( !$block instanceof Block
1909 && $ip !== null
1910 && $this->isAnon()
1911 && IP::isInRanges( $ip, $wgSoftBlockRanges )
1912 ) {
1913 $block = new Block( [
1914 'address' => $ip,
1915 'byText' => 'MediaWiki default',
1916 'reason' => wfMessage( 'softblockrangesreason', $ip )->plain(),
1917 'anonOnly' => true,
1918 'systemBlock' => 'wgSoftBlockRanges',
1919 ] );
1920 }
1921
1922 if ( $block instanceof Block ) {
1923 wfDebug( __METHOD__ . ": Found block.\n" );
1924 $this->mBlock = $block;
1925 $this->mBlockedby = $block->getByName();
1926 $this->mBlockreason = $block->mReason;
1927 $this->mHideName = $block->mHideName;
1928 $this->mAllowUsertalk = $block->isUsertalkEditAllowed();
1929 } else {
1930 $this->mBlock = null;
1931 $this->mBlockedby = '';
1932 $this->mBlockreason = '';
1933 $this->mHideName = 0;
1934 $this->mAllowUsertalk = false;
1935 }
1936
1937 // Avoid PHP 7.1 warning of passing $this by reference
1938 $user = $this;
1939 // Extensions
1940 Hooks::run( 'GetBlockedStatus', [ &$user ] );
1941 }
1942
1943 /**
1944 * Try to load a Block from an ID given in a cookie value.
1945 * @param string|null $blockCookieVal The cookie value to check.
1946 * @return Block|bool The Block object, or false if none could be loaded.
1947 */
1948 protected function getBlockFromCookieValue( $blockCookieVal ) {
1949 // Make sure there's something to check. The cookie value must start with a number.
1950 if ( strlen( $blockCookieVal ) < 1 || !is_numeric( substr( $blockCookieVal, 0, 1 ) ) ) {
1951 return false;
1952 }
1953 // Load the Block from the ID in the cookie.
1954 $blockCookieId = Block::getIdFromCookieValue( $blockCookieVal );
1955 if ( $blockCookieId !== null ) {
1956 // An ID was found in the cookie.
1957 $tmpBlock = Block::newFromID( $blockCookieId );
1958 if ( $tmpBlock instanceof Block ) {
1959 $config = RequestContext::getMain()->getConfig();
1960
1961 switch ( $tmpBlock->getType() ) {
1962 case Block::TYPE_USER:
1963 $blockIsValid = !$tmpBlock->isExpired() && $tmpBlock->isAutoblocking();
1964 $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true );
1965 break;
1966 case Block::TYPE_IP:
1967 case Block::TYPE_RANGE:
1968 // If block is type IP or IP range, load only if user is not logged in (T152462)
1969 $blockIsValid = !$tmpBlock->isExpired() && !$this->isLoggedIn();
1970 $useBlockCookie = ( $config->get( 'CookieSetOnIpBlock' ) === true );
1971 break;
1972 default:
1973 $blockIsValid = false;
1974 $useBlockCookie = false;
1975 }
1976
1977 if ( $blockIsValid && $useBlockCookie ) {
1978 // Use the block.
1979 return $tmpBlock;
1980 }
1981
1982 // If the block is not valid, remove the cookie.
1983 Block::clearCookie( $this->getRequest()->response() );
1984 } else {
1985 // If the block doesn't exist, remove the cookie.
1986 Block::clearCookie( $this->getRequest()->response() );
1987 }
1988 }
1989 return false;
1990 }
1991
1992 /**
1993 * Whether the given IP is in a DNS blacklist.
1994 *
1995 * @param string $ip IP to check
1996 * @param bool $checkWhitelist Whether to check the whitelist first
1997 * @return bool True if blacklisted.
1998 */
1999 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
2000 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
2001
2002 if ( !$wgEnableDnsBlacklist ||
2003 ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
2004 ) {
2005 return false;
2006 }
2007
2008 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
2009 }
2010
2011 /**
2012 * Whether the given IP is in a given DNS blacklist.
2013 *
2014 * @param string $ip IP to check
2015 * @param string|array $bases Array of Strings: URL of the DNS blacklist
2016 * @return bool True if blacklisted.
2017 */
2018 public function inDnsBlacklist( $ip, $bases ) {
2019 $found = false;
2020 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
2021 if ( IP::isIPv4( $ip ) ) {
2022 // Reverse IP, T23255
2023 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
2024
2025 foreach ( (array)$bases as $base ) {
2026 // Make hostname
2027 // If we have an access key, use that too (ProjectHoneypot, etc.)
2028 $basename = $base;
2029 if ( is_array( $base ) ) {
2030 if ( count( $base ) >= 2 ) {
2031 // Access key is 1, base URL is 0
2032 $host = "{$base[1]}.$ipReversed.{$base[0]}";
2033 } else {
2034 $host = "$ipReversed.{$base[0]}";
2035 }
2036 $basename = $base[0];
2037 } else {
2038 $host = "$ipReversed.$base";
2039 }
2040
2041 // Send query
2042 $ipList = gethostbynamel( $host );
2043
2044 if ( $ipList ) {
2045 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
2046 $found = true;
2047 break;
2048 }
2049
2050 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
2051 }
2052 }
2053
2054 return $found;
2055 }
2056
2057 /**
2058 * Check if an IP address is in the local proxy list
2059 *
2060 * @param string $ip
2061 *
2062 * @return bool
2063 */
2064 public static function isLocallyBlockedProxy( $ip ) {
2065 global $wgProxyList;
2066
2067 if ( !$wgProxyList ) {
2068 return false;
2069 }
2070
2071 if ( !is_array( $wgProxyList ) ) {
2072 // Load values from the specified file
2073 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
2074 }
2075
2076 $resultProxyList = [];
2077 $deprecatedIPEntries = [];
2078
2079 // backward compatibility: move all ip addresses in keys to values
2080 foreach ( $wgProxyList as $key => $value ) {
2081 $keyIsIP = IP::isIPAddress( $key );
2082 $valueIsIP = IP::isIPAddress( $value );
2083 if ( $keyIsIP && !$valueIsIP ) {
2084 $deprecatedIPEntries[] = $key;
2085 $resultProxyList[] = $key;
2086 } elseif ( $keyIsIP && $valueIsIP ) {
2087 $deprecatedIPEntries[] = $key;
2088 $resultProxyList[] = $key;
2089 $resultProxyList[] = $value;
2090 } else {
2091 $resultProxyList[] = $value;
2092 }
2093 }
2094
2095 if ( $deprecatedIPEntries ) {
2096 wfDeprecated(
2097 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
2098 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
2099 }
2100
2101 $proxyListIPSet = new IPSet( $resultProxyList );
2102 return $proxyListIPSet->match( $ip );
2103 }
2104
2105 /**
2106 * Is this user subject to rate limiting?
2107 *
2108 * @return bool True if rate limited
2109 */
2110 public function isPingLimitable() {
2111 global $wgRateLimitsExcludedIPs;
2112 if ( IP::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
2113 // No other good way currently to disable rate limits
2114 // for specific IPs. :P
2115 // But this is a crappy hack and should die.
2116 return false;
2117 }
2118 return !$this->isAllowed( 'noratelimit' );
2119 }
2120
2121 /**
2122 * Primitive rate limits: enforce maximum actions per time period
2123 * to put a brake on flooding.
2124 *
2125 * The method generates both a generic profiling point and a per action one
2126 * (suffix being "-$action".
2127 *
2128 * @note When using a shared cache like memcached, IP-address
2129 * last-hit counters will be shared across wikis.
2130 *
2131 * @param string $action Action to enforce; 'edit' if unspecified
2132 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
2133 * @return bool True if a rate limiter was tripped
2134 */
2135 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
2136 // Avoid PHP 7.1 warning of passing $this by reference
2137 $user = $this;
2138 // Call the 'PingLimiter' hook
2139 $result = false;
2140 if ( !Hooks::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
2141 return $result;
2142 }
2143
2144 global $wgRateLimits;
2145 if ( !isset( $wgRateLimits[$action] ) ) {
2146 return false;
2147 }
2148
2149 $limits = array_merge(
2150 [ '&can-bypass' => true ],
2151 $wgRateLimits[$action]
2152 );
2153
2154 // Some groups shouldn't trigger the ping limiter, ever
2155 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
2156 return false;
2157 }
2158
2159 $keys = [];
2160 $id = $this->getId();
2161 $userLimit = false;
2162 $isNewbie = $this->isNewbie();
2163 $cache = ObjectCache::getLocalClusterInstance();
2164
2165 if ( $id == 0 ) {
2166 // limits for anons
2167 if ( isset( $limits['anon'] ) ) {
2168 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
2169 }
2170 } elseif ( isset( $limits['user'] ) ) {
2171 // limits for logged-in users
2172 $userLimit = $limits['user'];
2173 }
2174
2175 // limits for anons and for newbie logged-in users
2176 if ( $isNewbie ) {
2177 // ip-based limits
2178 if ( isset( $limits['ip'] ) ) {
2179 $ip = $this->getRequest()->getIP();
2180 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
2181 }
2182 // subnet-based limits
2183 if ( isset( $limits['subnet'] ) ) {
2184 $ip = $this->getRequest()->getIP();
2185 $subnet = IP::getSubnet( $ip );
2186 if ( $subnet !== false ) {
2187 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
2188 }
2189 }
2190 }
2191
2192 // Check for group-specific permissions
2193 // If more than one group applies, use the group with the highest limit ratio (max/period)
2194 foreach ( $this->getGroups() as $group ) {
2195 if ( isset( $limits[$group] ) ) {
2196 if ( $userLimit === false
2197 || $limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
2198 ) {
2199 $userLimit = $limits[$group];
2200 }
2201 }
2202 }
2203
2204 // limits for newbie logged-in users (override all the normal user limits)
2205 if ( $id !== 0 && $isNewbie && isset( $limits['newbie'] ) ) {
2206 $userLimit = $limits['newbie'];
2207 }
2208
2209 // Set the user limit key
2210 if ( $userLimit !== false ) {
2211 list( $max, $period ) = $userLimit;
2212 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
2213 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
2214 }
2215
2216 // ip-based limits for all ping-limitable users
2217 if ( isset( $limits['ip-all'] ) ) {
2218 $ip = $this->getRequest()->getIP();
2219 // ignore if user limit is more permissive
2220 if ( $isNewbie || $userLimit === false
2221 || $limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2222 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
2223 }
2224 }
2225
2226 // subnet-based limits for all ping-limitable users
2227 if ( isset( $limits['subnet-all'] ) ) {
2228 $ip = $this->getRequest()->getIP();
2229 $subnet = IP::getSubnet( $ip );
2230 if ( $subnet !== false ) {
2231 // ignore if user limit is more permissive
2232 if ( $isNewbie || $userLimit === false
2233 || $limits['ip-all'][0] / $limits['ip-all'][1]
2234 > $userLimit[0] / $userLimit[1] ) {
2235 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2236 }
2237 }
2238 }
2239
2240 $triggered = false;
2241 foreach ( $keys as $key => $limit ) {
2242 list( $max, $period ) = $limit;
2243 $summary = "(limit $max in {$period}s)";
2244 $count = $cache->get( $key );
2245 // Already pinged?
2246 if ( $count ) {
2247 if ( $count >= $max ) {
2248 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2249 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2250 $triggered = true;
2251 } else {
2252 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
2253 }
2254 } else {
2255 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
2256 if ( $incrBy > 0 ) {
2257 $cache->add( $key, 0, intval( $period ) ); // first ping
2258 }
2259 }
2260 if ( $incrBy > 0 ) {
2261 $cache->incr( $key, $incrBy );
2262 }
2263 }
2264
2265 return $triggered;
2266 }
2267
2268 /**
2269 * Check if user is blocked
2270 *
2271 * @param bool $bFromReplica Whether to check the replica DB instead of
2272 * the master. Hacked from false due to horrible probs on site.
2273 * @return bool True if blocked, false otherwise
2274 */
2275 public function isBlocked( $bFromReplica = true ) {
2276 return $this->getBlock( $bFromReplica ) instanceof Block &&
2277 $this->getBlock()->appliesToRight( 'edit' );
2278 }
2279
2280 /**
2281 * Get the block affecting the user, or null if the user is not blocked
2282 *
2283 * @param bool $bFromReplica Whether to check the replica DB instead of the master
2284 * @return Block|null
2285 */
2286 public function getBlock( $bFromReplica = true ) {
2287 $this->getBlockedStatus( $bFromReplica );
2288 return $this->mBlock instanceof Block ? $this->mBlock : null;
2289 }
2290
2291 /**
2292 * Check if user is blocked from editing a particular article
2293 *
2294 * @param Title $title Title to check
2295 * @param bool $fromReplica Whether to check the replica DB instead of the master
2296 * @return bool
2297 */
2298 public function isBlockedFrom( $title, $fromReplica = false ) {
2299 $blocked = $this->isHidden();
2300
2301 if ( !$blocked ) {
2302 $block = $this->getBlock( $fromReplica );
2303 if ( $block ) {
2304 // Special handling for a user's own talk page. The block is not aware
2305 // of the user, so this must be done here.
2306 if ( $title->equals( $this->getTalkPage() ) ) {
2307 $blocked = $block->appliesToUsertalk( $title );
2308 } else {
2309 $blocked = $block->appliesToTitle( $title );
2310 }
2311 }
2312 }
2313
2314 // only for the purpose of the hook. We really don't need this here.
2315 $allowUsertalk = $this->mAllowUsertalk;
2316
2317 Hooks::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2318
2319 return $blocked;
2320 }
2321
2322 /**
2323 * If user is blocked, return the name of the user who placed the block
2324 * @return string Name of blocker
2325 */
2326 public function blockedBy() {
2327 $this->getBlockedStatus();
2328 return $this->mBlockedby;
2329 }
2330
2331 /**
2332 * If user is blocked, return the specified reason for the block
2333 * @return string Blocking reason
2334 */
2335 public function blockedFor() {
2336 $this->getBlockedStatus();
2337 return $this->mBlockreason;
2338 }
2339
2340 /**
2341 * If user is blocked, return the ID for the block
2342 * @return int Block ID
2343 */
2344 public function getBlockId() {
2345 $this->getBlockedStatus();
2346 return ( $this->mBlock ? $this->mBlock->getId() : false );
2347 }
2348
2349 /**
2350 * Check if user is blocked on all wikis.
2351 * Do not use for actual edit permission checks!
2352 * This is intended for quick UI checks.
2353 *
2354 * @param string $ip IP address, uses current client if none given
2355 * @return bool True if blocked, false otherwise
2356 */
2357 public function isBlockedGlobally( $ip = '' ) {
2358 return $this->getGlobalBlock( $ip ) instanceof Block;
2359 }
2360
2361 /**
2362 * Check if user is blocked on all wikis.
2363 * Do not use for actual edit permission checks!
2364 * This is intended for quick UI checks.
2365 *
2366 * @param string $ip IP address, uses current client if none given
2367 * @return Block|null Block object if blocked, null otherwise
2368 * @throws FatalError
2369 * @throws MWException
2370 */
2371 public function getGlobalBlock( $ip = '' ) {
2372 if ( $this->mGlobalBlock !== null ) {
2373 return $this->mGlobalBlock ?: null;
2374 }
2375 // User is already an IP?
2376 if ( IP::isIPAddress( $this->getName() ) ) {
2377 $ip = $this->getName();
2378 } elseif ( !$ip ) {
2379 $ip = $this->getRequest()->getIP();
2380 }
2381 // Avoid PHP 7.1 warning of passing $this by reference
2382 $user = $this;
2383 $blocked = false;
2384 $block = null;
2385 Hooks::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2386
2387 if ( $blocked && $block === null ) {
2388 // back-compat: UserIsBlockedGlobally didn't have $block param first
2389 $block = new Block( [
2390 'address' => $ip,
2391 'systemBlock' => 'global-block'
2392 ] );
2393 }
2394
2395 $this->mGlobalBlock = $blocked ? $block : false;
2396 return $this->mGlobalBlock ?: null;
2397 }
2398
2399 /**
2400 * Check if user account is locked
2401 *
2402 * @return bool True if locked, false otherwise
2403 */
2404 public function isLocked() {
2405 if ( $this->mLocked !== null ) {
2406 return $this->mLocked;
2407 }
2408 // Reset for hook
2409 $this->mLocked = false;
2410 Hooks::run( 'UserIsLocked', [ $this, &$this->mLocked ] );
2411 return $this->mLocked;
2412 }
2413
2414 /**
2415 * Check if user account is hidden
2416 *
2417 * @return bool True if hidden, false otherwise
2418 */
2419 public function isHidden() {
2420 if ( $this->mHideName !== null ) {
2421 return (bool)$this->mHideName;
2422 }
2423 $this->getBlockedStatus();
2424 if ( !$this->mHideName ) {
2425 // Reset for hook
2426 $this->mHideName = false;
2427 Hooks::run( 'UserIsHidden', [ $this, &$this->mHideName ] );
2428 }
2429 return (bool)$this->mHideName;
2430 }
2431
2432 /**
2433 * Get the user's ID.
2434 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2435 */
2436 public function getId() {
2437 if ( $this->mId === null && $this->mName !== null && self::isIP( $this->mName ) ) {
2438 // Special case, we know the user is anonymous
2439 return 0;
2440 }
2441
2442 if ( !$this->isItemLoaded( 'id' ) ) {
2443 // Don't load if this was initialized from an ID
2444 $this->load();
2445 }
2446
2447 return (int)$this->mId;
2448 }
2449
2450 /**
2451 * Set the user and reload all fields according to a given ID
2452 * @param int $v User ID to reload
2453 */
2454 public function setId( $v ) {
2455 $this->mId = $v;
2456 $this->clearInstanceCache( 'id' );
2457 }
2458
2459 /**
2460 * Get the user name, or the IP of an anonymous user
2461 * @return string User's name or IP address
2462 */
2463 public function getName() {
2464 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2465 // Special case optimisation
2466 return $this->mName;
2467 }
2468
2469 $this->load();
2470 if ( $this->mName === false ) {
2471 // Clean up IPs
2472 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
2473 }
2474
2475 return $this->mName;
2476 }
2477
2478 /**
2479 * Set the user name.
2480 *
2481 * This does not reload fields from the database according to the given
2482 * name. Rather, it is used to create a temporary "nonexistent user" for
2483 * later addition to the database. It can also be used to set the IP
2484 * address for an anonymous user to something other than the current
2485 * remote IP.
2486 *
2487 * @note User::newFromName() has roughly the same function, when the named user
2488 * does not exist.
2489 * @param string $str New user name to set
2490 */
2491 public function setName( $str ) {
2492 $this->load();
2493 $this->mName = $str;
2494 }
2495
2496 /**
2497 * Get the user's actor ID.
2498 * @since 1.31
2499 * @param IDatabase|null $dbw Assign a new actor ID, using this DB handle, if none exists
2500 * @return int The actor's ID, or 0 if no actor ID exists and $dbw was null
2501 */
2502 public function getActorId( IDatabase $dbw = null ) {
2503 global $wgActorTableSchemaMigrationStage;
2504
2505 // Technically we should always return 0 without SCHEMA_COMPAT_READ_NEW,
2506 // but it does little harm and might be needed for write callers loading a User.
2507 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) ) {
2508 return 0;
2509 }
2510
2511 if ( !$this->isItemLoaded( 'actor' ) ) {
2512 $this->load();
2513 }
2514
2515 // Currently $this->mActorId might be null if $this was loaded from a
2516 // cache entry that was written when $wgActorTableSchemaMigrationStage
2517 // was SCHEMA_COMPAT_OLD. Once that is no longer a possibility (i.e. when
2518 // User::VERSION is incremented after $wgActorTableSchemaMigrationStage
2519 // has been removed), that condition may be removed.
2520 if ( $this->mActorId === null || !$this->mActorId && $dbw ) {
2521 $q = [
2522 'actor_user' => $this->getId() ?: null,
2523 'actor_name' => (string)$this->getName(),
2524 ];
2525 if ( $dbw ) {
2526 if ( $q['actor_user'] === null && self::isUsableName( $q['actor_name'] ) ) {
2527 throw new CannotCreateActorException(
2528 'Cannot create an actor for a usable name that is not an existing user'
2529 );
2530 }
2531 if ( $q['actor_name'] === '' ) {
2532 throw new CannotCreateActorException( 'Cannot create an actor for a user with no name' );
2533 }
2534 $dbw->insert( 'actor', $q, __METHOD__, [ 'IGNORE' ] );
2535 if ( $dbw->affectedRows() ) {
2536 $this->mActorId = (int)$dbw->insertId();
2537 } else {
2538 // Outdated cache?
2539 // Use LOCK IN SHARE MODE to bypass any MySQL REPEATABLE-READ snapshot.
2540 $this->mActorId = (int)$dbw->selectField(
2541 'actor',
2542 'actor_id',
2543 $q,
2544 __METHOD__,
2545 [ 'LOCK IN SHARE MODE' ]
2546 );
2547 if ( !$this->mActorId ) {
2548 throw new CannotCreateActorException(
2549 "Cannot create actor ID for user_id={$this->getId()} user_name={$this->getName()}"
2550 );
2551 }
2552 }
2553 $this->invalidateCache();
2554 } else {
2555 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $this->queryFlagsUsed );
2556 $db = wfGetDB( $index );
2557 $this->mActorId = (int)$db->selectField( 'actor', 'actor_id', $q, __METHOD__, $options );
2558 }
2559 $this->setItemLoaded( 'actor' );
2560 }
2561
2562 return (int)$this->mActorId;
2563 }
2564
2565 /**
2566 * Get the user's name escaped by underscores.
2567 * @return string Username escaped by underscores.
2568 */
2569 public function getTitleKey() {
2570 return str_replace( ' ', '_', $this->getName() );
2571 }
2572
2573 /**
2574 * Check if the user has new messages.
2575 * @return bool True if the user has new messages
2576 */
2577 public function getNewtalk() {
2578 $this->load();
2579
2580 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2581 if ( $this->mNewtalk === -1 ) {
2582 $this->mNewtalk = false; # reset talk page status
2583
2584 // Check memcached separately for anons, who have no
2585 // entire User object stored in there.
2586 if ( !$this->mId ) {
2587 global $wgDisableAnonTalk;
2588 if ( $wgDisableAnonTalk ) {
2589 // Anon newtalk disabled by configuration.
2590 $this->mNewtalk = false;
2591 } else {
2592 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName() );
2593 }
2594 } else {
2595 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
2596 }
2597 }
2598
2599 return (bool)$this->mNewtalk;
2600 }
2601
2602 /**
2603 * Return the data needed to construct links for new talk page message
2604 * alerts. If there are new messages, this will return an associative array
2605 * with the following data:
2606 * wiki: The database name of the wiki
2607 * link: Root-relative link to the user's talk page
2608 * rev: The last talk page revision that the user has seen or null. This
2609 * is useful for building diff links.
2610 * If there are no new messages, it returns an empty array.
2611 * @note This function was designed to accomodate multiple talk pages, but
2612 * currently only returns a single link and revision.
2613 * @return array
2614 */
2615 public function getNewMessageLinks() {
2616 // Avoid PHP 7.1 warning of passing $this by reference
2617 $user = $this;
2618 $talks = [];
2619 if ( !Hooks::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2620 return $talks;
2621 }
2622
2623 if ( !$this->getNewtalk() ) {
2624 return [];
2625 }
2626 $utp = $this->getTalkPage();
2627 $dbr = wfGetDB( DB_REPLICA );
2628 // Get the "last viewed rev" timestamp from the oldest message notification
2629 $timestamp = $dbr->selectField( 'user_newtalk',
2630 'MIN(user_last_timestamp)',
2631 $this->isAnon() ? [ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2632 __METHOD__ );
2633 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2634 return [
2635 [
2636 'wiki' => WikiMap::getWikiIdFromDbDomain( WikiMap::getCurrentWikiDbDomain() ),
2637 'link' => $utp->getLocalURL(),
2638 'rev' => $rev
2639 ]
2640 ];
2641 }
2642
2643 /**
2644 * Get the revision ID for the last talk page revision viewed by the talk
2645 * page owner.
2646 * @return int|null Revision ID or null
2647 */
2648 public function getNewMessageRevisionId() {
2649 $newMessageRevisionId = null;
2650 $newMessageLinks = $this->getNewMessageLinks();
2651
2652 // Note: getNewMessageLinks() never returns more than a single link
2653 // and it is always for the same wiki, but we double-check here in
2654 // case that changes some time in the future.
2655 if ( $newMessageLinks && count( $newMessageLinks ) === 1
2656 && WikiMap::isCurrentWikiId( $newMessageLinks[0]['wiki'] )
2657 && $newMessageLinks[0]['rev']
2658 ) {
2659 /** @var Revision $newMessageRevision */
2660 $newMessageRevision = $newMessageLinks[0]['rev'];
2661 $newMessageRevisionId = $newMessageRevision->getId();
2662 }
2663
2664 return $newMessageRevisionId;
2665 }
2666
2667 /**
2668 * Internal uncached check for new messages
2669 *
2670 * @see getNewtalk()
2671 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2672 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2673 * @return bool True if the user has new messages
2674 */
2675 protected function checkNewtalk( $field, $id ) {
2676 $dbr = wfGetDB( DB_REPLICA );
2677
2678 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__ );
2679
2680 return $ok !== false;
2681 }
2682
2683 /**
2684 * Add or update the new messages flag
2685 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2686 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2687 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2688 * @return bool True if successful, false otherwise
2689 */
2690 protected function updateNewtalk( $field, $id, $curRev = null ) {
2691 // Get timestamp of the talk page revision prior to the current one
2692 $prevRev = $curRev ? $curRev->getPrevious() : false;
2693 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2694 // Mark the user as having new messages since this revision
2695 $dbw = wfGetDB( DB_MASTER );
2696 $dbw->insert( 'user_newtalk',
2697 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2698 __METHOD__,
2699 'IGNORE' );
2700 if ( $dbw->affectedRows() ) {
2701 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2702 return true;
2703 }
2704
2705 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2706 return false;
2707 }
2708
2709 /**
2710 * Clear the new messages flag for the given user
2711 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2712 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2713 * @return bool True if successful, false otherwise
2714 */
2715 protected function deleteNewtalk( $field, $id ) {
2716 $dbw = wfGetDB( DB_MASTER );
2717 $dbw->delete( 'user_newtalk',
2718 [ $field => $id ],
2719 __METHOD__ );
2720 if ( $dbw->affectedRows() ) {
2721 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2722 return true;
2723 }
2724
2725 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2726 return false;
2727 }
2728
2729 /**
2730 * Update the 'You have new messages!' status.
2731 * @param bool $val Whether the user has new messages
2732 * @param Revision|null $curRev New, as yet unseen revision of the user talk
2733 * page. Ignored if null or !$val.
2734 */
2735 public function setNewtalk( $val, $curRev = null ) {
2736 if ( wfReadOnly() ) {
2737 return;
2738 }
2739
2740 $this->load();
2741 $this->mNewtalk = $val;
2742
2743 if ( $this->isAnon() ) {
2744 $field = 'user_ip';
2745 $id = $this->getName();
2746 } else {
2747 $field = 'user_id';
2748 $id = $this->getId();
2749 }
2750
2751 if ( $val ) {
2752 $changed = $this->updateNewtalk( $field, $id, $curRev );
2753 } else {
2754 $changed = $this->deleteNewtalk( $field, $id );
2755 }
2756
2757 if ( $changed ) {
2758 $this->invalidateCache();
2759 }
2760 }
2761
2762 /**
2763 * Generate a current or new-future timestamp to be stored in the
2764 * user_touched field when we update things.
2765 *
2766 * @return string Timestamp in TS_MW format
2767 */
2768 private function newTouchedTimestamp() {
2769 $time = time();
2770 if ( $this->mTouched ) {
2771 $time = max( $time, wfTimestamp( TS_UNIX, $this->mTouched ) + 1 );
2772 }
2773
2774 return wfTimestamp( TS_MW, $time );
2775 }
2776
2777 /**
2778 * Clear user data from memcached
2779 *
2780 * Use after applying updates to the database; caller's
2781 * responsibility to update user_touched if appropriate.
2782 *
2783 * Called implicitly from invalidateCache() and saveSettings().
2784 *
2785 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2786 */
2787 public function clearSharedCache( $mode = 'changed' ) {
2788 if ( !$this->getId() ) {
2789 return;
2790 }
2791
2792 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2793 $key = $this->getCacheKey( $cache );
2794 if ( $mode === 'refresh' ) {
2795 $cache->delete( $key, 1 );
2796 } else {
2797 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
2798 if ( $lb->hasOrMadeRecentMasterChanges() ) {
2799 $lb->getConnection( DB_MASTER )->onTransactionPreCommitOrIdle(
2800 function () use ( $cache, $key ) {
2801 $cache->delete( $key );
2802 },
2803 __METHOD__
2804 );
2805 } else {
2806 $cache->delete( $key );
2807 }
2808 }
2809 }
2810
2811 /**
2812 * Immediately touch the user data cache for this account
2813 *
2814 * Calls touch() and removes account data from memcached
2815 */
2816 public function invalidateCache() {
2817 $this->touch();
2818 $this->clearSharedCache();
2819 }
2820
2821 /**
2822 * Update the "touched" timestamp for the user
2823 *
2824 * This is useful on various login/logout events when making sure that
2825 * a browser or proxy that has multiple tenants does not suffer cache
2826 * pollution where the new user sees the old users content. The value
2827 * of getTouched() is checked when determining 304 vs 200 responses.
2828 * Unlike invalidateCache(), this preserves the User object cache and
2829 * avoids database writes.
2830 *
2831 * @since 1.25
2832 */
2833 public function touch() {
2834 $id = $this->getId();
2835 if ( $id ) {
2836 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2837 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2838 $cache->touchCheckKey( $key );
2839 $this->mQuickTouched = null;
2840 }
2841 }
2842
2843 /**
2844 * Validate the cache for this account.
2845 * @param string $timestamp A timestamp in TS_MW format
2846 * @return bool
2847 */
2848 public function validateCache( $timestamp ) {
2849 return ( $timestamp >= $this->getTouched() );
2850 }
2851
2852 /**
2853 * Get the user touched timestamp
2854 *
2855 * Use this value only to validate caches via inequalities
2856 * such as in the case of HTTP If-Modified-Since response logic
2857 *
2858 * @return string TS_MW Timestamp
2859 */
2860 public function getTouched() {
2861 $this->load();
2862
2863 if ( $this->mId ) {
2864 if ( $this->mQuickTouched === null ) {
2865 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2866 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId );
2867
2868 $this->mQuickTouched = wfTimestamp( TS_MW, $cache->getCheckKeyTime( $key ) );
2869 }
2870
2871 return max( $this->mTouched, $this->mQuickTouched );
2872 }
2873
2874 return $this->mTouched;
2875 }
2876
2877 /**
2878 * Get the user_touched timestamp field (time of last DB updates)
2879 * @return string TS_MW Timestamp
2880 * @since 1.26
2881 */
2882 public function getDBTouched() {
2883 $this->load();
2884
2885 return $this->mTouched;
2886 }
2887
2888 /**
2889 * Set the password and reset the random token.
2890 * Calls through to authentication plugin if necessary;
2891 * will have no effect if the auth plugin refuses to
2892 * pass the change through or if the legal password
2893 * checks fail.
2894 *
2895 * As a special case, setting the password to null
2896 * wipes it, so the account cannot be logged in until
2897 * a new password is set, for instance via e-mail.
2898 *
2899 * @deprecated since 1.27, use AuthManager instead
2900 * @param string $str New password to set
2901 * @throws PasswordError On failure
2902 * @return bool
2903 */
2904 public function setPassword( $str ) {
2905 wfDeprecated( __METHOD__, '1.27' );
2906 return $this->setPasswordInternal( $str );
2907 }
2908
2909 /**
2910 * Set the password and reset the random token unconditionally.
2911 *
2912 * @deprecated since 1.27, use AuthManager instead
2913 * @param string|null $str New password to set or null to set an invalid
2914 * password hash meaning that the user will not be able to log in
2915 * through the web interface.
2916 */
2917 public function setInternalPassword( $str ) {
2918 wfDeprecated( __METHOD__, '1.27' );
2919 $this->setPasswordInternal( $str );
2920 }
2921
2922 /**
2923 * Actually set the password and such
2924 * @since 1.27 cannot set a password for a user not in the database
2925 * @param string|null $str New password to set or null to set an invalid
2926 * password hash meaning that the user will not be able to log in
2927 * through the web interface.
2928 * @return bool Success
2929 */
2930 private function setPasswordInternal( $str ) {
2931 $manager = AuthManager::singleton();
2932
2933 // If the user doesn't exist yet, fail
2934 if ( !$manager->userExists( $this->getName() ) ) {
2935 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2936 }
2937
2938 $status = $this->changeAuthenticationData( [
2939 'username' => $this->getName(),
2940 'password' => $str,
2941 'retype' => $str,
2942 ] );
2943 if ( !$status->isGood() ) {
2944 \MediaWiki\Logger\LoggerFactory::getInstance( 'authentication' )
2945 ->info( __METHOD__ . ': Password change rejected: '
2946 . $status->getWikiText( null, null, 'en' ) );
2947 return false;
2948 }
2949
2950 $this->setOption( 'watchlisttoken', false );
2951 SessionManager::singleton()->invalidateSessionsForUser( $this );
2952
2953 return true;
2954 }
2955
2956 /**
2957 * Changes credentials of the user.
2958 *
2959 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2960 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2961 * e.g. when no provider handled the change.
2962 *
2963 * @param array $data A set of authentication data in fieldname => value format. This is the
2964 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2965 * @return Status
2966 * @since 1.27
2967 */
2968 public function changeAuthenticationData( array $data ) {
2969 $manager = AuthManager::singleton();
2970 $reqs = $manager->getAuthenticationRequests( AuthManager::ACTION_CHANGE, $this );
2971 $reqs = AuthenticationRequest::loadRequestsFromSubmission( $reqs, $data );
2972
2973 $status = Status::newGood( 'ignored' );
2974 foreach ( $reqs as $req ) {
2975 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2976 }
2977 if ( $status->getValue() === 'ignored' ) {
2978 $status->warning( 'authenticationdatachange-ignored' );
2979 }
2980
2981 if ( $status->isGood() ) {
2982 foreach ( $reqs as $req ) {
2983 $manager->changeAuthenticationData( $req );
2984 }
2985 }
2986 return $status;
2987 }
2988
2989 /**
2990 * Get the user's current token.
2991 * @param bool $forceCreation Force the generation of a new token if the
2992 * user doesn't have one (default=true for backwards compatibility).
2993 * @return string|null Token
2994 */
2995 public function getToken( $forceCreation = true ) {
2996 global $wgAuthenticationTokenVersion;
2997
2998 $this->load();
2999 if ( !$this->mToken && $forceCreation ) {
3000 $this->setToken();
3001 }
3002
3003 if ( !$this->mToken ) {
3004 // The user doesn't have a token, return null to indicate that.
3005 return null;
3006 }
3007
3008 if ( $this->mToken === self::INVALID_TOKEN ) {
3009 // We return a random value here so existing token checks are very
3010 // likely to fail.
3011 return MWCryptRand::generateHex( self::TOKEN_LENGTH );
3012 }
3013
3014 if ( $wgAuthenticationTokenVersion === null ) {
3015 // $wgAuthenticationTokenVersion not in use, so return the raw secret
3016 return $this->mToken;
3017 }
3018
3019 // $wgAuthenticationTokenVersion in use, so hmac it.
3020 $ret = MWCryptHash::hmac( $wgAuthenticationTokenVersion, $this->mToken, false );
3021
3022 // The raw hash can be overly long. Shorten it up.
3023 $len = max( 32, self::TOKEN_LENGTH );
3024 if ( strlen( $ret ) < $len ) {
3025 // Should never happen, even md5 is 128 bits
3026 throw new \UnexpectedValueException( 'Hmac returned less than 128 bits' );
3027 }
3028
3029 return substr( $ret, -$len );
3030 }
3031
3032 /**
3033 * Set the random token (used for persistent authentication)
3034 * Called from loadDefaults() among other places.
3035 *
3036 * @param string|bool $token If specified, set the token to this value
3037 */
3038 public function setToken( $token = false ) {
3039 $this->load();
3040 if ( $this->mToken === self::INVALID_TOKEN ) {
3041 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3042 ->debug( __METHOD__ . ": Ignoring attempt to set token for system user \"$this\"" );
3043 } elseif ( !$token ) {
3044 $this->mToken = MWCryptRand::generateHex( self::TOKEN_LENGTH );
3045 } else {
3046 $this->mToken = $token;
3047 }
3048 }
3049
3050 /**
3051 * Set the password for a password reminder or new account email
3052 *
3053 * @deprecated Removed in 1.27. Use PasswordReset instead.
3054 * @param string $str New password to set or null to set an invalid
3055 * password hash meaning that the user will not be able to use it
3056 * @param bool $throttle If true, reset the throttle timestamp to the present
3057 */
3058 public function setNewpassword( $str, $throttle = true ) {
3059 throw new BadMethodCallException( __METHOD__ . ' has been removed in 1.27' );
3060 }
3061
3062 /**
3063 * Get the user's e-mail address
3064 * @return string User's email address
3065 */
3066 public function getEmail() {
3067 $this->load();
3068 Hooks::run( 'UserGetEmail', [ $this, &$this->mEmail ] );
3069 return $this->mEmail;
3070 }
3071
3072 /**
3073 * Get the timestamp of the user's e-mail authentication
3074 * @return string TS_MW timestamp
3075 */
3076 public function getEmailAuthenticationTimestamp() {
3077 $this->load();
3078 Hooks::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated ] );
3079 return $this->mEmailAuthenticated;
3080 }
3081
3082 /**
3083 * Set the user's e-mail address
3084 * @param string $str New e-mail address
3085 */
3086 public function setEmail( $str ) {
3087 $this->load();
3088 if ( $str == $this->mEmail ) {
3089 return;
3090 }
3091 $this->invalidateEmail();
3092 $this->mEmail = $str;
3093 Hooks::run( 'UserSetEmail', [ $this, &$this->mEmail ] );
3094 }
3095
3096 /**
3097 * Set the user's e-mail address and a confirmation mail if needed.
3098 *
3099 * @since 1.20
3100 * @param string $str New e-mail address
3101 * @return Status
3102 */
3103 public function setEmailWithConfirmation( $str ) {
3104 global $wgEnableEmail, $wgEmailAuthentication;
3105
3106 if ( !$wgEnableEmail ) {
3107 return Status::newFatal( 'emaildisabled' );
3108 }
3109
3110 $oldaddr = $this->getEmail();
3111 if ( $str === $oldaddr ) {
3112 return Status::newGood( true );
3113 }
3114
3115 $type = $oldaddr != '' ? 'changed' : 'set';
3116 $notificationResult = null;
3117
3118 if ( $wgEmailAuthentication && $type === 'changed' ) {
3119 // Send the user an email notifying the user of the change in registered
3120 // email address on their previous email address
3121 $change = $str != '' ? 'changed' : 'removed';
3122 $notificationResult = $this->sendMail(
3123 wfMessage( 'notificationemail_subject_' . $change )->text(),
3124 wfMessage( 'notificationemail_body_' . $change,
3125 $this->getRequest()->getIP(),
3126 $this->getName(),
3127 $str )->text()
3128 );
3129 }
3130
3131 $this->setEmail( $str );
3132
3133 if ( $str !== '' && $wgEmailAuthentication ) {
3134 // Send a confirmation request to the new address if needed
3135 $result = $this->sendConfirmationMail( $type );
3136
3137 if ( $notificationResult !== null ) {
3138 $result->merge( $notificationResult );
3139 }
3140
3141 if ( $result->isGood() ) {
3142 // Say to the caller that a confirmation and notification mail has been sent
3143 $result->value = 'eauth';
3144 }
3145 } else {
3146 $result = Status::newGood( true );
3147 }
3148
3149 return $result;
3150 }
3151
3152 /**
3153 * Get the user's real name
3154 * @return string User's real name
3155 */
3156 public function getRealName() {
3157 if ( !$this->isItemLoaded( 'realname' ) ) {
3158 $this->load();
3159 }
3160
3161 return $this->mRealName;
3162 }
3163
3164 /**
3165 * Set the user's real name
3166 * @param string $str New real name
3167 */
3168 public function setRealName( $str ) {
3169 $this->load();
3170 $this->mRealName = $str;
3171 }
3172
3173 /**
3174 * Get the user's current setting for a given option.
3175 *
3176 * @param string $oname The option to check
3177 * @param string|array|null $defaultOverride A default value returned if the option does not exist
3178 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
3179 * @return string|array|int|null User's current value for the option
3180 * @see getBoolOption()
3181 * @see getIntOption()
3182 */
3183 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
3184 global $wgHiddenPrefs;
3185 $this->loadOptions();
3186
3187 # We want 'disabled' preferences to always behave as the default value for
3188 # users, even if they have set the option explicitly in their settings (ie they
3189 # set it, and then it was disabled removing their ability to change it). But
3190 # we don't want to erase the preferences in the database in case the preference
3191 # is re-enabled again. So don't touch $mOptions, just override the returned value
3192 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
3193 return self::getDefaultOption( $oname );
3194 }
3195
3196 if ( array_key_exists( $oname, $this->mOptions ) ) {
3197 return $this->mOptions[$oname];
3198 }
3199
3200 return $defaultOverride;
3201 }
3202
3203 /**
3204 * Get all user's options
3205 *
3206 * @param int $flags Bitwise combination of:
3207 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
3208 * to the default value. (Since 1.25)
3209 * @return array
3210 */
3211 public function getOptions( $flags = 0 ) {
3212 global $wgHiddenPrefs;
3213 $this->loadOptions();
3214 $options = $this->mOptions;
3215
3216 # We want 'disabled' preferences to always behave as the default value for
3217 # users, even if they have set the option explicitly in their settings (ie they
3218 # set it, and then it was disabled removing their ability to change it). But
3219 # we don't want to erase the preferences in the database in case the preference
3220 # is re-enabled again. So don't touch $mOptions, just override the returned value
3221 foreach ( $wgHiddenPrefs as $pref ) {
3222 $default = self::getDefaultOption( $pref );
3223 if ( $default !== null ) {
3224 $options[$pref] = $default;
3225 }
3226 }
3227
3228 if ( $flags & self::GETOPTIONS_EXCLUDE_DEFAULTS ) {
3229 $options = array_diff_assoc( $options, self::getDefaultOptions() );
3230 }
3231
3232 return $options;
3233 }
3234
3235 /**
3236 * Get the user's current setting for a given option, as a boolean value.
3237 *
3238 * @param string $oname The option to check
3239 * @return bool User's current value for the option
3240 * @see getOption()
3241 */
3242 public function getBoolOption( $oname ) {
3243 return (bool)$this->getOption( $oname );
3244 }
3245
3246 /**
3247 * Get the user's current setting for a given option, as an integer value.
3248 *
3249 * @param string $oname The option to check
3250 * @param int $defaultOverride A default value returned if the option does not exist
3251 * @return int User's current value for the option
3252 * @see getOption()
3253 */
3254 public function getIntOption( $oname, $defaultOverride = 0 ) {
3255 $val = $this->getOption( $oname );
3256 if ( $val == '' ) {
3257 $val = $defaultOverride;
3258 }
3259 return intval( $val );
3260 }
3261
3262 /**
3263 * Set the given option for a user.
3264 *
3265 * You need to call saveSettings() to actually write to the database.
3266 *
3267 * @param string $oname The option to set
3268 * @param mixed $val New value to set
3269 */
3270 public function setOption( $oname, $val ) {
3271 $this->loadOptions();
3272
3273 // Explicitly NULL values should refer to defaults
3274 if ( is_null( $val ) ) {
3275 $val = self::getDefaultOption( $oname );
3276 }
3277
3278 $this->mOptions[$oname] = $val;
3279 }
3280
3281 /**
3282 * Get a token stored in the preferences (like the watchlist one),
3283 * resetting it if it's empty (and saving changes).
3284 *
3285 * @param string $oname The option name to retrieve the token from
3286 * @return string|bool User's current value for the option, or false if this option is disabled.
3287 * @see resetTokenFromOption()
3288 * @see getOption()
3289 * @deprecated since 1.26 Applications should use the OAuth extension
3290 */
3291 public function getTokenFromOption( $oname ) {
3292 global $wgHiddenPrefs;
3293
3294 $id = $this->getId();
3295 if ( !$id || in_array( $oname, $wgHiddenPrefs ) ) {
3296 return false;
3297 }
3298
3299 $token = $this->getOption( $oname );
3300 if ( !$token ) {
3301 // Default to a value based on the user token to avoid space
3302 // wasted on storing tokens for all users. When this option
3303 // is set manually by the user, only then is it stored.
3304 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3305 }
3306
3307 return $token;
3308 }
3309
3310 /**
3311 * Reset a token stored in the preferences (like the watchlist one).
3312 * *Does not* save user's preferences (similarly to setOption()).
3313 *
3314 * @param string $oname The option name to reset the token in
3315 * @return string|bool New token value, or false if this option is disabled.
3316 * @see getTokenFromOption()
3317 * @see setOption()
3318 */
3319 public function resetTokenFromOption( $oname ) {
3320 global $wgHiddenPrefs;
3321 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3322 return false;
3323 }
3324
3325 $token = MWCryptRand::generateHex( 40 );
3326 $this->setOption( $oname, $token );
3327 return $token;
3328 }
3329
3330 /**
3331 * Return a list of the types of user options currently returned by
3332 * User::getOptionKinds().
3333 *
3334 * Currently, the option kinds are:
3335 * - 'registered' - preferences which are registered in core MediaWiki or
3336 * by extensions using the UserGetDefaultOptions hook.
3337 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3338 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3339 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3340 * be used by user scripts.
3341 * - 'special' - "preferences" that are not accessible via User::getOptions
3342 * or User::setOptions.
3343 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3344 * These are usually legacy options, removed in newer versions.
3345 *
3346 * The API (and possibly others) use this function to determine the possible
3347 * option types for validation purposes, so make sure to update this when a
3348 * new option kind is added.
3349 *
3350 * @see User::getOptionKinds
3351 * @return array Option kinds
3352 */
3353 public static function listOptionKinds() {
3354 return [
3355 'registered',
3356 'registered-multiselect',
3357 'registered-checkmatrix',
3358 'userjs',
3359 'special',
3360 'unused'
3361 ];
3362 }
3363
3364 /**
3365 * Return an associative array mapping preferences keys to the kind of a preference they're
3366 * used for. Different kinds are handled differently when setting or reading preferences.
3367 *
3368 * See User::listOptionKinds for the list of valid option types that can be provided.
3369 *
3370 * @see User::listOptionKinds
3371 * @param IContextSource $context
3372 * @param array|null $options Assoc. array with options keys to check as keys.
3373 * Defaults to $this->mOptions.
3374 * @return array The key => kind mapping data
3375 */
3376 public function getOptionKinds( IContextSource $context, $options = null ) {
3377 $this->loadOptions();
3378 if ( $options === null ) {
3379 $options = $this->mOptions;
3380 }
3381
3382 $preferencesFactory = MediaWikiServices::getInstance()->getPreferencesFactory();
3383 $prefs = $preferencesFactory->getFormDescriptor( $this, $context );
3384 $mapping = [];
3385
3386 // Pull out the "special" options, so they don't get converted as
3387 // multiselect or checkmatrix.
3388 $specialOptions = array_fill_keys( $preferencesFactory->getSaveBlacklist(), true );
3389 foreach ( $specialOptions as $name => $value ) {
3390 unset( $prefs[$name] );
3391 }
3392
3393 // Multiselect and checkmatrix options are stored in the database with
3394 // one key per option, each having a boolean value. Extract those keys.
3395 $multiselectOptions = [];
3396 foreach ( $prefs as $name => $info ) {
3397 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3398 ( isset( $info['class'] ) && $info['class'] == HTMLMultiSelectField::class ) ) {
3399 $opts = HTMLFormField::flattenOptions( $info['options'] );
3400 $prefix = $info['prefix'] ?? $name;
3401
3402 foreach ( $opts as $value ) {
3403 $multiselectOptions["$prefix$value"] = true;
3404 }
3405
3406 unset( $prefs[$name] );
3407 }
3408 }
3409 $checkmatrixOptions = [];
3410 foreach ( $prefs as $name => $info ) {
3411 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3412 ( isset( $info['class'] ) && $info['class'] == HTMLCheckMatrix::class ) ) {
3413 $columns = HTMLFormField::flattenOptions( $info['columns'] );
3414 $rows = HTMLFormField::flattenOptions( $info['rows'] );
3415 $prefix = $info['prefix'] ?? $name;
3416
3417 foreach ( $columns as $column ) {
3418 foreach ( $rows as $row ) {
3419 $checkmatrixOptions["$prefix$column-$row"] = true;
3420 }
3421 }
3422
3423 unset( $prefs[$name] );
3424 }
3425 }
3426
3427 // $value is ignored
3428 foreach ( $options as $key => $value ) {
3429 if ( isset( $prefs[$key] ) ) {
3430 $mapping[$key] = 'registered';
3431 } elseif ( isset( $multiselectOptions[$key] ) ) {
3432 $mapping[$key] = 'registered-multiselect';
3433 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3434 $mapping[$key] = 'registered-checkmatrix';
3435 } elseif ( isset( $specialOptions[$key] ) ) {
3436 $mapping[$key] = 'special';
3437 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3438 $mapping[$key] = 'userjs';
3439 } else {
3440 $mapping[$key] = 'unused';
3441 }
3442 }
3443
3444 return $mapping;
3445 }
3446
3447 /**
3448 * Reset certain (or all) options to the site defaults
3449 *
3450 * The optional parameter determines which kinds of preferences will be reset.
3451 * Supported values are everything that can be reported by getOptionKinds()
3452 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3453 *
3454 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3455 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3456 * for backwards-compatibility.
3457 * @param IContextSource|null $context Context source used when $resetKinds
3458 * does not contain 'all', passed to getOptionKinds().
3459 * Defaults to RequestContext::getMain() when null.
3460 */
3461 public function resetOptions(
3462 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3463 IContextSource $context = null
3464 ) {
3465 $this->load();
3466 $defaultOptions = self::getDefaultOptions();
3467
3468 if ( !is_array( $resetKinds ) ) {
3469 $resetKinds = [ $resetKinds ];
3470 }
3471
3472 if ( in_array( 'all', $resetKinds ) ) {
3473 $newOptions = $defaultOptions;
3474 } else {
3475 if ( $context === null ) {
3476 $context = RequestContext::getMain();
3477 }
3478
3479 $optionKinds = $this->getOptionKinds( $context );
3480 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
3481 $newOptions = [];
3482
3483 // Use default values for the options that should be deleted, and
3484 // copy old values for the ones that shouldn't.
3485 foreach ( $this->mOptions as $key => $value ) {
3486 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3487 if ( array_key_exists( $key, $defaultOptions ) ) {
3488 $newOptions[$key] = $defaultOptions[$key];
3489 }
3490 } else {
3491 $newOptions[$key] = $value;
3492 }
3493 }
3494 }
3495
3496 Hooks::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions, $resetKinds ] );
3497
3498 $this->mOptions = $newOptions;
3499 $this->mOptionsLoaded = true;
3500 }
3501
3502 /**
3503 * Get the user's preferred date format.
3504 * @return string User's preferred date format
3505 */
3506 public function getDatePreference() {
3507 // Important migration for old data rows
3508 if ( is_null( $this->mDatePreference ) ) {
3509 global $wgLang;
3510 $value = $this->getOption( 'date' );
3511 $map = $wgLang->getDatePreferenceMigrationMap();
3512 if ( isset( $map[$value] ) ) {
3513 $value = $map[$value];
3514 }
3515 $this->mDatePreference = $value;
3516 }
3517 return $this->mDatePreference;
3518 }
3519
3520 /**
3521 * Determine based on the wiki configuration and the user's options,
3522 * whether this user must be over HTTPS no matter what.
3523 *
3524 * @return bool
3525 */
3526 public function requiresHTTPS() {
3527 global $wgSecureLogin;
3528 if ( !$wgSecureLogin ) {
3529 return false;
3530 }
3531
3532 $https = $this->getBoolOption( 'prefershttps' );
3533 Hooks::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3534 if ( $https ) {