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