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