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