SECURITY: Make 'newbie' limit in $wgRateLimits really override 'user' limit
[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 Wikimedia\IPSet;
31 use Wikimedia\ScopedCallback;
32 use Wikimedia\Rdbms\Database;
33 use Wikimedia\Rdbms\DBExpectedError;
34 use Wikimedia\Rdbms\IDatabase;
35
36 /**
37 * The User object encapsulates all of the user-specific settings (user_id,
38 * name, rights, email address, options, last login time). Client
39 * classes use the getXXX() functions to access these fields. These functions
40 * do all the work of determining whether the user is logged in,
41 * whether the requested option can be satisfied from cookies or
42 * whether a database query is needed. Most of the settings needed
43 * for rendering normal pages are set in the cookie to minimize use
44 * of the database.
45 */
46 class User implements IDBAccessObject, UserIdentity {
47 /**
48 * @const int Number of characters in user_token field.
49 */
50 const TOKEN_LENGTH = 32;
51
52 /**
53 * @const string An invalid value for user_token
54 */
55 const INVALID_TOKEN = '*** INVALID ***';
56
57 /**
58 * Global constant made accessible as class constants so that autoloader
59 * magic can be used.
60 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
61 */
62 const EDIT_TOKEN_SUFFIX = Token::SUFFIX;
63
64 /**
65 * @const int Serialized record version.
66 */
67 const VERSION = 12;
68
69 /**
70 * Exclude user options that are set to their default value.
71 * @since 1.25
72 */
73 const GETOPTIONS_EXCLUDE_DEFAULTS = 1;
74
75 /**
76 * @since 1.27
77 */
78 const CHECK_USER_RIGHTS = true;
79
80 /**
81 * @since 1.27
82 */
83 const IGNORE_USER_RIGHTS = false;
84
85 /**
86 * Array of Strings List of member variables which are saved to the
87 * shared cache (memcached). Any operation which changes the
88 * corresponding database fields must call a cache-clearing function.
89 * @showinitializer
90 */
91 protected static $mCacheVars = [
92 // user table
93 'mId',
94 'mName',
95 'mRealName',
96 'mEmail',
97 'mTouched',
98 'mToken',
99 'mEmailAuthenticated',
100 'mEmailToken',
101 'mEmailTokenExpires',
102 'mRegistration',
103 'mEditCount',
104 // user_groups table
105 'mGroupMemberships',
106 // user_properties table
107 'mOptionOverrides',
108 // actor table
109 'mActorId',
110 ];
111
112 /**
113 * Array of Strings Core rights.
114 * Each of these should have a corresponding message of the form
115 * "right-$right".
116 * @showinitializer
117 */
118 protected static $mCoreRights = [
119 'apihighlimits',
120 'applychangetags',
121 'autoconfirmed',
122 'autocreateaccount',
123 'autopatrol',
124 'bigdelete',
125 'block',
126 'blockemail',
127 'bot',
128 'browsearchive',
129 'changetags',
130 'createaccount',
131 'createpage',
132 'createtalk',
133 'delete',
134 'deletechangetags',
135 'deletedhistory',
136 'deletedtext',
137 'deletelogentry',
138 'deleterevision',
139 'edit',
140 'editcontentmodel',
141 'editinterface',
142 'editprotected',
143 'editmyoptions',
144 'editmyprivateinfo',
145 'editmyusercss',
146 'editmyuserjson',
147 'editmyuserjs',
148 'editmywatchlist',
149 'editsemiprotected',
150 'editsitecss',
151 'editsitejson',
152 'editsitejs',
153 'editusercss',
154 'edituserjson',
155 'edituserjs',
156 'hideuser',
157 'import',
158 'importupload',
159 'ipblock-exempt',
160 'managechangetags',
161 'markbotedits',
162 'mergehistory',
163 'minoredit',
164 'move',
165 'movefile',
166 'move-categorypages',
167 'move-rootuserpages',
168 'move-subpages',
169 'nominornewtalk',
170 'noratelimit',
171 'override-export-depth',
172 'pagelang',
173 'patrol',
174 'patrolmarks',
175 'protect',
176 'purge',
177 'read',
178 'reupload',
179 'reupload-own',
180 'reupload-shared',
181 'rollback',
182 'sendemail',
183 'siteadmin',
184 'suppressionlog',
185 'suppressredirect',
186 'suppressrevision',
187 'unblockself',
188 'undelete',
189 'unwatchedpages',
190 'upload',
191 'upload_by_url',
192 'userrights',
193 'userrights-interwiki',
194 'viewmyprivateinfo',
195 'viewmywatchlist',
196 'viewsuppressed',
197 'writeapi',
198 ];
199
200 /**
201 * String Cached results of getAllRights()
202 */
203 protected static $mAllRights = false;
204
205 /** Cache variables */
206 // @{
207 /** @var int */
208 public $mId;
209 /** @var string */
210 public $mName;
211 /** @var int|null */
212 protected $mActorId;
213 /** @var string */
214 public $mRealName;
215
216 /** @var string */
217 public $mEmail;
218 /** @var string TS_MW timestamp from the DB */
219 public $mTouched;
220 /** @var string TS_MW timestamp from cache */
221 protected $mQuickTouched;
222 /** @var string */
223 protected $mToken;
224 /** @var string */
225 public $mEmailAuthenticated;
226 /** @var string */
227 protected $mEmailToken;
228 /** @var string */
229 protected $mEmailTokenExpires;
230 /** @var string */
231 protected $mRegistration;
232 /** @var int */
233 protected $mEditCount;
234 /** @var UserGroupMembership[] Associative array of (group name => UserGroupMembership object) */
235 protected $mGroupMemberships;
236 /** @var array */
237 protected $mOptionOverrides;
238 // @}
239
240 /**
241 * Bool Whether the cache variables have been loaded.
242 */
243 // @{
244 public $mOptionsLoaded;
245
246 /**
247 * Array with already loaded items or true if all items have been loaded.
248 */
249 protected $mLoadedItems = [];
250 // @}
251
252 /**
253 * String Initialization data source if mLoadedItems!==true. May be one of:
254 * - 'defaults' anonymous user initialised from class defaults
255 * - 'name' initialise from mName
256 * - 'id' initialise from mId
257 * - 'actor' initialise from mActorId
258 * - 'session' log in from session if possible
259 *
260 * Use the User::newFrom*() family of functions to set this.
261 */
262 public $mFrom;
263
264 /**
265 * Lazy-initialized variables, invalidated with clearInstanceCache
266 */
267 protected $mNewtalk;
268 /** @var string */
269 protected $mDatePreference;
270 /** @var string */
271 public $mBlockedby;
272 /** @var string */
273 protected $mHash;
274 /** @var array */
275 public $mRights;
276 /** @var string */
277 protected $mBlockreason;
278 /** @var array */
279 protected $mEffectiveGroups;
280 /** @var array */
281 protected $mImplicitGroups;
282 /** @var array */
283 protected $mFormerGroups;
284 /** @var Block */
285 protected $mGlobalBlock;
286 /** @var bool */
287 protected $mLocked;
288 /** @var bool */
289 public $mHideName;
290 /** @var array */
291 public $mOptions;
292
293 /** @var WebRequest */
294 private $mRequest;
295
296 /** @var Block */
297 public $mBlock;
298
299 /** @var bool */
300 protected $mAllowUsertalk;
301
302 /** @var Block */
303 private $mBlockedFromCreateAccount = false;
304
305 /** @var int User::READ_* constant bitfield used to load data */
306 protected $queryFlagsUsed = self::READ_NORMAL;
307
308 public static $idCacheByName = [];
309
310 /**
311 * Lightweight constructor for an anonymous user.
312 * Use the User::newFrom* factory functions for other kinds of users.
313 *
314 * @see newFromName()
315 * @see newFromId()
316 * @see newFromActorId()
317 * @see newFromConfirmationCode()
318 * @see newFromSession()
319 * @see newFromRow()
320 */
321 public function __construct() {
322 $this->clearInstanceCache( 'defaults' );
323 }
324
325 /**
326 * @return string
327 */
328 public function __toString() {
329 return (string)$this->getName();
330 }
331
332 /**
333 * Test if it's safe to load this User object.
334 *
335 * You should typically check this before using $wgUser or
336 * RequestContext::getUser in a method that might be called before the
337 * system has been fully initialized. If the object is unsafe, you should
338 * use an anonymous user:
339 * \code
340 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
341 * \endcode
342 *
343 * @since 1.27
344 * @return bool
345 */
346 public function isSafeToLoad() {
347 global $wgFullyInitialised;
348
349 // The user is safe to load if:
350 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
351 // * mLoadedItems === true (already loaded)
352 // * mFrom !== 'session' (sessions not involved at all)
353
354 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
355 $this->mLoadedItems === true || $this->mFrom !== 'session';
356 }
357
358 /**
359 * Load the user table data for this object from the source given by mFrom.
360 *
361 * @param int $flags User::READ_* constant bitfield
362 */
363 public function load( $flags = self::READ_NORMAL ) {
364 global $wgFullyInitialised;
365
366 if ( $this->mLoadedItems === true ) {
367 return;
368 }
369
370 // Set it now to avoid infinite recursion in accessors
371 $oldLoadedItems = $this->mLoadedItems;
372 $this->mLoadedItems = true;
373 $this->queryFlagsUsed = $flags;
374
375 // If this is called too early, things are likely to break.
376 if ( !$wgFullyInitialised && $this->mFrom === 'session' ) {
377 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
378 ->warning( 'User::loadFromSession called before the end of Setup.php', [
379 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
380 ] );
381 $this->loadDefaults();
382 $this->mLoadedItems = $oldLoadedItems;
383 return;
384 }
385
386 switch ( $this->mFrom ) {
387 case 'defaults':
388 $this->loadDefaults();
389 break;
390 case 'name':
391 // Make sure this thread sees its own changes
392 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
393 if ( $lb->hasOrMadeRecentMasterChanges() ) {
394 $flags |= self::READ_LATEST;
395 $this->queryFlagsUsed = $flags;
396 }
397
398 $this->mId = self::idFromName( $this->mName, $flags );
399 if ( !$this->mId ) {
400 // Nonexistent user placeholder object
401 $this->loadDefaults( $this->mName );
402 } else {
403 $this->loadFromId( $flags );
404 }
405 break;
406 case 'id':
407 // Make sure this thread sees its own changes, if the ID isn't 0
408 if ( $this->mId != 0 ) {
409 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
410 if ( $lb->hasOrMadeRecentMasterChanges() ) {
411 $flags |= self::READ_LATEST;
412 $this->queryFlagsUsed = $flags;
413 }
414 }
415
416 $this->loadFromId( $flags );
417 break;
418 case 'actor':
419 // Make sure this thread sees its own changes
420 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
421 if ( $lb->hasOrMadeRecentMasterChanges() ) {
422 $flags |= self::READ_LATEST;
423 $this->queryFlagsUsed = $flags;
424 }
425
426 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
427 $row = wfGetDB( $index )->selectRow(
428 'actor',
429 [ 'actor_user', 'actor_name' ],
430 [ 'actor_id' => $this->mActorId ],
431 __METHOD__,
432 $options
433 );
434
435 if ( !$row ) {
436 // Ugh.
437 $this->loadDefaults();
438 } elseif ( $row->actor_user ) {
439 $this->mId = $row->actor_user;
440 $this->loadFromId( $flags );
441 } else {
442 $this->loadDefaults( $row->actor_name );
443 }
444 break;
445 case 'session':
446 if ( !$this->loadFromSession() ) {
447 // Loading from session failed. Load defaults.
448 $this->loadDefaults();
449 }
450 Hooks::run( 'UserLoadAfterLoadFromSession', [ $this ] );
451 break;
452 default:
453 throw new UnexpectedValueException(
454 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
455 }
456 }
457
458 /**
459 * Load user table data, given mId has already been set.
460 * @param int $flags User::READ_* constant bitfield
461 * @return bool False if the ID does not exist, true otherwise
462 */
463 public function loadFromId( $flags = self::READ_NORMAL ) {
464 if ( $this->mId == 0 ) {
465 // Anonymous users are not in the database (don't need cache)
466 $this->loadDefaults();
467 return false;
468 }
469
470 // Try cache (unless this needs data from the master DB).
471 // NOTE: if this thread called saveSettings(), the cache was cleared.
472 $latest = DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST );
473 if ( $latest ) {
474 if ( !$this->loadFromDatabase( $flags ) ) {
475 // Can't load from ID
476 return false;
477 }
478 } else {
479 $this->loadFromCache();
480 }
481
482 $this->mLoadedItems = true;
483 $this->queryFlagsUsed = $flags;
484
485 return true;
486 }
487
488 /**
489 * @since 1.27
490 * @param string $wikiId
491 * @param int $userId
492 */
493 public static function purge( $wikiId, $userId ) {
494 $cache = ObjectCache::getMainWANInstance();
495 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
496 $cache->delete( $key );
497 }
498
499 /**
500 * @since 1.27
501 * @param WANObjectCache $cache
502 * @return string
503 */
504 protected function getCacheKey( WANObjectCache $cache ) {
505 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId );
506 }
507
508 /**
509 * @param WANObjectCache $cache
510 * @return string[]
511 * @since 1.28
512 */
513 public function getMutableCacheKeys( WANObjectCache $cache ) {
514 $id = $this->getId();
515
516 return $id ? [ $this->getCacheKey( $cache ) ] : [];
517 }
518
519 /**
520 * Load user data from shared cache, given mId has already been set.
521 *
522 * @return bool True
523 * @since 1.25
524 */
525 protected function loadFromCache() {
526 $cache = ObjectCache::getMainWANInstance();
527 $data = $cache->getWithSetCallback(
528 $this->getCacheKey( $cache ),
529 $cache::TTL_HOUR,
530 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
531 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
532 wfDebug( "User: cache miss for user {$this->mId}\n" );
533
534 $this->loadFromDatabase( self::READ_NORMAL );
535 $this->loadGroups();
536 $this->loadOptions();
537
538 $data = [];
539 foreach ( self::$mCacheVars as $name ) {
540 $data[$name] = $this->$name;
541 }
542
543 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX, $this->mTouched ), $ttl );
544
545 // if a user group membership is about to expire, the cache needs to
546 // expire at that time (T163691)
547 foreach ( $this->mGroupMemberships as $ugm ) {
548 if ( $ugm->getExpiry() ) {
549 $secondsUntilExpiry = wfTimestamp( TS_UNIX, $ugm->getExpiry() ) - time();
550 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
551 $ttl = $secondsUntilExpiry;
552 }
553 }
554 }
555
556 return $data;
557 },
558 [ 'pcTTL' => $cache::TTL_PROC_LONG, 'version' => self::VERSION ]
559 );
560
561 // Restore from cache
562 foreach ( self::$mCacheVars as $name ) {
563 $this->$name = $data[$name];
564 }
565
566 return true;
567 }
568
569 /** @name newFrom*() static factory methods */
570 // @{
571
572 /**
573 * Static factory method for creation from username.
574 *
575 * This is slightly less efficient than newFromId(), so use newFromId() if
576 * you have both an ID and a name handy.
577 *
578 * @param string $name Username, validated by Title::newFromText()
579 * @param string|bool $validate Validate username. Takes the same parameters as
580 * User::getCanonicalName(), except that true is accepted as an alias
581 * for 'valid', for BC.
582 *
583 * @return User|bool User object, or false if the username is invalid
584 * (e.g. if it contains illegal characters or is an IP address). If the
585 * username is not present in the database, the result will be a user object
586 * with a name, zero user ID and default settings.
587 */
588 public static function newFromName( $name, $validate = 'valid' ) {
589 if ( $validate === true ) {
590 $validate = 'valid';
591 }
592 $name = self::getCanonicalName( $name, $validate );
593 if ( $name === false ) {
594 return false;
595 } else {
596 // Create unloaded user object
597 $u = new User;
598 $u->mName = $name;
599 $u->mFrom = 'name';
600 $u->setItemLoaded( 'name' );
601 return $u;
602 }
603 }
604
605 /**
606 * Static factory method for creation from a given user ID.
607 *
608 * @param int $id Valid user ID
609 * @return User The corresponding User object
610 */
611 public static function newFromId( $id ) {
612 $u = new User;
613 $u->mId = $id;
614 $u->mFrom = 'id';
615 $u->setItemLoaded( 'id' );
616 return $u;
617 }
618
619 /**
620 * Static factory method for creation from a given actor ID.
621 *
622 * @since 1.31
623 * @param int $id Valid actor ID
624 * @return User The corresponding User object
625 */
626 public static function newFromActorId( $id ) {
627 global $wgActorTableSchemaMigrationStage;
628
629 if ( $wgActorTableSchemaMigrationStage <= MIGRATION_OLD ) {
630 throw new BadMethodCallException(
631 'Cannot use ' . __METHOD__ . ' when $wgActorTableSchemaMigrationStage is MIGRATION_OLD'
632 );
633 }
634
635 $u = new User;
636 $u->mActorId = $id;
637 $u->mFrom = 'actor';
638 $u->setItemLoaded( 'actor' );
639 return $u;
640 }
641
642 /**
643 * Returns a User object corresponding to the given UserIdentity.
644 *
645 * @since 1.32
646 *
647 * @param UserIdentity $identity
648 *
649 * @return User
650 */
651 public static function newFromIdentity( UserIdentity $identity ) {
652 if ( $identity instanceof User ) {
653 return $identity;
654 }
655
656 return self::newFromAnyId(
657 $identity->getId() === 0 ? null : $identity->getId(),
658 $identity->getName() === '' ? null : $identity->getName(),
659 $identity->getActorId() === 0 ? null : $identity->getActorId()
660 );
661 }
662
663 /**
664 * Static factory method for creation from an ID, name, and/or actor ID
665 *
666 * This does not check that the ID, name, and actor ID all correspond to
667 * the same user.
668 *
669 * @since 1.31
670 * @param int|null $userId User ID, if known
671 * @param string|null $userName User name, if known
672 * @param int|null $actorId Actor ID, if known
673 * @return User
674 */
675 public static function newFromAnyId( $userId, $userName, $actorId ) {
676 global $wgActorTableSchemaMigrationStage;
677
678 $user = new User;
679 $user->mFrom = 'defaults';
680
681 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD && $actorId !== null ) {
682 $user->mActorId = (int)$actorId;
683 if ( $user->mActorId !== 0 ) {
684 $user->mFrom = 'actor';
685 }
686 $user->setItemLoaded( 'actor' );
687 }
688
689 if ( $userName !== null && $userName !== '' ) {
690 $user->mName = $userName;
691 $user->mFrom = 'name';
692 $user->setItemLoaded( 'name' );
693 }
694
695 if ( $userId !== null ) {
696 $user->mId = (int)$userId;
697 if ( $user->mId !== 0 ) {
698 $user->mFrom = 'id';
699 }
700 $user->setItemLoaded( 'id' );
701 }
702
703 if ( $user->mFrom === 'defaults' ) {
704 throw new InvalidArgumentException(
705 'Cannot create a user with no name, no ID, and no actor ID'
706 );
707 }
708
709 return $user;
710 }
711
712 /**
713 * Factory method to fetch whichever user has a given email confirmation code.
714 * This code is generated when an account is created or its e-mail address
715 * has changed.
716 *
717 * If the code is invalid or has expired, returns NULL.
718 *
719 * @param string $code Confirmation code
720 * @param int $flags User::READ_* bitfield
721 * @return User|null
722 */
723 public static function newFromConfirmationCode( $code, $flags = 0 ) {
724 $db = ( $flags & self::READ_LATEST ) == self::READ_LATEST
725 ? wfGetDB( DB_MASTER )
726 : wfGetDB( DB_REPLICA );
727
728 $id = $db->selectField(
729 'user',
730 'user_id',
731 [
732 'user_email_token' => md5( $code ),
733 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
734 ]
735 );
736
737 return $id ? self::newFromId( $id ) : null;
738 }
739
740 /**
741 * Create a new user object using data from session. If the login
742 * credentials are invalid, the result is an anonymous user.
743 *
744 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
745 * @return User
746 */
747 public static function newFromSession( WebRequest $request = null ) {
748 $user = new User;
749 $user->mFrom = 'session';
750 $user->mRequest = $request;
751 return $user;
752 }
753
754 /**
755 * Create a new user object from a user row.
756 * The row should have the following fields from the user table in it:
757 * - either user_name or user_id to load further data if needed (or both)
758 * - user_real_name
759 * - all other fields (email, etc.)
760 * It is useless to provide the remaining fields if either user_id,
761 * user_name and user_real_name are not provided because the whole row
762 * will be loaded once more from the database when accessing them.
763 *
764 * @param stdClass $row A row from the user table
765 * @param array|null $data Further data to load into the object
766 * (see User::loadFromRow for valid keys)
767 * @return User
768 */
769 public static function newFromRow( $row, $data = null ) {
770 $user = new User;
771 $user->loadFromRow( $row, $data );
772 return $user;
773 }
774
775 /**
776 * Static factory method for creation of a "system" user from username.
777 *
778 * A "system" user is an account that's used to attribute logged actions
779 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
780 * might include the 'Maintenance script' or 'Conversion script' accounts
781 * used by various scripts in the maintenance/ directory or accounts such
782 * as 'MediaWiki message delivery' used by the MassMessage extension.
783 *
784 * This can optionally create the user if it doesn't exist, and "steal" the
785 * account if it does exist.
786 *
787 * "Stealing" an existing user is intended to make it impossible for normal
788 * authentication processes to use the account, effectively disabling the
789 * account for normal use:
790 * - Email is invalidated, to prevent account recovery by emailing a
791 * temporary password and to disassociate the account from the existing
792 * human.
793 * - The token is set to a magic invalid value, to kill existing sessions
794 * and to prevent $this->setToken() calls from resetting the token to a
795 * valid value.
796 * - SessionManager is instructed to prevent new sessions for the user, to
797 * do things like deauthorizing OAuth consumers.
798 * - AuthManager is instructed to revoke access, to invalidate or remove
799 * passwords and other credentials.
800 *
801 * @param string $name Username
802 * @param array $options Options are:
803 * - validate: As for User::getCanonicalName(), default 'valid'
804 * - create: Whether to create the user if it doesn't already exist, default true
805 * - steal: Whether to "disable" the account for normal use if it already
806 * exists, default false
807 * @return User|null
808 * @since 1.27
809 */
810 public static function newSystemUser( $name, $options = [] ) {
811 $options += [
812 'validate' => 'valid',
813 'create' => true,
814 'steal' => false,
815 ];
816
817 $name = self::getCanonicalName( $name, $options['validate'] );
818 if ( $name === false ) {
819 return null;
820 }
821
822 $dbr = wfGetDB( DB_REPLICA );
823 $userQuery = self::getQueryInfo();
824 $row = $dbr->selectRow(
825 $userQuery['tables'],
826 $userQuery['fields'],
827 [ 'user_name' => $name ],
828 __METHOD__,
829 [],
830 $userQuery['joins']
831 );
832 if ( !$row ) {
833 // Try the master database...
834 $dbw = wfGetDB( DB_MASTER );
835 $row = $dbw->selectRow(
836 $userQuery['tables'],
837 $userQuery['fields'],
838 [ 'user_name' => $name ],
839 __METHOD__,
840 [],
841 $userQuery['joins']
842 );
843 }
844
845 if ( !$row ) {
846 // No user. Create it?
847 return $options['create']
848 ? self::createNew( $name, [ 'token' => self::INVALID_TOKEN ] )
849 : null;
850 }
851
852 $user = self::newFromRow( $row );
853
854 // A user is considered to exist as a non-system user if it can
855 // authenticate, or has an email set, or has a non-invalid token.
856 if ( $user->mEmail || $user->mToken !== self::INVALID_TOKEN ||
857 AuthManager::singleton()->userCanAuthenticate( $name )
858 ) {
859 // User exists. Steal it?
860 if ( !$options['steal'] ) {
861 return null;
862 }
863
864 AuthManager::singleton()->revokeAccessForUser( $name );
865
866 $user->invalidateEmail();
867 $user->mToken = self::INVALID_TOKEN;
868 $user->saveSettings();
869 SessionManager::singleton()->preventSessionsForUser( $user->getName() );
870 }
871
872 return $user;
873 }
874
875 // @}
876
877 /**
878 * Get the username corresponding to a given user ID
879 * @param int $id User ID
880 * @return string|bool The corresponding username
881 */
882 public static function whoIs( $id ) {
883 return UserCache::singleton()->getProp( $id, 'name' );
884 }
885
886 /**
887 * Get the real name of a user given their user ID
888 *
889 * @param int $id User ID
890 * @return string|bool The corresponding user's real name
891 */
892 public static function whoIsReal( $id ) {
893 return UserCache::singleton()->getProp( $id, 'real_name' );
894 }
895
896 /**
897 * Get database id given a user name
898 * @param string $name Username
899 * @param int $flags User::READ_* constant bitfield
900 * @return int|null The corresponding user's ID, or null if user is nonexistent
901 */
902 public static function idFromName( $name, $flags = self::READ_NORMAL ) {
903 $nt = Title::makeTitleSafe( NS_USER, $name );
904 if ( is_null( $nt ) ) {
905 // Illegal name
906 return null;
907 }
908
909 if ( !( $flags & self::READ_LATEST ) && array_key_exists( $name, self::$idCacheByName ) ) {
910 return self::$idCacheByName[$name];
911 }
912
913 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
914 $db = wfGetDB( $index );
915
916 $s = $db->selectRow(
917 'user',
918 [ 'user_id' ],
919 [ 'user_name' => $nt->getText() ],
920 __METHOD__,
921 $options
922 );
923
924 if ( $s === false ) {
925 $result = null;
926 } else {
927 $result = $s->user_id;
928 }
929
930 self::$idCacheByName[$name] = $result;
931
932 if ( count( self::$idCacheByName ) > 1000 ) {
933 self::$idCacheByName = [];
934 }
935
936 return $result;
937 }
938
939 /**
940 * Reset the cache used in idFromName(). For use in tests.
941 */
942 public static function resetIdByNameCache() {
943 self::$idCacheByName = [];
944 }
945
946 /**
947 * Does the string match an anonymous IP address?
948 *
949 * This function exists for username validation, in order to reject
950 * usernames which are similar in form to IP addresses. Strings such
951 * as 300.300.300.300 will return true because it looks like an IP
952 * address, despite not being strictly valid.
953 *
954 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
955 * address because the usemod software would "cloak" anonymous IP
956 * addresses like this, if we allowed accounts like this to be created
957 * new users could get the old edits of these anonymous users.
958 *
959 * @param string $name Name to match
960 * @return bool
961 */
962 public static function isIP( $name ) {
963 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
964 || IP::isIPv6( $name );
965 }
966
967 /**
968 * Is the user an IP range?
969 *
970 * @since 1.30
971 * @return bool
972 */
973 public function isIPRange() {
974 return IP::isValidRange( $this->mName );
975 }
976
977 /**
978 * Is the input a valid username?
979 *
980 * Checks if the input is a valid username, we don't want an empty string,
981 * an IP address, anything that contains slashes (would mess up subpages),
982 * is longer than the maximum allowed username size or doesn't begin with
983 * a capital letter.
984 *
985 * @param string $name Name to match
986 * @return bool
987 */
988 public static function isValidUserName( $name ) {
989 global $wgMaxNameChars;
990
991 if ( $name == ''
992 || self::isIP( $name )
993 || strpos( $name, '/' ) !== false
994 || strlen( $name ) > $wgMaxNameChars
995 || $name != MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $name )
996 ) {
997 return false;
998 }
999
1000 // Ensure that the name can't be misresolved as a different title,
1001 // such as with extra namespace keys at the start.
1002 $parsed = Title::newFromText( $name );
1003 if ( is_null( $parsed )
1004 || $parsed->getNamespace()
1005 || strcmp( $name, $parsed->getPrefixedText() ) ) {
1006 return false;
1007 }
1008
1009 // Check an additional blacklist of troublemaker characters.
1010 // Should these be merged into the title char list?
1011 $unicodeBlacklist = '/[' .
1012 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
1013 '\x{00a0}' . # non-breaking space
1014 '\x{2000}-\x{200f}' . # various whitespace
1015 '\x{2028}-\x{202f}' . # breaks and control chars
1016 '\x{3000}' . # ideographic space
1017 '\x{e000}-\x{f8ff}' . # private use
1018 ']/u';
1019 if ( preg_match( $unicodeBlacklist, $name ) ) {
1020 return false;
1021 }
1022
1023 return true;
1024 }
1025
1026 /**
1027 * Usernames which fail to pass this function will be blocked
1028 * from user login and new account registrations, but may be used
1029 * internally by batch processes.
1030 *
1031 * If an account already exists in this form, login will be blocked
1032 * by a failure to pass this function.
1033 *
1034 * @param string $name Name to match
1035 * @return bool
1036 */
1037 public static function isUsableName( $name ) {
1038 global $wgReservedUsernames;
1039 // Must be a valid username, obviously ;)
1040 if ( !self::isValidUserName( $name ) ) {
1041 return false;
1042 }
1043
1044 static $reservedUsernames = false;
1045 if ( !$reservedUsernames ) {
1046 $reservedUsernames = $wgReservedUsernames;
1047 Hooks::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
1048 }
1049
1050 // Certain names may be reserved for batch processes.
1051 foreach ( $reservedUsernames as $reserved ) {
1052 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
1053 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
1054 }
1055 if ( $reserved == $name ) {
1056 return false;
1057 }
1058 }
1059 return true;
1060 }
1061
1062 /**
1063 * Return the users who are members of the given group(s). In case of multiple groups,
1064 * users who are members of at least one of them are returned.
1065 *
1066 * @param string|array $groups A single group name or an array of group names
1067 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
1068 * records; larger values are ignored.
1069 * @param int|null $after ID the user to start after
1070 * @return UserArrayFromResult
1071 */
1072 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
1073 if ( $groups === [] ) {
1074 return UserArrayFromResult::newFromIDs( [] );
1075 }
1076
1077 $groups = array_unique( (array)$groups );
1078 $limit = min( 5000, $limit );
1079
1080 $conds = [ 'ug_group' => $groups ];
1081 if ( $after !== null ) {
1082 $conds[] = 'ug_user > ' . (int)$after;
1083 }
1084
1085 $dbr = wfGetDB( DB_REPLICA );
1086 $ids = $dbr->selectFieldValues(
1087 'user_groups',
1088 'ug_user',
1089 $conds,
1090 __METHOD__,
1091 [
1092 'DISTINCT' => true,
1093 'ORDER BY' => 'ug_user',
1094 'LIMIT' => $limit,
1095 ]
1096 ) ?: [];
1097 return UserArray::newFromIDs( $ids );
1098 }
1099
1100 /**
1101 * Usernames which fail to pass this function will be blocked
1102 * from new account registrations, but may be used internally
1103 * either by batch processes or by user accounts which have
1104 * already been created.
1105 *
1106 * Additional blacklisting may be added here rather than in
1107 * isValidUserName() to avoid disrupting existing accounts.
1108 *
1109 * @param string $name String to match
1110 * @return bool
1111 */
1112 public static function isCreatableName( $name ) {
1113 global $wgInvalidUsernameCharacters;
1114
1115 // Ensure that the username isn't longer than 235 bytes, so that
1116 // (at least for the builtin skins) user javascript and css files
1117 // will work. (T25080)
1118 if ( strlen( $name ) > 235 ) {
1119 wfDebugLog( 'username', __METHOD__ .
1120 ": '$name' invalid due to length" );
1121 return false;
1122 }
1123
1124 // Preg yells if you try to give it an empty string
1125 if ( $wgInvalidUsernameCharacters !== '' ) {
1126 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
1127 wfDebugLog( 'username', __METHOD__ .
1128 ": '$name' invalid due to wgInvalidUsernameCharacters" );
1129 return false;
1130 }
1131 }
1132
1133 return self::isUsableName( $name );
1134 }
1135
1136 /**
1137 * Is the input a valid password for this user?
1138 *
1139 * @param string $password Desired password
1140 * @return bool
1141 */
1142 public function isValidPassword( $password ) {
1143 // simple boolean wrapper for getPasswordValidity
1144 return $this->getPasswordValidity( $password ) === true;
1145 }
1146
1147 /**
1148 * Given unvalidated password input, return error message on failure.
1149 *
1150 * @param string $password Desired password
1151 * @return bool|string|array True on success, string or array of error message on failure
1152 */
1153 public function getPasswordValidity( $password ) {
1154 $result = $this->checkPasswordValidity( $password );
1155 if ( $result->isGood() ) {
1156 return true;
1157 } else {
1158 $messages = [];
1159 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
1160 $messages[] = $error['message'];
1161 }
1162 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
1163 $messages[] = $warning['message'];
1164 }
1165 if ( count( $messages ) === 1 ) {
1166 return $messages[0];
1167 }
1168 return $messages;
1169 }
1170 }
1171
1172 /**
1173 * Check if this is a valid password for this user
1174 *
1175 * Create a Status object based on the password's validity.
1176 * The Status should be set to fatal if the user should not
1177 * be allowed to log in, and should have any errors that
1178 * would block changing the password.
1179 *
1180 * If the return value of this is not OK, the password
1181 * should not be checked. If the return value is not Good,
1182 * the password can be checked, but the user should not be
1183 * able to set their password to this.
1184 *
1185 * @param string $password Desired password
1186 * @return Status
1187 * @since 1.23
1188 */
1189 public function checkPasswordValidity( $password ) {
1190 global $wgPasswordPolicy;
1191
1192 $upp = new UserPasswordPolicy(
1193 $wgPasswordPolicy['policies'],
1194 $wgPasswordPolicy['checks']
1195 );
1196
1197 $status = Status::newGood();
1198 $result = false; // init $result to false for the internal checks
1199
1200 if ( !Hooks::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1201 $status->error( $result );
1202 return $status;
1203 }
1204
1205 if ( $result === false ) {
1206 $status->merge( $upp->checkUserPassword( $this, $password ) );
1207 return $status;
1208 } elseif ( $result === true ) {
1209 return $status;
1210 } else {
1211 $status->error( $result );
1212 return $status; // the isValidPassword hook set a string $result and returned true
1213 }
1214 }
1215
1216 /**
1217 * Given unvalidated user input, return a canonical username, or false if
1218 * the username is invalid.
1219 * @param string $name User input
1220 * @param string|bool $validate Type of validation to use:
1221 * - false No validation
1222 * - 'valid' Valid for batch processes
1223 * - 'usable' Valid for batch processes and login
1224 * - 'creatable' Valid for batch processes, login and account creation
1225 *
1226 * @throws InvalidArgumentException
1227 * @return bool|string
1228 */
1229 public static function getCanonicalName( $name, $validate = 'valid' ) {
1230 // Force usernames to capital
1231 $name = MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $name );
1232
1233 # Reject names containing '#'; these will be cleaned up
1234 # with title normalisation, but then it's too late to
1235 # check elsewhere
1236 if ( strpos( $name, '#' ) !== false ) {
1237 return false;
1238 }
1239
1240 // Clean up name according to title rules,
1241 // but only when validation is requested (T14654)
1242 $t = ( $validate !== false ) ?
1243 Title::newFromText( $name, NS_USER ) : Title::makeTitle( NS_USER, $name );
1244 // Check for invalid titles
1245 if ( is_null( $t ) || $t->getNamespace() !== NS_USER || $t->isExternal() ) {
1246 return false;
1247 }
1248
1249 // Reject various classes of invalid names
1250 $name = AuthManager::callLegacyAuthPlugin(
1251 'getCanonicalName', [ $t->getText() ], $t->getText()
1252 );
1253
1254 switch ( $validate ) {
1255 case false:
1256 break;
1257 case 'valid':
1258 if ( !self::isValidUserName( $name ) ) {
1259 $name = false;
1260 }
1261 break;
1262 case 'usable':
1263 if ( !self::isUsableName( $name ) ) {
1264 $name = false;
1265 }
1266 break;
1267 case 'creatable':
1268 if ( !self::isCreatableName( $name ) ) {
1269 $name = false;
1270 }
1271 break;
1272 default:
1273 throw new InvalidArgumentException(
1274 'Invalid parameter value for $validate in ' . __METHOD__ );
1275 }
1276 return $name;
1277 }
1278
1279 /**
1280 * Return a random password.
1281 *
1282 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1283 * @return string New random password
1284 */
1285 public static function randomPassword() {
1286 global $wgMinimalPasswordLength;
1287 return PasswordFactory::generateRandomPasswordString( $wgMinimalPasswordLength );
1288 }
1289
1290 /**
1291 * Set cached properties to default.
1292 *
1293 * @note This no longer clears uncached lazy-initialised properties;
1294 * the constructor does that instead.
1295 *
1296 * @param string|bool $name
1297 */
1298 public function loadDefaults( $name = false ) {
1299 $this->mId = 0;
1300 $this->mName = $name;
1301 $this->mActorId = null;
1302 $this->mRealName = '';
1303 $this->mEmail = '';
1304 $this->mOptionOverrides = null;
1305 $this->mOptionsLoaded = false;
1306
1307 $loggedOut = $this->mRequest && !defined( 'MW_NO_SESSION' )
1308 ? $this->mRequest->getSession()->getLoggedOutTimestamp() : 0;
1309 if ( $loggedOut !== 0 ) {
1310 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
1311 } else {
1312 $this->mTouched = '1'; # Allow any pages to be cached
1313 }
1314
1315 $this->mToken = null; // Don't run cryptographic functions till we need a token
1316 $this->mEmailAuthenticated = null;
1317 $this->mEmailToken = '';
1318 $this->mEmailTokenExpires = null;
1319 $this->mRegistration = wfTimestamp( TS_MW );
1320 $this->mGroupMemberships = [];
1321
1322 Hooks::run( 'UserLoadDefaults', [ $this, $name ] );
1323 }
1324
1325 /**
1326 * Return whether an item has been loaded.
1327 *
1328 * @param string $item Item to check. Current possibilities:
1329 * - id
1330 * - name
1331 * - realname
1332 * @param string $all 'all' to check if the whole object has been loaded
1333 * or any other string to check if only the item is available (e.g.
1334 * for optimisation)
1335 * @return bool
1336 */
1337 public function isItemLoaded( $item, $all = 'all' ) {
1338 return ( $this->mLoadedItems === true && $all === 'all' ) ||
1339 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1340 }
1341
1342 /**
1343 * Set that an item has been loaded
1344 *
1345 * @param string $item
1346 */
1347 protected function setItemLoaded( $item ) {
1348 if ( is_array( $this->mLoadedItems ) ) {
1349 $this->mLoadedItems[$item] = true;
1350 }
1351 }
1352
1353 /**
1354 * Load user data from the session.
1355 *
1356 * @return bool True if the user is logged in, false otherwise.
1357 */
1358 private function loadFromSession() {
1359 // Deprecated hook
1360 $result = null;
1361 Hooks::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1362 if ( $result !== null ) {
1363 return $result;
1364 }
1365
1366 // MediaWiki\Session\Session already did the necessary authentication of the user
1367 // returned here, so just use it if applicable.
1368 $session = $this->getRequest()->getSession();
1369 $user = $session->getUser();
1370 if ( $user->isLoggedIn() ) {
1371 $this->loadFromUserObject( $user );
1372 if ( $user->isBlocked() ) {
1373 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1374 // every session load, because an autoblocked editor might not edit again from the same
1375 // IP address after being blocked.
1376 $this->trackBlockWithCookie();
1377 }
1378
1379 // Other code expects these to be set in the session, so set them.
1380 $session->set( 'wsUserID', $this->getId() );
1381 $session->set( 'wsUserName', $this->getName() );
1382 $session->set( 'wsToken', $this->getToken() );
1383
1384 return true;
1385 }
1386
1387 return false;
1388 }
1389
1390 /**
1391 * Set the 'BlockID' cookie depending on block type and user authentication status.
1392 */
1393 public function trackBlockWithCookie() {
1394 $block = $this->getBlock();
1395 if ( $block && $this->getRequest()->getCookie( 'BlockID' ) === null ) {
1396 $config = RequestContext::getMain()->getConfig();
1397 $shouldSetCookie = false;
1398
1399 if ( $this->isAnon() && $config->get( 'CookieSetOnIpBlock' ) ) {
1400 // If user is logged-out, set a cookie to track the Block
1401 $shouldSetCookie = in_array( $block->getType(), [
1402 Block::TYPE_IP, Block::TYPE_RANGE
1403 ] );
1404 if ( $shouldSetCookie ) {
1405 $block->setCookie( $this->getRequest()->response() );
1406
1407 // temporary measure the use of cookies on ip blocks
1408 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
1409 $stats->increment( 'block.ipblock.setCookie.success' );
1410 }
1411 } elseif ( $this->isLoggedIn() && $config->get( 'CookieSetOnAutoblock' ) ) {
1412 $shouldSetCookie = $block->getType() === Block::TYPE_USER && $block->isAutoblocking();
1413 if ( $shouldSetCookie ) {
1414 $block->setCookie( $this->getRequest()->response() );
1415 }
1416 }
1417 }
1418 }
1419
1420 /**
1421 * Load user and user_group data from the database.
1422 * $this->mId must be set, this is how the user is identified.
1423 *
1424 * @param int $flags User::READ_* constant bitfield
1425 * @return bool True if the user exists, false if the user is anonymous
1426 */
1427 public function loadFromDatabase( $flags = self::READ_LATEST ) {
1428 // Paranoia
1429 $this->mId = intval( $this->mId );
1430
1431 if ( !$this->mId ) {
1432 // Anonymous users are not in the database
1433 $this->loadDefaults();
1434 return false;
1435 }
1436
1437 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
1438 $db = wfGetDB( $index );
1439
1440 $userQuery = self::getQueryInfo();
1441 $s = $db->selectRow(
1442 $userQuery['tables'],
1443 $userQuery['fields'],
1444 [ 'user_id' => $this->mId ],
1445 __METHOD__,
1446 $options,
1447 $userQuery['joins']
1448 );
1449
1450 $this->queryFlagsUsed = $flags;
1451 Hooks::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1452
1453 if ( $s !== false ) {
1454 // Initialise user table data
1455 $this->loadFromRow( $s );
1456 $this->mGroupMemberships = null; // deferred
1457 $this->getEditCount(); // revalidation for nulls
1458 return true;
1459 } else {
1460 // Invalid user_id
1461 $this->mId = 0;
1462 $this->loadDefaults();
1463 return false;
1464 }
1465 }
1466
1467 /**
1468 * Initialize this object from a row from the user table.
1469 *
1470 * @param stdClass $row Row from the user table to load.
1471 * @param array|null $data Further user data to load into the object
1472 *
1473 * user_groups Array of arrays or stdClass result rows out of the user_groups
1474 * table. Previously you were supposed to pass an array of strings
1475 * here, but we also need expiry info nowadays, so an array of
1476 * strings is ignored.
1477 * user_properties Array with properties out of the user_properties table
1478 */
1479 protected function loadFromRow( $row, $data = null ) {
1480 global $wgActorTableSchemaMigrationStage;
1481
1482 if ( !is_object( $row ) ) {
1483 throw new InvalidArgumentException( '$row must be an object' );
1484 }
1485
1486 $all = true;
1487
1488 $this->mGroupMemberships = null; // deferred
1489
1490 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD ) {
1491 if ( isset( $row->actor_id ) ) {
1492 $this->mActorId = (int)$row->actor_id;
1493 if ( $this->mActorId !== 0 ) {
1494 $this->mFrom = 'actor';
1495 }
1496 $this->setItemLoaded( 'actor' );
1497 } else {
1498 $all = false;
1499 }
1500 }
1501
1502 if ( isset( $row->user_name ) && $row->user_name !== '' ) {
1503 $this->mName = $row->user_name;
1504 $this->mFrom = 'name';
1505 $this->setItemLoaded( 'name' );
1506 } else {
1507 $all = false;
1508 }
1509
1510 if ( isset( $row->user_real_name ) ) {
1511 $this->mRealName = $row->user_real_name;
1512 $this->setItemLoaded( 'realname' );
1513 } else {
1514 $all = false;
1515 }
1516
1517 if ( isset( $row->user_id ) ) {
1518 $this->mId = intval( $row->user_id );
1519 if ( $this->mId !== 0 ) {
1520 $this->mFrom = 'id';
1521 }
1522 $this->setItemLoaded( 'id' );
1523 } else {
1524 $all = false;
1525 }
1526
1527 if ( isset( $row->user_id ) && isset( $row->user_name ) && $row->user_name !== '' ) {
1528 self::$idCacheByName[$row->user_name] = $row->user_id;
1529 }
1530
1531 if ( isset( $row->user_editcount ) ) {
1532 $this->mEditCount = $row->user_editcount;
1533 } else {
1534 $all = false;
1535 }
1536
1537 if ( isset( $row->user_touched ) ) {
1538 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1539 } else {
1540 $all = false;
1541 }
1542
1543 if ( isset( $row->user_token ) ) {
1544 // The definition for the column is binary(32), so trim the NULs
1545 // that appends. The previous definition was char(32), so trim
1546 // spaces too.
1547 $this->mToken = rtrim( $row->user_token, " \0" );
1548 if ( $this->mToken === '' ) {
1549 $this->mToken = null;
1550 }
1551 } else {
1552 $all = false;
1553 }
1554
1555 if ( isset( $row->user_email ) ) {
1556 $this->mEmail = $row->user_email;
1557 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1558 $this->mEmailToken = $row->user_email_token;
1559 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1560 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1561 } else {
1562 $all = false;
1563 }
1564
1565 if ( $all ) {
1566 $this->mLoadedItems = true;
1567 }
1568
1569 if ( is_array( $data ) ) {
1570 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1571 if ( !count( $data['user_groups'] ) ) {
1572 $this->mGroupMemberships = [];
1573 } else {
1574 $firstGroup = reset( $data['user_groups'] );
1575 if ( is_array( $firstGroup ) || is_object( $firstGroup ) ) {
1576 $this->mGroupMemberships = [];
1577 foreach ( $data['user_groups'] as $row ) {
1578 $ugm = UserGroupMembership::newFromRow( (object)$row );
1579 $this->mGroupMemberships[$ugm->getGroup()] = $ugm;
1580 }
1581 }
1582 }
1583 }
1584 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1585 $this->loadOptions( $data['user_properties'] );
1586 }
1587 }
1588 }
1589
1590 /**
1591 * Load the data for this user object from another user object.
1592 *
1593 * @param User $user
1594 */
1595 protected function loadFromUserObject( $user ) {
1596 $user->load();
1597 foreach ( self::$mCacheVars as $var ) {
1598 $this->$var = $user->$var;
1599 }
1600 }
1601
1602 /**
1603 * Load the groups from the database if they aren't already loaded.
1604 */
1605 private function loadGroups() {
1606 if ( is_null( $this->mGroupMemberships ) ) {
1607 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
1608 ? wfGetDB( DB_MASTER )
1609 : wfGetDB( DB_REPLICA );
1610 $this->mGroupMemberships = UserGroupMembership::getMembershipsForUser(
1611 $this->mId, $db );
1612 }
1613 }
1614
1615 /**
1616 * Add the user to the group if he/she meets given criteria.
1617 *
1618 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1619 * possible to remove manually via Special:UserRights. In such case it
1620 * will not be re-added automatically. The user will also not lose the
1621 * group if they no longer meet the criteria.
1622 *
1623 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1624 *
1625 * @return array Array of groups the user has been promoted to.
1626 *
1627 * @see $wgAutopromoteOnce
1628 */
1629 public function addAutopromoteOnceGroups( $event ) {
1630 global $wgAutopromoteOnceLogInRC;
1631
1632 if ( wfReadOnly() || !$this->getId() ) {
1633 return [];
1634 }
1635
1636 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1637 if ( !count( $toPromote ) ) {
1638 return [];
1639 }
1640
1641 if ( !$this->checkAndSetTouched() ) {
1642 return []; // raced out (bug T48834)
1643 }
1644
1645 $oldGroups = $this->getGroups(); // previous groups
1646 $oldUGMs = $this->getGroupMemberships();
1647 foreach ( $toPromote as $group ) {
1648 $this->addGroup( $group );
1649 }
1650 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1651 $newUGMs = $this->getGroupMemberships();
1652
1653 // update groups in external authentication database
1654 Hooks::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false, $oldUGMs, $newUGMs ] );
1655 AuthManager::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1656
1657 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1658 $logEntry->setPerformer( $this );
1659 $logEntry->setTarget( $this->getUserPage() );
1660 $logEntry->setParameters( [
1661 '4::oldgroups' => $oldGroups,
1662 '5::newgroups' => $newGroups,
1663 ] );
1664 $logid = $logEntry->insert();
1665 if ( $wgAutopromoteOnceLogInRC ) {
1666 $logEntry->publish( $logid );
1667 }
1668
1669 return $toPromote;
1670 }
1671
1672 /**
1673 * Builds update conditions. Additional conditions may be added to $conditions to
1674 * protected against race conditions using a compare-and-set (CAS) mechanism
1675 * based on comparing $this->mTouched with the user_touched field.
1676 *
1677 * @param Database $db
1678 * @param array $conditions WHERE conditions for use with Database::update
1679 * @return array WHERE conditions for use with Database::update
1680 */
1681 protected function makeUpdateConditions( Database $db, array $conditions ) {
1682 if ( $this->mTouched ) {
1683 // CAS check: only update if the row wasn't changed sicne it was loaded.
1684 $conditions['user_touched'] = $db->timestamp( $this->mTouched );
1685 }
1686
1687 return $conditions;
1688 }
1689
1690 /**
1691 * Bump user_touched if it didn't change since this object was loaded
1692 *
1693 * On success, the mTouched field is updated.
1694 * The user serialization cache is always cleared.
1695 *
1696 * @return bool Whether user_touched was actually updated
1697 * @since 1.26
1698 */
1699 protected function checkAndSetTouched() {
1700 $this->load();
1701
1702 if ( !$this->mId ) {
1703 return false; // anon
1704 }
1705
1706 // Get a new user_touched that is higher than the old one
1707 $newTouched = $this->newTouchedTimestamp();
1708
1709 $dbw = wfGetDB( DB_MASTER );
1710 $dbw->update( 'user',
1711 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1712 $this->makeUpdateConditions( $dbw, [
1713 'user_id' => $this->mId,
1714 ] ),
1715 __METHOD__
1716 );
1717 $success = ( $dbw->affectedRows() > 0 );
1718
1719 if ( $success ) {
1720 $this->mTouched = $newTouched;
1721 $this->clearSharedCache();
1722 } else {
1723 // Clears on failure too since that is desired if the cache is stale
1724 $this->clearSharedCache( 'refresh' );
1725 }
1726
1727 return $success;
1728 }
1729
1730 /**
1731 * Clear various cached data stored in this object. The cache of the user table
1732 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1733 *
1734 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1735 * given source. May be "name", "id", "actor", "defaults", "session", or false for no reload.
1736 */
1737 public function clearInstanceCache( $reloadFrom = false ) {
1738 $this->mNewtalk = -1;
1739 $this->mDatePreference = null;
1740 $this->mBlockedby = -1; # Unset
1741 $this->mHash = false;
1742 $this->mRights = null;
1743 $this->mEffectiveGroups = null;
1744 $this->mImplicitGroups = null;
1745 $this->mGroupMemberships = null;
1746 $this->mOptions = null;
1747 $this->mOptionsLoaded = false;
1748 $this->mEditCount = null;
1749
1750 if ( $reloadFrom ) {
1751 $this->mLoadedItems = [];
1752 $this->mFrom = $reloadFrom;
1753 }
1754 }
1755
1756 /**
1757 * Combine the language default options with any site-specific options
1758 * and add the default language variants.
1759 *
1760 * @return array Array of String options
1761 */
1762 public static function getDefaultOptions() {
1763 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgDefaultSkin;
1764
1765 static $defOpt = null;
1766 static $defOptLang = null;
1767
1768 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
1769 if ( $defOpt !== null && $defOptLang === $contLang->getCode() ) {
1770 // The content language does not change (and should not change) mid-request, but the
1771 // unit tests change it anyway, and expect this method to return values relevant to the
1772 // current content language.
1773 return $defOpt;
1774 }
1775
1776 $defOpt = $wgDefaultUserOptions;
1777 // Default language setting
1778 $defOptLang = $contLang->getCode();
1779 $defOpt['language'] = $defOptLang;
1780 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1781 if ( $langCode === $contLang->getCode() ) {
1782 $defOpt['variant'] = $langCode;
1783 } else {
1784 $defOpt["variant-$langCode"] = $langCode;
1785 }
1786 }
1787
1788 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1789 // since extensions may change the set of searchable namespaces depending
1790 // on user groups/permissions.
1791 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1792 $defOpt['searchNs' . $nsnum] = (bool)$val;
1793 }
1794 $defOpt['skin'] = Skin::normalizeKey( $wgDefaultSkin );
1795
1796 Hooks::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1797
1798 return $defOpt;
1799 }
1800
1801 /**
1802 * Get a given default option value.
1803 *
1804 * @param string $opt Name of option to retrieve
1805 * @return string Default option value
1806 */
1807 public static function getDefaultOption( $opt ) {
1808 $defOpts = self::getDefaultOptions();
1809 if ( isset( $defOpts[$opt] ) ) {
1810 return $defOpts[$opt];
1811 } else {
1812 return null;
1813 }
1814 }
1815
1816 /**
1817 * Get blocking information
1818 * @param bool $bFromSlave Whether to check the replica DB first.
1819 * To improve performance, non-critical checks are done against replica DBs.
1820 * Check when actually saving should be done against master.
1821 */
1822 private function getBlockedStatus( $bFromSlave = true ) {
1823 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff, $wgSoftBlockRanges;
1824
1825 if ( -1 != $this->mBlockedby ) {
1826 return;
1827 }
1828
1829 wfDebug( __METHOD__ . ": checking...\n" );
1830
1831 // Initialize data...
1832 // Otherwise something ends up stomping on $this->mBlockedby when
1833 // things get lazy-loaded later, causing false positive block hits
1834 // due to -1 !== 0. Probably session-related... Nothing should be
1835 // overwriting mBlockedby, surely?
1836 $this->load();
1837
1838 # We only need to worry about passing the IP address to the Block generator if the
1839 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1840 # know which IP address they're actually coming from
1841 $ip = null;
1842 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1843 // $wgUser->getName() only works after the end of Setup.php. Until
1844 // then, assume it's a logged-out user.
1845 $globalUserName = $wgUser->isSafeToLoad()
1846 ? $wgUser->getName()
1847 : IP::sanitizeIP( $wgUser->getRequest()->getIP() );
1848 if ( $this->getName() === $globalUserName ) {
1849 $ip = $this->getRequest()->getIP();
1850 }
1851 }
1852
1853 // User/IP blocking
1854 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1855
1856 // Cookie blocking
1857 if ( !$block instanceof Block ) {
1858 $block = $this->getBlockFromCookieValue( $this->getRequest()->getCookie( 'BlockID' ) );
1859 }
1860
1861 // Proxy blocking
1862 if ( !$block instanceof Block && $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1863 // Local list
1864 if ( self::isLocallyBlockedProxy( $ip ) ) {
1865 $block = new Block( [
1866 'byText' => wfMessage( 'proxyblocker' )->text(),
1867 'reason' => wfMessage( 'proxyblockreason' )->plain(),
1868 'address' => $ip,
1869 'systemBlock' => 'proxy',
1870 ] );
1871 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1872 $block = new Block( [
1873 'byText' => wfMessage( 'sorbs' )->text(),
1874 'reason' => wfMessage( 'sorbsreason' )->plain(),
1875 'address' => $ip,
1876 'systemBlock' => 'dnsbl',
1877 ] );
1878 }
1879 }
1880
1881 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
1882 if ( !$block instanceof Block
1883 && $wgApplyIpBlocksToXff
1884 && $ip !== null
1885 && !in_array( $ip, $wgProxyWhitelist )
1886 ) {
1887 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1888 $xff = array_map( 'trim', explode( ',', $xff ) );
1889 $xff = array_diff( $xff, [ $ip ] );
1890 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1891 $block = Block::chooseBlock( $xffblocks, $xff );
1892 if ( $block instanceof Block ) {
1893 # Mangle the reason to alert the user that the block
1894 # originated from matching the X-Forwarded-For header.
1895 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->plain();
1896 }
1897 }
1898
1899 if ( !$block instanceof Block
1900 && $ip !== null
1901 && $this->isAnon()
1902 && IP::isInRanges( $ip, $wgSoftBlockRanges )
1903 ) {
1904 $block = new Block( [
1905 'address' => $ip,
1906 'byText' => 'MediaWiki default',
1907 'reason' => wfMessage( 'softblockrangesreason', $ip )->plain(),
1908 'anonOnly' => true,
1909 'systemBlock' => 'wgSoftBlockRanges',
1910 ] );
1911 }
1912
1913 if ( $block instanceof Block ) {
1914 wfDebug( __METHOD__ . ": Found block.\n" );
1915 $this->mBlock = $block;
1916 $this->mBlockedby = $block->getByName();
1917 $this->mBlockreason = $block->mReason;
1918 $this->mHideName = $block->mHideName;
1919 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1920 } else {
1921 $this->mBlock = null;
1922 $this->mBlockedby = '';
1923 $this->mBlockreason = '';
1924 $this->mHideName = 0;
1925 $this->mAllowUsertalk = false;
1926 }
1927
1928 // Avoid PHP 7.1 warning of passing $this by reference
1929 $user = $this;
1930 // Extensions
1931 Hooks::run( 'GetBlockedStatus', [ &$user ] );
1932 }
1933
1934 /**
1935 * Try to load a Block from an ID given in a cookie value.
1936 * @param string|null $blockCookieVal The cookie value to check.
1937 * @return Block|bool The Block object, or false if none could be loaded.
1938 */
1939 protected function getBlockFromCookieValue( $blockCookieVal ) {
1940 // Make sure there's something to check. The cookie value must start with a number.
1941 if ( strlen( $blockCookieVal ) < 1 || !is_numeric( substr( $blockCookieVal, 0, 1 ) ) ) {
1942 return false;
1943 }
1944 // Load the Block from the ID in the cookie.
1945 $blockCookieId = Block::getIdFromCookieValue( $blockCookieVal );
1946 if ( $blockCookieId !== null ) {
1947 // An ID was found in the cookie.
1948 $tmpBlock = Block::newFromID( $blockCookieId );
1949 if ( $tmpBlock instanceof Block ) {
1950 $config = RequestContext::getMain()->getConfig();
1951
1952 switch ( $tmpBlock->getType() ) {
1953 case Block::TYPE_USER:
1954 $blockIsValid = !$tmpBlock->isExpired() && $tmpBlock->isAutoblocking();
1955 $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true );
1956 break;
1957 case Block::TYPE_IP:
1958 case Block::TYPE_RANGE:
1959 // If block is type IP or IP range, load only if user is not logged in (T152462)
1960 $blockIsValid = !$tmpBlock->isExpired() && !$this->isLoggedIn();
1961 $useBlockCookie = ( $config->get( 'CookieSetOnIpBlock' ) === true );
1962 break;
1963 default:
1964 $blockIsValid = false;
1965 $useBlockCookie = false;
1966 }
1967
1968 if ( $blockIsValid && $useBlockCookie ) {
1969 // Use the block.
1970 return $tmpBlock;
1971 } else {
1972 // If the block is not valid, remove the cookie.
1973 Block::clearCookie( $this->getRequest()->response() );
1974 }
1975 } else {
1976 // If the block doesn't exist, remove the cookie.
1977 Block::clearCookie( $this->getRequest()->response() );
1978 }
1979 }
1980 return false;
1981 }
1982
1983 /**
1984 * Whether the given IP is in a DNS blacklist.
1985 *
1986 * @param string $ip IP to check
1987 * @param bool $checkWhitelist Whether to check the whitelist first
1988 * @return bool True if blacklisted.
1989 */
1990 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1991 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1992
1993 if ( !$wgEnableDnsBlacklist ) {
1994 return false;
1995 }
1996
1997 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1998 return false;
1999 }
2000
2001 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
2002 }
2003
2004 /**
2005 * Whether the given IP is in a given DNS blacklist.
2006 *
2007 * @param string $ip IP to check
2008 * @param string|array $bases Array of Strings: URL of the DNS blacklist
2009 * @return bool True if blacklisted.
2010 */
2011 public function inDnsBlacklist( $ip, $bases ) {
2012 $found = false;
2013 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
2014 if ( IP::isIPv4( $ip ) ) {
2015 // Reverse IP, T23255
2016 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
2017
2018 foreach ( (array)$bases as $base ) {
2019 // Make hostname
2020 // If we have an access key, use that too (ProjectHoneypot, etc.)
2021 $basename = $base;
2022 if ( is_array( $base ) ) {
2023 if ( count( $base ) >= 2 ) {
2024 // Access key is 1, base URL is 0
2025 $host = "{$base[1]}.$ipReversed.{$base[0]}";
2026 } else {
2027 $host = "$ipReversed.{$base[0]}";
2028 }
2029 $basename = $base[0];
2030 } else {
2031 $host = "$ipReversed.$base";
2032 }
2033
2034 // Send query
2035 $ipList = gethostbynamel( $host );
2036
2037 if ( $ipList ) {
2038 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
2039 $found = true;
2040 break;
2041 } else {
2042 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
2043 }
2044 }
2045 }
2046
2047 return $found;
2048 }
2049
2050 /**
2051 * Check if an IP address is in the local proxy list
2052 *
2053 * @param string $ip
2054 *
2055 * @return bool
2056 */
2057 public static function isLocallyBlockedProxy( $ip ) {
2058 global $wgProxyList;
2059
2060 if ( !$wgProxyList ) {
2061 return false;
2062 }
2063
2064 if ( !is_array( $wgProxyList ) ) {
2065 // Load values from the specified file
2066 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
2067 }
2068
2069 $resultProxyList = [];
2070 $deprecatedIPEntries = [];
2071
2072 // backward compatibility: move all ip addresses in keys to values
2073 foreach ( $wgProxyList as $key => $value ) {
2074 $keyIsIP = IP::isIPAddress( $key );
2075 $valueIsIP = IP::isIPAddress( $value );
2076 if ( $keyIsIP && !$valueIsIP ) {
2077 $deprecatedIPEntries[] = $key;
2078 $resultProxyList[] = $key;
2079 } elseif ( $keyIsIP && $valueIsIP ) {
2080 $deprecatedIPEntries[] = $key;
2081 $resultProxyList[] = $key;
2082 $resultProxyList[] = $value;
2083 } else {
2084 $resultProxyList[] = $value;
2085 }
2086 }
2087
2088 if ( $deprecatedIPEntries ) {
2089 wfDeprecated(
2090 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
2091 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
2092 }
2093
2094 $proxyListIPSet = new IPSet( $resultProxyList );
2095 return $proxyListIPSet->match( $ip );
2096 }
2097
2098 /**
2099 * Is this user subject to rate limiting?
2100 *
2101 * @return bool True if rate limited
2102 */
2103 public function isPingLimitable() {
2104 global $wgRateLimitsExcludedIPs;
2105 if ( IP::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
2106 // No other good way currently to disable rate limits
2107 // for specific IPs. :P
2108 // But this is a crappy hack and should die.
2109 return false;
2110 }
2111 return !$this->isAllowed( 'noratelimit' );
2112 }
2113
2114 /**
2115 * Primitive rate limits: enforce maximum actions per time period
2116 * to put a brake on flooding.
2117 *
2118 * The method generates both a generic profiling point and a per action one
2119 * (suffix being "-$action".
2120 *
2121 * @note When using a shared cache like memcached, IP-address
2122 * last-hit counters will be shared across wikis.
2123 *
2124 * @param string $action Action to enforce; 'edit' if unspecified
2125 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
2126 * @return bool True if a rate limiter was tripped
2127 */
2128 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
2129 // Avoid PHP 7.1 warning of passing $this by reference
2130 $user = $this;
2131 // Call the 'PingLimiter' hook
2132 $result = false;
2133 if ( !Hooks::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
2134 return $result;
2135 }
2136
2137 global $wgRateLimits;
2138 if ( !isset( $wgRateLimits[$action] ) ) {
2139 return false;
2140 }
2141
2142 $limits = array_merge(
2143 [ '&can-bypass' => true ],
2144 $wgRateLimits[$action]
2145 );
2146
2147 // Some groups shouldn't trigger the ping limiter, ever
2148 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
2149 return false;
2150 }
2151
2152 $keys = [];
2153 $id = $this->getId();
2154 $userLimit = false;
2155 $isNewbie = $this->isNewbie();
2156 $cache = ObjectCache::getLocalClusterInstance();
2157
2158 if ( $id == 0 ) {
2159 // limits for anons
2160 if ( isset( $limits['anon'] ) ) {
2161 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
2162 }
2163 } else {
2164 // limits for logged-in users
2165 if ( isset( $limits['user'] ) ) {
2166 $userLimit = $limits['user'];
2167 }
2168 }
2169
2170 // limits for anons and for newbie logged-in users
2171 if ( $isNewbie ) {
2172 // ip-based limits
2173 if ( isset( $limits['ip'] ) ) {
2174 $ip = $this->getRequest()->getIP();
2175 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
2176 }
2177 // subnet-based limits
2178 if ( isset( $limits['subnet'] ) ) {
2179 $ip = $this->getRequest()->getIP();
2180 $subnet = IP::getSubnet( $ip );
2181 if ( $subnet !== false ) {
2182 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
2183 }
2184 }
2185 }
2186
2187 // Check for group-specific permissions
2188 // If more than one group applies, use the group with the highest limit ratio (max/period)
2189 foreach ( $this->getGroups() as $group ) {
2190 if ( isset( $limits[$group] ) ) {
2191 if ( $userLimit === false
2192 || $limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
2193 ) {
2194 $userLimit = $limits[$group];
2195 }
2196 }
2197 }
2198
2199 // limits for newbie logged-in users (override all the normal user limits)
2200 if ( $id !== 0 && $isNewbie && isset( $limits['newbie'] ) ) {
2201 $userLimit = $limits['newbie'];
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 throw new MWException(
4213 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
4214 " the version of the user to be saved is older than the current version."
4215 );
4216 }
4217
4218 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD ) {
4219 $dbw->update(
4220 'actor',
4221 [ 'actor_name' => $this->mName ],
4222 [ 'actor_user' => $this->mId ],
4223 $fname
4224 );
4225 }
4226 } );
4227
4228 $this->mTouched = $newTouched;
4229 $this->saveOptions();
4230
4231 Hooks::run( 'UserSaveSettings', [ $this ] );
4232 $this->clearSharedCache();
4233 $this->getUserPage()->invalidateCache();
4234 }
4235
4236 /**
4237 * If only this user's username is known, and it exists, return the user ID.
4238 *
4239 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4240 * @return int
4241 */
4242 public function idForName( $flags = 0 ) {
4243 $s = trim( $this->getName() );
4244 if ( $s === '' ) {
4245 return 0;
4246 }
4247
4248 $db = ( ( $flags & self::READ_LATEST ) == self::READ_LATEST )
4249 ? wfGetDB( DB_MASTER )
4250 : wfGetDB( DB_REPLICA );
4251
4252 $options = ( ( $flags & self::READ_LOCKING ) == self::READ_LOCKING )
4253 ? [ 'LOCK IN SHARE MODE' ]
4254 : [];
4255
4256 $id = $db->selectField( 'user',
4257 'user_id', [ 'user_name' => $s ], __METHOD__, $options );
4258
4259 return (int)$id;
4260 }
4261
4262 /**
4263 * Add a user to the database, return the user object
4264 *
4265 * @param string $name Username to add
4266 * @param array $params Array of Strings Non-default parameters to save to
4267 * the database as user_* fields:
4268 * - email: The user's email address.
4269 * - email_authenticated: The email authentication timestamp.
4270 * - real_name: The user's real name.
4271 * - options: An associative array of non-default options.
4272 * - token: Random authentication token. Do not set.
4273 * - registration: Registration timestamp. Do not set.
4274 *
4275 * @return User|null User object, or null if the username already exists.
4276 */
4277 public static function createNew( $name, $params = [] ) {
4278 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4279 if ( isset( $params[$field] ) ) {
4280 wfDeprecated( __METHOD__ . " with param '$field'", '1.27' );
4281 unset( $params[$field] );
4282 }
4283 }
4284
4285 $user = new User;
4286 $user->load();
4287 $user->setToken(); // init token
4288 if ( isset( $params['options'] ) ) {
4289 $user->mOptions = $params['options'] + (array)$user->mOptions;
4290 unset( $params['options'] );
4291 }
4292 $dbw = wfGetDB( DB_MASTER );
4293
4294 $noPass = PasswordFactory::newInvalidPassword()->toString();
4295
4296 $fields = [
4297 'user_name' => $name,
4298 'user_password' => $noPass,
4299 'user_newpassword' => $noPass,
4300 'user_email' => $user->mEmail,
4301 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
4302 'user_real_name' => $user->mRealName,
4303 'user_token' => strval( $user->mToken ),
4304 'user_registration' => $dbw->timestamp( $user->mRegistration ),
4305 'user_editcount' => 0,
4306 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4307 ];
4308 foreach ( $params as $name => $value ) {
4309 $fields["user_$name"] = $value;
4310 }
4311
4312 return $dbw->doAtomicSection( __METHOD__, function ( $dbw, $fname ) use ( $fields ) {
4313 $dbw->insert( 'user', $fields, $fname, [ 'IGNORE' ] );
4314 if ( $dbw->affectedRows() ) {
4315 $newUser = self::newFromId( $dbw->insertId() );
4316 // Load the user from master to avoid replica lag
4317 $newUser->load( self::READ_LATEST );
4318 $newUser->updateActorId( $dbw );
4319 } else {
4320 $newUser = null;
4321 }
4322 return $newUser;
4323 } );
4324 }
4325
4326 /**
4327 * Add this existing user object to the database. If the user already
4328 * exists, a fatal status object is returned, and the user object is
4329 * initialised with the data from the database.
4330 *
4331 * Previously, this function generated a DB error due to a key conflict
4332 * if the user already existed. Many extension callers use this function
4333 * in code along the lines of:
4334 *
4335 * $user = User::newFromName( $name );
4336 * if ( !$user->isLoggedIn() ) {
4337 * $user->addToDatabase();
4338 * }
4339 * // do something with $user...
4340 *
4341 * However, this was vulnerable to a race condition (T18020). By
4342 * initialising the user object if the user exists, we aim to support this
4343 * calling sequence as far as possible.
4344 *
4345 * Note that if the user exists, this function will acquire a write lock,
4346 * so it is still advisable to make the call conditional on isLoggedIn(),
4347 * and to commit the transaction after calling.
4348 *
4349 * @throws MWException
4350 * @return Status
4351 */
4352 public function addToDatabase() {
4353 $this->load();
4354 if ( !$this->mToken ) {
4355 $this->setToken(); // init token
4356 }
4357
4358 if ( !is_string( $this->mName ) ) {
4359 throw new RuntimeException( "User name field is not set." );
4360 }
4361
4362 $this->mTouched = $this->newTouchedTimestamp();
4363
4364 $dbw = wfGetDB( DB_MASTER );
4365 $status = $dbw->doAtomicSection( __METHOD__, function ( $dbw, $fname ) {
4366 $noPass = PasswordFactory::newInvalidPassword()->toString();
4367 $dbw->insert( 'user',
4368 [
4369 'user_name' => $this->mName,
4370 'user_password' => $noPass,
4371 'user_newpassword' => $noPass,
4372 'user_email' => $this->mEmail,
4373 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
4374 'user_real_name' => $this->mRealName,
4375 'user_token' => strval( $this->mToken ),
4376 'user_registration' => $dbw->timestamp( $this->mRegistration ),
4377 'user_editcount' => 0,
4378 'user_touched' => $dbw->timestamp( $this->mTouched ),
4379 ], $fname,
4380 [ 'IGNORE' ]
4381 );
4382 if ( !$dbw->affectedRows() ) {
4383 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4384 $this->mId = $dbw->selectField(
4385 'user',
4386 'user_id',
4387 [ 'user_name' => $this->mName ],
4388 __METHOD__,
4389 [ 'LOCK IN SHARE MODE' ]
4390 );
4391 $loaded = false;
4392 if ( $this->mId ) {
4393 if ( $this->loadFromDatabase( self::READ_LOCKING ) ) {
4394 $loaded = true;
4395 }
4396 }
4397 if ( !$loaded ) {
4398 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
4399 "to insert user '{$this->mName}' row, but it was not present in select!" );
4400 }
4401 return Status::newFatal( 'userexists' );
4402 }
4403 $this->mId = $dbw->insertId();
4404 self::$idCacheByName[$this->mName] = $this->mId;
4405 $this->updateActorId( $dbw );
4406
4407 return Status::newGood();
4408 } );
4409 if ( !$status->isGood() ) {
4410 return $status;
4411 }
4412
4413 // Clear instance cache other than user table data and actor, which is already accurate
4414 $this->clearInstanceCache();
4415
4416 $this->saveOptions();
4417 return Status::newGood();
4418 }
4419
4420 /**
4421 * Update the actor ID after an insert
4422 * @param IDatabase $dbw Writable database handle
4423 */
4424 private function updateActorId( IDatabase $dbw ) {
4425 global $wgActorTableSchemaMigrationStage;
4426
4427 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD ) {
4428 $dbw->insert(
4429 'actor',
4430 [ 'actor_user' => $this->mId, 'actor_name' => $this->mName ],
4431 __METHOD__
4432 );
4433 $this->mActorId = (int)$dbw->insertId();
4434 }
4435 }
4436
4437 /**
4438 * If this user is logged-in and blocked,
4439 * block any IP address they've successfully logged in from.
4440 * @return bool A block was spread
4441 */
4442 public function spreadAnyEditBlock() {
4443 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4444 return $this->spreadBlock();
4445 }
4446
4447 return false;
4448 }
4449
4450 /**
4451 * If this (non-anonymous) user is blocked,
4452 * block the IP address they've successfully logged in from.
4453 * @return bool A block was spread
4454 */
4455 protected function spreadBlock() {
4456 wfDebug( __METHOD__ . "()\n" );
4457 $this->load();
4458 if ( $this->mId == 0 ) {
4459 return false;
4460 }
4461
4462 $userblock = Block::newFromTarget( $this->getName() );
4463 if ( !$userblock ) {
4464 return false;
4465 }
4466
4467 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4468 }
4469
4470 /**
4471 * Get whether the user is explicitly blocked from account creation.
4472 * @return bool|Block
4473 */
4474 public function isBlockedFromCreateAccount() {
4475 $this->getBlockedStatus();
4476 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
4477 return $this->mBlock;
4478 }
4479
4480 # T15611: if the IP address the user is trying to create an account from is
4481 # blocked with createaccount disabled, prevent new account creation there even
4482 # when the user is logged in
4483 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4484 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
4485 }
4486 return $this->mBlockedFromCreateAccount instanceof Block
4487 && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
4488 ? $this->mBlockedFromCreateAccount
4489 : false;
4490 }
4491
4492 /**
4493 * Get whether the user is blocked from using Special:Emailuser.
4494 * @return bool
4495 */
4496 public function isBlockedFromEmailuser() {
4497 $this->getBlockedStatus();
4498 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
4499 }
4500
4501 /**
4502 * Get whether the user is allowed to create an account.
4503 * @return bool
4504 */
4505 public function isAllowedToCreateAccount() {
4506 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4507 }
4508
4509 /**
4510 * Get this user's personal page title.
4511 *
4512 * @return Title User's personal page title
4513 */
4514 public function getUserPage() {
4515 return Title::makeTitle( NS_USER, $this->getName() );
4516 }
4517
4518 /**
4519 * Get this user's talk page title.
4520 *
4521 * @return Title User's talk page title
4522 */
4523 public function getTalkPage() {
4524 $title = $this->getUserPage();
4525 return $title->getTalkPage();
4526 }
4527
4528 /**
4529 * Determine whether the user is a newbie. Newbies are either
4530 * anonymous IPs, or the most recently created accounts.
4531 * @return bool
4532 */
4533 public function isNewbie() {
4534 return !$this->isAllowed( 'autoconfirmed' );
4535 }
4536
4537 /**
4538 * Check to see if the given clear-text password is one of the accepted passwords
4539 * @deprecated since 1.27, use AuthManager instead
4540 * @param string $password User password
4541 * @return bool True if the given password is correct, otherwise False
4542 */
4543 public function checkPassword( $password ) {
4544 $manager = AuthManager::singleton();
4545 $reqs = AuthenticationRequest::loadRequestsFromSubmission(
4546 $manager->getAuthenticationRequests( AuthManager::ACTION_LOGIN ),
4547 [
4548 'username' => $this->getName(),
4549 'password' => $password,
4550 ]
4551 );
4552 $res = AuthManager::singleton()->beginAuthentication( $reqs, 'null:' );
4553 switch ( $res->status ) {
4554 case AuthenticationResponse::PASS:
4555 return true;
4556 case AuthenticationResponse::FAIL:
4557 // Hope it's not a PreAuthenticationProvider that failed...
4558 \MediaWiki\Logger\LoggerFactory::getInstance( 'authentication' )
4559 ->info( __METHOD__ . ': Authentication failed: ' . $res->message->plain() );
4560 return false;
4561 default:
4562 throw new BadMethodCallException(
4563 'AuthManager returned a response unsupported by ' . __METHOD__
4564 );
4565 }
4566 }
4567
4568 /**
4569 * Check if the given clear-text password matches the temporary password
4570 * sent by e-mail for password reset operations.
4571 *
4572 * @deprecated since 1.27, use AuthManager instead
4573 * @param string $plaintext
4574 * @return bool True if matches, false otherwise
4575 */
4576 public function checkTemporaryPassword( $plaintext ) {
4577 // Can't check the temporary password individually.
4578 return $this->checkPassword( $plaintext );
4579 }
4580
4581 /**
4582 * Initialize (if necessary) and return a session token value
4583 * which can be used in edit forms to show that the user's
4584 * login credentials aren't being hijacked with a foreign form
4585 * submission.
4586 *
4587 * @since 1.27
4588 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4589 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4590 * @return MediaWiki\Session\Token The new edit token
4591 */
4592 public function getEditTokenObject( $salt = '', $request = null ) {
4593 if ( $this->isAnon() ) {
4594 return new LoggedOutEditToken();
4595 }
4596
4597 if ( !$request ) {
4598 $request = $this->getRequest();
4599 }
4600 return $request->getSession()->getToken( $salt );
4601 }
4602
4603 /**
4604 * Initialize (if necessary) and return a session token value
4605 * which can be used in edit forms to show that the user's
4606 * login credentials aren't being hijacked with a foreign form
4607 * submission.
4608 *
4609 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4610 *
4611 * @since 1.19
4612 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4613 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4614 * @return string The new edit token
4615 */
4616 public function getEditToken( $salt = '', $request = null ) {
4617 return $this->getEditTokenObject( $salt, $request )->toString();
4618 }
4619
4620 /**
4621 * Check given value against the token value stored in the session.
4622 * A match should confirm that the form was submitted from the
4623 * user's own login session, not a form submission from a third-party
4624 * site.
4625 *
4626 * @param string $val Input value to compare
4627 * @param string|array $salt Optional function-specific data for hashing
4628 * @param WebRequest|null $request Object to use or null to use $wgRequest
4629 * @param int|null $maxage Fail tokens older than this, in seconds
4630 * @return bool Whether the token matches
4631 */
4632 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4633 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4634 }
4635
4636 /**
4637 * Check given value against the token value stored in the session,
4638 * ignoring the suffix.
4639 *
4640 * @param string $val Input value to compare
4641 * @param string|array $salt Optional function-specific data for hashing
4642 * @param WebRequest|null $request Object to use or null to use $wgRequest
4643 * @param int|null $maxage Fail tokens older than this, in seconds
4644 * @return bool Whether the token matches
4645 */
4646 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4647 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token::SUFFIX;
4648 return $this->matchEditToken( $val, $salt, $request, $maxage );
4649 }
4650
4651 /**
4652 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4653 * mail to the user's given address.
4654 *
4655 * @param string $type Message to send, either "created", "changed" or "set"
4656 * @return Status
4657 */
4658 public function sendConfirmationMail( $type = 'created' ) {
4659 global $wgLang;
4660 $expiration = null; // gets passed-by-ref and defined in next line.
4661 $token = $this->confirmationToken( $expiration );
4662 $url = $this->confirmationTokenUrl( $token );
4663 $invalidateURL = $this->invalidationTokenUrl( $token );
4664 $this->saveSettings();
4665
4666 if ( $type == 'created' || $type === false ) {
4667 $message = 'confirmemail_body';
4668 } elseif ( $type === true ) {
4669 $message = 'confirmemail_body_changed';
4670 } else {
4671 // Messages: confirmemail_body_changed, confirmemail_body_set
4672 $message = 'confirmemail_body_' . $type;
4673 }
4674
4675 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4676 wfMessage( $message,
4677 $this->getRequest()->getIP(),
4678 $this->getName(),
4679 $url,
4680 $wgLang->userTimeAndDate( $expiration, $this ),
4681 $invalidateURL,
4682 $wgLang->userDate( $expiration, $this ),
4683 $wgLang->userTime( $expiration, $this ) )->text() );
4684 }
4685
4686 /**
4687 * Send an e-mail to this user's account. Does not check for
4688 * confirmed status or validity.
4689 *
4690 * @param string $subject Message subject
4691 * @param string $body Message body
4692 * @param User|null $from Optional sending user; if unspecified, default
4693 * $wgPasswordSender will be used.
4694 * @param string|null $replyto Reply-To address
4695 * @return Status
4696 */
4697 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4698 global $wgPasswordSender;
4699
4700 if ( $from instanceof User ) {
4701 $sender = MailAddress::newFromUser( $from );
4702 } else {
4703 $sender = new MailAddress( $wgPasswordSender,
4704 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4705 }
4706 $to = MailAddress::newFromUser( $this );
4707
4708 return UserMailer::send( $to, $sender, $subject, $body, [
4709 'replyTo' => $replyto,
4710 ] );
4711 }
4712
4713 /**
4714 * Generate, store, and return a new e-mail confirmation code.
4715 * A hash (unsalted, since it's used as a key) is stored.
4716 *
4717 * @note Call saveSettings() after calling this function to commit
4718 * this change to the database.
4719 *
4720 * @param string &$expiration Accepts the expiration time
4721 * @return string New token
4722 */
4723 protected function confirmationToken( &$expiration ) {
4724 global $wgUserEmailConfirmationTokenExpiry;
4725 $now = time();
4726 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
4727 $expiration = wfTimestamp( TS_MW, $expires );
4728 $this->load();
4729 $token = MWCryptRand::generateHex( 32 );
4730 $hash = md5( $token );
4731 $this->mEmailToken = $hash;
4732 $this->mEmailTokenExpires = $expiration;
4733 return $token;
4734 }
4735
4736 /**
4737 * Return a URL the user can use to confirm their email address.
4738 * @param string $token Accepts the email confirmation token
4739 * @return string New token URL
4740 */
4741 protected function confirmationTokenUrl( $token ) {
4742 return $this->getTokenUrl( 'ConfirmEmail', $token );
4743 }
4744
4745 /**
4746 * Return a URL the user can use to invalidate their email address.
4747 * @param string $token Accepts the email confirmation token
4748 * @return string New token URL
4749 */
4750 protected function invalidationTokenUrl( $token ) {
4751 return $this->getTokenUrl( 'InvalidateEmail', $token );
4752 }
4753
4754 /**
4755 * Internal function to format the e-mail validation/invalidation URLs.
4756 * This uses a quickie hack to use the
4757 * hardcoded English names of the Special: pages, for ASCII safety.
4758 *
4759 * @note Since these URLs get dropped directly into emails, using the
4760 * short English names avoids insanely long URL-encoded links, which
4761 * also sometimes can get corrupted in some browsers/mailers
4762 * (T8957 with Gmail and Internet Explorer).
4763 *
4764 * @param string $page Special page
4765 * @param string $token
4766 * @return string Formatted URL
4767 */
4768 protected function getTokenUrl( $page, $token ) {
4769 // Hack to bypass localization of 'Special:'
4770 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
4771 return $title->getCanonicalURL();
4772 }
4773
4774 /**
4775 * Mark the e-mail address confirmed.
4776 *
4777 * @note Call saveSettings() after calling this function to commit the change.
4778 *
4779 * @return bool
4780 */
4781 public function confirmEmail() {
4782 // Check if it's already confirmed, so we don't touch the database
4783 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4784 if ( !$this->isEmailConfirmed() ) {
4785 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4786 Hooks::run( 'ConfirmEmailComplete', [ $this ] );
4787 }
4788 return true;
4789 }
4790
4791 /**
4792 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4793 * address if it was already confirmed.
4794 *
4795 * @note Call saveSettings() after calling this function to commit the change.
4796 * @return bool Returns true
4797 */
4798 public function invalidateEmail() {
4799 $this->load();
4800 $this->mEmailToken = null;
4801 $this->mEmailTokenExpires = null;
4802 $this->setEmailAuthenticationTimestamp( null );
4803 $this->mEmail = '';
4804 Hooks::run( 'InvalidateEmailComplete', [ $this ] );
4805 return true;
4806 }
4807
4808 /**
4809 * Set the e-mail authentication timestamp.
4810 * @param string $timestamp TS_MW timestamp
4811 */
4812 public function setEmailAuthenticationTimestamp( $timestamp ) {
4813 $this->load();
4814 $this->mEmailAuthenticated = $timestamp;
4815 Hooks::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated ] );
4816 }
4817
4818 /**
4819 * Is this user allowed to send e-mails within limits of current
4820 * site configuration?
4821 * @return bool
4822 */
4823 public function canSendEmail() {
4824 global $wgEnableEmail, $wgEnableUserEmail;
4825 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4826 return false;
4827 }
4828 $canSend = $this->isEmailConfirmed();
4829 // Avoid PHP 7.1 warning of passing $this by reference
4830 $user = $this;
4831 Hooks::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4832 return $canSend;
4833 }
4834
4835 /**
4836 * Is this user allowed to receive e-mails within limits of current
4837 * site configuration?
4838 * @return bool
4839 */
4840 public function canReceiveEmail() {
4841 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4842 }
4843
4844 /**
4845 * Is this user's e-mail address valid-looking and confirmed within
4846 * limits of the current site configuration?
4847 *
4848 * @note If $wgEmailAuthentication is on, this may require the user to have
4849 * confirmed their address by returning a code or using a password
4850 * sent to the address from the wiki.
4851 *
4852 * @return bool
4853 */
4854 public function isEmailConfirmed() {
4855 global $wgEmailAuthentication;
4856 $this->load();
4857 // Avoid PHP 7.1 warning of passing $this by reference
4858 $user = $this;
4859 $confirmed = true;
4860 if ( Hooks::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4861 if ( $this->isAnon() ) {
4862 return false;
4863 }
4864 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4865 return false;
4866 }
4867 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4868 return false;
4869 }
4870 return true;
4871 } else {
4872 return $confirmed;
4873 }
4874 }
4875
4876 /**
4877 * Check whether there is an outstanding request for e-mail confirmation.
4878 * @return bool
4879 */
4880 public function isEmailConfirmationPending() {
4881 global $wgEmailAuthentication;
4882 return $wgEmailAuthentication &&
4883 !$this->isEmailConfirmed() &&
4884 $this->mEmailToken &&
4885 $this->mEmailTokenExpires > wfTimestamp();
4886 }
4887
4888 /**
4889 * Get the timestamp of account creation.
4890 *
4891 * @return string|bool|null Timestamp of account creation, false for
4892 * non-existent/anonymous user accounts, or null if existing account
4893 * but information is not in database.
4894 */
4895 public function getRegistration() {
4896 if ( $this->isAnon() ) {
4897 return false;
4898 }
4899 $this->load();
4900 return $this->mRegistration;
4901 }
4902
4903 /**
4904 * Get the timestamp of the first edit
4905 *
4906 * @return string|bool Timestamp of first edit, or false for
4907 * non-existent/anonymous user accounts.
4908 */
4909 public function getFirstEditTimestamp() {
4910 if ( $this->getId() == 0 ) {
4911 return false; // anons
4912 }
4913 $dbr = wfGetDB( DB_REPLICA );
4914 $actorWhere = ActorMigration::newMigration()->getWhere( $dbr, 'rev_user', $this );
4915 $time = $dbr->selectField(
4916 [ 'revision' ] + $actorWhere['tables'],
4917 'rev_timestamp',
4918 [ $actorWhere['conds'] ],
4919 __METHOD__,
4920 [ 'ORDER BY' => 'rev_timestamp ASC' ],
4921 $actorWhere['joins']
4922 );
4923 if ( !$time ) {
4924 return false; // no edits
4925 }
4926 return wfTimestamp( TS_MW, $time );
4927 }
4928
4929 /**
4930 * Get the permissions associated with a given list of groups
4931 *
4932 * @param array $groups Array of Strings List of internal group names
4933 * @return array Array of Strings List of permission key names for given groups combined
4934 */
4935 public static function getGroupPermissions( $groups ) {
4936 global $wgGroupPermissions, $wgRevokePermissions;
4937 $rights = [];
4938 // grant every granted permission first
4939 foreach ( $groups as $group ) {
4940 if ( isset( $wgGroupPermissions[$group] ) ) {
4941 $rights = array_merge( $rights,
4942 // array_filter removes empty items
4943 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4944 }
4945 }
4946 // now revoke the revoked permissions
4947 foreach ( $groups as $group ) {
4948 if ( isset( $wgRevokePermissions[$group] ) ) {
4949 $rights = array_diff( $rights,
4950 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4951 }
4952 }
4953 return array_unique( $rights );
4954 }
4955
4956 /**
4957 * Get all the groups who have a given permission
4958 *
4959 * @param string $role Role to check
4960 * @return array Array of Strings List of internal group names with the given permission
4961 */
4962 public static function getGroupsWithPermission( $role ) {
4963 global $wgGroupPermissions;
4964 $allowedGroups = [];
4965 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4966 if ( self::groupHasPermission( $group, $role ) ) {
4967 $allowedGroups[] = $group;
4968 }
4969 }
4970 return $allowedGroups;
4971 }
4972
4973 /**
4974 * Check, if the given group has the given permission
4975 *
4976 * If you're wanting to check whether all users have a permission, use
4977 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4978 * from anyone.
4979 *
4980 * @since 1.21
4981 * @param string $group Group to check
4982 * @param string $role Role to check
4983 * @return bool
4984 */
4985 public static function groupHasPermission( $group, $role ) {
4986 global $wgGroupPermissions, $wgRevokePermissions;
4987 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4988 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4989 }
4990
4991 /**
4992 * Check if all users may be assumed to have the given permission
4993 *
4994 * We generally assume so if the right is granted to '*' and isn't revoked
4995 * on any group. It doesn't attempt to take grants or other extension
4996 * limitations on rights into account in the general case, though, as that
4997 * would require it to always return false and defeat the purpose.
4998 * Specifically, session-based rights restrictions (such as OAuth or bot
4999 * passwords) are applied based on the current session.
5000 *
5001 * @since 1.22
5002 * @param string $right Right to check
5003 * @return bool
5004 */
5005 public static function isEveryoneAllowed( $right ) {
5006 global $wgGroupPermissions, $wgRevokePermissions;
5007 static $cache = [];
5008
5009 // Use the cached results, except in unit tests which rely on
5010 // being able change the permission mid-request
5011 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
5012 return $cache[$right];
5013 }
5014
5015 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
5016 $cache[$right] = false;
5017 return false;
5018 }
5019
5020 // If it's revoked anywhere, then everyone doesn't have it
5021 foreach ( $wgRevokePermissions as $rights ) {
5022 if ( isset( $rights[$right] ) && $rights[$right] ) {
5023 $cache[$right] = false;
5024 return false;
5025 }
5026 }
5027
5028 // Remove any rights that aren't allowed to the global-session user,
5029 // unless there are no sessions for this endpoint.
5030 if ( !defined( 'MW_NO_SESSION' ) ) {
5031 $allowedRights = SessionManager::getGlobalSession()->getAllowedUserRights();
5032 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
5033 $cache[$right] = false;
5034 return false;
5035 }
5036 }
5037
5038 // Allow extensions to say false
5039 if ( !Hooks::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
5040 $cache[$right] = false;
5041 return false;
5042 }
5043
5044 $cache[$right] = true;
5045 return true;
5046 }
5047
5048 /**
5049 * Get the localized descriptive name for a group, if it exists
5050 * @deprecated since 1.29 Use UserGroupMembership::getGroupName instead
5051 *
5052 * @param string $group Internal group name
5053 * @return string Localized descriptive group name
5054 */
5055 public static function getGroupName( $group ) {
5056 wfDeprecated( __METHOD__, '1.29' );
5057 return UserGroupMembership::getGroupName( $group );
5058 }
5059
5060 /**
5061 * Get the localized descriptive name for a member of a group, if it exists
5062 * @deprecated since 1.29 Use UserGroupMembership::getGroupMemberName instead
5063 *
5064 * @param string $group Internal group name
5065 * @param string $username Username for gender (since 1.19)
5066 * @return string Localized name for group member
5067 */
5068 public static function getGroupMember( $group, $username = '#' ) {
5069 wfDeprecated( __METHOD__, '1.29' );
5070 return UserGroupMembership::getGroupMemberName( $group, $username );
5071 }
5072
5073 /**
5074 * Return the set of defined explicit groups.
5075 * The implicit groups (by default *, 'user' and 'autoconfirmed')
5076 * are not included, as they are defined automatically, not in the database.
5077 * @return array Array of internal group names
5078 */
5079 public static function getAllGroups() {
5080 global $wgGroupPermissions, $wgRevokePermissions;
5081 return array_values( array_diff(
5082 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
5083 self::getImplicitGroups()
5084 ) );
5085 }
5086
5087 /**
5088 * Get a list of all available permissions.
5089 * @return string[] Array of permission names
5090 */
5091 public static function getAllRights() {
5092 if ( self::$mAllRights === false ) {
5093 global $wgAvailableRights;
5094 if ( count( $wgAvailableRights ) ) {
5095 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
5096 } else {
5097 self::$mAllRights = self::$mCoreRights;
5098 }
5099 Hooks::run( 'UserGetAllRights', [ &self::$mAllRights ] );
5100 }
5101 return self::$mAllRights;
5102 }
5103
5104 /**
5105 * Get a list of implicit groups
5106 * @return array Array of Strings Array of internal group names
5107 */
5108 public static function getImplicitGroups() {
5109 global $wgImplicitGroups;
5110
5111 $groups = $wgImplicitGroups;
5112 # Deprecated, use $wgImplicitGroups instead
5113 Hooks::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
5114
5115 return $groups;
5116 }
5117
5118 /**
5119 * Get the title of a page describing a particular group
5120 * @deprecated since 1.29 Use UserGroupMembership::getGroupPage instead
5121 *
5122 * @param string $group Internal group name
5123 * @return Title|bool Title of the page if it exists, false otherwise
5124 */
5125 public static function getGroupPage( $group ) {
5126 wfDeprecated( __METHOD__, '1.29' );
5127 return UserGroupMembership::getGroupPage( $group );
5128 }
5129
5130 /**
5131 * Create a link to the group in HTML, if available;
5132 * else return the group name.
5133 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
5134 * make the link yourself if you need custom text
5135 *
5136 * @param string $group Internal name of the group
5137 * @param string $text The text of the link
5138 * @return string HTML link to the group
5139 */
5140 public static function makeGroupLinkHTML( $group, $text = '' ) {
5141 wfDeprecated( __METHOD__, '1.29' );
5142
5143 if ( $text == '' ) {
5144 $text = UserGroupMembership::getGroupName( $group );
5145 }
5146 $title = UserGroupMembership::getGroupPage( $group );
5147 if ( $title ) {
5148 return MediaWikiServices::getInstance()
5149 ->getLinkRenderer()->makeLink( $title, $text );
5150 } else {
5151 return htmlspecialchars( $text );
5152 }
5153 }
5154
5155 /**
5156 * Create a link to the group in Wikitext, if available;
5157 * else return the group name.
5158 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
5159 * make the link yourself if you need custom text
5160 *
5161 * @param string $group Internal name of the group
5162 * @param string $text The text of the link
5163 * @return string Wikilink to the group
5164 */
5165 public static function makeGroupLinkWiki( $group, $text = '' ) {
5166 wfDeprecated( __METHOD__, '1.29' );
5167
5168 if ( $text == '' ) {
5169 $text = UserGroupMembership::getGroupName( $group );
5170 }
5171 $title = UserGroupMembership::getGroupPage( $group );
5172 if ( $title ) {
5173 $page = $title->getFullText();
5174 return "[[$page|$text]]";
5175 } else {
5176 return $text;
5177 }
5178 }
5179
5180 /**
5181 * Returns an array of the groups that a particular group can add/remove.
5182 *
5183 * @param string $group The group to check for whether it can add/remove
5184 * @return array Array( 'add' => array( addablegroups ),
5185 * 'remove' => array( removablegroups ),
5186 * 'add-self' => array( addablegroups to self),
5187 * 'remove-self' => array( removable groups from self) )
5188 */
5189 public static function changeableByGroup( $group ) {
5190 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
5191
5192 $groups = [
5193 'add' => [],
5194 'remove' => [],
5195 'add-self' => [],
5196 'remove-self' => []
5197 ];
5198
5199 if ( empty( $wgAddGroups[$group] ) ) {
5200 // Don't add anything to $groups
5201 } elseif ( $wgAddGroups[$group] === true ) {
5202 // You get everything
5203 $groups['add'] = self::getAllGroups();
5204 } elseif ( is_array( $wgAddGroups[$group] ) ) {
5205 $groups['add'] = $wgAddGroups[$group];
5206 }
5207
5208 // Same thing for remove
5209 if ( empty( $wgRemoveGroups[$group] ) ) {
5210 // Do nothing
5211 } elseif ( $wgRemoveGroups[$group] === true ) {
5212 $groups['remove'] = self::getAllGroups();
5213 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
5214 $groups['remove'] = $wgRemoveGroups[$group];
5215 }
5216
5217 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
5218 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
5219 foreach ( $wgGroupsAddToSelf as $key => $value ) {
5220 if ( is_int( $key ) ) {
5221 $wgGroupsAddToSelf['user'][] = $value;
5222 }
5223 }
5224 }
5225
5226 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
5227 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
5228 if ( is_int( $key ) ) {
5229 $wgGroupsRemoveFromSelf['user'][] = $value;
5230 }
5231 }
5232 }
5233
5234 // Now figure out what groups the user can add to him/herself
5235 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
5236 // Do nothing
5237 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
5238 // No idea WHY this would be used, but it's there
5239 $groups['add-self'] = self::getAllGroups();
5240 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
5241 $groups['add-self'] = $wgGroupsAddToSelf[$group];
5242 }
5243
5244 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
5245 // Do nothing
5246 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
5247 $groups['remove-self'] = self::getAllGroups();
5248 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
5249 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
5250 }
5251
5252 return $groups;
5253 }
5254
5255 /**
5256 * Returns an array of groups that this user can add and remove
5257 * @return array Array( 'add' => array( addablegroups ),
5258 * 'remove' => array( removablegroups ),
5259 * 'add-self' => array( addablegroups to self),
5260 * 'remove-self' => array( removable groups from self) )
5261 */
5262 public function changeableGroups() {
5263 if ( $this->isAllowed( 'userrights' ) ) {
5264 // This group gives the right to modify everything (reverse-
5265 // compatibility with old "userrights lets you change
5266 // everything")
5267 // Using array_merge to make the groups reindexed
5268 $all = array_merge( self::getAllGroups() );
5269 return [
5270 'add' => $all,
5271 'remove' => $all,
5272 'add-self' => [],
5273 'remove-self' => []
5274 ];
5275 }
5276
5277 // Okay, it's not so simple, we will have to go through the arrays
5278 $groups = [
5279 'add' => [],
5280 'remove' => [],
5281 'add-self' => [],
5282 'remove-self' => []
5283 ];
5284 $addergroups = $this->getEffectiveGroups();
5285
5286 foreach ( $addergroups as $addergroup ) {
5287 $groups = array_merge_recursive(
5288 $groups, $this->changeableByGroup( $addergroup )
5289 );
5290 $groups['add'] = array_unique( $groups['add'] );
5291 $groups['remove'] = array_unique( $groups['remove'] );
5292 $groups['add-self'] = array_unique( $groups['add-self'] );
5293 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5294 }
5295 return $groups;
5296 }
5297
5298 /**
5299 * Deferred version of incEditCountImmediate()
5300 *
5301 * This function, rather than incEditCountImmediate(), should be used for
5302 * most cases as it avoids potential deadlocks caused by concurrent editing.
5303 */
5304 public function incEditCount() {
5305 wfGetDB( DB_MASTER )->onTransactionPreCommitOrIdle(
5306 function () {
5307 $this->incEditCountImmediate();
5308 },
5309 __METHOD__
5310 );
5311 }
5312
5313 /**
5314 * Increment the user's edit-count field.
5315 * Will have no effect for anonymous users.
5316 * @since 1.26
5317 */
5318 public function incEditCountImmediate() {
5319 if ( $this->isAnon() ) {
5320 return;
5321 }
5322
5323 $dbw = wfGetDB( DB_MASTER );
5324 // No rows will be "affected" if user_editcount is NULL
5325 $dbw->update(
5326 'user',
5327 [ 'user_editcount=user_editcount+1' ],
5328 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5329 __METHOD__
5330 );
5331 // Lazy initialization check...
5332 if ( $dbw->affectedRows() == 0 ) {
5333 // Now here's a goddamn hack...
5334 $dbr = wfGetDB( DB_REPLICA );
5335 if ( $dbr !== $dbw ) {
5336 // If we actually have a replica DB server, the count is
5337 // at least one behind because the current transaction
5338 // has not been committed and replicated.
5339 $this->mEditCount = $this->initEditCount( 1 );
5340 } else {
5341 // But if DB_REPLICA is selecting the master, then the
5342 // count we just read includes the revision that was
5343 // just added in the working transaction.
5344 $this->mEditCount = $this->initEditCount();
5345 }
5346 } else {
5347 if ( $this->mEditCount === null ) {
5348 $this->getEditCount();
5349 $dbr = wfGetDB( DB_REPLICA );
5350 $this->mEditCount += ( $dbr !== $dbw ) ? 1 : 0;
5351 } else {
5352 $this->mEditCount++;
5353 }
5354 }
5355 // Edit count in user cache too
5356 $this->invalidateCache();
5357 }
5358
5359 /**
5360 * Initialize user_editcount from data out of the revision table
5361 *
5362 * @param int $add Edits to add to the count from the revision table
5363 * @return int Number of edits
5364 */
5365 protected function initEditCount( $add = 0 ) {
5366 // Pull from a replica DB to be less cruel to servers
5367 // Accuracy isn't the point anyway here
5368 $dbr = wfGetDB( DB_REPLICA );
5369 $actorWhere = ActorMigration::newMigration()->getWhere( $dbr, 'rev_user', $this );
5370 $count = (int)$dbr->selectField(
5371 [ 'revision' ] + $actorWhere['tables'],
5372 'COUNT(*)',
5373 [ $actorWhere['conds'] ],
5374 __METHOD__,
5375 [],
5376 $actorWhere['joins']
5377 );
5378 $count = $count + $add;
5379
5380 $dbw = wfGetDB( DB_MASTER );
5381 $dbw->update(
5382 'user',
5383 [ 'user_editcount' => $count ],
5384 [ 'user_id' => $this->getId() ],
5385 __METHOD__
5386 );
5387
5388 return $count;
5389 }
5390
5391 /**
5392 * Get the description of a given right
5393 *
5394 * @since 1.29
5395 * @param string $right Right to query
5396 * @return string Localized description of the right
5397 */
5398 public static function getRightDescription( $right ) {
5399 $key = "right-$right";
5400 $msg = wfMessage( $key );
5401 return $msg->isDisabled() ? $right : $msg->text();
5402 }
5403
5404 /**
5405 * Get the name of a given grant
5406 *
5407 * @since 1.29
5408 * @param string $grant Grant to query
5409 * @return string Localized name of the grant
5410 */
5411 public static function getGrantName( $grant ) {
5412 $key = "grant-$grant";
5413 $msg = wfMessage( $key );
5414 return $msg->isDisabled() ? $grant : $msg->text();
5415 }
5416
5417 /**
5418 * Add a newuser log entry for this user.
5419 * Before 1.19 the return value was always true.
5420 *
5421 * @deprecated since 1.27, AuthManager handles logging
5422 * @param string|bool $action Account creation type.
5423 * - String, one of the following values:
5424 * - 'create' for an anonymous user creating an account for himself.
5425 * This will force the action's performer to be the created user itself,
5426 * no matter the value of $wgUser
5427 * - 'create2' for a logged in user creating an account for someone else
5428 * - 'byemail' when the created user will receive its password by e-mail
5429 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5430 * - Boolean means whether the account was created by e-mail (deprecated):
5431 * - true will be converted to 'byemail'
5432 * - false will be converted to 'create' if this object is the same as
5433 * $wgUser and to 'create2' otherwise
5434 * @param string $reason User supplied reason
5435 * @return bool true
5436 */
5437 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5438 return true; // disabled
5439 }
5440
5441 /**
5442 * Add an autocreate newuser log entry for this user
5443 * Used by things like CentralAuth and perhaps other authplugins.
5444 * Consider calling addNewUserLogEntry() directly instead.
5445 *
5446 * @deprecated since 1.27, AuthManager handles logging
5447 * @return bool
5448 */
5449 public function addNewUserLogEntryAutoCreate() {
5450 $this->addNewUserLogEntry( 'autocreate' );
5451
5452 return true;
5453 }
5454
5455 /**
5456 * Load the user options either from cache, the database or an array
5457 *
5458 * @param array|null $data Rows for the current user out of the user_properties table
5459 */
5460 protected function loadOptions( $data = null ) {
5461 $this->load();
5462
5463 if ( $this->mOptionsLoaded ) {
5464 return;
5465 }
5466
5467 $this->mOptions = self::getDefaultOptions();
5468
5469 if ( !$this->getId() ) {
5470 // For unlogged-in users, load language/variant options from request.
5471 // There's no need to do it for logged-in users: they can set preferences,
5472 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5473 // so don't override user's choice (especially when the user chooses site default).
5474 $variant = MediaWikiServices::getInstance()->getContentLanguage()->getDefaultVariant();
5475 $this->mOptions['variant'] = $variant;
5476 $this->mOptions['language'] = $variant;
5477 $this->mOptionsLoaded = true;
5478 return;
5479 }
5480
5481 // Maybe load from the object
5482 if ( !is_null( $this->mOptionOverrides ) ) {
5483 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5484 foreach ( $this->mOptionOverrides as $key => $value ) {
5485 $this->mOptions[$key] = $value;
5486 }
5487 } else {
5488 if ( !is_array( $data ) ) {
5489 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5490 // Load from database
5491 $dbr = ( $this->queryFlagsUsed & self::READ_LATEST )
5492 ? wfGetDB( DB_MASTER )
5493 : wfGetDB( DB_REPLICA );
5494
5495 $res = $dbr->select(
5496 'user_properties',
5497 [ 'up_property', 'up_value' ],
5498 [ 'up_user' => $this->getId() ],
5499 __METHOD__
5500 );
5501
5502 $this->mOptionOverrides = [];
5503 $data = [];
5504 foreach ( $res as $row ) {
5505 // Convert '0' to 0. PHP's boolean conversion considers them both
5506 // false, but e.g. JavaScript considers the former as true.
5507 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5508 // and convert all values here.
5509 if ( $row->up_value === '0' ) {
5510 $row->up_value = 0;
5511 }
5512 $data[$row->up_property] = $row->up_value;
5513 }
5514 }
5515
5516 foreach ( $data as $property => $value ) {
5517 $this->mOptionOverrides[$property] = $value;
5518 $this->mOptions[$property] = $value;
5519 }
5520 }
5521
5522 // Replace deprecated language codes
5523 $this->mOptions['language'] = LanguageCode::replaceDeprecatedCodes(
5524 $this->mOptions['language']
5525 );
5526
5527 $this->mOptionsLoaded = true;
5528
5529 Hooks::run( 'UserLoadOptions', [ $this, &$this->mOptions ] );
5530 }
5531
5532 /**
5533 * Saves the non-default options for this user, as previously set e.g. via
5534 * setOption(), in the database's "user_properties" (preferences) table.
5535 * Usually used via saveSettings().
5536 */
5537 protected function saveOptions() {
5538 $this->loadOptions();
5539
5540 // Not using getOptions(), to keep hidden preferences in database
5541 $saveOptions = $this->mOptions;
5542
5543 // Allow hooks to abort, for instance to save to a global profile.
5544 // Reset options to default state before saving.
5545 if ( !Hooks::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5546 return;
5547 }
5548
5549 $userId = $this->getId();
5550
5551 $insert_rows = []; // all the new preference rows
5552 foreach ( $saveOptions as $key => $value ) {
5553 // Don't bother storing default values
5554 $defaultOption = self::getDefaultOption( $key );
5555 if ( ( $defaultOption === null && $value !== false && $value !== null )
5556 || $value != $defaultOption
5557 ) {
5558 $insert_rows[] = [
5559 'up_user' => $userId,
5560 'up_property' => $key,
5561 'up_value' => $value,
5562 ];
5563 }
5564 }
5565
5566 $dbw = wfGetDB( DB_MASTER );
5567
5568 $res = $dbw->select( 'user_properties',
5569 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__ );
5570
5571 // Find prior rows that need to be removed or updated. These rows will
5572 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5573 $keysDelete = [];
5574 foreach ( $res as $row ) {
5575 if ( !isset( $saveOptions[$row->up_property] )
5576 || strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
5577 ) {
5578 $keysDelete[] = $row->up_property;
5579 }
5580 }
5581
5582 if ( count( $keysDelete ) ) {
5583 // Do the DELETE by PRIMARY KEY for prior rows.
5584 // In the past a very large portion of calls to this function are for setting
5585 // 'rememberpassword' for new accounts (a preference that has since been removed).
5586 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5587 // caused gap locks on [max user ID,+infinity) which caused high contention since
5588 // updates would pile up on each other as they are for higher (newer) user IDs.
5589 // It might not be necessary these days, but it shouldn't hurt either.
5590 $dbw->delete( 'user_properties',
5591 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__ );
5592 }
5593 // Insert the new preference rows
5594 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, [ 'IGNORE' ] );
5595 }
5596
5597 /**
5598 * Return the list of user fields that should be selected to create
5599 * a new user object.
5600 * @deprecated since 1.31, use self::getQueryInfo() instead.
5601 * @return array
5602 */
5603 public static function selectFields() {
5604 wfDeprecated( __METHOD__, '1.31' );
5605 return [
5606 'user_id',
5607 'user_name',
5608 'user_real_name',
5609 'user_email',
5610 'user_touched',
5611 'user_token',
5612 'user_email_authenticated',
5613 'user_email_token',
5614 'user_email_token_expires',
5615 'user_registration',
5616 'user_editcount',
5617 ];
5618 }
5619
5620 /**
5621 * Return the tables, fields, and join conditions to be selected to create
5622 * a new user object.
5623 * @since 1.31
5624 * @return array With three keys:
5625 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
5626 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
5627 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
5628 */
5629 public static function getQueryInfo() {
5630 global $wgActorTableSchemaMigrationStage;
5631
5632 $ret = [
5633 'tables' => [ 'user' ],
5634 'fields' => [
5635 'user_id',
5636 'user_name',
5637 'user_real_name',
5638 'user_email',
5639 'user_touched',
5640 'user_token',
5641 'user_email_authenticated',
5642 'user_email_token',
5643 'user_email_token_expires',
5644 'user_registration',
5645 'user_editcount',
5646 ],
5647 'joins' => [],
5648 ];
5649 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD ) {
5650 $ret['tables']['user_actor'] = 'actor';
5651 $ret['fields'][] = 'user_actor.actor_id';
5652 $ret['joins']['user_actor'] = [
5653 $wgActorTableSchemaMigrationStage === MIGRATION_NEW ? 'JOIN' : 'LEFT JOIN',
5654 [ 'user_actor.actor_user = user_id' ]
5655 ];
5656 }
5657 return $ret;
5658 }
5659
5660 /**
5661 * Factory function for fatal permission-denied errors
5662 *
5663 * @since 1.22
5664 * @param string $permission User right required
5665 * @return Status
5666 */
5667 static function newFatalPermissionDeniedStatus( $permission ) {
5668 global $wgLang;
5669
5670 $groups = [];
5671 foreach ( self::getGroupsWithPermission( $permission ) as $group ) {
5672 $groups[] = UserGroupMembership::getLink( $group, RequestContext::getMain(), 'wiki' );
5673 }
5674
5675 if ( $groups ) {
5676 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5677 } else {
5678 return Status::newFatal( 'badaccess-group0' );
5679 }
5680 }
5681
5682 /**
5683 * Get a new instance of this user that was loaded from the master via a locking read
5684 *
5685 * Use this instead of the main context User when updating that user. This avoids races
5686 * where that user was loaded from a replica DB or even the master but without proper locks.
5687 *
5688 * @return User|null Returns null if the user was not found in the DB
5689 * @since 1.27
5690 */
5691 public function getInstanceForUpdate() {
5692 if ( !$this->getId() ) {
5693 return null; // anon
5694 }
5695
5696 $user = self::newFromId( $this->getId() );
5697 if ( !$user->loadFromId( self::READ_EXCLUSIVE ) ) {
5698 return null;
5699 }
5700
5701 return $user;
5702 }
5703
5704 /**
5705 * Checks if two user objects point to the same user.
5706 *
5707 * @since 1.25 ; takes a UserIdentity instead of a User since 1.32
5708 * @param UserIdentity $user
5709 * @return bool
5710 */
5711 public function equals( UserIdentity $user ) {
5712 // XXX it's not clear whether central ID providers are supposed to obey this
5713 return $this->getName() === $user->getName();
5714 }
5715 }