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