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