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