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