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