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