Debian Codegraph @

includes/user/User.php

raw symbols SCIP
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 namespace MediaWiki\User;
24
25 use AllowDynamicProperties;
26 use ArrayIterator;
27 use BadMethodCallException;
28 use InvalidArgumentException;
29 use MailAddress;
30 use MediaWiki\Auth\AuthenticationRequest;
31 use MediaWiki\Auth\AuthManager;
32 use MediaWiki\Block\AbstractBlock;
33 use MediaWiki\Block\Block;
34 use MediaWiki\Block\SystemBlock;
35 use MediaWiki\Context\RequestContext;
36 use MediaWiki\DAO\WikiAwareEntityTrait;
37 use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
38 use MediaWiki\Logger\LoggerFactory;
39 use MediaWiki\Mail\UserEmailContact;
40 use MediaWiki\MainConfigNames;
41 use MediaWiki\MainConfigSchema;
42 use MediaWiki\MediaWikiServices;
43 use MediaWiki\Page\PageIdentity;
44 use MediaWiki\Parser\Sanitizer;
45 use MediaWiki\Password\PasswordFactory;
46 use MediaWiki\Password\UserPasswordPolicy;
47 use MediaWiki\Permissions\Authority;
48 use MediaWiki\Permissions\PermissionStatus;
49 use MediaWiki\Permissions\RateLimitSubject;
50 use MediaWiki\Permissions\UserAuthority;
51 use MediaWiki\Request\WebRequest;
52 use MediaWiki\Session\SessionManager;
53 use MediaWiki\Session\Token;
54 use MediaWiki\Status\Status;
55 use MediaWiki\Title\Title;
56 use MWCryptHash;
57 use MWCryptRand;
58 use MWExceptionHandler;
59 use RuntimeException;
60 use stdClass;
61 use Stringable;
62 use UnexpectedValueException;
63 use Wikimedia\Assert\Assert;
64 use Wikimedia\Assert\PreconditionException;
65 use Wikimedia\DebugInfo\DebugInfoTrait;
66 use Wikimedia\IPUtils;
67 use Wikimedia\ObjectCache\WANObjectCache;
68 use Wikimedia\Rdbms\Database;
69 use Wikimedia\Rdbms\DBAccessObjectUtils;
70 use Wikimedia\Rdbms\DBExpectedError;
71 use Wikimedia\Rdbms\IDatabase;
72 use Wikimedia\Rdbms\IDBAccessObject;
73 use Wikimedia\Rdbms\IReadableDatabase;
74 use Wikimedia\Rdbms\SelectQueryBuilder;
75 use Wikimedia\ScopedCallback;
76 use Wikimedia\Timestamp\ConvertibleTimestamp;
77
78 /**
79 * The User object encapsulates all of the user-specific settings (user_id,
80 * name, rights, email address, options, last login time). Client
81 * classes use the getXXX() functions to access these fields. These functions
82 * do all the work of determining whether the user is logged in,
83 * whether the requested option can be satisfied from cookies or
84 * whether a database query is needed. Most of the settings needed
85 * for rendering normal pages are set in the cookie to minimize use
86 * of the database.
87 *
88 * @note User implements Authority to ease transition. Always prefer
89 * using existing Authority or obtaining a proper Authority implementation.
90 *
91 * @note {@}newable in 1.35 only, the constructor is {@}internal since 1.36
92 */
93 #[AllowDynamicProperties]
94 class User implements Stringable, Authority, UserIdentity, UserEmailContact {
95 use DebugInfoTrait;
96 use ProtectedHookAccessorTrait;
97 use WikiAwareEntityTrait;
98
99 /**
100 * @see IDBAccessObject::READ_EXCLUSIVE
101 */
102 public const READ_EXCLUSIVE = IDBAccessObject::READ_EXCLUSIVE;
103
104 /**
105 * @see IDBAccessObject::READ_LOCKING
106 */
107 public const READ_LOCKING = IDBAccessObject::READ_LOCKING;
108
109 /**
110 * Number of characters required for the user_token field.
111 */
112 public const TOKEN_LENGTH = 32;
113
114 /**
115 * An invalid string value for the user_token field.
116 */
117 public const INVALID_TOKEN = '*** INVALID ***';
118
119 /**
120 * Version number to tag cached versions of serialized User objects. Should be increased when
121 * {@link $mCacheVars} or one of its members changes.
122 */
123 private const VERSION = 17;
124
125 /**
126 * Username used for various maintenance scripts.
127 * @since 1.37
128 */
129 public const MAINTENANCE_SCRIPT_USER = 'Maintenance script';
130
131 /**
132 * List of member variables which are saved to the
133 * shared cache (memcached). Any operation which changes the
134 * corresponding database fields must call a cache-clearing function.
135 * @showinitializer
136 * @var string[]
137 */
138 protected static $mCacheVars = [
139 // user table
140 'mId',
141 'mName',
142 'mRealName',
143 'mEmail',
144 'mTouched',
145 'mToken',
146 'mEmailAuthenticated',
147 'mEmailToken',
148 'mEmailTokenExpires',
149 'mRegistration',
150 // actor table
151 'mActorId',
152 ];
153
154 /** Cache variables */
155 // Some of these are public, including for use by the UserFactory, but they generally
156 // should not be set manually
157 // @{
158 /** @var int */
159 public $mId;
160 /** @var string */
161 public $mName;
162 /**
163 * Switched from protected to public for use in UserFactory
164 *
165 * @var int|null
166 */
167 public $mActorId;
168 /** @var string */
169 public $mRealName;
170
171 /** @var string */
172 public $mEmail;
173 /** @var string TS_MW timestamp from the DB */
174 public $mTouched;
175 /** @var string|null TS_MW timestamp from cache */
176 protected $mQuickTouched;
177 /** @var string|null */
178 protected $mToken;
179 /** @var string|null */
180 public $mEmailAuthenticated;
181 /** @var string|null */
182 protected $mEmailToken;
183 /** @var string|null */
184 protected $mEmailTokenExpires;
185 /** @var string|null */
186 protected $mRegistration;
187 // @}
188
189 // @{
190 /**
191 * @var array|bool Array with already loaded items or true if all items have been loaded.
192 */
193 protected $mLoadedItems = [];
194 // @}
195
196 /**
197 * @var string Initialization data source if mLoadedItems!==true. May be one of:
198 * - 'defaults' anonymous user initialised from class defaults
199 * - 'name' initialise from mName
200 * - 'id' initialise from mId
201 * - 'actor' initialise from mActorId
202 * - 'session' log in from session if possible
203 *
204 * Use the User::newFrom*() family of functions to set this.
205 */
206 public $mFrom;
207
208 /**
209 * Lazy-initialized variables, invalidated with clearInstanceCache
210 */
211 /** @var string|null */
212 protected $mDatePreference;
213 /** @var string|false */
214 protected $mHash;
215 /** @var AbstractBlock */
216 protected $mGlobalBlock;
217 /** @var bool */
218 protected $mLocked;
219
220 /** @var WebRequest|null */
221 private $mRequest;
222
223 /** @var int IDBAccessObject::READ_* constant bitfield used to load data */
224 protected $queryFlagsUsed = IDBAccessObject::READ_NORMAL;
225
226 /**
227 * @var UserAuthority|null lazy-initialized Authority of this user
228 * @noVarDump
229 */
230 private $mThisAsAuthority;
231
232 /** @var bool|null */
233 private $isTemp;
234
235 /**
236 * Lightweight constructor for an anonymous user.
237 *
238 * @stable to call since 1.35
239 * @internal since 1.36, use the UserFactory service instead
240 *
241 * @see MediaWiki\User\UserFactory
242 *
243 * @see newFromName()
244 * @see newFromId()
245 * @see newFromActorId()
246 * @see newFromConfirmationCode()
247 * @see newFromSession()
248 * @see newFromRow()
249 */
250 public function __construct() {
251 $this->clearInstanceCache( 'defaults' );
252 }
253
254 /**
255 * Returns self::LOCAL to indicate the user is associated with the local wiki.
256 *
257 * @since 1.36
258 * @return string|false
259 */
260 public function getWikiId() {
261 return self::LOCAL;
262 }
263
264 /**
265 * @return string
266 */
267 public function __toString() {
268 return $this->getName();
269 }
270
271 public function &__get( $name ) {
272 // A shortcut for $mRights deprecation phase
273 if ( $name === 'mRights' ) {
274 // hard deprecated since 1.40
275 wfDeprecated( 'User::$mRights', '1.34' );
276 $copy = MediaWikiServices::getInstance()
277 ->getPermissionManager()
278 ->getUserPermissions( $this );
279 return $copy;
280 } elseif ( !property_exists( $this, $name ) ) {
281 // T227688 - do not break $u->foo['bar'] = 1
282 wfLogWarning( 'tried to get non-existent property' );
283 $this->$name = null;
284 return $this->$name;
285 } else {
286 wfLogWarning( 'tried to get non-visible property' );
287 $null = null;
288 return $null;
289 }
290 }
291
292 public function __set( $name, $value ) {
293 // A shortcut for $mRights deprecation phase, only known legitimate use was for
294 // testing purposes, other uses seem bad in principle
295 if ( $name === 'mRights' ) {
296 // hard deprecated since 1.40
297 wfDeprecated( 'User::$mRights', '1.34' );
298 MediaWikiServices::getInstance()->getPermissionManager()->overrideUserRightsForTesting(
299 $this,
300 $value ?? []
301 );
302 } elseif ( !property_exists( $this, $name ) ) {
303 $this->$name = $value;
304 } else {
305 wfLogWarning( 'tried to set non-visible property' );
306 }
307 }
308
309 public function __sleep(): array {
310 return array_diff(
311 array_keys( get_object_vars( $this ) ),
312 [
313 'mThisAsAuthority' // memoization, will be recreated on demand.
314 ]
315 );
316 }
317
318 /**
319 * Test if it's safe to load this User object.
320 *
321 * You should typically check this before using $wgUser or
322 * RequestContext::getUser in a method that might be called before the
323 * system has been fully initialized. If the object is unsafe, you should
324 * use an anonymous user:
325 * \code
326 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
327 * \endcode
328 *
329 * @since 1.27
330 * @return bool
331 */
332 public function isSafeToLoad() {
333 global $wgFullyInitialised;
334
335 // The user is safe to load if:
336 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
337 // * mLoadedItems === true (already loaded)
338 // * mFrom !== 'session' (sessions not involved at all)
339
340 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
341 $this->mLoadedItems === true || $this->mFrom !== 'session';
342 }
343
344 /**
345 * Load the user table data for this object from the source given by mFrom.
346 *
347 * @param int $flags IDBAccessObject::READ_* constant bitfield
348 */
349 public function load( $flags = IDBAccessObject::READ_NORMAL ) {
350 global $wgFullyInitialised;
351
352 if ( $this->mLoadedItems === true ) {
353 return;
354 }
355
356 // Set it now to avoid infinite recursion in accessors
357 $oldLoadedItems = $this->mLoadedItems;
358 $this->mLoadedItems = true;
359 $this->queryFlagsUsed = $flags;
360
361 // If this is called too early, things are likely to break.
362 if ( !$wgFullyInitialised && $this->mFrom === 'session' ) {
363 LoggerFactory::getInstance( 'session' )
364 ->warning( 'User::loadFromSession called before the end of Setup.php', [
365 'exception' => new RuntimeException(
366 'User::loadFromSession called before the end of Setup.php'
367 ),
368 ] );
369 $this->loadDefaults();
370 $this->mLoadedItems = $oldLoadedItems;
371 return;
372 } elseif ( $this->mFrom === 'session'
373 && defined( 'MW_NO_SESSION' ) && MW_NO_SESSION !== 'warn'
374 ) {
375 // Even though we are throwing an exception, make sure the User object is left in a
376 // clean state as sometimes these exceptions are caught and the object accessed again.
377 $this->loadDefaults();
378 $this->mLoadedItems = $oldLoadedItems;
379 $ep = defined( 'MW_ENTRY_POINT' ) ? MW_ENTRY_POINT : 'this';
380 throw new BadMethodCallException( "Sessions are disabled for $ep entry point" );
381 }
382
383 switch ( $this->mFrom ) {
384 case 'defaults':
385 $this->loadDefaults();
386 break;
387 case 'id':
388 // Make sure this thread sees its own changes, if the ID isn't 0
389 if ( $this->mId != 0 ) {
390 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
391 if ( $lb->hasOrMadeRecentPrimaryChanges() ) {
392 $flags |= IDBAccessObject::READ_LATEST;
393 $this->queryFlagsUsed = $flags;
394 }
395 }
396
397 $this->loadFromId( $flags );
398 break;
399 case 'actor':
400 case 'name':
401 // Make sure this thread sees its own changes
402 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
403 if ( $lb->hasOrMadeRecentPrimaryChanges() ) {
404 $flags |= IDBAccessObject::READ_LATEST;
405 $this->queryFlagsUsed = $flags;
406 }
407
408 $dbr = DBAccessObjectUtils::getDBFromRecency(
409 MediaWikiServices::getInstance()->getDBLoadBalancerFactory(),
410 $flags
411 );
412 $queryBuilder = $dbr->newSelectQueryBuilder()
413 ->select( [ 'actor_id', 'actor_user', 'actor_name' ] )
414 ->from( 'actor' )
415 ->recency( $flags );
416 if ( $this->mFrom === 'name' ) {
417 // make sure to use normalized form of IP for anonymous users
418 $queryBuilder->where( [ 'actor_name' => IPUtils::sanitizeIP( $this->mName ) ] );
419 } else {
420 $queryBuilder->where( [ 'actor_id' => $this->mActorId ] );
421 }
422 $row = $queryBuilder->caller( __METHOD__ )->fetchRow();
423
424 if ( !$row ) {
425 // Ugh.
426 $this->loadDefaults( $this->mFrom === 'name' ? $this->mName : false );
427 } elseif ( $row->actor_user ) {
428 $this->mId = $row->actor_user;
429 $this->loadFromId( $flags );
430 } else {
431 $this->loadDefaults( $row->actor_name, $row->actor_id );
432 }
433 break;
434 case 'session':
435 if ( !$this->loadFromSession() ) {
436 // Loading from session failed. Load defaults.
437 $this->loadDefaults();
438 }
439 $this->getHookRunner()->onUserLoadAfterLoadFromSession( $this );
440 break;
441 default:
442 throw new UnexpectedValueException(
443 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
444 }
445 }
446
447 /**
448 * Load user table data, given mId has already been set.
449 * @param int $flags IDBAccessObject::READ_* constant bitfield
450 * @return bool False if the ID does not exist, true otherwise
451 */
452 public function loadFromId( $flags = IDBAccessObject::READ_NORMAL ) {
453 if ( $this->mId == 0 ) {
454 // Anonymous users are not in the database (don't need cache)
455 $this->loadDefaults();
456 return false;
457 }
458
459 // Try cache (unless this needs data from the primary DB).
460 // NOTE: if this thread called saveSettings(), the cache was cleared.
461 $latest = DBAccessObjectUtils::hasFlags( $flags, IDBAccessObject::READ_LATEST );
462 if ( $latest ) {
463 if ( !$this->loadFromDatabase( $flags ) ) {
464 // Can't load from ID
465 return false;
466 }
467 } else {
468 $this->loadFromCache();
469 }
470
471 $this->mLoadedItems = true;
472 $this->queryFlagsUsed = $flags;
473
474 return true;
475 }
476
477 /**
478 * @since 1.27
479 * @param string $dbDomain
480 * @param int $userId
481 */
482 public static function purge( $dbDomain, $userId ) {
483 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
484 $key = $cache->makeGlobalKey( 'user', 'id', $dbDomain, $userId );
485 $cache->delete( $key );
486 }
487
488 /**
489 * @since 1.27
490 * @param WANObjectCache $cache
491 * @return string
492 */
493 protected function getCacheKey( WANObjectCache $cache ) {
494 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
495
496 return $cache->makeGlobalKey( 'user', 'id',
497 $lbFactory->getLocalDomainID(), $this->mId );
498 }
499
500 /**
501 * Load user data from shared cache, given mId has already been set.
502 *
503 * @return bool True
504 * @since 1.25
505 */
506 protected function loadFromCache() {
507 global $wgFullyInitialised;
508
509 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
510 $data = $cache->getWithSetCallback(
511 $this->getCacheKey( $cache ),
512 $cache::TTL_HOUR,
513 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache, $wgFullyInitialised ) {
514 $setOpts += Database::getCacheSetOptions(
515 MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase()
516 );
517 wfDebug( "User: cache miss for user {$this->mId}" );
518
519 $this->loadFromDatabase( IDBAccessObject::READ_NORMAL );
520
521 $data = [];
522 foreach ( self::$mCacheVars as $name ) {
523 $data[$name] = $this->$name;
524 }
525
526 $ttl = $cache->adaptiveTTL(
527 (int)wfTimestamp( TS_UNIX, $this->mTouched ),
528 $ttl
529 );
530
531 if ( $wgFullyInitialised ) {
532 $groupMemberships = MediaWikiServices::getInstance()
533 ->getUserGroupManager()
534 ->getUserGroupMemberships( $this, $this->queryFlagsUsed );
535
536 // if a user group membership is about to expire, the cache needs to
537 // expire at that time (T163691)
538 foreach ( $groupMemberships as $ugm ) {
539 if ( $ugm->getExpiry() ) {
540 $secondsUntilExpiry =
541 (int)wfTimestamp( TS_UNIX, $ugm->getExpiry() ) - time();
542
543 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
544 $ttl = $secondsUntilExpiry;
545 }
546 }
547 }
548 }
549
550 return $data;
551 },
552 [ 'pcTTL' => $cache::TTL_PROC_LONG, 'version' => self::VERSION ]
553 );
554
555 // Restore from cache
556 foreach ( self::$mCacheVars as $name ) {
557 $this->$name = $data[$name];
558 }
559
560 return true;
561 }
562
563 /***************************************************************************/
564 // region newFrom*() static factory methods
565 /** @name newFrom*() static factory methods
566 * @{
567 */
568
569 /**
570 * @see UserFactory::newFromName
571 *
572 * @deprecated since 1.36, use a UserFactory instead
573 *
574 * This is slightly less efficient than newFromId(), so use newFromId() if
575 * you have both an ID and a name handy.
576 *
577 * @param string $name Username, validated by Title::newFromText()
578 * @param string|bool $validate Validate username.Type of validation to use:
579 * - false No validation
580 * - 'valid' Valid for batch processes
581 * - 'usable' Valid for batch processes and login
582 * - 'creatable' Valid for batch processes, login and account creation,
583 * except that true is accepted as an alias for 'valid', for BC.
584 *
585 * @return User|false User object, or false if the username is invalid
586 * (e.g. if it contains illegal characters or is an IP address). If the
587 * username is not present in the database, the result will be a user object
588 * with a name, zero user ID and default settings.
589 */
590 public static function newFromName( $name, $validate = 'valid' ) {
591 // Backwards compatibility with strings / false
592 $validationLevels = [
593 'valid' => UserRigorOptions::RIGOR_VALID,
594 'usable' => UserRigorOptions::RIGOR_USABLE,
595 'creatable' => UserRigorOptions::RIGOR_CREATABLE
596 ];
597 if ( $validate === true ) {
598 $validate = 'valid';
599 }
600 if ( $validate === false ) {
601 $validation = UserRigorOptions::RIGOR_NONE;
602 } elseif ( array_key_exists( $validate, $validationLevels ) ) {
603 $validation = $validationLevels[ $validate ];
604 } else {
605 // Not a recognized value, probably a test for unsupported validation
606 // levels, regardless, just pass it along
607 $validation = $validate;
608 }
609
610 return MediaWikiServices::getInstance()->getUserFactory()
611 ->newFromName( (string)$name, $validation ) ?? false;
612 }
613
614 /**
615 * Static factory method for creation from a given user ID.
616 *
617 * @see UserFactory::newFromId
618 *
619 * @deprecated since 1.36, use a UserFactory instead
620 *
621 * @param int $id Valid user ID
622 * @return User
623 */
624 public static function newFromId( $id ) {
625 return MediaWikiServices::getInstance()
626 ->getUserFactory()
627 ->newFromId( (int)$id );
628 }
629
630 /**
631 * Static factory method for creation from a given actor ID.
632 *
633 * @see UserFactory::newFromActorId
634 *
635 * @deprecated since 1.36, use a UserFactory instead
636 *
637 * @since 1.31
638 * @param int $id Valid actor ID
639 * @return User
640 */
641 public static function newFromActorId( $id ) {
642 return MediaWikiServices::getInstance()
643 ->getUserFactory()
644 ->newFromActorId( (int)$id );
645 }
646
647 /**
648 * Returns a User object corresponding to the given UserIdentity.
649 *
650 * @see UserFactory::newFromUserIdentity
651 *
652 * @deprecated since 1.36, use a UserFactory instead
653 *
654 * @since 1.32
655 *
656 * @param UserIdentity $identity
657 *
658 * @return User
659 */
660 public static function newFromIdentity( UserIdentity $identity ) {
661 // Don't use the service if we already have a User object,
662 // so that User::newFromIdentity calls don't break things in unit tests.
663 if ( $identity instanceof User ) {
664 return $identity;
665 }
666
667 return MediaWikiServices::getInstance()
668 ->getUserFactory()
669 ->newFromUserIdentity( $identity );
670 }
671
672 /**
673 * Static factory method for creation from an ID, name, and/or actor ID
674 *
675 * This does not check that the ID, name, and actor ID all correspond to
676 * the same user.
677 *
678 * @see UserFactory::newFromAnyId
679 *
680 * @deprecated since 1.36, use a UserFactory instead
681 *
682 * @since 1.31
683 * @param int|null $userId User ID, if known
684 * @param string|null $userName User name, if known
685 * @param int|null $actorId Actor ID, if known
686 * @param string|false $dbDomain remote wiki to which the User/Actor ID
687 * applies, or false if none
688 * @return User
689 */
690 public static function newFromAnyId( $userId, $userName, $actorId, $dbDomain = false ) {
691 return MediaWikiServices::getInstance()
692 ->getUserFactory()
693 ->newFromAnyId( $userId, $userName, $actorId, $dbDomain );
694 }
695
696 /**
697 * Factory method to fetch whichever user has a given email confirmation code.
698 * This code is generated when an account is created or its e-mail address
699 * has changed.
700 *
701 * If the code is invalid or has expired, returns NULL.
702 *
703 * @see UserFactory::newFromConfirmationCode
704 *
705 * @deprecated since 1.36, use a UserFactory instead
706 *
707 * @param string $code Confirmation code
708 * @param int $flags IDBAccessObject::READ_* bitfield
709 * @return User|null
710 */
711 public static function newFromConfirmationCode( $code, $flags = IDBAccessObject::READ_NORMAL ) {
712 return MediaWikiServices::getInstance()
713 ->getUserFactory()
714 ->newFromConfirmationCode( (string)$code, $flags );
715 }
716
717 /**
718 * Create a new user object using data from session. If the login
719 * credentials are invalid, the result is an anonymous user.
720 *
721 * @param WebRequest|null $request Object to use; the global request will be used if omitted.
722 * @return User
723 */
724 public static function newFromSession( ?WebRequest $request = null ) {
725 $user = new User;
726 $user->mFrom = 'session';
727 $user->mRequest = $request;
728 return $user;
729 }
730
731 /**
732 * Create a new user object from a user row.
733 * The row should have the following fields from the user table in it:
734 * - either user_name or user_id to load further data if needed (or both)
735 * - user_real_name
736 * - all other fields (email, etc.)
737 * It is useless to provide the remaining fields if either user_id,
738 * user_name and user_real_name are not provided because the whole row
739 * will be loaded once more from the database when accessing them.
740 *
741 * @param stdClass $row A row from the user table
742 * @param array|null $data Further data to load into the object
743 * (see User::loadFromRow for valid keys)
744 * @return User
745 */
746 public static function newFromRow( $row, $data = null ) {
747 $user = new User;
748 $user->loadFromRow( $row, $data );
749 return $user;
750 }
751
752 /**
753 * Static factory method for creation of a "system" user from username.
754 *
755 * A "system" user is an account that's used to attribute logged actions
756 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
757 * might include the 'Maintenance script' or 'Conversion script' accounts
758 * used by various scripts in the maintenance/ directory or accounts such
759 * as 'MediaWiki message delivery' used by the MassMessage extension.
760 *
761 * This can optionally create the user if it doesn't exist, and "steal" the
762 * account if it does exist.
763 *
764 * "Stealing" an existing user is intended to make it impossible for normal
765 * authentication processes to use the account, effectively disabling the
766 * account for normal use:
767 * - Email is invalidated, to prevent account recovery by emailing a
768 * temporary password and to disassociate the account from the existing
769 * human.
770 * - The token is set to a magic invalid value, to kill existing sessions
771 * and to prevent $this->setToken() calls from resetting the token to a
772 * valid value.
773 * - SessionManager is instructed to prevent new sessions for the user, to
774 * do things like deauthorizing OAuth consumers.
775 * - AuthManager is instructed to revoke access, to invalidate or remove
776 * passwords and other credentials.
777 *
778 * System users should usually be listed in $wgReservedUsernames.
779 *
780 * @param string $name Username
781 * @param array $options Options are:
782 * - validate: Type of validation to use:
783 * - false No validation
784 * - 'valid' Valid for batch processes
785 * - 'usable' Valid for batch processes and login
786 * - 'creatable' Valid for batch processes, login and account creation,
787 * default 'valid'. Deprecated since 1.36.
788 * - create: Whether to create the user if it doesn't already exist, default true
789 * - steal: Whether to "disable" the account for normal use if it already
790 * exists, default false
791 * @return User|null
792 * @since 1.27
793 * @see self::isSystemUser()
794 * @see MainConfigSchema::ReservedUsernames
795 */
796 public static function newSystemUser( $name, $options = [] ) {
797 $options += [
798 'validate' => UserRigorOptions::RIGOR_VALID,
799 'create' => true,
800 'steal' => false,
801 ];
802
803 // Username validation
804 // Backwards compatibility with strings / false
805 $validationLevels = [
806 'valid' => UserRigorOptions::RIGOR_VALID,
807 'usable' => UserRigorOptions::RIGOR_USABLE,
808 'creatable' => UserRigorOptions::RIGOR_CREATABLE
809 ];
810 $validate = $options['validate'];
811
812 // @phan-suppress-next-line PhanSuspiciousValueComparison
813 if ( $validate === false ) {
814 $validation = UserRigorOptions::RIGOR_NONE;
815 } elseif ( array_key_exists( $validate, $validationLevels ) ) {
816 $validation = $validationLevels[ $validate ];
817 } else {
818 // Not a recognized value, probably a test for unsupported validation
819 // levels, regardless, just pass it along
820 $validation = $validate;
821 }
822
823 if ( $validation !== UserRigorOptions::RIGOR_VALID ) {
824 wfDeprecatedMsg(
825 __METHOD__ . ' options["validation"] parameter must be omitted or set to "valid".',
826 '1.36'
827 );
828 }
829 $services = MediaWikiServices::getInstance();
830 $userNameUtils = $services->getUserNameUtils();
831
832 $name = $userNameUtils->getCanonical( (string)$name, $validation );
833 if ( $name === false ) {
834 return null;
835 }
836
837 $dbProvider = $services->getDBLoadBalancerFactory();
838 $dbr = $dbProvider->getReplicaDatabase();
839
840 $userQuery = self::newQueryBuilder( $dbr )
841 ->where( [ 'user_name' => $name ] )
842 ->caller( __METHOD__ );
843 $row = $userQuery->fetchRow();
844 if ( !$row ) {
845 // Try the primary database
846 $userQuery->connection( $dbProvider->getPrimaryDatabase() );
847 // Lock the row to prevent insertNewUser() returning null due to race conditions
848 $userQuery->forUpdate();
849 $row = $userQuery->fetchRow();
850 }
851
852 if ( !$row ) {
853 // No user. Create it?
854 // @phan-suppress-next-line PhanImpossibleCondition
855 if ( !$options['create'] ) {
856 // No.
857 return null;
858 }
859
860 // If it's a reserved user that had an anonymous actor created for it at
861 // some point, we need special handling.
862 return self::insertNewUser( static function ( UserIdentity $actor, IDatabase $dbw ) {
863 return MediaWikiServices::getInstance()->getActorStore()
864 ->acquireSystemActorId( $actor, $dbw );
865 }, $name, [ 'token' => self::INVALID_TOKEN ] );
866 }
867
868 $user = self::newFromRow( $row );
869
870 if ( !$user->isSystemUser() ) {
871 // User exists. Steal it?
872 // @phan-suppress-next-line PhanRedundantCondition
873 if ( !$options['steal'] ) {
874 return null;
875 }
876
877 $services->getAuthManager()->revokeAccessForUser( $name );
878
879 $user->invalidateEmail();
880 $user->mToken = self::INVALID_TOKEN;
881 $user->saveSettings();
882 SessionManager::singleton()->preventSessionsForUser( $user->getName() );
883 }
884
885 return $user;
886 }
887
888 /** @} */
889 // endregion -- end of newFrom*() static factory methods
890
891 /**
892 * Get the username corresponding to a given user ID
893 * @deprecated since 1.43, Use UserIdentityLookup to get name from id
894 * @param int $id User ID
895 * @return string|false The corresponding username
896 */
897 public static function whoIs( $id ) {
898 return MediaWikiServices::getInstance()->getUserCache()
899 ->getProp( $id, 'name' );
900 }
901
902 /**
903 * Get the real name of a user given their user ID
904 *
905 * @deprecated since 1.43, Use UserFactory to get user instance and use User::getRealName
906 * @param int $id User ID
907 * @return string|false The corresponding user's real name
908 */
909 public static function whoIsReal( $id ) {
910 return MediaWikiServices::getInstance()->getUserCache()
911 ->getProp( $id, 'real_name' );
912 }
913
914 /**
915 * Return the users who are members of the given group(s). In case of multiple groups,
916 * users who are members of at least one of them are returned.
917 *
918 * @param string|array $groups A single group name or an array of group names
919 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
920 * records; larger values are ignored.
921 * @param int|null $after ID the user to start after
922 * @return UserArrayFromResult|ArrayIterator
923 */
924 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
925 if ( $groups === [] ) {
926 return UserArrayFromResult::newFromIDs( [] );
927 }
928 $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
929 $queryBuilder = $dbr->newSelectQueryBuilder()
930 ->select( 'ug_user' )
931 ->distinct()
932 ->from( 'user_groups' )
933 ->where( [ 'ug_group' => array_unique( (array)$groups ) ] )
934 ->orderBy( 'ug_user' )
935 ->limit( min( 5000, $limit ) );
936
937 if ( $after !== null ) {
938 $queryBuilder->andWhere( $dbr->expr( 'ug_user', '>', (int)$after ) );
939 }
940
941 $ids = $queryBuilder->caller( __METHOD__ )->fetchFieldValues() ?: [];
942 return UserArray::newFromIDs( $ids );
943 }
944
945 /**
946 * Is the input a valid password for this user?
947 *
948 * @param string $password Desired password
949 * @return bool
950 */
951 public function isValidPassword( $password ) {
952 // simple boolean wrapper for checkPasswordValidity
953 return $this->checkPasswordValidity( $password )->isGood();
954 }
955
956 /**
957 * Check if this is a valid password for this user
958 *
959 * Returns a Status object with a set of messages describing
960 * problems with the password. If the return status is fatal,
961 * the action should be refused and the password should not be
962 * checked at all (this is mainly meant for DoS mitigation).
963 * If the return value is OK but not good, the password can be checked,
964 * but the user should not be able to set their password to this.
965 * The value of the returned Status object will be an array which
966 * can have the following fields:
967 * - forceChange (bool): if set to true, the user should not be
968 * allowed to log with this password unless they change it during
969 * the login process (see ResetPasswordSecondaryAuthenticationProvider).
970 * - suggestChangeOnLogin (bool): if set to true, the user should be prompted for
971 * a password change on login.
972 *
973 * @param string $password Desired password
974 * @return Status
975 * @since 1.23
976 */
977 public function checkPasswordValidity( $password ) {
978 $passwordPolicy = MediaWikiServices::getInstance()->getMainConfig()
979 ->get( MainConfigNames::PasswordPolicy );
980
981 $upp = new UserPasswordPolicy(
982 $passwordPolicy['policies'],
983 $passwordPolicy['checks']
984 );
985
986 $status = Status::newGood( [] );
987 $result = false; // init $result to false for the internal checks
988
989 if ( !$this->getHookRunner()->onIsValidPassword( $password, $result, $this ) ) {
990 $status->error( $result );
991 return $status;
992 }
993
994 if ( $result === false ) {
995 $status->merge( $upp->checkUserPassword( $this, $password ), true );
996 return $status;
997 }
998
999 if ( $result === true ) {
1000 return $status;
1001 }
1002
1003 $status->error( $result );
1004 return $status; // the isValidPassword hook set a string $result and returned true
1005 }
1006
1007 /**
1008 * Set cached properties to default.
1009 *
1010 * @note This no longer clears uncached lazy-initialised properties;
1011 * the constructor does that instead.
1012 *
1013 * @param string|false $name
1014 * @param int|null $actorId
1015 */
1016 public function loadDefaults( $name = false, $actorId = null ) {
1017 $this->mId = 0;
1018 $this->mName = $name;
1019 $this->mActorId = $actorId;
1020 $this->mRealName = '';
1021 $this->mEmail = '';
1022 $this->isTemp = null;
1023
1024 $loggedOut = $this->mRequest && !defined( 'MW_NO_SESSION' )
1025 ? $this->mRequest->getSession()->getLoggedOutTimestamp() : 0;
1026 if ( $loggedOut !== 0 ) {
1027 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
1028 } else {
1029 $this->mTouched = '1'; # Allow any pages to be cached
1030 }
1031
1032 $this->mToken = null; // Don't run cryptographic functions till we need a token
1033 $this->mEmailAuthenticated = null;
1034 $this->mEmailToken = '';
1035 $this->mEmailTokenExpires = null;
1036 $this->mRegistration = wfTimestamp( TS_MW );
1037
1038 $this->getHookRunner()->onUserLoadDefaults( $this, $name );
1039 }
1040
1041 /**
1042 * Return whether an item has been loaded.
1043 *
1044 * @param string $item Item to check. Current possibilities:
1045 * - id
1046 * - name
1047 * - realname
1048 * @param string $all 'all' to check if the whole object has been loaded
1049 * or any other string to check if only the item is available (e.g.
1050 * for optimisation)
1051 * @return bool
1052 */
1053 public function isItemLoaded( $item, $all = 'all' ) {
1054 return ( $this->mLoadedItems === true && $all === 'all' ) ||
1055 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1056 }
1057
1058 /**
1059 * Set that an item has been loaded
1060 *
1061 * @internal Only public for use in UserFactory
1062 *
1063 * @param string $item
1064 */
1065 public function setItemLoaded( $item ) {
1066 if ( is_array( $this->mLoadedItems ) ) {
1067 $this->mLoadedItems[$item] = true;
1068 }
1069 }
1070
1071 /**
1072 * Load user data from the session.
1073 *
1074 * @return bool True if the user is logged in, false otherwise.
1075 */
1076 private function loadFromSession() {
1077 // MediaWiki\Session\Session already did the necessary authentication of the user
1078 // returned here, so just use it if applicable.
1079 $session = $this->getRequest()->getSession();
1080 $user = $session->getUser();
1081 if ( $user->isRegistered() ) {
1082 $this->loadFromUserObject( $user );
1083
1084 // Other code expects these to be set in the session, so set them.
1085 $session->set( 'wsUserID', $this->getId() );
1086 $session->set( 'wsUserName', $this->getName() );
1087 $session->set( 'wsToken', $this->getToken() );
1088
1089 return true;
1090 }
1091
1092 return false;
1093 }
1094
1095 /**
1096 * Load user data from the database.
1097 * $this->mId must be set, this is how the user is identified.
1098 *
1099 * @param int $flags IDBAccessObject::READ_* constant bitfield
1100 * @return bool True if the user exists, false if the user is anonymous
1101 */
1102 public function loadFromDatabase( $flags = IDBAccessObject::READ_LATEST ) {
1103 // Paranoia
1104 $this->mId = intval( $this->mId );
1105
1106 if ( !$this->mId ) {
1107 // Anonymous users are not in the database
1108 $this->loadDefaults();
1109 return false;
1110 }
1111
1112 $db = DBAccessObjectUtils::getDBFromRecency(
1113 MediaWikiServices::getInstance()->getDBLoadBalancerFactory(),
1114 $flags
1115 );
1116 $row = self::newQueryBuilder( $db )
1117 ->where( [ 'user_id' => $this->mId ] )
1118 ->recency( $flags )
1119 ->caller( __METHOD__ )
1120 ->fetchRow();
1121
1122 $this->queryFlagsUsed = $flags;
1123
1124 if ( $row !== false ) {
1125 // Initialise user table data
1126 $this->loadFromRow( $row );
1127 return true;
1128 }
1129
1130 // Invalid user_id
1131 $this->mId = 0;
1132 $this->loadDefaults( 'Unknown user' );
1133
1134 return false;
1135 }
1136
1137 /**
1138 * Initialize this object from a row from the user table.
1139 *
1140 * @param stdClass $row Row from the user table to load.
1141 * @param array|null $data Further user data to load into the object
1142 *
1143 * user_groups Array of arrays or stdClass result rows out of the user_groups
1144 * table. Previously you were supposed to pass an array of strings
1145 * here, but we also need expiry info nowadays, so an array of
1146 * strings is ignored.
1147 */
1148 protected function loadFromRow( $row, $data = null ) {
1149 if ( !is_object( $row ) ) {
1150 throw new InvalidArgumentException( '$row must be an object' );
1151 }
1152
1153 $all = true;
1154
1155 if ( isset( $row->actor_id ) ) {
1156 $this->mActorId = (int)$row->actor_id;
1157 if ( $this->mActorId !== 0 ) {
1158 $this->mFrom = 'actor';
1159 }
1160 $this->setItemLoaded( 'actor' );
1161 } else {
1162 $all = false;
1163 }
1164
1165 if ( isset( $row->user_name ) && $row->user_name !== '' ) {
1166 $this->mName = $row->user_name;
1167 $this->mFrom = 'name';
1168 $this->setItemLoaded( 'name' );
1169 } else {
1170 $all = false;
1171 }
1172
1173 if ( isset( $row->user_real_name ) ) {
1174 $this->mRealName = $row->user_real_name;
1175 $this->setItemLoaded( 'realname' );
1176 } else {
1177 $all = false;
1178 }
1179
1180 if ( isset( $row->user_id ) ) {
1181 $this->mId = intval( $row->user_id );
1182 if ( $this->mId !== 0 ) {
1183 $this->mFrom = 'id';
1184 }
1185 $this->setItemLoaded( 'id' );
1186 } else {
1187 $all = false;
1188 }
1189
1190 if ( isset( $row->user_editcount ) ) {
1191 // Don't try to set edit count for anonymous users
1192 // We check the id here and not in UserEditTracker because calling
1193 // User::getId() can trigger some other loading. This will result in
1194 // discarding the user_editcount field for rows if the id wasn't set.
1195 if ( $this->mId !== null && $this->mId !== 0 ) {
1196 MediaWikiServices::getInstance()
1197 ->getUserEditTracker()
1198 ->setCachedUserEditCount( $this, (int)$row->user_editcount );
1199 }
1200 } else {
1201 $all = false;
1202 }
1203
1204 if ( isset( $row->user_touched ) ) {
1205 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1206 } else {
1207 $all = false;
1208 }
1209
1210 if ( isset( $row->user_token ) ) {
1211 // The definition for the column is binary(32), so trim the NULs
1212 // that appends. The previous definition was char(32), so trim
1213 // spaces too.
1214 $this->mToken = rtrim( $row->user_token, " \0" );
1215 if ( $this->mToken === '' ) {
1216 $this->mToken = null;
1217 }
1218 } else {
1219 $all = false;
1220 }
1221
1222 if ( isset( $row->user_email ) ) {
1223 $this->mEmail = $row->user_email;
1224 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1225 $this->mEmailToken = $row->user_email_token;
1226 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1227 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1228 } else {
1229 $all = false;
1230 }
1231
1232 if ( $all ) {
1233 $this->mLoadedItems = true;
1234 }
1235
1236 if ( is_array( $data ) ) {
1237
1238 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1239 MediaWikiServices::getInstance()
1240 ->getUserGroupManager()
1241 ->loadGroupMembershipsFromArray(
1242 $this,
1243 $data['user_groups'],
1244 $this->queryFlagsUsed
1245 );
1246 }
1247 }
1248 }
1249
1250 /**
1251 * Load the data for this user object from another user object.
1252 *
1253 * @param User $user
1254 */
1255 protected function loadFromUserObject( $user ) {
1256 $user->load();
1257 foreach ( self::$mCacheVars as $var ) {
1258 $this->$var = $user->$var;
1259 }
1260 }
1261
1262 /**
1263 * Builds update conditions. Additional conditions may be added to $conditions to
1264 * protected against race conditions using a compare-and-set (CAS) mechanism
1265 * based on comparing $this->mTouched with the user_touched field.
1266 *
1267 * @param IReadableDatabase $db
1268 * @param array $conditions WHERE conditions for use with Database::update
1269 * @return array WHERE conditions for use with Database::update
1270 */
1271 protected function makeUpdateConditions( IReadableDatabase $db, array $conditions ) {
1272 if ( $this->mTouched ) {
1273 // CAS check: only update if the row wasn't changed since it was loaded.
1274 $conditions['user_touched'] = $db->timestamp( $this->mTouched );
1275 }
1276
1277 return $conditions;
1278 }
1279
1280 /**
1281 * Bump user_touched if it didn't change since this object was loaded
1282 *
1283 * On success, the mTouched field is updated.
1284 * The user serialization cache is always cleared.
1285 *
1286 * @internal
1287 * @return bool Whether user_touched was actually updated
1288 * @since 1.26
1289 */
1290 public function checkAndSetTouched() {
1291 $this->load();
1292
1293 if ( !$this->mId ) {
1294 return false; // anon
1295 }
1296
1297 // Get a new user_touched that is higher than the old one
1298 $newTouched = $this->newTouchedTimestamp();
1299
1300 $dbw = MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase();
1301 $dbw->newUpdateQueryBuilder()
1302 ->update( 'user' )
1303 ->set( [ 'user_touched' => $dbw->timestamp( $newTouched ) ] )
1304 ->where( $this->makeUpdateConditions( $dbw, [
1305 'user_id' => $this->mId,
1306 ] ) )
1307 ->caller( __METHOD__ )->execute();
1308 $success = ( $dbw->affectedRows() > 0 );
1309
1310 if ( $success ) {
1311 $this->mTouched = $newTouched;
1312 $this->clearSharedCache( 'changed' );
1313 } else {
1314 // Clears on failure too since that is desired if the cache is stale
1315 $this->clearSharedCache( 'refresh' );
1316 }
1317
1318 return $success;
1319 }
1320
1321 /**
1322 * Clear various cached data stored in this object. The cache of the user table
1323 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1324 *
1325 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1326 * given source. May be "name", "id", "actor", "defaults", "session", or false for no reload.
1327 */
1328 public function clearInstanceCache( $reloadFrom = false ) {
1329 global $wgFullyInitialised;
1330
1331 $this->mDatePreference = null;
1332 $this->mHash = false;
1333 $this->mThisAsAuthority = null;
1334
1335 if ( $wgFullyInitialised && $this->mFrom ) {
1336 $services = MediaWikiServices::getInstance();
1337
1338 if ( $services->peekService( 'PermissionManager' ) ) {
1339 $services->getPermissionManager()->invalidateUsersRightsCache( $this );
1340 }
1341
1342 if ( $services->peekService( 'UserOptionsManager' ) ) {
1343 $services->getUserOptionsManager()->clearUserOptionsCache( $this );
1344 }
1345
1346 if ( $services->peekService( 'TalkPageNotificationManager' ) ) {
1347 $services->getTalkPageNotificationManager()->clearInstanceCache( $this );
1348 }
1349
1350 if ( $services->peekService( 'UserGroupManager' ) ) {
1351 $services->getUserGroupManager()->clearCache( $this );
1352 }
1353
1354 if ( $services->peekService( 'UserEditTracker' ) ) {
1355 $services->getUserEditTracker()->clearUserEditCache( $this );
1356 }
1357
1358 if ( $services->peekService( 'BlockManager' ) ) {
1359 $services->getBlockManager()->clearUserCache( $this );
1360 }
1361 }
1362
1363 if ( $reloadFrom ) {
1364 if ( in_array( $reloadFrom, [ 'name', 'id', 'actor' ] ) ) {
1365 $this->mLoadedItems = [ $reloadFrom => true ];
1366 } else {
1367 $this->mLoadedItems = [];
1368 }
1369 $this->mFrom = $reloadFrom;
1370 }
1371 }
1372
1373 /**
1374 * Is this user subject to rate limiting?
1375 *
1376 * @return bool True if rate limited
1377 */
1378 public function isPingLimitable() {
1379 $limiter = MediaWikiServices::getInstance()->getRateLimiter();
1380 $subject = $this->toRateLimitSubject();
1381 return !$limiter->isExempt( $subject );
1382 }
1383
1384 /**
1385 * Primitive rate limits: enforce maximum actions per time period
1386 * to put a brake on flooding.
1387 *
1388 * The method generates both a generic profiling point and a per action one
1389 * (suffix being "-$action").
1390 *
1391 * @note When using a shared cache like memcached, IP-address
1392 * last-hit counters will be shared across wikis.
1393 *
1394 * @param string $action Action to enforce; 'edit' if unspecified
1395 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1396 *
1397 * @return bool True if a rate limiter was tripped
1398 */
1399 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1400 return $this->getThisAsAuthority()->limit( $action, $incrBy, null );
1401 }
1402
1403 /**
1404 * @internal for use by UserAuthority only!
1405 * @return RateLimitSubject
1406 */
1407 public function toRateLimitSubject(): RateLimitSubject {
1408 $flags = [
1409 'exempt' => $this->isAllowed( 'noratelimit' ),
1410 'newbie' => $this->isNewbie(),
1411 ];
1412
1413 return new RateLimitSubject( $this, $this->getRequest()->getIP(), $flags );
1414 }
1415
1416 /**
1417 * Get the block affecting the user, or null if the user is not blocked
1418 *
1419 * @param int|bool $freshness One of the IDBAccessObject::READ_XXX constants.
1420 * For backwards compatibility, a boolean is also accepted,
1421 * with true meaning READ_NORMAL and false meaning
1422 * READ_LATEST.
1423 * @param bool $disableIpBlockExemptChecking This is used internally to prevent
1424 * a infinite recursion with autopromote. See T270145.
1425 *
1426 * @return ?AbstractBlock
1427 */
1428 public function getBlock(
1429 $freshness = IDBAccessObject::READ_NORMAL,
1430 $disableIpBlockExemptChecking = false
1431 ): ?Block {
1432 if ( is_bool( $freshness ) ) {
1433 $fromReplica = $freshness;
1434 } else {
1435 $fromReplica = ( $freshness !== IDBAccessObject::READ_LATEST );
1436 }
1437
1438 if ( $disableIpBlockExemptChecking ) {
1439 $isExempt = false;
1440 } else {
1441 $isExempt = $this->isAllowed( 'ipblock-exempt' );
1442 }
1443
1444 // TODO: Block checking shouldn't really be done from the User object. Block
1445 // checking can involve checking for IP blocks, cookie blocks, and/or XFF blocks,
1446 // which need more knowledge of the request context than the User should have.
1447 // Since we do currently check blocks from the User, we have to do the following
1448 // here:
1449 // - Check if this is the user associated with the main request
1450 // - If so, pass the relevant request information to the block manager
1451 $request = null;
1452 if ( !$isExempt && $this->isGlobalSessionUser() ) {
1453 // This is the global user, so we need to pass the request
1454 $request = $this->getRequest();
1455 }
1456
1457 return MediaWikiServices::getInstance()->getBlockManager()->getBlock(
1458 $this,
1459 $request,
1460 $fromReplica,
1461 );
1462 }
1463
1464 /**
1465 * Check if user is blocked on all wikis.
1466 * Do not use for actual edit permission checks!
1467 * This is intended for quick UI checks.
1468 *
1469 * @param string $ip IP address, uses current client if none given
1470 * @return bool True if blocked, false otherwise
1471 * @deprecated since 1.40, emits deprecation warnings since 1.43. Use getBlock instead.
1472 */
1473 public function isBlockedGlobally( $ip = '' ) {
1474 wfDeprecated( __METHOD__, '1.40' );
1475 return $this->getGlobalBlock( $ip ) instanceof AbstractBlock;
1476 }
1477
1478 /**
1479 * Check if user is blocked on all wikis.
1480 * Do not use for actual edit permission checks!
1481 * This is intended for quick UI checks.
1482 *
1483 * @param string $ip IP address, uses current client if none given
1484 * @return AbstractBlock|null Block object if blocked, null otherwise
1485 * @deprecated since 1.40. Use getBlock instead
1486 */
1487 public function getGlobalBlock( $ip = '' ) {
1488 if ( $this->mGlobalBlock !== null ) {
1489 return $this->mGlobalBlock ?: null;
1490 }
1491 // User is already an IP?
1492 if ( IPUtils::isIPAddress( $this->getName() ) ) {
1493 $ip = $this->getName();
1494 } elseif ( !$ip ) {
1495 $ip = $this->getRequest()->getIP();
1496 }
1497 $blocked = false;
1498 $block = null;
1499 $this->getHookRunner()->onUserIsBlockedGlobally( $this, $ip, $blocked, $block );
1500
1501 if ( $blocked && $block === null ) {
1502 // back-compat: UserIsBlockedGlobally didn't have $block param first
1503 $block = new SystemBlock( [
1504 'address' => $ip,
1505 'systemBlock' => 'global-block'
1506 ] );
1507 }
1508
1509 $this->mGlobalBlock = $blocked ? $block : false;
1510 return $this->mGlobalBlock ?: null;
1511 }
1512
1513 /**
1514 * Check if user account is locked
1515 *
1516 * @return bool True if locked, false otherwise
1517 */
1518 public function isLocked() {
1519 if ( $this->mLocked !== null ) {
1520 return $this->mLocked;
1521 }
1522 // Reset for hook
1523 $this->mLocked = false;
1524 $this->getHookRunner()->onUserIsLocked( $this, $this->mLocked );
1525 return $this->mLocked;
1526 }
1527
1528 /**
1529 * Check if user account is hidden
1530 *
1531 * @return bool True if hidden, false otherwise
1532 */
1533 public function isHidden() {
1534 $block = $this->getBlock();
1535 return $block ? $block->getHideName() : false;
1536 }
1537
1538 /**
1539 * Get the user's ID.
1540 * @param string|false $wikiId The wiki ID expected by the caller.
1541 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1542 */
1543 public function getId( $wikiId = self::LOCAL ): int {
1544 $this->assertWiki( $wikiId );
1545 if ( $this->mId === null && $this->mName !== null ) {
1546 $userNameUtils = MediaWikiServices::getInstance()->getUserNameUtils();
1547 if ( $userNameUtils->isIP( $this->mName ) || ExternalUserNames::isExternal( $this->mName ) ) {
1548 // Special case, we know the user is anonymous
1549 // Note that "external" users are "local" (they have an actor ID that is relative to
1550 // the local wiki).
1551 return 0;
1552 }
1553 }
1554
1555 if ( !$this->isItemLoaded( 'id' ) ) {
1556 // Don't load if this was initialized from an ID
1557 $this->load();
1558 }
1559
1560 return (int)$this->mId;
1561 }
1562
1563 /**
1564 * Set the user and reload all fields according to a given ID
1565 * @param int $v User ID to reload
1566 */
1567 public function setId( $v ) {
1568 $this->mId = $v;
1569 $this->clearInstanceCache( 'id' );
1570 }
1571
1572 /**
1573 * Get the user name, or the IP of an anonymous user
1574 * @return string User's name or IP address
1575 */
1576 public function getName(): string {
1577 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1578 // Special case optimisation
1579 return $this->mName;
1580 }
1581
1582 $this->load();
1583 if ( $this->mName === false ) {
1584 // Clean up IPs
1585 $this->mName = IPUtils::sanitizeIP( $this->getRequest()->getIP() );
1586 }
1587
1588 return $this->mName;
1589 }
1590
1591 /**
1592 * Set the user name.
1593 *
1594 * This does not reload fields from the database according to the given
1595 * name. Rather, it is used to create a temporary "nonexistent user" for
1596 * later addition to the database. It can also be used to set the IP
1597 * address for an anonymous user to something other than the current
1598 * remote IP.
1599 *
1600 * @note User::newFromName() has roughly the same function, when the named user
1601 * does not exist.
1602 * @param string $str New user name to set
1603 */
1604 public function setName( $str ) {
1605 $this->load();
1606 $this->mName = $str;
1607 }
1608
1609 /**
1610 * Get the user's actor ID.
1611 * @since 1.31
1612 * @note This method was removed from the UserIdentity interface in 1.36,
1613 * but remains supported in the User class for now.
1614 * New code should use ActorNormalization::findActorId() or
1615 * ActorNormalization::acquireActorId() instead.
1616 * @param IDatabase|string|false $dbwOrWikiId Deprecated since 1.36.
1617 * If a database connection is passed, a new actor ID is assigned if needed.
1618 * ActorNormalization::acquireActorId() should be used for that purpose instead.
1619 * @return int The actor's ID, or 0 if no actor ID exists and $dbw was null
1620 * @throws PreconditionException if $dbwOrWikiId is a string and does not match the local wiki
1621 */
1622 public function getActorId( $dbwOrWikiId = self::LOCAL ): int {
1623 if ( $dbwOrWikiId ) {
1624 wfDeprecatedMsg( 'Passing a parameter to getActorId() is deprecated', '1.36' );
1625 }
1626
1627 if ( is_string( $dbwOrWikiId ) ) {
1628 $this->assertWiki( $dbwOrWikiId );
1629 }
1630
1631 if ( !$this->isItemLoaded( 'actor' ) ) {
1632 $this->load();
1633 }
1634
1635 if ( !$this->mActorId && $dbwOrWikiId instanceof IDatabase ) {
1636 MediaWikiServices::getInstance()
1637 ->getActorStoreFactory()
1638 ->getActorNormalization( $dbwOrWikiId->getDomainID() )
1639 ->acquireActorId( $this, $dbwOrWikiId );
1640 // acquireActorId will call setActorId on $this
1641 Assert::postcondition(
1642 $this->mActorId !== null,
1643 "Failed to acquire actor ID for user id {$this->mId} name {$this->mName}"
1644 );
1645 }
1646
1647 return (int)$this->mActorId;
1648 }
1649
1650 /**
1651 * Sets the actor id.
1652 * For use by ActorStore only.
1653 * Should be removed once callers of getActorId() have been migrated to using ActorNormalization.
1654 *
1655 * @internal
1656 * @deprecated since 1.36
1657 * @param int $actorId
1658 */
1659 public function setActorId( int $actorId ) {
1660 $this->mActorId = $actorId;
1661 $this->setItemLoaded( 'actor' );
1662 }
1663
1664 /**
1665 * Get the user's name escaped by underscores.
1666 * @return string Username escaped by underscores.
1667 */
1668 public function getTitleKey(): string {
1669 return str_replace( ' ', '_', $this->getName() );
1670 }
1671
1672 /**
1673 * Generate a current or new-future timestamp to be stored in the
1674 * user_touched field when we update things.
1675 *
1676 * @return string Timestamp in TS_MW format
1677 */
1678 private function newTouchedTimestamp() {
1679 $time = (int)ConvertibleTimestamp::now( TS_UNIX );
1680 if ( $this->mTouched ) {
1681 $time = max( $time, (int)ConvertibleTimestamp::convert( TS_UNIX, $this->mTouched ) + 1 );
1682 }
1683
1684 return ConvertibleTimestamp::convert( TS_MW, $time );
1685 }
1686
1687 /**
1688 * Clear user data from memcached
1689 *
1690 * Use after applying updates to the database; caller's
1691 * responsibility to update user_touched if appropriate.
1692 *
1693 * Called implicitly from invalidateCache() and saveSettings().
1694 *
1695 * @param string $mode Use 'refresh' to clear now or 'changed' to clear before DB commit
1696 */
1697 public function clearSharedCache( $mode = 'refresh' ) {
1698 if ( !$this->getId() ) {
1699 return;
1700 }
1701
1702 $dbProvider = MediaWikiServices::getInstance()->getConnectionProvider();
1703 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1704 $key = $this->getCacheKey( $cache );
1705
1706 if ( $mode === 'refresh' ) {
1707 $cache->delete( $key, 1 ); // low tombstone/"hold-off" TTL
1708 } else {
1709 $dbProvider->getPrimaryDatabase()->onTransactionPreCommitOrIdle(
1710 static function () use ( $cache, $key ) {
1711 $cache->delete( $key );
1712 },
1713 __METHOD__
1714 );
1715 }
1716 }
1717
1718 /**
1719 * Immediately touch the user data cache for this account
1720 *
1721 * Calls touch() and removes account data from memcached
1722 */
1723 public function invalidateCache() {
1724 $this->touch();
1725 $this->clearSharedCache( 'changed' );
1726 }
1727
1728 /**
1729 * Update the "touched" timestamp for the user
1730 *
1731 * This is useful on various login/logout events when making sure that
1732 * a browser or proxy that has multiple tenants does not suffer cache
1733 * pollution where the new user sees the old users content. The value
1734 * of getTouched() is checked when determining 304 vs 200 responses.
1735 * Unlike invalidateCache(), this preserves the User object cache and
1736 * avoids database writes.
1737 *
1738 * @since 1.25
1739 */
1740 public function touch() {
1741 $id = $this->getId();
1742 if ( $id ) {
1743 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1744 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
1745 $cache->touchCheckKey( $key );
1746 $this->mQuickTouched = null;
1747 }
1748 }
1749
1750 /**
1751 * Validate the cache for this account.
1752 * @param string $timestamp A timestamp in TS_MW format
1753 * @return bool
1754 */
1755 public function validateCache( $timestamp ) {
1756 return ( $timestamp >= $this->getTouched() );
1757 }
1758
1759 /**
1760 * Get the user touched timestamp
1761 *
1762 * Use this value only to validate caches via inequalities
1763 * such as in the case of HTTP If-Modified-Since response logic
1764 *
1765 * @return string TS_MW Timestamp
1766 */
1767 public function getTouched() {
1768 $this->load();
1769
1770 if ( $this->mId ) {
1771 if ( $this->mQuickTouched === null ) {
1772 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1773 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId );
1774
1775 $this->mQuickTouched = wfTimestamp( TS_MW, $cache->getCheckKeyTime( $key ) );
1776 }
1777
1778 return max( $this->mTouched, $this->mQuickTouched );
1779 }
1780
1781 return $this->mTouched;
1782 }
1783
1784 /**
1785 * Get the user_touched timestamp field (time of last DB updates)
1786 * @return string TS_MW Timestamp
1787 * @since 1.26
1788 */
1789 public function getDBTouched() {
1790 $this->load();
1791
1792 return $this->mTouched;
1793 }
1794
1795 /**
1796 * Changes credentials of the user.
1797 *
1798 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
1799 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
1800 * e.g. when no provider handled the change.
1801 *
1802 * @param array $data A set of authentication data in fieldname => value format. This is the
1803 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
1804 * @return Status
1805 * @since 1.27
1806 */
1807 public function changeAuthenticationData( array $data ) {
1808 $manager = MediaWikiServices::getInstance()->getAuthManager();
1809 $reqs = $manager->getAuthenticationRequests( AuthManager::ACTION_CHANGE, $this );
1810 $reqs = AuthenticationRequest::loadRequestsFromSubmission( $reqs, $data );
1811
1812 $status = Status::newGood( 'ignored' );
1813 foreach ( $reqs as $req ) {
1814 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
1815 }
1816 if ( $status->getValue() === 'ignored' ) {
1817 $status->warning( 'authenticationdatachange-ignored' );
1818 }
1819
1820 if ( $status->isGood() ) {
1821 foreach ( $reqs as $req ) {
1822 $manager->changeAuthenticationData( $req );
1823 }
1824 }
1825 return $status;
1826 }
1827
1828 /**
1829 * Get the user's current token.
1830 * @param bool $forceCreation Force the generation of a new token if the
1831 * user doesn't have one (default=true for backwards compatibility).
1832 * @return string|null Token
1833 */
1834 public function getToken( $forceCreation = true ) {
1835 $authenticationTokenVersion = MediaWikiServices::getInstance()
1836 ->getMainConfig()->get( MainConfigNames::AuthenticationTokenVersion );
1837
1838 $this->load();
1839 if ( !$this->mToken && $forceCreation ) {
1840 $this->setToken();
1841 }
1842
1843 if ( !$this->mToken ) {
1844 // The user doesn't have a token, return null to indicate that.
1845 return null;
1846 }
1847
1848 if ( $this->mToken === self::INVALID_TOKEN ) {
1849 // We return a random value here so existing token checks are very
1850 // likely to fail.
1851 return MWCryptRand::generateHex( self::TOKEN_LENGTH );
1852 }
1853
1854 if ( $authenticationTokenVersion === null ) {
1855 // $wgAuthenticationTokenVersion not in use, so return the raw secret
1856 return $this->mToken;
1857 }
1858
1859 // $wgAuthenticationTokenVersion in use, so hmac it.
1860 $ret = MWCryptHash::hmac( $authenticationTokenVersion, $this->mToken, false );
1861
1862 // The raw hash can be overly long. Shorten it up.
1863 $len = max( 32, self::TOKEN_LENGTH );
1864 if ( strlen( $ret ) < $len ) {
1865 // Should never happen, even md5 is 128 bits
1866 throw new \UnexpectedValueException( 'Hmac returned less than 128 bits' );
1867 }
1868
1869 return substr( $ret, -$len );
1870 }
1871
1872 /**
1873 * Set the random token (used for persistent authentication)
1874 * Called from loadDefaults() among other places.
1875 *
1876 * @param string|false $token If specified, set the token to this value
1877 */
1878 public function setToken( $token = false ) {
1879 $this->load();
1880 if ( $this->mToken === self::INVALID_TOKEN ) {
1881 LoggerFactory::getInstance( 'session' )
1882 ->debug( __METHOD__ . ": Ignoring attempt to set token for system user \"$this\"" );
1883 } elseif ( !$token ) {
1884 $this->mToken = MWCryptRand::generateHex( self::TOKEN_LENGTH );
1885 } else {
1886 $this->mToken = $token;
1887 }
1888 }
1889
1890 /**
1891 * Get the user's e-mail address
1892 * @return string User's email address
1893 */
1894 public function getEmail(): string {
1895 $this->load();
1896 $email = $this->mEmail;
1897 $this->getHookRunner()->onUserGetEmail( $this, $email );
1898 // In case a hook handler returns e.g. null
1899 $this->mEmail = is_string( $email ) ? $email : '';
1900 return $this->mEmail;
1901 }
1902
1903 /**
1904 * Get the timestamp of the user's e-mail authentication
1905 * @return string TS_MW timestamp
1906 */
1907 public function getEmailAuthenticationTimestamp() {
1908 $this->load();
1909 $this->getHookRunner()->onUserGetEmailAuthenticationTimestamp(
1910 $this, $this->mEmailAuthenticated );
1911 return $this->mEmailAuthenticated;
1912 }
1913
1914 /**
1915 * Set the user's e-mail address
1916 * @param string $str New e-mail address
1917 */
1918 public function setEmail( string $str ) {
1919 $this->load();
1920 if ( $str == $this->getEmail() ) {
1921 return;
1922 }
1923 $this->invalidateEmail();
1924 $this->mEmail = $str;
1925 $this->getHookRunner()->onUserSetEmail( $this, $this->mEmail );
1926 }
1927
1928 /**
1929 * Set the user's e-mail address and send a confirmation mail if needed.
1930 *
1931 * @since 1.20
1932 * @param string $str New e-mail address
1933 * @return Status
1934 */
1935 public function setEmailWithConfirmation( string $str ) {
1936 $config = MediaWikiServices::getInstance()->getMainConfig();
1937 $enableEmail = $config->get( MainConfigNames::EnableEmail );
1938
1939 if ( !$enableEmail ) {
1940 return Status::newFatal( 'emaildisabled' );
1941 }
1942
1943 $oldaddr = $this->getEmail();
1944 if ( $str === $oldaddr ) {
1945 return Status::newGood( true );
1946 }
1947
1948 $type = $oldaddr != '' ? 'changed' : 'set';
1949 $notificationResult = null;
1950
1951 $emailAuthentication = $config->get( MainConfigNames::EmailAuthentication );
1952
1953 if ( $emailAuthentication && $type === 'changed' && $this->isEmailConfirmed() ) {
1954 // Send the user an email notifying the user of the change in registered
1955 // email address on their previous verified email address
1956 $change = $str != '' ? 'changed' : 'removed';
1957 $notificationResult = $this->sendMail(
1958 wfMessage( 'notificationemail_subject_' . $change )->text(),
1959 wfMessage( 'notificationemail_body_' . $change,
1960 $this->getRequest()->getIP(),
1961 $this->getName(),
1962 $str )->text()
1963 );
1964 }
1965
1966 $this->setEmail( $str );
1967
1968 if ( $str !== '' && $emailAuthentication ) {
1969 // Send a confirmation request to the new address if needed
1970 $result = $this->sendConfirmationMail( $type );
1971
1972 if ( $notificationResult !== null ) {
1973 $result->merge( $notificationResult );
1974 }
1975
1976 if ( $result->isGood() ) {
1977 // Say to the caller that a confirmation and notification mail has been sent
1978 $result->value = 'eauth';
1979 }
1980 } else {
1981 $result = Status::newGood( true );
1982 }
1983
1984 return $result;
1985 }
1986
1987 /**
1988 * Get the user's real name
1989 * @return string User's real name
1990 */
1991 public function getRealName(): string {
1992 if ( !$this->isItemLoaded( 'realname' ) ) {
1993 $this->load();
1994 }
1995
1996 return $this->mRealName;
1997 }
1998
1999 /**
2000 * Set the user's real name
2001 * @param string $str New real name
2002 */
2003 public function setRealName( string $str ) {
2004 $this->load();
2005 $this->mRealName = $str;
2006 }
2007
2008 /**
2009 * Get a token stored in the preferences (like the watchlist one),
2010 * resetting it if it's empty (and saving changes).
2011 *
2012 * @param string $oname The option name to retrieve the token from
2013 * @return string|false User's current value for the option, or false if this option is disabled.
2014 * @see resetTokenFromOption()
2015 * @see getOption()
2016 * @deprecated since 1.26 Applications should use the OAuth extension
2017 */
2018 public function getTokenFromOption( $oname ) {
2019 $hiddenPrefs =
2020 MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::HiddenPrefs );
2021
2022 $id = $this->getId();
2023 if ( !$id || in_array( $oname, $hiddenPrefs ) ) {
2024 return false;
2025 }
2026
2027 $userOptionsLookup = MediaWikiServices::getInstance()
2028 ->getUserOptionsLookup();
2029 $token = $userOptionsLookup->getOption( $this, (string)$oname );
2030 if ( !$token ) {
2031 // Default to a value based on the user token to avoid space
2032 // wasted on storing tokens for all users. When this option
2033 // is set manually by the user, only then is it stored.
2034 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2035 }
2036
2037 return $token;
2038 }
2039
2040 /**
2041 * Reset a token stored in the preferences (like the watchlist one).
2042 * *Does not* save user's preferences (similarly to UserOptionsManager::setOption()).
2043 *
2044 * @param string $oname The option name to reset the token in
2045 * @return string|false New token value, or false if this option is disabled.
2046 * @see getTokenFromOption()
2047 * @see \MediaWiki\User\Options\UserOptionsManager::setOption
2048 */
2049 public function resetTokenFromOption( $oname ) {
2050 $hiddenPrefs =
2051 MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::HiddenPrefs );
2052 if ( in_array( $oname, $hiddenPrefs ) ) {
2053 return false;
2054 }
2055
2056 $token = MWCryptRand::generateHex( 40 );
2057 MediaWikiServices::getInstance()
2058 ->getUserOptionsManager()
2059 ->setOption( $this, $oname, $token );
2060 return $token;
2061 }
2062
2063 /**
2064 * Get the user's preferred date format.
2065 * @return string User's preferred date format
2066 */
2067 public function getDatePreference() {
2068 // Important migration for old data rows
2069 if ( $this->mDatePreference === null ) {
2070 global $wgLang;
2071 $userOptionsLookup = MediaWikiServices::getInstance()
2072 ->getUserOptionsLookup();
2073 $value = $userOptionsLookup->getOption( $this, 'date' ) ?? 'default';
2074 $map = $wgLang->getDatePreferenceMigrationMap();
2075 if ( isset( $map[$value] ) ) {
2076 $value = $map[$value];
2077 }
2078 $this->mDatePreference = $value;
2079 }
2080 return $this->mDatePreference;
2081 }
2082
2083 /**
2084 * Determine based on the wiki configuration and the user's options,
2085 * whether this user must be over HTTPS no matter what.
2086 *
2087 * @return bool
2088 */
2089 public function requiresHTTPS() {
2090 if ( !$this->isRegistered() ) {
2091 return false;
2092 }
2093
2094 $services = MediaWikiServices::getInstance();
2095 $config = $services->getMainConfig();
2096 if ( $config->get( MainConfigNames::ForceHTTPS ) ) {
2097 return true;
2098 }
2099 if ( !$config->get( MainConfigNames::SecureLogin ) ) {
2100 return false;
2101 }
2102 return $services->getUserOptionsLookup()
2103 ->getBoolOption( $this, 'prefershttps' );
2104 }
2105
2106 /**
2107 * Get the user's edit count.
2108 * @return int|null Null for anonymous users
2109 */
2110 public function getEditCount() {
2111 return MediaWikiServices::getInstance()
2112 ->getUserEditTracker()
2113 ->getUserEditCount( $this );
2114 }
2115
2116 /**
2117 * Get whether the user is registered.
2118 *
2119 * @return bool True if user is registered on this wiki, i.e., has a user ID. False if user is
2120 * anonymous or has no local account (which can happen when importing). This is equivalent to
2121 * getId() != 0 and is provided for code readability.
2122 * @since 1.34
2123 */
2124 public function isRegistered(): bool {
2125 return $this->getId() != 0;
2126 }
2127
2128 /**
2129 * Get whether the user is anonymous
2130 * @return bool
2131 */
2132 public function isAnon() {
2133 return !$this->isRegistered();
2134 }
2135
2136 /**
2137 * @return bool Whether this user is flagged as being a bot role account
2138 * @since 1.28
2139 */
2140 public function isBot() {
2141 $userGroupManager = MediaWikiServices::getInstance()->getUserGroupManager();
2142 if ( in_array( 'bot', $userGroupManager->getUserGroups( $this ) )
2143 && $this->isAllowed( 'bot' )
2144 ) {
2145 return true;
2146 }
2147
2148 $isBot = false;
2149 $this->getHookRunner()->onUserIsBot( $this, $isBot );
2150
2151 return $isBot;
2152 }
2153
2154 /**
2155 * Get whether the user is a system user
2156 *
2157 * A user is considered to exist as a non-system user if it can
2158 * authenticate, or has an email set, or has a non-invalid token.
2159 *
2160 * @return bool Whether this user is a system user
2161 * @since 1.35
2162 */
2163 public function isSystemUser() {
2164 $this->load();
2165 if ( $this->getEmail() || $this->mToken !== self::INVALID_TOKEN ||
2166 MediaWikiServices::getInstance()->getAuthManager()->userCanAuthenticate( $this->mName )
2167 ) {
2168 return false;
2169 }
2170 return true;
2171 }
2172
2173 public function isAllowedAny( ...$permissions ): bool {
2174 return $this->getThisAsAuthority()->isAllowedAny( ...$permissions );
2175 }
2176
2177 public function isAllowedAll( ...$permissions ): bool {
2178 return $this->getThisAsAuthority()->isAllowedAll( ...$permissions );
2179 }
2180
2181 public function isAllowed( string $permission, ?PermissionStatus $status = null ): bool {
2182 return $this->getThisAsAuthority()->isAllowed( $permission, $status );
2183 }
2184
2185 /**
2186 * Check whether to enable recent changes patrol features for this user
2187 * @return bool True or false
2188 */
2189 public function useRCPatrol() {
2190 $useRCPatrol =
2191 MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::UseRCPatrol );
2192 return $useRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
2193 }
2194
2195 /**
2196 * Check whether to enable new pages patrol features for this user
2197 * @return bool True or false
2198 */
2199 public function useNPPatrol() {
2200 $useRCPatrol =
2201 MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::UseRCPatrol );
2202 $useNPPatrol =
2203 MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::UseNPPatrol );
2204 return (
2205 ( $useRCPatrol || $useNPPatrol )
2206 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
2207 );
2208 }
2209
2210 /**
2211 * Check whether to enable new files patrol features for this user
2212 * @return bool True or false
2213 */
2214 public function useFilePatrol() {
2215 $useRCPatrol =
2216 MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::UseRCPatrol );
2217 $useFilePatrol = MediaWikiServices::getInstance()->getMainConfig()
2218 ->get( MainConfigNames::UseFilePatrol );
2219 return (
2220 ( $useRCPatrol || $useFilePatrol )
2221 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
2222 );
2223 }
2224
2225 /**
2226 * Get the WebRequest object to use with this object
2227 *
2228 * @return WebRequest
2229 */
2230 public function getRequest(): WebRequest {
2231 return $this->mRequest ?? RequestContext::getMain()->getRequest();
2232 }
2233
2234 /**
2235 * Compute experienced level based on edit count and registration date.
2236 *
2237 * @return string|false 'newcomer', 'learner', or 'experienced', false for anonymous users
2238 */
2239 public function getExperienceLevel() {
2240 $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
2241 $learnerEdits = $mainConfig->get( MainConfigNames::LearnerEdits );
2242 $experiencedUserEdits = $mainConfig->get( MainConfigNames::ExperiencedUserEdits );
2243 $learnerMemberSince = $mainConfig->get( MainConfigNames::LearnerMemberSince );
2244 $experiencedUserMemberSince =
2245 $mainConfig->get( MainConfigNames::ExperiencedUserMemberSince );
2246 if ( $this->isAnon() ) {
2247 return false;
2248 }
2249
2250 $editCount = $this->getEditCount();
2251 $registration = $this->getRegistration();
2252 $now = time();
2253 $learnerRegistration = wfTimestamp( TS_MW, $now - $learnerMemberSince * 86400 );
2254 $experiencedRegistration = wfTimestamp( TS_MW, $now - $experiencedUserMemberSince * 86400 );
2255 if ( $registration === null ) {
2256 // for some very old accounts, this information is missing in the database
2257 // treat them as old enough to be 'experienced'
2258 $registration = $experiencedRegistration;
2259 }
2260
2261 if ( $editCount < $learnerEdits ||
2262 $registration > $learnerRegistration ) {
2263 return 'newcomer';
2264 }
2265
2266 if ( $editCount > $experiencedUserEdits &&
2267 $registration <= $experiencedRegistration
2268 ) {
2269 return 'experienced';
2270 }
2271
2272 return 'learner';
2273 }
2274
2275 /**
2276 * Persist this user's session (e.g. set cookies)
2277 *
2278 * @param WebRequest|null $request WebRequest object to use; the global request
2279 * will be used if null is passed.
2280 * @param bool|null $secure Whether to force secure/insecure cookies or use default
2281 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
2282 */
2283 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
2284 $this->load();
2285 if ( $this->mId == 0 ) {
2286 return;
2287 }
2288
2289 $session = $this->getRequest()->getSession();
2290 if ( $request && $session->getRequest() !== $request ) {
2291 $session = $session->sessionWithRequest( $request );
2292 }
2293 $delay = $session->delaySave();
2294
2295 if ( !$session->getUser()->equals( $this ) ) {
2296 if ( !$session->canSetUser() ) {
2297 LoggerFactory::getInstance( 'session' )
2298 ->warning( __METHOD__ .
2299 ": Cannot save user \"$this\" to a user " .
2300 "\"{$session->getUser()}\"'s immutable session"
2301 );
2302 return;
2303 }
2304 $session->setUser( $this );
2305 }
2306
2307 $session->setRememberUser( $rememberMe );
2308 if ( $secure !== null ) {
2309 $session->setForceHTTPS( $secure );
2310 }
2311
2312 $session->persist();
2313
2314 ScopedCallback::consume( $delay );
2315 }
2316
2317 /**
2318 * Log this user out.
2319 */
2320 public function logout() {
2321 if ( $this->getHookRunner()->onUserLogout( $this ) ) {
2322 $this->doLogout();
2323 }
2324 }
2325
2326 /**
2327 * Clear the user's session, and reset the instance cache.
2328 * @see logout()
2329 */
2330 public function doLogout() {
2331 $session = $this->getRequest()->getSession();
2332 if ( !$session->canSetUser() ) {
2333 LoggerFactory::getInstance( 'session' )
2334 ->warning( __METHOD__ . ": Cannot log out of an immutable session" );
2335 $error = 'immutable';
2336 } elseif ( !$session->getUser()->equals( $this ) ) {
2337 LoggerFactory::getInstance( 'session' )
2338 ->warning( __METHOD__ .
2339 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
2340 );
2341 // But we still may as well make this user object anon
2342 $this->clearInstanceCache( 'defaults' );
2343 $error = 'wronguser';
2344 } else {
2345 $this->clearInstanceCache( 'defaults' );
2346 $delay = $session->delaySave();
2347 $session->unpersist(); // Clear cookies (T127436)
2348 $session->setLoggedOutTimestamp( time() );
2349 $session->setUser( new User );
2350 $session->set( 'wsUserID', 0 ); // Other code expects this
2351 $session->resetAllTokens();
2352 ScopedCallback::consume( $delay );
2353 $error = false;
2354 }
2355 LoggerFactory::getInstance( 'authevents' )->info( 'Logout', [
2356 'event' => 'logout',
2357 'successful' => $error === false,
2358 'status' => $error ?: 'success',
2359 ] );
2360 }
2361
2362 /**
2363 * Save this user's settings into the database.
2364 * @todo Only rarely do all these fields need to be set!
2365 */
2366 public function saveSettings() {
2367 if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
2368 // @TODO: caller should deal with this instead!
2369 // This should really just be an exception.
2370 MWExceptionHandler::logException( new DBExpectedError(
2371 null,
2372 "Could not update user with ID '{$this->mId}'; DB is read-only."
2373 ) );
2374 return;
2375 }
2376
2377 $this->load();
2378 if ( $this->mId == 0 ) {
2379 return; // anon
2380 }
2381
2382 // Get a new user_touched that is higher than the old one.
2383 // This will be used for a CAS check as a last-resort safety
2384 // check against race conditions and replica DB lag.
2385 $newTouched = $this->newTouchedTimestamp();
2386
2387 $dbw = MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase();
2388 $dbw->doAtomicSection( __METHOD__, function ( IDatabase $dbw, $fname ) use ( $newTouched ) {
2389 $dbw->newUpdateQueryBuilder()
2390 ->update( 'user' )
2391 ->set( [
2392 'user_name' => $this->mName,
2393 'user_real_name' => $this->mRealName,
2394 'user_email' => $this->mEmail,
2395 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2396 'user_touched' => $dbw->timestamp( $newTouched ),
2397 'user_token' => strval( $this->mToken ),
2398 'user_email_token' => $this->mEmailToken,
2399 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
2400 ] )
2401 ->where( $this->makeUpdateConditions( $dbw, [ /* WHERE */
2402 'user_id' => $this->mId,
2403 ] ) )
2404 ->caller( $fname )->execute();
2405
2406 if ( !$dbw->affectedRows() ) {
2407 // Maybe the problem was a missed cache update; clear it to be safe
2408 $this->clearSharedCache( 'refresh' );
2409 // User was changed in the meantime or loaded with stale data
2410 $from = ( $this->queryFlagsUsed & IDBAccessObject::READ_LATEST ) ? 'primary' : 'replica';
2411 LoggerFactory::getInstance( 'preferences' )->warning(
2412 "CAS update failed on user_touched for user ID '{user_id}' ({db_flag} read)",
2413 [ 'user_id' => $this->mId, 'db_flag' => $from ]
2414 );
2415 throw new RuntimeException( "CAS update failed on user_touched. " .
2416 "The version of the user to be saved is older than the current version."
2417 );
2418 }
2419
2420 $dbw->newUpdateQueryBuilder()
2421 ->update( 'actor' )
2422 ->set( [ 'actor_name' => $this->mName ] )
2423 ->where( [ 'actor_user' => $this->mId ] )
2424 ->caller( $fname )->execute();
2425 MediaWikiServices::getInstance()->getActorStore()->deleteUserIdentityFromCache( $this );
2426 } );
2427
2428 $this->mTouched = $newTouched;
2429 if ( $this->isNamed() ) {
2430 MediaWikiServices::getInstance()->getUserOptionsManager()->saveOptionsInternal( $this );
2431 }
2432
2433 $this->getHookRunner()->onUserSaveSettings( $this );
2434 $this->clearSharedCache( 'changed' );
2435 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2436 $hcu->purgeTitleUrls( $this->getUserPage(), $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2437 }
2438
2439 /**
2440 * If only this user's username is known, and it exists, return the user ID.
2441 *
2442 * @param int $flags Bitfield of IDBAccessObject::READ_* constants; useful for existence checks
2443 * @return int
2444 */
2445 public function idForName( $flags = IDBAccessObject::READ_NORMAL ) {
2446 $s = trim( $this->getName() );
2447 if ( $s === '' ) {
2448 return 0;
2449 }
2450
2451 $db = DBAccessObjectUtils::getDBFromRecency(
2452 MediaWikiServices::getInstance()->getDBLoadBalancerFactory(),
2453 $flags
2454 );
2455 $id = $db->newSelectQueryBuilder()
2456 ->select( 'user_id' )
2457 ->from( 'user' )
2458 ->where( [ 'user_name' => $s ] )
2459 ->recency( $flags )
2460 ->caller( __METHOD__ )->fetchField();
2461
2462 return (int)$id;
2463 }
2464
2465 /**
2466 * Add a user to the database, return the user object
2467 *
2468 * @param string $name Username to add
2469 * @param array $params Array of Strings Non-default parameters to save to
2470 * the database as user_* fields:
2471 * - email: The user's email address.
2472 * - email_authenticated: The email authentication timestamp.
2473 * - real_name: The user's real name.
2474 * - token: Random authentication token. Do not set.
2475 * - registration: Registration timestamp. Do not set.
2476 * @return User|null User object, or null if the username already exists.
2477 */
2478 public static function createNew( $name, $params = [] ) {
2479 return self::insertNewUser( static function ( UserIdentity $actor, IDatabase $dbw ) {
2480 return MediaWikiServices::getInstance()->getActorStore()->createNewActor( $actor, $dbw );
2481 }, $name, $params );
2482 }
2483
2484 /**
2485 * See ::createNew
2486 * @param callable $insertActor ( UserIdentity $actor, IDatabase $dbw ): int actor ID,
2487 * @param string $name
2488 * @param array $params
2489 * @return User|null User object, or null if the username already exists.
2490 */
2491 private static function insertNewUser( callable $insertActor, $name, $params = [] ) {
2492 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
2493 if ( isset( $params[$field] ) ) {
2494 wfDeprecated( __METHOD__ . " with param '$field'", '1.27' );
2495 unset( $params[$field] );
2496 }
2497 }
2498
2499 $user = new User;
2500 $user->load();
2501 $user->setToken(); // init token
2502 $dbw = MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase();
2503
2504 $noPass = PasswordFactory::newInvalidPassword()->toString();
2505
2506 $fields = [
2507 'user_name' => $name,
2508 'user_password' => $noPass,
2509 'user_newpassword' => $noPass,
2510 'user_email' => $user->mEmail,
2511 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
2512 'user_real_name' => $user->mRealName,
2513 'user_token' => strval( $user->mToken ),
2514 'user_registration' => $dbw->timestamp( $user->mRegistration ),
2515 'user_editcount' => 0,
2516 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
2517 ];
2518 foreach ( $params as $name => $value ) {
2519 $fields["user_$name"] = $value;
2520 }
2521
2522 return $dbw->doAtomicSection( __METHOD__, static function ( IDatabase $dbw, $fname )
2523 use ( $fields, $insertActor )
2524 {
2525 $dbw->newInsertQueryBuilder()
2526 ->insertInto( 'user' )
2527 ->ignore()
2528 ->row( $fields )
2529 ->caller( $fname )->execute();
2530 if ( $dbw->affectedRows() ) {
2531 $newUser = self::newFromId( $dbw->insertId() );
2532 $newUser->mName = $fields['user_name'];
2533 // Don't pass $this, since calling ::getId, ::getName might force ::load
2534 // and this user might not be ready for the yet.
2535 $newUser->mActorId = $insertActor(
2536 new UserIdentityValue( $newUser->mId, $newUser->mName ),
2537 $dbw
2538 );
2539 // Load the user from primary DB to avoid replica lag
2540 $newUser->load( IDBAccessObject::READ_LATEST );
2541 } else {
2542 $newUser = null;
2543 }
2544 return $newUser;
2545 } );
2546 }
2547
2548 /**
2549 * Add this existing user object to the database. If the user already
2550 * exists, a fatal status object is returned, and the user object is
2551 * initialised with the data from the database.
2552 *
2553 * Previously, this function generated a DB error due to a key conflict
2554 * if the user already existed. Many extension callers use this function
2555 * in code along the lines of:
2556 *
2557 * $user = User::newFromName( $name );
2558 * if ( !$user->isRegistered() ) {
2559 * $user->addToDatabase();
2560 * }
2561 * // do something with $user...
2562 *
2563 * However, this was vulnerable to a race condition (T18020). By
2564 * initialising the user object if the user exists, we aim to support this
2565 * calling sequence as far as possible.
2566 *
2567 * Note that if the user exists, this function will acquire a write lock,
2568 * so it is still advisable to make the call conditional on isRegistered(),
2569 * and to commit the transaction after calling.
2570 *
2571 * @return Status
2572 */
2573 public function addToDatabase() {
2574 $this->load();
2575 if ( !$this->mToken ) {
2576 $this->setToken(); // init token
2577 }
2578
2579 if ( !is_string( $this->mName ) ) {
2580 throw new RuntimeException( "User name field is not set." );
2581 }
2582
2583 $this->mTouched = $this->newTouchedTimestamp();
2584
2585 $dbw = MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase();
2586 $status = $dbw->doAtomicSection( __METHOD__, function ( IDatabase $dbw, $fname ) {
2587 $noPass = PasswordFactory::newInvalidPassword()->toString();
2588 $dbw->newInsertQueryBuilder()
2589 ->insertInto( 'user' )
2590 ->ignore()
2591 ->row( [
2592 'user_name' => $this->mName,
2593 'user_password' => $noPass,
2594 'user_newpassword' => $noPass,
2595 'user_email' => $this->mEmail,
2596 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2597 'user_real_name' => $this->mRealName,
2598 'user_token' => strval( $this->mToken ),
2599 'user_registration' => $dbw->timestamp( $this->mRegistration ),
2600 'user_editcount' => 0,
2601 'user_touched' => $dbw->timestamp( $this->mTouched ),
2602 'user_is_temp' => $this->isTemp(),
2603 ] )
2604 ->caller( $fname )->execute();
2605 if ( !$dbw->affectedRows() ) {
2606 // Use locking reads to bypass any REPEATABLE-READ snapshot.
2607 $this->mId = $dbw->newSelectQueryBuilder()
2608 ->select( 'user_id' )
2609 ->lockInShareMode()
2610 ->from( 'user' )
2611 ->where( [ 'user_name' => $this->mName ] )
2612 ->caller( $fname )->fetchField();
2613 $loaded = false;
2614 if ( $this->mId && $this->loadFromDatabase( IDBAccessObject::READ_LOCKING ) ) {
2615 $loaded = true;
2616 }
2617 if ( !$loaded ) {
2618 throw new RuntimeException( $fname . ": hit a key conflict attempting " .
2619 "to insert user '{$this->mName}' row, but it was not present in select!" );
2620 }
2621 return Status::newFatal( 'userexists' );
2622 }
2623 $this->mId = $dbw->insertId();
2624
2625 // Don't pass $this, since calling ::getId, ::getName might force ::load
2626 // and this user might not be ready for the yet.
2627 $this->mActorId = MediaWikiServices::getInstance()
2628 ->getActorNormalization()
2629 ->acquireActorId( new UserIdentityValue( $this->mId, $this->mName ), $dbw );
2630 return Status::newGood();
2631 } );
2632 if ( !$status->isGood() ) {
2633 return $status;
2634 }
2635
2636 // Clear instance cache other than user table data and actor, which is already accurate
2637 $this->clearInstanceCache();
2638
2639 if ( $this->isNamed() ) {
2640 MediaWikiServices::getInstance()->getUserOptionsManager()->saveOptions( $this );
2641 }
2642 return Status::newGood();
2643 }
2644
2645 /**
2646 * If this user is logged-in and blocked, block any IP address they've successfully logged in from.
2647 * Calls the "SpreadAnyEditBlock" hook, so this may block the IP address using a non-core blocking mechanism.
2648 *
2649 * @return bool A block was spread
2650 */
2651 public function spreadAnyEditBlock() {
2652 if ( !$this->isRegistered() ) {
2653 return false;
2654 }
2655
2656 $blockWasSpread = false;
2657 $this->getHookRunner()->onSpreadAnyEditBlock( $this, $blockWasSpread );
2658
2659 if ( $this->getBlock() ) {
2660 $blockWasSpread = $blockWasSpread || $this->spreadBlock();
2661 }
2662
2663 return $blockWasSpread;
2664 }
2665
2666 /**
2667 * If this (non-anonymous) user is blocked,
2668 * block the IP address they've successfully logged in from.
2669 * @return bool A block was spread
2670 */
2671 protected function spreadBlock() {
2672 wfDebug( __METHOD__ . "()" );
2673 $this->load();
2674 if ( $this->mId == 0 ) {
2675 return false;
2676 }
2677
2678 $blockStore = MediaWikiServices::getInstance()->getDatabaseBlockStore();
2679
2680 $userblock = $blockStore->newFromTarget( $this->getName() );
2681 if ( !$userblock ) {
2682 return false;
2683 }
2684
2685 return (bool)$blockStore->doAutoblock( $userblock, $this->getRequest()->getIP() );
2686 }
2687
2688 /**
2689 * Get whether the user is blocked from using Special:Emailuser.
2690 * @return bool
2691 * @deprecated since 1.41, emits deprecation warnings since 1.43. EmailUser::canSend
2692 * checks blocks amongst other things. If you only need this check, use
2693 * ::getBlock()->appliesToRight( 'sendemail' ).
2694 */
2695 public function isBlockedFromEmailuser() {
2696 wfDeprecated( __METHOD__, '1.41' );
2697 $block = $this->getBlock();
2698 return $block && $block->appliesToRight( 'sendemail' );
2699 }
2700
2701 /**
2702 * Get whether the user is blocked from using Special:Upload
2703 *
2704 * @since 1.33
2705 * @return bool
2706 */
2707 public function isBlockedFromUpload() {
2708 $block = $this->getBlock();
2709 return $block && $block->appliesToRight( 'upload' );
2710 }
2711
2712 /**
2713 * Get whether the user is allowed to create an account.
2714 * @return bool
2715 */
2716 public function isAllowedToCreateAccount() {
2717 return $this->getThisAsAuthority()->isDefinitelyAllowed( 'createaccount' );
2718 }
2719
2720 /**
2721 * Get this user's personal page title.
2722 *
2723 * @return Title User's personal page title
2724 */
2725 public function getUserPage() {
2726 return Title::makeTitle( NS_USER, $this->getName() );
2727 }
2728
2729 /**
2730 * Get this user's talk page title.
2731 *
2732 * @return Title
2733 */
2734 public function getTalkPage() {
2735 $title = $this->getUserPage();
2736 return $title->getTalkPage();
2737 }
2738
2739 /**
2740 * Determine whether the user is a newbie. Newbies are one of:
2741 * - IP address editors
2742 * - temporary accounts
2743 * - most recently created full accounts.
2744 * @return bool
2745 */
2746 public function isNewbie() {
2747 // IP users and temp account users are excluded from the autoconfirmed group.
2748 return !$this->isAllowed( 'autoconfirmed' );
2749 }
2750
2751 /**
2752 * Initialize (if necessary) and return a session token value
2753 * which can be used in edit forms to show that the user's
2754 * login credentials aren't being hijacked with a foreign form
2755 * submission.
2756 *
2757 * @since 1.27
2758 * @deprecated since 1.37. Use CsrfTokenSet::getToken instead
2759 * @param string|string[] $salt Optional function-specific data for hashing
2760 * @param WebRequest|null $request WebRequest object to use, or null to use the global request
2761 * @return Token The new edit token
2762 */
2763 public function getEditTokenObject( $salt = '', $request = null ) {
2764 if ( $this->isAnon() ) {
2765 return new LoggedOutEditToken();
2766 }
2767
2768 if ( !$request ) {
2769 $request = $this->getRequest();
2770 }
2771 return $request->getSession()->getToken( $salt );
2772 }
2773
2774 /**
2775 * Initialize (if necessary) and return a session token value
2776 * which can be used in edit forms to show that the user's
2777 * login credentials aren't being hijacked with a foreign form
2778 * submission.
2779 *
2780 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
2781 *
2782 * @since 1.19
2783 * @deprecated since 1.37. Use CsrfTokenSet::getToken instead
2784 * @param string|string[] $salt Optional function-specific data for hashing
2785 * @param WebRequest|null $request WebRequest object to use, or null to use the global request
2786 * @return string The new edit token
2787 */
2788 public function getEditToken( $salt = '', $request = null ) {
2789 return $this->getEditTokenObject( $salt, $request )->toString();
2790 }
2791
2792 /**
2793 * Check given value against the token value stored in the session.
2794 * A match should confirm that the form was submitted from the
2795 * user's own login session, not a form submission from a third-party
2796 * site.
2797 *
2798 * @deprecated since 1.37. Use CsrfTokenSet::matchToken instead
2799 * @param string|null $val Input value to compare
2800 * @param string|array $salt Optional function-specific data for hashing
2801 * @param WebRequest|null $request Object to use, or null to use the global request
2802 * @param int|null $maxage Fail tokens older than this, in seconds
2803 * @return bool Whether the token matches
2804 */
2805 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
2806 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
2807 }
2808
2809 /**
2810 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2811 * mail to the user's given address.
2812 *
2813 * @param string $type Message to send, either "created", "changed" or "set"
2814 * @return Status
2815 */
2816 public function sendConfirmationMail( $type = 'created' ) {
2817 global $wgLang;
2818 $expiration = null; // gets passed-by-ref and defined in next line.
2819 $token = $this->confirmationToken( $expiration );
2820 $url = $this->confirmationTokenUrl( $token );
2821 $invalidateURL = $this->invalidationTokenUrl( $token );
2822 $this->saveSettings();
2823
2824 if ( $type == 'created' || $type === false ) {
2825 $message = 'confirmemail_body';
2826 $type = 'created';
2827 } elseif ( $type === true ) {
2828 $message = 'confirmemail_body_changed';
2829 $type = 'changed';
2830 } else {
2831 // Messages: confirmemail_body_changed, confirmemail_body_set
2832 $message = 'confirmemail_body_' . $type;
2833 }
2834
2835 $mail = [
2836 'subject' => wfMessage( 'confirmemail_subject' )->text(),
2837 'body' => wfMessage( $message,
2838 $this->getRequest()->getIP(),
2839 $this->getName(),
2840 $url,
2841 $wgLang->userTimeAndDate( $expiration, $this ),
2842 $invalidateURL,
2843 $wgLang->userDate( $expiration, $this ),
2844 $wgLang->userTime( $expiration, $this ) )->text(),
2845 'from' => null,
2846 'replyTo' => null,
2847 ];
2848 $info = [
2849 'type' => $type,
2850 'ip' => $this->getRequest()->getIP(),
2851 'confirmURL' => $url,
2852 'invalidateURL' => $invalidateURL,
2853 'expiration' => $expiration
2854 ];
2855
2856 $this->getHookRunner()->onUserSendConfirmationMail( $this, $mail, $info );
2857 return $this->sendMail( $mail['subject'], $mail['body'], $mail['from'], $mail['replyTo'] );
2858 }
2859
2860 /**
2861 * Send an e-mail to this user's account. Does not check for
2862 * confirmed status or validity.
2863 *
2864 * @param string $subject Message subject
2865 * @param string|string[] $body Message body or array containing keys text and html
2866 * @param User|null $from Optional sending user; if unspecified, default
2867 * $wgPasswordSender will be used.
2868 * @param MailAddress|null $replyto Reply-To address
2869 * @return Status
2870 */
2871 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
2872 $passwordSender = MediaWikiServices::getInstance()->getMainConfig()
2873 ->get( MainConfigNames::PasswordSender );
2874
2875 if ( $from instanceof User ) {
2876 $sender = MailAddress::newFromUser( $from );
2877 } else {
2878 $sender = new MailAddress( $passwordSender,
2879 wfMessage( 'emailsender' )->inContentLanguage()->text() );
2880 }
2881 $to = MailAddress::newFromUser( $this );
2882
2883 if ( is_array( $body ) ) {
2884 $bodyText = $body['text'] ?? '';
2885 $bodyHtml = $body['html'] ?? null;
2886 } else {
2887 $bodyText = $body;
2888 $bodyHtml = null;
2889 }
2890
2891 return Status::wrap( MediaWikiServices::getInstance()->getEmailer()
2892 ->send(
2893 [ $to ],
2894 $sender,
2895 $subject,
2896 $bodyText,
2897 $bodyHtml,
2898 [ 'replyTo' => $replyto ]
2899 ) );
2900 }
2901
2902 /**
2903 * Generate, store, and return a new e-mail confirmation code.
2904 * A hash (unsalted, since it's used as a key) is stored.
2905 *
2906 * @note Call saveSettings() after calling this function to commit
2907 * this change to the database.
2908 *
2909 * @param string &$expiration Accepts the expiration time @phan-output-reference
2910 * @return string New token
2911 */
2912 protected function confirmationToken( &$expiration ) {
2913 $userEmailConfirmationTokenExpiry = MediaWikiServices::getInstance()
2914 ->getMainConfig()->get( MainConfigNames::UserEmailConfirmationTokenExpiry );
2915 $now = time();
2916 $expires = $now + $userEmailConfirmationTokenExpiry;
2917 $expiration = wfTimestamp( TS_MW, $expires );
2918 $this->load();
2919 $token = MWCryptRand::generateHex( 32 );
2920 $hash = md5( $token );
2921 $this->mEmailToken = $hash;
2922 $this->mEmailTokenExpires = $expiration;
2923 return $token;
2924 }
2925
2926 /**
2927 * Check if the given email confirmation token is well-formed (to detect mangling by
2928 * email clients). This does not check whether the token is valid.
2929 * @param string $token
2930 * @return bool
2931 */
2932 public static function isWellFormedConfirmationToken( string $token ): bool {
2933 return preg_match( '/^[a-f0-9]{32}$/', $token );
2934 }
2935
2936 /**
2937 * Return a URL the user can use to confirm their email address.
2938 * @param string $token Accepts the email confirmation token
2939 * @return string New token URL
2940 */
2941 protected function confirmationTokenUrl( $token ) {
2942 return $this->getTokenUrl( 'ConfirmEmail', $token );
2943 }
2944
2945 /**
2946 * Return a URL the user can use to invalidate their email address.
2947 * @param string $token Accepts the email confirmation token
2948 * @return string New token URL
2949 */
2950 protected function invalidationTokenUrl( $token ) {
2951 return $this->getTokenUrl( 'InvalidateEmail', $token );
2952 }
2953
2954 /**
2955 * Internal function to format the e-mail validation/invalidation URLs.
2956 * This uses a quickie hack to use the
2957 * hardcoded English names of the Special: pages, for ASCII safety.
2958 *
2959 * @note Since these URLs get dropped directly into emails, using the
2960 * short English names avoids really long URL-encoded links, which
2961 * also sometimes can get corrupted in some browsers/mailers
2962 * (T8957 with Gmail and Internet Explorer).
2963 *
2964 * @param string $page Special page
2965 * @param string $token
2966 * @return string Formatted URL
2967 */
2968 protected function getTokenUrl( $page, $token ) {
2969 // Hack to bypass localization of 'Special:'
2970 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
2971 return $title->getCanonicalURL();
2972 }
2973
2974 /**
2975 * Mark the e-mail address confirmed.
2976 *
2977 * @note Call saveSettings() after calling this function to commit the change.
2978 *
2979 * @return bool
2980 */
2981 public function confirmEmail() {
2982 // Check if it's already confirmed, so we don't touch the database
2983 // and fire the ConfirmEmailComplete hook on redundant confirmations.
2984 if ( !$this->isEmailConfirmed() ) {
2985 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2986 $this->getHookRunner()->onConfirmEmailComplete( $this );
2987 }
2988 return true;
2989 }
2990
2991 /**
2992 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
2993 * address if it was already confirmed.
2994 *
2995 * @note Call saveSettings() after calling this function to commit the change.
2996 * @return bool Returns true
2997 */
2998 public function invalidateEmail() {
2999 $this->load();
3000 $this->mEmailToken = null;
3001 $this->mEmailTokenExpires = null;
3002 $this->setEmailAuthenticationTimestamp( null );
3003 $this->mEmail = '';
3004 $this->getHookRunner()->onInvalidateEmailComplete( $this );
3005 return true;
3006 }
3007
3008 /**
3009 * Set the e-mail authentication timestamp.
3010 * @param string|null $timestamp TS_MW timestamp
3011 */
3012 public function setEmailAuthenticationTimestamp( $timestamp ) {
3013 $this->load();
3014 $this->mEmailAuthenticated = $timestamp;
3015 $this->getHookRunner()->onUserSetEmailAuthenticationTimestamp(
3016 $this, $this->mEmailAuthenticated );
3017 }
3018
3019 /**
3020 * Is this user allowed to send e-mails within limits of current
3021 * site configuration?
3022 * @deprecated since 1.41, emits deprecation warnings since 1.43.
3023 * Use EmailUser::canSend() instead.
3024 * @return bool
3025 */
3026 public function canSendEmail() {
3027 wfDeprecated( __METHOD__, '1.41' );
3028 $permError = MediaWikiServices::getInstance()->getEmailUserFactory()
3029 ->newEmailUser( $this->getThisAsAuthority() )
3030 ->canSend();
3031 return $permError->isGood();
3032 }
3033
3034 /**
3035 * Is this user allowed to receive e-mails within limits of current
3036 * site configuration?
3037 * @return bool
3038 */
3039 public function canReceiveEmail() {
3040 $userOptionsLookup = MediaWikiServices::getInstance()
3041 ->getUserOptionsLookup();
3042 return $this->isEmailConfirmed() && !$userOptionsLookup->getOption( $this, 'disablemail' );
3043 }
3044
3045 /**
3046 * Is this user's e-mail address valid-looking and confirmed within
3047 * limits of the current site configuration?
3048 *
3049 * @note If $wgEmailAuthentication is on, this may require the user to have
3050 * confirmed their address by returning a code or using a password
3051 * sent to the address from the wiki.
3052 *
3053 * @return bool
3054 */
3055 public function isEmailConfirmed(): bool {
3056 $emailAuthentication = MediaWikiServices::getInstance()->getMainConfig()
3057 ->get( MainConfigNames::EmailAuthentication );
3058 $this->load();
3059 $confirmed = true;
3060 if ( $this->getHookRunner()->onEmailConfirmed( $this, $confirmed ) ) {
3061 return !$this->isAnon() &&
3062 Sanitizer::validateEmail( $this->getEmail() ) &&
3063 ( !$emailAuthentication || $this->getEmailAuthenticationTimestamp() );
3064 }
3065
3066 return $confirmed;
3067 }
3068
3069 /**
3070 * Check whether there is an outstanding request for e-mail confirmation.
3071 * @return bool
3072 */
3073 public function isEmailConfirmationPending() {
3074 $emailAuthentication = MediaWikiServices::getInstance()->getMainConfig()
3075 ->get( MainConfigNames::EmailAuthentication );
3076 return $emailAuthentication &&
3077 !$this->isEmailConfirmed() &&
3078 $this->mEmailToken &&
3079 $this->mEmailTokenExpires > wfTimestamp();
3080 }
3081
3082 /**
3083 * Get the timestamp of account creation.
3084 *
3085 * @return string|false|null Timestamp of account creation, false for
3086 * non-existent/anonymous user accounts, or null if existing account
3087 * but information is not in database.
3088 */
3089 public function getRegistration() {
3090 if ( $this->isAnon() ) {
3091 return false;
3092 }
3093 $this->load();
3094 return $this->mRegistration;
3095 }
3096
3097 /**
3098 * Get the description of a given right as wikitext
3099 *
3100 * @since 1.29
3101 * @param string $right Right to query
3102 * @return string Localized description of the right
3103 */
3104 public static function getRightDescription( $right ) {
3105 $key = "right-$right";
3106 $msg = wfMessage( $key );
3107 return $msg->isDisabled() ? $right : $msg->text();
3108 }
3109
3110 /**
3111 * Get the description of a given right as rendered HTML
3112 *
3113 * @since 1.42
3114 * @param string $right Right to query
3115 * @return string HTML description of the right
3116 */
3117 public static function getRightDescriptionHtml( $right ) {
3118 return wfMessage( "right-$right" )->parse();
3119 }
3120
3121 /**
3122 * Return the tables, fields, and join conditions to be selected to create
3123 * a new user object.
3124 * @since 1.31
3125 * @return array[] With three keys:
3126 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
3127 * or `SelectQueryBuilder::tables`
3128 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
3129 * or `SelectQueryBuilder::fields`
3130 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
3131 * or `SelectQueryBuilder::joinConds`
3132 * @phan-return array{tables:string[],fields:string[],joins:array}
3133 */
3134 public static function getQueryInfo() {
3135 $ret = [
3136 'tables' => [ 'user', 'user_actor' => 'actor' ],
3137 'fields' => [
3138 'user_id',
3139 'user_name',
3140 'user_real_name',
3141 'user_email',
3142 'user_touched',
3143 'user_token',
3144 'user_email_authenticated',
3145 'user_email_token',
3146 'user_email_token_expires',
3147 'user_registration',
3148 'user_editcount',
3149 'user_actor.actor_id',
3150 ],
3151 'joins' => [
3152 'user_actor' => [ 'JOIN', 'user_actor.actor_user = user_id' ],
3153 ],
3154 ];
3155
3156 return $ret;
3157 }
3158
3159 /**
3160 * Get a SelectQueryBuilder with the tables, fields and join conditions
3161 * needed to create a new User object.
3162 *
3163 * The return value is a plain SelectQueryBuilder, not a UserSelectQueryBuilder.
3164 * That way, there is no need for an ActorStore.
3165 *
3166 * @return SelectQueryBuilder
3167 */
3168 public static function newQueryBuilder( IReadableDatabase $db ) {
3169 return $db->newSelectQueryBuilder()
3170 ->select( [
3171 'user_id',
3172 'user_name',
3173 'user_real_name',
3174 'user_email',
3175 'user_touched',
3176 'user_token',
3177 'user_email_authenticated',
3178 'user_email_token',
3179 'user_email_token_expires',
3180 'user_registration',
3181 'user_editcount',
3182 'user_actor.actor_id',
3183 ] )
3184 ->from( 'user' )
3185 ->join( 'actor', 'user_actor', 'user_actor.actor_user = user_id' );
3186 }
3187
3188 /**
3189 * Factory function for fatal permission-denied errors
3190 *
3191 * @since 1.22
3192 * @deprecated since 1.41, use Authority::isAllowed instead.
3193 * Core code can also use PermissionManager::newFatalPermissionDeniedStatus.
3194 *
3195 * @param string $permission User right required
3196 * @return Status
3197 */
3198 public static function newFatalPermissionDeniedStatus( $permission ) {
3199 return Status::wrap( MediaWikiServices::getInstance()->getPermissionManager()
3200 ->newFatalPermissionDeniedStatus(
3201 $permission,
3202 RequestContext::getMain()
3203 ) );
3204 }
3205
3206 /**
3207 * Get a new instance of this user that was loaded from the primary DB via a locking read
3208 *
3209 * Use this instead of the main context User when updating that user. This avoids races
3210 * where that user was loaded from a replica DB or even the primary DB but without proper locks.
3211 *
3212 * @return User|null Returns null if the user was not found in the DB
3213 * @since 1.27
3214 */
3215 public function getInstanceForUpdate() {
3216 if ( !$this->getId() ) {
3217 return null; // anon
3218 }
3219
3220 $user = self::newFromId( $this->getId() );
3221 if ( !$user->loadFromId( IDBAccessObject::READ_EXCLUSIVE ) ) {
3222 return null;
3223 }
3224
3225 return $user;
3226 }
3227
3228 /**
3229 * Checks if two user objects point to the same user.
3230 *
3231 * @since 1.25 ; takes a UserIdentity instead of a User since 1.32
3232 * @param UserIdentity|null $user
3233 * @return bool
3234 */
3235 public function equals( ?UserIdentity $user ): bool {
3236 if ( !$user ) {
3237 return false;
3238 }
3239 // XXX it's not clear whether central ID providers are supposed to obey this
3240 return $this->getName() === $user->getName();
3241 }
3242
3243 /**
3244 * @note This is only here for compatibility with the Authority interface.
3245 * @since 1.36
3246 * @return UserIdentity $this
3247 */
3248 public function getUser(): UserIdentity {
3249 return $this;
3250 }
3251
3252 /**
3253 * @since 1.36
3254 * @param string $action
3255 * @param PageIdentity $target
3256 * @param PermissionStatus|null $status
3257 * @return bool
3258 */
3259 public function probablyCan(
3260 string $action,
3261 PageIdentity $target,
3262 ?PermissionStatus $status = null
3263 ): bool {
3264 return $this->getThisAsAuthority()->probablyCan( $action, $target, $status );
3265 }
3266
3267 /**
3268 * @since 1.36
3269 * @param string $action
3270 * @param PageIdentity $target
3271 * @param PermissionStatus|null $status
3272 * @return bool
3273 */
3274 public function definitelyCan(
3275 string $action,
3276 PageIdentity $target,
3277 ?PermissionStatus $status = null
3278 ): bool {
3279 return $this->getThisAsAuthority()->definitelyCan( $action, $target, $status );
3280 }
3281
3282 /**
3283 * @inheritDoc
3284 *
3285 * @since 1.41
3286 * @param string $action
3287 * @param PermissionStatus|null $status
3288 * @return bool
3289 */
3290 public function isDefinitelyAllowed( string $action, ?PermissionStatus $status = null ): bool {
3291 return $this->getThisAsAuthority()->isDefinitelyAllowed( $action, $status );
3292 }
3293
3294 /**
3295 * @inheritDoc
3296 *
3297 * @since 1.41
3298 * @param string $action
3299 * @param PermissionStatus|null $status
3300 * @return bool
3301 */
3302 public function authorizeAction( string $action, ?PermissionStatus $status = null ): bool {
3303 return $this->getThisAsAuthority()->authorizeAction( $action, $status );
3304 }
3305
3306 /**
3307 * @since 1.36
3308 * @param string $action
3309 * @param PageIdentity $target
3310 * @param PermissionStatus|null $status
3311 * @return bool
3312 */
3313 public function authorizeRead(
3314 string $action,
3315 PageIdentity $target,
3316 ?PermissionStatus $status = null
3317 ): bool {
3318 return $this->getThisAsAuthority()->authorizeRead( $action, $target, $status );
3319 }
3320
3321 /**
3322 * @since 1.36
3323 * @param string $action
3324 * @param PageIdentity $target
3325 * @param PermissionStatus|null $status
3326 * @return bool
3327 */
3328 public function authorizeWrite(
3329 string $action, PageIdentity $target,
3330 ?PermissionStatus $status = null
3331 ): bool {
3332 return $this->getThisAsAuthority()->authorizeWrite( $action, $target, $status );
3333 }
3334
3335 /**
3336 * Returns the Authority of this User if it's the main request context user.
3337 * This is intended to exist only for the period of transition to Authority.
3338 * @return UserAuthority
3339 */
3340 private function getThisAsAuthority(): UserAuthority {
3341 if ( !$this->mThisAsAuthority ) {
3342 // TODO: For users that are not User::isGlobalSessionUser,
3343 // creating a UserAuthority here is incorrect, since it depends
3344 // on global WebRequest, but that is what we've used to do before Authority.
3345 // When PermissionManager is refactored into Authority, we need
3346 // to provide base implementation, based on just user groups/rights,
3347 // and use it here.
3348 $request = $this->getRequest();
3349 $uiContext = RequestContext::getMain();
3350
3351 $services = MediaWikiServices::getInstance();
3352 $this->mThisAsAuthority = new UserAuthority(
3353 $this,
3354 $request,
3355 $uiContext,
3356 $services->getPermissionManager(),
3357 $services->getRateLimiter(),
3358 $services->getFormatterFactory()->getBlockErrorFormatter( $uiContext )
3359 );
3360 }
3361
3362 return $this->mThisAsAuthority;
3363 }
3364
3365 /**
3366 * Check whether this is the global session user.
3367 * @return bool
3368 */
3369 private function isGlobalSessionUser(): bool {
3370 // The session user is set up towards the end of Setup.php. Until then,
3371 // assume it's a logged-out user.
3372 $sessionUser = RequestContext::getMain()->getUser();
3373 $globalUserName = $sessionUser->isSafeToLoad()
3374 ? $sessionUser->getName()
3375 : IPUtils::sanitizeIP( $sessionUser->getRequest()->getIP() );
3376
3377 return $this->getName() === $globalUserName;
3378 }
3379
3380 /**
3381 * Is the user an autocreated temporary user?
3382 * @since 1.39
3383 * @return bool
3384 */
3385 public function isTemp(): bool {
3386 if ( $this->isTemp === null ) {
3387 $this->isTemp = MediaWikiServices::getInstance()->getUserIdentityUtils()
3388 ->isTemp( $this );
3389 }
3390 return $this->isTemp;
3391 }
3392
3393 /**
3394 * Is the user a normal non-temporary registered user?
3395 *
3396 * @since 1.39
3397 * @return bool
3398 */
3399 public function isNamed(): bool {
3400 return $this->isRegistered() && !$this->isTemp();
3401 }
3402 }
3403
3404 /** @deprecated class alias since 1.41 */
3405 class_alias( User::class, 'User' );