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