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