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