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