Update IPSet use statements
[lhc/web/wiklou.git] / includes / user / User.php
1 <?php
2 /**
3 * Implements the User class for the %MediaWiki software.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 use MediaWiki\MediaWikiServices;
24 use MediaWiki\Session\SessionManager;
25 use MediaWiki\Session\Token;
26 use MediaWiki\Auth\AuthManager;
27 use MediaWiki\Auth\AuthenticationResponse;
28 use MediaWiki\Auth\AuthenticationRequest;
29 use MediaWiki\User\UserIdentity;
30 use Wikimedia\IPSet;
31 use Wikimedia\ScopedCallback;
32 use Wikimedia\Rdbms\Database;
33 use Wikimedia\Rdbms\DBExpectedError;
34
35 /**
36 * String Some punctuation to prevent editing from broken text-mangling proxies.
37 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
38 * @ingroup Constants
39 */
40 define( 'EDIT_TOKEN_SUFFIX', Token::SUFFIX );
41
42 /**
43 * The User object encapsulates all of the user-specific settings (user_id,
44 * name, rights, email address, options, last login time). Client
45 * classes use the getXXX() functions to access these fields. These functions
46 * do all the work of determining whether the user is logged in,
47 * whether the requested option can be satisfied from cookies or
48 * whether a database query is needed. Most of the settings needed
49 * for rendering normal pages are set in the cookie to minimize use
50 * of the database.
51 */
52 class User implements IDBAccessObject, UserIdentity {
53 /**
54 * @const int Number of characters in user_token field.
55 */
56 const TOKEN_LENGTH = 32;
57
58 /**
59 * @const string An invalid value for user_token
60 */
61 const INVALID_TOKEN = '*** INVALID ***';
62
63 /**
64 * Global constant made accessible as class constants so that autoloader
65 * magic can be used.
66 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
67 */
68 const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
69
70 /**
71 * @const int Serialized record version.
72 */
73 const VERSION = 11;
74
75 /**
76 * Exclude user options that are set to their default value.
77 * @since 1.25
78 */
79 const GETOPTIONS_EXCLUDE_DEFAULTS = 1;
80
81 /**
82 * @since 1.27
83 */
84 const CHECK_USER_RIGHTS = true;
85
86 /**
87 * @since 1.27
88 */
89 const IGNORE_USER_RIGHTS = false;
90
91 /**
92 * Array of Strings List of member variables which are saved to the
93 * shared cache (memcached). Any operation which changes the
94 * corresponding database fields must call a cache-clearing function.
95 * @showinitializer
96 */
97 protected static $mCacheVars = [
98 // user table
99 'mId',
100 'mName',
101 'mRealName',
102 'mEmail',
103 'mTouched',
104 'mToken',
105 'mEmailAuthenticated',
106 'mEmailToken',
107 'mEmailTokenExpires',
108 'mRegistration',
109 'mEditCount',
110 // user_groups table
111 'mGroupMemberships',
112 // user_properties table
113 'mOptionOverrides',
114 ];
115
116 /**
117 * Array of Strings Core rights.
118 * Each of these should have a corresponding message of the form
119 * "right-$right".
120 * @showinitializer
121 */
122 protected static $mCoreRights = [
123 'apihighlimits',
124 'applychangetags',
125 'autoconfirmed',
126 'autocreateaccount',
127 'autopatrol',
128 'bigdelete',
129 'block',
130 'blockemail',
131 'bot',
132 'browsearchive',
133 'changetags',
134 'createaccount',
135 'createpage',
136 'createtalk',
137 'delete',
138 'deletechangetags',
139 'deletedhistory',
140 'deletedtext',
141 'deletelogentry',
142 'deleterevision',
143 'edit',
144 'editcontentmodel',
145 'editinterface',
146 'editprotected',
147 'editmyoptions',
148 'editmyprivateinfo',
149 'editmyusercss',
150 'editmyuserjs',
151 'editmywatchlist',
152 'editsemiprotected',
153 'editusercss',
154 'edituserjs',
155 'hideuser',
156 'import',
157 'importupload',
158 'ipblock-exempt',
159 'managechangetags',
160 'markbotedits',
161 'mergehistory',
162 'minoredit',
163 'move',
164 'movefile',
165 'move-categorypages',
166 'move-rootuserpages',
167 'move-subpages',
168 'nominornewtalk',
169 'noratelimit',
170 'override-export-depth',
171 'pagelang',
172 'patrol',
173 'patrolmarks',
174 'protect',
175 'purge',
176 'read',
177 'reupload',
178 'reupload-own',
179 'reupload-shared',
180 'rollback',
181 'sendemail',
182 'siteadmin',
183 'suppressionlog',
184 'suppressredirect',
185 'suppressrevision',
186 'unblockself',
187 'undelete',
188 'unwatchedpages',
189 'upload',
190 'upload_by_url',
191 'userrights',
192 'userrights-interwiki',
193 'viewmyprivateinfo',
194 'viewmywatchlist',
195 'viewsuppressed',
196 'writeapi',
197 ];
198
199 /**
200 * String Cached results of getAllRights()
201 */
202 protected static $mAllRights = false;
203
204 /** Cache variables */
205 // @{
206 /** @var int */
207 public $mId;
208 /** @var string */
209 public $mName;
210 /** @var string */
211 public $mRealName;
212
213 /** @var string */
214 public $mEmail;
215 /** @var string TS_MW timestamp from the DB */
216 public $mTouched;
217 /** @var string TS_MW timestamp from cache */
218 protected $mQuickTouched;
219 /** @var string */
220 protected $mToken;
221 /** @var string */
222 public $mEmailAuthenticated;
223 /** @var string */
224 protected $mEmailToken;
225 /** @var string */
226 protected $mEmailTokenExpires;
227 /** @var string */
228 protected $mRegistration;
229 /** @var int */
230 protected $mEditCount;
231 /** @var UserGroupMembership[] Associative array of (group name => UserGroupMembership object) */
232 protected $mGroupMemberships;
233 /** @var array */
234 protected $mOptionOverrides;
235 // @}
236
237 /**
238 * Bool Whether the cache variables have been loaded.
239 */
240 // @{
241 public $mOptionsLoaded;
242
243 /**
244 * Array with already loaded items or true if all items have been loaded.
245 */
246 protected $mLoadedItems = [];
247 // @}
248
249 /**
250 * String Initialization data source if mLoadedItems!==true. May be one of:
251 * - 'defaults' anonymous user initialised from class defaults
252 * - 'name' initialise from mName
253 * - 'id' initialise from mId
254 * - 'session' log in from session if possible
255 *
256 * Use the User::newFrom*() family of functions to set this.
257 */
258 public $mFrom;
259
260 /**
261 * Lazy-initialized variables, invalidated with clearInstanceCache
262 */
263 protected $mNewtalk;
264 /** @var string */
265 protected $mDatePreference;
266 /** @var string */
267 public $mBlockedby;
268 /** @var string */
269 protected $mHash;
270 /** @var array */
271 public $mRights;
272 /** @var string */
273 protected $mBlockreason;
274 /** @var array */
275 protected $mEffectiveGroups;
276 /** @var array */
277 protected $mImplicitGroups;
278 /** @var array */
279 protected $mFormerGroups;
280 /** @var Block */
281 protected $mGlobalBlock;
282 /** @var bool */
283 protected $mLocked;
284 /** @var bool */
285 public $mHideName;
286 /** @var array */
287 public $mOptions;
288
289 /** @var WebRequest */
290 private $mRequest;
291
292 /** @var Block */
293 public $mBlock;
294
295 /** @var bool */
296 protected $mAllowUsertalk;
297
298 /** @var Block */
299 private $mBlockedFromCreateAccount = false;
300
301 /** @var int User::READ_* constant bitfield used to load data */
302 protected $queryFlagsUsed = self::READ_NORMAL;
303
304 public static $idCacheByName = [];
305
306 /**
307 * Lightweight constructor for an anonymous user.
308 * Use the User::newFrom* factory functions for other kinds of users.
309 *
310 * @see newFromName()
311 * @see newFromId()
312 * @see newFromConfirmationCode()
313 * @see newFromSession()
314 * @see newFromRow()
315 */
316 public function __construct() {
317 $this->clearInstanceCache( 'defaults' );
318 }
319
320 /**
321 * @return string
322 */
323 public function __toString() {
324 return (string)$this->getName();
325 }
326
327 /**
328 * Test if it's safe to load this User object.
329 *
330 * You should typically check this before using $wgUser or
331 * RequestContext::getUser in a method that might be called before the
332 * system has been fully initialized. If the object is unsafe, you should
333 * use an anonymous user:
334 * \code
335 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
336 * \endcode
337 *
338 * @since 1.27
339 * @return bool
340 */
341 public function isSafeToLoad() {
342 global $wgFullyInitialised;
343
344 // The user is safe to load if:
345 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
346 // * mLoadedItems === true (already loaded)
347 // * mFrom !== 'session' (sessions not involved at all)
348
349 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
350 $this->mLoadedItems === true || $this->mFrom !== 'session';
351 }
352
353 /**
354 * Load the user table data for this object from the source given by mFrom.
355 *
356 * @param int $flags User::READ_* constant bitfield
357 */
358 public function load( $flags = self::READ_NORMAL ) {
359 global $wgFullyInitialised;
360
361 if ( $this->mLoadedItems === true ) {
362 return;
363 }
364
365 // Set it now to avoid infinite recursion in accessors
366 $oldLoadedItems = $this->mLoadedItems;
367 $this->mLoadedItems = true;
368 $this->queryFlagsUsed = $flags;
369
370 // If this is called too early, things are likely to break.
371 if ( !$wgFullyInitialised && $this->mFrom === 'session' ) {
372 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
373 ->warning( 'User::loadFromSession called before the end of Setup.php', [
374 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
375 ] );
376 $this->loadDefaults();
377 $this->mLoadedItems = $oldLoadedItems;
378 return;
379 }
380
381 switch ( $this->mFrom ) {
382 case 'defaults':
383 $this->loadDefaults();
384 break;
385 case 'name':
386 // Make sure this thread sees its own changes
387 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
388 if ( $lb->hasOrMadeRecentMasterChanges() ) {
389 $flags |= self::READ_LATEST;
390 $this->queryFlagsUsed = $flags;
391 }
392
393 $this->mId = self::idFromName( $this->mName, $flags );
394 if ( !$this->mId ) {
395 // Nonexistent user placeholder object
396 $this->loadDefaults( $this->mName );
397 } else {
398 $this->loadFromId( $flags );
399 }
400 break;
401 case 'id':
402 $this->loadFromId( $flags );
403 break;
404 case 'session':
405 if ( !$this->loadFromSession() ) {
406 // Loading from session failed. Load defaults.
407 $this->loadDefaults();
408 }
409 Hooks::run( 'UserLoadAfterLoadFromSession', [ $this ] );
410 break;
411 default:
412 throw new UnexpectedValueException(
413 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
414 }
415 }
416
417 /**
418 * Load user table data, given mId has already been set.
419 * @param int $flags User::READ_* constant bitfield
420 * @return bool False if the ID does not exist, true otherwise
421 */
422 public function loadFromId( $flags = self::READ_NORMAL ) {
423 if ( $this->mId == 0 ) {
424 // Anonymous users are not in the database (don't need cache)
425 $this->loadDefaults();
426 return false;
427 }
428
429 // Try cache (unless this needs data from the master DB).
430 // NOTE: if this thread called saveSettings(), the cache was cleared.
431 $latest = DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST );
432 if ( $latest ) {
433 if ( !$this->loadFromDatabase( $flags ) ) {
434 // Can't load from ID
435 return false;
436 }
437 } else {
438 $this->loadFromCache();
439 }
440
441 $this->mLoadedItems = true;
442 $this->queryFlagsUsed = $flags;
443
444 return true;
445 }
446
447 /**
448 * @since 1.27
449 * @param string $wikiId
450 * @param int $userId
451 */
452 public static function purge( $wikiId, $userId ) {
453 $cache = ObjectCache::getMainWANInstance();
454 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
455 $cache->delete( $key );
456 }
457
458 /**
459 * @since 1.27
460 * @param WANObjectCache $cache
461 * @return string
462 */
463 protected function getCacheKey( WANObjectCache $cache ) {
464 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId );
465 }
466
467 /**
468 * @param WANObjectCache $cache
469 * @return string[]
470 * @since 1.28
471 */
472 public function getMutableCacheKeys( WANObjectCache $cache ) {
473 $id = $this->getId();
474
475 return $id ? [ $this->getCacheKey( $cache ) ] : [];
476 }
477
478 /**
479 * Load user data from shared cache, given mId has already been set.
480 *
481 * @return bool True
482 * @since 1.25
483 */
484 protected function loadFromCache() {
485 $cache = ObjectCache::getMainWANInstance();
486 $data = $cache->getWithSetCallback(
487 $this->getCacheKey( $cache ),
488 $cache::TTL_HOUR,
489 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
490 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
491 wfDebug( "User: cache miss for user {$this->mId}\n" );
492
493 $this->loadFromDatabase( self::READ_NORMAL );
494 $this->loadGroups();
495 $this->loadOptions();
496
497 $data = [];
498 foreach ( self::$mCacheVars as $name ) {
499 $data[$name] = $this->$name;
500 }
501
502 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX, $this->mTouched ), $ttl );
503
504 // if a user group membership is about to expire, the cache needs to
505 // expire at that time (T163691)
506 foreach ( $this->mGroupMemberships as $ugm ) {
507 if ( $ugm->getExpiry() ) {
508 $secondsUntilExpiry = wfTimestamp( TS_UNIX, $ugm->getExpiry() ) - time();
509 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
510 $ttl = $secondsUntilExpiry;
511 }
512 }
513 }
514
515 return $data;
516 },
517 [ 'pcTTL' => $cache::TTL_PROC_LONG, 'version' => self::VERSION ]
518 );
519
520 // Restore from cache
521 foreach ( self::$mCacheVars as $name ) {
522 $this->$name = $data[$name];
523 }
524
525 return true;
526 }
527
528 /** @name newFrom*() static factory methods */
529 // @{
530
531 /**
532 * Static factory method for creation from username.
533 *
534 * This is slightly less efficient than newFromId(), so use newFromId() if
535 * you have both an ID and a name handy.
536 *
537 * @param string $name Username, validated by Title::newFromText()
538 * @param string|bool $validate Validate username. Takes the same parameters as
539 * User::getCanonicalName(), except that true is accepted as an alias
540 * for 'valid', for BC.
541 *
542 * @return User|bool User object, or false if the username is invalid
543 * (e.g. if it contains illegal characters or is an IP address). If the
544 * username is not present in the database, the result will be a user object
545 * with a name, zero user ID and default settings.
546 */
547 public static function newFromName( $name, $validate = 'valid' ) {
548 if ( $validate === true ) {
549 $validate = 'valid';
550 }
551 $name = self::getCanonicalName( $name, $validate );
552 if ( $name === false ) {
553 return false;
554 } else {
555 // Create unloaded user object
556 $u = new User;
557 $u->mName = $name;
558 $u->mFrom = 'name';
559 $u->setItemLoaded( 'name' );
560 return $u;
561 }
562 }
563
564 /**
565 * Static factory method for creation from a given user ID.
566 *
567 * @param int $id Valid user ID
568 * @return User The corresponding User object
569 */
570 public static function newFromId( $id ) {
571 $u = new User;
572 $u->mId = $id;
573 $u->mFrom = 'id';
574 $u->setItemLoaded( 'id' );
575 return $u;
576 }
577
578 /**
579 * Factory method to fetch whichever user has a given email confirmation code.
580 * This code is generated when an account is created or its e-mail address
581 * has changed.
582 *
583 * If the code is invalid or has expired, returns NULL.
584 *
585 * @param string $code Confirmation code
586 * @param int $flags User::READ_* bitfield
587 * @return User|null
588 */
589 public static function newFromConfirmationCode( $code, $flags = 0 ) {
590 $db = ( $flags & self::READ_LATEST ) == self::READ_LATEST
591 ? wfGetDB( DB_MASTER )
592 : wfGetDB( DB_REPLICA );
593
594 $id = $db->selectField(
595 'user',
596 'user_id',
597 [
598 'user_email_token' => md5( $code ),
599 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
600 ]
601 );
602
603 return $id ? self::newFromId( $id ) : null;
604 }
605
606 /**
607 * Create a new user object using data from session. If the login
608 * credentials are invalid, the result is an anonymous user.
609 *
610 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
611 * @return User
612 */
613 public static function newFromSession( WebRequest $request = null ) {
614 $user = new User;
615 $user->mFrom = 'session';
616 $user->mRequest = $request;
617 return $user;
618 }
619
620 /**
621 * Create a new user object from a user row.
622 * The row should have the following fields from the user table in it:
623 * - either user_name or user_id to load further data if needed (or both)
624 * - user_real_name
625 * - all other fields (email, etc.)
626 * It is useless to provide the remaining fields if either user_id,
627 * user_name and user_real_name are not provided because the whole row
628 * will be loaded once more from the database when accessing them.
629 *
630 * @param stdClass $row A row from the user table
631 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
632 * @return User
633 */
634 public static function newFromRow( $row, $data = null ) {
635 $user = new User;
636 $user->loadFromRow( $row, $data );
637 return $user;
638 }
639
640 /**
641 * Static factory method for creation of a "system" user from username.
642 *
643 * A "system" user is an account that's used to attribute logged actions
644 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
645 * might include the 'Maintenance script' or 'Conversion script' accounts
646 * used by various scripts in the maintenance/ directory or accounts such
647 * as 'MediaWiki message delivery' used by the MassMessage extension.
648 *
649 * This can optionally create the user if it doesn't exist, and "steal" the
650 * account if it does exist.
651 *
652 * "Stealing" an existing user is intended to make it impossible for normal
653 * authentication processes to use the account, effectively disabling the
654 * account for normal use:
655 * - Email is invalidated, to prevent account recovery by emailing a
656 * temporary password and to disassociate the account from the existing
657 * human.
658 * - The token is set to a magic invalid value, to kill existing sessions
659 * and to prevent $this->setToken() calls from resetting the token to a
660 * valid value.
661 * - SessionManager is instructed to prevent new sessions for the user, to
662 * do things like deauthorizing OAuth consumers.
663 * - AuthManager is instructed to revoke access, to invalidate or remove
664 * passwords and other credentials.
665 *
666 * @param string $name Username
667 * @param array $options Options are:
668 * - validate: As for User::getCanonicalName(), default 'valid'
669 * - create: Whether to create the user if it doesn't already exist, default true
670 * - steal: Whether to "disable" the account for normal use if it already
671 * exists, default false
672 * @return User|null
673 * @since 1.27
674 */
675 public static function newSystemUser( $name, $options = [] ) {
676 $options += [
677 'validate' => 'valid',
678 'create' => true,
679 'steal' => false,
680 ];
681
682 $name = self::getCanonicalName( $name, $options['validate'] );
683 if ( $name === false ) {
684 return null;
685 }
686
687 $dbr = wfGetDB( DB_REPLICA );
688 $userQuery = self::getQueryInfo();
689 $row = $dbr->selectRow(
690 $userQuery['tables'],
691 $userQuery['fields'],
692 [ 'user_name' => $name ],
693 __METHOD__,
694 [],
695 $userQuery['joins']
696 );
697 if ( !$row ) {
698 // Try the master database...
699 $dbw = wfGetDB( DB_MASTER );
700 $row = $dbw->selectRow(
701 $userQuery['tables'],
702 $userQuery['fields'],
703 [ 'user_name' => $name ],
704 __METHOD__,
705 [],
706 $userQuery['joins']
707 );
708 }
709
710 if ( !$row ) {
711 // No user. Create it?
712 return $options['create']
713 ? self::createNew( $name, [ 'token' => self::INVALID_TOKEN ] )
714 : null;
715 }
716
717 $user = self::newFromRow( $row );
718
719 // A user is considered to exist as a non-system user if it can
720 // authenticate, or has an email set, or has a non-invalid token.
721 if ( $user->mEmail || $user->mToken !== self::INVALID_TOKEN ||
722 AuthManager::singleton()->userCanAuthenticate( $name )
723 ) {
724 // User exists. Steal it?
725 if ( !$options['steal'] ) {
726 return null;
727 }
728
729 AuthManager::singleton()->revokeAccessForUser( $name );
730
731 $user->invalidateEmail();
732 $user->mToken = self::INVALID_TOKEN;
733 $user->saveSettings();
734 SessionManager::singleton()->preventSessionsForUser( $user->getName() );
735 }
736
737 return $user;
738 }
739
740 // @}
741
742 /**
743 * Get the username corresponding to a given user ID
744 * @param int $id User ID
745 * @return string|bool The corresponding username
746 */
747 public static function whoIs( $id ) {
748 return UserCache::singleton()->getProp( $id, 'name' );
749 }
750
751 /**
752 * Get the real name of a user given their user ID
753 *
754 * @param int $id User ID
755 * @return string|bool The corresponding user's real name
756 */
757 public static function whoIsReal( $id ) {
758 return UserCache::singleton()->getProp( $id, 'real_name' );
759 }
760
761 /**
762 * Get database id given a user name
763 * @param string $name Username
764 * @param int $flags User::READ_* constant bitfield
765 * @return int|null The corresponding user's ID, or null if user is nonexistent
766 */
767 public static function idFromName( $name, $flags = self::READ_NORMAL ) {
768 $nt = Title::makeTitleSafe( NS_USER, $name );
769 if ( is_null( $nt ) ) {
770 // Illegal name
771 return null;
772 }
773
774 if ( !( $flags & self::READ_LATEST ) && isset( self::$idCacheByName[$name] ) ) {
775 return self::$idCacheByName[$name];
776 }
777
778 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
779 $db = wfGetDB( $index );
780
781 $s = $db->selectRow(
782 'user',
783 [ 'user_id' ],
784 [ 'user_name' => $nt->getText() ],
785 __METHOD__,
786 $options
787 );
788
789 if ( $s === false ) {
790 $result = null;
791 } else {
792 $result = $s->user_id;
793 }
794
795 self::$idCacheByName[$name] = $result;
796
797 if ( count( self::$idCacheByName ) > 1000 ) {
798 self::$idCacheByName = [];
799 }
800
801 return $result;
802 }
803
804 /**
805 * Reset the cache used in idFromName(). For use in tests.
806 */
807 public static function resetIdByNameCache() {
808 self::$idCacheByName = [];
809 }
810
811 /**
812 * Does the string match an anonymous IP address?
813 *
814 * This function exists for username validation, in order to reject
815 * usernames which are similar in form to IP addresses. Strings such
816 * as 300.300.300.300 will return true because it looks like an IP
817 * address, despite not being strictly valid.
818 *
819 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
820 * address because the usemod software would "cloak" anonymous IP
821 * addresses like this, if we allowed accounts like this to be created
822 * new users could get the old edits of these anonymous users.
823 *
824 * @param string $name Name to match
825 * @return bool
826 */
827 public static function isIP( $name ) {
828 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
829 || IP::isIPv6( $name );
830 }
831
832 /**
833 * Is the user an IP range?
834 *
835 * @since 1.30
836 * @return bool
837 */
838 public function isIPRange() {
839 return IP::isValidRange( $this->mName );
840 }
841
842 /**
843 * Is the input a valid username?
844 *
845 * Checks if the input is a valid username, we don't want an empty string,
846 * an IP address, anything that contains slashes (would mess up subpages),
847 * is longer than the maximum allowed username size or doesn't begin with
848 * a capital letter.
849 *
850 * @param string $name Name to match
851 * @return bool
852 */
853 public static function isValidUserName( $name ) {
854 global $wgContLang, $wgMaxNameChars;
855
856 if ( $name == ''
857 || self::isIP( $name )
858 || strpos( $name, '/' ) !== false
859 || strlen( $name ) > $wgMaxNameChars
860 || $name != $wgContLang->ucfirst( $name )
861 ) {
862 return false;
863 }
864
865 // Ensure that the name can't be misresolved as a different title,
866 // such as with extra namespace keys at the start.
867 $parsed = Title::newFromText( $name );
868 if ( is_null( $parsed )
869 || $parsed->getNamespace()
870 || strcmp( $name, $parsed->getPrefixedText() ) ) {
871 return false;
872 }
873
874 // Check an additional blacklist of troublemaker characters.
875 // Should these be merged into the title char list?
876 $unicodeBlacklist = '/[' .
877 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
878 '\x{00a0}' . # non-breaking space
879 '\x{2000}-\x{200f}' . # various whitespace
880 '\x{2028}-\x{202f}' . # breaks and control chars
881 '\x{3000}' . # ideographic space
882 '\x{e000}-\x{f8ff}' . # private use
883 ']/u';
884 if ( preg_match( $unicodeBlacklist, $name ) ) {
885 return false;
886 }
887
888 return true;
889 }
890
891 /**
892 * Usernames which fail to pass this function will be blocked
893 * from user login and new account registrations, but may be used
894 * internally by batch processes.
895 *
896 * If an account already exists in this form, login will be blocked
897 * by a failure to pass this function.
898 *
899 * @param string $name Name to match
900 * @return bool
901 */
902 public static function isUsableName( $name ) {
903 global $wgReservedUsernames;
904 // Must be a valid username, obviously ;)
905 if ( !self::isValidUserName( $name ) ) {
906 return false;
907 }
908
909 static $reservedUsernames = false;
910 if ( !$reservedUsernames ) {
911 $reservedUsernames = $wgReservedUsernames;
912 Hooks::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
913 }
914
915 // Certain names may be reserved for batch processes.
916 foreach ( $reservedUsernames as $reserved ) {
917 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
918 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
919 }
920 if ( $reserved == $name ) {
921 return false;
922 }
923 }
924 return true;
925 }
926
927 /**
928 * Return the users who are members of the given group(s). In case of multiple groups,
929 * users who are members of at least one of them are returned.
930 *
931 * @param string|array $groups A single group name or an array of group names
932 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
933 * records; larger values are ignored.
934 * @param int $after ID the user to start after
935 * @return UserArrayFromResult
936 */
937 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
938 if ( $groups === [] ) {
939 return UserArrayFromResult::newFromIDs( [] );
940 }
941
942 $groups = array_unique( (array)$groups );
943 $limit = min( 5000, $limit );
944
945 $conds = [ 'ug_group' => $groups ];
946 if ( $after !== null ) {
947 $conds[] = 'ug_user > ' . (int)$after;
948 }
949
950 $dbr = wfGetDB( DB_REPLICA );
951 $ids = $dbr->selectFieldValues(
952 'user_groups',
953 'ug_user',
954 $conds,
955 __METHOD__,
956 [
957 'DISTINCT' => true,
958 'ORDER BY' => 'ug_user',
959 'LIMIT' => $limit,
960 ]
961 ) ?: [];
962 return UserArray::newFromIDs( $ids );
963 }
964
965 /**
966 * Usernames which fail to pass this function will be blocked
967 * from new account registrations, but may be used internally
968 * either by batch processes or by user accounts which have
969 * already been created.
970 *
971 * Additional blacklisting may be added here rather than in
972 * isValidUserName() to avoid disrupting existing accounts.
973 *
974 * @param string $name String to match
975 * @return bool
976 */
977 public static function isCreatableName( $name ) {
978 global $wgInvalidUsernameCharacters;
979
980 // Ensure that the username isn't longer than 235 bytes, so that
981 // (at least for the builtin skins) user javascript and css files
982 // will work. (T25080)
983 if ( strlen( $name ) > 235 ) {
984 wfDebugLog( 'username', __METHOD__ .
985 ": '$name' invalid due to length" );
986 return false;
987 }
988
989 // Preg yells if you try to give it an empty string
990 if ( $wgInvalidUsernameCharacters !== '' ) {
991 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
992 wfDebugLog( 'username', __METHOD__ .
993 ": '$name' invalid due to wgInvalidUsernameCharacters" );
994 return false;
995 }
996 }
997
998 return self::isUsableName( $name );
999 }
1000
1001 /**
1002 * Is the input a valid password for this user?
1003 *
1004 * @param string $password Desired password
1005 * @return bool
1006 */
1007 public function isValidPassword( $password ) {
1008 // simple boolean wrapper for getPasswordValidity
1009 return $this->getPasswordValidity( $password ) === true;
1010 }
1011
1012 /**
1013 * Given unvalidated password input, return error message on failure.
1014 *
1015 * @param string $password Desired password
1016 * @return bool|string|array True on success, string or array of error message on failure
1017 */
1018 public function getPasswordValidity( $password ) {
1019 $result = $this->checkPasswordValidity( $password );
1020 if ( $result->isGood() ) {
1021 return true;
1022 } else {
1023 $messages = [];
1024 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
1025 $messages[] = $error['message'];
1026 }
1027 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
1028 $messages[] = $warning['message'];
1029 }
1030 if ( count( $messages ) === 1 ) {
1031 return $messages[0];
1032 }
1033 return $messages;
1034 }
1035 }
1036
1037 /**
1038 * Check if this is a valid password for this user
1039 *
1040 * Create a Status object based on the password's validity.
1041 * The Status should be set to fatal if the user should not
1042 * be allowed to log in, and should have any errors that
1043 * would block changing the password.
1044 *
1045 * If the return value of this is not OK, the password
1046 * should not be checked. If the return value is not Good,
1047 * the password can be checked, but the user should not be
1048 * able to set their password to this.
1049 *
1050 * @param string $password Desired password
1051 * @return Status
1052 * @since 1.23
1053 */
1054 public function checkPasswordValidity( $password ) {
1055 global $wgPasswordPolicy;
1056
1057 $upp = new UserPasswordPolicy(
1058 $wgPasswordPolicy['policies'],
1059 $wgPasswordPolicy['checks']
1060 );
1061
1062 $status = Status::newGood();
1063 $result = false; // init $result to false for the internal checks
1064
1065 if ( !Hooks::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1066 $status->error( $result );
1067 return $status;
1068 }
1069
1070 if ( $result === false ) {
1071 $status->merge( $upp->checkUserPassword( $this, $password ) );
1072 return $status;
1073 } elseif ( $result === true ) {
1074 return $status;
1075 } else {
1076 $status->error( $result );
1077 return $status; // the isValidPassword hook set a string $result and returned true
1078 }
1079 }
1080
1081 /**
1082 * Given unvalidated user input, return a canonical username, or false if
1083 * the username is invalid.
1084 * @param string $name User input
1085 * @param string|bool $validate Type of validation to use:
1086 * - false No validation
1087 * - 'valid' Valid for batch processes
1088 * - 'usable' Valid for batch processes and login
1089 * - 'creatable' Valid for batch processes, login and account creation
1090 *
1091 * @throws InvalidArgumentException
1092 * @return bool|string
1093 */
1094 public static function getCanonicalName( $name, $validate = 'valid' ) {
1095 // Force usernames to capital
1096 global $wgContLang;
1097 $name = $wgContLang->ucfirst( $name );
1098
1099 # Reject names containing '#'; these will be cleaned up
1100 # with title normalisation, but then it's too late to
1101 # check elsewhere
1102 if ( strpos( $name, '#' ) !== false ) {
1103 return false;
1104 }
1105
1106 // Clean up name according to title rules,
1107 // but only when validation is requested (T14654)
1108 $t = ( $validate !== false ) ?
1109 Title::newFromText( $name, NS_USER ) : Title::makeTitle( NS_USER, $name );
1110 // Check for invalid titles
1111 if ( is_null( $t ) || $t->getNamespace() !== NS_USER || $t->isExternal() ) {
1112 return false;
1113 }
1114
1115 // Reject various classes of invalid names
1116 $name = AuthManager::callLegacyAuthPlugin(
1117 'getCanonicalName', [ $t->getText() ], $t->getText()
1118 );
1119
1120 switch ( $validate ) {
1121 case false:
1122 break;
1123 case 'valid':
1124 if ( !self::isValidUserName( $name ) ) {
1125 $name = false;
1126 }
1127 break;
1128 case 'usable':
1129 if ( !self::isUsableName( $name ) ) {
1130 $name = false;
1131 }
1132 break;
1133 case 'creatable':
1134 if ( !self::isCreatableName( $name ) ) {
1135 $name = false;
1136 }
1137 break;
1138 default:
1139 throw new InvalidArgumentException(
1140 'Invalid parameter value for $validate in ' . __METHOD__ );
1141 }
1142 return $name;
1143 }
1144
1145 /**
1146 * Return a random password.
1147 *
1148 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1149 * @return string New random password
1150 */
1151 public static function randomPassword() {
1152 global $wgMinimalPasswordLength;
1153 return PasswordFactory::generateRandomPasswordString( $wgMinimalPasswordLength );
1154 }
1155
1156 /**
1157 * Set cached properties to default.
1158 *
1159 * @note This no longer clears uncached lazy-initialised properties;
1160 * the constructor does that instead.
1161 *
1162 * @param string|bool $name
1163 */
1164 public function loadDefaults( $name = false ) {
1165 $this->mId = 0;
1166 $this->mName = $name;
1167 $this->mRealName = '';
1168 $this->mEmail = '';
1169 $this->mOptionOverrides = null;
1170 $this->mOptionsLoaded = false;
1171
1172 $loggedOut = $this->mRequest && !defined( 'MW_NO_SESSION' )
1173 ? $this->mRequest->getSession()->getLoggedOutTimestamp() : 0;
1174 if ( $loggedOut !== 0 ) {
1175 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
1176 } else {
1177 $this->mTouched = '1'; # Allow any pages to be cached
1178 }
1179
1180 $this->mToken = null; // Don't run cryptographic functions till we need a token
1181 $this->mEmailAuthenticated = null;
1182 $this->mEmailToken = '';
1183 $this->mEmailTokenExpires = null;
1184 $this->mRegistration = wfTimestamp( TS_MW );
1185 $this->mGroupMemberships = [];
1186
1187 Hooks::run( 'UserLoadDefaults', [ $this, $name ] );
1188 }
1189
1190 /**
1191 * Return whether an item has been loaded.
1192 *
1193 * @param string $item Item to check. Current possibilities:
1194 * - id
1195 * - name
1196 * - realname
1197 * @param string $all 'all' to check if the whole object has been loaded
1198 * or any other string to check if only the item is available (e.g.
1199 * for optimisation)
1200 * @return bool
1201 */
1202 public function isItemLoaded( $item, $all = 'all' ) {
1203 return ( $this->mLoadedItems === true && $all === 'all' ) ||
1204 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1205 }
1206
1207 /**
1208 * Set that an item has been loaded
1209 *
1210 * @param string $item
1211 */
1212 protected function setItemLoaded( $item ) {
1213 if ( is_array( $this->mLoadedItems ) ) {
1214 $this->mLoadedItems[$item] = true;
1215 }
1216 }
1217
1218 /**
1219 * Load user data from the session.
1220 *
1221 * @return bool True if the user is logged in, false otherwise.
1222 */
1223 private function loadFromSession() {
1224 // Deprecated hook
1225 $result = null;
1226 Hooks::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1227 if ( $result !== null ) {
1228 return $result;
1229 }
1230
1231 // MediaWiki\Session\Session already did the necessary authentication of the user
1232 // returned here, so just use it if applicable.
1233 $session = $this->getRequest()->getSession();
1234 $user = $session->getUser();
1235 if ( $user->isLoggedIn() ) {
1236 $this->loadFromUserObject( $user );
1237
1238 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1239 // every session load, because an autoblocked editor might not edit again from the same
1240 // IP address after being blocked.
1241 $config = RequestContext::getMain()->getConfig();
1242 if ( $config->get( 'CookieSetOnAutoblock' ) === true ) {
1243 $block = $this->getBlock();
1244 $shouldSetCookie = $this->getRequest()->getCookie( 'BlockID' ) === null
1245 && $block
1246 && $block->getType() === Block::TYPE_USER
1247 && $block->isAutoblocking();
1248 if ( $shouldSetCookie ) {
1249 wfDebug( __METHOD__ . ': User is autoblocked, setting cookie to track' );
1250 $block->setCookie( $this->getRequest()->response() );
1251 }
1252 }
1253
1254 // Other code expects these to be set in the session, so set them.
1255 $session->set( 'wsUserID', $this->getId() );
1256 $session->set( 'wsUserName', $this->getName() );
1257 $session->set( 'wsToken', $this->getToken() );
1258 return true;
1259 }
1260 return false;
1261 }
1262
1263 /**
1264 * Load user and user_group data from the database.
1265 * $this->mId must be set, this is how the user is identified.
1266 *
1267 * @param int $flags User::READ_* constant bitfield
1268 * @return bool True if the user exists, false if the user is anonymous
1269 */
1270 public function loadFromDatabase( $flags = self::READ_LATEST ) {
1271 // Paranoia
1272 $this->mId = intval( $this->mId );
1273
1274 if ( !$this->mId ) {
1275 // Anonymous users are not in the database
1276 $this->loadDefaults();
1277 return false;
1278 }
1279
1280 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
1281 $db = wfGetDB( $index );
1282
1283 $userQuery = self::getQueryInfo();
1284 $s = $db->selectRow(
1285 $userQuery['tables'],
1286 $userQuery['fields'],
1287 [ 'user_id' => $this->mId ],
1288 __METHOD__,
1289 $options,
1290 $userQuery['joins']
1291 );
1292
1293 $this->queryFlagsUsed = $flags;
1294 Hooks::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1295
1296 if ( $s !== false ) {
1297 // Initialise user table data
1298 $this->loadFromRow( $s );
1299 $this->mGroupMemberships = null; // deferred
1300 $this->getEditCount(); // revalidation for nulls
1301 return true;
1302 } else {
1303 // Invalid user_id
1304 $this->mId = 0;
1305 $this->loadDefaults();
1306 return false;
1307 }
1308 }
1309
1310 /**
1311 * Initialize this object from a row from the user table.
1312 *
1313 * @param stdClass $row Row from the user table to load.
1314 * @param array $data Further user data to load into the object
1315 *
1316 * user_groups Array of arrays or stdClass result rows out of the user_groups
1317 * table. Previously you were supposed to pass an array of strings
1318 * here, but we also need expiry info nowadays, so an array of
1319 * strings is ignored.
1320 * user_properties Array with properties out of the user_properties table
1321 */
1322 protected function loadFromRow( $row, $data = null ) {
1323 $all = true;
1324
1325 $this->mGroupMemberships = null; // deferred
1326
1327 if ( isset( $row->user_name ) ) {
1328 $this->mName = $row->user_name;
1329 $this->mFrom = 'name';
1330 $this->setItemLoaded( 'name' );
1331 } else {
1332 $all = false;
1333 }
1334
1335 if ( isset( $row->user_real_name ) ) {
1336 $this->mRealName = $row->user_real_name;
1337 $this->setItemLoaded( 'realname' );
1338 } else {
1339 $all = false;
1340 }
1341
1342 if ( isset( $row->user_id ) ) {
1343 $this->mId = intval( $row->user_id );
1344 $this->mFrom = 'id';
1345 $this->setItemLoaded( 'id' );
1346 } else {
1347 $all = false;
1348 }
1349
1350 if ( isset( $row->user_id ) && isset( $row->user_name ) ) {
1351 self::$idCacheByName[$row->user_name] = $row->user_id;
1352 }
1353
1354 if ( isset( $row->user_editcount ) ) {
1355 $this->mEditCount = $row->user_editcount;
1356 } else {
1357 $all = false;
1358 }
1359
1360 if ( isset( $row->user_touched ) ) {
1361 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1362 } else {
1363 $all = false;
1364 }
1365
1366 if ( isset( $row->user_token ) ) {
1367 // The definition for the column is binary(32), so trim the NULs
1368 // that appends. The previous definition was char(32), so trim
1369 // spaces too.
1370 $this->mToken = rtrim( $row->user_token, " \0" );
1371 if ( $this->mToken === '' ) {
1372 $this->mToken = null;
1373 }
1374 } else {
1375 $all = false;
1376 }
1377
1378 if ( isset( $row->user_email ) ) {
1379 $this->mEmail = $row->user_email;
1380 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1381 $this->mEmailToken = $row->user_email_token;
1382 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1383 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1384 } else {
1385 $all = false;
1386 }
1387
1388 if ( $all ) {
1389 $this->mLoadedItems = true;
1390 }
1391
1392 if ( is_array( $data ) ) {
1393 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1394 if ( !count( $data['user_groups'] ) ) {
1395 $this->mGroupMemberships = [];
1396 } else {
1397 $firstGroup = reset( $data['user_groups'] );
1398 if ( is_array( $firstGroup ) || is_object( $firstGroup ) ) {
1399 $this->mGroupMemberships = [];
1400 foreach ( $data['user_groups'] as $row ) {
1401 $ugm = UserGroupMembership::newFromRow( (object)$row );
1402 $this->mGroupMemberships[$ugm->getGroup()] = $ugm;
1403 }
1404 }
1405 }
1406 }
1407 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1408 $this->loadOptions( $data['user_properties'] );
1409 }
1410 }
1411 }
1412
1413 /**
1414 * Load the data for this user object from another user object.
1415 *
1416 * @param User $user
1417 */
1418 protected function loadFromUserObject( $user ) {
1419 $user->load();
1420 foreach ( self::$mCacheVars as $var ) {
1421 $this->$var = $user->$var;
1422 }
1423 }
1424
1425 /**
1426 * Load the groups from the database if they aren't already loaded.
1427 */
1428 private function loadGroups() {
1429 if ( is_null( $this->mGroupMemberships ) ) {
1430 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
1431 ? wfGetDB( DB_MASTER )
1432 : wfGetDB( DB_REPLICA );
1433 $this->mGroupMemberships = UserGroupMembership::getMembershipsForUser(
1434 $this->mId, $db );
1435 }
1436 }
1437
1438 /**
1439 * Add the user to the group if he/she meets given criteria.
1440 *
1441 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1442 * possible to remove manually via Special:UserRights. In such case it
1443 * will not be re-added automatically. The user will also not lose the
1444 * group if they no longer meet the criteria.
1445 *
1446 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1447 *
1448 * @return array Array of groups the user has been promoted to.
1449 *
1450 * @see $wgAutopromoteOnce
1451 */
1452 public function addAutopromoteOnceGroups( $event ) {
1453 global $wgAutopromoteOnceLogInRC;
1454
1455 if ( wfReadOnly() || !$this->getId() ) {
1456 return [];
1457 }
1458
1459 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1460 if ( !count( $toPromote ) ) {
1461 return [];
1462 }
1463
1464 if ( !$this->checkAndSetTouched() ) {
1465 return []; // raced out (bug T48834)
1466 }
1467
1468 $oldGroups = $this->getGroups(); // previous groups
1469 $oldUGMs = $this->getGroupMemberships();
1470 foreach ( $toPromote as $group ) {
1471 $this->addGroup( $group );
1472 }
1473 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1474 $newUGMs = $this->getGroupMemberships();
1475
1476 // update groups in external authentication database
1477 Hooks::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false, $oldUGMs, $newUGMs ] );
1478 AuthManager::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1479
1480 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1481 $logEntry->setPerformer( $this );
1482 $logEntry->setTarget( $this->getUserPage() );
1483 $logEntry->setParameters( [
1484 '4::oldgroups' => $oldGroups,
1485 '5::newgroups' => $newGroups,
1486 ] );
1487 $logid = $logEntry->insert();
1488 if ( $wgAutopromoteOnceLogInRC ) {
1489 $logEntry->publish( $logid );
1490 }
1491
1492 return $toPromote;
1493 }
1494
1495 /**
1496 * Builds update conditions. Additional conditions may be added to $conditions to
1497 * protected against race conditions using a compare-and-set (CAS) mechanism
1498 * based on comparing $this->mTouched with the user_touched field.
1499 *
1500 * @param Database $db
1501 * @param array $conditions WHERE conditions for use with Database::update
1502 * @return array WHERE conditions for use with Database::update
1503 */
1504 protected function makeUpdateConditions( Database $db, array $conditions ) {
1505 if ( $this->mTouched ) {
1506 // CAS check: only update if the row wasn't changed sicne it was loaded.
1507 $conditions['user_touched'] = $db->timestamp( $this->mTouched );
1508 }
1509
1510 return $conditions;
1511 }
1512
1513 /**
1514 * Bump user_touched if it didn't change since this object was loaded
1515 *
1516 * On success, the mTouched field is updated.
1517 * The user serialization cache is always cleared.
1518 *
1519 * @return bool Whether user_touched was actually updated
1520 * @since 1.26
1521 */
1522 protected function checkAndSetTouched() {
1523 $this->load();
1524
1525 if ( !$this->mId ) {
1526 return false; // anon
1527 }
1528
1529 // Get a new user_touched that is higher than the old one
1530 $newTouched = $this->newTouchedTimestamp();
1531
1532 $dbw = wfGetDB( DB_MASTER );
1533 $dbw->update( 'user',
1534 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1535 $this->makeUpdateConditions( $dbw, [
1536 'user_id' => $this->mId,
1537 ] ),
1538 __METHOD__
1539 );
1540 $success = ( $dbw->affectedRows() > 0 );
1541
1542 if ( $success ) {
1543 $this->mTouched = $newTouched;
1544 $this->clearSharedCache();
1545 } else {
1546 // Clears on failure too since that is desired if the cache is stale
1547 $this->clearSharedCache( 'refresh' );
1548 }
1549
1550 return $success;
1551 }
1552
1553 /**
1554 * Clear various cached data stored in this object. The cache of the user table
1555 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1556 *
1557 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1558 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1559 */
1560 public function clearInstanceCache( $reloadFrom = false ) {
1561 $this->mNewtalk = -1;
1562 $this->mDatePreference = null;
1563 $this->mBlockedby = -1; # Unset
1564 $this->mHash = false;
1565 $this->mRights = null;
1566 $this->mEffectiveGroups = null;
1567 $this->mImplicitGroups = null;
1568 $this->mGroupMemberships = null;
1569 $this->mOptions = null;
1570 $this->mOptionsLoaded = false;
1571 $this->mEditCount = null;
1572
1573 if ( $reloadFrom ) {
1574 $this->mLoadedItems = [];
1575 $this->mFrom = $reloadFrom;
1576 }
1577 }
1578
1579 /**
1580 * Combine the language default options with any site-specific options
1581 * and add the default language variants.
1582 *
1583 * @return array Array of String options
1584 */
1585 public static function getDefaultOptions() {
1586 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1587
1588 static $defOpt = null;
1589 static $defOptLang = null;
1590
1591 if ( $defOpt !== null && $defOptLang === $wgContLang->getCode() ) {
1592 // $wgContLang does not change (and should not change) mid-request,
1593 // but the unit tests change it anyway, and expect this method to
1594 // return values relevant to the current $wgContLang.
1595 return $defOpt;
1596 }
1597
1598 $defOpt = $wgDefaultUserOptions;
1599 // Default language setting
1600 $defOptLang = $wgContLang->getCode();
1601 $defOpt['language'] = $defOptLang;
1602 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1603 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1604 }
1605
1606 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1607 // since extensions may change the set of searchable namespaces depending
1608 // on user groups/permissions.
1609 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1610 $defOpt['searchNs' . $nsnum] = (bool)$val;
1611 }
1612 $defOpt['skin'] = Skin::normalizeKey( $wgDefaultSkin );
1613
1614 Hooks::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1615
1616 return $defOpt;
1617 }
1618
1619 /**
1620 * Get a given default option value.
1621 *
1622 * @param string $opt Name of option to retrieve
1623 * @return string Default option value
1624 */
1625 public static function getDefaultOption( $opt ) {
1626 $defOpts = self::getDefaultOptions();
1627 if ( isset( $defOpts[$opt] ) ) {
1628 return $defOpts[$opt];
1629 } else {
1630 return null;
1631 }
1632 }
1633
1634 /**
1635 * Get blocking information
1636 * @param bool $bFromSlave Whether to check the replica DB first.
1637 * To improve performance, non-critical checks are done against replica DBs.
1638 * Check when actually saving should be done against master.
1639 */
1640 private function getBlockedStatus( $bFromSlave = true ) {
1641 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff, $wgSoftBlockRanges;
1642
1643 if ( -1 != $this->mBlockedby ) {
1644 return;
1645 }
1646
1647 wfDebug( __METHOD__ . ": checking...\n" );
1648
1649 // Initialize data...
1650 // Otherwise something ends up stomping on $this->mBlockedby when
1651 // things get lazy-loaded later, causing false positive block hits
1652 // due to -1 !== 0. Probably session-related... Nothing should be
1653 // overwriting mBlockedby, surely?
1654 $this->load();
1655
1656 # We only need to worry about passing the IP address to the Block generator if the
1657 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1658 # know which IP address they're actually coming from
1659 $ip = null;
1660 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1661 // $wgUser->getName() only works after the end of Setup.php. Until
1662 // then, assume it's a logged-out user.
1663 $globalUserName = $wgUser->isSafeToLoad()
1664 ? $wgUser->getName()
1665 : IP::sanitizeIP( $wgUser->getRequest()->getIP() );
1666 if ( $this->getName() === $globalUserName ) {
1667 $ip = $this->getRequest()->getIP();
1668 }
1669 }
1670
1671 // User/IP blocking
1672 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1673
1674 // Cookie blocking
1675 if ( !$block instanceof Block ) {
1676 $block = $this->getBlockFromCookieValue( $this->getRequest()->getCookie( 'BlockID' ) );
1677 }
1678
1679 // Proxy blocking
1680 if ( !$block instanceof Block && $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1681 // Local list
1682 if ( self::isLocallyBlockedProxy( $ip ) ) {
1683 $block = new Block( [
1684 'byText' => wfMessage( 'proxyblocker' )->text(),
1685 'reason' => wfMessage( 'proxyblockreason' )->text(),
1686 'address' => $ip,
1687 'systemBlock' => 'proxy',
1688 ] );
1689 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1690 $block = new Block( [
1691 'byText' => wfMessage( 'sorbs' )->text(),
1692 'reason' => wfMessage( 'sorbsreason' )->text(),
1693 'address' => $ip,
1694 'systemBlock' => 'dnsbl',
1695 ] );
1696 }
1697 }
1698
1699 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
1700 if ( !$block instanceof Block
1701 && $wgApplyIpBlocksToXff
1702 && $ip !== null
1703 && !in_array( $ip, $wgProxyWhitelist )
1704 ) {
1705 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1706 $xff = array_map( 'trim', explode( ',', $xff ) );
1707 $xff = array_diff( $xff, [ $ip ] );
1708 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1709 $block = Block::chooseBlock( $xffblocks, $xff );
1710 if ( $block instanceof Block ) {
1711 # Mangle the reason to alert the user that the block
1712 # originated from matching the X-Forwarded-For header.
1713 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1714 }
1715 }
1716
1717 if ( !$block instanceof Block
1718 && $ip !== null
1719 && $this->isAnon()
1720 && IP::isInRanges( $ip, $wgSoftBlockRanges )
1721 ) {
1722 $block = new Block( [
1723 'address' => $ip,
1724 'byText' => 'MediaWiki default',
1725 'reason' => wfMessage( 'softblockrangesreason', $ip )->text(),
1726 'anonOnly' => true,
1727 'systemBlock' => 'wgSoftBlockRanges',
1728 ] );
1729 }
1730
1731 if ( $block instanceof Block ) {
1732 wfDebug( __METHOD__ . ": Found block.\n" );
1733 $this->mBlock = $block;
1734 $this->mBlockedby = $block->getByName();
1735 $this->mBlockreason = $block->mReason;
1736 $this->mHideName = $block->mHideName;
1737 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1738 } else {
1739 $this->mBlockedby = '';
1740 $this->mHideName = 0;
1741 $this->mAllowUsertalk = false;
1742 }
1743
1744 // Avoid PHP 7.1 warning of passing $this by reference
1745 $user = $this;
1746 // Extensions
1747 Hooks::run( 'GetBlockedStatus', [ &$user ] );
1748 }
1749
1750 /**
1751 * Try to load a Block from an ID given in a cookie value.
1752 * @param string|null $blockCookieVal The cookie value to check.
1753 * @return Block|bool The Block object, or false if none could be loaded.
1754 */
1755 protected function getBlockFromCookieValue( $blockCookieVal ) {
1756 // Make sure there's something to check. The cookie value must start with a number.
1757 if ( strlen( $blockCookieVal ) < 1 || !is_numeric( substr( $blockCookieVal, 0, 1 ) ) ) {
1758 return false;
1759 }
1760 // Load the Block from the ID in the cookie.
1761 $blockCookieId = Block::getIdFromCookieValue( $blockCookieVal );
1762 if ( $blockCookieId !== null ) {
1763 // An ID was found in the cookie.
1764 $tmpBlock = Block::newFromID( $blockCookieId );
1765 if ( $tmpBlock instanceof Block ) {
1766 // Check the validity of the block.
1767 $blockIsValid = $tmpBlock->getType() == Block::TYPE_USER
1768 && !$tmpBlock->isExpired()
1769 && $tmpBlock->isAutoblocking();
1770 $config = RequestContext::getMain()->getConfig();
1771 $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true );
1772 if ( $blockIsValid && $useBlockCookie ) {
1773 // Use the block.
1774 return $tmpBlock;
1775 } else {
1776 // If the block is not valid, remove the cookie.
1777 Block::clearCookie( $this->getRequest()->response() );
1778 }
1779 } else {
1780 // If the block doesn't exist, remove the cookie.
1781 Block::clearCookie( $this->getRequest()->response() );
1782 }
1783 }
1784 return false;
1785 }
1786
1787 /**
1788 * Whether the given IP is in a DNS blacklist.
1789 *
1790 * @param string $ip IP to check
1791 * @param bool $checkWhitelist Whether to check the whitelist first
1792 * @return bool True if blacklisted.
1793 */
1794 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1795 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1796
1797 if ( !$wgEnableDnsBlacklist ) {
1798 return false;
1799 }
1800
1801 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1802 return false;
1803 }
1804
1805 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1806 }
1807
1808 /**
1809 * Whether the given IP is in a given DNS blacklist.
1810 *
1811 * @param string $ip IP to check
1812 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1813 * @return bool True if blacklisted.
1814 */
1815 public function inDnsBlacklist( $ip, $bases ) {
1816 $found = false;
1817 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1818 if ( IP::isIPv4( $ip ) ) {
1819 // Reverse IP, T23255
1820 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1821
1822 foreach ( (array)$bases as $base ) {
1823 // Make hostname
1824 // If we have an access key, use that too (ProjectHoneypot, etc.)
1825 $basename = $base;
1826 if ( is_array( $base ) ) {
1827 if ( count( $base ) >= 2 ) {
1828 // Access key is 1, base URL is 0
1829 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1830 } else {
1831 $host = "$ipReversed.{$base[0]}";
1832 }
1833 $basename = $base[0];
1834 } else {
1835 $host = "$ipReversed.$base";
1836 }
1837
1838 // Send query
1839 $ipList = gethostbynamel( $host );
1840
1841 if ( $ipList ) {
1842 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1843 $found = true;
1844 break;
1845 } else {
1846 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1847 }
1848 }
1849 }
1850
1851 return $found;
1852 }
1853
1854 /**
1855 * Check if an IP address is in the local proxy list
1856 *
1857 * @param string $ip
1858 *
1859 * @return bool
1860 */
1861 public static function isLocallyBlockedProxy( $ip ) {
1862 global $wgProxyList;
1863
1864 if ( !$wgProxyList ) {
1865 return false;
1866 }
1867
1868 if ( !is_array( $wgProxyList ) ) {
1869 // Load values from the specified file
1870 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1871 }
1872
1873 $resultProxyList = [];
1874 $deprecatedIPEntries = [];
1875
1876 // backward compatibility: move all ip addresses in keys to values
1877 foreach ( $wgProxyList as $key => $value ) {
1878 $keyIsIP = IP::isIPAddress( $key );
1879 $valueIsIP = IP::isIPAddress( $value );
1880 if ( $keyIsIP && !$valueIsIP ) {
1881 $deprecatedIPEntries[] = $key;
1882 $resultProxyList[] = $key;
1883 } elseif ( $keyIsIP && $valueIsIP ) {
1884 $deprecatedIPEntries[] = $key;
1885 $resultProxyList[] = $key;
1886 $resultProxyList[] = $value;
1887 } else {
1888 $resultProxyList[] = $value;
1889 }
1890 }
1891
1892 if ( $deprecatedIPEntries ) {
1893 wfDeprecated(
1894 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
1895 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
1896 }
1897
1898 $proxyListIPSet = new IPSet( $resultProxyList );
1899 return $proxyListIPSet->match( $ip );
1900 }
1901
1902 /**
1903 * Is this user subject to rate limiting?
1904 *
1905 * @return bool True if rate limited
1906 */
1907 public function isPingLimitable() {
1908 global $wgRateLimitsExcludedIPs;
1909 if ( IP::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1910 // No other good way currently to disable rate limits
1911 // for specific IPs. :P
1912 // But this is a crappy hack and should die.
1913 return false;
1914 }
1915 return !$this->isAllowed( 'noratelimit' );
1916 }
1917
1918 /**
1919 * Primitive rate limits: enforce maximum actions per time period
1920 * to put a brake on flooding.
1921 *
1922 * The method generates both a generic profiling point and a per action one
1923 * (suffix being "-$action".
1924 *
1925 * @note When using a shared cache like memcached, IP-address
1926 * last-hit counters will be shared across wikis.
1927 *
1928 * @param string $action Action to enforce; 'edit' if unspecified
1929 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1930 * @return bool True if a rate limiter was tripped
1931 */
1932 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1933 // Avoid PHP 7.1 warning of passing $this by reference
1934 $user = $this;
1935 // Call the 'PingLimiter' hook
1936 $result = false;
1937 if ( !Hooks::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
1938 return $result;
1939 }
1940
1941 global $wgRateLimits;
1942 if ( !isset( $wgRateLimits[$action] ) ) {
1943 return false;
1944 }
1945
1946 $limits = array_merge(
1947 [ '&can-bypass' => true ],
1948 $wgRateLimits[$action]
1949 );
1950
1951 // Some groups shouldn't trigger the ping limiter, ever
1952 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1953 return false;
1954 }
1955
1956 $keys = [];
1957 $id = $this->getId();
1958 $userLimit = false;
1959 $isNewbie = $this->isNewbie();
1960 $cache = ObjectCache::getLocalClusterInstance();
1961
1962 if ( $id == 0 ) {
1963 // limits for anons
1964 if ( isset( $limits['anon'] ) ) {
1965 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1966 }
1967 } else {
1968 // limits for logged-in users
1969 if ( isset( $limits['user'] ) ) {
1970 $userLimit = $limits['user'];
1971 }
1972 // limits for newbie logged-in users
1973 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1974 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1975 }
1976 }
1977
1978 // limits for anons and for newbie logged-in users
1979 if ( $isNewbie ) {
1980 // ip-based limits
1981 if ( isset( $limits['ip'] ) ) {
1982 $ip = $this->getRequest()->getIP();
1983 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1984 }
1985 // subnet-based limits
1986 if ( isset( $limits['subnet'] ) ) {
1987 $ip = $this->getRequest()->getIP();
1988 $subnet = IP::getSubnet( $ip );
1989 if ( $subnet !== false ) {
1990 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1991 }
1992 }
1993 }
1994
1995 // Check for group-specific permissions
1996 // If more than one group applies, use the group with the highest limit ratio (max/period)
1997 foreach ( $this->getGroups() as $group ) {
1998 if ( isset( $limits[$group] ) ) {
1999 if ( $userLimit === false
2000 || $limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
2001 ) {
2002 $userLimit = $limits[$group];
2003 }
2004 }
2005 }
2006
2007 // Set the user limit key
2008 if ( $userLimit !== false ) {
2009 list( $max, $period ) = $userLimit;
2010 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
2011 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
2012 }
2013
2014 // ip-based limits for all ping-limitable users
2015 if ( isset( $limits['ip-all'] ) ) {
2016 $ip = $this->getRequest()->getIP();
2017 // ignore if user limit is more permissive
2018 if ( $isNewbie || $userLimit === false
2019 || $limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2020 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
2021 }
2022 }
2023
2024 // subnet-based limits for all ping-limitable users
2025 if ( isset( $limits['subnet-all'] ) ) {
2026 $ip = $this->getRequest()->getIP();
2027 $subnet = IP::getSubnet( $ip );
2028 if ( $subnet !== false ) {
2029 // ignore if user limit is more permissive
2030 if ( $isNewbie || $userLimit === false
2031 || $limits['ip-all'][0] / $limits['ip-all'][1]
2032 > $userLimit[0] / $userLimit[1] ) {
2033 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2034 }
2035 }
2036 }
2037
2038 $triggered = false;
2039 foreach ( $keys as $key => $limit ) {
2040 list( $max, $period ) = $limit;
2041 $summary = "(limit $max in {$period}s)";
2042 $count = $cache->get( $key );
2043 // Already pinged?
2044 if ( $count ) {
2045 if ( $count >= $max ) {
2046 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2047 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2048 $triggered = true;
2049 } else {
2050 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
2051 }
2052 } else {
2053 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
2054 if ( $incrBy > 0 ) {
2055 $cache->add( $key, 0, intval( $period ) ); // first ping
2056 }
2057 }
2058 if ( $incrBy > 0 ) {
2059 $cache->incr( $key, $incrBy );
2060 }
2061 }
2062
2063 return $triggered;
2064 }
2065
2066 /**
2067 * Check if user is blocked
2068 *
2069 * @param bool $bFromSlave Whether to check the replica DB instead of
2070 * the master. Hacked from false due to horrible probs on site.
2071 * @return bool True if blocked, false otherwise
2072 */
2073 public function isBlocked( $bFromSlave = true ) {
2074 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
2075 }
2076
2077 /**
2078 * Get the block affecting the user, or null if the user is not blocked
2079 *
2080 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2081 * @return Block|null
2082 */
2083 public function getBlock( $bFromSlave = true ) {
2084 $this->getBlockedStatus( $bFromSlave );
2085 return $this->mBlock instanceof Block ? $this->mBlock : null;
2086 }
2087
2088 /**
2089 * Check if user is blocked from editing a particular article
2090 *
2091 * @param Title $title Title to check
2092 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2093 * @return bool
2094 */
2095 public function isBlockedFrom( $title, $bFromSlave = false ) {
2096 global $wgBlockAllowsUTEdit;
2097
2098 $blocked = $this->isBlocked( $bFromSlave );
2099 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
2100 // If a user's name is suppressed, they cannot make edits anywhere
2101 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
2102 && $title->getNamespace() == NS_USER_TALK ) {
2103 $blocked = false;
2104 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
2105 }
2106
2107 Hooks::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2108
2109 return $blocked;
2110 }
2111
2112 /**
2113 * If user is blocked, return the name of the user who placed the block
2114 * @return string Name of blocker
2115 */
2116 public function blockedBy() {
2117 $this->getBlockedStatus();
2118 return $this->mBlockedby;
2119 }
2120
2121 /**
2122 * If user is blocked, return the specified reason for the block
2123 * @return string Blocking reason
2124 */
2125 public function blockedFor() {
2126 $this->getBlockedStatus();
2127 return $this->mBlockreason;
2128 }
2129
2130 /**
2131 * If user is blocked, return the ID for the block
2132 * @return int Block ID
2133 */
2134 public function getBlockId() {
2135 $this->getBlockedStatus();
2136 return ( $this->mBlock ? $this->mBlock->getId() : false );
2137 }
2138
2139 /**
2140 * Check if user is blocked on all wikis.
2141 * Do not use for actual edit permission checks!
2142 * This is intended for quick UI checks.
2143 *
2144 * @param string $ip IP address, uses current client if none given
2145 * @return bool True if blocked, false otherwise
2146 */
2147 public function isBlockedGlobally( $ip = '' ) {
2148 return $this->getGlobalBlock( $ip ) instanceof Block;
2149 }
2150
2151 /**
2152 * Check if user is blocked on all wikis.
2153 * Do not use for actual edit permission checks!
2154 * This is intended for quick UI checks.
2155 *
2156 * @param string $ip IP address, uses current client if none given
2157 * @return Block|null Block object if blocked, null otherwise
2158 * @throws FatalError
2159 * @throws MWException
2160 */
2161 public function getGlobalBlock( $ip = '' ) {
2162 if ( $this->mGlobalBlock !== null ) {
2163 return $this->mGlobalBlock ?: null;
2164 }
2165 // User is already an IP?
2166 if ( IP::isIPAddress( $this->getName() ) ) {
2167 $ip = $this->getName();
2168 } elseif ( !$ip ) {
2169 $ip = $this->getRequest()->getIP();
2170 }
2171 // Avoid PHP 7.1 warning of passing $this by reference
2172 $user = $this;
2173 $blocked = false;
2174 $block = null;
2175 Hooks::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2176
2177 if ( $blocked && $block === null ) {
2178 // back-compat: UserIsBlockedGlobally didn't have $block param first
2179 $block = new Block( [
2180 'address' => $ip,
2181 'systemBlock' => 'global-block'
2182 ] );
2183 }
2184
2185 $this->mGlobalBlock = $blocked ? $block : false;
2186 return $this->mGlobalBlock ?: null;
2187 }
2188
2189 /**
2190 * Check if user account is locked
2191 *
2192 * @return bool True if locked, false otherwise
2193 */
2194 public function isLocked() {
2195 if ( $this->mLocked !== null ) {
2196 return $this->mLocked;
2197 }
2198 // Avoid PHP 7.1 warning of passing $this by reference
2199 $user = $this;
2200 $authUser = AuthManager::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2201 $this->mLocked = $authUser && $authUser->isLocked();
2202 Hooks::run( 'UserIsLocked', [ $this, &$this->mLocked ] );
2203 return $this->mLocked;
2204 }
2205
2206 /**
2207 * Check if user account is hidden
2208 *
2209 * @return bool True if hidden, false otherwise
2210 */
2211 public function isHidden() {
2212 if ( $this->mHideName !== null ) {
2213 return $this->mHideName;
2214 }
2215 $this->getBlockedStatus();
2216 if ( !$this->mHideName ) {
2217 // Avoid PHP 7.1 warning of passing $this by reference
2218 $user = $this;
2219 $authUser = AuthManager::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2220 $this->mHideName = $authUser && $authUser->isHidden();
2221 Hooks::run( 'UserIsHidden', [ $this, &$this->mHideName ] );
2222 }
2223 return $this->mHideName;
2224 }
2225
2226 /**
2227 * Get the user's ID.
2228 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2229 */
2230 public function getId() {
2231 if ( $this->mId === null && $this->mName !== null && self::isIP( $this->mName ) ) {
2232 // Special case, we know the user is anonymous
2233 return 0;
2234 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2235 // Don't load if this was initialized from an ID
2236 $this->load();
2237 }
2238
2239 return (int)$this->mId;
2240 }
2241
2242 /**
2243 * Set the user and reload all fields according to a given ID
2244 * @param int $v User ID to reload
2245 */
2246 public function setId( $v ) {
2247 $this->mId = $v;
2248 $this->clearInstanceCache( 'id' );
2249 }
2250
2251 /**
2252 * Get the user name, or the IP of an anonymous user
2253 * @return string User's name or IP address
2254 */
2255 public function getName() {
2256 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2257 // Special case optimisation
2258 return $this->mName;
2259 } else {
2260 $this->load();
2261 if ( $this->mName === false ) {
2262 // Clean up IPs
2263 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
2264 }
2265 return $this->mName;
2266 }
2267 }
2268
2269 /**
2270 * Set the user name.
2271 *
2272 * This does not reload fields from the database according to the given
2273 * name. Rather, it is used to create a temporary "nonexistent user" for
2274 * later addition to the database. It can also be used to set the IP
2275 * address for an anonymous user to something other than the current
2276 * remote IP.
2277 *
2278 * @note User::newFromName() has roughly the same function, when the named user
2279 * does not exist.
2280 * @param string $str New user name to set
2281 */
2282 public function setName( $str ) {
2283 $this->load();
2284 $this->mName = $str;
2285 }
2286
2287 /**
2288 * Get the user's name escaped by underscores.
2289 * @return string Username escaped by underscores.
2290 */
2291 public function getTitleKey() {
2292 return str_replace( ' ', '_', $this->getName() );
2293 }
2294
2295 /**
2296 * Check if the user has new messages.
2297 * @return bool True if the user has new messages
2298 */
2299 public function getNewtalk() {
2300 $this->load();
2301
2302 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2303 if ( $this->mNewtalk === -1 ) {
2304 $this->mNewtalk = false; # reset talk page status
2305
2306 // Check memcached separately for anons, who have no
2307 // entire User object stored in there.
2308 if ( !$this->mId ) {
2309 global $wgDisableAnonTalk;
2310 if ( $wgDisableAnonTalk ) {
2311 // Anon newtalk disabled by configuration.
2312 $this->mNewtalk = false;
2313 } else {
2314 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName() );
2315 }
2316 } else {
2317 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
2318 }
2319 }
2320
2321 return (bool)$this->mNewtalk;
2322 }
2323
2324 /**
2325 * Return the data needed to construct links for new talk page message
2326 * alerts. If there are new messages, this will return an associative array
2327 * with the following data:
2328 * wiki: The database name of the wiki
2329 * link: Root-relative link to the user's talk page
2330 * rev: The last talk page revision that the user has seen or null. This
2331 * is useful for building diff links.
2332 * If there are no new messages, it returns an empty array.
2333 * @note This function was designed to accomodate multiple talk pages, but
2334 * currently only returns a single link and revision.
2335 * @return array
2336 */
2337 public function getNewMessageLinks() {
2338 // Avoid PHP 7.1 warning of passing $this by reference
2339 $user = $this;
2340 $talks = [];
2341 if ( !Hooks::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2342 return $talks;
2343 } elseif ( !$this->getNewtalk() ) {
2344 return [];
2345 }
2346 $utp = $this->getTalkPage();
2347 $dbr = wfGetDB( DB_REPLICA );
2348 // Get the "last viewed rev" timestamp from the oldest message notification
2349 $timestamp = $dbr->selectField( 'user_newtalk',
2350 'MIN(user_last_timestamp)',
2351 $this->isAnon() ? [ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2352 __METHOD__ );
2353 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2354 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2355 }
2356
2357 /**
2358 * Get the revision ID for the last talk page revision viewed by the talk
2359 * page owner.
2360 * @return int|null Revision ID or null
2361 */
2362 public function getNewMessageRevisionId() {
2363 $newMessageRevisionId = null;
2364 $newMessageLinks = $this->getNewMessageLinks();
2365 if ( $newMessageLinks ) {
2366 // Note: getNewMessageLinks() never returns more than a single link
2367 // and it is always for the same wiki, but we double-check here in
2368 // case that changes some time in the future.
2369 if ( count( $newMessageLinks ) === 1
2370 && $newMessageLinks[0]['wiki'] === wfWikiID()
2371 && $newMessageLinks[0]['rev']
2372 ) {
2373 /** @var Revision $newMessageRevision */
2374 $newMessageRevision = $newMessageLinks[0]['rev'];
2375 $newMessageRevisionId = $newMessageRevision->getId();
2376 }
2377 }
2378 return $newMessageRevisionId;
2379 }
2380
2381 /**
2382 * Internal uncached check for new messages
2383 *
2384 * @see getNewtalk()
2385 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2386 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2387 * @return bool True if the user has new messages
2388 */
2389 protected function checkNewtalk( $field, $id ) {
2390 $dbr = wfGetDB( DB_REPLICA );
2391
2392 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__ );
2393
2394 return $ok !== false;
2395 }
2396
2397 /**
2398 * Add or update the new messages flag
2399 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2400 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2401 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2402 * @return bool True if successful, false otherwise
2403 */
2404 protected function updateNewtalk( $field, $id, $curRev = null ) {
2405 // Get timestamp of the talk page revision prior to the current one
2406 $prevRev = $curRev ? $curRev->getPrevious() : false;
2407 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2408 // Mark the user as having new messages since this revision
2409 $dbw = wfGetDB( DB_MASTER );
2410 $dbw->insert( 'user_newtalk',
2411 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2412 __METHOD__,
2413 'IGNORE' );
2414 if ( $dbw->affectedRows() ) {
2415 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2416 return true;
2417 } else {
2418 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2419 return false;
2420 }
2421 }
2422
2423 /**
2424 * Clear the new messages flag for the given user
2425 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2426 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2427 * @return bool True if successful, false otherwise
2428 */
2429 protected function deleteNewtalk( $field, $id ) {
2430 $dbw = wfGetDB( DB_MASTER );
2431 $dbw->delete( 'user_newtalk',
2432 [ $field => $id ],
2433 __METHOD__ );
2434 if ( $dbw->affectedRows() ) {
2435 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2436 return true;
2437 } else {
2438 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2439 return false;
2440 }
2441 }
2442
2443 /**
2444 * Update the 'You have new messages!' status.
2445 * @param bool $val Whether the user has new messages
2446 * @param Revision $curRev New, as yet unseen revision of the user talk
2447 * page. Ignored if null or !$val.
2448 */
2449 public function setNewtalk( $val, $curRev = null ) {
2450 if ( wfReadOnly() ) {
2451 return;
2452 }
2453
2454 $this->load();
2455 $this->mNewtalk = $val;
2456
2457 if ( $this->isAnon() ) {
2458 $field = 'user_ip';
2459 $id = $this->getName();
2460 } else {
2461 $field = 'user_id';
2462 $id = $this->getId();
2463 }
2464
2465 if ( $val ) {
2466 $changed = $this->updateNewtalk( $field, $id, $curRev );
2467 } else {
2468 $changed = $this->deleteNewtalk( $field, $id );
2469 }
2470
2471 if ( $changed ) {
2472 $this->invalidateCache();
2473 }
2474 }
2475
2476 /**
2477 * Generate a current or new-future timestamp to be stored in the
2478 * user_touched field when we update things.
2479 * @return string Timestamp in TS_MW format
2480 */
2481 private function newTouchedTimestamp() {
2482 global $wgClockSkewFudge;
2483
2484 $time = wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2485 if ( $this->mTouched && $time <= $this->mTouched ) {
2486 $time = wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $this->mTouched ) + 1 );
2487 }
2488
2489 return $time;
2490 }
2491
2492 /**
2493 * Clear user data from memcached
2494 *
2495 * Use after applying updates to the database; caller's
2496 * responsibility to update user_touched if appropriate.
2497 *
2498 * Called implicitly from invalidateCache() and saveSettings().
2499 *
2500 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2501 */
2502 public function clearSharedCache( $mode = 'changed' ) {
2503 if ( !$this->getId() ) {
2504 return;
2505 }
2506
2507 $cache = ObjectCache::getMainWANInstance();
2508 $key = $this->getCacheKey( $cache );
2509 if ( $mode === 'refresh' ) {
2510 $cache->delete( $key, 1 );
2511 } else {
2512 wfGetDB( DB_MASTER )->onTransactionPreCommitOrIdle(
2513 function () use ( $cache, $key ) {
2514 $cache->delete( $key );
2515 },
2516 __METHOD__
2517 );
2518 }
2519 }
2520
2521 /**
2522 * Immediately touch the user data cache for this account
2523 *
2524 * Calls touch() and removes account data from memcached
2525 */
2526 public function invalidateCache() {
2527 $this->touch();
2528 $this->clearSharedCache();
2529 }
2530
2531 /**
2532 * Update the "touched" timestamp for the user
2533 *
2534 * This is useful on various login/logout events when making sure that
2535 * a browser or proxy that has multiple tenants does not suffer cache
2536 * pollution where the new user sees the old users content. The value
2537 * of getTouched() is checked when determining 304 vs 200 responses.
2538 * Unlike invalidateCache(), this preserves the User object cache and
2539 * avoids database writes.
2540 *
2541 * @since 1.25
2542 */
2543 public function touch() {
2544 $id = $this->getId();
2545 if ( $id ) {
2546 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2547 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2548 $cache->touchCheckKey( $key );
2549 $this->mQuickTouched = null;
2550 }
2551 }
2552
2553 /**
2554 * Validate the cache for this account.
2555 * @param string $timestamp A timestamp in TS_MW format
2556 * @return bool
2557 */
2558 public function validateCache( $timestamp ) {
2559 return ( $timestamp >= $this->getTouched() );
2560 }
2561
2562 /**
2563 * Get the user touched timestamp
2564 *
2565 * Use this value only to validate caches via inequalities
2566 * such as in the case of HTTP If-Modified-Since response logic
2567 *
2568 * @return string TS_MW Timestamp
2569 */
2570 public function getTouched() {
2571 $this->load();
2572
2573 if ( $this->mId ) {
2574 if ( $this->mQuickTouched === null ) {
2575 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2576 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId );
2577
2578 $this->mQuickTouched = wfTimestamp( TS_MW, $cache->getCheckKeyTime( $key ) );
2579 }
2580
2581 return max( $this->mTouched, $this->mQuickTouched );
2582 }
2583
2584 return $this->mTouched;
2585 }
2586
2587 /**
2588 * Get the user_touched timestamp field (time of last DB updates)
2589 * @return string TS_MW Timestamp
2590 * @since 1.26
2591 */
2592 public function getDBTouched() {
2593 $this->load();
2594
2595 return $this->mTouched;
2596 }
2597
2598 /**
2599 * Set the password and reset the random token.
2600 * Calls through to authentication plugin if necessary;
2601 * will have no effect if the auth plugin refuses to
2602 * pass the change through or if the legal password
2603 * checks fail.
2604 *
2605 * As a special case, setting the password to null
2606 * wipes it, so the account cannot be logged in until
2607 * a new password is set, for instance via e-mail.
2608 *
2609 * @deprecated since 1.27, use AuthManager instead
2610 * @param string $str New password to set
2611 * @throws PasswordError On failure
2612 * @return bool
2613 */
2614 public function setPassword( $str ) {
2615 return $this->setPasswordInternal( $str );
2616 }
2617
2618 /**
2619 * Set the password and reset the random token unconditionally.
2620 *
2621 * @deprecated since 1.27, use AuthManager instead
2622 * @param string|null $str New password to set or null to set an invalid
2623 * password hash meaning that the user will not be able to log in
2624 * through the web interface.
2625 */
2626 public function setInternalPassword( $str ) {
2627 $this->setPasswordInternal( $str );
2628 }
2629
2630 /**
2631 * Actually set the password and such
2632 * @since 1.27 cannot set a password for a user not in the database
2633 * @param string|null $str New password to set or null to set an invalid
2634 * password hash meaning that the user will not be able to log in
2635 * through the web interface.
2636 * @return bool Success
2637 */
2638 private function setPasswordInternal( $str ) {
2639 $manager = AuthManager::singleton();
2640
2641 // If the user doesn't exist yet, fail
2642 if ( !$manager->userExists( $this->getName() ) ) {
2643 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2644 }
2645
2646 $status = $this->changeAuthenticationData( [
2647 'username' => $this->getName(),
2648 'password' => $str,
2649 'retype' => $str,
2650 ] );
2651 if ( !$status->isGood() ) {
2652 \MediaWiki\Logger\LoggerFactory::getInstance( 'authentication' )
2653 ->info( __METHOD__ . ': Password change rejected: '
2654 . $status->getWikiText( null, null, 'en' ) );
2655 return false;
2656 }
2657
2658 $this->setOption( 'watchlisttoken', false );
2659 SessionManager::singleton()->invalidateSessionsForUser( $this );
2660
2661 return true;
2662 }
2663
2664 /**
2665 * Changes credentials of the user.
2666 *
2667 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2668 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2669 * e.g. when no provider handled the change.
2670 *
2671 * @param array $data A set of authentication data in fieldname => value format. This is the
2672 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2673 * @return Status
2674 * @since 1.27
2675 */
2676 public function changeAuthenticationData( array $data ) {
2677 $manager = AuthManager::singleton();
2678 $reqs = $manager->getAuthenticationRequests( AuthManager::ACTION_CHANGE, $this );
2679 $reqs = AuthenticationRequest::loadRequestsFromSubmission( $reqs, $data );
2680
2681 $status = Status::newGood( 'ignored' );
2682 foreach ( $reqs as $req ) {
2683 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2684 }
2685 if ( $status->getValue() === 'ignored' ) {
2686 $status->warning( 'authenticationdatachange-ignored' );
2687 }
2688
2689 if ( $status->isGood() ) {
2690 foreach ( $reqs as $req ) {
2691 $manager->changeAuthenticationData( $req );
2692 }
2693 }
2694 return $status;
2695 }
2696
2697 /**
2698 * Get the user's current token.
2699 * @param bool $forceCreation Force the generation of a new token if the
2700 * user doesn't have one (default=true for backwards compatibility).
2701 * @return string|null Token
2702 */
2703 public function getToken( $forceCreation = true ) {
2704 global $wgAuthenticationTokenVersion;
2705
2706 $this->load();
2707 if ( !$this->mToken && $forceCreation ) {
2708 $this->setToken();
2709 }
2710
2711 if ( !$this->mToken ) {
2712 // The user doesn't have a token, return null to indicate that.
2713 return null;
2714 } elseif ( $this->mToken === self::INVALID_TOKEN ) {
2715 // We return a random value here so existing token checks are very
2716 // likely to fail.
2717 return MWCryptRand::generateHex( self::TOKEN_LENGTH );
2718 } elseif ( $wgAuthenticationTokenVersion === null ) {
2719 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2720 return $this->mToken;
2721 } else {
2722 // $wgAuthenticationTokenVersion in use, so hmac it.
2723 $ret = MWCryptHash::hmac( $wgAuthenticationTokenVersion, $this->mToken, false );
2724
2725 // The raw hash can be overly long. Shorten it up.
2726 $len = max( 32, self::TOKEN_LENGTH );
2727 if ( strlen( $ret ) < $len ) {
2728 // Should never happen, even md5 is 128 bits
2729 throw new \UnexpectedValueException( 'Hmac returned less than 128 bits' );
2730 }
2731 return substr( $ret, -$len );
2732 }
2733 }
2734
2735 /**
2736 * Set the random token (used for persistent authentication)
2737 * Called from loadDefaults() among other places.
2738 *
2739 * @param string|bool $token If specified, set the token to this value
2740 */
2741 public function setToken( $token = false ) {
2742 $this->load();
2743 if ( $this->mToken === self::INVALID_TOKEN ) {
2744 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
2745 ->debug( __METHOD__ . ": Ignoring attempt to set token for system user \"$this\"" );
2746 } elseif ( !$token ) {
2747 $this->mToken = MWCryptRand::generateHex( self::TOKEN_LENGTH );
2748 } else {
2749 $this->mToken = $token;
2750 }
2751 }
2752
2753 /**
2754 * Set the password for a password reminder or new account email
2755 *
2756 * @deprecated Removed in 1.27. Use PasswordReset instead.
2757 * @param string $str New password to set or null to set an invalid
2758 * password hash meaning that the user will not be able to use it
2759 * @param bool $throttle If true, reset the throttle timestamp to the present
2760 */
2761 public function setNewpassword( $str, $throttle = true ) {
2762 throw new BadMethodCallException( __METHOD__ . ' has been removed in 1.27' );
2763 }
2764
2765 /**
2766 * Get the user's e-mail address
2767 * @return string User's email address
2768 */
2769 public function getEmail() {
2770 $this->load();
2771 Hooks::run( 'UserGetEmail', [ $this, &$this->mEmail ] );
2772 return $this->mEmail;
2773 }
2774
2775 /**
2776 * Get the timestamp of the user's e-mail authentication
2777 * @return string TS_MW timestamp
2778 */
2779 public function getEmailAuthenticationTimestamp() {
2780 $this->load();
2781 Hooks::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated ] );
2782 return $this->mEmailAuthenticated;
2783 }
2784
2785 /**
2786 * Set the user's e-mail address
2787 * @param string $str New e-mail address
2788 */
2789 public function setEmail( $str ) {
2790 $this->load();
2791 if ( $str == $this->mEmail ) {
2792 return;
2793 }
2794 $this->invalidateEmail();
2795 $this->mEmail = $str;
2796 Hooks::run( 'UserSetEmail', [ $this, &$this->mEmail ] );
2797 }
2798
2799 /**
2800 * Set the user's e-mail address and a confirmation mail if needed.
2801 *
2802 * @since 1.20
2803 * @param string $str New e-mail address
2804 * @return Status
2805 */
2806 public function setEmailWithConfirmation( $str ) {
2807 global $wgEnableEmail, $wgEmailAuthentication;
2808
2809 if ( !$wgEnableEmail ) {
2810 return Status::newFatal( 'emaildisabled' );
2811 }
2812
2813 $oldaddr = $this->getEmail();
2814 if ( $str === $oldaddr ) {
2815 return Status::newGood( true );
2816 }
2817
2818 $type = $oldaddr != '' ? 'changed' : 'set';
2819 $notificationResult = null;
2820
2821 if ( $wgEmailAuthentication ) {
2822 // Send the user an email notifying the user of the change in registered
2823 // email address on their previous email address
2824 if ( $type == 'changed' ) {
2825 $change = $str != '' ? 'changed' : 'removed';
2826 $notificationResult = $this->sendMail(
2827 wfMessage( 'notificationemail_subject_' . $change )->text(),
2828 wfMessage( 'notificationemail_body_' . $change,
2829 $this->getRequest()->getIP(),
2830 $this->getName(),
2831 $str )->text()
2832 );
2833 }
2834 }
2835
2836 $this->setEmail( $str );
2837
2838 if ( $str !== '' && $wgEmailAuthentication ) {
2839 // Send a confirmation request to the new address if needed
2840 $result = $this->sendConfirmationMail( $type );
2841
2842 if ( $notificationResult !== null ) {
2843 $result->merge( $notificationResult );
2844 }
2845
2846 if ( $result->isGood() ) {
2847 // Say to the caller that a confirmation and notification mail has been sent
2848 $result->value = 'eauth';
2849 }
2850 } else {
2851 $result = Status::newGood( true );
2852 }
2853
2854 return $result;
2855 }
2856
2857 /**
2858 * Get the user's real name
2859 * @return string User's real name
2860 */
2861 public function getRealName() {
2862 if ( !$this->isItemLoaded( 'realname' ) ) {
2863 $this->load();
2864 }
2865
2866 return $this->mRealName;
2867 }
2868
2869 /**
2870 * Set the user's real name
2871 * @param string $str New real name
2872 */
2873 public function setRealName( $str ) {
2874 $this->load();
2875 $this->mRealName = $str;
2876 }
2877
2878 /**
2879 * Get the user's current setting for a given option.
2880 *
2881 * @param string $oname The option to check
2882 * @param string $defaultOverride A default value returned if the option does not exist
2883 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2884 * @return string|null User's current value for the option
2885 * @see getBoolOption()
2886 * @see getIntOption()
2887 */
2888 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2889 global $wgHiddenPrefs;
2890 $this->loadOptions();
2891
2892 # We want 'disabled' preferences to always behave as the default value for
2893 # users, even if they have set the option explicitly in their settings (ie they
2894 # set it, and then it was disabled removing their ability to change it). But
2895 # we don't want to erase the preferences in the database in case the preference
2896 # is re-enabled again. So don't touch $mOptions, just override the returned value
2897 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2898 return self::getDefaultOption( $oname );
2899 }
2900
2901 if ( array_key_exists( $oname, $this->mOptions ) ) {
2902 return $this->mOptions[$oname];
2903 } else {
2904 return $defaultOverride;
2905 }
2906 }
2907
2908 /**
2909 * Get all user's options
2910 *
2911 * @param int $flags Bitwise combination of:
2912 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2913 * to the default value. (Since 1.25)
2914 * @return array
2915 */
2916 public function getOptions( $flags = 0 ) {
2917 global $wgHiddenPrefs;
2918 $this->loadOptions();
2919 $options = $this->mOptions;
2920
2921 # We want 'disabled' preferences to always behave as the default value for
2922 # users, even if they have set the option explicitly in their settings (ie they
2923 # set it, and then it was disabled removing their ability to change it). But
2924 # we don't want to erase the preferences in the database in case the preference
2925 # is re-enabled again. So don't touch $mOptions, just override the returned value
2926 foreach ( $wgHiddenPrefs as $pref ) {
2927 $default = self::getDefaultOption( $pref );
2928 if ( $default !== null ) {
2929 $options[$pref] = $default;
2930 }
2931 }
2932
2933 if ( $flags & self::GETOPTIONS_EXCLUDE_DEFAULTS ) {
2934 $options = array_diff_assoc( $options, self::getDefaultOptions() );
2935 }
2936
2937 return $options;
2938 }
2939
2940 /**
2941 * Get the user's current setting for a given option, as a boolean value.
2942 *
2943 * @param string $oname The option to check
2944 * @return bool User's current value for the option
2945 * @see getOption()
2946 */
2947 public function getBoolOption( $oname ) {
2948 return (bool)$this->getOption( $oname );
2949 }
2950
2951 /**
2952 * Get the user's current setting for a given option, as an integer value.
2953 *
2954 * @param string $oname The option to check
2955 * @param int $defaultOverride A default value returned if the option does not exist
2956 * @return int User's current value for the option
2957 * @see getOption()
2958 */
2959 public function getIntOption( $oname, $defaultOverride = 0 ) {
2960 $val = $this->getOption( $oname );
2961 if ( $val == '' ) {
2962 $val = $defaultOverride;
2963 }
2964 return intval( $val );
2965 }
2966
2967 /**
2968 * Set the given option for a user.
2969 *
2970 * You need to call saveSettings() to actually write to the database.
2971 *
2972 * @param string $oname The option to set
2973 * @param mixed $val New value to set
2974 */
2975 public function setOption( $oname, $val ) {
2976 $this->loadOptions();
2977
2978 // Explicitly NULL values should refer to defaults
2979 if ( is_null( $val ) ) {
2980 $val = self::getDefaultOption( $oname );
2981 }
2982
2983 $this->mOptions[$oname] = $val;
2984 }
2985
2986 /**
2987 * Get a token stored in the preferences (like the watchlist one),
2988 * resetting it if it's empty (and saving changes).
2989 *
2990 * @param string $oname The option name to retrieve the token from
2991 * @return string|bool User's current value for the option, or false if this option is disabled.
2992 * @see resetTokenFromOption()
2993 * @see getOption()
2994 * @deprecated since 1.26 Applications should use the OAuth extension
2995 */
2996 public function getTokenFromOption( $oname ) {
2997 global $wgHiddenPrefs;
2998
2999 $id = $this->getId();
3000 if ( !$id || in_array( $oname, $wgHiddenPrefs ) ) {
3001 return false;
3002 }
3003
3004 $token = $this->getOption( $oname );
3005 if ( !$token ) {
3006 // Default to a value based on the user token to avoid space
3007 // wasted on storing tokens for all users. When this option
3008 // is set manually by the user, only then is it stored.
3009 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3010 }
3011
3012 return $token;
3013 }
3014
3015 /**
3016 * Reset a token stored in the preferences (like the watchlist one).
3017 * *Does not* save user's preferences (similarly to setOption()).
3018 *
3019 * @param string $oname The option name to reset the token in
3020 * @return string|bool New token value, or false if this option is disabled.
3021 * @see getTokenFromOption()
3022 * @see setOption()
3023 */
3024 public function resetTokenFromOption( $oname ) {
3025 global $wgHiddenPrefs;
3026 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3027 return false;
3028 }
3029
3030 $token = MWCryptRand::generateHex( 40 );
3031 $this->setOption( $oname, $token );
3032 return $token;
3033 }
3034
3035 /**
3036 * Return a list of the types of user options currently returned by
3037 * User::getOptionKinds().
3038 *
3039 * Currently, the option kinds are:
3040 * - 'registered' - preferences which are registered in core MediaWiki or
3041 * by extensions using the UserGetDefaultOptions hook.
3042 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3043 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3044 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3045 * be used by user scripts.
3046 * - 'special' - "preferences" that are not accessible via User::getOptions
3047 * or User::setOptions.
3048 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3049 * These are usually legacy options, removed in newer versions.
3050 *
3051 * The API (and possibly others) use this function to determine the possible
3052 * option types for validation purposes, so make sure to update this when a
3053 * new option kind is added.
3054 *
3055 * @see User::getOptionKinds
3056 * @return array Option kinds
3057 */
3058 public static function listOptionKinds() {
3059 return [
3060 'registered',
3061 'registered-multiselect',
3062 'registered-checkmatrix',
3063 'userjs',
3064 'special',
3065 'unused'
3066 ];
3067 }
3068
3069 /**
3070 * Return an associative array mapping preferences keys to the kind of a preference they're
3071 * used for. Different kinds are handled differently when setting or reading preferences.
3072 *
3073 * See User::listOptionKinds for the list of valid option types that can be provided.
3074 *
3075 * @see User::listOptionKinds
3076 * @param IContextSource $context
3077 * @param array $options Assoc. array with options keys to check as keys.
3078 * Defaults to $this->mOptions.
3079 * @return array The key => kind mapping data
3080 */
3081 public function getOptionKinds( IContextSource $context, $options = null ) {
3082 $this->loadOptions();
3083 if ( $options === null ) {
3084 $options = $this->mOptions;
3085 }
3086
3087 $preferencesFactory = MediaWikiServices::getInstance()->getPreferencesFactory();
3088 $prefs = $preferencesFactory->getFormDescriptor( $this, $context );
3089 $mapping = [];
3090
3091 // Pull out the "special" options, so they don't get converted as