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