Unsuppress phan issues, part 8
[lhc/web/wiklou.git] / includes / user / User.php
1 <?php
2 /**
3 * Implements the User class for the %MediaWiki software.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 use MediaWiki\Block\AbstractBlock;
24 use MediaWiki\Block\DatabaseBlock;
25 use MediaWiki\Block\SystemBlock;
26 use MediaWiki\MediaWikiServices;
27 use MediaWiki\Session\SessionManager;
28 use MediaWiki\Session\Token;
29 use MediaWiki\Auth\AuthManager;
30 use MediaWiki\Auth\AuthenticationResponse;
31 use MediaWiki\Auth\AuthenticationRequest;
32 use MediaWiki\User\UserIdentity;
33 use MediaWiki\Logger\LoggerFactory;
34 use Wikimedia\Assert\Assert;
35 use Wikimedia\IPSet;
36 use Wikimedia\ScopedCallback;
37 use Wikimedia\Rdbms\Database;
38 use Wikimedia\Rdbms\DBExpectedError;
39 use Wikimedia\Rdbms\IDatabase;
40
41 /**
42 * The User object encapsulates all of the user-specific settings (user_id,
43 * name, rights, email address, options, last login time). Client
44 * classes use the getXXX() functions to access these fields. These functions
45 * do all the work of determining whether the user is logged in,
46 * whether the requested option can be satisfied from cookies or
47 * whether a database query is needed. Most of the settings needed
48 * for rendering normal pages are set in the cookie to minimize use
49 * of the database.
50 */
51 class User implements IDBAccessObject, UserIdentity {
52
53 /**
54 * Number of characters required for the user_token field.
55 */
56 const TOKEN_LENGTH = 32;
57
58 /**
59 * An invalid string value for the user_token field.
60 */
61 const INVALID_TOKEN = '*** INVALID ***';
62
63 /**
64 * Version number to tag cached versions of serialized User objects. Should be increased when
65 * {@link $mCacheVars} or one of it's members changes.
66 */
67 const VERSION = 13;
68
69 /**
70 * Exclude user options that are set to their default value.
71 * @since 1.25
72 */
73 const GETOPTIONS_EXCLUDE_DEFAULTS = 1;
74
75 /**
76 * @since 1.27
77 */
78 const CHECK_USER_RIGHTS = true;
79
80 /**
81 * @since 1.27
82 */
83 const IGNORE_USER_RIGHTS = false;
84
85 /**
86 * Array of Strings List of member variables which are saved to the
87 * shared cache (memcached). Any operation which changes the
88 * corresponding database fields must call a cache-clearing function.
89 * @showinitializer
90 * @var string[]
91 */
92 protected static $mCacheVars = [
93 // user table
94 'mId',
95 'mName',
96 'mRealName',
97 'mEmail',
98 'mTouched',
99 'mToken',
100 'mEmailAuthenticated',
101 'mEmailToken',
102 'mEmailTokenExpires',
103 'mRegistration',
104 'mEditCount',
105 // user_groups table
106 'mGroupMemberships',
107 // user_properties table
108 'mOptionOverrides',
109 // actor table
110 'mActorId',
111 ];
112
113 /** Cache variables */
114 // @{
115 /** @var int */
116 public $mId;
117 /** @var string */
118 public $mName;
119 /** @var int|null */
120 protected $mActorId;
121 /** @var string */
122 public $mRealName;
123
124 /** @var string */
125 public $mEmail;
126 /** @var string TS_MW timestamp from the DB */
127 public $mTouched;
128 /** @var string TS_MW timestamp from cache */
129 protected $mQuickTouched;
130 /** @var string */
131 protected $mToken;
132 /** @var string */
133 public $mEmailAuthenticated;
134 /** @var string */
135 protected $mEmailToken;
136 /** @var string */
137 protected $mEmailTokenExpires;
138 /** @var string */
139 protected $mRegistration;
140 /** @var int */
141 protected $mEditCount;
142 /** @var UserGroupMembership[] Associative array of (group name => UserGroupMembership object) */
143 protected $mGroupMemberships;
144 /** @var array */
145 protected $mOptionOverrides;
146 // @}
147
148 // @{
149 /**
150 * @var bool Whether the cache variables have been loaded.
151 */
152 public $mOptionsLoaded;
153
154 /**
155 * @var array|bool Array with already loaded items or true if all items have been loaded.
156 */
157 protected $mLoadedItems = [];
158 // @}
159
160 /**
161 * @var string Initialization data source if mLoadedItems!==true. May be one of:
162 * - 'defaults' anonymous user initialised from class defaults
163 * - 'name' initialise from mName
164 * - 'id' initialise from mId
165 * - 'actor' initialise from mActorId
166 * - 'session' log in from session if possible
167 *
168 * Use the User::newFrom*() family of functions to set this.
169 */
170 public $mFrom;
171
172 /**
173 * Lazy-initialized variables, invalidated with clearInstanceCache
174 */
175 /** @var int|bool */
176 protected $mNewtalk;
177 /** @var string */
178 protected $mDatePreference;
179 /** @var string */
180 public $mBlockedby;
181 /** @var string */
182 protected $mHash;
183 /** @var string */
184 protected $mBlockreason;
185 /** @var array */
186 protected $mEffectiveGroups;
187 /** @var array */
188 protected $mImplicitGroups;
189 /** @var array */
190 protected $mFormerGroups;
191 /** @var AbstractBlock */
192 protected $mGlobalBlock;
193 /** @var bool */
194 protected $mLocked;
195 /** @var bool */
196 public $mHideName;
197 /** @var array */
198 public $mOptions;
199
200 /** @var WebRequest */
201 private $mRequest;
202
203 /** @var AbstractBlock */
204 public $mBlock;
205
206 /** @var bool */
207 protected $mAllowUsertalk;
208
209 /** @var AbstractBlock|bool */
210 private $mBlockedFromCreateAccount = false;
211
212 /** @var int User::READ_* constant bitfield used to load data */
213 protected $queryFlagsUsed = self::READ_NORMAL;
214
215 /** @var int[] */
216 public static $idCacheByName = [];
217
218 /**
219 * Lightweight constructor for an anonymous user.
220 * Use the User::newFrom* factory functions for other kinds of users.
221 *
222 * @see newFromName()
223 * @see newFromId()
224 * @see newFromActorId()
225 * @see newFromConfirmationCode()
226 * @see newFromSession()
227 * @see newFromRow()
228 */
229 public function __construct() {
230 $this->clearInstanceCache( 'defaults' );
231 }
232
233 /**
234 * @return string
235 */
236 public function __toString() {
237 return (string)$this->getName();
238 }
239
240 public function &__get( $name ) {
241 // A shortcut for $mRights deprecation phase
242 if ( $name === 'mRights' ) {
243 $copy = $this->getRights();
244 return $copy;
245 } elseif ( !property_exists( $this, $name ) ) {
246 // T227688 - do not break $u->foo['bar'] = 1
247 wfLogWarning( 'tried to get non-existent property' );
248 $this->$name = null;
249 return $this->$name;
250 } else {
251 wfLogWarning( 'tried to get non-visible property' );
252 return null;
253 }
254 }
255
256 public function __set( $name, $value ) {
257 // A shortcut for $mRights deprecation phase, only known legitimate use was for
258 // testing purposes, other uses seem bad in principle
259 if ( $name === 'mRights' ) {
260 MediaWikiServices::getInstance()->getPermissionManager()->overrideUserRightsForTesting(
261 $this,
262 is_null( $value ) ? [] : $value
263 );
264 } elseif ( !property_exists( $this, $name ) ) {
265 $this->$name = $value;
266 } else {
267 wfLogWarning( 'tried to set non-visible property' );
268 }
269 }
270
271 /**
272 * Test if it's safe to load this User object.
273 *
274 * You should typically check this before using $wgUser or
275 * RequestContext::getUser in a method that might be called before the
276 * system has been fully initialized. If the object is unsafe, you should
277 * use an anonymous user:
278 * \code
279 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
280 * \endcode
281 *
282 * @since 1.27
283 * @return bool
284 */
285 public function isSafeToLoad() {
286 global $wgFullyInitialised;
287
288 // The user is safe to load if:
289 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
290 // * mLoadedItems === true (already loaded)
291 // * mFrom !== 'session' (sessions not involved at all)
292
293 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
294 $this->mLoadedItems === true || $this->mFrom !== 'session';
295 }
296
297 /**
298 * Load the user table data for this object from the source given by mFrom.
299 *
300 * @param int $flags User::READ_* constant bitfield
301 */
302 public function load( $flags = self::READ_NORMAL ) {
303 global $wgFullyInitialised;
304
305 if ( $this->mLoadedItems === true ) {
306 return;
307 }
308
309 // Set it now to avoid infinite recursion in accessors
310 $oldLoadedItems = $this->mLoadedItems;
311 $this->mLoadedItems = true;
312 $this->queryFlagsUsed = $flags;
313
314 // If this is called too early, things are likely to break.
315 if ( !$wgFullyInitialised && $this->mFrom === 'session' ) {
316 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
317 ->warning( 'User::loadFromSession called before the end of Setup.php', [
318 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
319 ] );
320 $this->loadDefaults();
321 $this->mLoadedItems = $oldLoadedItems;
322 return;
323 }
324
325 switch ( $this->mFrom ) {
326 case 'defaults':
327 $this->loadDefaults();
328 break;
329 case 'name':
330 // Make sure this thread sees its own changes
331 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
332 if ( $lb->hasOrMadeRecentMasterChanges() ) {
333 $flags |= self::READ_LATEST;
334 $this->queryFlagsUsed = $flags;
335 }
336
337 $this->mId = self::idFromName( $this->mName, $flags );
338 if ( !$this->mId ) {
339 // Nonexistent user placeholder object
340 $this->loadDefaults( $this->mName );
341 } else {
342 $this->loadFromId( $flags );
343 }
344 break;
345 case 'id':
346 // Make sure this thread sees its own changes, if the ID isn't 0
347 if ( $this->mId != 0 ) {
348 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
349 if ( $lb->hasOrMadeRecentMasterChanges() ) {
350 $flags |= self::READ_LATEST;
351 $this->queryFlagsUsed = $flags;
352 }
353 }
354
355 $this->loadFromId( $flags );
356 break;
357 case 'actor':
358 // Make sure this thread sees its own changes
359 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
360 if ( $lb->hasOrMadeRecentMasterChanges() ) {
361 $flags |= self::READ_LATEST;
362 $this->queryFlagsUsed = $flags;
363 }
364
365 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
366 $row = wfGetDB( $index )->selectRow(
367 'actor',
368 [ 'actor_user', 'actor_name' ],
369 [ 'actor_id' => $this->mActorId ],
370 __METHOD__,
371 $options
372 );
373
374 if ( !$row ) {
375 // Ugh.
376 $this->loadDefaults();
377 } elseif ( $row->actor_user ) {
378 $this->mId = $row->actor_user;
379 $this->loadFromId( $flags );
380 } else {
381 $this->loadDefaults( $row->actor_name );
382 }
383 break;
384 case 'session':
385 if ( !$this->loadFromSession() ) {
386 // Loading from session failed. Load defaults.
387 $this->loadDefaults();
388 }
389 Hooks::run( 'UserLoadAfterLoadFromSession', [ $this ] );
390 break;
391 default:
392 throw new UnexpectedValueException(
393 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
394 }
395 }
396
397 /**
398 * Load user table data, given mId has already been set.
399 * @param int $flags User::READ_* constant bitfield
400 * @return bool False if the ID does not exist, true otherwise
401 */
402 public function loadFromId( $flags = self::READ_NORMAL ) {
403 if ( $this->mId == 0 ) {
404 // Anonymous users are not in the database (don't need cache)
405 $this->loadDefaults();
406 return false;
407 }
408
409 // Try cache (unless this needs data from the master DB).
410 // NOTE: if this thread called saveSettings(), the cache was cleared.
411 $latest = DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST );
412 if ( $latest ) {
413 if ( !$this->loadFromDatabase( $flags ) ) {
414 // Can't load from ID
415 return false;
416 }
417 } else {
418 $this->loadFromCache();
419 }
420
421 $this->mLoadedItems = true;
422 $this->queryFlagsUsed = $flags;
423
424 return true;
425 }
426
427 /**
428 * @since 1.27
429 * @param string $dbDomain
430 * @param int $userId
431 */
432 public static function purge( $dbDomain, $userId ) {
433 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
434 $key = $cache->makeGlobalKey( 'user', 'id', $dbDomain, $userId );
435 $cache->delete( $key );
436 }
437
438 /**
439 * @since 1.27
440 * @param WANObjectCache $cache
441 * @return string
442 */
443 protected function getCacheKey( WANObjectCache $cache ) {
444 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
445
446 return $cache->makeGlobalKey( 'user', 'id', $lbFactory->getLocalDomainID(), $this->mId );
447 }
448
449 /**
450 * @param WANObjectCache $cache
451 * @return string[]
452 * @since 1.28
453 */
454 public function getMutableCacheKeys( WANObjectCache $cache ) {
455 $id = $this->getId();
456
457 return $id ? [ $this->getCacheKey( $cache ) ] : [];
458 }
459
460 /**
461 * Load user data from shared cache, given mId has already been set.
462 *
463 * @return bool True
464 * @since 1.25
465 */
466 protected function loadFromCache() {
467 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
468 $data = $cache->getWithSetCallback(
469 $this->getCacheKey( $cache ),
470 $cache::TTL_HOUR,
471 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
472 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
473 wfDebug( "User: cache miss for user {$this->mId}\n" );
474
475 $this->loadFromDatabase( self::READ_NORMAL );
476 $this->loadGroups();
477 $this->loadOptions();
478
479 $data = [];
480 foreach ( self::$mCacheVars as $name ) {
481 $data[$name] = $this->$name;
482 }
483
484 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX, $this->mTouched ), $ttl );
485
486 // if a user group membership is about to expire, the cache needs to
487 // expire at that time (T163691)
488 foreach ( $this->mGroupMemberships as $ugm ) {
489 if ( $ugm->getExpiry() ) {
490 $secondsUntilExpiry = wfTimestamp( TS_UNIX, $ugm->getExpiry() ) - time();
491 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
492 $ttl = $secondsUntilExpiry;
493 }
494 }
495 }
496
497 return $data;
498 },
499 [ 'pcTTL' => $cache::TTL_PROC_LONG, 'version' => self::VERSION ]
500 );
501
502 // Restore from cache
503 foreach ( self::$mCacheVars as $name ) {
504 $this->$name = $data[$name];
505 }
506
507 return true;
508 }
509
510 /** @name newFrom*() static factory methods */
511 // @{
512
513 /**
514 * Static factory method for creation from username.
515 *
516 * This is slightly less efficient than newFromId(), so use newFromId() if
517 * you have both an ID and a name handy.
518 *
519 * @param string $name Username, validated by Title::newFromText()
520 * @param string|bool $validate Validate username. Takes the same parameters as
521 * User::getCanonicalName(), except that true is accepted as an alias
522 * for 'valid', for BC.
523 *
524 * @return User|bool User object, or false if the username is invalid
525 * (e.g. if it contains illegal characters or is an IP address). If the
526 * username is not present in the database, the result will be a user object
527 * with a name, zero user ID and default settings.
528 */
529 public static function newFromName( $name, $validate = 'valid' ) {
530 if ( $validate === true ) {
531 $validate = 'valid';
532 }
533 $name = self::getCanonicalName( $name, $validate );
534 if ( $name === false ) {
535 return false;
536 }
537
538 // Create unloaded user object
539 $u = new User;
540 $u->mName = $name;
541 $u->mFrom = 'name';
542 $u->setItemLoaded( 'name' );
543
544 return $u;
545 }
546
547 /**
548 * Static factory method for creation from a given user ID.
549 *
550 * @param int $id Valid user ID
551 * @return User The corresponding User object
552 */
553 public static function newFromId( $id ) {
554 $u = new User;
555 $u->mId = $id;
556 $u->mFrom = 'id';
557 $u->setItemLoaded( 'id' );
558 return $u;
559 }
560
561 /**
562 * Static factory method for creation from a given actor ID.
563 *
564 * @since 1.31
565 * @param int $id Valid actor ID
566 * @return User The corresponding User object
567 */
568 public static function newFromActorId( $id ) {
569 global $wgActorTableSchemaMigrationStage;
570
571 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
572 // but it does little harm and might be needed for write callers loading a User.
573 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW ) ) {
574 throw new BadMethodCallException(
575 'Cannot use ' . __METHOD__
576 . ' when $wgActorTableSchemaMigrationStage lacks SCHEMA_COMPAT_NEW'
577 );
578 }
579
580 $u = new User;
581 $u->mActorId = $id;
582 $u->mFrom = 'actor';
583 $u->setItemLoaded( 'actor' );
584 return $u;
585 }
586
587 /**
588 * Returns a User object corresponding to the given UserIdentity.
589 *
590 * @since 1.32
591 *
592 * @param UserIdentity $identity
593 *
594 * @return User
595 */
596 public static function newFromIdentity( UserIdentity $identity ) {
597 if ( $identity instanceof User ) {
598 return $identity;
599 }
600
601 return self::newFromAnyId(
602 $identity->getId() === 0 ? null : $identity->getId(),
603 $identity->getName() === '' ? null : $identity->getName(),
604 $identity->getActorId() === 0 ? null : $identity->getActorId()
605 );
606 }
607
608 /**
609 * Static factory method for creation from an ID, name, and/or actor ID
610 *
611 * This does not check that the ID, name, and actor ID all correspond to
612 * the same user.
613 *
614 * @since 1.31
615 * @param int|null $userId User ID, if known
616 * @param string|null $userName User name, if known
617 * @param int|null $actorId Actor ID, if known
618 * @param bool|string $dbDomain remote wiki to which the User/Actor ID applies, or false if none
619 * @return User
620 */
621 public static function newFromAnyId( $userId, $userName, $actorId, $dbDomain = false ) {
622 global $wgActorTableSchemaMigrationStage;
623
624 // Stop-gap solution for the problem described in T222212.
625 // Force the User ID and Actor ID to zero for users loaded from the database
626 // of another wiki, to prevent subtle data corruption and confusing failure modes.
627 if ( $dbDomain !== false ) {
628 $userId = 0;
629 $actorId = 0;
630 }
631
632 $user = new User;
633 $user->mFrom = 'defaults';
634
635 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
636 // but it does little harm and might be needed for write callers loading a User.
637 if ( ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW ) && $actorId !== null ) {
638 $user->mActorId = (int)$actorId;
639 if ( $user->mActorId !== 0 ) {
640 $user->mFrom = 'actor';
641 }
642 $user->setItemLoaded( 'actor' );
643 }
644
645 if ( $userName !== null && $userName !== '' ) {
646 $user->mName = $userName;
647 $user->mFrom = 'name';
648 $user->setItemLoaded( 'name' );
649 }
650
651 if ( $userId !== null ) {
652 $user->mId = (int)$userId;
653 if ( $user->mId !== 0 ) {
654 $user->mFrom = 'id';
655 }
656 $user->setItemLoaded( 'id' );
657 }
658
659 if ( $user->mFrom === 'defaults' ) {
660 throw new InvalidArgumentException(
661 'Cannot create a user with no name, no ID, and no actor ID'
662 );
663 }
664
665 return $user;
666 }
667
668 /**
669 * Factory method to fetch whichever user has a given email confirmation code.
670 * This code is generated when an account is created or its e-mail address
671 * has changed.
672 *
673 * If the code is invalid or has expired, returns NULL.
674 *
675 * @param string $code Confirmation code
676 * @param int $flags User::READ_* bitfield
677 * @return User|null
678 */
679 public static function newFromConfirmationCode( $code, $flags = 0 ) {
680 $db = ( $flags & self::READ_LATEST ) == self::READ_LATEST
681 ? wfGetDB( DB_MASTER )
682 : wfGetDB( DB_REPLICA );
683
684 $id = $db->selectField(
685 'user',
686 'user_id',
687 [
688 'user_email_token' => md5( $code ),
689 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
690 ]
691 );
692
693 return $id ? self::newFromId( $id ) : null;
694 }
695
696 /**
697 * Create a new user object using data from session. If the login
698 * credentials are invalid, the result is an anonymous user.
699 *
700 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
701 * @return User
702 */
703 public static function newFromSession( WebRequest $request = null ) {
704 $user = new User;
705 $user->mFrom = 'session';
706 $user->mRequest = $request;
707 return $user;
708 }
709
710 /**
711 * Create a new user object from a user row.
712 * The row should have the following fields from the user table in it:
713 * - either user_name or user_id to load further data if needed (or both)
714 * - user_real_name
715 * - all other fields (email, etc.)
716 * It is useless to provide the remaining fields if either user_id,
717 * user_name and user_real_name are not provided because the whole row
718 * will be loaded once more from the database when accessing them.
719 *
720 * @param stdClass $row A row from the user table
721 * @param array|null $data Further data to load into the object
722 * (see User::loadFromRow for valid keys)
723 * @return User
724 */
725 public static function newFromRow( $row, $data = null ) {
726 $user = new User;
727 $user->loadFromRow( $row, $data );
728 return $user;
729 }
730
731 /**
732 * Static factory method for creation of a "system" user from username.
733 *
734 * A "system" user is an account that's used to attribute logged actions
735 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
736 * might include the 'Maintenance script' or 'Conversion script' accounts
737 * used by various scripts in the maintenance/ directory or accounts such
738 * as 'MediaWiki message delivery' used by the MassMessage extension.
739 *
740 * This can optionally create the user if it doesn't exist, and "steal" the
741 * account if it does exist.
742 *
743 * "Stealing" an existing user is intended to make it impossible for normal
744 * authentication processes to use the account, effectively disabling the
745 * account for normal use:
746 * - Email is invalidated, to prevent account recovery by emailing a
747 * temporary password and to disassociate the account from the existing
748 * human.
749 * - The token is set to a magic invalid value, to kill existing sessions
750 * and to prevent $this->setToken() calls from resetting the token to a
751 * valid value.
752 * - SessionManager is instructed to prevent new sessions for the user, to
753 * do things like deauthorizing OAuth consumers.
754 * - AuthManager is instructed to revoke access, to invalidate or remove
755 * passwords and other credentials.
756 *
757 * @param string $name Username
758 * @param array $options Options are:
759 * - validate: As for User::getCanonicalName(), default 'valid'
760 * - create: Whether to create the user if it doesn't already exist, default true
761 * - steal: Whether to "disable" the account for normal use if it already
762 * exists, default false
763 * @return User|null
764 * @since 1.27
765 */
766 public static function newSystemUser( $name, $options = [] ) {
767 $options += [
768 'validate' => 'valid',
769 'create' => true,
770 'steal' => false,
771 ];
772
773 $name = self::getCanonicalName( $name, $options['validate'] );
774 if ( $name === false ) {
775 return null;
776 }
777
778 $dbr = wfGetDB( DB_REPLICA );
779 $userQuery = self::getQueryInfo();
780 $row = $dbr->selectRow(
781 $userQuery['tables'],
782 $userQuery['fields'],
783 [ 'user_name' => $name ],
784 __METHOD__,
785 [],
786 $userQuery['joins']
787 );
788 if ( !$row ) {
789 // Try the master database...
790 $dbw = wfGetDB( DB_MASTER );
791 $row = $dbw->selectRow(
792 $userQuery['tables'],
793 $userQuery['fields'],
794 [ 'user_name' => $name ],
795 __METHOD__,
796 [],
797 $userQuery['joins']
798 );
799 }
800
801 if ( !$row ) {
802 // No user. Create it?
803 return $options['create']
804 ? self::createNew( $name, [ 'token' => self::INVALID_TOKEN ] )
805 : null;
806 }
807
808 $user = self::newFromRow( $row );
809
810 // A user is considered to exist as a non-system user if it can
811 // authenticate, or has an email set, or has a non-invalid token.
812 if ( $user->mEmail || $user->mToken !== self::INVALID_TOKEN ||
813 AuthManager::singleton()->userCanAuthenticate( $name )
814 ) {
815 // User exists. Steal it?
816 if ( !$options['steal'] ) {
817 return null;
818 }
819
820 AuthManager::singleton()->revokeAccessForUser( $name );
821
822 $user->invalidateEmail();
823 $user->mToken = self::INVALID_TOKEN;
824 $user->saveSettings();
825 SessionManager::singleton()->preventSessionsForUser( $user->getName() );
826 }
827
828 return $user;
829 }
830
831 // @}
832
833 /**
834 * Get the username corresponding to a given user ID
835 * @param int $id User ID
836 * @return string|bool The corresponding username
837 */
838 public static function whoIs( $id ) {
839 return UserCache::singleton()->getProp( $id, 'name' );
840 }
841
842 /**
843 * Get the real name of a user given their user ID
844 *
845 * @param int $id User ID
846 * @return string|bool The corresponding user's real name
847 */
848 public static function whoIsReal( $id ) {
849 return UserCache::singleton()->getProp( $id, 'real_name' );
850 }
851
852 /**
853 * Get database id given a user name
854 * @param string $name Username
855 * @param int $flags User::READ_* constant bitfield
856 * @return int|null The corresponding user's ID, or null if user is nonexistent
857 */
858 public static function idFromName( $name, $flags = self::READ_NORMAL ) {
859 // Don't explode on self::$idCacheByName[$name] if $name is not a string but e.g. a User object
860 $name = (string)$name;
861 $nt = Title::makeTitleSafe( NS_USER, $name );
862 if ( is_null( $nt ) ) {
863 // Illegal name
864 return null;
865 }
866
867 if ( !( $flags & self::READ_LATEST ) && array_key_exists( $name, self::$idCacheByName ) ) {
868 return is_null( self::$idCacheByName[$name] ) ? null : (int)self::$idCacheByName[$name];
869 }
870
871 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
872 $db = wfGetDB( $index );
873
874 $s = $db->selectRow(
875 'user',
876 [ 'user_id' ],
877 [ 'user_name' => $nt->getText() ],
878 __METHOD__,
879 $options
880 );
881
882 if ( $s === false ) {
883 $result = null;
884 } else {
885 $result = (int)$s->user_id;
886 }
887
888 if ( count( self::$idCacheByName ) >= 1000 ) {
889 self::$idCacheByName = [];
890 }
891
892 self::$idCacheByName[$name] = $result;
893
894 return $result;
895 }
896
897 /**
898 * Reset the cache used in idFromName(). For use in tests.
899 */
900 public static function resetIdByNameCache() {
901 self::$idCacheByName = [];
902 }
903
904 /**
905 * Does the string match an anonymous IP address?
906 *
907 * This function exists for username validation, in order to reject
908 * usernames which are similar in form to IP addresses. Strings such
909 * as 300.300.300.300 will return true because it looks like an IP
910 * address, despite not being strictly valid.
911 *
912 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
913 * address because the usemod software would "cloak" anonymous IP
914 * addresses like this, if we allowed accounts like this to be created
915 * new users could get the old edits of these anonymous users.
916 *
917 * @param string $name Name to match
918 * @return bool
919 */
920 public static function isIP( $name ) {
921 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
922 || IP::isIPv6( $name );
923 }
924
925 /**
926 * Is the user an IP range?
927 *
928 * @since 1.30
929 * @return bool
930 */
931 public function isIPRange() {
932 return IP::isValidRange( $this->mName );
933 }
934
935 /**
936 * Is the input a valid username?
937 *
938 * Checks if the input is a valid username, we don't want an empty string,
939 * an IP address, anything that contains slashes (would mess up subpages),
940 * is longer than the maximum allowed username size or doesn't begin with
941 * a capital letter.
942 *
943 * @param string $name Name to match
944 * @return bool
945 */
946 public static function isValidUserName( $name ) {
947 global $wgMaxNameChars;
948
949 if ( $name == ''
950 || self::isIP( $name )
951 || strpos( $name, '/' ) !== false
952 || strlen( $name ) > $wgMaxNameChars
953 || $name != MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $name )
954 ) {
955 return false;
956 }
957
958 // Ensure that the name can't be misresolved as a different title,
959 // such as with extra namespace keys at the start.
960 $parsed = Title::newFromText( $name );
961 if ( is_null( $parsed )
962 || $parsed->getNamespace()
963 || strcmp( $name, $parsed->getPrefixedText() ) ) {
964 return false;
965 }
966
967 // Check an additional blacklist of troublemaker characters.
968 // Should these be merged into the title char list?
969 $unicodeBlacklist = '/[' .
970 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
971 '\x{00a0}' . # non-breaking space
972 '\x{2000}-\x{200f}' . # various whitespace
973 '\x{2028}-\x{202f}' . # breaks and control chars
974 '\x{3000}' . # ideographic space
975 '\x{e000}-\x{f8ff}' . # private use
976 ']/u';
977 if ( preg_match( $unicodeBlacklist, $name ) ) {
978 return false;
979 }
980
981 return true;
982 }
983
984 /**
985 * Usernames which fail to pass this function will be blocked
986 * from user login and new account registrations, but may be used
987 * internally by batch processes.
988 *
989 * If an account already exists in this form, login will be blocked
990 * by a failure to pass this function.
991 *
992 * @param string $name Name to match
993 * @return bool
994 */
995 public static function isUsableName( $name ) {
996 global $wgReservedUsernames;
997 // Must be a valid username, obviously ;)
998 if ( !self::isValidUserName( $name ) ) {
999 return false;
1000 }
1001
1002 static $reservedUsernames = false;
1003 if ( !$reservedUsernames ) {
1004 $reservedUsernames = $wgReservedUsernames;
1005 Hooks::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
1006 }
1007
1008 // Certain names may be reserved for batch processes.
1009 foreach ( $reservedUsernames as $reserved ) {
1010 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
1011 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->plain();
1012 }
1013 if ( $reserved == $name ) {
1014 return false;
1015 }
1016 }
1017 return true;
1018 }
1019
1020 /**
1021 * Return the users who are members of the given group(s). In case of multiple groups,
1022 * users who are members of at least one of them are returned.
1023 *
1024 * @param string|array $groups A single group name or an array of group names
1025 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
1026 * records; larger values are ignored.
1027 * @param int|null $after ID the user to start after
1028 * @return UserArrayFromResult
1029 */
1030 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
1031 if ( $groups === [] ) {
1032 return UserArrayFromResult::newFromIDs( [] );
1033 }
1034
1035 $groups = array_unique( (array)$groups );
1036 $limit = min( 5000, $limit );
1037
1038 $conds = [ 'ug_group' => $groups ];
1039 if ( $after !== null ) {
1040 $conds[] = 'ug_user > ' . (int)$after;
1041 }
1042
1043 $dbr = wfGetDB( DB_REPLICA );
1044 $ids = $dbr->selectFieldValues(
1045 'user_groups',
1046 'ug_user',
1047 $conds,
1048 __METHOD__,
1049 [
1050 'DISTINCT' => true,
1051 'ORDER BY' => 'ug_user',
1052 'LIMIT' => $limit,
1053 ]
1054 ) ?: [];
1055 return UserArray::newFromIDs( $ids );
1056 }
1057
1058 /**
1059 * Usernames which fail to pass this function will be blocked
1060 * from new account registrations, but may be used internally
1061 * either by batch processes or by user accounts which have
1062 * already been created.
1063 *
1064 * Additional blacklisting may be added here rather than in
1065 * isValidUserName() to avoid disrupting existing accounts.
1066 *
1067 * @param string $name String to match
1068 * @return bool
1069 */
1070 public static function isCreatableName( $name ) {
1071 global $wgInvalidUsernameCharacters;
1072
1073 // Ensure that the username isn't longer than 235 bytes, so that
1074 // (at least for the builtin skins) user javascript and css files
1075 // will work. (T25080)
1076 if ( strlen( $name ) > 235 ) {
1077 wfDebugLog( 'username', __METHOD__ .
1078 ": '$name' invalid due to length" );
1079 return false;
1080 }
1081
1082 // Preg yells if you try to give it an empty string
1083 if ( $wgInvalidUsernameCharacters !== '' &&
1084 preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name )
1085 ) {
1086 wfDebugLog( 'username', __METHOD__ .
1087 ": '$name' invalid due to wgInvalidUsernameCharacters" );
1088 return false;
1089 }
1090
1091 return self::isUsableName( $name );
1092 }
1093
1094 /**
1095 * Is the input a valid password for this user?
1096 *
1097 * @param string $password Desired password
1098 * @return bool
1099 */
1100 public function isValidPassword( $password ) {
1101 // simple boolean wrapper for checkPasswordValidity
1102 return $this->checkPasswordValidity( $password )->isGood();
1103 }
1104
1105 /**
1106 * Check if this is a valid password for this user
1107 *
1108 * Returns a Status object with a set of messages describing
1109 * problems with the password. If the return status is fatal,
1110 * the action should be refused and the password should not be
1111 * checked at all (this is mainly meant for DoS mitigation).
1112 * If the return value is OK but not good, the password can be checked,
1113 * but the user should not be able to set their password to this.
1114 * The value of the returned Status object will be an array which
1115 * can have the following fields:
1116 * - forceChange (bool): if set to true, the user should not be
1117 * allowed to log with this password unless they change it during
1118 * the login process (see ResetPasswordSecondaryAuthenticationProvider).
1119 * - suggestChangeOnLogin (bool): if set to true, the user should be prompted for
1120 * a password change on login.
1121 *
1122 * @param string $password Desired password
1123 * @return Status
1124 * @since 1.23
1125 */
1126 public function checkPasswordValidity( $password ) {
1127 global $wgPasswordPolicy;
1128
1129 $upp = new UserPasswordPolicy(
1130 $wgPasswordPolicy['policies'],
1131 $wgPasswordPolicy['checks']
1132 );
1133
1134 $status = Status::newGood( [] );
1135 $result = false; // init $result to false for the internal checks
1136
1137 if ( !Hooks::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1138 $status->error( $result );
1139 return $status;
1140 }
1141
1142 if ( $result === false ) {
1143 $status->merge( $upp->checkUserPassword( $this, $password ), true );
1144 return $status;
1145 }
1146
1147 if ( $result === true ) {
1148 return $status;
1149 }
1150
1151 $status->error( $result );
1152 return $status; // the isValidPassword hook set a string $result and returned true
1153 }
1154
1155 /**
1156 * Given unvalidated user input, return a canonical username, or false if
1157 * the username is invalid.
1158 * @param string $name User input
1159 * @param string|bool $validate Type of validation to use:
1160 * - false No validation
1161 * - 'valid' Valid for batch processes
1162 * - 'usable' Valid for batch processes and login
1163 * - 'creatable' Valid for batch processes, login and account creation
1164 *
1165 * @throws InvalidArgumentException
1166 * @return bool|string
1167 */
1168 public static function getCanonicalName( $name, $validate = 'valid' ) {
1169 // Force usernames to capital
1170 $name = MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $name );
1171
1172 # Reject names containing '#'; these will be cleaned up
1173 # with title normalisation, but then it's too late to
1174 # check elsewhere
1175 if ( strpos( $name, '#' ) !== false ) {
1176 return false;
1177 }
1178
1179 // Clean up name according to title rules,
1180 // but only when validation is requested (T14654)
1181 $t = ( $validate !== false ) ?
1182 Title::newFromText( $name, NS_USER ) : Title::makeTitle( NS_USER, $name );
1183 // Check for invalid titles
1184 if ( is_null( $t ) || $t->getNamespace() !== NS_USER || $t->isExternal() ) {
1185 return false;
1186 }
1187
1188 $name = $t->getText();
1189
1190 switch ( $validate ) {
1191 case false:
1192 break;
1193 case 'valid':
1194 if ( !self::isValidUserName( $name ) ) {
1195 $name = false;
1196 }
1197 break;
1198 case 'usable':
1199 if ( !self::isUsableName( $name ) ) {
1200 $name = false;
1201 }
1202 break;
1203 case 'creatable':
1204 if ( !self::isCreatableName( $name ) ) {
1205 $name = false;
1206 }
1207 break;
1208 default:
1209 throw new InvalidArgumentException(
1210 'Invalid parameter value for $validate in ' . __METHOD__ );
1211 }
1212 return $name;
1213 }
1214
1215 /**
1216 * Set cached properties to default.
1217 *
1218 * @note This no longer clears uncached lazy-initialised properties;
1219 * the constructor does that instead.
1220 *
1221 * @param string|bool $name
1222 */
1223 public function loadDefaults( $name = false ) {
1224 $this->mId = 0;
1225 $this->mName = $name;
1226 $this->mActorId = null;
1227 $this->mRealName = '';
1228 $this->mEmail = '';
1229 $this->mOptionOverrides = null;
1230 $this->mOptionsLoaded = false;
1231
1232 $loggedOut = $this->mRequest && !defined( 'MW_NO_SESSION' )
1233 ? $this->mRequest->getSession()->getLoggedOutTimestamp() : 0;
1234 if ( $loggedOut !== 0 ) {
1235 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
1236 } else {
1237 $this->mTouched = '1'; # Allow any pages to be cached
1238 }
1239
1240 $this->mToken = null; // Don't run cryptographic functions till we need a token
1241 $this->mEmailAuthenticated = null;
1242 $this->mEmailToken = '';
1243 $this->mEmailTokenExpires = null;
1244 $this->mRegistration = wfTimestamp( TS_MW );
1245 $this->mGroupMemberships = [];
1246
1247 Hooks::run( 'UserLoadDefaults', [ $this, $name ] );
1248 }
1249
1250 /**
1251 * Return whether an item has been loaded.
1252 *
1253 * @param string $item Item to check. Current possibilities:
1254 * - id
1255 * - name
1256 * - realname
1257 * @param string $all 'all' to check if the whole object has been loaded
1258 * or any other string to check if only the item is available (e.g.
1259 * for optimisation)
1260 * @return bool
1261 */
1262 public function isItemLoaded( $item, $all = 'all' ) {
1263 return ( $this->mLoadedItems === true && $all === 'all' ) ||
1264 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1265 }
1266
1267 /**
1268 * Set that an item has been loaded
1269 *
1270 * @param string $item
1271 */
1272 protected function setItemLoaded( $item ) {
1273 if ( is_array( $this->mLoadedItems ) ) {
1274 $this->mLoadedItems[$item] = true;
1275 }
1276 }
1277
1278 /**
1279 * Load user data from the session.
1280 *
1281 * @return bool True if the user is logged in, false otherwise.
1282 */
1283 private function loadFromSession() {
1284 // MediaWiki\Session\Session already did the necessary authentication of the user
1285 // returned here, so just use it if applicable.
1286 $session = $this->getRequest()->getSession();
1287 $user = $session->getUser();
1288 if ( $user->isLoggedIn() ) {
1289 $this->loadFromUserObject( $user );
1290
1291 // If this user is autoblocked, set a cookie to track the block. This has to be done on
1292 // every session load, because an autoblocked editor might not edit again from the same
1293 // IP address after being blocked.
1294 MediaWikiServices::getInstance()->getBlockManager()->trackBlockWithCookie( $this );
1295
1296 // Other code expects these to be set in the session, so set them.
1297 $session->set( 'wsUserID', $this->getId() );
1298 $session->set( 'wsUserName', $this->getName() );
1299 $session->set( 'wsToken', $this->getToken() );
1300
1301 return true;
1302 }
1303
1304 return false;
1305 }
1306
1307 /**
1308 * Set the 'BlockID' cookie depending on block type and user authentication status.
1309 *
1310 * @deprecated since 1.34 Use BlockManager::trackBlockWithCookie instead
1311 */
1312 public function trackBlockWithCookie() {
1313 MediaWikiServices::getInstance()->getBlockManager()->trackBlockWithCookie( $this );
1314 }
1315
1316 /**
1317 * Load user and user_group data from the database.
1318 * $this->mId must be set, this is how the user is identified.
1319 *
1320 * @param int $flags User::READ_* constant bitfield
1321 * @return bool True if the user exists, false if the user is anonymous
1322 */
1323 public function loadFromDatabase( $flags = self::READ_LATEST ) {
1324 // Paranoia
1325 $this->mId = intval( $this->mId );
1326
1327 if ( !$this->mId ) {
1328 // Anonymous users are not in the database
1329 $this->loadDefaults();
1330 return false;
1331 }
1332
1333 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
1334 $db = wfGetDB( $index );
1335
1336 $userQuery = self::getQueryInfo();
1337 $s = $db->selectRow(
1338 $userQuery['tables'],
1339 $userQuery['fields'],
1340 [ 'user_id' => $this->mId ],
1341 __METHOD__,
1342 $options,
1343 $userQuery['joins']
1344 );
1345
1346 $this->queryFlagsUsed = $flags;
1347 Hooks::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1348
1349 if ( $s !== false ) {
1350 // Initialise user table data
1351 $this->loadFromRow( $s );
1352 $this->mGroupMemberships = null; // deferred
1353 $this->getEditCount(); // revalidation for nulls
1354 return true;
1355 }
1356
1357 // Invalid user_id
1358 $this->mId = 0;
1359 $this->loadDefaults();
1360
1361 return false;
1362 }
1363
1364 /**
1365 * Initialize this object from a row from the user table.
1366 *
1367 * @param stdClass $row Row from the user table to load.
1368 * @param array|null $data Further user data to load into the object
1369 *
1370 * user_groups Array of arrays or stdClass result rows out of the user_groups
1371 * table. Previously you were supposed to pass an array of strings
1372 * here, but we also need expiry info nowadays, so an array of
1373 * strings is ignored.
1374 * user_properties Array with properties out of the user_properties table
1375 */
1376 protected function loadFromRow( $row, $data = null ) {
1377 global $wgActorTableSchemaMigrationStage;
1378
1379 if ( !is_object( $row ) ) {
1380 throw new InvalidArgumentException( '$row must be an object' );
1381 }
1382
1383 $all = true;
1384
1385 $this->mGroupMemberships = null; // deferred
1386
1387 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
1388 // but it does little harm and might be needed for write callers loading a User.
1389 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW ) {
1390 if ( isset( $row->actor_id ) ) {
1391 $this->mActorId = (int)$row->actor_id;
1392 if ( $this->mActorId !== 0 ) {
1393 $this->mFrom = 'actor';
1394 }
1395 $this->setItemLoaded( 'actor' );
1396 } else {
1397 $all = false;
1398 }
1399 }
1400
1401 if ( isset( $row->user_name ) && $row->user_name !== '' ) {
1402 $this->mName = $row->user_name;
1403 $this->mFrom = 'name';
1404 $this->setItemLoaded( 'name' );
1405 } else {
1406 $all = false;
1407 }
1408
1409 if ( isset( $row->user_real_name ) ) {
1410 $this->mRealName = $row->user_real_name;
1411 $this->setItemLoaded( 'realname' );
1412 } else {
1413 $all = false;
1414 }
1415
1416 if ( isset( $row->user_id ) ) {
1417 $this->mId = intval( $row->user_id );
1418 if ( $this->mId !== 0 ) {
1419 $this->mFrom = 'id';
1420 }
1421 $this->setItemLoaded( 'id' );
1422 } else {
1423 $all = false;
1424 }
1425
1426 if ( isset( $row->user_id ) && isset( $row->user_name ) && $row->user_name !== '' ) {
1427 self::$idCacheByName[$row->user_name] = $row->user_id;
1428 }
1429
1430 if ( isset( $row->user_editcount ) ) {
1431 $this->mEditCount = $row->user_editcount;
1432 } else {
1433 $all = false;
1434 }
1435
1436 if ( isset( $row->user_touched ) ) {
1437 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1438 } else {
1439 $all = false;
1440 }
1441
1442 if ( isset( $row->user_token ) ) {
1443 // The definition for the column is binary(32), so trim the NULs
1444 // that appends. The previous definition was char(32), so trim
1445 // spaces too.
1446 $this->mToken = rtrim( $row->user_token, " \0" );
1447 if ( $this->mToken === '' ) {
1448 $this->mToken = null;
1449 }
1450 } else {
1451 $all = false;
1452 }
1453
1454 if ( isset( $row->user_email ) ) {
1455 $this->mEmail = $row->user_email;
1456 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1457 $this->mEmailToken = $row->user_email_token;
1458 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1459 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1460 } else {
1461 $all = false;
1462 }
1463
1464 if ( $all ) {
1465 $this->mLoadedItems = true;
1466 }
1467
1468 if ( is_array( $data ) ) {
1469 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1470 if ( $data['user_groups'] === [] ) {
1471 $this->mGroupMemberships = [];
1472 } else {
1473 $firstGroup = reset( $data['user_groups'] );
1474 if ( is_array( $firstGroup ) || is_object( $firstGroup ) ) {
1475 $this->mGroupMemberships = [];
1476 foreach ( $data['user_groups'] as $row ) {
1477 $ugm = UserGroupMembership::newFromRow( (object)$row );
1478 $this->mGroupMemberships[$ugm->getGroup()] = $ugm;
1479 }
1480 }
1481 }
1482 }
1483 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1484 $this->loadOptions( $data['user_properties'] );
1485 }
1486 }
1487 }
1488
1489 /**
1490 * Load the data for this user object from another user object.
1491 *
1492 * @param User $user
1493 */
1494 protected function loadFromUserObject( $user ) {
1495 $user->load();
1496 foreach ( self::$mCacheVars as $var ) {
1497 $this->$var = $user->$var;
1498 }
1499 }
1500
1501 /**
1502 * Load the groups from the database if they aren't already loaded.
1503 */
1504 private function loadGroups() {
1505 if ( is_null( $this->mGroupMemberships ) ) {
1506 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
1507 ? wfGetDB( DB_MASTER )
1508 : wfGetDB( DB_REPLICA );
1509 $this->mGroupMemberships = UserGroupMembership::getMembershipsForUser(
1510 $this->mId, $db );
1511 }
1512 }
1513
1514 /**
1515 * Add the user to the group if he/she meets given criteria.
1516 *
1517 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1518 * possible to remove manually via Special:UserRights. In such case it
1519 * will not be re-added automatically. The user will also not lose the
1520 * group if they no longer meet the criteria.
1521 *
1522 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1523 *
1524 * @return array Array of groups the user has been promoted to.
1525 *
1526 * @see $wgAutopromoteOnce
1527 */
1528 public function addAutopromoteOnceGroups( $event ) {
1529 global $wgAutopromoteOnceLogInRC;
1530
1531 if ( wfReadOnly() || !$this->getId() ) {
1532 return [];
1533 }
1534
1535 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1536 if ( $toPromote === [] ) {
1537 return [];
1538 }
1539
1540 if ( !$this->checkAndSetTouched() ) {
1541 return []; // raced out (bug T48834)
1542 }
1543
1544 $oldGroups = $this->getGroups(); // previous groups
1545 $oldUGMs = $this->getGroupMemberships();
1546 foreach ( $toPromote as $group ) {
1547 $this->addGroup( $group );
1548 }
1549 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1550 $newUGMs = $this->getGroupMemberships();
1551
1552 // update groups in external authentication database
1553 Hooks::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false, $oldUGMs, $newUGMs ] );
1554
1555 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1556 $logEntry->setPerformer( $this );
1557 $logEntry->setTarget( $this->getUserPage() );
1558 $logEntry->setParameters( [
1559 '4::oldgroups' => $oldGroups,
1560 '5::newgroups' => $newGroups,
1561 ] );
1562 $logid = $logEntry->insert();
1563 if ( $wgAutopromoteOnceLogInRC ) {
1564 $logEntry->publish( $logid );
1565 }
1566
1567 return $toPromote;
1568 }
1569
1570 /**
1571 * Builds update conditions. Additional conditions may be added to $conditions to
1572 * protected against race conditions using a compare-and-set (CAS) mechanism
1573 * based on comparing $this->mTouched with the user_touched field.
1574 *
1575 * @param IDatabase $db
1576 * @param array $conditions WHERE conditions for use with Database::update
1577 * @return array WHERE conditions for use with Database::update
1578 */
1579 protected function makeUpdateConditions( IDatabase $db, array $conditions ) {
1580 if ( $this->mTouched ) {
1581 // CAS check: only update if the row wasn't changed sicne it was loaded.
1582 $conditions['user_touched'] = $db->timestamp( $this->mTouched );
1583 }
1584
1585 return $conditions;
1586 }
1587
1588 /**
1589 * Bump user_touched if it didn't change since this object was loaded
1590 *
1591 * On success, the mTouched field is updated.
1592 * The user serialization cache is always cleared.
1593 *
1594 * @return bool Whether user_touched was actually updated
1595 * @since 1.26
1596 */
1597 protected function checkAndSetTouched() {
1598 $this->load();
1599
1600 if ( !$this->mId ) {
1601 return false; // anon
1602 }
1603
1604 // Get a new user_touched that is higher than the old one
1605 $newTouched = $this->newTouchedTimestamp();
1606
1607 $dbw = wfGetDB( DB_MASTER );
1608 $dbw->update( 'user',
1609 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1610 $this->makeUpdateConditions( $dbw, [
1611 'user_id' => $this->mId,
1612 ] ),
1613 __METHOD__
1614 );
1615 $success = ( $dbw->affectedRows() > 0 );
1616
1617 if ( $success ) {
1618 $this->mTouched = $newTouched;
1619 $this->clearSharedCache( 'changed' );
1620 } else {
1621 // Clears on failure too since that is desired if the cache is stale
1622 $this->clearSharedCache( 'refresh' );
1623 }
1624
1625 return $success;
1626 }
1627
1628 /**
1629 * Clear various cached data stored in this object. The cache of the user table
1630 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1631 *
1632 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1633 * given source. May be "name", "id", "actor", "defaults", "session", or false for no reload.
1634 */
1635 public function clearInstanceCache( $reloadFrom = false ) {
1636 global $wgFullyInitialised;
1637
1638 $this->mNewtalk = -1;
1639 $this->mDatePreference = null;
1640 $this->mBlockedby = -1; # Unset
1641 $this->mHash = false;
1642 $this->mEffectiveGroups = null;
1643 $this->mImplicitGroups = null;
1644 $this->mGroupMemberships = null;
1645 $this->mOptions = null;
1646 $this->mOptionsLoaded = false;
1647 $this->mEditCount = null;
1648
1649 // Replacement of former `$this->mRights = null` line
1650 if ( $wgFullyInitialised && $this->mFrom ) {
1651 MediaWikiServices::getInstance()->getPermissionManager()->invalidateUsersRightsCache(
1652 $this
1653 );
1654 }
1655
1656 if ( $reloadFrom ) {
1657 $this->mLoadedItems = [];
1658 $this->mFrom = $reloadFrom;
1659 }
1660 }
1661
1662 /** @var array|null */
1663 private static $defOpt = null;
1664 /** @var string|null */
1665 private static $defOptLang = null;
1666
1667 /**
1668 * Reset the process cache of default user options. This is only necessary
1669 * if the wiki configuration has changed since defaults were calculated,
1670 * and as such should only be performed inside the testing suite that
1671 * regularly changes wiki configuration.
1672 */
1673 public static function resetGetDefaultOptionsForTestsOnly() {
1674 Assert::invariant( defined( 'MW_PHPUNIT_TEST' ), 'Unit tests only' );
1675 self::$defOpt = null;
1676 self::$defOptLang = null;
1677 }
1678
1679 /**
1680 * Combine the language default options with any site-specific options
1681 * and add the default language variants.
1682 *
1683 * @return array Array of String options
1684 */
1685 public static function getDefaultOptions() {
1686 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgDefaultSkin;
1687
1688 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
1689 if ( self::$defOpt !== null && self::$defOptLang === $contLang->getCode() ) {
1690 // The content language does not change (and should not change) mid-request, but the
1691 // unit tests change it anyway, and expect this method to return values relevant to the
1692 // current content language.
1693 return self::$defOpt;
1694 }
1695
1696 self::$defOpt = $wgDefaultUserOptions;
1697 // Default language setting
1698 self::$defOptLang = $contLang->getCode();
1699 self::$defOpt['language'] = self::$defOptLang;
1700 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1701 if ( $langCode === $contLang->getCode() ) {
1702 self::$defOpt['variant'] = $langCode;
1703 } else {
1704 self::$defOpt["variant-$langCode"] = $langCode;
1705 }
1706 }
1707
1708 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1709 // since extensions may change the set of searchable namespaces depending
1710 // on user groups/permissions.
1711 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1712 self::$defOpt['searchNs' . $nsnum] = (bool)$val;
1713 }
1714 self::$defOpt['skin'] = Skin::normalizeKey( $wgDefaultSkin );
1715
1716 Hooks::run( 'UserGetDefaultOptions', [ &self::$defOpt ] );
1717
1718 return self::$defOpt;
1719 }
1720
1721 /**
1722 * Get a given default option value.
1723 *
1724 * @param string $opt Name of option to retrieve
1725 * @return string Default option value
1726 */
1727 public static function getDefaultOption( $opt ) {
1728 $defOpts = self::getDefaultOptions();
1729 return $defOpts[$opt] ?? null;
1730 }
1731
1732 /**
1733 * Get blocking information
1734 *
1735 * TODO: Move this into the BlockManager, along with block-related properties.
1736 *
1737 * @param bool $fromReplica Whether to check the replica DB first.
1738 * To improve performance, non-critical checks are done against replica DBs.
1739 * Check when actually saving should be done against master.
1740 */
1741 private function getBlockedStatus( $fromReplica = true ) {
1742 if ( $this->mBlockedby != -1 ) {
1743 return;
1744 }
1745
1746 wfDebug( __METHOD__ . ": checking...\n" );
1747
1748 // Initialize data...
1749 // Otherwise something ends up stomping on $this->mBlockedby when
1750 // things get lazy-loaded later, causing false positive block hits
1751 // due to -1 !== 0. Probably session-related... Nothing should be
1752 // overwriting mBlockedby, surely?
1753 $this->load();
1754
1755 // @phan-suppress-next-line PhanAccessMethodInternal It's the only allowed use
1756 $block = MediaWikiServices::getInstance()->getBlockManager()->getUserBlock(
1757 $this,
1758 $fromReplica
1759 );
1760
1761 if ( $block ) {
1762 $this->mBlock = $block;
1763 $this->mBlockedby = $block->getByName();
1764 $this->mBlockreason = $block->getReason();
1765 $this->mHideName = $block->getHideName();
1766 $this->mAllowUsertalk = $block->isUsertalkEditAllowed();
1767 } else {
1768 $this->mBlock = null;
1769 $this->mBlockedby = '';
1770 $this->mBlockreason = '';
1771 $this->mHideName = 0;
1772 $this->mAllowUsertalk = false;
1773 }
1774
1775 // Avoid PHP 7.1 warning of passing $this by reference
1776 $thisUser = $this;
1777 // Extensions
1778 Hooks::run( 'GetBlockedStatus', [ &$thisUser ] );
1779 }
1780
1781 /**
1782 * Whether the given IP is in a DNS blacklist.
1783 *
1784 * @deprecated since 1.34 Use BlockManager::isDnsBlacklisted.
1785 * @param string $ip IP to check
1786 * @param bool $checkWhitelist Whether to check the whitelist first
1787 * @return bool True if blacklisted.
1788 */
1789 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1790 return MediaWikiServices::getInstance()->getBlockManager()
1791 ->isDnsBlacklisted( $ip, $checkWhitelist );
1792 }
1793
1794 /**
1795 * Whether the given IP is in a given DNS blacklist.
1796 *
1797 * @deprecated since 1.34 Check via BlockManager::isDnsBlacklisted instead.
1798 * @param string $ip IP to check
1799 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1800 * @return bool True if blacklisted.
1801 */
1802 public function inDnsBlacklist( $ip, $bases ) {
1803 wfDeprecated( __METHOD__, '1.34' );
1804
1805 $found = false;
1806 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1807 if ( IP::isIPv4( $ip ) ) {
1808 // Reverse IP, T23255
1809 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1810
1811 foreach ( (array)$bases as $base ) {
1812 // Make hostname
1813 // If we have an access key, use that too (ProjectHoneypot, etc.)
1814 $basename = $base;
1815 if ( is_array( $base ) ) {
1816 if ( count( $base ) >= 2 ) {
1817 // Access key is 1, base URL is 0
1818 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1819 } else {
1820 $host = "$ipReversed.{$base[0]}";
1821 }
1822 $basename = $base[0];
1823 } else {
1824 $host = "$ipReversed.$base";
1825 }
1826
1827 // Send query
1828 $ipList = gethostbynamel( $host );
1829
1830 if ( $ipList ) {
1831 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1832 $found = true;
1833 break;
1834 }
1835
1836 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1837 }
1838 }
1839
1840 return $found;
1841 }
1842
1843 /**
1844 * Check if an IP address is in the local proxy list
1845 *
1846 * @deprecated since 1.34 Use BlockManager::getUserBlock instead.
1847 * @param string $ip
1848 * @return bool
1849 */
1850 public static function isLocallyBlockedProxy( $ip ) {
1851 wfDeprecated( __METHOD__, '1.34' );
1852
1853 global $wgProxyList;
1854
1855 if ( !$wgProxyList ) {
1856 return false;
1857 }
1858
1859 if ( !is_array( $wgProxyList ) ) {
1860 // Load values from the specified file
1861 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1862 }
1863
1864 $resultProxyList = [];
1865 $deprecatedIPEntries = [];
1866
1867 // backward compatibility: move all ip addresses in keys to values
1868 foreach ( $wgProxyList as $key => $value ) {
1869 $keyIsIP = IP::isIPAddress( $key );
1870 $valueIsIP = IP::isIPAddress( $value );
1871 if ( $keyIsIP && !$valueIsIP ) {
1872 $deprecatedIPEntries[] = $key;
1873 $resultProxyList[] = $key;
1874 } elseif ( $keyIsIP && $valueIsIP ) {
1875 $deprecatedIPEntries[] = $key;
1876 $resultProxyList[] = $key;
1877 $resultProxyList[] = $value;
1878 } else {
1879 $resultProxyList[] = $value;
1880 }
1881 }
1882
1883 if ( $deprecatedIPEntries ) {
1884 wfDeprecated(
1885 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
1886 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
1887 }
1888
1889 $proxyListIPSet = new IPSet( $resultProxyList );
1890 return $proxyListIPSet->match( $ip );
1891 }
1892
1893 /**
1894 * Is this user subject to rate limiting?
1895 *
1896 * @return bool True if rate limited
1897 */
1898 public function isPingLimitable() {
1899 global $wgRateLimitsExcludedIPs;
1900 if ( IP::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1901 // No other good way currently to disable rate limits
1902 // for specific IPs. :P
1903 // But this is a crappy hack and should die.
1904 return false;
1905 }
1906 return !$this->isAllowed( 'noratelimit' );
1907 }
1908
1909 /**
1910 * Primitive rate limits: enforce maximum actions per time period
1911 * to put a brake on flooding.
1912 *
1913 * The method generates both a generic profiling point and a per action one
1914 * (suffix being "-$action".
1915 *
1916 * @note When using a shared cache like memcached, IP-address
1917 * last-hit counters will be shared across wikis.
1918 *
1919 * @param string $action Action to enforce; 'edit' if unspecified
1920 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1921 * @return bool True if a rate limiter was tripped
1922 */
1923 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1924 // Avoid PHP 7.1 warning of passing $this by reference
1925 $user = $this;
1926 // Call the 'PingLimiter' hook
1927 $result = false;
1928 if ( !Hooks::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
1929 return $result;
1930 }
1931
1932 global $wgRateLimits;
1933 if ( !isset( $wgRateLimits[$action] ) ) {
1934 return false;
1935 }
1936
1937 $limits = array_merge(
1938 [ '&can-bypass' => true ],
1939 $wgRateLimits[$action]
1940 );
1941
1942 // Some groups shouldn't trigger the ping limiter, ever
1943 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1944 return false;
1945 }
1946
1947 $keys = [];
1948 $id = $this->getId();
1949 $userLimit = false;
1950 $isNewbie = $this->isNewbie();
1951 $cache = ObjectCache::getLocalClusterInstance();
1952
1953 if ( $id == 0 ) {
1954 // limits for anons
1955 if ( isset( $limits['anon'] ) ) {
1956 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1957 }
1958 } elseif ( isset( $limits['user'] ) ) {
1959 // limits for logged-in users
1960 $userLimit = $limits['user'];
1961 }
1962
1963 // limits for anons and for newbie logged-in users
1964 if ( $isNewbie ) {
1965 // ip-based limits
1966 if ( isset( $limits['ip'] ) ) {
1967 $ip = $this->getRequest()->getIP();
1968 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1969 }
1970 // subnet-based limits
1971 if ( isset( $limits['subnet'] ) ) {
1972 $ip = $this->getRequest()->getIP();
1973 $subnet = IP::getSubnet( $ip );
1974 if ( $subnet !== false ) {
1975 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1976 }
1977 }
1978 }
1979
1980 // Check for group-specific permissions
1981 // If more than one group applies, use the group with the highest limit ratio (max/period)
1982 foreach ( $this->getGroups() as $group ) {
1983 if ( isset( $limits[$group] ) ) {
1984 if ( $userLimit === false
1985 || $limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1986 ) {
1987 $userLimit = $limits[$group];
1988 }
1989 }
1990 }
1991
1992 // limits for newbie logged-in users (override all the normal user limits)
1993 if ( $id !== 0 && $isNewbie && isset( $limits['newbie'] ) ) {
1994 $userLimit = $limits['newbie'];
1995 }
1996
1997 // Set the user limit key
1998 if ( $userLimit !== false ) {
1999 // phan is confused because &can-bypass's value is a bool, so it assumes
2000 // that $userLimit is also a bool here.
2001 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
2002 list( $max, $period ) = $userLimit;
2003 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
2004 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
2005 }
2006
2007 // ip-based limits for all ping-limitable users
2008 if ( isset( $limits['ip-all'] ) ) {
2009 $ip = $this->getRequest()->getIP();
2010 // ignore if user limit is more permissive
2011 if ( $isNewbie || $userLimit === false
2012 || $limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2013 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
2014 }
2015 }
2016
2017 // subnet-based limits for all ping-limitable users
2018 if ( isset( $limits['subnet-all'] ) ) {
2019 $ip = $this->getRequest()->getIP();
2020 $subnet = IP::getSubnet( $ip );
2021 if ( $subnet !== false ) {
2022 // ignore if user limit is more permissive
2023 if ( $isNewbie || $userLimit === false
2024 || $limits['ip-all'][0] / $limits['ip-all'][1]
2025 > $userLimit[0] / $userLimit[1] ) {
2026 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2027 }
2028 }
2029 }
2030
2031 $triggered = false;
2032 foreach ( $keys as $key => $limit ) {
2033 // phan is confused because &can-bypass's value is a bool, so it assumes
2034 // that $userLimit is also a bool here.
2035 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
2036 list( $max, $period ) = $limit;
2037 $summary = "(limit $max in {$period}s)";
2038 $count = $cache->get( $key );
2039 // Already pinged?
2040 if ( $count && $count >= $max ) {
2041 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2042 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2043 $triggered = true;
2044 } else {
2045 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
2046 if ( $incrBy > 0 ) {
2047 $cache->add( $key, 0, intval( $period ) ); // first ping
2048 }
2049 }
2050 if ( $incrBy > 0 ) {
2051 $cache->incrWithInit( $key, (int)$period, $incrBy, $incrBy );
2052 }
2053 }
2054
2055 return $triggered;
2056 }
2057
2058 /**
2059 * Check if user is blocked
2060 *
2061 * @deprecated since 1.34, use User::getBlock() or
2062 * PermissionManager::isBlockedFrom() or
2063 * PermissionManager::userCan() instead.
2064 *
2065 * @param bool $fromReplica Whether to check the replica DB instead of
2066 * the master. Hacked from false due to horrible probs on site.
2067 * @return bool True if blocked, false otherwise
2068 */
2069 public function isBlocked( $fromReplica = true ) {
2070 return $this->getBlock( $fromReplica ) instanceof AbstractBlock &&
2071 $this->getBlock()->appliesToRight( 'edit' );
2072 }
2073
2074 /**
2075 * Get the block affecting the user, or null if the user is not blocked
2076 *
2077 * @param bool $fromReplica Whether to check the replica DB instead of the master
2078 * @return AbstractBlock|null
2079 */
2080 public function getBlock( $fromReplica = true ) {
2081 $this->getBlockedStatus( $fromReplica );
2082 return $this->mBlock instanceof AbstractBlock ? $this->mBlock : null;
2083 }
2084
2085 /**
2086 * Check if user is blocked from editing a particular article
2087 *
2088 * @param Title $title Title to check
2089 * @param bool $fromReplica Whether to check the replica DB instead of the master
2090 * @return bool
2091 *
2092 * @deprecated since 1.33,
2093 * use MediaWikiServices::getInstance()->getPermissionManager()->isBlockedFrom(..)
2094 *
2095 */
2096 public function isBlockedFrom( $title, $fromReplica = false ) {
2097 return MediaWikiServices::getInstance()->getPermissionManager()
2098 ->isBlockedFrom( $this, $title, $fromReplica );
2099 }
2100
2101 /**
2102 * If user is blocked, return the name of the user who placed the block
2103 * @return string Name of blocker
2104 */
2105 public function blockedBy() {
2106 $this->getBlockedStatus();
2107 return $this->mBlockedby;
2108 }
2109
2110 /**
2111 * If user is blocked, return the specified reason for the block
2112 * @return string Blocking reason
2113 */
2114 public function blockedFor() {
2115 $this->getBlockedStatus();
2116 return $this->mBlockreason;
2117 }
2118
2119 /**
2120 * If user is blocked, return the ID for the block
2121 * @return int Block ID
2122 */
2123 public function getBlockId() {
2124 $this->getBlockedStatus();
2125 return ( $this->mBlock ? $this->mBlock->getId() : false );
2126 }
2127
2128 /**
2129 * Check if user is blocked on all wikis.
2130 * Do not use for actual edit permission checks!
2131 * This is intended for quick UI checks.
2132 *
2133 * @param string $ip IP address, uses current client if none given
2134 * @return bool True if blocked, false otherwise
2135 */
2136 public function isBlockedGlobally( $ip = '' ) {
2137 return $this->getGlobalBlock( $ip ) instanceof AbstractBlock;
2138 }
2139
2140 /**
2141 * Check if user is blocked on all wikis.
2142 * Do not use for actual edit permission checks!
2143 * This is intended for quick UI checks.
2144 *
2145 * @param string $ip IP address, uses current client if none given
2146 * @return AbstractBlock|null Block object if blocked, null otherwise
2147 * @throws FatalError
2148 * @throws MWException
2149 */
2150 public function getGlobalBlock( $ip = '' ) {
2151 if ( $this->mGlobalBlock !== null ) {
2152 return $this->mGlobalBlock ?: null;
2153 }
2154 // User is already an IP?
2155 if ( IP::isIPAddress( $this->getName() ) ) {
2156 $ip = $this->getName();
2157 } elseif ( !$ip ) {
2158 $ip = $this->getRequest()->getIP();
2159 }
2160 // Avoid PHP 7.1 warning of passing $this by reference
2161 $user = $this;
2162 $blocked = false;
2163 $block = null;
2164 Hooks::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2165
2166 if ( $blocked && $block === null ) {
2167 // back-compat: UserIsBlockedGlobally didn't have $block param first
2168 $block = new SystemBlock( [
2169 'address' => $ip,
2170 'systemBlock' => 'global-block'
2171 ] );
2172 }
2173
2174 $this->mGlobalBlock = $blocked ? $block : false;
2175 return $this->mGlobalBlock ?: null;
2176 }
2177
2178 /**
2179 * Check if user account is locked
2180 *
2181 * @return bool True if locked, false otherwise
2182 */
2183 public function isLocked() {
2184 if ( $this->mLocked !== null ) {
2185 return $this->mLocked;
2186 }
2187 // Reset for hook
2188 $this->mLocked = false;
2189 Hooks::run( 'UserIsLocked', [ $this, &$this->mLocked ] );
2190 return $this->mLocked;
2191 }
2192
2193 /**
2194 * Check if user account is hidden
2195 *
2196 * @return bool True if hidden, false otherwise
2197 */
2198 public function isHidden() {
2199 if ( $this->mHideName !== null ) {
2200 return (bool)$this->mHideName;
2201 }
2202 $this->getBlockedStatus();
2203 if ( !$this->mHideName ) {
2204 // Reset for hook
2205 $this->mHideName = false;
2206 Hooks::run( 'UserIsHidden', [ $this, &$this->mHideName ] );
2207 }
2208 return (bool)$this->mHideName;
2209 }
2210
2211 /**
2212 * Get the user's ID.
2213 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2214 */
2215 public function getId() {
2216 if ( $this->mId === null && $this->mName !== null && self::isIP( $this->mName ) ) {
2217 // Special case, we know the user is anonymous
2218 return 0;
2219 }
2220
2221 if ( !$this->isItemLoaded( 'id' ) ) {
2222 // Don't load if this was initialized from an ID
2223 $this->load();
2224 }
2225
2226 return (int)$this->mId;
2227 }
2228
2229 /**
2230 * Set the user and reload all fields according to a given ID
2231 * @param int $v User ID to reload
2232 */
2233 public function setId( $v ) {
2234 $this->mId = $v;
2235 $this->clearInstanceCache( 'id' );
2236 }
2237
2238 /**
2239 * Get the user name, or the IP of an anonymous user
2240 * @return string User's name or IP address
2241 */
2242 public function getName() {
2243 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2244 // Special case optimisation
2245 return $this->mName;
2246 }
2247
2248 $this->load();
2249 if ( $this->mName === false ) {
2250 // Clean up IPs
2251 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
2252 }
2253
2254 return $this->mName;
2255 }
2256
2257 /**
2258 * Set the user name.
2259 *
2260 * This does not reload fields from the database according to the given
2261 * name. Rather, it is used to create a temporary "nonexistent user" for
2262 * later addition to the database. It can also be used to set the IP
2263 * address for an anonymous user to something other than the current
2264 * remote IP.
2265 *
2266 * @note User::newFromName() has roughly the same function, when the named user
2267 * does not exist.
2268 * @param string $str New user name to set
2269 */
2270 public function setName( $str ) {
2271 $this->load();
2272 $this->mName = $str;
2273 }
2274
2275 /**
2276 * Get the user's actor ID.
2277 * @since 1.31
2278 * @param IDatabase|null $dbw Assign a new actor ID, using this DB handle, if none exists
2279 * @return int The actor's ID, or 0 if no actor ID exists and $dbw was null
2280 */
2281 public function getActorId( IDatabase $dbw = null ) {
2282 global $wgActorTableSchemaMigrationStage;
2283
2284 // Technically we should always return 0 without SCHEMA_COMPAT_READ_NEW,
2285 // but it does little harm and might be needed for write callers loading a User.
2286 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) ) {
2287 return 0;
2288 }
2289
2290 if ( !$this->isItemLoaded( 'actor' ) ) {
2291 $this->load();
2292 }
2293
2294 // Currently $this->mActorId might be null if $this was loaded from a
2295 // cache entry that was written when $wgActorTableSchemaMigrationStage
2296 // was SCHEMA_COMPAT_OLD. Once that is no longer a possibility (i.e. when
2297 // User::VERSION is incremented after $wgActorTableSchemaMigrationStage
2298 // has been removed), that condition may be removed.
2299 if ( $this->mActorId === null || !$this->mActorId && $dbw ) {
2300 $q = [
2301 'actor_user' => $this->getId() ?: null,
2302 'actor_name' => (string)$this->getName(),
2303 ];
2304 if ( $dbw ) {
2305 if ( $q['actor_user'] === null && self::isUsableName( $q['actor_name'] ) ) {
2306 throw new CannotCreateActorException(
2307 'Cannot create an actor for a usable name that is not an existing user'
2308 );
2309 }
2310 if ( $q['actor_name'] === '' ) {
2311 throw new CannotCreateActorException( 'Cannot create an actor for a user with no name' );
2312 }
2313 $dbw->insert( 'actor', $q, __METHOD__, [ 'IGNORE' ] );
2314 if ( $dbw->affectedRows() ) {
2315 $this->mActorId = (int)$dbw->insertId();
2316 } else {
2317 // Outdated cache?
2318 // Use LOCK IN SHARE MODE to bypass any MySQL REPEATABLE-READ snapshot.
2319 $this->mActorId = (int)$dbw->selectField(
2320 'actor',
2321 'actor_id',
2322 $q,
2323 __METHOD__,
2324 [ 'LOCK IN SHARE MODE' ]
2325 );
2326 if ( !$this->mActorId ) {
2327 throw new CannotCreateActorException(
2328 "Cannot create actor ID for user_id={$this->getId()} user_name={$this->getName()}"
2329 );
2330 }
2331 }
2332 $this->invalidateCache();
2333 } else {
2334 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $this->queryFlagsUsed );
2335 $db = wfGetDB( $index );
2336 $this->mActorId = (int)$db->selectField( 'actor', 'actor_id', $q, __METHOD__, $options );
2337 }
2338 $this->setItemLoaded( 'actor' );
2339 }
2340
2341 return (int)$this->mActorId;
2342 }
2343
2344 /**
2345 * Get the user's name escaped by underscores.
2346 * @return string Username escaped by underscores.
2347 */
2348 public function getTitleKey() {
2349 return str_replace( ' ', '_', $this->getName() );
2350 }
2351
2352 /**
2353 * Check if the user has new messages.
2354 * @return bool True if the user has new messages
2355 */
2356 public function getNewtalk() {
2357 $this->load();
2358
2359 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2360 if ( $this->mNewtalk === -1 ) {
2361 $this->mNewtalk = false; # reset talk page status
2362
2363 // Check memcached separately for anons, who have no
2364 // entire User object stored in there.
2365 if ( !$this->mId ) {
2366 global $wgDisableAnonTalk;
2367 if ( $wgDisableAnonTalk ) {
2368 // Anon newtalk disabled by configuration.
2369 $this->mNewtalk = false;
2370 } else {
2371 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName() );
2372 }
2373 } else {
2374 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
2375 }
2376 }
2377
2378 return (bool)$this->mNewtalk;
2379 }
2380
2381 /**
2382 * Return the data needed to construct links for new talk page message
2383 * alerts. If there are new messages, this will return an associative array
2384 * with the following data:
2385 * wiki: The database name of the wiki
2386 * link: Root-relative link to the user's talk page
2387 * rev: The last talk page revision that the user has seen or null. This
2388 * is useful for building diff links.
2389 * If there are no new messages, it returns an empty array.
2390 * @note This function was designed to accomodate multiple talk pages, but
2391 * currently only returns a single link and revision.
2392 * @return array
2393 */
2394 public function getNewMessageLinks() {
2395 // Avoid PHP 7.1 warning of passing $this by reference
2396 $user = $this;
2397 $talks = [];
2398 if ( !Hooks::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2399 return $talks;
2400 }
2401
2402 if ( !$this->getNewtalk() ) {
2403 return [];
2404 }
2405 $utp = $this->getTalkPage();
2406 $dbr = wfGetDB( DB_REPLICA );
2407 // Get the "last viewed rev" timestamp from the oldest message notification
2408 $timestamp = $dbr->selectField( 'user_newtalk',
2409 'MIN(user_last_timestamp)',
2410 $this->isAnon() ? [ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2411 __METHOD__ );
2412 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2413 return [
2414 [
2415 'wiki' => WikiMap::getWikiIdFromDbDomain( WikiMap::getCurrentWikiDbDomain() ),
2416 'link' => $utp->getLocalURL(),
2417 'rev' => $rev
2418 ]
2419 ];
2420 }
2421
2422 /**
2423 * Get the revision ID for the last talk page revision viewed by the talk
2424 * page owner.
2425 * @return int|null Revision ID or null
2426 */
2427 public function getNewMessageRevisionId() {
2428 $newMessageRevisionId = null;
2429 $newMessageLinks = $this->getNewMessageLinks();
2430
2431 // Note: getNewMessageLinks() never returns more than a single link
2432 // and it is always for the same wiki, but we double-check here in
2433 // case that changes some time in the future.
2434 if ( $newMessageLinks && count( $newMessageLinks ) === 1
2435 && WikiMap::isCurrentWikiId( $newMessageLinks[0]['wiki'] )
2436 && $newMessageLinks[0]['rev']
2437 ) {
2438 /** @var Revision $newMessageRevision */
2439 $newMessageRevision = $newMessageLinks[0]['rev'];
2440 $newMessageRevisionId = $newMessageRevision->getId();
2441 }
2442
2443 return $newMessageRevisionId;
2444 }
2445
2446 /**
2447 * Internal uncached check for new messages
2448 *
2449 * @see getNewtalk()
2450 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2451 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2452 * @return bool True if the user has new messages
2453 */
2454 protected function checkNewtalk( $field, $id ) {
2455 $dbr = wfGetDB( DB_REPLICA );
2456
2457 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__ );
2458
2459 return $ok !== false;
2460 }
2461
2462 /**
2463 * Add or update the new messages flag
2464 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2465 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2466 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2467 * @return bool True if successful, false otherwise
2468 */
2469 protected function updateNewtalk( $field, $id, $curRev = null ) {
2470 // Get timestamp of the talk page revision prior to the current one
2471 $prevRev = $curRev ? $curRev->getPrevious() : false;
2472 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2473 // Mark the user as having new messages since this revision
2474 $dbw = wfGetDB( DB_MASTER );
2475 $dbw->insert( 'user_newtalk',
2476 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2477 __METHOD__,
2478 [ 'IGNORE' ] );
2479 if ( $dbw->affectedRows() ) {
2480 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2481 return true;
2482 }
2483
2484 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2485 return false;
2486 }
2487
2488 /**
2489 * Clear the new messages flag for the given user
2490 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2491 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2492 * @return bool True if successful, false otherwise
2493 */
2494 protected function deleteNewtalk( $field, $id ) {
2495 $dbw = wfGetDB( DB_MASTER );
2496 $dbw->delete( 'user_newtalk',
2497 [ $field => $id ],
2498 __METHOD__ );
2499 if ( $dbw->affectedRows() ) {
2500 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2501 return true;
2502 }
2503
2504 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2505 return false;
2506 }
2507
2508 /**
2509 * Update the 'You have new messages!' status.
2510 * @param bool $val Whether the user has new messages
2511 * @param Revision|null $curRev New, as yet unseen revision of the user talk
2512 * page. Ignored if null or !$val.
2513 */
2514 public function setNewtalk( $val, $curRev = null ) {
2515 if ( wfReadOnly() ) {
2516 return;
2517 }
2518
2519 $this->load();
2520 $this->mNewtalk = $val;
2521
2522 if ( $this->isAnon() ) {
2523 $field = 'user_ip';
2524 $id = $this->getName();
2525 } else {
2526 $field = 'user_id';
2527 $id = $this->getId();
2528 }
2529
2530 if ( $val ) {
2531 $changed = $this->updateNewtalk( $field, $id, $curRev );
2532 } else {
2533 $changed = $this->deleteNewtalk( $field, $id );
2534 }
2535
2536 if ( $changed ) {
2537 $this->invalidateCache();
2538 }
2539 }
2540
2541 /**
2542 * Generate a current or new-future timestamp to be stored in the
2543 * user_touched field when we update things.
2544 *
2545 * @return string Timestamp in TS_MW format
2546 */
2547 private function newTouchedTimestamp() {
2548 $time = time();
2549 if ( $this->mTouched ) {
2550 $time = max( $time, wfTimestamp( TS_UNIX, $this->mTouched ) + 1 );
2551 }
2552
2553 return wfTimestamp( TS_MW, $time );
2554 }
2555
2556 /**
2557 * Clear user data from memcached
2558 *
2559 * Use after applying updates to the database; caller's
2560 * responsibility to update user_touched if appropriate.
2561 *
2562 * Called implicitly from invalidateCache() and saveSettings().
2563 *
2564 * @param string $mode Use 'refresh' to clear now or 'changed' to clear before DB commit
2565 */
2566 public function clearSharedCache( $mode = 'refresh' ) {
2567 if ( !$this->getId() ) {
2568 return;
2569 }
2570
2571 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
2572 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2573 $key = $this->getCacheKey( $cache );
2574
2575 if ( $mode === 'refresh' ) {
2576 $cache->delete( $key, 1 ); // low tombstone/"hold-off" TTL
2577 } else {
2578 $lb->getConnectionRef( DB_MASTER )->onTransactionPreCommitOrIdle(
2579 function () use ( $cache, $key ) {
2580 $cache->delete( $key );
2581 },
2582 __METHOD__
2583 );
2584 }
2585 }
2586
2587 /**
2588 * Immediately touch the user data cache for this account
2589 *
2590 * Calls touch() and removes account data from memcached
2591 */
2592 public function invalidateCache() {
2593 $this->touch();
2594 $this->clearSharedCache( 'changed' );
2595 }
2596
2597 /**
2598 * Update the "touched" timestamp for the user
2599 *
2600 * This is useful on various login/logout events when making sure that
2601 * a browser or proxy that has multiple tenants does not suffer cache
2602 * pollution where the new user sees the old users content. The value
2603 * of getTouched() is checked when determining 304 vs 200 responses.
2604 * Unlike invalidateCache(), this preserves the User object cache and
2605 * avoids database writes.
2606 *
2607 * @since 1.25
2608 */
2609 public function touch() {
2610 $id = $this->getId();
2611 if ( $id ) {
2612 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2613 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2614 $cache->touchCheckKey( $key );
2615 $this->mQuickTouched = null;
2616 }
2617 }
2618
2619 /**
2620 * Validate the cache for this account.
2621 * @param string $timestamp A timestamp in TS_MW format
2622 * @return bool
2623 */
2624 public function validateCache( $timestamp ) {
2625 return ( $timestamp >= $this->getTouched() );
2626 }
2627
2628 /**
2629 * Get the user touched timestamp
2630 *
2631 * Use this value only to validate caches via inequalities
2632 * such as in the case of HTTP If-Modified-Since response logic
2633 *
2634 * @return string TS_MW Timestamp
2635 */
2636 public function getTouched() {
2637 $this->load();
2638
2639 if ( $this->mId ) {
2640 if ( $this->mQuickTouched === null ) {
2641 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2642 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId );
2643
2644 $this->mQuickTouched = wfTimestamp( TS_MW, $cache->getCheckKeyTime( $key ) );
2645 }
2646
2647 return max( $this->mTouched, $this->mQuickTouched );
2648 }
2649
2650 return $this->mTouched;
2651 }
2652
2653 /**
2654 * Get the user_touched timestamp field (time of last DB updates)
2655 * @return string TS_MW Timestamp
2656 * @since 1.26
2657 */
2658 public function getDBTouched() {
2659 $this->load();
2660
2661 return $this->mTouched;
2662 }
2663
2664 /**
2665 * Set the password and reset the random token.
2666 * Calls through to authentication plugin if necessary;
2667 * will have no effect if the auth plugin refuses to
2668 * pass the change through or if the legal password
2669 * checks fail.
2670 *
2671 * As a special case, setting the password to null
2672 * wipes it, so the account cannot be logged in until
2673 * a new password is set, for instance via e-mail.
2674 *
2675 * @deprecated since 1.27, use AuthManager instead
2676 * @param string $str New password to set
2677 * @throws PasswordError On failure
2678 * @return bool
2679 */
2680 public function setPassword( $str ) {
2681 wfDeprecated( __METHOD__, '1.27' );
2682 return $this->setPasswordInternal( $str );
2683 }
2684
2685 /**
2686 * Set the password and reset the random token unconditionally.
2687 *
2688 * @deprecated since 1.27, use AuthManager instead
2689 * @param string|null $str New password to set or null to set an invalid
2690 * password hash meaning that the user will not be able to log in
2691 * through the web interface.
2692 */
2693 public function setInternalPassword( $str ) {
2694 wfDeprecated( __METHOD__, '1.27' );
2695 $this->setPasswordInternal( $str );
2696 }
2697
2698 /**
2699 * Actually set the password and such
2700 * @since 1.27 cannot set a password for a user not in the database
2701 * @param string|null $str New password to set or null to set an invalid
2702 * password hash meaning that the user will not be able to log in
2703 * through the web interface.
2704 * @return bool Success
2705 */
2706 private function setPasswordInternal( $str ) {
2707 $manager = AuthManager::singleton();
2708
2709 // If the user doesn't exist yet, fail
2710 if ( !$manager->userExists( $this->getName() ) ) {
2711 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2712 }
2713
2714 $status = $this->changeAuthenticationData( [
2715 'username' => $this->getName(),
2716 'password' => $str,
2717 'retype' => $str,
2718 ] );
2719 if ( !$status->isGood() ) {
2720 \MediaWiki\Logger\LoggerFactory::getInstance( 'authentication' )
2721 ->info( __METHOD__ . ': Password change rejected: '
2722 . $status->getWikiText( null, null, 'en' ) );
2723 return false;
2724 }
2725
2726 $this->setOption( 'watchlisttoken', false );
2727 SessionManager::singleton()->invalidateSessionsForUser( $this );
2728
2729 return true;
2730 }
2731
2732 /**
2733 * Changes credentials of the user.
2734 *
2735 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2736 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2737 * e.g. when no provider handled the change.
2738 *
2739 * @param array $data A set of authentication data in fieldname => value format. This is the
2740 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2741 * @return Status
2742 * @since 1.27
2743 */
2744 public function changeAuthenticationData( array $data ) {
2745 $manager = AuthManager::singleton();
2746 $reqs = $manager->getAuthenticationRequests( AuthManager::ACTION_CHANGE, $this );
2747 $reqs = AuthenticationRequest::loadRequestsFromSubmission( $reqs, $data );
2748
2749 $status = Status::newGood( 'ignored' );
2750 foreach ( $reqs as $req ) {
2751 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2752 }
2753 if ( $status->getValue() === 'ignored' ) {
2754 $status->warning( 'authenticationdatachange-ignored' );
2755 }
2756
2757 if ( $status->isGood() ) {
2758 foreach ( $reqs as $req ) {
2759 $manager->changeAuthenticationData( $req );
2760 }
2761 }
2762 return $status;
2763 }
2764
2765 /**
2766 * Get the user's current token.
2767 * @param bool $forceCreation Force the generation of a new token if the
2768 * user doesn't have one (default=true for backwards compatibility).
2769 * @return string|null Token
2770 */
2771 public function getToken( $forceCreation = true ) {
2772 global $wgAuthenticationTokenVersion;
2773
2774 $this->load();
2775 if ( !$this->mToken && $forceCreation ) {
2776 $this->setToken();
2777 }
2778
2779 if ( !$this->mToken ) {
2780 // The user doesn't have a token, return null to indicate that.
2781 return null;
2782 }
2783
2784 if ( $this->mToken === self::INVALID_TOKEN ) {
2785 // We return a random value here so existing token checks are very
2786 // likely to fail.
2787 return MWCryptRand::generateHex( self::TOKEN_LENGTH );
2788 }
2789
2790 if ( $wgAuthenticationTokenVersion === null ) {
2791 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2792 return $this->mToken;
2793 }
2794
2795 // $wgAuthenticationTokenVersion in use, so hmac it.
2796 $ret = MWCryptHash::hmac( $wgAuthenticationTokenVersion, $this->mToken, false );
2797
2798 // The raw hash can be overly long. Shorten it up.
2799 $len = max( 32, self::TOKEN_LENGTH );
2800 if ( strlen( $ret ) < $len ) {
2801 // Should never happen, even md5 is 128 bits
2802 throw new \UnexpectedValueException( 'Hmac returned less than 128 bits' );
2803 }
2804
2805 return substr( $ret, -$len );
2806 }
2807
2808 /**
2809 * Set the random token (used for persistent authentication)
2810 * Called from loadDefaults() among other places.
2811 *
2812 * @param string|bool $token If specified, set the token to this value
2813 */
2814 public function setToken( $token = false ) {
2815 $this->load();
2816 if ( $this->mToken === self::INVALID_TOKEN ) {
2817 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
2818 ->debug( __METHOD__ . ": Ignoring attempt to set token for system user \"$this\"" );
2819 } elseif ( !$token ) {
2820 $this->mToken = MWCryptRand::generateHex( self::TOKEN_LENGTH );
2821 } else {
2822 $this->mToken = $token;
2823 }
2824 }
2825
2826 /**
2827 * Set the password for a password reminder or new account email
2828 *
2829 * @deprecated Removed in 1.27. Use PasswordReset instead.
2830 * @param string $str New password to set or null to set an invalid
2831 * password hash meaning that the user will not be able to use it
2832 * @param bool $throttle If true, reset the throttle timestamp to the present
2833 */
2834 public function setNewpassword( $str, $throttle = true ) {
2835 throw new BadMethodCallException( __METHOD__ . ' has been removed in 1.27' );
2836 }
2837
2838 /**
2839 * Get the user's e-mail address
2840 * @return string User's email address
2841 */
2842 public function getEmail() {
2843 $this->load();
2844 Hooks::run( 'UserGetEmail', [ $this, &$this->mEmail ] );
2845 return $this->mEmail;
2846 }
2847
2848 /**
2849 * Get the timestamp of the user's e-mail authentication
2850 * @return string TS_MW timestamp
2851 */
2852 public function getEmailAuthenticationTimestamp() {
2853 $this->load();
2854 Hooks::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated ] );
2855 return $this->mEmailAuthenticated;
2856 }
2857
2858 /**
2859 * Set the user's e-mail address
2860 * @param string $str New e-mail address
2861 */
2862 public function setEmail( $str ) {
2863 $this->load();
2864 if ( $str == $this->mEmail ) {
2865 return;
2866 }
2867 $this->invalidateEmail();
2868 $this->mEmail = $str;
2869 Hooks::run( 'UserSetEmail', [ $this, &$this->mEmail ] );
2870 }
2871
2872 /**
2873 * Set the user's e-mail address and a confirmation mail if needed.
2874 *
2875 * @since 1.20
2876 * @param string $str New e-mail address
2877 * @return Status
2878 */
2879 public function setEmailWithConfirmation( $str ) {
2880 global $wgEnableEmail, $wgEmailAuthentication;
2881
2882 if ( !$wgEnableEmail ) {
2883 return Status::newFatal( 'emaildisabled' );
2884 }
2885
2886 $oldaddr = $this->getEmail();
2887 if ( $str === $oldaddr ) {
2888 return Status::newGood( true );
2889 }
2890
2891 $type = $oldaddr != '' ? 'changed' : 'set';
2892 $notificationResult = null;
2893
2894 if ( $wgEmailAuthentication && $type === 'changed' ) {
2895 // Send the user an email notifying the user of the change in registered
2896 // email address on their previous email address
2897 $change = $str != '' ? 'changed' : 'removed';
2898 $notificationResult = $this->sendMail(
2899 wfMessage( 'notificationemail_subject_' . $change )->text(),
2900 wfMessage( 'notificationemail_body_' . $change,
2901 $this->getRequest()->getIP(),
2902 $this->getName(),
2903 $str )->text()
2904 );
2905 }
2906
2907 $this->setEmail( $str );
2908
2909 if ( $str !== '' && $wgEmailAuthentication ) {
2910 // Send a confirmation request to the new address if needed
2911 $result = $this->sendConfirmationMail( $type );
2912
2913 if ( $notificationResult !== null ) {
2914 $result->merge( $notificationResult );
2915 }
2916
2917 if ( $result->isGood() ) {
2918 // Say to the caller that a confirmation and notification mail has been sent
2919 $result->value = 'eauth';
2920 }
2921 } else {
2922 $result = Status::newGood( true );
2923 }
2924
2925 return $result;
2926 }
2927
2928 /**
2929 * Get the user's real name
2930 * @return string User's real name
2931 */
2932 public function getRealName() {
2933 if ( !$this->isItemLoaded( 'realname' ) ) {
2934 $this->load();
2935 }
2936
2937 return $this->mRealName;
2938 }
2939
2940 /**
2941 * Set the user's real name
2942 * @param string $str New real name
2943 */
2944 public function setRealName( $str ) {
2945 $this->load();
2946 $this->mRealName = $str;
2947 }
2948
2949 /**
2950 * Get the user's current setting for a given option.
2951 *
2952 * @param string $oname The option to check
2953 * @param string|array|null $defaultOverride A default value returned if the option does not exist
2954 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2955 * @return string|array|int|null User's current value for the option
2956 * @see getBoolOption()
2957 * @see getIntOption()
2958 */
2959 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2960 global $wgHiddenPrefs;
2961 $this->loadOptions();
2962
2963 # We want 'disabled' preferences to always behave as the default value for
2964 # users, even if they have set the option explicitly in their settings (ie they
2965 # set it, and then it was disabled removing their ability to change it). But
2966 # we don't want to erase the preferences in the database in case the preference
2967 # is re-enabled again. So don't touch $mOptions, just override the returned value
2968 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2969 return self::getDefaultOption( $oname );
2970 }
2971
2972 if ( array_key_exists( $oname, $this->mOptions ) ) {
2973 return $this->mOptions[$oname];
2974 }
2975
2976 return $defaultOverride;
2977 }
2978
2979 /**
2980 * Get all user's options
2981 *
2982 * @param int $flags Bitwise combination of:
2983 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2984 * to the default value. (Since 1.25)
2985 * @return array
2986 */
2987 public function getOptions( $flags = 0 ) {
2988 global $wgHiddenPrefs;
2989 $this->loadOptions();
2990 $options = $this->mOptions;
2991
2992 # We want 'disabled' preferences to always behave as the default value for
2993 # users, even if they have set the option explicitly in their settings (ie they
2994 # set it, and then it was disabled removing their ability to change it). But
2995 # we don't want to erase the preferences in the database in case the preference
2996 # is re-enabled again. So don't touch $mOptions, just override the returned value
2997 foreach ( $wgHiddenPrefs as $pref ) {
2998 $default = self::getDefaultOption( $pref );
2999 if ( $default !== null ) {
3000 $options[$pref] = $default;
3001 }
3002 }
3003
3004 if ( $flags & self::GETOPTIONS_EXCLUDE_DEFAULTS ) {
3005 $options = array_diff_assoc( $options, self::getDefaultOptions() );
3006 }
3007
3008 return $options;
3009 }
3010
3011 /**
3012 * Get the user's current setting for a given option, as a boolean value.
3013 *
3014 * @param string $oname The option to check
3015 * @return bool User's current value for the option
3016 * @see getOption()
3017 */
3018 public function getBoolOption( $oname ) {
3019 return (bool)$this->getOption( $oname );
3020 }
3021
3022 /**
3023 * Get the user's current setting for a given option, as an integer value.
3024 *
3025 * @param string $oname The option to check
3026 * @param int $defaultOverride A default value returned if the option does not exist
3027 * @return int User's current value for the option
3028 * @see getOption()
3029 */
3030 public function getIntOption( $oname, $defaultOverride = 0 ) {
3031 $val = $this->getOption( $oname );
3032 if ( $val == '' ) {
3033 $val = $defaultOverride;
3034 }
3035 return intval( $val );
3036 }
3037
3038 /**
3039 * Set the given option for a user.
3040 *
3041 * You need to call saveSettings() to actually write to the database.
3042 *
3043 * @param string $oname The option to set
3044 * @param mixed $val New value to set
3045 */
3046 public function setOption( $oname, $val ) {
3047 $this->loadOptions();
3048
3049 // Explicitly NULL values should refer to defaults
3050 if ( is_null( $val ) ) {
3051 $val = self::getDefaultOption( $oname );
3052 }
3053
3054 $this->mOptions[$oname] = $val;
3055 }
3056
3057 /**
3058 * Get a token stored in the preferences (like the watchlist one),
3059 * resetting it if it's empty (and saving changes).
3060 *
3061 * @param string $oname The option name to retrieve the token from
3062 * @return string|bool User's current value for the option, or false if this option is disabled.
3063 * @see resetTokenFromOption()
3064 * @see getOption()
3065 * @deprecated since 1.26 Applications should use the OAuth extension
3066 */
3067 public function getTokenFromOption( $oname ) {
3068 global $wgHiddenPrefs;
3069
3070 $id = $this->getId();
3071 if ( !$id || in_array( $oname, $wgHiddenPrefs ) ) {
3072 return false;
3073 }
3074
3075 $token = $this->getOption( $oname );
3076 if ( !$token ) {
3077 // Default to a value based on the user token to avoid space
3078 // wasted on storing tokens for all users. When this option
3079 // is set manually by the user, only then is it stored.
3080 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3081 }
3082
3083 return $token;
3084 }
3085
3086 /**
3087 * Reset a token stored in the preferences (like the watchlist one).
3088 * *Does not* save user's preferences (similarly to setOption()).
3089 *
3090 * @param string $oname The option name to reset the token in
3091 * @return string|bool New token value, or false if this option is disabled.
3092 * @see getTokenFromOption()
3093 * @see setOption()
3094 */
3095 public function resetTokenFromOption( $oname ) {
3096 global $wgHiddenPrefs;
3097 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3098 return false;
3099 }
3100
3101 $token = MWCryptRand::generateHex( 40 );
3102 $this->setOption( $oname, $token );
3103 return $token;
3104 }
3105
3106 /**
3107 * Return a list of the types of user options currently returned by
3108 * User::getOptionKinds().
3109 *
3110 * Currently, the option kinds are:
3111 * - 'registered' - preferences which are registered in core MediaWiki or
3112 * by extensions using the UserGetDefaultOptions hook.
3113 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3114 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3115 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3116 * be used by user scripts.
3117 * - 'special' - "preferences" that are not accessible via User::getOptions
3118 * or User::setOptions.
3119 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3120 * These are usually legacy options, removed in newer versions.
3121 *
3122 * The API (and possibly others) use this function to determine the possible
3123 * option types for validation purposes, so make sure to update this when a
3124 * new option kind is added.
3125 *
3126 * @see User::getOptionKinds
3127 * @return array Option kinds
3128 */
3129 public static function listOptionKinds() {
3130 return [
3131 'registered',
3132 'registered-multiselect',
3133 'registered-checkmatrix',
3134 'userjs',
3135 'special',
3136 'unused'
3137 ];
3138 }
3139
3140 /**
3141 * Return an associative array mapping preferences keys to the kind of a preference they're
3142 * used for. Different kinds are handled differently when setting or reading preferences.
3143 *
3144 * See User::listOptionKinds for the list of valid option types that can be provided.
3145 *
3146 * @see User::listOptionKinds
3147 * @param IContextSource $context
3148 * @param array|null $options Assoc. array with options keys to check as keys.
3149 * Defaults to $this->mOptions.
3150 * @return array The key => kind mapping data
3151 */
3152 public function getOptionKinds( IContextSource $context, $options = null ) {
3153 $this->loadOptions();
3154 if ( $options === null ) {
3155 $options = $this->mOptions;
3156 }
3157
3158 $preferencesFactory = MediaWikiServices::getInstance()->getPreferencesFactory();
3159 $prefs = $preferencesFactory->getFormDescriptor( $this, $context );
3160 $mapping = [];
3161
3162 // Pull out the "special" options, so they don't get converted as
3163 // multiselect or checkmatrix.
3164 $specialOptions = array_fill_keys( $preferencesFactory->getSaveBlacklist(), true );
3165 foreach ( $specialOptions as $name => $value ) {
3166 unset( $prefs[$name] );
3167 }
3168
3169 // Multiselect and checkmatrix options are stored in the database with
3170 // one key per option, each having a boolean value. Extract those keys.
3171 $multiselectOptions = [];
3172 foreach ( $prefs as $name => $info ) {
3173 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3174 ( isset( $info['class'] ) && $info['class'] == HTMLMultiSelectField::class ) ) {
3175 $opts = HTMLFormField::flattenOptions( $info['options'] );
3176 $prefix = $info['prefix'] ?? $name;
3177
3178 foreach ( $opts as $value ) {
3179 $multiselectOptions["$prefix$value"] = true;
3180 }
3181
3182 unset( $prefs[$name] );
3183 }
3184 }
3185 $checkmatrixOptions = [];
3186 foreach ( $prefs as $name => $info ) {
3187 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3188 ( isset( $info['class'] ) && $info['class'] == HTMLCheckMatrix::class ) ) {
3189 $columns = HTMLFormField::flattenOptions( $info['columns'] );
3190 $rows = HTMLFormField::flattenOptions( $info['rows'] );
3191 $prefix = $info['prefix'] ?? $name;
3192
3193 foreach ( $columns as $column ) {
3194 foreach ( $rows as $row ) {
3195 $checkmatrixOptions["$prefix$column-$row"] = true;
3196 }
3197 }
3198
3199 unset( $prefs[$name] );
3200 }
3201 }
3202
3203 // $value is ignored
3204 foreach ( $options as $key => $value ) {
3205 if ( isset( $prefs[$key] ) ) {
3206 $mapping[$key] = 'registered';
3207 } elseif ( isset( $multiselectOptions[$key] ) ) {
3208 $mapping[$key] = 'registered-multiselect';
3209 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3210 $mapping[$key] = 'registered-checkmatrix';
3211 } elseif ( isset( $specialOptions[$key] ) ) {
3212 $mapping[$key] = 'special';
3213 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3214 $mapping[$key] = 'userjs';
3215 } else {
3216 $mapping[$key] = 'unused';
3217 }
3218 }
3219
3220 return $mapping;
3221 }
3222
3223 /**
3224 * Reset certain (or all) options to the site defaults
3225 *
3226 * The optional parameter determines which kinds of preferences will be reset.
3227 * Supported values are everything that can be reported by getOptionKinds()
3228 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3229 *
3230 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3231 * [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ]
3232 * for backwards-compatibility.
3233 * @param IContextSource|null $context Context source used when $resetKinds
3234 * does not contain 'all', passed to getOptionKinds().
3235 * Defaults to RequestContext::getMain() when null.
3236 */
3237 public function resetOptions(
3238 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3239 IContextSource $context = null
3240 ) {
3241 $this->load();
3242 $defaultOptions = self::getDefaultOptions();
3243
3244 if ( !is_array( $resetKinds ) ) {
3245 $resetKinds = [ $resetKinds ];
3246 }
3247
3248 if ( in_array( 'all', $resetKinds ) ) {
3249 $newOptions = $defaultOptions;
3250 } else {
3251 if ( $context === null ) {
3252 $context = RequestContext::getMain();
3253 }
3254
3255 $optionKinds = $this->getOptionKinds( $context );
3256 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
3257 $newOptions = [];
3258
3259 // Use default values for the options that should be deleted, and
3260 // copy old values for the ones that shouldn't.
3261 foreach ( $this->mOptions as $key => $value ) {
3262 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3263 if ( array_key_exists( $key, $defaultOptions ) ) {
3264 $newOptions[$key] = $defaultOptions[$key];
3265 }
3266 } else {
3267 $newOptions[$key] = $value;
3268 }
3269 }
3270 }
3271
3272 Hooks::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions, $resetKinds ] );
3273
3274 $this->mOptions = $newOptions;
3275 $this->mOptionsLoaded = true;
3276 }
3277
3278 /**
3279 * Get the user's preferred date format.
3280 * @return string User's preferred date format
3281 */
3282 public function getDatePreference() {
3283 // Important migration for old data rows
3284 if ( is_null( $this->mDatePreference ) ) {
3285 global $wgLang;
3286 $value = $this->getOption( 'date' );
3287 $map = $wgLang->getDatePreferenceMigrationMap();
3288 if ( isset( $map[$value] ) ) {
3289 $value = $map[$value];
3290 }
3291 $this->mDatePreference = $value;
3292 }
3293 return $this->mDatePreference;
3294 }
3295
3296 /**
3297 * Determine based on the wiki configuration and the user's options,
3298 * whether this user must be over HTTPS no matter what.
3299 *
3300 * @return bool
3301 */
3302 public function requiresHTTPS() {
3303 global $wgSecureLogin;
3304 if ( !$wgSecureLogin ) {
3305 return false;
3306 }
3307
3308 $https = $this->getBoolOption( 'prefershttps' );
3309 Hooks::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3310 if ( $https ) {
3311 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3312 }
3313
3314 return $https;
3315 }
3316
3317 /**
3318 * Get the user preferred stub threshold
3319 *
3320 * @return int
3321 */
3322 public function getStubThreshold() {
3323 global $wgMaxArticleSize; # Maximum article size, in Kb
3324 $threshold = $this->getIntOption( 'stubthreshold' );
3325 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3326 // If they have set an impossible value, disable the preference
3327 // so we can use the parser cache again.
3328 $threshold = 0;
3329 }
3330 return $threshold;
3331 }
3332
3333 /**
3334 * Get the permissions this user has.
3335 * @return string[] permission names
3336 *
3337 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
3338 * ->getUserPermissions(..) instead
3339 *
3340 */
3341 public function getRights() {
3342 return MediaWikiServices::getInstance()->getPermissionManager()->getUserPermissions( $this );
3343 }
3344
3345 /**
3346 * Get the list of explicit group memberships this user has.
3347 * The implicit * and user groups are not included.
3348 *
3349 * @return string[] Array of internal group names (sorted since 1.33)
3350 */
3351 public function getGroups() {
3352 $this->load();
3353 $this->loadGroups();
3354 return array_keys( $this->mGroupMemberships );
3355 }
3356
3357 /**
3358 * Get the list of explicit group memberships this user has, stored as
3359 * UserGroupMembership objects. Implicit groups are not included.
3360 *
3361 * @return UserGroupMembership[] Associative array of (group name => UserGroupMembership object)
3362 * @since 1.29
3363 */
3364 public function getGroupMemberships() {
3365 $this->load();
3366 $this->loadGroups();
3367 return $this->mGroupMemberships;
3368 }
3369
3370 /**
3371 * Get the list of implicit group memberships this user has.
3372 * This includes all explicit groups, plus 'user' if logged in,
3373 * '*' for all accounts, and autopromoted groups
3374 * @param bool $recache Whether to avoid the cache
3375 * @return array Array of String internal group names
3376 */
3377 public function getEffectiveGroups( $recache = false ) {
3378 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
3379 $this->mEffectiveGroups = array_unique( array_merge(
3380 $this->getGroups(), // explicit groups
3381 $this->getAutomaticGroups( $recache ) // implicit groups
3382 ) );
3383 // Avoid PHP 7.1 warning of passing $this by reference
3384 $user = $this;
3385 // Hook for additional groups
3386 Hooks::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups ] );
3387 // Force reindexation of groups when a hook has unset one of them
3388 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
3389 }
3390 return $this->mEffectiveGroups;
3391 }
3392
3393 /**
3394 * Get the list of implicit group memberships this user has.
3395 * This includes 'user' if logged in, '*' for all accounts,
3396 * and autopromoted groups
3397 * @param bool $recache Whether to avoid the cache
3398 * @return array Array of String internal group names
3399 */
3400 public function getAutomaticGroups( $recache = false ) {
3401 if ( $recache || is_null( $this->mImplicitGroups ) ) {
3402 $this->mImplicitGroups = [ '*' ];
3403 if ( $this->getId() ) {
3404 $this->mImplicitGroups[] = 'user';
3405
3406 $this->mImplicitGroups = array_unique( array_merge(
3407 $this->mImplicitGroups,
3408 Autopromote::getAutopromoteGroups( $this )
3409 ) );
3410 }
3411 if ( $recache ) {
3412 // Assure data consistency with rights/groups,
3413 // as getEffectiveGroups() depends on this function
3414 $this->mEffectiveGroups = null;
3415 }
3416 }
3417 return $this->mImplicitGroups;
3418 }
3419
3420 /**
3421 * Returns the groups the user has belonged to.
3422 *
3423 * The user may still belong to the returned groups. Compare with getGroups().
3424 *
3425 * The function will not return groups the user had belonged to before MW 1.17
3426 *
3427 * @return array Names of the groups the user has belonged to.
3428 */
3429 public function getFormerGroups() {
3430 $this->load();
3431
3432 if ( is_null( $this->mFormerGroups ) ) {
3433 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
3434 ? wfGetDB( DB_MASTER )
3435 : wfGetDB( DB_REPLICA );
3436 $res = $db->select( 'user_former_groups',
3437 [ 'ufg_group' ],
3438 [ 'ufg_user' => $this->mId ],
3439 __METHOD__ );
3440 $this->mFormerGroups = [];
3441 foreach ( $res as $row ) {
3442 $this->mFormerGroups[] = $row->ufg_group;
3443 }
3444 }
3445
3446 return $this->mFormerGroups;
3447 }
3448
3449 /**
3450 * Get the user's edit count.
3451 * @return int|null Null for anonymous users
3452 */
3453 public function getEditCount() {
3454 if ( !$this->getId() ) {
3455 return null;
3456 }
3457
3458 if ( $this->mEditCount === null ) {
3459 /* Populate the count, if it has not been populated yet */
3460 $dbr = wfGetDB( DB_REPLICA );
3461 // check if the user_editcount field has been initialized
3462 $count = $dbr->selectField(
3463 'user', 'user_editcount',
3464 [ 'user_id' => $this->mId ],
3465 __METHOD__
3466 );
3467
3468 if ( $count === null ) {
3469 // it has not been initialized. do so.
3470 $count = $this->initEditCountInternal( $dbr );
3471 }
3472 $this->mEditCount = $count;
3473 }
3474 return (int)$this->mEditCount;
3475 }
3476
3477 /**
3478 * Add the user to the given group. This takes immediate effect.
3479 * If the user is already in the group, the expiry time will be updated to the new
3480 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3481 * never expire.)
3482 *
3483 * @param string $group Name of the group to add
3484 * @param string|null $expiry Optional expiry timestamp in any format acceptable to
3485 * wfTimestamp(), or null if the group assignment should not expire
3486 * @return bool
3487 */
3488 public function addGroup( $group, $expiry = null ) {
3489 $this->load();
3490 $this->loadGroups();
3491
3492 if ( $expiry ) {
3493 $expiry = wfTimestamp( TS_MW, $expiry );
3494 }
3495
3496 if ( !Hooks::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3497 return false;
3498 }
3499
3500 // create the new UserGroupMembership and put it in the DB
3501 $ugm = new UserGroupMembership( $this->mId, $group, $expiry );
3502 if ( !$ugm->insert( true ) ) {
3503 return false;
3504 }
3505
3506 $this->mGroupMemberships[$group] = $ugm;
3507
3508 // Refresh the groups caches, and clear the rights cache so it will be
3509 // refreshed on the next call to $this->getRights().
3510 $this->getEffectiveGroups( true );
3511 MediaWikiServices::getInstance()->getPermissionManager()->invalidateUsersRightsCache( $this );
3512 $this->invalidateCache();
3513
3514 return true;
3515 }
3516
3517 /**
3518 * Remove the user from the given group.
3519 * This takes immediate effect.
3520 * @param string $group Name of the group to remove
3521 * @return bool
3522 */
3523 public function removeGroup( $group ) {
3524 $this->load();
3525
3526 if ( !Hooks::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3527 return false;
3528 }
3529
3530 $ugm = UserGroupMembership::getMembership( $this->mId, $group );
3531 // delete the membership entry
3532 if ( !$ugm || !$ugm->delete() ) {
3533 return false;
3534 }
3535
3536 $this->loadGroups();
3537 unset( $this->mGroupMemberships[$group] );
3538
3539 // Refresh the groups caches, and clear the rights cache so it will be
3540 // refreshed on the next call to $this->getRights().
3541 $this->getEffectiveGroups( true );
3542 MediaWikiServices::getInstance()->getPermissionManager()->invalidateUsersRightsCache( $this );
3543 $this->invalidateCache();
3544
3545 return true;
3546 }
3547
3548 /**
3549 * Alias of isLoggedIn() with a name that describes its actual functionality. UserIdentity has
3550 * only this new name and not the old isLoggedIn() variant.
3551 *
3552 * @return bool True if user is registered on this wiki, i.e., has a user ID. False if user is
3553 * anonymous or has no local account (which can happen when importing). This is equivalent to
3554 * getId() != 0 and is provided for code readability.
3555 * @since 1.34
3556 */
3557 public function isRegistered() {
3558 return $this->getId() != 0;
3559 }
3560
3561 /**
3562 * Get whether the user is logged in
3563 * @return bool
3564 */
3565 public function isLoggedIn() {
3566 return $this->isRegistered();
3567 }
3568
3569 /**
3570 * Get whether the user is anonymous
3571 * @return bool
3572 */
3573 public function isAnon() {
3574 return !$this->isRegistered();
3575 }
3576
3577 /**
3578 * @return bool Whether this user is flagged as being a bot role account
3579 * @since 1.28
3580 */
3581 public function isBot() {
3582 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3583 return true;
3584 }
3585
3586 $isBot = false;
3587 Hooks::run( "UserIsBot", [ $this, &$isBot ] );
3588
3589 return $isBot;
3590 }
3591
3592 /**
3593 * Check if user is allowed to access a feature / make an action
3594 *
3595 * @deprecated since 1.34, use MediaWikiServices::getInstance()
3596 * ->getPermissionManager()->userHasAnyRights(...) instead
3597 *
3598 * @param string $permissions,... Permissions to test
3599 * @return bool True if user is allowed to perform *any* of the given actions
3600 * @suppress PhanCommentParamOnEmptyParamList Cannot make variadic due to HHVM bug, T191668#5263929
3601 */
3602 public function isAllowedAny() {
3603 return MediaWikiServices::getInstance()
3604 ->getPermissionManager()
3605 ->userHasAnyRight( $this, ...func_get_args() );
3606 }
3607
3608 /**
3609 * @deprecated since 1.34, use MediaWikiServices::getInstance()
3610 * ->getPermissionManager()->userHasAllRights(...) instead
3611 * @param string $permissions,... Permissions to test
3612 * @return bool True if the user is allowed to perform *all* of the given actions
3613 * @suppress PhanCommentParamOnEmptyParamList Cannot make variadic due to HHVM bug, T191668#5263929
3614 */
3615 public function isAllowedAll() {
3616 return MediaWikiServices::getInstance()
3617 ->getPermissionManager()
3618 ->userHasAllRights( $this, ...func_get_args() );
3619 }
3620
3621 /**
3622 * Internal mechanics of testing a permission
3623 *
3624 * @deprecated since 1.34, use MediaWikiServices::getInstance()
3625 * ->getPermissionManager()->userHasRight(...) instead
3626 *
3627 * @param string $action
3628 *
3629 * @return bool
3630 */
3631 public function isAllowed( $action = '' ) {
3632 return MediaWikiServices::getInstance()->getPermissionManager()
3633 ->userHasRight( $this, $action );
3634 }
3635
3636 /**
3637 * Check whether to enable recent changes patrol features for this user
3638 * @return bool True or false
3639 */
3640 public function useRCPatrol() {
3641 global $wgUseRCPatrol;
3642 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3643 }
3644
3645 /**
3646 * Check whether to enable new pages patrol features for this user
3647 * @return bool True or false
3648 */
3649 public function useNPPatrol() {
3650 global $wgUseRCPatrol, $wgUseNPPatrol;
3651 return (
3652 ( $wgUseRCPatrol || $wgUseNPPatrol )
3653 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3654 );
3655 }
3656
3657 /**
3658 * Check whether to enable new files patrol features for this user
3659 * @return bool True or false
3660 */
3661 public function useFilePatrol() {
3662 global $wgUseRCPatrol, $wgUseFilePatrol;
3663 return (
3664 ( $wgUseRCPatrol || $wgUseFilePatrol )
3665 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3666 );
3667 }
3668
3669 /**
3670 * Get the WebRequest object to use with this object
3671 *
3672 * @return WebRequest
3673 */
3674 public function getRequest() {
3675 if ( $this->mRequest ) {
3676 return $this->mRequest;
3677 }
3678
3679 global $wgRequest;
3680 return $wgRequest;
3681 }
3682
3683 /**
3684 * Check the watched status of an article.
3685 * @since 1.22 $checkRights parameter added
3686 * @param Title $title Title of the article to look at
3687 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3688 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3689 * @return bool
3690 */
3691 public function isWatched( $title, $checkRights = self::CHECK_USER_RIGHTS ) {
3692 if ( $title->isWatchable() && ( !$checkRights || $this->isAllowed( 'viewmywatchlist' ) ) ) {
3693 return MediaWikiServices::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3694 }
3695 return false;
3696 }
3697
3698 /**
3699 * Watch an article.
3700 * @since 1.22 $checkRights parameter added
3701 * @param Title $title Title of the article to look at
3702 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3703 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3704 */
3705 public function addWatch( $title, $checkRights = self::CHECK_USER_RIGHTS ) {
3706 if ( !$checkRights || $this->isAllowed( 'editmywatchlist' ) ) {
3707 MediaWikiServices::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3708 $this,
3709 [ $title->getSubjectPage(), $title->getTalkPage() ]
3710 );
3711 }
3712 $this->invalidateCache();
3713 }
3714
3715 /**
3716 * Stop watching an article.
3717 * @since 1.22 $checkRights parameter added
3718 * @param Title $title Title of the article to look at
3719 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3720 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3721 */
3722 public function removeWatch( $title, $checkRights = self::CHECK_USER_RIGHTS ) {
3723 if ( !$checkRights || $this->isAllowed( 'editmywatchlist' ) ) {
3724 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
3725 $store->removeWatch( $this, $title->getSubjectPage() );
3726 $store->removeWatch( $this, $title->getTalkPage() );
3727 }
3728 $this->invalidateCache();
3729 }
3730
3731 /**
3732 * Clear the user's notification timestamp for the given title.
3733 * If e-notif e-mails are on, they will receive notification mails on
3734 * the next change of the page if it's watched etc.
3735 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3736 * @param Title &$title Title of the article to look at
3737 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3738 */
3739 public function clearNotification( &$title, $oldid = 0 ) {
3740 global $wgUseEnotif, $wgShowUpdatedMarker;
3741
3742 // Do nothing if the database is locked to writes
3743 if ( wfReadOnly() ) {
3744 return;
3745 }
3746
3747 // Do nothing if not allowed to edit the watchlist
3748 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3749 return;
3750 }
3751
3752 // If we're working on user's talk page, we should update the talk page message indicator
3753 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3754 // Avoid PHP 7.1 warning of passing $this by reference
3755 $user = $this;
3756 if ( !Hooks::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3757 return;
3758 }
3759
3760 // Try to update the DB post-send and only if needed...
3761 DeferredUpdates::addCallableUpdate( function () use ( $title, $oldid ) {
3762 if ( !$this->getNewtalk() ) {
3763 return; // no notifications to clear
3764 }
3765
3766 // Delete the last notifications (they stack up)
3767 $this->setNewtalk( false );
3768
3769 // If there is a new, unseen, revision, use its timestamp
3770 $nextid = $oldid
3771 ? $title->getNextRevisionID( $oldid, Title::GAID_FOR_UPDATE )
3772 : null;
3773 if ( $nextid ) {
3774 $this->setNewtalk( true, Revision::newFromId( $nextid ) );
3775 }
3776 } );
3777 }
3778
3779 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3780 return;
3781 }
3782
3783 if ( $this->isAnon() ) {
3784 // Nothing else to do...
3785 return;
3786 }
3787
3788 // Only update the timestamp if the page is being watched.
3789 // The query to find out if it is watched is cached both in memcached and per-invocation,
3790 // and when it does have to be executed, it can be on a replica DB
3791 // If this is the user's newtalk page, we always update the timestamp
3792 $force = '';
3793 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3794 $force = 'force';
3795 }
3796
3797 MediaWikiServices::getInstance()->getWatchedItemStore()
3798 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3799 }
3800
3801 /**
3802 * Resets all of the given user's page-change notification timestamps.
3803 * If e-notif e-mails are on, they will receive notification mails on
3804 * the next change of any watched page.
3805 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3806 */
3807 public function clearAllNotifications() {
3808 global $wgUseEnotif, $wgShowUpdatedMarker;
3809 // Do nothing if not allowed to edit the watchlist
3810 if ( wfReadOnly() || !$this->isAllowed( 'editmywatchlist' ) ) {
3811 return;
3812 }
3813
3814 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3815 $this->setNewtalk( false );
3816 return;
3817 }
3818
3819 $id = $this->getId();
3820 if ( !$id ) {
3821 return;
3822 }
3823
3824 $watchedItemStore = MediaWikiServices::getInstance()->getWatchedItemStore();
3825 $watchedItemStore->resetAllNotificationTimestampsForUser( $this );
3826
3827 // We also need to clear here the "you have new message" notification for the own
3828 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3829 }
3830
3831 /**
3832 * Compute experienced level based on edit count and registration date.
3833 *
3834 * @return string 'newcomer', 'learner', or 'experienced'
3835 */
3836 public function getExperienceLevel() {
3837 global $wgLearnerEdits,
3838 $wgExperiencedUserEdits,
3839 $wgLearnerMemberSince,
3840 $wgExperiencedUserMemberSince;
3841
3842 if ( $this->isAnon() ) {
3843 return false;
3844 }
3845
3846 $editCount = $this->getEditCount();
3847 $registration = $this->getRegistration();
3848 $now = time();
3849 $learnerRegistration = wfTimestamp( TS_MW, $now - $wgLearnerMemberSince * 86400 );
3850 $experiencedRegistration = wfTimestamp( TS_MW, $now - $wgExperiencedUserMemberSince * 86400 );
3851
3852 if ( $editCount < $wgLearnerEdits ||
3853 $registration > $learnerRegistration ) {
3854 return 'newcomer';
3855 }
3856
3857 if ( $editCount > $wgExperiencedUserEdits &&
3858 $registration <= $experiencedRegistration
3859 ) {
3860 return 'experienced';
3861 }
3862
3863 return 'learner';
3864 }
3865
3866 /**
3867 * Persist this user's session (e.g. set cookies)
3868 *
3869 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3870 * is passed.
3871 * @param bool|null $secure Whether to force secure/insecure cookies or use default
3872 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3873 */
3874 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3875 $this->load();
3876 if ( $this->mId == 0 ) {
3877 return;
3878 }
3879
3880 $session = $this->getRequest()->getSession();
3881 if ( $request && $session->getRequest() !== $request ) {
3882 $session = $session->sessionWithRequest( $request );
3883 }
3884 $delay = $session->delaySave();
3885
3886 if ( !$session->getUser()->equals( $this ) ) {
3887 if ( !$session->canSetUser() ) {
3888 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3889 ->warning( __METHOD__ .
3890 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3891 );
3892 return;
3893 }
3894 $session->setUser( $this );
3895 }
3896
3897 $session->setRememberUser( $rememberMe );
3898 if ( $secure !== null ) {
3899 $session->setForceHTTPS( $secure );
3900 }
3901
3902 $session->persist();
3903
3904 ScopedCallback::consume( $delay );
3905 }
3906
3907 /**
3908 * Log this user out.
3909 */
3910 public function logout() {
3911 // Avoid PHP 7.1 warning of passing $this by reference
3912 $user = $this;
3913 if ( Hooks::run( 'UserLogout', [ &$user ] ) ) {
3914 $this->doLogout();
3915 }
3916 }
3917
3918 /**
3919 * Clear the user's session, and reset the instance cache.
3920 * @see logout()
3921 */
3922 public function doLogout() {
3923 $session = $this->getRequest()->getSession();
3924 if ( !$session->canSetUser() ) {
3925 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3926 ->warning( __METHOD__ . ": Cannot log out of an immutable session" );
3927 $error = 'immutable';
3928 } elseif ( !$session->getUser()->equals( $this ) ) {
3929 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3930 ->warning( __METHOD__ .
3931 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3932 );
3933 // But we still may as well make this user object anon
3934 $this->clearInstanceCache( 'defaults' );
3935 $error = 'wronguser';
3936 } else {
3937 $this->clearInstanceCache( 'defaults' );
3938 $delay = $session->delaySave();
3939 $session->unpersist(); // Clear cookies (T127436)
3940 $session->setLoggedOutTimestamp( time() );
3941 $session->setUser( new User );
3942 $session->set( 'wsUserID', 0 ); // Other code expects this
3943 $session->resetAllTokens();
3944 ScopedCallback::consume( $delay );
3945 $error = false;
3946 }
3947 \MediaWiki\Logger\LoggerFactory::getInstance( 'authevents' )->info( 'Logout', [
3948 'event' => 'logout',
3949 'successful' => $error === false,
3950 'status' => $error ?: 'success',
3951 ] );
3952 }
3953
3954 /**
3955 * Save this user's settings into the database.
3956 * @todo Only rarely do all these fields need to be set!
3957 */
3958 public function saveSettings() {
3959 if ( wfReadOnly() ) {
3960 // @TODO: caller should deal with this instead!
3961 // This should really just be an exception.
3962 MWExceptionHandler::logException( new DBExpectedError(
3963 null,
3964 "Could not update user with ID '{$this->mId}'; DB is read-only."
3965 ) );
3966 return;
3967 }
3968
3969 $this->load();
3970 if ( $this->mId == 0 ) {
3971 return; // anon
3972 }
3973
3974 // Get a new user_touched that is higher than the old one.
3975 // This will be used for a CAS check as a last-resort safety
3976 // check against race conditions and replica DB lag.
3977 $newTouched = $this->newTouchedTimestamp();
3978
3979 $dbw = wfGetDB( DB_MASTER );
3980 $dbw->doAtomicSection( __METHOD__, function ( IDatabase $dbw, $fname ) use ( $newTouched ) {
3981 global $wgActorTableSchemaMigrationStage;
3982
3983 $dbw->update( 'user',
3984 [ /* SET */
3985 'user_name' => $this->mName,
3986 'user_real_name' => $this->mRealName,
3987 'user_email' => $this->mEmail,
3988 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3989 'user_touched' => $dbw->timestamp( $newTouched ),
3990 'user_token' => strval( $this->mToken ),
3991 'user_email_token' => $this->mEmailToken,
3992 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3993 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
3994 'user_id' => $this->mId,
3995 ] ), $fname
3996 );
3997
3998 if ( !$dbw->affectedRows() ) {
3999 // Maybe the problem was a missed cache update; clear it to be safe
4000 $this->clearSharedCache( 'refresh' );
4001 // User was changed in the meantime or loaded with stale data
4002 $from = ( $this->queryFlagsUsed & self::READ_LATEST ) ? 'master' : 'replica';
4003 LoggerFactory::getInstance( 'preferences' )->warning(
4004 "CAS update failed on user_touched for user ID '{user_id}' ({db_flag} read)",
4005 [ 'user_id' => $this->mId, 'db_flag' => $from ]
4006 );
4007 throw new MWException( "CAS update failed on user_touched. " .
4008 "The version of the user to be saved is older than the current version."
4009 );
4010 }
4011
4012 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) {
4013 $dbw->update(
4014 'actor',
4015 [ 'actor_name' => $this->mName ],
4016 [ 'actor_user' => $this->mId ],
4017 $fname
4018 );
4019 }
4020 } );
4021
4022 $this->mTouched = $newTouched;
4023 $this->saveOptions();
4024
4025 Hooks::run( 'UserSaveSettings', [ $this ] );
4026 $this->clearSharedCache( 'changed' );
4027 $this->getUserPage()->purgeSquid();
4028 }
4029
4030 /**
4031 * If only this user's username is known, and it exists, return the user ID.
4032 *
4033 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4034 * @return int
4035 */
4036 public function idForName( $flags = 0 ) {
4037 $s = trim( $this->getName() );
4038 if ( $s === '' ) {
4039 return 0;
4040 }
4041
4042 $db = ( ( $flags & self::READ_LATEST ) == self::READ_LATEST )
4043 ? wfGetDB( DB_MASTER )
4044 : wfGetDB( DB_REPLICA );
4045
4046 $options = ( ( $flags & self::READ_LOCKING ) == self::READ_LOCKING )
4047 ? [ 'LOCK IN SHARE MODE' ]
4048 : [];
4049
4050 $id = $db->selectField( 'user',
4051 'user_id', [ 'user_name' => $s ], __METHOD__, $options );
4052
4053 return (int)$id;
4054 }
4055
4056 /**
4057 * Add a user to the database, return the user object
4058 *
4059 * @param string $name Username to add
4060 * @param array $params Array of Strings Non-default parameters to save to
4061 * the database as user_* fields:
4062 * - email: The user's email address.
4063 * - email_authenticated: The email authentication timestamp.
4064 * - real_name: The user's real name.
4065 * - options: An associative array of non-default options.
4066 * - token: Random authentication token. Do not set.
4067 * - registration: Registration timestamp. Do not set.
4068 *
4069 * @return User|null User object, or null if the username already exists.
4070 */
4071 public static function createNew( $name, $params = [] ) {
4072 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4073 if ( isset( $params[$field] ) ) {
4074 wfDeprecated( __METHOD__ . " with param '$field'", '1.27' );
4075 unset( $params[$field] );
4076 }
4077 }
4078
4079 $user = new User;
4080 $user->load();
4081 $user->setToken(); // init token
4082 if ( isset( $params['options'] ) ) {
4083 $user->mOptions = $params['options'] + (array)$user->mOptions;
4084 unset( $params['options'] );
4085 }
4086 $dbw = wfGetDB( DB_MASTER );
4087
4088 $noPass = PasswordFactory::newInvalidPassword()->toString();
4089
4090 $fields = [
4091 'user_name' => $name,
4092 'user_password' => $noPass,
4093 'user_newpassword' => $noPass,
4094 'user_email' => $user->mEmail,
4095 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
4096 'user_real_name' => $user->mRealName,
4097 'user_token' => strval( $user->mToken ),
4098 'user_registration' => $dbw->timestamp( $user->mRegistration ),
4099 'user_editcount' => 0,
4100 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4101 ];
4102 foreach ( $params as $name => $value ) {
4103 $fields["user_$name"] = $value;
4104 }
4105
4106 return $dbw->doAtomicSection( __METHOD__, function ( IDatabase $dbw, $fname ) use ( $fields ) {
4107 $dbw->insert( 'user', $fields, $fname, [ 'IGNORE' ] );
4108 if ( $dbw->affectedRows() ) {
4109 $newUser = self::newFromId( $dbw->insertId() );
4110 $newUser->mName = $fields['user_name'];
4111 $newUser->updateActorId( $dbw );
4112 // Load the user from master to avoid replica lag
4113 $newUser->load( self::READ_LATEST );
4114 } else {
4115 $newUser = null;
4116 }
4117 return $newUser;
4118 } );
4119 }
4120
4121 /**
4122 * Add this existing user object to the database. If the user already
4123 * exists, a fatal status object is returned, and the user object is
4124 * initialised with the data from the database.
4125 *
4126 * Previously, this function generated a DB error due to a key conflict
4127 * if the user already existed. Many extension callers use this function
4128 * in code along the lines of:
4129 *
4130 * $user = User::newFromName( $name );
4131 * if ( !$user->isLoggedIn() ) {
4132 * $user->addToDatabase();
4133 * }
4134 * // do something with $user...
4135 *
4136 * However, this was vulnerable to a race condition (T18020). By
4137 * initialising the user object if the user exists, we aim to support this
4138 * calling sequence as far as possible.
4139 *
4140 * Note that if the user exists, this function will acquire a write lock,
4141 * so it is still advisable to make the call conditional on isLoggedIn(),
4142 * and to commit the transaction after calling.
4143 *
4144 * @throws MWException
4145 * @return Status
4146 */
4147 public function addToDatabase() {
4148 $this->load();
4149 if ( !$this->mToken ) {
4150 $this->setToken(); // init token
4151 }
4152
4153 if ( !is_string( $this->mName ) ) {
4154 throw new RuntimeException( "User name field is not set." );
4155 }
4156
4157 $this->mTouched = $this->newTouchedTimestamp();
4158
4159 $dbw = wfGetDB( DB_MASTER );
4160 $status = $dbw->doAtomicSection( __METHOD__, function ( IDatabase $dbw, $fname ) {
4161 $noPass = PasswordFactory::newInvalidPassword()->toString();
4162 $dbw->insert( 'user',
4163 [
4164 'user_name' => $this->mName,
4165 'user_password' => $noPass,
4166 'user_newpassword' => $noPass,
4167 'user_email' => $this->mEmail,
4168 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
4169 'user_real_name' => $this->mRealName,
4170 'user_token' => strval( $this->mToken ),
4171 'user_registration' => $dbw->timestamp( $this->mRegistration ),
4172 'user_editcount' => 0,
4173 'user_touched' => $dbw->timestamp( $this->mTouched ),
4174 ], $fname,
4175 [ 'IGNORE' ]
4176 );
4177 if ( !$dbw->affectedRows() ) {
4178 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4179 $this->mId = $dbw->selectField(
4180 'user',
4181 'user_id',
4182 [ 'user_name' => $this->mName ],
4183 $fname,
4184 [ 'LOCK IN SHARE MODE' ]
4185 );
4186 $loaded = false;
4187 if ( $this->mId && $this->loadFromDatabase( self::READ_LOCKING ) ) {
4188 $loaded = true;
4189 }
4190 if ( !$loaded ) {
4191 throw new MWException( $fname . ": hit a key conflict attempting " .
4192 "to insert user '{$this->mName}' row, but it was not present in select!" );
4193 }
4194 return Status::newFatal( 'userexists' );
4195 }
4196 $this->mId = $dbw->insertId();
4197 self::$idCacheByName[$this->mName] = $this->mId;
4198 $this->updateActorId( $dbw );
4199
4200 return Status::newGood();
4201 } );
4202 if ( !$status->isGood() ) {
4203 return $status;
4204 }
4205
4206 // Clear instance cache other than user table data and actor, which is already accurate
4207 $this->clearInstanceCache();
4208
4209 $this->saveOptions();
4210 return Status::newGood();
4211 }
4212
4213 /**
4214 * Update the actor ID after an insert
4215 * @param IDatabase $dbw Writable database handle
4216 */
4217 private function updateActorId( IDatabase $dbw ) {
4218 global $wgActorTableSchemaMigrationStage;
4219
4220 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) {
4221 $dbw->insert(
4222 'actor',
4223 [ 'actor_user' => $this->mId, 'actor_name' => $this->mName ],
4224 __METHOD__
4225 );
4226 $this->mActorId = (int)$dbw->insertId();
4227 }
4228 }
4229
4230 /**
4231 * If this user is logged-in and blocked,
4232 * block any IP address they've successfully logged in from.
4233 * @return bool A block was spread
4234 */
4235 public function spreadAnyEditBlock() {
4236 if ( $this->isLoggedIn() && $this->getBlock() ) {
4237 return $this->spreadBlock();
4238 }
4239
4240 return false;
4241 }
4242
4243 /**
4244 * If this (non-anonymous) user is blocked,
4245 * block the IP address they've successfully logged in from.
4246 * @return bool A block was spread
4247 */
4248 protected function spreadBlock() {
4249 wfDebug( __METHOD__ . "()\n" );
4250 $this->load();
4251 if ( $this->mId == 0 ) {
4252 return false;
4253 }
4254
4255 $userblock = DatabaseBlock::newFromTarget( $this->getName() );
4256 if ( !$userblock ) {
4257 return false;
4258 }
4259
4260 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4261 }
4262
4263 /**
4264 * Get whether the user is explicitly blocked from account creation.
4265 * @return bool|AbstractBlock
4266 */
4267 public function isBlockedFromCreateAccount() {
4268 $this->getBlockedStatus();
4269 if ( $this->mBlock && $this->mBlock->appliesToRight( 'createaccount' ) ) {
4270 return $this->mBlock;
4271 }
4272
4273 # T15611: if the IP address the user is trying to create an account from is
4274 # blocked with createaccount disabled, prevent new account creation there even
4275 # when the user is logged in
4276 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4277 $this->mBlockedFromCreateAccount = DatabaseBlock::newFromTarget(
4278 null, $this->getRequest()->getIP()
4279 );
4280 }
4281 return $this->mBlockedFromCreateAccount instanceof AbstractBlock
4282 && $this->mBlockedFromCreateAccount->appliesToRight( 'createaccount' )
4283 ? $this->mBlockedFromCreateAccount
4284 : false;
4285 }
4286
4287 /**
4288 * Get whether the user is blocked from using Special:Emailuser.
4289 * @return bool
4290 */
4291 public function isBlockedFromEmailuser() {
4292 $this->getBlockedStatus();
4293 return $this->mBlock && $this->mBlock->appliesToRight( 'sendemail' );
4294 }
4295
4296 /**
4297 * Get whether the user is blocked from using Special:Upload
4298 *
4299 * @since 1.33
4300 * @return bool
4301 */
4302 public function isBlockedFromUpload() {
4303 $this->getBlockedStatus();
4304 return $this->mBlock && $this->mBlock->appliesToRight( 'upload' );
4305 }
4306
4307 /**
4308 * Get whether the user is allowed to create an account.
4309 * @return bool
4310 */
4311 public function isAllowedToCreateAccount() {
4312 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4313 }
4314
4315 /**
4316 * Get this user's personal page title.
4317 *
4318 * @return Title User's personal page title
4319 */
4320 public function getUserPage() {
4321 return Title::makeTitle( NS_USER, $this->getName() );
4322 }
4323
4324 /**
4325 * Get this user's talk page title.
4326 *
4327 * @return Title User's talk page title
4328 */
4329 public function getTalkPage() {
4330 $title = $this->getUserPage();
4331 return $title->getTalkPage();
4332 }
4333
4334 /**
4335 * Determine whether the user is a newbie. Newbies are either
4336 * anonymous IPs, or the most recently created accounts.
4337 * @return bool
4338 */
4339 public function isNewbie() {
4340 return !$this->isAllowed( 'autoconfirmed' );
4341 }
4342
4343 /**
4344 * Check to see if the given clear-text password is one of the accepted passwords
4345 * @deprecated since 1.27, use AuthManager instead
4346 * @param string $password User password
4347 * @return bool True if the given password is correct, otherwise False
4348 */
4349 public function checkPassword( $password ) {
4350 wfDeprecated( __METHOD__, '1.27' );
4351
4352 $manager = AuthManager::singleton();
4353 $reqs = AuthenticationRequest::loadRequestsFromSubmission(
4354 $manager->getAuthenticationRequests( AuthManager::ACTION_LOGIN ),
4355 [
4356 'username' => $this->getName(),
4357 'password' => $password,
4358 ]
4359 );
4360 $res = AuthManager::singleton()->beginAuthentication( $reqs, 'null:' );
4361 switch ( $res->status ) {
4362 case AuthenticationResponse::PASS:
4363 return true;
4364 case AuthenticationResponse::FAIL:
4365 // Hope it's not a PreAuthenticationProvider that failed...
4366 \MediaWiki\Logger\LoggerFactory::getInstance( 'authentication' )
4367 ->info( __METHOD__ . ': Authentication failed: ' . $res->message->plain() );
4368 return false;
4369 default:
4370 throw new BadMethodCallException(
4371 'AuthManager returned a response unsupported by ' . __METHOD__
4372 );
4373 }
4374 }
4375
4376 /**
4377 * Check if the given clear-text password matches the temporary password
4378 * sent by e-mail for password reset operations.
4379 *
4380 * @deprecated since 1.27, use AuthManager instead
4381 * @param string $plaintext
4382 * @return bool True if matches, false otherwise
4383 */
4384 public function checkTemporaryPassword( $plaintext ) {
4385 wfDeprecated( __METHOD__, '1.27' );
4386 // Can't check the temporary password individually.
4387 return $this->checkPassword( $plaintext );
4388 }
4389
4390 /**
4391 * Initialize (if necessary) and return a session token value
4392 * which can be used in edit forms to show that the user's
4393 * login credentials aren't being hijacked with a foreign form
4394 * submission.
4395 *
4396 * @since 1.27
4397 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4398 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4399 * @return MediaWiki\Session\Token The new edit token
4400 */
4401 public function getEditTokenObject( $salt = '', $request = null ) {
4402 if ( $this->isAnon() ) {
4403 return new LoggedOutEditToken();
4404 }
4405
4406 if ( !$request ) {
4407 $request = $this->getRequest();
4408 }
4409 return $request->getSession()->getToken( $salt );
4410 }
4411
4412 /**
4413 * Initialize (if necessary) and return a session token value
4414 * which can be used in edit forms to show that the user's
4415 * login credentials aren't being hijacked with a foreign form
4416 * submission.
4417 *
4418 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4419 *
4420 * @since 1.19
4421 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4422 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4423 * @return string The new edit token
4424 */
4425 public function getEditToken( $salt = '', $request = null ) {
4426 return $this->getEditTokenObject( $salt, $request )->toString();
4427 }
4428
4429 /**
4430 * Check given value against the token value stored in the session.
4431 * A match should confirm that the form was submitted from the
4432 * user's own login session, not a form submission from a third-party
4433 * site.
4434 *
4435 * @param string $val Input value to compare
4436 * @param string|array $salt Optional function-specific data for hashing
4437 * @param WebRequest|null $request Object to use or null to use $wgRequest
4438 * @param int|null $maxage Fail tokens older than this, in seconds
4439 * @return bool Whether the token matches
4440 */
4441 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4442 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4443 }
4444
4445 /**
4446 * Check given value against the token value stored in the session,
4447 * ignoring the suffix.
4448 *
4449 * @param string $val Input value to compare
4450 * @param string|array $salt Optional function-specific data for hashing
4451 * @param WebRequest|null $request Object to use or null to use $wgRequest
4452 * @param int|null $maxage Fail tokens older than this, in seconds
4453 * @return bool Whether the token matches
4454 */
4455 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4456 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token::SUFFIX;
4457 return $this->matchEditToken( $val, $salt, $request, $maxage );
4458 }
4459
4460 /**
4461 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4462 * mail to the user's given address.
4463 *
4464 * @param string $type Message to send, either "created", "changed" or "set"
4465 * @return Status
4466 */
4467 public function sendConfirmationMail( $type = 'created' ) {
4468 global $wgLang;
4469 $expiration = null; // gets passed-by-ref and defined in next line.
4470 $token = $this->confirmationToken( $expiration );
4471 $url = $this->confirmationTokenUrl( $token );
4472 $invalidateURL = $this->invalidationTokenUrl( $token );
4473 $this->saveSettings();
4474
4475 if ( $type == 'created' || $type === false ) {
4476 $message = 'confirmemail_body';
4477 $type = 'created';
4478 } elseif ( $type === true ) {
4479 $message = 'confirmemail_body_changed';
4480 $type = 'changed';
4481 } else {
4482 // Messages: confirmemail_body_changed, confirmemail_body_set
4483 $message = 'confirmemail_body_' . $type;
4484 }
4485
4486 $mail = [
4487 'subject' => wfMessage( 'confirmemail_subject' )->text(),
4488 'body' => wfMessage( $message,
4489 $this->getRequest()->getIP(),
4490 $this->getName(),
4491 $url,
4492 $wgLang->userTimeAndDate( $expiration, $this ),
4493 $invalidateURL,
4494 $wgLang->userDate( $expiration, $this ),
4495 $wgLang->userTime( $expiration, $this ) )->text(),
4496 'from' => null,
4497 'replyTo' => null,
4498 ];
4499 $info = [
4500 'type' => $type,
4501 'ip' => $this->getRequest()->getIP(),
4502 'confirmURL' => $url,
4503 'invalidateURL' => $invalidateURL,
4504 'expiration' => $expiration
4505 ];
4506
4507 Hooks::run( 'UserSendConfirmationMail', [ $this, &$mail, $info ] );
4508 return $this->sendMail( $mail['subject'], $mail['body'], $mail['from'], $mail['replyTo'] );
4509 }
4510
4511 /**
4512 * Send an e-mail to this user's account. Does not check for
4513 * confirmed status or validity.
4514 *
4515 * @param string $subject Message subject
4516 * @param string $body Message body
4517 * @param User|null $from Optional sending user; if unspecified, default
4518 * $wgPasswordSender will be used.
4519 * @param MailAddress|null $replyto Reply-To address
4520 * @return Status
4521 */
4522 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4523 global $wgPasswordSender;
4524
4525 if ( $from instanceof User ) {
4526 $sender = MailAddress::newFromUser( $from );
4527 } else {
4528 $sender = new MailAddress( $wgPasswordSender,
4529 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4530 }
4531 $to = MailAddress::newFromUser( $this );
4532
4533 return UserMailer::send( $to, $sender, $subject, $body, [
4534 'replyTo' => $replyto,
4535 ] );
4536 }
4537
4538 /**
4539 * Generate, store, and return a new e-mail confirmation code.
4540 * A hash (unsalted, since it's used as a key) is stored.
4541 *
4542 * @note Call saveSettings() after calling this function to commit
4543 * this change to the database.
4544 *
4545 * @param string &$expiration Accepts the expiration time
4546 * @return string New token
4547 */
4548 protected function confirmationToken( &$expiration ) {
4549 global $wgUserEmailConfirmationTokenExpiry;
4550 $now = time();
4551 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
4552 $expiration = wfTimestamp( TS_MW, $expires );
4553 $this->load();
4554 $token = MWCryptRand::generateHex( 32 );
4555 $hash = md5( $token );
4556 $this->mEmailToken = $hash;
4557 $this->mEmailTokenExpires = $expiration;
4558 return $token;
4559 }
4560
4561 /**
4562 * Return a URL the user can use to confirm their email address.
4563 * @param string $token Accepts the email confirmation token
4564 * @return string New token URL
4565 */
4566 protected function confirmationTokenUrl( $token ) {
4567 return $this->getTokenUrl( 'ConfirmEmail', $token );
4568 }
4569
4570 /**
4571 * Return a URL the user can use to invalidate their email address.
4572 * @param string $token Accepts the email confirmation token
4573 * @return string New token URL
4574 */
4575 protected function invalidationTokenUrl( $token ) {
4576 return $this->getTokenUrl( 'InvalidateEmail', $token );
4577 }
4578
4579 /**
4580 * Internal function to format the e-mail validation/invalidation URLs.
4581 * This uses a quickie hack to use the
4582 * hardcoded English names of the Special: pages, for ASCII safety.
4583 *
4584 * @note Since these URLs get dropped directly into emails, using the
4585 * short English names avoids insanely long URL-encoded links, which
4586 * also sometimes can get corrupted in some browsers/mailers
4587 * (T8957 with Gmail and Internet Explorer).
4588 *
4589 * @param string $page Special page
4590 * @param string $token
4591 * @return string Formatted URL
4592 */
4593 protected function getTokenUrl( $page, $token ) {
4594 // Hack to bypass localization of 'Special:'
4595 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
4596 return $title->getCanonicalURL();
4597 }
4598
4599 /**
4600 * Mark the e-mail address confirmed.
4601 *
4602 * @note Call saveSettings() after calling this function to commit the change.
4603 *
4604 * @return bool
4605 */
4606 public function confirmEmail() {
4607 // Check if it's already confirmed, so we don't touch the database
4608 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4609 if ( !$this->isEmailConfirmed() ) {
4610 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4611 Hooks::run( 'ConfirmEmailComplete', [ $this ] );
4612 }
4613 return true;
4614 }
4615
4616 /**
4617 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4618 * address if it was already confirmed.
4619 *
4620 * @note Call saveSettings() after calling this function to commit the change.
4621 * @return bool Returns true
4622 */
4623 public function invalidateEmail() {
4624 $this->load();
4625 $this->mEmailToken = null;
4626 $this->mEmailTokenExpires = null;
4627 $this->setEmailAuthenticationTimestamp( null );
4628 $this->mEmail = '';
4629 Hooks::run( 'InvalidateEmailComplete', [ $this ] );
4630 return true;
4631 }
4632
4633 /**
4634 * Set the e-mail authentication timestamp.
4635 * @param string $timestamp TS_MW timestamp
4636 */
4637 public function setEmailAuthenticationTimestamp( $timestamp ) {
4638 $this->load();
4639 $this->mEmailAuthenticated = $timestamp;
4640 Hooks::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated ] );
4641 }
4642
4643 /**
4644 * Is this user allowed to send e-mails within limits of current
4645 * site configuration?
4646 * @return bool
4647 */
4648 public function canSendEmail() {
4649 global $wgEnableEmail, $wgEnableUserEmail;
4650 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4651 return false;
4652 }
4653 $canSend = $this->isEmailConfirmed();
4654 // Avoid PHP 7.1 warning of passing $this by reference
4655 $user = $this;
4656 Hooks::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4657 return $canSend;
4658 }
4659
4660 /**
4661 * Is this user allowed to receive e-mails within limits of current
4662 * site configuration?
4663 * @return bool
4664 */
4665 public function canReceiveEmail() {
4666 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4667 }
4668
4669 /**
4670 * Is this user's e-mail address valid-looking and confirmed within
4671 * limits of the current site configuration?
4672 *
4673 * @note If $wgEmailAuthentication is on, this may require the user to have
4674 * confirmed their address by returning a code or using a password
4675 * sent to the address from the wiki.
4676 *
4677 * @return bool
4678 */
4679 public function isEmailConfirmed() {
4680 global $wgEmailAuthentication;
4681 $this->load();
4682 // Avoid PHP 7.1 warning of passing $this by reference
4683 $user = $this;
4684 $confirmed = true;
4685 if ( Hooks::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4686 if ( $this->isAnon() ) {
4687 return false;
4688 }
4689 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4690 return false;
4691 }
4692 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4693 return false;
4694 }
4695 return true;
4696 }
4697
4698 return $confirmed;
4699 }
4700
4701 /**
4702 * Check whether there is an outstanding request for e-mail confirmation.
4703 * @return bool
4704 */
4705 public function isEmailConfirmationPending() {
4706 global $wgEmailAuthentication;
4707 return $wgEmailAuthentication &&
4708 !$this->isEmailConfirmed() &&
4709 $this->mEmailToken &&
4710 $this->mEmailTokenExpires > wfTimestamp();
4711 }
4712
4713 /**
4714 * Get the timestamp of account creation.
4715 *
4716 * @return string|bool|null Timestamp of account creation, false for
4717 * non-existent/anonymous user accounts, or null if existing account
4718 * but information is not in database.
4719 */
4720 public function getRegistration() {
4721 if ( $this->isAnon() ) {
4722 return false;
4723 }
4724 $this->load();
4725 return $this->mRegistration;
4726 }
4727
4728 /**
4729 * Get the timestamp of the first edit
4730 *
4731 * @return string|bool Timestamp of first edit, or false for
4732 * non-existent/anonymous user accounts.
4733 */
4734 public function getFirstEditTimestamp() {
4735 return $this->getEditTimestamp( true );
4736 }
4737
4738 /**
4739 * Get the timestamp of the latest edit
4740 *
4741 * @since 1.33
4742 * @return string|bool Timestamp of first edit, or false for
4743 * non-existent/anonymous user accounts.
4744 */
4745 public function getLatestEditTimestamp() {
4746 return $this->getEditTimestamp( false );
4747 }
4748
4749 /**
4750 * Get the timestamp of the first or latest edit
4751 *
4752 * @param bool $first True for the first edit, false for the latest one
4753 * @return string|bool Timestamp of first or latest edit, or false for
4754 * non-existent/anonymous user accounts.
4755 */
4756 private function getEditTimestamp( $first ) {
4757 if ( $this->getId() == 0 ) {
4758 return false; // anons
4759 }
4760 $dbr = wfGetDB( DB_REPLICA );
4761 $actorWhere = ActorMigration::newMigration()->getWhere( $dbr, 'rev_user', $this );
4762 $tsField = isset( $actorWhere['tables']['temp_rev_user'] )
4763 ? 'revactor_timestamp' : 'rev_timestamp';
4764 $sortOrder = $first ? 'ASC' : 'DESC';
4765 $time = $dbr->selectField(
4766 [ 'revision' ] + $actorWhere['tables'],
4767 $tsField,
4768 [ $actorWhere['conds'] ],
4769 __METHOD__,
4770 [ 'ORDER BY' => "$tsField $sortOrder" ],
4771 $actorWhere['joins']
4772 );
4773 if ( !$time ) {
4774 return false; // no edits
4775 }
4776 return wfTimestamp( TS_MW, $time );
4777 }
4778
4779 /**
4780 * Get the permissions associated with a given list of groups
4781 *
4782 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4783 * ->getGroupPermissions() instead
4784 *
4785 * @param array $groups Array of Strings List of internal group names
4786 * @return array Array of Strings List of permission key names for given groups combined
4787 */
4788 public static function getGroupPermissions( $groups ) {
4789 return MediaWikiServices::getInstance()->getPermissionManager()->getGroupPermissions( $groups );
4790 }
4791
4792 /**
4793 * Get all the groups who have a given permission
4794 *
4795 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4796 * ->getGroupsWithPermission() instead
4797 *
4798 * @param string $role Role to check
4799 * @return array Array of Strings List of internal group names with the given permission
4800 */
4801 public static function getGroupsWithPermission( $role ) {
4802 return MediaWikiServices::getInstance()->getPermissionManager()->getGroupsWithPermission( $role );
4803 }
4804
4805 /**
4806 * Check, if the given group has the given permission
4807 *
4808 * If you're wanting to check whether all users have a permission, use
4809 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4810 * from anyone.
4811 *
4812 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4813 * ->groupHasPermission(..) instead
4814 *
4815 * @since 1.21
4816 * @param string $group Group to check
4817 * @param string $role Role to check
4818 * @return bool
4819 */
4820 public static function groupHasPermission( $group, $role ) {
4821 return MediaWikiServices::getInstance()->getPermissionManager()
4822 ->groupHasPermission( $group, $role );
4823 }
4824
4825 /**
4826 * Check if all users may be assumed to have the given permission
4827 *
4828 * We generally assume so if the right is granted to '*' and isn't revoked
4829 * on any group. It doesn't attempt to take grants or other extension
4830 * limitations on rights into account in the general case, though, as that
4831 * would require it to always return false and defeat the purpose.
4832 * Specifically, session-based rights restrictions (such as OAuth or bot
4833 * passwords) are applied based on the current session.
4834 *
4835 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4836 * ->isEveryoneAllowed() instead
4837 *
4838 * @param string $right Right to check
4839 *
4840 * @return bool
4841 * @since 1.22
4842 */
4843 public static function isEveryoneAllowed( $right ) {
4844 return MediaWikiServices::getInstance()->getPermissionManager()->isEveryoneAllowed( $right );
4845 }
4846
4847 /**
4848 * Return the set of defined explicit groups.
4849 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4850 * are not included, as they are defined automatically, not in the database.
4851 * @return array Array of internal group names
4852 */
4853 public static function getAllGroups() {
4854 global $wgGroupPermissions, $wgRevokePermissions;
4855 return array_values( array_diff(
4856 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4857 self::getImplicitGroups()
4858 ) );
4859 }
4860
4861 /**
4862 * Get a list of all available permissions.
4863 *
4864 * @deprecated since 1.34, use PermissionManager::getAllPermissions() instead
4865 *
4866 * @return string[] Array of permission names
4867 */
4868 public static function getAllRights() {
4869 return MediaWikiServices::getInstance()->getPermissionManager()->getAllPermissions();
4870 }
4871
4872 /**
4873 * Get a list of implicit groups
4874 * TODO: Should we deprecate this? It's trivial, but we don't want to encourage use of globals.
4875 *
4876 * @return array Array of Strings Array of internal group names
4877 */
4878 public static function getImplicitGroups() {
4879 global $wgImplicitGroups;
4880 return $wgImplicitGroups;
4881 }
4882
4883 /**
4884 * Returns an array of the groups that a particular group can add/remove.
4885 *
4886 * @param string $group The group to check for whether it can add/remove
4887 * @return array [ 'add' => [ addablegroups ],
4888 * 'remove' => [ removablegroups ],
4889 * 'add-self' => [ addablegroups to self ],
4890 * 'remove-self' => [ removable groups from self ] ]
4891 */
4892 public static function changeableByGroup( $group ) {
4893 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4894
4895 $groups = [
4896 'add' => [],
4897 'remove' => [],
4898 'add-self' => [],
4899 'remove-self' => []
4900 ];
4901
4902 if ( empty( $wgAddGroups[$group] ) ) {
4903 // Don't add anything to $groups
4904 } elseif ( $wgAddGroups[$group] === true ) {
4905 // You get everything
4906 $groups['add'] = self::getAllGroups();
4907 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4908 $groups['add'] = $wgAddGroups[$group];
4909 }
4910
4911 // Same thing for remove
4912 if ( empty( $wgRemoveGroups[$group] ) ) {
4913 // Do nothing
4914 } elseif ( $wgRemoveGroups[$group] === true ) {
4915 $groups['remove'] = self::getAllGroups();
4916 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4917 $groups['remove'] = $wgRemoveGroups[$group];
4918 }
4919
4920 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4921 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4922 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4923 if ( is_int( $key ) ) {
4924 $wgGroupsAddToSelf['user'][] = $value;
4925 }
4926 }
4927 }
4928
4929 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4930 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4931 if ( is_int( $key ) ) {
4932 $wgGroupsRemoveFromSelf['user'][] = $value;
4933 }
4934 }
4935 }
4936
4937 // Now figure out what groups the user can add to him/herself
4938 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4939 // Do nothing
4940 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4941 // No idea WHY this would be used, but it's there
4942 $groups['add-self'] = self::getAllGroups();
4943 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4944 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4945 }
4946
4947 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4948 // Do nothing
4949 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4950 $groups['remove-self'] = self::getAllGroups();
4951 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4952 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4953 }
4954
4955 return $groups;
4956 }
4957
4958 /**
4959 * Returns an array of groups that this user can add and remove
4960 * @return array [ 'add' => [ addablegroups ],
4961 * 'remove' => [ removablegroups ],
4962 * 'add-self' => [ addablegroups to self ],
4963 * 'remove-self' => [ removable groups from self ] ]
4964 */
4965 public function changeableGroups() {
4966 if ( $this->isAllowed( 'userrights' ) ) {
4967 // This group gives the right to modify everything (reverse-
4968 // compatibility with old "userrights lets you change
4969 // everything")
4970 // Using array_merge to make the groups reindexed
4971 $all = array_merge( self::getAllGroups() );
4972 return [
4973 'add' => $all,
4974 'remove' => $all,
4975 'add-self' => [],
4976 'remove-self' => []
4977 ];
4978 }
4979
4980 // Okay, it's not so simple, we will have to go through the arrays
4981 $groups = [
4982 'add' => [],
4983 'remove' => [],
4984 'add-self' => [],
4985 'remove-self' => []
4986 ];
4987 $addergroups = $this->getEffectiveGroups();
4988
4989 foreach ( $addergroups as $addergroup ) {
4990 $groups = array_merge_recursive(
4991 $groups, $this->changeableByGroup( $addergroup )
4992 );
4993 $groups['add'] = array_unique( $groups['add'] );
4994 $groups['remove'] = array_unique( $groups['remove'] );
4995 $groups['add-self'] = array_unique( $groups['add-self'] );
4996 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4997 }
4998 return $groups;
4999 }
5000
5001 /**
5002 * Schedule a deferred update to update the user's edit count
5003 */
5004 public function incEditCount() {
5005 if ( $this->isAnon() ) {
5006 return; // sanity
5007 }
5008
5009 DeferredUpdates::addUpdate(
5010 new UserEditCountUpdate( $this, 1 ),
5011 DeferredUpdates::POSTSEND
5012 );
5013 }
5014
5015 /**
5016 * This method should not be called outside User/UserEditCountUpdate
5017 *
5018 * @param int $count
5019 */
5020 public function setEditCountInternal( $count ) {
5021 $this->mEditCount = $count;
5022 }
5023
5024 /**
5025 * Initialize user_editcount from data out of the revision table
5026 *
5027 * @internal This method should not be called outside User/UserEditCountUpdate
5028 * @param IDatabase $dbr Replica database
5029 * @return int Number of edits
5030 */
5031 public function initEditCountInternal( IDatabase $dbr ) {
5032 // Pull from a replica DB to be less cruel to servers
5033 // Accuracy isn't the point anyway here
5034 $actorWhere = ActorMigration::newMigration()->getWhere( $dbr, 'rev_user', $this );
5035 $count = (int)$dbr->selectField(
5036 [ 'revision' ] + $actorWhere['tables'],
5037 'COUNT(*)',
5038 [ $actorWhere['conds'] ],
5039 __METHOD__,
5040 [],
5041 $actorWhere['joins']
5042 );
5043
5044 $dbw = wfGetDB( DB_MASTER );
5045 $dbw->update(
5046 'user',
5047 [ 'user_editcount' => $count ],
5048 [
5049 'user_id' => $this->getId(),
5050 'user_editcount IS NULL OR user_editcount < ' . (int)$count
5051 ],
5052 __METHOD__
5053 );
5054
5055 return $count;
5056 }
5057
5058 /**
5059 * Get the description of a given right
5060 *
5061 * @since 1.29
5062 * @param string $right Right to query
5063 * @return string Localized description of the right
5064 */
5065 public static function getRightDescription( $right ) {
5066 $key = "right-$right";
5067 $msg = wfMessage( $key );
5068 return $msg->isDisabled() ? $right : $msg->text();
5069 }
5070
5071 /**
5072 * Get the name of a given grant
5073 *
5074 * @since 1.29
5075 * @param string $grant Grant to query
5076 * @return string Localized name of the grant
5077 */
5078 public static function getGrantName( $grant ) {
5079 $key = "grant-$grant";
5080 $msg = wfMessage( $key );
5081 return $msg->isDisabled() ? $grant : $msg->text();
5082 }
5083
5084 /**
5085 * Add a newuser log entry for this user.
5086 * Before 1.19 the return value was always true.
5087 *
5088 * @deprecated since 1.27, AuthManager handles logging
5089 * @param string|bool $action Account creation type.
5090 * - String, one of the following values:
5091 * - 'create' for an anonymous user creating an account for himself.
5092 * This will force the action's performer to be the created user itself,
5093 * no matter the value of $wgUser
5094 * - 'create2' for a logged in user creating an account for someone else
5095 * - 'byemail' when the created user will receive its password by e-mail
5096 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5097 * - Boolean means whether the account was created by e-mail (deprecated):
5098 * - true will be converted to 'byemail'
5099 * - false will be converted to 'create' if this object is the same as
5100 * $wgUser and to 'create2' otherwise
5101 * @param string $reason User supplied reason
5102 * @return bool true
5103 */
5104 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5105 return true; // disabled
5106 }
5107
5108 /**
5109 * Add an autocreate newuser log entry for this user
5110 * Used by things like CentralAuth and perhaps other authplugins.
5111 * Consider calling addNewUserLogEntry() directly instead.
5112 *
5113 * @deprecated since 1.27, AuthManager handles logging
5114 * @return bool
5115 */
5116 public function addNewUserLogEntryAutoCreate() {
5117 wfDeprecated( __METHOD__, '1.27' );
5118 $this->addNewUserLogEntry( 'autocreate' );
5119
5120 return true;
5121 }
5122
5123 /**
5124 * Load the user options either from cache, the database or an array
5125 *
5126 * @param array|null $data Rows for the current user out of the user_properties table
5127 */
5128 protected function loadOptions( $data = null ) {
5129 $this->load();
5130
5131 if ( $this->mOptionsLoaded ) {
5132 return;
5133 }
5134
5135 $this->mOptions = self::getDefaultOptions();
5136
5137 if ( !$this->getId() ) {
5138 // For unlogged-in users, load language/variant options from request.
5139 // There's no need to do it for logged-in users: they can set preferences,
5140 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5141 // so don't override user's choice (especially when the user chooses site default).
5142 $variant = MediaWikiServices::getInstance()->getContentLanguage()->getDefaultVariant();
5143 $this->mOptions['variant'] = $variant;
5144 $this->mOptions['language'] = $variant;
5145 $this->mOptionsLoaded = true;
5146 return;
5147 }
5148
5149 // Maybe load from the object
5150 if ( !is_null( $this->mOptionOverrides ) ) {
5151 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5152 foreach ( $this->mOptionOverrides as $key => $value ) {
5153 $this->mOptions[$key] = $value;
5154 }
5155 } else {
5156 if ( !is_array( $data ) ) {
5157 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5158 // Load from database
5159 $dbr = ( $this->queryFlagsUsed & self::READ_LATEST )
5160 ? wfGetDB( DB_MASTER )
5161 : wfGetDB( DB_REPLICA );
5162
5163 $res = $dbr->select(
5164 'user_properties',
5165 [ 'up_property', 'up_value' ],
5166 [ 'up_user' => $this->getId() ],
5167 __METHOD__
5168 );
5169
5170 $this->mOptionOverrides = [];
5171 $data = [];
5172 foreach ( $res as $row ) {
5173 // Convert '0' to 0. PHP's boolean conversion considers them both
5174 // false, but e.g. JavaScript considers the former as true.
5175 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5176 // and convert all values here.
5177 if ( $row->up_value === '0' ) {
5178 $row->up_value = 0;
5179 }
5180 $data[$row->up_property] = $row->up_value;
5181 }
5182 }
5183
5184 foreach ( $data as $property => $value ) {
5185 $this->mOptionOverrides[$property] = $value;
5186 $this->mOptions[$property] = $value;
5187 }
5188 }
5189
5190 // Replace deprecated language codes
5191 $this->mOptions['language'] = LanguageCode::replaceDeprecatedCodes(
5192 $this->mOptions['language']
5193 );
5194
5195 $this->mOptionsLoaded = true;
5196
5197 Hooks::run( 'UserLoadOptions', [ $this, &$this->mOptions ] );
5198 }
5199
5200 /**
5201 * Saves the non-default options for this user, as previously set e.g. via
5202 * setOption(), in the database's "user_properties" (preferences) table.
5203 * Usually used via saveSettings().
5204 */
5205 protected function saveOptions() {
5206 $this->loadOptions();
5207
5208 // Not using getOptions(), to keep hidden preferences in database
5209 $saveOptions = $this->mOptions;
5210
5211 // Allow hooks to abort, for instance to save to a global profile.
5212 // Reset options to default state before saving.
5213 if ( !Hooks::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5214 return;
5215 }
5216
5217 $userId = $this->getId();
5218
5219 $insert_rows = []; // all the new preference rows
5220 foreach ( $saveOptions as $key => $value ) {
5221 // Don't bother storing default values
5222 $defaultOption = self::getDefaultOption( $key );
5223 if ( ( $defaultOption === null && $value !== false && $value !== null )
5224 || $value != $defaultOption
5225 ) {
5226 $insert_rows[] = [
5227 'up_user' => $userId,
5228 'up_property' => $key,
5229 'up_value' => $value,
5230 ];
5231 }
5232 }
5233
5234 $dbw = wfGetDB( DB_MASTER );
5235
5236 $res = $dbw->select( 'user_properties',
5237 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__ );
5238
5239 // Find prior rows that need to be removed or updated. These rows will
5240 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5241 $keysDelete = [];
5242 foreach ( $res as $row ) {
5243 if ( !isset( $saveOptions[$row->up_property] )
5244 || strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
5245 ) {
5246 $keysDelete[] = $row->up_property;
5247 }
5248 }
5249
5250 if ( count( $keysDelete ) ) {
5251 // Do the DELETE by PRIMARY KEY for prior rows.
5252 // In the past a very large portion of calls to this function are for setting
5253 // 'rememberpassword' for new accounts (a preference that has since been removed).
5254 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5255 // caused gap locks on [max user ID,+infinity) which caused high contention since
5256 // updates would pile up on each other as they are for higher (newer) user IDs.
5257 // It might not be necessary these days, but it shouldn't hurt either.
5258 $dbw->delete( 'user_properties',
5259 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__ );
5260 }
5261 // Insert the new preference rows
5262 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, [ 'IGNORE' ] );
5263 }
5264
5265 /**
5266 * Return the list of user fields that should be selected to create
5267 * a new user object.
5268 * @deprecated since 1.31, use self::getQueryInfo() instead.
5269 * @return array
5270 */
5271 public static function selectFields() {
5272 wfDeprecated( __METHOD__, '1.31' );
5273 return [
5274 'user_id',
5275 'user_name',
5276 'user_real_name',
5277 'user_email',
5278 'user_touched',
5279 'user_token',
5280 'user_email_authenticated',
5281 'user_email_token',
5282 'user_email_token_expires',
5283 'user_registration',
5284 'user_editcount',
5285 ];
5286 }
5287
5288 /**
5289 * Return the tables, fields, and join conditions to be selected to create
5290 * a new user object.
5291 * @since 1.31
5292 * @return array With three keys:
5293 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
5294 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
5295 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
5296 */
5297 public static function getQueryInfo() {
5298 global $wgActorTableSchemaMigrationStage;
5299
5300 $ret = [
5301 'tables' => [ 'user' ],
5302 'fields' => [
5303 'user_id',
5304 'user_name',
5305 'user_real_name',
5306 'user_email',
5307 'user_touched',
5308 'user_token',
5309 'user_email_authenticated',
5310 'user_email_token',
5311 'user_email_token_expires',
5312 'user_registration',
5313 'user_editcount',
5314 ],
5315 'joins' => [],
5316 ];
5317
5318 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
5319 // but it does little harm and might be needed for write callers loading a User.
5320 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW ) {
5321 $ret['tables']['user_actor'] = 'actor';
5322 $ret['fields'][] = 'user_actor.actor_id';
5323 $ret['joins']['user_actor'] = [
5324 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW ) ? 'JOIN' : 'LEFT JOIN',
5325 [ 'user_actor.actor_user = user_id' ]
5326 ];
5327 }
5328
5329 return $ret;
5330 }
5331
5332 /**
5333 * Factory function for fatal permission-denied errors
5334 *
5335 * @since 1.22
5336 * @param string $permission User right required
5337 * @return Status
5338 */
5339 static function newFatalPermissionDeniedStatus( $permission ) {
5340 global $wgLang;
5341
5342 $groups = [];
5343 foreach ( MediaWikiServices::getInstance()
5344 ->getPermissionManager()
5345 ->getGroupsWithPermission( $permission ) as $group ) {
5346 $groups[] = UserGroupMembership::getLink( $group, RequestContext::getMain(), 'wiki' );
5347 }
5348
5349 if ( $groups ) {
5350 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5351 }
5352
5353 return Status::newFatal( 'badaccess-group0' );
5354 }
5355
5356 /**
5357 * Get a new instance of this user that was loaded from the master via a locking read
5358 *
5359 * Use this instead of the main context User when updating that user. This avoids races
5360 * where that user was loaded from a replica DB or even the master but without proper locks.
5361 *
5362 * @return User|null Returns null if the user was not found in the DB
5363 * @since 1.27
5364 */
5365 public function getInstanceForUpdate() {
5366 if ( !$this->getId() ) {
5367 return null; // anon
5368 }
5369
5370 $user = self::newFromId( $this->getId() );
5371 if ( !$user->loadFromId( self::READ_EXCLUSIVE ) ) {
5372 return null;
5373 }
5374
5375 return $user;
5376 }
5377
5378 /**
5379 * Checks if two user objects point to the same user.
5380 *
5381 * @since 1.25 ; takes a UserIdentity instead of a User since 1.32
5382 * @param UserIdentity $user
5383 * @return bool
5384 */
5385 public function equals( UserIdentity $user ) {
5386 // XXX it's not clear whether central ID providers are supposed to obey this
5387 return $this->getName() === $user->getName();
5388 }
5389
5390 /**
5391 * Checks if usertalk is allowed
5392 *
5393 * @return bool
5394 */
5395 public function isAllowUsertalk() {
5396 return $this->mAllowUsertalk;
5397 }
5398
5399 }