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