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