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