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