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