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