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