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