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