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