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