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