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