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