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