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