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