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