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