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