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