Merge "skins: Remove 'usemsgcache' and deprecate getDynamicStylesheetQuery"
[lhc/web/wiklou.git] / includes / user / User.php
1 <?php
2 /**
3 * Implements the User class for the %MediaWiki software.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 use MediaWiki\MediaWikiServices;
24 use MediaWiki\Session\SessionManager;
25 use MediaWiki\Session\Token;
26 use MediaWiki\Auth\AuthManager;
27 use MediaWiki\Auth\AuthenticationResponse;
28 use MediaWiki\Auth\AuthenticationRequest;
29 use MediaWiki\User\UserIdentity;
30 use MediaWiki\Logger\LoggerFactory;
31 use Wikimedia\IPSet;
32 use Wikimedia\ScopedCallback;
33 use Wikimedia\Rdbms\Database;
34 use Wikimedia\Rdbms\DBExpectedError;
35 use Wikimedia\Rdbms\IDatabase;
36
37 /**
38 * The User object encapsulates all of the user-specific settings (user_id,
39 * name, rights, email address, options, last login time). Client
40 * classes use the getXXX() functions to access these fields. These functions
41 * do all the work of determining whether the user is logged in,
42 * whether the requested option can be satisfied from cookies or
43 * whether a database query is needed. Most of the settings needed
44 * for rendering normal pages are set in the cookie to minimize use
45 * of the database.
46 */
47 class User implements IDBAccessObject, UserIdentity {
48 /**
49 * @const int Number of characters in user_token field.
50 */
51 const TOKEN_LENGTH = 32;
52
53 /**
54 * @const string An invalid value for user_token
55 */
56 const INVALID_TOKEN = '*** INVALID ***';
57
58 /**
59 * Global constant made accessible as class constants so that autoloader
60 * magic can be used.
61 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
62 */
63 const EDIT_TOKEN_SUFFIX = Token::SUFFIX;
64
65 /**
66 * @const int Serialized record version.
67 */
68 const VERSION = 12;
69
70 /**
71 * Exclude user options that are set to their default value.
72 * @since 1.25
73 */
74 const GETOPTIONS_EXCLUDE_DEFAULTS = 1;
75
76 /**
77 * @since 1.27
78 */
79 const CHECK_USER_RIGHTS = true;
80
81 /**
82 * @since 1.27
83 */
84 const IGNORE_USER_RIGHTS = false;
85
86 /**
87 * Array of Strings List of member variables which are saved to the
88 * shared cache (memcached). Any operation which changes the
89 * corresponding database fields must call a cache-clearing function.
90 * @showinitializer
91 */
92 protected static $mCacheVars = [
93 // user table
94 'mId',
95 'mName',
96 'mRealName',
97 'mEmail',
98 'mTouched',
99 'mToken',
100 'mEmailAuthenticated',
101 'mEmailToken',
102 'mEmailTokenExpires',
103 'mRegistration',
104 'mEditCount',
105 // user_groups table
106 'mGroupMemberships',
107 // user_properties table
108 'mOptionOverrides',
109 // actor table
110 'mActorId',
111 ];
112
113 /**
114 * Array of Strings Core rights.
115 * Each of these should have a corresponding message of the form
116 * "right-$right".
117 * @showinitializer
118 */
119 protected static $mCoreRights = [
120 'apihighlimits',
121 'applychangetags',
122 'autoconfirmed',
123 'autocreateaccount',
124 'autopatrol',
125 'bigdelete',
126 'block',
127 'blockemail',
128 'bot',
129 'browsearchive',
130 'changetags',
131 'createaccount',
132 'createpage',
133 'createtalk',
134 'delete',
135 'deletechangetags',
136 'deletedhistory',
137 'deletedtext',
138 'deletelogentry',
139 'deleterevision',
140 'edit',
141 'editcontentmodel',
142 'editinterface',
143 'editprotected',
144 'editmyoptions',
145 'editmyprivateinfo',
146 'editmyusercss',
147 'editmyuserjson',
148 'editmyuserjs',
149 'editmywatchlist',
150 'editsemiprotected',
151 'editsitecss',
152 'editsitejson',
153 'editsitejs',
154 'editusercss',
155 'edituserjson',
156 'edituserjs',
157 'hideuser',
158 'import',
159 'importupload',
160 'ipblock-exempt',
161 'managechangetags',
162 'markbotedits',
163 'mergehistory',
164 'minoredit',
165 'move',
166 'movefile',
167 'move-categorypages',
168 'move-rootuserpages',
169 'move-subpages',
170 'nominornewtalk',
171 'noratelimit',
172 'override-export-depth',
173 'pagelang',
174 'patrol',
175 'patrolmarks',
176 'protect',
177 'purge',
178 'read',
179 'reupload',
180 'reupload-own',
181 'reupload-shared',
182 'rollback',
183 'sendemail',
184 'siteadmin',
185 'suppressionlog',
186 'suppressredirect',
187 'suppressrevision',
188 'unblockself',
189 'undelete',
190 'unwatchedpages',
191 'upload',
192 'upload_by_url',
193 'userrights',
194 'userrights-interwiki',
195 'viewmyprivateinfo',
196 'viewmywatchlist',
197 'viewsuppressed',
198 'writeapi',
199 ];
200
201 /**
202 * String Cached results of getAllRights()
203 */
204 protected static $mAllRights = false;
205
206 /** Cache variables */
207 // @{
208 /** @var int */
209 public $mId;
210 /** @var string */
211 public $mName;
212 /** @var int|null */
213 protected $mActorId;
214 /** @var string */
215 public $mRealName;
216
217 /** @var string */
218 public $mEmail;
219 /** @var string TS_MW timestamp from the DB */
220 public $mTouched;
221 /** @var string TS_MW timestamp from cache */
222 protected $mQuickTouched;
223 /** @var string */
224 protected $mToken;
225 /** @var string */
226 public $mEmailAuthenticated;
227 /** @var string */
228 protected $mEmailToken;
229 /** @var string */
230 protected $mEmailTokenExpires;
231 /** @var string */
232 protected $mRegistration;
233 /** @var int */
234 protected $mEditCount;
235 /** @var UserGroupMembership[] Associative array of (group name => UserGroupMembership object) */
236 protected $mGroupMemberships;
237 /** @var array */
238 protected $mOptionOverrides;
239 // @}
240
241 /**
242 * Bool Whether the cache variables have been loaded.
243 */
244 // @{
245 public $mOptionsLoaded;
246
247 /**
248 * Array with already loaded items or true if all items have been loaded.
249 */
250 protected $mLoadedItems = [];
251 // @}
252
253 /**
254 * String Initialization data source if mLoadedItems!==true. May be one of:
255 * - 'defaults' anonymous user initialised from class defaults
256 * - 'name' initialise from mName
257 * - 'id' initialise from mId
258 * - 'actor' initialise from mActorId
259 * - 'session' log in from session if possible
260 *
261 * Use the User::newFrom*() family of functions to set this.
262 */
263 public $mFrom;
264
265 /**
266 * Lazy-initialized variables, invalidated with clearInstanceCache
267 */
268 protected $mNewtalk;
269 /** @var string */
270 protected $mDatePreference;
271 /** @var string */
272 public $mBlockedby;
273 /** @var string */
274 protected $mHash;
275 /** @var array */
276 public $mRights;
277 /** @var string */
278 protected $mBlockreason;
279 /** @var array */
280 protected $mEffectiveGroups;
281 /** @var array */
282 protected $mImplicitGroups;
283 /** @var array */
284 protected $mFormerGroups;
285 /** @var Block */
286 protected $mGlobalBlock;
287 /** @var bool */
288 protected $mLocked;
289 /** @var bool */
290 public $mHideName;
291 /** @var array */
292 public $mOptions;
293
294 /** @var WebRequest */
295 private $mRequest;
296
297 /** @var Block */
298 public $mBlock;
299
300 /** @var bool */
301 protected $mAllowUsertalk;
302
303 /** @var Block */
304 private $mBlockedFromCreateAccount = false;
305
306 /** @var int User::READ_* constant bitfield used to load data */
307 protected $queryFlagsUsed = self::READ_NORMAL;
308
309 public static $idCacheByName = [];
310
311 /**
312 * Lightweight constructor for an anonymous user.
313 * Use the User::newFrom* factory functions for other kinds of users.
314 *
315 * @see newFromName()
316 * @see newFromId()
317 * @see newFromActorId()
318 * @see newFromConfirmationCode()
319 * @see newFromSession()
320 * @see newFromRow()
321 */
322 public function __construct() {
323 $this->clearInstanceCache( 'defaults' );
324 }
325
326 /**
327 * @return string
328 */
329 public function __toString() {
330 return (string)$this->getName();
331 }
332
333 /**
334 * Test if it's safe to load this User object.
335 *
336 * You should typically check this before using $wgUser or
337 * RequestContext::getUser in a method that might be called before the
338 * system has been fully initialized. If the object is unsafe, you should
339 * use an anonymous user:
340 * \code
341 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
342 * \endcode
343 *
344 * @since 1.27
345 * @return bool
346 */
347 public function isSafeToLoad() {
348 global $wgFullyInitialised;
349
350 // The user is safe to load if:
351 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
352 // * mLoadedItems === true (already loaded)
353 // * mFrom !== 'session' (sessions not involved at all)
354
355 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
356 $this->mLoadedItems === true || $this->mFrom !== 'session';
357 }
358
359 /**
360 * Load the user table data for this object from the source given by mFrom.
361 *
362 * @param int $flags User::READ_* constant bitfield
363 */
364 public function load( $flags = self::READ_NORMAL ) {
365 global $wgFullyInitialised;
366
367 if ( $this->mLoadedItems === true ) {
368 return;
369 }
370
371 // Set it now to avoid infinite recursion in accessors
372 $oldLoadedItems = $this->mLoadedItems;
373 $this->mLoadedItems = true;
374 $this->queryFlagsUsed = $flags;
375
376 // If this is called too early, things are likely to break.
377 if ( !$wgFullyInitialised && $this->mFrom === 'session' ) {
378 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
379 ->warning( 'User::loadFromSession called before the end of Setup.php', [
380 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
381 ] );
382 $this->loadDefaults();
383 $this->mLoadedItems = $oldLoadedItems;
384 return;
385 }
386
387 switch ( $this->mFrom ) {
388 case 'defaults':
389 $this->loadDefaults();
390 break;
391 case 'name':
392 // Make sure this thread sees its own changes
393 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
394 if ( $lb->hasOrMadeRecentMasterChanges() ) {
395 $flags |= self::READ_LATEST;
396 $this->queryFlagsUsed = $flags;
397 }
398
399 $this->mId = self::idFromName( $this->mName, $flags );
400 if ( !$this->mId ) {
401 // Nonexistent user placeholder object
402 $this->loadDefaults( $this->mName );
403 } else {
404 $this->loadFromId( $flags );
405 }
406 break;
407 case 'id':
408 // Make sure this thread sees its own changes, if the ID isn't 0
409 if ( $this->mId != 0 ) {
410 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
411 if ( $lb->hasOrMadeRecentMasterChanges() ) {
412 $flags |= self::READ_LATEST;
413 $this->queryFlagsUsed = $flags;
414 }
415 }
416
417 $this->loadFromId( $flags );
418 break;
419 case 'actor':
420 // Make sure this thread sees its own changes
421 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
422 if ( $lb->hasOrMadeRecentMasterChanges() ) {
423 $flags |= self::READ_LATEST;
424 $this->queryFlagsUsed = $flags;
425 }
426
427 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
428 $row = wfGetDB( $index )->selectRow(
429 'actor',
430 [ 'actor_user', 'actor_name' ],
431 [ 'actor_id' => $this->mActorId ],
432 __METHOD__,
433 $options
434 );
435
436 if ( !$row ) {
437 // Ugh.
438 $this->loadDefaults();
439 } elseif ( $row->actor_user ) {
440 $this->mId = $row->actor_user;
441 $this->loadFromId( $flags );
442 } else {
443 $this->loadDefaults( $row->actor_name );
444 }
445 break;
446 case 'session':
447 if ( !$this->loadFromSession() ) {
448 // Loading from session failed. Load defaults.
449 $this->loadDefaults();
450 }
451 Hooks::run( 'UserLoadAfterLoadFromSession', [ $this ] );
452 break;
453 default:
454 throw new UnexpectedValueException(
455 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
456 }
457 }
458
459 /**
460 * Load user table data, given mId has already been set.
461 * @param int $flags User::READ_* constant bitfield
462 * @return bool False if the ID does not exist, true otherwise
463 */
464 public function loadFromId( $flags = self::READ_NORMAL ) {
465 if ( $this->mId == 0 ) {
466 // Anonymous users are not in the database (don't need cache)
467 $this->loadDefaults();
468 return false;
469 }
470
471 // Try cache (unless this needs data from the master DB).
472 // NOTE: if this thread called saveSettings(), the cache was cleared.
473 $latest = DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST );
474 if ( $latest ) {
475 if ( !$this->loadFromDatabase( $flags ) ) {
476 // Can't load from ID
477 return false;
478 }
479 } else {
480 $this->loadFromCache();
481 }
482
483 $this->mLoadedItems = true;
484 $this->queryFlagsUsed = $flags;
485
486 return true;
487 }
488
489 /**
490 * @since 1.27
491 * @param string $wikiId
492 * @param int $userId
493 */
494 public static function purge( $wikiId, $userId ) {
495 $cache = ObjectCache::getMainWANInstance();
496 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
497 $cache->delete( $key );
498 }
499
500 /**
501 * @since 1.27
502 * @param WANObjectCache $cache
503 * @return string
504 */
505 protected function getCacheKey( WANObjectCache $cache ) {
506 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId );
507 }
508
509 /**
510 * @param WANObjectCache $cache
511 * @return string[]
512 * @since 1.28
513 */
514 public function getMutableCacheKeys( WANObjectCache $cache ) {
515 $id = $this->getId();
516
517 return $id ? [ $this->getCacheKey( $cache ) ] : [];
518 }
519
520 /**
521 * Load user data from shared cache, given mId has already been set.
522 *
523 * @return bool True
524 * @since 1.25
525 */
526 protected function loadFromCache() {
527 $cache = ObjectCache::getMainWANInstance();
528 $data = $cache->getWithSetCallback(
529 $this->getCacheKey( $cache ),
530 $cache::TTL_HOUR,
531 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
532 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
533 wfDebug( "User: cache miss for user {$this->mId}\n" );
534
535 $this->loadFromDatabase( self::READ_NORMAL );
536 $this->loadGroups();
537 $this->loadOptions();
538
539 $data = [];
540 foreach ( self::$mCacheVars as $name ) {
541 $data[$name] = $this->$name;
542 }
543
544 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX, $this->mTouched ), $ttl );
545
546 // if a user group membership is about to expire, the cache needs to
547 // expire at that time (T163691)
548 foreach ( $this->mGroupMemberships as $ugm ) {
549 if ( $ugm->getExpiry() ) {
550 $secondsUntilExpiry = wfTimestamp( TS_UNIX, $ugm->getExpiry() ) - time();
551 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
552 $ttl = $secondsUntilExpiry;
553 }
554 }
555 }
556
557 return $data;
558 },
559 [ 'pcTTL' => $cache::TTL_PROC_LONG, 'version' => self::VERSION ]
560 );
561
562 // Restore from cache
563 foreach ( self::$mCacheVars as $name ) {
564 $this->$name = $data[$name];
565 }
566
567 return true;
568 }
569
570 /** @name newFrom*() static factory methods */
571 // @{
572
573 /**
574 * Static factory method for creation from username.
575 *
576 * This is slightly less efficient than newFromId(), so use newFromId() if
577 * you have both an ID and a name handy.
578 *
579 * @param string $name Username, validated by Title::newFromText()
580 * @param string|bool $validate Validate username. Takes the same parameters as
581 * User::getCanonicalName(), except that true is accepted as an alias
582 * for 'valid', for BC.
583 *
584 * @return User|bool User object, or false if the username is invalid
585 * (e.g. if it contains illegal characters or is an IP address). If the
586 * username is not present in the database, the result will be a user object
587 * with a name, zero user ID and default settings.
588 */
589 public static function newFromName( $name, $validate = 'valid' ) {
590 if ( $validate === true ) {
591 $validate = 'valid';
592 }
593 $name = self::getCanonicalName( $name, $validate );
594 if ( $name === false ) {
595 return false;
596 } else {
597 // Create unloaded user object
598 $u = new User;
599 $u->mName = $name;
600 $u->mFrom = 'name';
601 $u->setItemLoaded( 'name' );
602 return $u;
603 }
604 }
605
606 /**
607 * Static factory method for creation from a given user ID.
608 *
609 * @param int $id Valid user ID
610 * @return User The corresponding User object
611 */
612 public static function newFromId( $id ) {
613 $u = new User;
614 $u->mId = $id;
615 $u->mFrom = 'id';
616 $u->setItemLoaded( 'id' );
617 return $u;
618 }
619
620 /**
621 * Static factory method for creation from a given actor ID.
622 *
623 * @since 1.31
624 * @param int $id Valid actor ID
625 * @return User The corresponding User object
626 */
627 public static function newFromActorId( $id ) {
628 global $wgActorTableSchemaMigrationStage;
629
630 if ( $wgActorTableSchemaMigrationStage <= MIGRATION_OLD ) {
631 throw new BadMethodCallException(
632 'Cannot use ' . __METHOD__ . ' when $wgActorTableSchemaMigrationStage is MIGRATION_OLD'
633 );
634 }
635
636 $u = new User;
637 $u->mActorId = $id;
638 $u->mFrom = 'actor';
639 $u->setItemLoaded( 'actor' );
640 return $u;
641 }
642
643 /**
644 * Returns a User object corresponding to the given UserIdentity.
645 *
646 * @since 1.32
647 *
648 * @param UserIdentity $identity
649 *
650 * @return User
651 */
652 public static function newFromIdentity( UserIdentity $identity ) {
653 if ( $identity instanceof User ) {
654 return $identity;
655 }
656
657 return self::newFromAnyId(
658 $identity->getId() === 0 ? null : $identity->getId(),
659 $identity->getName() === '' ? null : $identity->getName(),
660 $identity->getActorId() === 0 ? null : $identity->getActorId()
661 );
662 }
663
664 /**
665 * Static factory method for creation from an ID, name, and/or actor ID
666 *
667 * This does not check that the ID, name, and actor ID all correspond to
668 * the same user.
669 *
670 * @since 1.31
671 * @param int|null $userId User ID, if known
672 * @param string|null $userName User name, if known
673 * @param int|null $actorId Actor ID, if known
674 * @return User
675 */
676 public static function newFromAnyId( $userId, $userName, $actorId ) {
677 global $wgActorTableSchemaMigrationStage;
678
679 $user = new User;
680 $user->mFrom = 'defaults';
681
682 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD && $actorId !== null ) {
683 $user->mActorId = (int)$actorId;
684 if ( $user->mActorId !== 0 ) {
685 $user->mFrom = 'actor';
686 }
687 $user->setItemLoaded( 'actor' );
688 }
689
690 if ( $userName !== null && $userName !== '' ) {
691 $user->mName = $userName;
692 $user->mFrom = 'name';
693 $user->setItemLoaded( 'name' );
694 }
695
696 if ( $userId !== null ) {
697 $user->mId = (int)$userId;
698 if ( $user->mId !== 0 ) {
699 $user->mFrom = 'id';
700 }
701 $user->setItemLoaded( 'id' );
702 }
703
704 if ( $user->mFrom === 'defaults' ) {
705 throw new InvalidArgumentException(
706 'Cannot create a user with no name, no ID, and no actor ID'
707 );
708 }
709
710 return $user;
711 }
712
713 /**
714 * Factory method to fetch whichever user has a given email confirmation code.
715 * This code is generated when an account is created or its e-mail address
716 * has changed.
717 *
718 * If the code is invalid or has expired, returns NULL.
719 *
720 * @param string $code Confirmation code
721 * @param int $flags User::READ_* bitfield
722 * @return User|null
723 */
724 public static function newFromConfirmationCode( $code, $flags = 0 ) {
725 $db = ( $flags & self::READ_LATEST ) == self::READ_LATEST
726 ? wfGetDB( DB_MASTER )
727 : wfGetDB( DB_REPLICA );
728
729 $id = $db->selectField(
730 'user',
731 'user_id',
732 [
733 'user_email_token' => md5( $code ),
734 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
735 ]
736 );
737
738 return $id ? self::newFromId( $id ) : null;
739 }
740
741 /**
742 * Create a new user object using data from session. If the login
743 * credentials are invalid, the result is an anonymous user.
744 *
745 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
746 * @return User
747 */
748 public static function newFromSession( WebRequest $request = null ) {
749 $user = new User;
750 $user->mFrom = 'session';
751 $user->mRequest = $request;
752 return $user;
753 }
754
755 /**
756 * Create a new user object from a user row.
757 * The row should have the following fields from the user table in it:
758 * - either user_name or user_id to load further data if needed (or both)
759 * - user_real_name
760 * - all other fields (email, etc.)
761 * It is useless to provide the remaining fields if either user_id,
762 * user_name and user_real_name are not provided because the whole row
763 * will be loaded once more from the database when accessing them.
764 *
765 * @param stdClass $row A row from the user table
766 * @param array|null $data Further data to load into the object
767 * (see User::loadFromRow for valid keys)
768 * @return User
769 */
770 public static function newFromRow( $row, $data = null ) {
771 $user = new User;
772 $user->loadFromRow( $row, $data );
773 return $user;
774 }
775
776 /**
777 * Static factory method for creation of a "system" user from username.
778 *
779 * A "system" user is an account that's used to attribute logged actions
780 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
781 * might include the 'Maintenance script' or 'Conversion script' accounts
782 * used by various scripts in the maintenance/ directory or accounts such
783 * as 'MediaWiki message delivery' used by the MassMessage extension.
784 *
785 * This can optionally create the user if it doesn't exist, and "steal" the
786 * account if it does exist.
787 *
788 * "Stealing" an existing user is intended to make it impossible for normal
789 * authentication processes to use the account, effectively disabling the
790 * account for normal use:
791 * - Email is invalidated, to prevent account recovery by emailing a
792 * temporary password and to disassociate the account from the existing
793 * human.
794 * - The token is set to a magic invalid value, to kill existing sessions
795 * and to prevent $this->setToken() calls from resetting the token to a
796 * valid value.
797 * - SessionManager is instructed to prevent new sessions for the user, to
798 * do things like deauthorizing OAuth consumers.
799 * - AuthManager is instructed to revoke access, to invalidate or remove
800 * passwords and other credentials.
801 *
802 * @param string $name Username
803 * @param array $options Options are:
804 * - validate: As for User::getCanonicalName(), default 'valid'
805 * - create: Whether to create the user if it doesn't already exist, default true
806 * - steal: Whether to "disable" the account for normal use if it already
807 * exists, default false
808 * @return User|null
809 * @since 1.27
810 */
811 public static function newSystemUser( $name, $options = [] ) {
812 $options += [
813 'validate' => 'valid',
814 'create' => true,
815 'steal' => false,
816 ];
817
818 $name = self::getCanonicalName( $name, $options['validate'] );
819 if ( $name === false ) {
820 return null;
821 }
822
823 $dbr = wfGetDB( DB_REPLICA );
824 $userQuery = self::getQueryInfo();
825 $row = $dbr->selectRow(
826 $userQuery['tables'],
827 $userQuery['fields'],
828 [ 'user_name' => $name ],
829 __METHOD__,
830 [],
831 $userQuery['joins']
832 );
833 if ( !$row ) {
834 // Try the master database...
835 $dbw = wfGetDB( DB_MASTER );
836 $row = $dbw->selectRow(
837 $userQuery['tables'],
838 $userQuery['fields'],
839 [ 'user_name' => $name ],
840 __METHOD__,
841 [],
842 $userQuery['joins']
843 );
844 }
845
846 if ( !$row ) {
847 // No user. Create it?
848 return $options['create']
849 ? self::createNew( $name, [ 'token' => self::INVALID_TOKEN ] )
850 : null;
851 }
852
853 $user = self::newFromRow( $row );
854
855 // A user is considered to exist as a non-system user if it can
856 // authenticate, or has an email set, or has a non-invalid token.
857 if ( $user->mEmail || $user->mToken !== self::INVALID_TOKEN ||
858 AuthManager::singleton()->userCanAuthenticate( $name )
859 ) {
860 // User exists. Steal it?
861 if ( !$options['steal'] ) {
862 return null;
863 }
864
865 AuthManager::singleton()->revokeAccessForUser( $name );
866
867 $user->invalidateEmail();
868 $user->mToken = self::INVALID_TOKEN;
869 $user->saveSettings();
870 SessionManager::singleton()->preventSessionsForUser( $user->getName() );
871 }
872
873 return $user;
874 }
875
876 // @}
877
878 /**
879 * Get the username corresponding to a given user ID
880 * @param int $id User ID
881 * @return string|bool The corresponding username
882 */
883 public static function whoIs( $id ) {
884 return UserCache::singleton()->getProp( $id, 'name' );
885 }
886
887 /**
888 * Get the real name of a user given their user ID
889 *
890 * @param int $id User ID
891 * @return string|bool The corresponding user's real name
892 */
893 public static function whoIsReal( $id ) {
894 return UserCache::singleton()->getProp( $id, 'real_name' );
895 }
896
897 /**
898 * Get database id given a user name
899 * @param string $name Username
900 * @param int $flags User::READ_* constant bitfield
901 * @return int|null The corresponding user's ID, or null if user is nonexistent
902 */
903 public static function idFromName( $name, $flags = self::READ_NORMAL ) {
904 $nt = Title::makeTitleSafe( NS_USER, $name );
905 if ( is_null( $nt ) ) {
906 // Illegal name
907 return null;
908 }
909
910 if ( !( $flags & self::READ_LATEST ) && array_key_exists( $name, self::$idCacheByName ) ) {
911 return self::$idCacheByName[$name];
912 }
913
914 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
915 $db = wfGetDB( $index );
916
917 $s = $db->selectRow(
918 'user',
919 [ 'user_id' ],
920 [ 'user_name' => $nt->getText() ],
921 __METHOD__,
922 $options
923 );
924
925 if ( $s === false ) {
926 $result = null;
927 } else {
928 $result = $s->user_id;
929 }
930
931 self::$idCacheByName[$name] = $result;
932
933 if ( count( self::$idCacheByName ) > 1000 ) {
934 self::$idCacheByName = [];
935 }
936
937 return $result;
938 }
939
940 /**
941 * Reset the cache used in idFromName(). For use in tests.
942 */
943 public static function resetIdByNameCache() {
944 self::$idCacheByName = [];
945 }
946
947 /**
948 * Does the string match an anonymous IP address?
949 *
950 * This function exists for username validation, in order to reject
951 * usernames which are similar in form to IP addresses. Strings such
952 * as 300.300.300.300 will return true because it looks like an IP
953 * address, despite not being strictly valid.
954 *
955 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
956 * address because the usemod software would "cloak" anonymous IP
957 * addresses like this, if we allowed accounts like this to be created
958 * new users could get the old edits of these anonymous users.
959 *
960 * @param string $name Name to match
961 * @return bool
962 */
963 public static function isIP( $name ) {
964 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
965 || IP::isIPv6( $name );
966 }
967
968 /**
969 * Is the user an IP range?
970 *
971 * @since 1.30
972 * @return bool
973 */
974 public function isIPRange() {
975 return IP::isValidRange( $this->mName );
976 }
977
978 /**
979 * Is the input a valid username?
980 *
981 * Checks if the input is a valid username, we don't want an empty string,
982 * an IP address, anything that contains slashes (would mess up subpages),
983 * is longer than the maximum allowed username size or doesn't begin with
984 * a capital letter.
985 *
986 * @param string $name Name to match
987 * @return bool
988 */
989 public static function isValidUserName( $name ) {
990 global $wgMaxNameChars;
991
992 if ( $name == ''
993 || self::isIP( $name )
994 || strpos( $name, '/' ) !== false
995 || strlen( $name ) > $wgMaxNameChars
996 || $name != MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $name )
997 ) {
998 return false;
999 }
1000
1001 // Ensure that the name can't be misresolved as a different title,
1002 // such as with extra namespace keys at the start.
1003 $parsed = Title::newFromText( $name );
1004 if ( is_null( $parsed )
1005 || $parsed->getNamespace()
1006 || strcmp( $name, $parsed->getPrefixedText() ) ) {
1007 return false;
1008 }
1009
1010 // Check an additional blacklist of troublemaker characters.
1011 // Should these be merged into the title char list?
1012 $unicodeBlacklist = '/[' .
1013 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
1014 '\x{00a0}' . # non-breaking space
1015 '\x{2000}-\x{200f}' . # various whitespace
1016 '\x{2028}-\x{202f}' . # breaks and control chars
1017 '\x{3000}' . # ideographic space
1018 '\x{e000}-\x{f8ff}' . # private use
1019 ']/u';
1020 if ( preg_match( $unicodeBlacklist, $name ) ) {
1021 return false;
1022 }
1023
1024 return true;
1025 }
1026
1027 /**
1028 * Usernames which fail to pass this function will be blocked
1029 * from user login and new account registrations, but may be used
1030 * internally by batch processes.
1031 *
1032 * If an account already exists in this form, login will be blocked
1033 * by a failure to pass this function.
1034 *
1035 * @param string $name Name to match
1036 * @return bool
1037 */
1038 public static function isUsableName( $name ) {
1039 global $wgReservedUsernames;
1040 // Must be a valid username, obviously ;)
1041 if ( !self::isValidUserName( $name ) ) {
1042 return false;
1043 }
1044
1045 static $reservedUsernames = false;
1046 if ( !$reservedUsernames ) {
1047 $reservedUsernames = $wgReservedUsernames;
1048 Hooks::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
1049 }
1050
1051 // Certain names may be reserved for batch processes.
1052 foreach ( $reservedUsernames as $reserved ) {
1053 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
1054 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->plain();
1055 }
1056 if ( $reserved == $name ) {
1057 return false;
1058 }
1059 }
1060 return true;
1061 }
1062
1063 /**
1064 * Return the users who are members of the given group(s). In case of multiple groups,
1065 * users who are members of at least one of them are returned.
1066 *
1067 * @param string|array $groups A single group name or an array of group names
1068 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
1069 * records; larger values are ignored.
1070 * @param int|null $after ID the user to start after
1071 * @return UserArrayFromResult
1072 */
1073 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
1074 if ( $groups === [] ) {
1075 return UserArrayFromResult::newFromIDs( [] );
1076 }
1077
1078 $groups = array_unique( (array)$groups );
1079 $limit = min( 5000, $limit );
1080
1081 $conds = [ 'ug_group' => $groups ];
1082 if ( $after !== null ) {
1083 $conds[] = 'ug_user > ' . (int)$after;
1084 }
1085
1086 $dbr = wfGetDB( DB_REPLICA );
1087 $ids = $dbr->selectFieldValues(
1088 'user_groups',
1089 'ug_user',
1090 $conds,
1091 __METHOD__,
1092 [
1093 'DISTINCT' => true,
1094 'ORDER BY' => 'ug_user',
1095 'LIMIT' => $limit,
1096 ]
1097 ) ?: [];
1098 return UserArray::newFromIDs( $ids );
1099 }
1100
1101 /**
1102 * Usernames which fail to pass this function will be blocked
1103 * from new account registrations, but may be used internally
1104 * either by batch processes or by user accounts which have
1105 * already been created.
1106 *
1107 * Additional blacklisting may be added here rather than in
1108 * isValidUserName() to avoid disrupting existing accounts.
1109 *
1110 * @param string $name String to match
1111 * @return bool
1112 */
1113 public static function isCreatableName( $name ) {
1114 global $wgInvalidUsernameCharacters;
1115
1116 // Ensure that the username isn't longer than 235 bytes, so that
1117 // (at least for the builtin skins) user javascript and css files
1118 // will work. (T25080)
1119 if ( strlen( $name ) > 235 ) {
1120 wfDebugLog( 'username', __METHOD__ .
1121 ": '$name' invalid due to length" );
1122 return false;
1123 }
1124
1125 // Preg yells if you try to give it an empty string
1126 if ( $wgInvalidUsernameCharacters !== '' ) {
1127 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
1128 wfDebugLog( 'username', __METHOD__ .
1129 ": '$name' invalid due to wgInvalidUsernameCharacters" );
1130 return false;
1131 }
1132 }
1133
1134 return self::isUsableName( $name );
1135 }
1136
1137 /**
1138 * Is the input a valid password for this user?
1139 *
1140 * @param string $password Desired password
1141 * @return bool
1142 */
1143 public function isValidPassword( $password ) {
1144 // simple boolean wrapper for getPasswordValidity
1145 return $this->getPasswordValidity( $password ) === true;
1146 }
1147
1148 /**
1149 * Given unvalidated password input, return error message on failure.
1150 *
1151 * @param string $password Desired password
1152 * @return bool|string|array True on success, string or array of error message on failure
1153 */
1154 public function getPasswordValidity( $password ) {
1155 $result = $this->checkPasswordValidity( $password );
1156 if ( $result->isGood() ) {
1157 return true;
1158 } else {
1159 $messages = [];
1160 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
1161 $messages[] = $error['message'];
1162 }
1163 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
1164 $messages[] = $warning['message'];
1165 }
1166 if ( count( $messages ) === 1 ) {
1167 return $messages[0];
1168 }
1169 return $messages;
1170 }
1171 }
1172
1173 /**
1174 * Check if this is a valid password for this user
1175 *
1176 * Create a Status object based on the password's validity.
1177 * The Status should be set to fatal if the user should not
1178 * be allowed to log in, and should have any errors that
1179 * would block changing the password.
1180 *
1181 * If the return value of this is not OK, the password
1182 * should not be checked. If the return value is not Good,
1183 * the password can be checked, but the user should not be
1184 * able to set their password to this.
1185 *
1186 * @param string $password Desired password
1187 * @return Status
1188 * @since 1.23
1189 */
1190 public function checkPasswordValidity( $password ) {
1191 global $wgPasswordPolicy;
1192
1193 $upp = new UserPasswordPolicy(
1194 $wgPasswordPolicy['policies'],
1195 $wgPasswordPolicy['checks']
1196 );
1197
1198 $status = Status::newGood();
1199 $result = false; // init $result to false for the internal checks
1200
1201 if ( !Hooks::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1202 $status->error( $result );
1203 return $status;
1204 }
1205
1206 if ( $result === false ) {
1207 $status->merge( $upp->checkUserPassword( $this, $password ) );
1208 return $status;
1209 } elseif ( $result === true ) {
1210 return $status;
1211 } else {
1212 $status->error( $result );
1213 return $status; // the isValidPassword hook set a string $result and returned true
1214 }
1215 }
1216
1217 /**
1218 * Given unvalidated user input, return a canonical username, or false if
1219 * the username is invalid.
1220 * @param string $name User input
1221 * @param string|bool $validate Type of validation to use:
1222 * - false No validation
1223 * - 'valid' Valid for batch processes
1224 * - 'usable' Valid for batch processes and login
1225 * - 'creatable' Valid for batch processes, login and account creation
1226 *
1227 * @throws InvalidArgumentException
1228 * @return bool|string
1229 */
1230 public static function getCanonicalName( $name, $validate = 'valid' ) {
1231 // Force usernames to capital
1232 $name = MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $name );
1233
1234 # Reject names containing '#'; these will be cleaned up
1235 # with title normalisation, but then it's too late to
1236 # check elsewhere
1237 if ( strpos( $name, '#' ) !== false ) {
1238 return false;
1239 }
1240
1241 // Clean up name according to title rules,
1242 // but only when validation is requested (T14654)
1243 $t = ( $validate !== false ) ?
1244 Title::newFromText( $name, NS_USER ) : Title::makeTitle( NS_USER, $name );
1245 // Check for invalid titles
1246 if ( is_null( $t ) || $t->getNamespace() !== NS_USER || $t->isExternal() ) {
1247 return false;
1248 }
1249
1250 // Reject various classes of invalid names
1251 $name = AuthManager::callLegacyAuthPlugin(
1252 'getCanonicalName', [ $t->getText() ], $t->getText()
1253 );
1254
1255 switch ( $validate ) {
1256 case false:
1257 break;
1258 case 'valid':
1259 if ( !self::isValidUserName( $name ) ) {
1260 $name = false;
1261 }
1262 break;
1263 case 'usable':
1264 if ( !self::isUsableName( $name ) ) {
1265 $name = false;
1266 }
1267 break;
1268 case 'creatable':
1269 if ( !self::isCreatableName( $name ) ) {
1270 $name = false;
1271 }
1272 break;
1273 default:
1274 throw new InvalidArgumentException(
1275 'Invalid parameter value for $validate in ' . __METHOD__ );
1276 }
1277 return $name;
1278 }
1279
1280 /**
1281 * Return a random password.
1282 *
1283 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1284 * @return string New random password
1285 */
1286 public static function randomPassword() {
1287 global $wgMinimalPasswordLength;
1288 return PasswordFactory::generateRandomPasswordString( $wgMinimalPasswordLength );
1289 }
1290
1291 /**
1292 * Set cached properties to default.
1293 *
1294 * @note This no longer clears uncached lazy-initialised properties;
1295 * the constructor does that instead.
1296 *
1297 * @param string|bool $name
1298 */
1299 public function loadDefaults( $name = false ) {
1300 $this->mId = 0;
1301 $this->mName = $name;
1302 $this->mActorId = null;
1303 $this->mRealName = '';
1304 $this->mEmail = '';
1305 $this->mOptionOverrides = null;
1306 $this->mOptionsLoaded = false;
1307
1308 $loggedOut = $this->mRequest && !defined( 'MW_NO_SESSION' )
1309 ? $this->mRequest->getSession()->getLoggedOutTimestamp() : 0;
1310 if ( $loggedOut !== 0 ) {
1311 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
1312 } else {
1313 $this->mTouched = '1'; # Allow any pages to be cached
1314 }
1315
1316 $this->mToken = null; // Don't run cryptographic functions till we need a token
1317 $this->mEmailAuthenticated = null;
1318 $this->mEmailToken = '';
1319 $this->mEmailTokenExpires = null;
1320 $this->mRegistration = wfTimestamp( TS_MW );
1321 $this->mGroupMemberships = [];
1322
1323 Hooks::run( 'UserLoadDefaults', [ $this, $name ] );
1324 }
1325
1326 /**
1327 * Return whether an item has been loaded.
1328 *
1329 * @param string $item Item to check. Current possibilities:
1330 * - id
1331 * - name
1332 * - realname
1333 * @param string $all 'all' to check if the whole object has been loaded
1334 * or any other string to check if only the item is available (e.g.
1335 * for optimisation)
1336 * @return bool
1337 */
1338 public function isItemLoaded( $item, $all = 'all' ) {
1339 return ( $this->mLoadedItems === true && $all === 'all' ) ||
1340 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1341 }
1342
1343 /**
1344 * Set that an item has been loaded
1345 *
1346 * @param string $item
1347 */
1348 protected function setItemLoaded( $item ) {
1349 if ( is_array( $this->mLoadedItems ) ) {
1350 $this->mLoadedItems[$item] = true;
1351 }
1352 }
1353
1354 /**
1355 * Load user data from the session.
1356 *
1357 * @return bool True if the user is logged in, false otherwise.
1358 */
1359 private function loadFromSession() {
1360 // Deprecated hook
1361 $result = null;
1362 Hooks::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1363 if ( $result !== null ) {
1364 return $result;
1365 }
1366
1367 // MediaWiki\Session\Session already did the necessary authentication of the user
1368 // returned here, so just use it if applicable.
1369 $session = $this->getRequest()->getSession();
1370 $user = $session->getUser();
1371 if ( $user->isLoggedIn() ) {
1372 $this->loadFromUserObject( $user );
1373 if ( $user->isBlocked() ) {
1374 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1375 // every session load, because an autoblocked editor might not edit again from the same
1376 // IP address after being blocked.
1377 $this->trackBlockWithCookie();
1378 }
1379
1380 // Other code expects these to be set in the session, so set them.
1381 $session->set( 'wsUserID', $this->getId() );
1382 $session->set( 'wsUserName', $this->getName() );
1383 $session->set( 'wsToken', $this->getToken() );
1384
1385 return true;
1386 }
1387
1388 return false;
1389 }
1390
1391 /**
1392 * Set the 'BlockID' cookie depending on block type and user authentication status.
1393 */
1394 public function trackBlockWithCookie() {
1395 $block = $this->getBlock();
1396 if ( $block && $this->getRequest()->getCookie( 'BlockID' ) === null ) {
1397 $config = RequestContext::getMain()->getConfig();
1398 $shouldSetCookie = false;
1399
1400 if ( $this->isAnon() && $config->get( 'CookieSetOnIpBlock' ) ) {
1401 // If user is logged-out, set a cookie to track the Block
1402 $shouldSetCookie = in_array( $block->getType(), [
1403 Block::TYPE_IP, Block::TYPE_RANGE
1404 ] );
1405 if ( $shouldSetCookie ) {
1406 $block->setCookie( $this->getRequest()->response() );
1407
1408 // temporary measure the use of cookies on ip blocks
1409 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
1410 $stats->increment( 'block.ipblock.setCookie.success' );
1411 }
1412 } elseif ( $this->isLoggedIn() && $config->get( 'CookieSetOnAutoblock' ) ) {
1413 $shouldSetCookie = $block->getType() === Block::TYPE_USER && $block->isAutoblocking();
1414 if ( $shouldSetCookie ) {
1415 $block->setCookie( $this->getRequest()->response() );
1416 }
1417 }
1418 }
1419 }
1420
1421 /**
1422 * Load user and user_group data from the database.
1423 * $this->mId must be set, this is how the user is identified.
1424 *
1425 * @param int $flags User::READ_* constant bitfield
1426 * @return bool True if the user exists, false if the user is anonymous
1427 */
1428 public function loadFromDatabase( $flags = self::READ_LATEST ) {
1429 // Paranoia
1430 $this->mId = intval( $this->mId );
1431
1432 if ( !$this->mId ) {
1433 // Anonymous users are not in the database
1434 $this->loadDefaults();
1435 return false;
1436 }
1437
1438 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
1439 $db = wfGetDB( $index );
1440
1441 $userQuery = self::getQueryInfo();
1442 $s = $db->selectRow(
1443 $userQuery['tables'],
1444 $userQuery['fields'],
1445 [ 'user_id' => $this->mId ],
1446 __METHOD__,
1447 $options,
1448 $userQuery['joins']
1449 );
1450
1451 $this->queryFlagsUsed = $flags;
1452 Hooks::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1453
1454 if ( $s !== false ) {
1455 // Initialise user table data
1456 $this->loadFromRow( $s );
1457 $this->mGroupMemberships = null; // deferred
1458 $this->getEditCount(); // revalidation for nulls
1459 return true;
1460 } else {
1461 // Invalid user_id
1462 $this->mId = 0;
1463 $this->loadDefaults();
1464 return false;
1465 }
1466 }
1467
1468 /**
1469 * Initialize this object from a row from the user table.
1470 *
1471 * @param stdClass $row Row from the user table to load.
1472 * @param array|null $data Further user data to load into the object
1473 *
1474 * user_groups Array of arrays or stdClass result rows out of the user_groups
1475 * table. Previously you were supposed to pass an array of strings
1476 * here, but we also need expiry info nowadays, so an array of
1477 * strings is ignored.
1478 * user_properties Array with properties out of the user_properties table
1479 */
1480 protected function loadFromRow( $row, $data = null ) {
1481 global $wgActorTableSchemaMigrationStage;
1482
1483 if ( !is_object( $row ) ) {
1484 throw new InvalidArgumentException( '$row must be an object' );
1485 }
1486
1487 $all = true;
1488
1489 $this->mGroupMemberships = null; // deferred
1490
1491 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD ) {
1492 if ( isset( $row->actor_id ) ) {
1493 $this->mActorId = (int)$row->actor_id;
1494 if ( $this->mActorId !== 0 ) {
1495 $this->mFrom = 'actor';
1496 }
1497 $this->setItemLoaded( 'actor' );
1498 } else {
1499 $all = false;
1500 }
1501 }
1502
1503 if ( isset( $row->user_name ) && $row->user_name !== '' ) {
1504 $this->mName = $row->user_name;
1505 $this->mFrom = 'name';
1506 $this->setItemLoaded( 'name' );
1507 } else {
1508 $all = false;
1509 }
1510
1511 if ( isset( $row->user_real_name ) ) {
1512 $this->mRealName = $row->user_real_name;
1513 $this->setItemLoaded( 'realname' );
1514 } else {
1515 $all = false;
1516 }
1517
1518 if ( isset( $row->user_id ) ) {
1519 $this->mId = intval( $row->user_id );
1520 if ( $this->mId !== 0 ) {
1521 $this->mFrom = 'id';
1522 }
1523 $this->setItemLoaded( 'id' );
1524 } else {
1525 $all = false;
1526 }
1527
1528 if ( isset( $row->user_id ) && isset( $row->user_name ) && $row->user_name !== '' ) {
1529 self::$idCacheByName[$row->user_name] = $row->user_id;
1530 }
1531
1532 if ( isset( $row->user_editcount ) ) {
1533 $this->mEditCount = $row->user_editcount;
1534 } else {
1535 $all = false;
1536 }
1537
1538 if ( isset( $row->user_touched ) ) {
1539 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1540 } else {
1541 $all = false;
1542 }
1543
1544 if ( isset( $row->user_token ) ) {
1545 // The definition for the column is binary(32), so trim the NULs
1546 // that appends. The previous definition was char(32), so trim
1547 // spaces too.
1548 $this->mToken = rtrim( $row->user_token, " \0" );
1549 if ( $this->mToken === '' ) {
1550 $this->mToken = null;
1551 }
1552 } else {
1553 $all = false;
1554 }
1555
1556 if ( isset( $row->user_email ) ) {
1557 $this->mEmail = $row->user_email;
1558 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1559 $this->mEmailToken = $row->user_email_token;
1560 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1561 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1562 } else {
1563 $all = false;
1564 }
1565
1566 if ( $all ) {
1567 $this->mLoadedItems = true;
1568 }
1569
1570 if ( is_array( $data ) ) {
1571 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1572 if ( !count( $data['user_groups'] ) ) {
1573 $this->mGroupMemberships = [];
1574 } else {
1575 $firstGroup = reset( $data['user_groups'] );
1576 if ( is_array( $firstGroup ) || is_object( $firstGroup ) ) {
1577 $this->mGroupMemberships = [];
1578 foreach ( $data['user_groups'] as $row ) {
1579 $ugm = UserGroupMembership::newFromRow( (object)$row );
1580 $this->mGroupMemberships[$ugm->getGroup()] = $ugm;
1581 }
1582 }
1583 }
1584 }
1585 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1586 $this->loadOptions( $data['user_properties'] );
1587 }
1588 }
1589 }
1590
1591 /**
1592 * Load the data for this user object from another user object.
1593 *
1594 * @param User $user
1595 */
1596 protected function loadFromUserObject( $user ) {
1597 $user->load();
1598 foreach ( self::$mCacheVars as $var ) {
1599 $this->$var = $user->$var;
1600 }
1601 }
1602
1603 /**
1604 * Load the groups from the database if they aren't already loaded.
1605 */
1606 private function loadGroups() {
1607 if ( is_null( $this->mGroupMemberships ) ) {
1608 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
1609 ? wfGetDB( DB_MASTER )
1610 : wfGetDB( DB_REPLICA );
1611 $this->mGroupMemberships = UserGroupMembership::getMembershipsForUser(
1612 $this->mId, $db );
1613 }
1614 }
1615
1616 /**
1617 * Add the user to the group if he/she meets given criteria.
1618 *
1619 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1620 * possible to remove manually via Special:UserRights. In such case it
1621 * will not be re-added automatically. The user will also not lose the
1622 * group if they no longer meet the criteria.
1623 *
1624 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1625 *
1626 * @return array Array of groups the user has been promoted to.
1627 *
1628 * @see $wgAutopromoteOnce
1629 */
1630 public function addAutopromoteOnceGroups( $event ) {
1631 global $wgAutopromoteOnceLogInRC;
1632
1633 if ( wfReadOnly() || !$this->getId() ) {
1634 return [];
1635 }
1636
1637 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1638 if ( !count( $toPromote ) ) {
1639 return [];
1640 }
1641
1642 if ( !$this->checkAndSetTouched() ) {
1643 return []; // raced out (bug T48834)
1644 }
1645
1646 $oldGroups = $this->getGroups(); // previous groups
1647 $oldUGMs = $this->getGroupMemberships();
1648 foreach ( $toPromote as $group ) {
1649 $this->addGroup( $group );
1650 }
1651 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1652 $newUGMs = $this->getGroupMemberships();
1653
1654 // update groups in external authentication database
1655 Hooks::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false, $oldUGMs, $newUGMs ] );
1656 AuthManager::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1657
1658 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1659 $logEntry->setPerformer( $this );
1660 $logEntry->setTarget( $this->getUserPage() );
1661 $logEntry->setParameters( [
1662 '4::oldgroups' => $oldGroups,
1663 '5::newgroups' => $newGroups,
1664 ] );
1665 $logid = $logEntry->insert();
1666 if ( $wgAutopromoteOnceLogInRC ) {
1667 $logEntry->publish( $logid );
1668 }
1669
1670 return $toPromote;
1671 }
1672
1673 /**
1674 * Builds update conditions. Additional conditions may be added to $conditions to
1675 * protected against race conditions using a compare-and-set (CAS) mechanism
1676 * based on comparing $this->mTouched with the user_touched field.
1677 *
1678 * @param Database $db
1679 * @param array $conditions WHERE conditions for use with Database::update
1680 * @return array WHERE conditions for use with Database::update
1681 */
1682 protected function makeUpdateConditions( Database $db, array $conditions ) {
1683 if ( $this->mTouched ) {
1684 // CAS check: only update if the row wasn't changed sicne it was loaded.
1685 $conditions['user_touched'] = $db->timestamp( $this->mTouched );
1686 }
1687
1688 return $conditions;
1689 }
1690
1691 /**
1692 * Bump user_touched if it didn't change since this object was loaded
1693 *
1694 * On success, the mTouched field is updated.
1695 * The user serialization cache is always cleared.
1696 *
1697 * @return bool Whether user_touched was actually updated
1698 * @since 1.26
1699 */
1700 protected function checkAndSetTouched() {
1701 $this->load();
1702
1703 if ( !$this->mId ) {
1704 return false; // anon
1705 }
1706
1707 // Get a new user_touched that is higher than the old one
1708 $newTouched = $this->newTouchedTimestamp();
1709
1710 $dbw = wfGetDB( DB_MASTER );
1711 $dbw->update( 'user',
1712 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1713 $this->makeUpdateConditions( $dbw, [
1714 'user_id' => $this->mId,
1715 ] ),
1716 __METHOD__
1717 );
1718 $success = ( $dbw->affectedRows() > 0 );
1719
1720 if ( $success ) {
1721 $this->mTouched = $newTouched;
1722 $this->clearSharedCache();
1723 } else {
1724 // Clears on failure too since that is desired if the cache is stale
1725 $this->clearSharedCache( 'refresh' );
1726 }
1727
1728 return $success;
1729 }
1730
1731 /**
1732 * Clear various cached data stored in this object. The cache of the user table
1733 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1734 *
1735 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1736 * given source. May be "name", "id", "actor", "defaults", "session", or false for no reload.
1737 */
1738 public function clearInstanceCache( $reloadFrom = false ) {
1739 $this->mNewtalk = -1;
1740 $this->mDatePreference = null;
1741 $this->mBlockedby = -1; # Unset
1742 $this->mHash = false;
1743 $this->mRights = null;
1744 $this->mEffectiveGroups = null;
1745 $this->mImplicitGroups = null;
1746 $this->mGroupMemberships = null;
1747 $this->mOptions = null;
1748 $this->mOptionsLoaded = false;
1749 $this->mEditCount = null;
1750
1751 if ( $reloadFrom ) {
1752 $this->mLoadedItems = [];
1753 $this->mFrom = $reloadFrom;
1754 }
1755 }
1756
1757 /**
1758 * Combine the language default options with any site-specific options
1759 * and add the default language variants.
1760 *
1761 * @return array Array of String options
1762 */
1763 public static function getDefaultOptions() {
1764 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgDefaultSkin;
1765
1766 static $defOpt = null;
1767 static $defOptLang = null;
1768
1769 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
1770 if ( $defOpt !== null && $defOptLang === $contLang->getCode() ) {
1771 // The content language does not change (and should not change) mid-request, but the
1772 // unit tests change it anyway, and expect this method to return values relevant to the
1773 // current content language.
1774 return $defOpt;
1775 }
1776
1777 $defOpt = $wgDefaultUserOptions;
1778 // Default language setting
1779 $defOptLang = $contLang->getCode();
1780 $defOpt['language'] = $defOptLang;
1781 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1782 if ( $langCode === $contLang->getCode() ) {
1783 $defOpt['variant'] = $langCode;
1784 } else {
1785 $defOpt["variant-$langCode"] = $langCode;
1786 }
1787 }
1788
1789 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1790 // since extensions may change the set of searchable namespaces depending
1791 // on user groups/permissions.
1792 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1793 $defOpt['searchNs' . $nsnum] = (bool)$val;
1794 }
1795 $defOpt['skin'] = Skin::normalizeKey( $wgDefaultSkin );
1796
1797 Hooks::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1798
1799 return $defOpt;
1800 }
1801
1802 /**
1803 * Get a given default option value.
1804 *
1805 * @param string $opt Name of option to retrieve
1806 * @return string Default option value
1807 */
1808 public static function getDefaultOption( $opt ) {
1809 $defOpts = self::getDefaultOptions();
1810 if ( isset( $defOpts[$opt] ) ) {
1811 return $defOpts[$opt];
1812 } else {
1813 return null;
1814 }
1815 }
1816
1817 /**
1818 * Get blocking information
1819 * @param bool $bFromSlave Whether to check the replica DB first.
1820 * To improve performance, non-critical checks are done against replica DBs.
1821 * Check when actually saving should be done against master.
1822 */
1823 private function getBlockedStatus( $bFromSlave = true ) {
1824 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff, $wgSoftBlockRanges;
1825
1826 if ( -1 != $this->mBlockedby ) {
1827 return;
1828 }
1829
1830 wfDebug( __METHOD__ . ": checking...\n" );
1831
1832 // Initialize data...
1833 // Otherwise something ends up stomping on $this->mBlockedby when
1834 // things get lazy-loaded later, causing false positive block hits
1835 // due to -1 !== 0. Probably session-related... Nothing should be
1836 // overwriting mBlockedby, surely?
1837 $this->load();
1838
1839 # We only need to worry about passing the IP address to the Block generator if the
1840 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1841 # know which IP address they're actually coming from
1842 $ip = null;
1843 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1844 // $wgUser->getName() only works after the end of Setup.php. Until
1845 // then, assume it's a logged-out user.
1846 $globalUserName = $wgUser->isSafeToLoad()
1847 ? $wgUser->getName()
1848 : IP::sanitizeIP( $wgUser->getRequest()->getIP() );
1849 if ( $this->getName() === $globalUserName ) {
1850 $ip = $this->getRequest()->getIP();
1851 }
1852 }
1853
1854 // User/IP blocking
1855 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1856
1857 // Cookie blocking
1858 if ( !$block instanceof Block ) {
1859 $block = $this->getBlockFromCookieValue( $this->getRequest()->getCookie( 'BlockID' ) );
1860 }
1861
1862 // Proxy blocking
1863 if ( !$block instanceof Block && $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1864 // Local list
1865 if ( self::isLocallyBlockedProxy( $ip ) ) {
1866 $block = new Block( [
1867 'byText' => wfMessage( 'proxyblocker' )->text(),
1868 'reason' => wfMessage( 'proxyblockreason' )->plain(),
1869 'address' => $ip,
1870 'systemBlock' => 'proxy',
1871 ] );
1872 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1873 $block = new Block( [
1874 'byText' => wfMessage( 'sorbs' )->text(),
1875 'reason' => wfMessage( 'sorbsreason' )->plain(),
1876 'address' => $ip,
1877 'systemBlock' => 'dnsbl',
1878 ] );
1879 }
1880 }
1881
1882 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
1883 if ( !$block instanceof Block
1884 && $wgApplyIpBlocksToXff
1885 && $ip !== null
1886 && !in_array( $ip, $wgProxyWhitelist )
1887 ) {
1888 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1889 $xff = array_map( 'trim', explode( ',', $xff ) );
1890 $xff = array_diff( $xff, [ $ip ] );
1891 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1892 $block = Block::chooseBlock( $xffblocks, $xff );
1893 if ( $block instanceof Block ) {
1894 # Mangle the reason to alert the user that the block
1895 # originated from matching the X-Forwarded-For header.
1896 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->plain();
1897 }
1898 }
1899
1900 if ( !$block instanceof Block
1901 && $ip !== null
1902 && $this->isAnon()
1903 && IP::isInRanges( $ip, $wgSoftBlockRanges )
1904 ) {
1905 $block = new Block( [
1906 'address' => $ip,
1907 'byText' => 'MediaWiki default',
1908 'reason' => wfMessage( 'softblockrangesreason', $ip )->plain(),
1909 'anonOnly' => true,
1910 'systemBlock' => 'wgSoftBlockRanges',
1911 ] );
1912 }
1913
1914 if ( $block instanceof Block ) {
1915 wfDebug( __METHOD__ . ": Found block.\n" );
1916 $this->mBlock = $block;
1917 $this->mBlockedby = $block->getByName();
1918 $this->mBlockreason = $block->mReason;
1919 $this->mHideName = $block->mHideName;
1920 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1921 } else {
1922 $this->mBlock = null;
1923 $this->mBlockedby = '';
1924 $this->mBlockreason = '';
1925 $this->mHideName = 0;
1926 $this->mAllowUsertalk = false;
1927 }
1928
1929 // Avoid PHP 7.1 warning of passing $this by reference
1930 $user = $this;
1931 // Extensions
1932 Hooks::run( 'GetBlockedStatus', [ &$user ] );
1933 }
1934
1935 /**
1936 * Try to load a Block from an ID given in a cookie value.
1937 * @param string|null $blockCookieVal The cookie value to check.
1938 * @return Block|bool The Block object, or false if none could be loaded.
1939 */
1940 protected function getBlockFromCookieValue( $blockCookieVal ) {
1941 // Make sure there's something to check. The cookie value must start with a number.
1942 if ( strlen( $blockCookieVal ) < 1 || !is_numeric( substr( $blockCookieVal, 0, 1 ) ) ) {
1943 return false;
1944 }
1945 // Load the Block from the ID in the cookie.
1946 $blockCookieId = Block::getIdFromCookieValue( $blockCookieVal );
1947 if ( $blockCookieId !== null ) {
1948 // An ID was found in the cookie.
1949 $tmpBlock = Block::newFromID( $blockCookieId );
1950 if ( $tmpBlock instanceof Block ) {
1951 $config = RequestContext::getMain()->getConfig();
1952
1953 switch ( $tmpBlock->getType() ) {
1954 case Block::TYPE_USER:
1955 $blockIsValid = !$tmpBlock->isExpired() && $tmpBlock->isAutoblocking();
1956 $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true );
1957 break;
1958 case Block::TYPE_IP:
1959 case Block::TYPE_RANGE:
1960 // If block is type IP or IP range, load only if user is not logged in (T152462)
1961 $blockIsValid = !$tmpBlock->isExpired() && !$this->isLoggedIn();
1962 $useBlockCookie = ( $config->get( 'CookieSetOnIpBlock' ) === true );
1963 break;
1964 default:
1965 $blockIsValid = false;
1966 $useBlockCookie = false;
1967 }
1968
1969 if ( $blockIsValid && $useBlockCookie ) {
1970 // Use the block.
1971 return $tmpBlock;
1972 } else {
1973 // If the block is not valid, remove the cookie.
1974 Block::clearCookie( $this->getRequest()->response() );
1975 }
1976 } else {
1977 // If the block doesn't exist, remove the cookie.
1978 Block::clearCookie( $this->getRequest()->response() );
1979 }
1980 }
1981 return false;
1982 }
1983
1984 /**
1985 * Whether the given IP is in a DNS blacklist.
1986 *
1987 * @param string $ip IP to check
1988 * @param bool $checkWhitelist Whether to check the whitelist first
1989 * @return bool True if blacklisted.
1990 */
1991 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1992 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1993
1994 if ( !$wgEnableDnsBlacklist ) {
1995 return false;
1996 }
1997
1998 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1999 return false;
2000 }
2001
2002 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
2003 }
2004
2005 /**
2006 * Whether the given IP is in a given DNS blacklist.
2007 *
2008 * @param string $ip IP to check
2009 * @param string|array $bases Array of Strings: URL of the DNS blacklist
2010 * @return bool True if blacklisted.
2011 */
2012 public function inDnsBlacklist( $ip, $bases ) {
2013 $found = false;
2014 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
2015 if ( IP::isIPv4( $ip ) ) {
2016 // Reverse IP, T23255
2017 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
2018
2019 foreach ( (array)$bases as $base ) {
2020 // Make hostname
2021 // If we have an access key, use that too (ProjectHoneypot, etc.)
2022 $basename = $base;
2023 if ( is_array( $base ) ) {
2024 if ( count( $base ) >= 2 ) {
2025 // Access key is 1, base URL is 0
2026 $host = "{$base[1]}.$ipReversed.{$base[0]}";
2027 } else {
2028 $host = "$ipReversed.{$base[0]}";
2029 }
2030 $basename = $base[0];
2031 } else {
2032 $host = "$ipReversed.$base";
2033 }
2034
2035 // Send query
2036 $ipList = gethostbynamel( $host );
2037
2038 if ( $ipList ) {
2039 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
2040 $found = true;
2041 break;
2042 } else {
2043 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
2044 }
2045 }
2046 }
2047
2048 return $found;
2049 }
2050
2051 /**
2052 * Check if an IP address is in the local proxy list
2053 *
2054 * @param string $ip
2055 *
2056 * @return bool
2057 */
2058 public static function isLocallyBlockedProxy( $ip ) {
2059 global $wgProxyList;
2060
2061 if ( !$wgProxyList ) {
2062 return false;
2063 }
2064
2065 if ( !is_array( $wgProxyList ) ) {
2066 // Load values from the specified file
2067 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
2068 }
2069
2070 $resultProxyList = [];
2071 $deprecatedIPEntries = [];
2072
2073 // backward compatibility: move all ip addresses in keys to values
2074 foreach ( $wgProxyList as $key => $value ) {
2075 $keyIsIP = IP::isIPAddress( $key );
2076 $valueIsIP = IP::isIPAddress( $value );
2077 if ( $keyIsIP && !$valueIsIP ) {
2078 $deprecatedIPEntries[] = $key;
2079 $resultProxyList[] = $key;
2080 } elseif ( $keyIsIP && $valueIsIP ) {
2081 $deprecatedIPEntries[] = $key;
2082 $resultProxyList[] = $key;
2083 $resultProxyList[] = $value;
2084 } else {
2085 $resultProxyList[] = $value;
2086 }
2087 }
2088
2089 if ( $deprecatedIPEntries ) {
2090 wfDeprecated(
2091 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
2092 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
2093 }
2094
2095 $proxyListIPSet = new IPSet( $resultProxyList );
2096 return $proxyListIPSet->match( $ip );
2097 }
2098
2099 /**
2100 * Is this user subject to rate limiting?
2101 *
2102 * @return bool True if rate limited
2103 */
2104 public function isPingLimitable() {
2105 global $wgRateLimitsExcludedIPs;
2106 if ( IP::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
2107 // No other good way currently to disable rate limits
2108 // for specific IPs. :P
2109 // But this is a crappy hack and should die.
2110 return false;
2111 }
2112 return !$this->isAllowed( 'noratelimit' );
2113 }
2114
2115 /**
2116 * Primitive rate limits: enforce maximum actions per time period
2117 * to put a brake on flooding.
2118 *
2119 * The method generates both a generic profiling point and a per action one
2120 * (suffix being "-$action".
2121 *
2122 * @note When using a shared cache like memcached, IP-address
2123 * last-hit counters will be shared across wikis.
2124 *
2125 * @param string $action Action to enforce; 'edit' if unspecified
2126 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
2127 * @return bool True if a rate limiter was tripped
2128 */
2129 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
2130 // Avoid PHP 7.1 warning of passing $this by reference
2131 $user = $this;
2132 // Call the 'PingLimiter' hook
2133 $result = false;
2134 if ( !Hooks::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
2135 return $result;
2136 }
2137
2138 global $wgRateLimits;
2139 if ( !isset( $wgRateLimits[$action] ) ) {
2140 return false;
2141 }
2142
2143 $limits = array_merge(
2144 [ '&can-bypass' => true ],
2145 $wgRateLimits[$action]
2146 );
2147
2148 // Some groups shouldn't trigger the ping limiter, ever
2149 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
2150 return false;
2151 }
2152
2153 $keys = [];
2154 $id = $this->getId();
2155 $userLimit = false;
2156 $isNewbie = $this->isNewbie();
2157 $cache = ObjectCache::getLocalClusterInstance();
2158
2159 if ( $id == 0 ) {
2160 // limits for anons
2161 if ( isset( $limits['anon'] ) ) {
2162 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
2163 }
2164 } else {
2165 // limits for logged-in users
2166 if ( isset( $limits['user'] ) ) {
2167 $userLimit = $limits['user'];
2168 }
2169 }
2170
2171 // limits for anons and for newbie logged-in users
2172 if ( $isNewbie ) {
2173 // ip-based limits
2174 if ( isset( $limits['ip'] ) ) {
2175 $ip = $this->getRequest()->getIP();
2176 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
2177 }
2178 // subnet-based limits
2179 if ( isset( $limits['subnet'] ) ) {
2180 $ip = $this->getRequest()->getIP();
2181 $subnet = IP::getSubnet( $ip );
2182 if ( $subnet !== false ) {
2183 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
2184 }
2185 }
2186 }
2187
2188 // Check for group-specific permissions
2189 // If more than one group applies, use the group with the highest limit ratio (max/period)
2190 foreach ( $this->getGroups() as $group ) {
2191 if ( isset( $limits[$group] ) ) {
2192 if ( $userLimit === false
2193 || $limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
2194 ) {
2195 $userLimit = $limits[$group];
2196 }
2197 }
2198 }
2199
2200 // limits for newbie logged-in users (override all the normal user limits)
2201 if ( $id !== 0 && $isNewbie && isset( $limits['newbie'] ) ) {
2202 $userLimit = $limits['newbie'];
2203 }
2204
2205 // Set the user limit key
2206 if ( $userLimit !== false ) {
2207 list( $max, $period ) = $userLimit;
2208 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
2209 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
2210 }
2211
2212 // ip-based limits for all ping-limitable users
2213 if ( isset( $limits['ip-all'] ) ) {
2214 $ip = $this->getRequest()->getIP();
2215 // ignore if user limit is more permissive
2216 if ( $isNewbie || $userLimit === false
2217 || $limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2218 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
2219 }
2220 }
2221
2222 // subnet-based limits for all ping-limitable users
2223 if ( isset( $limits['subnet-all'] ) ) {
2224 $ip = $this->getRequest()->getIP();
2225 $subnet = IP::getSubnet( $ip );
2226 if ( $subnet !== false ) {
2227 // ignore if user limit is more permissive
2228 if ( $isNewbie || $userLimit === false
2229 || $limits['ip-all'][0] / $limits['ip-all'][1]
2230 > $userLimit[0] / $userLimit[1] ) {
2231 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2232 }
2233 }
2234 }
2235
2236 $triggered = false;
2237 foreach ( $keys as $key => $limit ) {
2238 list( $max, $period ) = $limit;
2239 $summary = "(limit $max in {$period}s)";
2240 $count = $cache->get( $key );
2241 // Already pinged?
2242 if ( $count ) {
2243 if ( $count >= $max ) {
2244 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2245 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2246 $triggered = true;
2247 } else {
2248 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
2249 }
2250 } else {
2251 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
2252 if ( $incrBy > 0 ) {
2253 $cache->add( $key, 0, intval( $period ) ); // first ping
2254 }
2255 }
2256 if ( $incrBy > 0 ) {
2257 $cache->incr( $key, $incrBy );
2258 }
2259 }
2260
2261 return $triggered;
2262 }
2263
2264 /**
2265 * Check if user is blocked
2266 *
2267 * @param bool $bFromSlave Whether to check the replica DB instead of
2268 * the master. Hacked from false due to horrible probs on site.
2269 * @return bool True if blocked, false otherwise
2270 */
2271 public function isBlocked( $bFromSlave = true ) {
2272 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
2273 }
2274
2275 /**
2276 * Get the block affecting the user, or null if the user is not blocked
2277 *
2278 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2279 * @return Block|null
2280 */
2281 public function getBlock( $bFromSlave = true ) {
2282 $this->getBlockedStatus( $bFromSlave );
2283 return $this->mBlock instanceof Block ? $this->mBlock : null;
2284 }
2285
2286 /**
2287 * Check if user is blocked from editing a particular article
2288 *
2289 * @param Title $title Title to check
2290 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2291 * @return bool
2292 */
2293 public function isBlockedFrom( $title, $bFromSlave = false ) {
2294 global $wgBlockAllowsUTEdit;
2295
2296 $blocked = $this->isBlocked( $bFromSlave );
2297 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
2298 // If a user's name is suppressed, they cannot make edits anywhere
2299 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
2300 && $title->getNamespace() == NS_USER_TALK ) {
2301 $blocked = false;
2302 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
2303 }
2304
2305 Hooks::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2306
2307 return $blocked;
2308 }
2309
2310 /**
2311 * If user is blocked, return the name of the user who placed the block
2312 * @return string Name of blocker
2313 */
2314 public function blockedBy() {
2315 $this->getBlockedStatus();
2316 return $this->mBlockedby;
2317 }
2318
2319 /**
2320 * If user is blocked, return the specified reason for the block
2321 * @return string Blocking reason
2322 */
2323 public function blockedFor() {
2324 $this->getBlockedStatus();
2325 return $this->mBlockreason;
2326 }
2327
2328 /**
2329 * If user is blocked, return the ID for the block
2330 * @return int Block ID
2331 */
2332 public function getBlockId() {
2333 $this->getBlockedStatus();
2334 return ( $this->mBlock ? $this->mBlock->getId() : false );
2335 }
2336
2337 /**
2338 * Check if user is blocked on all wikis.
2339 * Do not use for actual edit permission checks!
2340 * This is intended for quick UI checks.
2341 *
2342 * @param string $ip IP address, uses current client if none given
2343 * @return bool True if blocked, false otherwise
2344 */
2345 public function isBlockedGlobally( $ip = '' ) {
2346 return $this->getGlobalBlock( $ip ) instanceof Block;
2347 }
2348
2349 /**
2350 * Check if user is blocked on all wikis.
2351 * Do not use for actual edit permission checks!
2352 * This is intended for quick UI checks.
2353 *
2354 * @param string $ip IP address, uses current client if none given
2355 * @return Block|null Block object if blocked, null otherwise
2356 * @throws FatalError
2357 * @throws MWException
2358 */
2359 public function getGlobalBlock( $ip = '' ) {
2360 if ( $this->mGlobalBlock !== null ) {
2361 return $this->mGlobalBlock ?: null;
2362 }
2363 // User is already an IP?
2364 if ( IP::isIPAddress( $this->getName() ) ) {
2365 $ip = $this->getName();
2366 } elseif ( !$ip ) {
2367 $ip = $this->getRequest()->getIP();
2368 }
2369 // Avoid PHP 7.1 warning of passing $this by reference
2370 $user = $this;
2371 $blocked = false;
2372 $block = null;
2373 Hooks::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2374
2375 if ( $blocked && $block === null ) {
2376 // back-compat: UserIsBlockedGlobally didn't have $block param first
2377 $block = new Block( [
2378 'address' => $ip,
2379 'systemBlock' => 'global-block'
2380 ] );
2381 }
2382
2383 $this->mGlobalBlock = $blocked ? $block : false;
2384 return $this->mGlobalBlock ?: null;
2385 }
2386
2387 /**
2388 * Check if user account is locked
2389 *
2390 * @return bool True if locked, false otherwise
2391 */
2392 public function isLocked() {
2393 if ( $this->mLocked !== null ) {
2394 return $this->mLocked;
2395 }
2396 // Avoid PHP 7.1 warning of passing $this by reference
2397 $user = $this;
2398 $authUser = AuthManager::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2399 $this->mLocked = $authUser && $authUser->isLocked();
2400 Hooks::run( 'UserIsLocked', [ $this, &$this->mLocked ] );
2401 return $this->mLocked;
2402 }
2403
2404 /**
2405 * Check if user account is hidden
2406 *
2407 * @return bool True if hidden, false otherwise
2408 */
2409 public function isHidden() {
2410 if ( $this->mHideName !== null ) {
2411 return $this->mHideName;
2412 }
2413 $this->getBlockedStatus();
2414 if ( !$this->mHideName ) {
2415 // Avoid PHP 7.1 warning of passing $this by reference
2416 $user = $this;
2417 $authUser = AuthManager::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2418 $this->mHideName = $authUser && $authUser->isHidden();
2419 Hooks::run( 'UserIsHidden', [ $this, &$this->mHideName ] );
2420 }
2421 return $this->mHideName;
2422 }
2423
2424 /**
2425 * Get the user's ID.
2426 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2427 */
2428 public function getId() {
2429 if ( $this->mId === null && $this->mName !== null && self::isIP( $this->mName ) ) {
2430 // Special case, we know the user is anonymous
2431 return 0;
2432 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2433 // Don't load if this was initialized from an ID
2434 $this->load();
2435 }
2436
2437 return (int)$this->mId;
2438 }
2439
2440 /**
2441 * Set the user and reload all fields according to a given ID
2442 * @param int $v User ID to reload
2443 */
2444 public function setId( $v ) {
2445 $this->mId = $v;
2446 $this->clearInstanceCache( 'id' );
2447 }
2448
2449 /**
2450 * Get the user name, or the IP of an anonymous user
2451 * @return string User's name or IP address
2452 */
2453 public function getName() {
2454 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2455 // Special case optimisation
2456 return $this->mName;
2457 } else {
2458 $this->load();
2459 if ( $this->mName === false ) {
2460 // Clean up IPs
2461 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
2462 }
2463 return $this->mName;
2464 }
2465 }
2466
2467 /**
2468 * Set the user name.
2469 *
2470 * This does not reload fields from the database according to the given
2471 * name. Rather, it is used to create a temporary "nonexistent user" for
2472 * later addition to the database. It can also be used to set the IP
2473 * address for an anonymous user to something other than the current
2474 * remote IP.
2475 *
2476 * @note User::newFromName() has roughly the same function, when the named user
2477 * does not exist.
2478 * @param string $str New user name to set
2479 */
2480 public function setName( $str ) {
2481 $this->load();
2482 $this->mName = $str;
2483 }
2484
2485 /**
2486 * Get the user's actor ID.
2487 * @since 1.31
2488 * @param IDatabase|null $dbw Assign a new actor ID, using this DB handle, if none exists
2489 * @return int The actor's ID, or 0 if no actor ID exists and $dbw was null
2490 */
2491 public function getActorId( IDatabase $dbw = null ) {
2492 global $wgActorTableSchemaMigrationStage;
2493
2494 if ( $wgActorTableSchemaMigrationStage <= MIGRATION_OLD ) {
2495 return 0;
2496 }
2497
2498 if ( !$this->isItemLoaded( 'actor' ) ) {
2499 $this->load();
2500 }
2501
2502 // Currently $this->mActorId might be null if $this was loaded from a
2503 // cache entry that was written when $wgActorTableSchemaMigrationStage
2504 // was MIGRATION_OLD. Once that is no longer a possibility (i.e. when
2505 // User::VERSION is incremented after $wgActorTableSchemaMigrationStage
2506 // has been removed), that condition may be removed.
2507 if ( $this->mActorId === null || !$this->mActorId && $dbw ) {
2508 $q = [
2509 'actor_user' => $this->getId() ?: null,
2510 'actor_name' => (string)$this->getName(),
2511 ];
2512 if ( $dbw ) {
2513 if ( $q['actor_user'] === null && self::isUsableName( $q['actor_name'] ) ) {
2514 throw new CannotCreateActorException(
2515 'Cannot create an actor for a usable name that is not an existing user'
2516 );
2517 }
2518 if ( $q['actor_name'] === '' ) {
2519 throw new CannotCreateActorException( 'Cannot create an actor for a user with no name' );
2520 }
2521 $dbw->insert( 'actor', $q, __METHOD__, [ 'IGNORE' ] );
2522 if ( $dbw->affectedRows() ) {
2523 $this->mActorId = (int)$dbw->insertId();
2524 } else {
2525 // Outdated cache?
2526 list( , $options ) = DBAccessObjectUtils::getDBOptions( $this->queryFlagsUsed );
2527 $this->mActorId = (int)$dbw->selectField( 'actor', 'actor_id', $q, __METHOD__, $options );
2528 if ( !$this->mActorId ) {
2529 throw new CannotCreateActorException(
2530 "Cannot create actor ID for user_id={$this->getId()} user_name={$this->getName()}"
2531 );
2532 }
2533 }
2534 $this->invalidateCache();
2535 } else {
2536 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $this->queryFlagsUsed );
2537 $db = wfGetDB( $index );
2538 $this->mActorId = (int)$db->selectField( 'actor', 'actor_id', $q, __METHOD__, $options );
2539 }
2540 $this->setItemLoaded( 'actor' );
2541 }
2542
2543 return (int)$this->mActorId;
2544 }
2545
2546 /**
2547 * Get the user's name escaped by underscores.
2548 * @return string Username escaped by underscores.
2549 */
2550 public function getTitleKey() {
2551 return str_replace( ' ', '_', $this->getName() );
2552 }
2553
2554 /**
2555 * Check if the user has new messages.
2556 * @return bool True if the user has new messages
2557 */
2558 public function getNewtalk() {
2559 $this->load();
2560
2561 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2562 if ( $this->mNewtalk === -1 ) {
2563 $this->mNewtalk = false; # reset talk page status
2564
2565 // Check memcached separately for anons, who have no
2566 // entire User object stored in there.
2567 if ( !$this->mId ) {
2568 global $wgDisableAnonTalk;
2569 if ( $wgDisableAnonTalk ) {
2570 // Anon newtalk disabled by configuration.
2571 $this->mNewtalk = false;
2572 } else {
2573 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName() );
2574 }
2575 } else {
2576 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
2577 }
2578 }
2579
2580 return (bool)$this->mNewtalk;
2581 }
2582
2583 /**
2584 * Return the data needed to construct links for new talk page message
2585 * alerts. If there are new messages, this will return an associative array
2586 * with the following data:
2587 * wiki: The database name of the wiki
2588 * link: Root-relative link to the user's talk page
2589 * rev: The last talk page revision that the user has seen or null. This
2590 * is useful for building diff links.
2591 * If there are no new messages, it returns an empty array.
2592 * @note This function was designed to accomodate multiple talk pages, but
2593 * currently only returns a single link and revision.
2594 * @return array
2595 */
2596 public function getNewMessageLinks() {
2597 // Avoid PHP 7.1 warning of passing $this by reference
2598 $user = $this;
2599 $talks = [];
2600 if ( !Hooks::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2601 return $talks;
2602 } elseif ( !$this->getNewtalk() ) {
2603 return [];
2604 }
2605 $utp = $this->getTalkPage();
2606 $dbr = wfGetDB( DB_REPLICA );
2607 // Get the "last viewed rev" timestamp from the oldest message notification
2608 $timestamp = $dbr->selectField( 'user_newtalk',
2609 'MIN(user_last_timestamp)',
2610 $this->isAnon() ? [ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2611 __METHOD__ );
2612 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2613 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2614 }
2615
2616 /**
2617 * Get the revision ID for the last talk page revision viewed by the talk
2618 * page owner.
2619 * @return int|null Revision ID or null
2620 */
2621 public function getNewMessageRevisionId() {
2622 $newMessageRevisionId = null;
2623 $newMessageLinks = $this->getNewMessageLinks();
2624 if ( $newMessageLinks ) {
2625 // Note: getNewMessageLinks() never returns more than a single link
2626 // and it is always for the same wiki, but we double-check here in
2627 // case that changes some time in the future.
2628 if ( count( $newMessageLinks ) === 1
2629 && $newMessageLinks[0]['wiki'] === wfWikiID()
2630 && $newMessageLinks[0]['rev']
2631 ) {
2632 /** @var Revision $newMessageRevision */
2633 $newMessageRevision = $newMessageLinks[0]['rev'];
2634 $newMessageRevisionId = $newMessageRevision->getId();
2635 }
2636 }
2637 return $newMessageRevisionId;
2638 }
2639
2640 /**
2641 * Internal uncached check for new messages
2642 *
2643 * @see getNewtalk()
2644 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2645 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2646 * @return bool True if the user has new messages
2647 */
2648 protected function checkNewtalk( $field, $id ) {
2649 $dbr = wfGetDB( DB_REPLICA );
2650
2651 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__ );
2652
2653 return $ok !== false;
2654 }
2655
2656 /**
2657 * Add or update the new messages flag
2658 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2659 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2660 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2661 * @return bool True if successful, false otherwise
2662 */
2663 protected function updateNewtalk( $field, $id, $curRev = null ) {
2664 // Get timestamp of the talk page revision prior to the current one
2665 $prevRev = $curRev ? $curRev->getPrevious() : false;
2666 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2667 // Mark the user as having new messages since this revision
2668 $dbw = wfGetDB( DB_MASTER );
2669 $dbw->insert( 'user_newtalk',
2670 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2671 __METHOD__,
2672 'IGNORE' );
2673 if ( $dbw->affectedRows() ) {
2674 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2675 return true;
2676 } else {
2677 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2678 return false;
2679 }
2680 }
2681
2682 /**
2683 * Clear the new messages flag for the given user
2684 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2685 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2686 * @return bool True if successful, false otherwise
2687 */
2688 protected function deleteNewtalk( $field, $id ) {
2689 $dbw = wfGetDB( DB_MASTER );
2690 $dbw->delete( 'user_newtalk',
2691 [ $field => $id ],
2692 __METHOD__ );
2693 if ( $dbw->affectedRows() ) {
2694 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2695 return true;
2696 } else {
2697 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2698 return false;
2699 }
2700 }
2701
2702 /**
2703 * Update the 'You have new messages!' status.
2704 * @param bool $val Whether the user has new messages
2705 * @param Revision|null $curRev New, as yet unseen revision of the user talk
2706 * page. Ignored if null or !$val.
2707 */
2708 public function setNewtalk( $val, $curRev = null ) {
2709 if ( wfReadOnly() ) {
2710 return;
2711 }
2712
2713 $this->load();
2714 $this->mNewtalk = $val;
2715
2716 if ( $this->isAnon() ) {
2717 $field = 'user_ip';
2718 $id = $this->getName();
2719 } else {
2720 $field = 'user_id';
2721 $id = $this->getId();
2722 }
2723
2724 if ( $val ) {
2725 $changed = $this->updateNewtalk( $field, $id, $curRev );
2726 } else {
2727 $changed = $this->deleteNewtalk( $field, $id );
2728 }
2729
2730 if ( $changed ) {
2731 $this->invalidateCache();
2732 }
2733 }
2734
2735 /**
2736 * Generate a current or new-future timestamp to be stored in the
2737 * user_touched field when we update things.
2738 * @return string Timestamp in TS_MW format
2739 */
2740 private function newTouchedTimestamp() {
2741 global $wgClockSkewFudge;
2742
2743 $time = wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2744 if ( $this->mTouched && $time <= $this->mTouched ) {
2745 $time = wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $this->mTouched ) + 1 );
2746 }
2747
2748 return $time;
2749 }
2750
2751 /**
2752 * Clear user data from memcached
2753 *
2754 * Use after applying updates to the database; caller's
2755 * responsibility to update user_touched if appropriate.
2756 *
2757 * Called implicitly from invalidateCache() and saveSettings().
2758 *
2759 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2760 */
2761 public function clearSharedCache( $mode = 'changed' ) {
2762 if ( !$this->getId() ) {
2763 return;
2764 }
2765
2766 $cache = ObjectCache::getMainWANInstance();
2767 $key = $this->getCacheKey( $cache );
2768 if ( $mode === 'refresh' ) {
2769 $cache->delete( $key, 1 );
2770 } else {
2771 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
2772 if ( $lb->hasOrMadeRecentMasterChanges() ) {
2773 $lb->getConnection( DB_MASTER )->onTransactionPreCommitOrIdle(
2774 function () use ( $cache, $key ) {
2775 $cache->delete( $key );
2776 },
2777 __METHOD__
2778 );
2779 } else {
2780 $cache->delete( $key );
2781 }
2782 }
2783 }
2784
2785 /**
2786 * Immediately touch the user data cache for this account
2787 *
2788 * Calls touch() and removes account data from memcached
2789 */
2790 public function invalidateCache() {
2791 $this->touch();
2792 $this->clearSharedCache();
2793 }
2794
2795 /**
2796 * Update the "touched" timestamp for the user
2797 *
2798 * This is useful on various login/logout events when making sure that
2799 * a browser or proxy that has multiple tenants does not suffer cache
2800 * pollution where the new user sees the old users content. The value
2801 * of getTouched() is checked when determining 304 vs 200 responses.
2802 * Unlike invalidateCache(), this preserves the User object cache and
2803 * avoids database writes.
2804 *
2805 * @since 1.25
2806 */
2807 public function touch() {
2808 $id = $this->getId();
2809 if ( $id ) {
2810 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2811 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2812 $cache->touchCheckKey( $key );
2813 $this->mQuickTouched = null;
2814 }
2815 }
2816
2817 /**
2818 * Validate the cache for this account.
2819 * @param string $timestamp A timestamp in TS_MW format
2820 * @return bool
2821 */
2822 public function validateCache( $timestamp ) {
2823 return ( $timestamp >= $this->getTouched() );
2824 }
2825
2826 /**
2827 * Get the user touched timestamp
2828 *
2829 * Use this value only to validate caches via inequalities
2830 * such as in the case of HTTP If-Modified-Since response logic
2831 *
2832 * @return string TS_MW Timestamp
2833 */
2834 public function getTouched() {
2835 $this->load();
2836
2837 if ( $this->mId ) {
2838 if ( $this->mQuickTouched === null ) {
2839 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2840 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId );
2841
2842 $this->mQuickTouched = wfTimestamp( TS_MW, $cache->getCheckKeyTime( $key ) );
2843 }
2844
2845 return max( $this->mTouched, $this->mQuickTouched );
2846 }
2847
2848 return $this->mTouched;
2849 }
2850
2851 /**
2852 * Get the user_touched timestamp field (time of last DB updates)
2853 * @return string TS_MW Timestamp
2854 * @since 1.26
2855 */
2856 public function getDBTouched() {
2857 $this->load();
2858
2859 return $this->mTouched;
2860 }
2861
2862 /**
2863 * Set the password and reset the random token.
2864 * Calls through to authentication plugin if necessary;
2865 * will have no effect if the auth plugin refuses to
2866 * pass the change through or if the legal password
2867 * checks fail.
2868 *
2869 * As a special case, setting the password to null
2870 * wipes it, so the account cannot be logged in until
2871 * a new password is set, for instance via e-mail.
2872 *
2873 * @deprecated since 1.27, use AuthManager instead
2874 * @param string $str New password to set
2875 * @throws PasswordError On failure
2876 * @return bool
2877 */
2878 public function setPassword( $str ) {
2879 return $this->setPasswordInternal( $str );
2880 }
2881
2882 /**
2883 * Set the password and reset the random token unconditionally.
2884 *
2885 * @deprecated since 1.27, use AuthManager instead
2886 * @param string|null $str New password to set or null to set an invalid
2887 * password hash meaning that the user will not be able to log in
2888 * through the web interface.
2889 */
2890 public function setInternalPassword( $str ) {
2891 $this->setPasswordInternal( $str );
2892 }
2893
2894 /**
2895 * Actually set the password and such
2896 * @since 1.27 cannot set a password for a user not in the database
2897 * @param string|null $str New password to set or null to set an invalid
2898 * password hash meaning that the user will not be able to log in
2899 * through the web interface.
2900 * @return bool Success
2901 */
2902 private function setPasswordInternal( $str ) {
2903 $manager = AuthManager::singleton();
2904
2905 // If the user doesn't exist yet, fail
2906 if ( !$manager->userExists( $this->getName() ) ) {
2907 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2908 }
2909
2910 $status = $this->changeAuthenticationData( [
2911 'username' => $this->getName(),
2912 'password' => $str,
2913 'retype' => $str,
2914 ] );
2915 if ( !$status->isGood() ) {
2916 \MediaWiki\Logger\LoggerFactory::getInstance( 'authentication' )
2917 ->info( __METHOD__ . ': Password change rejected: '
2918 . $status->getWikiText( null, null, 'en' ) );
2919 return false;
2920 }
2921
2922 $this->setOption( 'watchlisttoken', false );
2923 SessionManager::singleton()->invalidateSessionsForUser( $this );
2924
2925 return true;
2926 }
2927
2928 /**
2929 * Changes credentials of the user.
2930 *
2931 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2932 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2933 * e.g. when no provider handled the change.
2934 *
2935 * @param array $data A set of authentication data in fieldname => value format. This is the
2936 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2937 * @return Status
2938 * @since 1.27
2939 */
2940 public function changeAuthenticationData( array $data ) {
2941 $manager = AuthManager::singleton();
2942 $reqs = $manager->getAuthenticationRequests( AuthManager::ACTION_CHANGE, $this );
2943 $reqs = AuthenticationRequest::loadRequestsFromSubmission( $reqs, $data );
2944
2945 $status = Status::newGood( 'ignored' );
2946 foreach ( $reqs as $req ) {
2947 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2948 }
2949 if ( $status->getValue() === 'ignored' ) {
2950 $status->warning( 'authenticationdatachange-ignored' );
2951 }
2952
2953 if ( $status->isGood() ) {
2954 foreach ( $reqs as $req ) {
2955 $manager->changeAuthenticationData( $req );
2956 }
2957 }
2958 return $status;
2959 }
2960
2961 /**
2962 * Get the user's current token.
2963 * @param bool $forceCreation Force the generation of a new token if the
2964 * user doesn't have one (default=true for backwards compatibility).
2965 * @return string|null Token
2966 */
2967 public function getToken( $forceCreation = true ) {
2968 global $wgAuthenticationTokenVersion;
2969
2970 $this->load();
2971 if ( !$this->mToken && $forceCreation ) {
2972 $this->setToken();
2973 }
2974
2975 if ( !$this->mToken ) {
2976 // The user doesn't have a token, return null to indicate that.
2977 return null;
2978 } elseif ( $this->mToken === self::INVALID_TOKEN ) {
2979 // We return a random value here so existing token checks are very
2980 // likely to fail.
2981 return MWCryptRand::generateHex( self::TOKEN_LENGTH );
2982 } elseif ( $wgAuthenticationTokenVersion === null ) {
2983 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2984 return $this->mToken;
2985 } else {
2986 // $wgAuthenticationTokenVersion in use, so hmac it.
2987 $ret = MWCryptHash::hmac( $wgAuthenticationTokenVersion, $this->mToken, false );
2988
2989 // The raw hash can be overly long. Shorten it up.
2990 $len = max( 32, self::TOKEN_LENGTH );
2991 if ( strlen( $ret ) < $len ) {
2992 // Should never happen, even md5 is 128 bits
2993 throw new \UnexpectedValueException( 'Hmac returned less than 128 bits' );
2994 }
2995 return substr( $ret, -$len );
2996 }
2997 }
2998
2999 /**
3000 * Set the random token (used for persistent authentication)
3001 * Called from loadDefaults() among other places.
3002 *
3003 * @param string|bool $token If specified, set the token to this value
3004 */
3005 public function setToken( $token = false ) {
3006 $this->load();
3007 if ( $this->mToken === self::INVALID_TOKEN ) {
3008 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3009 ->debug( __METHOD__ . ": Ignoring attempt to set token for system user \"$this\"" );
3010 } elseif ( !$token ) {
3011 $this->mToken = MWCryptRand::generateHex( self::TOKEN_LENGTH );
3012 } else {
3013 $this->mToken = $token;
3014 }
3015 }
3016
3017 /**
3018 * Set the password for a password reminder or new account email
3019 *
3020 * @deprecated Removed in 1.27. Use PasswordReset instead.
3021 * @param string $str New password to set or null to set an invalid
3022 * password hash meaning that the user will not be able to use it
3023 * @param bool $throttle If true, reset the throttle timestamp to the present
3024 */
3025 public function setNewpassword( $str, $throttle = true ) {
3026 throw new BadMethodCallException( __METHOD__ . ' has been removed in 1.27' );
3027 }
3028
3029 /**
3030 * Get the user's e-mail address
3031 * @return string User's email address
3032 */
3033 public function getEmail() {
3034 $this->load();
3035 Hooks::run( 'UserGetEmail', [ $this, &$this->mEmail ] );
3036 return $this->mEmail;
3037 }
3038
3039 /**
3040 * Get the timestamp of the user's e-mail authentication
3041 * @return string TS_MW timestamp
3042 */
3043 public function getEmailAuthenticationTimestamp() {
3044 $this->load();
3045 Hooks::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated ] );
3046 return $this->mEmailAuthenticated;
3047 }
3048
3049 /**
3050 * Set the user's e-mail address
3051 * @param string $str New e-mail address
3052 */
3053 public function setEmail( $str ) {
3054 $this->load();
3055 if ( $str == $this->mEmail ) {
3056 return;
3057 }
3058 $this->invalidateEmail();
3059 $this->mEmail = $str;
3060 Hooks::run( 'UserSetEmail', [ $this, &$this->mEmail ] );
3061 }