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