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