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