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