869adca44bb2e99393185d08dce5c8525c53f7f1
[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 $newUser->mName = $fields['user_name'];
4354 $newUser->setItemLoaded( 'name' );
4355 $newUser->updateActorId( $dbw );
4356 } else {
4357 $newUser = null;
4358 }
4359 return $newUser;
4360 } );
4361 }
4362
4363 /**
4364 * Add this existing user object to the database. If the user already
4365 * exists, a fatal status object is returned, and the user object is
4366 * initialised with the data from the database.
4367 *
4368 * Previously, this function generated a DB error due to a key conflict
4369 * if the user already existed. Many extension callers use this function
4370 * in code along the lines of:
4371 *
4372 * $user = User::newFromName( $name );
4373 * if ( !$user->isLoggedIn() ) {
4374 * $user->addToDatabase();
4375 * }
4376 * // do something with $user...
4377 *
4378 * However, this was vulnerable to a race condition (T18020). By
4379 * initialising the user object if the user exists, we aim to support this
4380 * calling sequence as far as possible.
4381 *
4382 * Note that if the user exists, this function will acquire a write lock,
4383 * so it is still advisable to make the call conditional on isLoggedIn(),
4384 * and to commit the transaction after calling.
4385 *
4386 * @throws MWException
4387 * @return Status
4388 */
4389 public function addToDatabase() {
4390 $this->load();
4391 if ( !$this->mToken ) {
4392 $this->setToken(); // init token
4393 }
4394
4395 if ( !is_string( $this->mName ) ) {
4396 throw new RuntimeException( "User name field is not set." );
4397 }
4398
4399 $this->mTouched = $this->newTouchedTimestamp();
4400
4401 $dbw = wfGetDB( DB_MASTER );
4402 $status = $dbw->doAtomicSection( __METHOD__, function ( $dbw, $fname ) {
4403 $noPass = PasswordFactory::newInvalidPassword()->toString();
4404 $dbw->insert( 'user',
4405 [
4406 'user_name' => $this->mName,
4407 'user_password' => $noPass,
4408 'user_newpassword' => $noPass,
4409 'user_email' => $this->mEmail,
4410 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
4411 'user_real_name' => $this->mRealName,
4412 'user_token' => strval( $this->mToken ),
4413 'user_registration' => $dbw->timestamp( $this->mRegistration ),
4414 'user_editcount' => 0,
4415 'user_touched' => $dbw->timestamp( $this->mTouched ),
4416 ], $fname,
4417 [ 'IGNORE' ]
4418 );
4419 if ( !$dbw->affectedRows() ) {
4420 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4421 $this->mId = $dbw->selectField(
4422 'user',
4423 'user_id',
4424 [ 'user_name' => $this->mName ],
4425 __METHOD__,
4426 [ 'LOCK IN SHARE MODE' ]
4427 );
4428 $loaded = false;
4429 if ( $this->mId ) {
4430 if ( $this->loadFromDatabase( self::READ_LOCKING ) ) {
4431 $loaded = true;
4432 }
4433 }
4434 if ( !$loaded ) {
4435 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
4436 "to insert user '{$this->mName}' row, but it was not present in select!" );
4437 }
4438 return Status::newFatal( 'userexists' );
4439 }
4440 $this->mId = $dbw->insertId();
4441 self::$idCacheByName[$this->mName] = $this->mId;
4442 $this->updateActorId( $dbw );
4443
4444 return Status::newGood();
4445 } );
4446 if ( !$status->isGood() ) {
4447 return $status;
4448 }
4449
4450 // Clear instance cache other than user table data and actor, which is already accurate
4451 $this->clearInstanceCache();
4452
4453 $this->saveOptions();
4454 return Status::newGood();
4455 }
4456
4457 /**
4458 * Update the actor ID after an insert
4459 * @param IDatabase $dbw Writable database handle
4460 */
4461 private function updateActorId( IDatabase $dbw ) {
4462 global $wgActorTableSchemaMigrationStage;
4463
4464 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD ) {
4465 $dbw->insert(
4466 'actor',
4467 [ 'actor_user' => $this->mId, 'actor_name' => $this->mName ],
4468 __METHOD__
4469 );
4470 $this->mActorId = (int)$dbw->insertId();
4471 }
4472 }
4473
4474 /**
4475 * If this user is logged-in and blocked,
4476 * block any IP address they've successfully logged in from.
4477 * @return bool A block was spread
4478 */
4479 public function spreadAnyEditBlock() {
4480 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4481 return $this->spreadBlock();
4482 }
4483
4484 return false;
4485 }
4486
4487 /**
4488 * If this (non-anonymous) user is blocked,
4489 * block the IP address they've successfully logged in from.
4490 * @return bool A block was spread
4491 */
4492 protected function spreadBlock() {
4493 wfDebug( __METHOD__ . "()\n" );
4494 $this->load();
4495 if ( $this->mId == 0 ) {
4496 return false;
4497 }
4498
4499 $userblock = Block::newFromTarget( $this->getName() );
4500 if ( !$userblock ) {
4501 return false;
4502 }
4503
4504 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4505 }
4506
4507 /**
4508 * Get whether the user is explicitly blocked from account creation.
4509 * @return bool|Block
4510 */
4511 public function isBlockedFromCreateAccount() {
4512 $this->getBlockedStatus();
4513 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
4514 return $this->mBlock;
4515 }
4516
4517 # T15611: if the IP address the user is trying to create an account from is
4518 # blocked with createaccount disabled, prevent new account creation there even
4519 # when the user is logged in
4520 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4521 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
4522 }
4523 return $this->mBlockedFromCreateAccount instanceof Block
4524 && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
4525 ? $this->mBlockedFromCreateAccount
4526 : false;
4527 }
4528
4529 /**
4530 * Get whether the user is blocked from using Special:Emailuser.
4531 * @return bool
4532 */
4533 public function isBlockedFromEmailuser() {
4534 $this->getBlockedStatus();
4535 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
4536 }
4537
4538 /**
4539 * Get whether the user is allowed to create an account.
4540 * @return bool
4541 */
4542 public function isAllowedToCreateAccount() {
4543 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4544 }
4545
4546 /**
4547 * Get this user's personal page title.
4548 *
4549 * @return Title User's personal page title
4550 */
4551 public function getUserPage() {
4552 return Title::makeTitle( NS_USER, $this->getName() );
4553 }
4554
4555 /**
4556 * Get this user's talk page title.
4557 *
4558 * @return Title User's talk page title
4559 */
4560 public function getTalkPage() {
4561 $title = $this->getUserPage();
4562 return $title->getTalkPage();
4563 }
4564
4565 /**
4566 * Determine whether the user is a newbie. Newbies are either
4567 * anonymous IPs, or the most recently created accounts.
4568 * @return bool
4569 */
4570 public function isNewbie() {
4571 return !$this->isAllowed( 'autoconfirmed' );
4572 }
4573
4574 /**
4575 * Check to see if the given clear-text password is one of the accepted passwords
4576 * @deprecated since 1.27, use AuthManager instead
4577 * @param string $password User password
4578 * @return bool True if the given password is correct, otherwise False
4579 */
4580 public function checkPassword( $password ) {
4581 $manager = AuthManager::singleton();
4582 $reqs = AuthenticationRequest::loadRequestsFromSubmission(
4583 $manager->getAuthenticationRequests( AuthManager::ACTION_LOGIN ),
4584 [
4585 'username' => $this->getName(),
4586 'password' => $password,
4587 ]
4588 );
4589 $res = AuthManager::singleton()->beginAuthentication( $reqs, 'null:' );
4590 switch ( $res->status ) {
4591 case AuthenticationResponse::PASS:
4592 return true;
4593 case AuthenticationResponse::FAIL:
4594 // Hope it's not a PreAuthenticationProvider that failed...
4595 \MediaWiki\Logger\LoggerFactory::getInstance( 'authentication' )
4596 ->info( __METHOD__ . ': Authentication failed: ' . $res->message->plain() );
4597 return false;
4598 default:
4599 throw new BadMethodCallException(
4600 'AuthManager returned a response unsupported by ' . __METHOD__
4601 );
4602 }
4603 }
4604
4605 /**
4606 * Check if the given clear-text password matches the temporary password
4607 * sent by e-mail for password reset operations.
4608 *
4609 * @deprecated since 1.27, use AuthManager instead
4610 * @param string $plaintext
4611 * @return bool True if matches, false otherwise
4612 */
4613 public function checkTemporaryPassword( $plaintext ) {
4614 // Can't check the temporary password individually.
4615 return $this->checkPassword( $plaintext );
4616 }
4617
4618 /**
4619 * Initialize (if necessary) and return a session token value
4620 * which can be used in edit forms to show that the user's
4621 * login credentials aren't being hijacked with a foreign form
4622 * submission.
4623 *
4624 * @since 1.27
4625 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4626 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4627 * @return MediaWiki\Session\Token The new edit token
4628 */
4629 public function getEditTokenObject( $salt = '', $request = null ) {
4630 if ( $this->isAnon() ) {
4631 return new LoggedOutEditToken();
4632 }
4633
4634 if ( !$request ) {
4635 $request = $this->getRequest();
4636 }
4637 return $request->getSession()->getToken( $salt );
4638 }
4639
4640 /**
4641 * Initialize (if necessary) and return a session token value
4642 * which can be used in edit forms to show that the user's
4643 * login credentials aren't being hijacked with a foreign form
4644 * submission.
4645 *
4646 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4647 *
4648 * @since 1.19
4649 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4650 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4651 * @return string The new edit token
4652 */
4653 public function getEditToken( $salt = '', $request = null ) {
4654 return $this->getEditTokenObject( $salt, $request )->toString();
4655 }
4656
4657 /**
4658 * Get the embedded timestamp from a token.
4659 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4660 * @param string $val Input token
4661 * @return int|null
4662 */
4663 public static function getEditTokenTimestamp( $val ) {
4664 wfDeprecated( __METHOD__, '1.27' );
4665 return MediaWiki\Session\Token::getTimestamp( $val );
4666 }
4667
4668 /**
4669 * Check given value against the token value stored in the session.
4670 * A match should confirm that the form was submitted from the
4671 * user's own login session, not a form submission from a third-party
4672 * site.
4673 *
4674 * @param string $val Input value to compare
4675 * @param string $salt Optional function-specific data for hashing
4676 * @param WebRequest|null $request Object to use or null to use $wgRequest
4677 * @param int $maxage Fail tokens older than this, in seconds
4678 * @return bool Whether the token matches
4679 */
4680 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4681 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4682 }
4683
4684 /**
4685 * Check given value against the token value stored in the session,
4686 * ignoring the suffix.
4687 *
4688 * @param string $val Input value to compare
4689 * @param string $salt Optional function-specific data for hashing
4690 * @param WebRequest|null $request Object to use or null to use $wgRequest
4691 * @param int $maxage Fail tokens older than this, in seconds
4692 * @return bool Whether the token matches
4693 */
4694 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4695 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token::SUFFIX;
4696 return $this->matchEditToken( $val, $salt, $request, $maxage );
4697 }
4698
4699 /**
4700 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4701 * mail to the user's given address.
4702 *
4703 * @param string $type Message to send, either "created", "changed" or "set"
4704 * @return Status
4705 */
4706 public function sendConfirmationMail( $type = 'created' ) {
4707 global $wgLang;
4708 $expiration = null; // gets passed-by-ref and defined in next line.
4709 $token = $this->confirmationToken( $expiration );
4710 $url = $this->confirmationTokenUrl( $token );
4711 $invalidateURL = $this->invalidationTokenUrl( $token );
4712 $this->saveSettings();
4713
4714 if ( $type == 'created' || $type === false ) {
4715 $message = 'confirmemail_body';
4716 } elseif ( $type === true ) {
4717 $message = 'confirmemail_body_changed';
4718 } else {
4719 // Messages: confirmemail_body_changed, confirmemail_body_set
4720 $message = 'confirmemail_body_' . $type;
4721 }
4722
4723 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4724 wfMessage( $message,
4725 $this->getRequest()->getIP(),
4726 $this->getName(),
4727 $url,
4728 $wgLang->userTimeAndDate( $expiration, $this ),
4729 $invalidateURL,
4730 $wgLang->userDate( $expiration, $this ),
4731 $wgLang->userTime( $expiration, $this ) )->text() );
4732 }
4733
4734 /**
4735 * Send an e-mail to this user's account. Does not check for
4736 * confirmed status or validity.
4737 *
4738 * @param string $subject Message subject
4739 * @param string $body Message body
4740 * @param User|null $from Optional sending user; if unspecified, default
4741 * $wgPasswordSender will be used.
4742 * @param string $replyto Reply-To address
4743 * @return Status
4744 */
4745 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4746 global $wgPasswordSender;
4747
4748 if ( $from instanceof User ) {
4749 $sender = MailAddress::newFromUser( $from );
4750 } else {
4751 $sender = new MailAddress( $wgPasswordSender,
4752 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4753 }
4754 $to = MailAddress::newFromUser( $this );
4755
4756 return UserMailer::send( $to, $sender, $subject, $body, [
4757 'replyTo' => $replyto,
4758 ] );
4759 }
4760
4761 /**
4762 * Generate, store, and return a new e-mail confirmation code.
4763 * A hash (unsalted, since it's used as a key) is stored.
4764 *
4765 * @note Call saveSettings() after calling this function to commit
4766 * this change to the database.
4767 *
4768 * @param string &$expiration Accepts the expiration time
4769 * @return string New token
4770 */
4771 protected function confirmationToken( &$expiration ) {
4772 global $wgUserEmailConfirmationTokenExpiry;
4773 $now = time();
4774 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
4775 $expiration = wfTimestamp( TS_MW, $expires );
4776 $this->load();
4777 $token = MWCryptRand::generateHex( 32 );
4778 $hash = md5( $token );
4779 $this->mEmailToken = $hash;
4780 $this->mEmailTokenExpires = $expiration;
4781 return $token;
4782 }
4783
4784 /**
4785 * Return a URL the user can use to confirm their email address.
4786 * @param string $token Accepts the email confirmation token
4787 * @return string New token URL
4788 */
4789 protected function confirmationTokenUrl( $token ) {
4790 return $this->getTokenUrl( 'ConfirmEmail', $token );
4791 }
4792
4793 /**
4794 * Return a URL the user can use to invalidate their email address.
4795 * @param string $token Accepts the email confirmation token
4796 * @return string New token URL
4797 */
4798 protected function invalidationTokenUrl( $token ) {
4799 return $this->getTokenUrl( 'InvalidateEmail', $token );
4800 }
4801
4802 /**
4803 * Internal function to format the e-mail validation/invalidation URLs.
4804 * This uses a quickie hack to use the
4805 * hardcoded English names of the Special: pages, for ASCII safety.
4806 *
4807 * @note Since these URLs get dropped directly into emails, using the
4808 * short English names avoids insanely long URL-encoded links, which
4809 * also sometimes can get corrupted in some browsers/mailers
4810 * (T8957 with Gmail and Internet Explorer).
4811 *
4812 * @param string $page Special page
4813 * @param string $token
4814 * @return string Formatted URL
4815 */
4816 protected function getTokenUrl( $page, $token ) {
4817 // Hack to bypass localization of 'Special:'
4818 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
4819 return $title->getCanonicalURL();
4820 }
4821
4822 /**
4823 * Mark the e-mail address confirmed.
4824 *
4825 * @note Call saveSettings() after calling this function to commit the change.
4826 *
4827 * @return bool
4828 */
4829 public function confirmEmail() {
4830 // Check if it's already confirmed, so we don't touch the database
4831 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4832 if ( !$this->isEmailConfirmed() ) {
4833 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4834 Hooks::run( 'ConfirmEmailComplete', [ $this ] );
4835 }
4836 return true;
4837 }
4838
4839 /**
4840 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4841 * address if it was already confirmed.
4842 *
4843 * @note Call saveSettings() after calling this function to commit the change.
4844 * @return bool Returns true
4845 */
4846 public function invalidateEmail() {
4847 $this->load();
4848 $this->mEmailToken = null;
4849 $this->mEmailTokenExpires = null;
4850 $this->setEmailAuthenticationTimestamp( null );
4851 $this->mEmail = '';
4852 Hooks::run( 'InvalidateEmailComplete', [ $this ] );
4853 return true;
4854 }
4855
4856 /**
4857 * Set the e-mail authentication timestamp.
4858 * @param string $timestamp TS_MW timestamp
4859 */
4860 public function setEmailAuthenticationTimestamp( $timestamp ) {
4861 $this->load();
4862 $this->mEmailAuthenticated = $timestamp;
4863 Hooks::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated ] );
4864 }
4865
4866 /**
4867 * Is this user allowed to send e-mails within limits of current
4868 * site configuration?
4869 * @return bool
4870 */
4871 public function canSendEmail() {
4872 global $wgEnableEmail, $wgEnableUserEmail;
4873 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4874 return false;
4875 }
4876 $canSend = $this->isEmailConfirmed();
4877 // Avoid PHP 7.1 warning of passing $this by reference
4878 $user = $this;
4879 Hooks::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4880 return $canSend;
4881 }
4882
4883 /**
4884 * Is this user allowed to receive e-mails within limits of current
4885 * site configuration?
4886 * @return bool
4887 */
4888 public function canReceiveEmail() {
4889 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4890 }
4891
4892 /**
4893 * Is this user's e-mail address valid-looking and confirmed within
4894 * limits of the current site configuration?
4895 *
4896 * @note If $wgEmailAuthentication is on, this may require the user to have
4897 * confirmed their address by returning a code or using a password
4898 * sent to the address from the wiki.
4899 *
4900 * @return bool
4901 */
4902 public function isEmailConfirmed() {
4903 global $wgEmailAuthentication;
4904 $this->load();
4905 // Avoid PHP 7.1 warning of passing $this by reference
4906 $user = $this;
4907 $confirmed = true;
4908 if ( Hooks::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4909 if ( $this->isAnon() ) {
4910 return false;
4911 }
4912 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4913 return false;
4914 }
4915 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4916 return false;
4917 }
4918 return true;
4919 } else {
4920 return $confirmed;
4921 }
4922 }
4923
4924 /**
4925 * Check whether there is an outstanding request for e-mail confirmation.
4926 * @return bool
4927 */
4928 public function isEmailConfirmationPending() {
4929 global $wgEmailAuthentication;
4930 return $wgEmailAuthentication &&
4931 !$this->isEmailConfirmed() &&
4932 $this->mEmailToken &&
4933 $this->mEmailTokenExpires > wfTimestamp();
4934 }
4935
4936 /**
4937 * Get the timestamp of account creation.
4938 *
4939 * @return string|bool|null Timestamp of account creation, false for
4940 * non-existent/anonymous user accounts, or null if existing account
4941 * but information is not in database.
4942 */
4943 public function getRegistration() {
4944 if ( $this->isAnon() ) {
4945 return false;
4946 }
4947 $this->load();
4948 return $this->mRegistration;
4949 }
4950
4951 /**
4952 * Get the timestamp of the first edit
4953 *
4954 * @return string|bool Timestamp of first edit, or false for
4955 * non-existent/anonymous user accounts.
4956 */
4957 public function getFirstEditTimestamp() {
4958 if ( $this->getId() == 0 ) {
4959 return false; // anons
4960 }
4961 $dbr = wfGetDB( DB_REPLICA );
4962 $actorWhere = ActorMigration::newMigration()->getWhere( $dbr, 'rev_user', $this );
4963 $time = $dbr->selectField(
4964 [ 'revision' ] + $actorWhere['tables'],
4965 'rev_timestamp',
4966 [ $actorWhere['conds'] ],
4967 __METHOD__,
4968 [ 'ORDER BY' => 'rev_timestamp ASC' ],
4969 $actorWhere['joins']
4970 );
4971 if ( !$time ) {
4972 return false; // no edits
4973 }
4974 return wfTimestamp( TS_MW, $time );
4975 }
4976
4977 /**
4978 * Get the permissions associated with a given list of groups
4979 *
4980 * @param array $groups Array of Strings List of internal group names
4981 * @return array Array of Strings List of permission key names for given groups combined
4982 */
4983 public static function getGroupPermissions( $groups ) {
4984 global $wgGroupPermissions, $wgRevokePermissions;
4985 $rights = [];
4986 // grant every granted permission first
4987 foreach ( $groups as $group ) {
4988 if ( isset( $wgGroupPermissions[$group] ) ) {
4989 $rights = array_merge( $rights,
4990 // array_filter removes empty items
4991 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4992 }
4993 }
4994 // now revoke the revoked permissions
4995 foreach ( $groups as $group ) {
4996 if ( isset( $wgRevokePermissions[$group] ) ) {
4997 $rights = array_diff( $rights,
4998 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4999 }
5000 }
5001 return array_unique( $rights );
5002 }
5003
5004 /**
5005 * Get all the groups who have a given permission
5006 *
5007 * @param string $role Role to check
5008 * @return array Array of Strings List of internal group names with the given permission
5009 */
5010 public static function getGroupsWithPermission( $role ) {
5011 global $wgGroupPermissions;
5012 $allowedGroups = [];
5013 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
5014 if ( self::groupHasPermission( $group, $role ) ) {
5015 $allowedGroups[] = $group;
5016 }
5017 }
5018 return $allowedGroups;
5019 }
5020
5021 /**
5022 * Check, if the given group has the given permission
5023 *
5024 * If you're wanting to check whether all users have a permission, use
5025 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
5026 * from anyone.
5027 *
5028 * @since 1.21
5029 * @param string $group Group to check
5030 * @param string $role Role to check
5031 * @return bool
5032 */
5033 public static function groupHasPermission( $group, $role ) {
5034 global $wgGroupPermissions, $wgRevokePermissions;
5035 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
5036 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
5037 }
5038
5039 /**
5040 * Check if all users may be assumed to have the given permission
5041 *
5042 * We generally assume so if the right is granted to '*' and isn't revoked
5043 * on any group. It doesn't attempt to take grants or other extension
5044 * limitations on rights into account in the general case, though, as that
5045 * would require it to always return false and defeat the purpose.
5046 * Specifically, session-based rights restrictions (such as OAuth or bot
5047 * passwords) are applied based on the current session.
5048 *
5049 * @since 1.22
5050 * @param string $right Right to check
5051 * @return bool
5052 */
5053 public static function isEveryoneAllowed( $right ) {
5054 global $wgGroupPermissions, $wgRevokePermissions;
5055 static $cache = [];
5056
5057 // Use the cached results, except in unit tests which rely on
5058 // being able change the permission mid-request
5059 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
5060 return $cache[$right];
5061 }
5062
5063 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
5064 $cache[$right] = false;
5065 return false;
5066 }
5067
5068 // If it's revoked anywhere, then everyone doesn't have it
5069 foreach ( $wgRevokePermissions as $rights ) {
5070 if ( isset( $rights[$right] ) && $rights[$right] ) {
5071 $cache[$right] = false;
5072 return false;
5073 }
5074 }
5075
5076 // Remove any rights that aren't allowed to the global-session user,
5077 // unless there are no sessions for this endpoint.
5078 if ( !defined( 'MW_NO_SESSION' ) ) {
5079 $allowedRights = SessionManager::getGlobalSession()->getAllowedUserRights();
5080 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
5081 $cache[$right] = false;
5082 return false;
5083 }
5084 }
5085
5086 // Allow extensions to say false
5087 if ( !Hooks::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
5088 $cache[$right] = false;
5089 return false;
5090 }
5091
5092 $cache[$right] = true;
5093 return true;
5094 }
5095
5096 /**
5097 * Get the localized descriptive name for a group, if it exists
5098 * @deprecated since 1.29 Use UserGroupMembership::getGroupName instead
5099 *
5100 * @param string $group Internal group name
5101 * @return string Localized descriptive group name
5102 */
5103 public static function getGroupName( $group ) {
5104 wfDeprecated( __METHOD__, '1.29' );
5105 return UserGroupMembership::getGroupName( $group );
5106 }
5107
5108 /**
5109 * Get the localized descriptive name for a member of a group, if it exists
5110 * @deprecated since 1.29 Use UserGroupMembership::getGroupMemberName instead
5111 *
5112 * @param string $group Internal group name
5113 * @param string $username Username for gender (since 1.19)
5114 * @return string Localized name for group member
5115 */
5116 public static function getGroupMember( $group, $username = '#' ) {
5117 wfDeprecated( __METHOD__, '1.29' );
5118 return UserGroupMembership::getGroupMemberName( $group, $username );
5119 }
5120
5121 /**
5122 * Return the set of defined explicit groups.
5123 * The implicit groups (by default *, 'user' and 'autoconfirmed')
5124 * are not included, as they are defined automatically, not in the database.
5125 * @return array Array of internal group names
5126 */
5127 public static function getAllGroups() {
5128 global $wgGroupPermissions, $wgRevokePermissions;
5129 return array_diff(
5130 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
5131 self::getImplicitGroups()
5132 );
5133 }
5134
5135 /**
5136 * Get a list of all available permissions.
5137 * @return string[] Array of permission names
5138 */
5139 public static function getAllRights() {
5140 if ( self::$mAllRights === false ) {
5141 global $wgAvailableRights;
5142 if ( count( $wgAvailableRights ) ) {
5143 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
5144 } else {
5145 self::$mAllRights = self::$mCoreRights;
5146 }
5147 Hooks::run( 'UserGetAllRights', [ &self::$mAllRights ] );
5148 }
5149 return self::$mAllRights;
5150 }
5151
5152 /**
5153 * Get a list of implicit groups
5154 * @return array Array of Strings Array of internal group names
5155 */
5156 public static function getImplicitGroups() {
5157 global $wgImplicitGroups;
5158
5159 $groups = $wgImplicitGroups;
5160 # Deprecated, use $wgImplicitGroups instead
5161 Hooks::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
5162
5163 return $groups;
5164 }
5165
5166 /**
5167 * Get the title of a page describing a particular group
5168 * @deprecated since 1.29 Use UserGroupMembership::getGroupPage instead
5169 *
5170 * @param string $group Internal group name
5171 * @return Title|bool Title of the page if it exists, false otherwise
5172 */
5173 public static function getGroupPage( $group ) {
5174 wfDeprecated( __METHOD__, '1.29' );
5175 return UserGroupMembership::getGroupPage( $group );
5176 }
5177
5178 /**
5179 * Create a link to the group in HTML, if available;
5180 * else return the group name.
5181 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
5182 * make the link yourself if you need custom text
5183 *
5184 * @param string $group Internal name of the group
5185 * @param string $text The text of the link
5186 * @return string HTML link to the group
5187 */
5188 public static function makeGroupLinkHTML( $group, $text = '' ) {
5189 wfDeprecated( __METHOD__, '1.29' );
5190
5191 if ( $text == '' ) {
5192 $text = UserGroupMembership::getGroupName( $group );
5193 }
5194 $title = UserGroupMembership::getGroupPage( $group );
5195 if ( $title ) {
5196 return MediaWikiServices::getInstance()
5197 ->getLinkRenderer()->makeLink( $title, $text );
5198 } else {
5199 return htmlspecialchars( $text );
5200 }
5201 }
5202
5203 /**
5204 * Create a link to the group in Wikitext, if available;
5205 * else return the group name.
5206 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
5207 * make the link yourself if you need custom text
5208 *
5209 * @param string $group Internal name of the group
5210 * @param string $text The text of the link
5211 * @return string Wikilink to the group
5212 */
5213 public static function makeGroupLinkWiki( $group, $text = '' ) {
5214 wfDeprecated( __METHOD__, '1.29' );
5215
5216 if ( $text == '' ) {
5217 $text = UserGroupMembership::getGroupName( $group );
5218 }
5219 $title = UserGroupMembership::getGroupPage( $group );
5220 if ( $title ) {
5221 $page = $title->getFullText();
5222 return "[[$page|$text]]";
5223 } else {
5224 return $text;
5225 }
5226 }
5227
5228 /**
5229 * Returns an array of the groups that a particular group can add/remove.
5230 *
5231 * @param string $group The group to check for whether it can add/remove
5232 * @return array Array( 'add' => array( addablegroups ),
5233 * 'remove' => array( removablegroups ),
5234 * 'add-self' => array( addablegroups to self),
5235 * 'remove-self' => array( removable groups from self) )
5236 */
5237 public static function changeableByGroup( $group ) {
5238 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
5239
5240 $groups = [
5241 'add' => [],
5242 'remove' => [],
5243 'add-self' => [],
5244 'remove-self' => []
5245 ];
5246
5247 if ( empty( $wgAddGroups[$group] ) ) {
5248 // Don't add anything to $groups
5249 } elseif ( $wgAddGroups[$group] === true ) {
5250 // You get everything
5251 $groups['add'] = self::getAllGroups();
5252 } elseif ( is_array( $wgAddGroups[$group] ) ) {
5253 $groups['add'] = $wgAddGroups[$group];
5254 }
5255
5256 // Same thing for remove
5257 if ( empty( $wgRemoveGroups[$group] ) ) {
5258 // Do nothing
5259 } elseif ( $wgRemoveGroups[$group] === true ) {
5260 $groups['remove'] = self::getAllGroups();
5261 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
5262 $groups['remove'] = $wgRemoveGroups[$group];
5263 }
5264
5265 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
5266 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
5267 foreach ( $wgGroupsAddToSelf as $key => $value ) {
5268 if ( is_int( $key ) ) {
5269 $wgGroupsAddToSelf['user'][] = $value;
5270 }
5271 }
5272 }
5273
5274 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
5275 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
5276 if ( is_int( $key ) ) {
5277 $wgGroupsRemoveFromSelf['user'][] = $value;
5278 }
5279 }
5280 }
5281
5282 // Now figure out what groups the user can add to him/herself
5283 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
5284 // Do nothing
5285 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
5286 // No idea WHY this would be used, but it's there
5287 $groups['add-self'] = self::getAllGroups();
5288 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
5289 $groups['add-self'] = $wgGroupsAddToSelf[$group];
5290 }
5291
5292 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
5293 // Do nothing
5294 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
5295 $groups['remove-self'] = self::getAllGroups();
5296 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
5297 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
5298 }
5299
5300 return $groups;
5301 }
5302
5303 /**
5304 * Returns an array of groups that this user can add and remove
5305 * @return array Array( 'add' => array( addablegroups ),
5306 * 'remove' => array( removablegroups ),
5307 * 'add-self' => array( addablegroups to self),
5308 * 'remove-self' => array( removable groups from self) )
5309 */
5310 public function changeableGroups() {
5311 if ( $this->isAllowed( 'userrights' ) ) {
5312 // This group gives the right to modify everything (reverse-
5313 // compatibility with old "userrights lets you change
5314 // everything")
5315 // Using array_merge to make the groups reindexed
5316 $all = array_merge( self::getAllGroups() );
5317 return [
5318 'add' => $all,
5319 'remove' => $all,
5320 'add-self' => [],
5321 'remove-self' => []
5322 ];
5323 }
5324
5325 // Okay, it's not so simple, we will have to go through the arrays
5326 $groups = [
5327 'add' => [],
5328 'remove' => [],
5329 'add-self' => [],
5330 'remove-self' => []
5331 ];
5332 $addergroups = $this->getEffectiveGroups();
5333
5334 foreach ( $addergroups as $addergroup ) {
5335 $groups = array_merge_recursive(
5336 $groups, $this->changeableByGroup( $addergroup )
5337 );
5338 $groups['add'] = array_unique( $groups['add'] );
5339 $groups['remove'] = array_unique( $groups['remove'] );
5340 $groups['add-self'] = array_unique( $groups['add-self'] );
5341 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5342 }
5343 return $groups;
5344 }
5345
5346 /**
5347 * Deferred version of incEditCountImmediate()
5348 *
5349 * This function, rather than incEditCountImmediate(), should be used for
5350 * most cases as it avoids potential deadlocks caused by concurrent editing.
5351 */
5352 public function incEditCount() {
5353 wfGetDB( DB_MASTER )->onTransactionPreCommitOrIdle(
5354 function () {
5355 $this->incEditCountImmediate();
5356 },
5357 __METHOD__
5358 );
5359 }
5360
5361 /**
5362 * Increment the user's edit-count field.
5363 * Will have no effect for anonymous users.
5364 * @since 1.26
5365 */
5366 public function incEditCountImmediate() {
5367 if ( $this->isAnon() ) {
5368 return;
5369 }
5370
5371 $dbw = wfGetDB( DB_MASTER );
5372 // No rows will be "affected" if user_editcount is NULL
5373 $dbw->update(
5374 'user',
5375 [ 'user_editcount=user_editcount+1' ],
5376 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5377 __METHOD__
5378 );
5379 // Lazy initialization check...
5380 if ( $dbw->affectedRows() == 0 ) {
5381 // Now here's a goddamn hack...
5382 $dbr = wfGetDB( DB_REPLICA );
5383 if ( $dbr !== $dbw ) {
5384 // If we actually have a replica DB server, the count is
5385 // at least one behind because the current transaction
5386 // has not been committed and replicated.
5387 $this->mEditCount = $this->initEditCount( 1 );
5388 } else {
5389 // But if DB_REPLICA is selecting the master, then the
5390 // count we just read includes the revision that was
5391 // just added in the working transaction.
5392 $this->mEditCount = $this->initEditCount();
5393 }
5394 } else {
5395 if ( $this->mEditCount === null ) {
5396 $this->getEditCount();
5397 $dbr = wfGetDB( DB_REPLICA );
5398 $this->mEditCount += ( $dbr !== $dbw ) ? 1 : 0;
5399 } else {
5400 $this->mEditCount++;
5401 }
5402 }
5403 // Edit count in user cache too
5404 $this->invalidateCache();
5405 }
5406
5407 /**
5408 * Initialize user_editcount from data out of the revision table
5409 *
5410 * @param int $add Edits to add to the count from the revision table
5411 * @return int Number of edits
5412 */
5413 protected function initEditCount( $add = 0 ) {
5414 // Pull from a replica DB to be less cruel to servers
5415 // Accuracy isn't the point anyway here
5416 $dbr = wfGetDB( DB_REPLICA );
5417 $actorWhere = ActorMigration::newMigration()->getWhere( $dbr, 'rev_user', $this );
5418 $count = (int)$dbr->selectField(
5419 [ 'revision' ] + $actorWhere['tables'],
5420 'COUNT(*)',
5421 [ $actorWhere['conds'] ],
5422 __METHOD__,
5423 [],
5424 $actorWhere['joins']
5425 );
5426 $count = $count + $add;
5427
5428 $dbw = wfGetDB( DB_MASTER );
5429 $dbw->update(
5430 'user',
5431 [ 'user_editcount' => $count ],
5432 [ 'user_id' => $this->getId() ],
5433 __METHOD__
5434 );
5435
5436 return $count;
5437 }
5438
5439 /**
5440 * Get the description of a given right
5441 *
5442 * @since 1.29
5443 * @param string $right Right to query
5444 * @return string Localized description of the right
5445 */
5446 public static function getRightDescription( $right ) {
5447 $key = "right-$right";
5448 $msg = wfMessage( $key );
5449 return $msg->isDisabled() ? $right : $msg->text();
5450 }
5451
5452 /**
5453 * Get the name of a given grant
5454 *
5455 * @since 1.29
5456 * @param string $grant Grant to query
5457 * @return string Localized name of the grant
5458 */
5459 public static function getGrantName( $grant ) {
5460 $key = "grant-$grant";
5461 $msg = wfMessage( $key );
5462 return $msg->isDisabled() ? $grant : $msg->text();
5463 }
5464
5465 /**
5466 * Add a newuser log entry for this user.
5467 * Before 1.19 the return value was always true.
5468 *
5469 * @deprecated since 1.27, AuthManager handles logging
5470 * @param string|bool $action Account creation type.
5471 * - String, one of the following values:
5472 * - 'create' for an anonymous user creating an account for himself.
5473 * This will force the action's performer to be the created user itself,
5474 * no matter the value of $wgUser
5475 * - 'create2' for a logged in user creating an account for someone else
5476 * - 'byemail' when the created user will receive its password by e-mail
5477 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5478 * - Boolean means whether the account was created by e-mail (deprecated):
5479 * - true will be converted to 'byemail'
5480 * - false will be converted to 'create' if this object is the same as
5481 * $wgUser and to 'create2' otherwise
5482 * @param string $reason User supplied reason
5483 * @return bool true
5484 */
5485 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5486 return true; // disabled
5487 }
5488
5489 /**
5490 * Add an autocreate newuser log entry for this user
5491 * Used by things like CentralAuth and perhaps other authplugins.
5492 * Consider calling addNewUserLogEntry() directly instead.
5493 *
5494 * @deprecated since 1.27, AuthManager handles logging
5495 * @return bool
5496 */
5497 public function addNewUserLogEntryAutoCreate() {
5498 $this->addNewUserLogEntry( 'autocreate' );
5499
5500 return true;
5501 }
5502
5503 /**
5504 * Load the user options either from cache, the database or an array
5505 *
5506 * @param array $data Rows for the current user out of the user_properties table
5507 */
5508 protected function loadOptions( $data = null ) {
5509 global $wgContLang;
5510
5511 $this->load();
5512
5513 if ( $this->mOptionsLoaded ) {
5514 return;
5515 }
5516
5517 $this->mOptions = self::getDefaultOptions();
5518
5519 if ( !$this->getId() ) {
5520 // For unlogged-in users, load language/variant options from request.
5521 // There's no need to do it for logged-in users: they can set preferences,
5522 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5523 // so don't override user's choice (especially when the user chooses site default).
5524 $variant = $wgContLang->getDefaultVariant();
5525 $this->mOptions['variant'] = $variant;
5526 $this->mOptions['language'] = $variant;
5527 $this->mOptionsLoaded = true;
5528 return;
5529 }
5530
5531 // Maybe load from the object
5532 if ( !is_null( $this->mOptionOverrides ) ) {
5533 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5534 foreach ( $this->mOptionOverrides as $key => $value ) {
5535 $this->mOptions[$key] = $value;
5536 }
5537 } else {
5538 if ( !is_array( $data ) ) {
5539 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5540 // Load from database
5541 $dbr = ( $this->queryFlagsUsed & self::READ_LATEST )
5542 ? wfGetDB( DB_MASTER )
5543 : wfGetDB( DB_REPLICA );
5544
5545 $res = $dbr->select(
5546 'user_properties',
5547 [ 'up_property', 'up_value' ],
5548 [ 'up_user' => $this->getId() ],
5549 __METHOD__
5550 );
5551
5552 $this->mOptionOverrides = [];
5553 $data = [];
5554 foreach ( $res as $row ) {
5555 // Convert '0' to 0. PHP's boolean conversion considers them both
5556 // false, but e.g. JavaScript considers the former as true.
5557 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5558 // and convert all values here.
5559 if ( $row->up_value === '0' ) {
5560 $row->up_value = 0;
5561 }
5562 $data[$row->up_property] = $row->up_value;
5563 }
5564 }
5565
5566 // Convert the email blacklist from a new line delimited string
5567 // to an array of ids.
5568 if ( isset( $data['email-blacklist'] ) && $data['email-blacklist'] ) {
5569 $data['email-blacklist'] = array_map( 'intval', explode( "\n", $data['email-blacklist'] ) );
5570 }
5571
5572 foreach ( $data as $property => $value ) {
5573 $this->mOptionOverrides[$property] = $value;
5574 $this->mOptions[$property] = $value;
5575 }
5576 }
5577
5578 $this->mOptionsLoaded = true;
5579
5580 Hooks::run( 'UserLoadOptions', [ $this, &$this->mOptions ] );
5581 }
5582
5583 /**
5584 * Saves the non-default options for this user, as previously set e.g. via
5585 * setOption(), in the database's "user_properties" (preferences) table.
5586 * Usually used via saveSettings().
5587 */
5588 protected function saveOptions() {
5589 $this->loadOptions();
5590
5591 // Not using getOptions(), to keep hidden preferences in database
5592 $saveOptions = $this->mOptions;
5593
5594 // Convert usernames to ids.
5595 if ( isset( $this->mOptions['email-blacklist'] ) ) {
5596 if ( $this->mOptions['email-blacklist'] ) {
5597 $value = $this->mOptions['email-blacklist'];
5598 // Email Blacklist may be an array of ids or a string of new line
5599 // delimnated user names.
5600 if ( is_array( $value ) ) {
5601 $ids = array_filter( $value, 'is_numeric' );
5602 } else {
5603 $lookup = CentralIdLookup::factory();
5604 $ids = $lookup->centralIdsFromNames( explode( "\n", $value ), $this );
5605 }
5606 $this->mOptions['email-blacklist'] = $ids;
5607 $saveOptions['email-blacklist'] = implode( "\n", $this->mOptions['email-blacklist'] );
5608 } else {
5609 // If the blacklist is empty, set it to null rather than an empty string.
5610 $this->mOptions['email-blacklist'] = null;
5611 }
5612 }
5613
5614 // Allow hooks to abort, for instance to save to a global profile.
5615 // Reset options to default state before saving.
5616 if ( !Hooks::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5617 return;
5618 }
5619
5620 $userId = $this->getId();
5621
5622 $insert_rows = []; // all the new preference rows
5623 foreach ( $saveOptions as $key => $value ) {
5624 // Don't bother storing default values
5625 $defaultOption = self::getDefaultOption( $key );
5626 if ( ( $defaultOption === null && $value !== false && $value !== null )
5627 || $value != $defaultOption
5628 ) {
5629 $insert_rows[] = [
5630 'up_user' => $userId,
5631 'up_property' => $key,
5632 'up_value' => $value,
5633 ];
5634 }
5635 }
5636
5637 $dbw = wfGetDB( DB_MASTER );
5638
5639 $res = $dbw->select( 'user_properties',
5640 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__ );
5641
5642 // Find prior rows that need to be removed or updated. These rows will
5643 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5644 $keysDelete = [];
5645 foreach ( $res as $row ) {
5646 if ( !isset( $saveOptions[$row->up_property] )
5647 || strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
5648 ) {
5649 $keysDelete[] = $row->up_property;
5650 }
5651 }
5652
5653 if ( count( $keysDelete ) ) {
5654 // Do the DELETE by PRIMARY KEY for prior rows.
5655 // In the past a very large portion of calls to this function are for setting
5656 // 'rememberpassword' for new accounts (a preference that has since been removed).
5657 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5658 // caused gap locks on [max user ID,+infinity) which caused high contention since
5659 // updates would pile up on each other as they are for higher (newer) user IDs.
5660 // It might not be necessary these days, but it shouldn't hurt either.
5661 $dbw->delete( 'user_properties',
5662 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__ );
5663 }
5664 // Insert the new preference rows
5665 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, [ 'IGNORE' ] );
5666 }
5667
5668 /**
5669 * Lazily instantiate and return a factory object for making passwords
5670 *
5671 * @deprecated since 1.27, create a PasswordFactory directly instead
5672 * @return PasswordFactory
5673 */
5674 public static function getPasswordFactory() {
5675 wfDeprecated( __METHOD__, '1.27' );
5676 $ret = new PasswordFactory();
5677 $ret->init( RequestContext::getMain()->getConfig() );
5678 return $ret;
5679 }
5680
5681 /**
5682 * Provide an array of HTML5 attributes to put on an input element
5683 * intended for the user to enter a new password. This may include
5684 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5685 *
5686 * Do *not* use this when asking the user to enter his current password!
5687 * Regardless of configuration, users may have invalid passwords for whatever
5688 * reason (e.g., they were set before requirements were tightened up).
5689 * Only use it when asking for a new password, like on account creation or
5690 * ResetPass.
5691 *
5692 * Obviously, you still need to do server-side checking.
5693 *
5694 * NOTE: A combination of bugs in various browsers means that this function
5695 * actually just returns array() unconditionally at the moment. May as
5696 * well keep it around for when the browser bugs get fixed, though.
5697 *
5698 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5699 *
5700 * @deprecated since 1.27
5701 * @return array Array of HTML attributes suitable for feeding to
5702 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5703 * That will get confused by the boolean attribute syntax used.)
5704 */
5705 public static function passwordChangeInputAttribs() {
5706 global $wgMinimalPasswordLength;
5707
5708 if ( $wgMinimalPasswordLength == 0 ) {
5709 return [];
5710 }
5711
5712 # Note that the pattern requirement will always be satisfied if the
5713 # input is empty, so we need required in all cases.
5714
5715 # @todo FIXME: T25769: This needs to not claim the password is required
5716 # if e-mail confirmation is being used. Since HTML5 input validation
5717 # is b0rked anyway in some browsers, just return nothing. When it's
5718 # re-enabled, fix this code to not output required for e-mail
5719 # registration.
5720 # $ret = array( 'required' );
5721 $ret = [];
5722
5723 # We can't actually do this right now, because Opera 9.6 will print out
5724 # the entered password visibly in its error message! When other
5725 # browsers add support for this attribute, or Opera fixes its support,
5726 # we can add support with a version check to avoid doing this on Opera
5727 # versions where it will be a problem. Reported to Opera as
5728 # DSK-262266, but they don't have a public bug tracker for us to follow.
5729 /*
5730 if ( $wgMinimalPasswordLength > 1 ) {
5731 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5732 $ret['title'] = wfMessage( 'passwordtooshort' )
5733 ->numParams( $wgMinimalPasswordLength )->text();
5734 }
5735 */
5736
5737 return $ret;
5738 }
5739
5740 /**
5741 * Return the list of user fields that should be selected to create
5742 * a new user object.
5743 * @deprecated since 1.31, use self::getQueryInfo() instead.
5744 * @return array
5745 */
5746 public static function selectFields() {
5747 wfDeprecated( __METHOD__, '1.31' );
5748 return [
5749 'user_id',
5750 'user_name',
5751 'user_real_name',
5752 'user_email',
5753 'user_touched',
5754 'user_token',
5755 'user_email_authenticated',
5756 'user_email_token',
5757 'user_email_token_expires',
5758 'user_registration',
5759 'user_editcount',
5760 ];
5761 }
5762
5763 /**
5764 * Return the tables, fields, and join conditions to be selected to create
5765 * a new user object.
5766 * @since 1.31
5767 * @return array With three keys:
5768 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
5769 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
5770 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
5771 */
5772 public static function getQueryInfo() {
5773 global $wgActorTableSchemaMigrationStage;
5774
5775 $ret = [
5776 'tables' => [ 'user' ],
5777 'fields' => [
5778 'user_id',
5779 'user_name',
5780 'user_real_name',
5781 'user_email',
5782 'user_touched',
5783 'user_token',
5784 'user_email_authenticated',
5785 'user_email_token',
5786 'user_email_token_expires',
5787 'user_registration',
5788 'user_editcount',
5789 ],
5790 'joins' => [],
5791 ];
5792 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD ) {
5793 $ret['tables']['user_actor'] = 'actor';
5794 $ret['fields'][] = 'user_actor.actor_id';
5795 $ret['joins']['user_actor'] = [
5796 $wgActorTableSchemaMigrationStage === MIGRATION_NEW ? 'JOIN' : 'LEFT JOIN',
5797 [ 'user_actor.actor_user = user_id' ]
5798 ];
5799 }
5800 return $ret;
5801 }
5802
5803 /**
5804 * Factory function for fatal permission-denied errors
5805 *
5806 * @since 1.22
5807 * @param string $permission User right required
5808 * @return Status
5809 */
5810 static function newFatalPermissionDeniedStatus( $permission ) {
5811 global $wgLang;
5812
5813 $groups = [];
5814 foreach ( self::getGroupsWithPermission( $permission ) as $group ) {
5815 $groups[] = UserGroupMembership::getLink( $group, RequestContext::getMain(), 'wiki' );
5816 }
5817
5818 if ( $groups ) {
5819 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5820 } else {
5821 return Status::newFatal( 'badaccess-group0' );
5822 }
5823 }
5824
5825 /**
5826 * Get a new instance of this user that was loaded from the master via a locking read
5827 *
5828 * Use this instead of the main context User when updating that user. This avoids races
5829 * where that user was loaded from a replica DB or even the master but without proper locks.
5830 *
5831 * @return User|null Returns null if the user was not found in the DB
5832 * @since 1.27
5833 */
5834 public function getInstanceForUpdate() {
5835 if ( !$this->getId() ) {
5836 return null; // anon
5837 }
5838
5839 $user = self::newFromId( $this->getId() );
5840 if ( !$user->loadFromId( self::READ_EXCLUSIVE ) ) {
5841 return null;
5842 }
5843
5844 return $user;
5845 }
5846
5847 /**
5848 * Checks if two user objects point to the same user.
5849 *
5850 * @since 1.25
5851 * @param User $user
5852 * @return bool
5853 */
5854 public function equals( User $user ) {
5855 return $this->getName() === $user->getName();
5856 }
5857 }