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