Merge "maintenance: Cleanup db code and bogus RevisionRecord constants in NamespaceDupes"
[lhc/web/wiklou.git] / includes / installer / Installer.php
1 <?php
2 /**
3 * Base code for MediaWiki installer.
4 *
5 * DO NOT PATCH THIS FILE IF YOU NEED TO CHANGE INSTALLER BEHAVIOR IN YOUR PACKAGE!
6 * See mw-config/overrides/README for details.
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup Deployment
25 */
26
27 use MediaWiki\Interwiki\NullInterwikiLookup;
28 use MediaWiki\MediaWikiServices;
29 use MediaWiki\Shell\Shell;
30
31 /**
32 * This documentation group collects source code files with deployment functionality.
33 *
34 * @defgroup Deployment Deployment
35 */
36
37 /**
38 * Base installer class.
39 *
40 * This class provides the base for installation and update functionality
41 * for both MediaWiki core and extensions.
42 *
43 * @ingroup Deployment
44 * @since 1.17
45 */
46 abstract class Installer {
47
48 /**
49 * The oldest version of PCRE we can support.
50 *
51 * Defining this is necessary because PHP may be linked with a system version
52 * of PCRE, which may be older than that bundled with the minimum PHP version.
53 */
54 const MINIMUM_PCRE_VERSION = '7.2';
55
56 /**
57 * @var array
58 */
59 protected $settings;
60
61 /**
62 * List of detected DBs, access using getCompiledDBs().
63 *
64 * @var array
65 */
66 protected $compiledDBs;
67
68 /**
69 * Cached DB installer instances, access using getDBInstaller().
70 *
71 * @var array
72 */
73 protected $dbInstallers = [];
74
75 /**
76 * Minimum memory size in MB.
77 *
78 * @var int
79 */
80 protected $minMemorySize = 50;
81
82 /**
83 * Cached Title, used by parse().
84 *
85 * @var Title
86 */
87 protected $parserTitle;
88
89 /**
90 * Cached ParserOptions, used by parse().
91 *
92 * @var ParserOptions
93 */
94 protected $parserOptions;
95
96 /**
97 * Known database types. These correspond to the class names <type>Installer,
98 * and are also MediaWiki database types valid for $wgDBtype.
99 *
100 * To add a new type, create a <type>Installer class and a Database<type>
101 * class, and add a config-type-<type> message to MessagesEn.php.
102 *
103 * @var array
104 */
105 protected static $dbTypes = [
106 'mysql',
107 'postgres',
108 'sqlite',
109 ];
110
111 /**
112 * A list of environment check methods called by doEnvironmentChecks().
113 * These may output warnings using showMessage(), and/or abort the
114 * installation process by returning false.
115 *
116 * For the WebInstaller these are only called on the Welcome page,
117 * if these methods have side-effects that should affect later page loads
118 * (as well as the generated stylesheet), use envPreps instead.
119 *
120 * @var array
121 */
122 protected $envChecks = [
123 'envCheckDB',
124 'envCheckBrokenXML',
125 'envCheckPCRE',
126 'envCheckMemory',
127 'envCheckCache',
128 'envCheckModSecurity',
129 'envCheckDiff3',
130 'envCheckGraphics',
131 'envCheckGit',
132 'envCheckServer',
133 'envCheckPath',
134 'envCheckShellLocale',
135 'envCheckUploadsDirectory',
136 'envCheckLibicu',
137 'envCheckSuhosinMaxValueLength',
138 'envCheck64Bit',
139 ];
140
141 /**
142 * A list of environment preparation methods called by doEnvironmentPreps().
143 *
144 * @var array
145 */
146 protected $envPreps = [
147 'envPrepServer',
148 'envPrepPath',
149 ];
150
151 /**
152 * MediaWiki configuration globals that will eventually be passed through
153 * to LocalSettings.php. The names only are given here, the defaults
154 * typically come from DefaultSettings.php.
155 *
156 * @var array
157 */
158 protected $defaultVarNames = [
159 'wgSitename',
160 'wgPasswordSender',
161 'wgLanguageCode',
162 'wgRightsIcon',
163 'wgRightsText',
164 'wgRightsUrl',
165 'wgEnableEmail',
166 'wgEnableUserEmail',
167 'wgEnotifUserTalk',
168 'wgEnotifWatchlist',
169 'wgEmailAuthentication',
170 'wgDBname',
171 'wgDBtype',
172 'wgDiff3',
173 'wgImageMagickConvertCommand',
174 'wgGitBin',
175 'IP',
176 'wgScriptPath',
177 'wgMetaNamespace',
178 'wgDeletedDirectory',
179 'wgEnableUploads',
180 'wgShellLocale',
181 'wgSecretKey',
182 'wgUseInstantCommons',
183 'wgUpgradeKey',
184 'wgDefaultSkin',
185 'wgPingback',
186 ];
187
188 /**
189 * Variables that are stored alongside globals, and are used for any
190 * configuration of the installation process aside from the MediaWiki
191 * configuration. Map of names to defaults.
192 *
193 * @var array
194 */
195 protected $internalDefaults = [
196 '_UserLang' => 'en',
197 '_Environment' => false,
198 '_RaiseMemory' => false,
199 '_UpgradeDone' => false,
200 '_InstallDone' => false,
201 '_Caches' => [],
202 '_InstallPassword' => '',
203 '_SameAccount' => true,
204 '_CreateDBAccount' => false,
205 '_NamespaceType' => 'site-name',
206 '_AdminName' => '', // will be set later, when the user selects language
207 '_AdminPassword' => '',
208 '_AdminPasswordConfirm' => '',
209 '_AdminEmail' => '',
210 '_Subscribe' => false,
211 '_SkipOptional' => 'continue',
212 '_RightsProfile' => 'wiki',
213 '_LicenseCode' => 'none',
214 '_CCDone' => false,
215 '_Extensions' => [],
216 '_Skins' => [],
217 '_MemCachedServers' => '',
218 '_UpgradeKeySupplied' => false,
219 '_ExistingDBSettings' => false,
220
221 // $wgLogo is probably wrong (T50084); set something that will work.
222 // Single quotes work fine here, as LocalSettingsGenerator outputs this unescaped.
223 'wgLogo' => '$wgResourceBasePath/resources/assets/wiki.png',
224 'wgAuthenticationTokenVersion' => 1,
225 ];
226
227 /**
228 * The actual list of installation steps. This will be initialized by getInstallSteps()
229 *
230 * @var array
231 */
232 private $installSteps = [];
233
234 /**
235 * Extra steps for installation, for things like DatabaseInstallers to modify
236 *
237 * @var array
238 */
239 protected $extraInstallSteps = [];
240
241 /**
242 * Known object cache types and the functions used to test for their existence.
243 *
244 * @var array
245 */
246 protected $objectCaches = [
247 'apc' => 'apc_fetch',
248 'apcu' => 'apcu_fetch',
249 'wincache' => 'wincache_ucache_get'
250 ];
251
252 /**
253 * User rights profiles.
254 *
255 * @var array
256 */
257 public $rightsProfiles = [
258 'wiki' => [],
259 'no-anon' => [
260 '*' => [ 'edit' => false ]
261 ],
262 'fishbowl' => [
263 '*' => [
264 'createaccount' => false,
265 'edit' => false,
266 ],
267 ],
268 'private' => [
269 '*' => [
270 'createaccount' => false,
271 'edit' => false,
272 'read' => false,
273 ],
274 ],
275 ];
276
277 /**
278 * License types.
279 *
280 * @var array
281 */
282 public $licenses = [
283 'cc-by' => [
284 'url' => 'https://creativecommons.org/licenses/by/4.0/',
285 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by.png',
286 ],
287 'cc-by-sa' => [
288 'url' => 'https://creativecommons.org/licenses/by-sa/4.0/',
289 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-sa.png',
290 ],
291 'cc-by-nc-sa' => [
292 'url' => 'https://creativecommons.org/licenses/by-nc-sa/4.0/',
293 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-nc-sa.png',
294 ],
295 'cc-0' => [
296 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
297 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-0.png',
298 ],
299 'gfdl' => [
300 'url' => 'https://www.gnu.org/copyleft/fdl.html',
301 'icon' => '$wgResourceBasePath/resources/assets/licenses/gnu-fdl.png',
302 ],
303 'none' => [
304 'url' => '',
305 'icon' => '',
306 'text' => ''
307 ],
308 'cc-choose' => [
309 // Details will be filled in by the selector.
310 'url' => '',
311 'icon' => '',
312 'text' => '',
313 ],
314 ];
315
316 /**
317 * URL to mediawiki-announce subscription
318 */
319 protected $mediaWikiAnnounceUrl =
320 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
321
322 /**
323 * Supported language codes for Mailman
324 */
325 protected $mediaWikiAnnounceLanguages = [
326 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
327 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
328 'sl', 'sr', 'sv', 'tr', 'uk'
329 ];
330
331 /**
332 * UI interface for displaying a short message
333 * The parameters are like parameters to wfMessage().
334 * The messages will be in wikitext format, which will be converted to an
335 * output format such as HTML or text before being sent to the user.
336 * @param string $msg
337 * @param mixed ...$params
338 */
339 abstract public function showMessage( $msg, ...$params );
340
341 /**
342 * Same as showMessage(), but for displaying errors
343 * @param string $msg
344 * @param mixed ...$params
345 */
346 abstract public function showError( $msg, ...$params );
347
348 /**
349 * Show a message to the installing user by using a Status object
350 * @param Status $status
351 */
352 abstract public function showStatusMessage( Status $status );
353
354 /**
355 * Constructs a Config object that contains configuration settings that should be
356 * overwritten for the installation process.
357 *
358 * @since 1.27
359 *
360 * @param Config $baseConfig
361 *
362 * @return Config The config to use during installation.
363 */
364 public static function getInstallerConfig( Config $baseConfig ) {
365 $configOverrides = new HashConfig();
366
367 // disable (problematic) object cache types explicitly, preserving all other (working) ones
368 // bug T113843
369 $emptyCache = [ 'class' => EmptyBagOStuff::class ];
370
371 $objectCaches = [
372 CACHE_NONE => $emptyCache,
373 CACHE_DB => $emptyCache,
374 CACHE_ANYTHING => $emptyCache,
375 CACHE_MEMCACHED => $emptyCache,
376 ] + $baseConfig->get( 'ObjectCaches' );
377
378 $configOverrides->set( 'ObjectCaches', $objectCaches );
379
380 // Load the installer's i18n.
381 $messageDirs = $baseConfig->get( 'MessagesDirs' );
382 $messageDirs['MediawikiInstaller'] = __DIR__ . '/i18n';
383
384 $configOverrides->set( 'MessagesDirs', $messageDirs );
385
386 $installerConfig = new MultiConfig( [ $configOverrides, $baseConfig ] );
387
388 // make sure we use the installer config as the main config
389 $configRegistry = $baseConfig->get( 'ConfigRegistry' );
390 $configRegistry['main'] = function () use ( $installerConfig ) {
391 return $installerConfig;
392 };
393
394 $configOverrides->set( 'ConfigRegistry', $configRegistry );
395
396 return $installerConfig;
397 }
398
399 /**
400 * Constructor, always call this from child classes.
401 */
402 public function __construct() {
403 global $wgMemc, $wgUser, $wgObjectCaches;
404
405 $defaultConfig = new GlobalVarConfig(); // all the stuff from DefaultSettings.php
406 $installerConfig = self::getInstallerConfig( $defaultConfig );
407
408 // Reset all services and inject config overrides
409 MediaWikiServices::resetGlobalInstance( $installerConfig );
410
411 // Don't attempt to load user language options (T126177)
412 // This will be overridden in the web installer with the user-specified language
413 RequestContext::getMain()->setLanguage( 'en' );
414
415 // Disable all global services, since we don't have any configuration yet!
416 MediaWikiServices::disableStorageBackend();
417
418 $mwServices = MediaWikiServices::getInstance();
419
420 // Disable i18n cache
421 $mwServices->getLocalisationCache()->disableBackend();
422
423 // Clear language cache so the old i18n cache doesn't sneak back in
424 Language::clearCaches();
425
426 // Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
427 // SqlBagOStuff will then throw since we just disabled wfGetDB)
428 $wgObjectCaches = $mwServices->getMainConfig()->get( 'ObjectCaches' );
429 $wgMemc = ObjectCache::getInstance( CACHE_NONE );
430
431 // Disable interwiki lookup, to avoid database access during parses
432 $mwServices->redefineService( 'InterwikiLookup', function () {
433 return new NullInterwikiLookup();
434 } );
435
436 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
437 $wgUser = User::newFromId( 0 );
438 RequestContext::getMain()->setUser( $wgUser );
439
440 $this->settings = $this->internalDefaults;
441
442 foreach ( $this->defaultVarNames as $var ) {
443 $this->settings[$var] = $GLOBALS[$var];
444 }
445
446 $this->doEnvironmentPreps();
447
448 $this->compiledDBs = [];
449 foreach ( self::getDBTypes() as $type ) {
450 $installer = $this->getDBInstaller( $type );
451
452 if ( !$installer->isCompiled() ) {
453 continue;
454 }
455 $this->compiledDBs[] = $type;
456 }
457
458 $this->parserTitle = Title::newFromText( 'Installer' );
459 $this->parserOptions = new ParserOptions( $wgUser ); // language will be wrong :(
460 $this->parserOptions->setTidy( true );
461 // Don't try to access DB before user language is initialised
462 $this->setParserLanguage( Language::factory( 'en' ) );
463 }
464
465 /**
466 * Get a list of known DB types.
467 *
468 * @return array
469 */
470 public static function getDBTypes() {
471 return self::$dbTypes;
472 }
473
474 /**
475 * Do initial checks of the PHP environment. Set variables according to
476 * the observed environment.
477 *
478 * It's possible that this may be called under the CLI SAPI, not the SAPI
479 * that the wiki will primarily run under. In that case, the subclass should
480 * initialise variables such as wgScriptPath, before calling this function.
481 *
482 * Under the web subclass, it can already be assumed that PHP 5+ is in use
483 * and that sessions are working.
484 *
485 * @return Status
486 */
487 public function doEnvironmentChecks() {
488 // Php version has already been checked by entry scripts
489 // Show message here for information purposes
490 if ( wfIsHHVM() ) {
491 $this->showMessage( 'config-env-hhvm', HHVM_VERSION );
492 } else {
493 $this->showMessage( 'config-env-php', PHP_VERSION );
494 }
495
496 $good = true;
497 // Must go here because an old version of PCRE can prevent other checks from completing
498 $pcreVersion = explode( ' ', PCRE_VERSION, 2 )[0];
499 if ( version_compare( $pcreVersion, self::MINIMUM_PCRE_VERSION, '<' ) ) {
500 $this->showError( 'config-pcre-old', self::MINIMUM_PCRE_VERSION, $pcreVersion );
501 $good = false;
502 } else {
503 foreach ( $this->envChecks as $check ) {
504 $status = $this->$check();
505 if ( $status === false ) {
506 $good = false;
507 }
508 }
509 }
510
511 $this->setVar( '_Environment', $good );
512
513 return $good ? Status::newGood() : Status::newFatal( 'config-env-bad' );
514 }
515
516 public function doEnvironmentPreps() {
517 foreach ( $this->envPreps as $prep ) {
518 $this->$prep();
519 }
520 }
521
522 /**
523 * Set a MW configuration variable, or internal installer configuration variable.
524 *
525 * @param string $name
526 * @param mixed $value
527 */
528 public function setVar( $name, $value ) {
529 $this->settings[$name] = $value;
530 }
531
532 /**
533 * Get an MW configuration variable, or internal installer configuration variable.
534 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
535 * Installer variables are typically prefixed by an underscore.
536 *
537 * @param string $name
538 * @param mixed|null $default
539 *
540 * @return mixed
541 */
542 public function getVar( $name, $default = null ) {
543 return $this->settings[$name] ?? $default;
544 }
545
546 /**
547 * Get a list of DBs supported by current PHP setup
548 *
549 * @return array
550 */
551 public function getCompiledDBs() {
552 return $this->compiledDBs;
553 }
554
555 /**
556 * Get the DatabaseInstaller class name for this type
557 *
558 * @param string $type database type ($wgDBtype)
559 * @return string Class name
560 * @since 1.30
561 */
562 public static function getDBInstallerClass( $type ) {
563 return ucfirst( $type ) . 'Installer';
564 }
565
566 /**
567 * Get an instance of DatabaseInstaller for the specified DB type.
568 *
569 * @param mixed $type DB installer for which is needed, false to use default.
570 *
571 * @return DatabaseInstaller
572 */
573 public function getDBInstaller( $type = false ) {
574 if ( !$type ) {
575 $type = $this->getVar( 'wgDBtype' );
576 }
577
578 $type = strtolower( $type );
579
580 if ( !isset( $this->dbInstallers[$type] ) ) {
581 $class = self::getDBInstallerClass( $type );
582 $this->dbInstallers[$type] = new $class( $this );
583 }
584
585 return $this->dbInstallers[$type];
586 }
587
588 /**
589 * Determine if LocalSettings.php exists. If it does, return its variables.
590 *
591 * @return array|false
592 */
593 public static function getExistingLocalSettings() {
594 global $IP;
595
596 // You might be wondering why this is here. Well if you don't do this
597 // then some poorly-formed extensions try to call their own classes
598 // after immediately registering them. We really need to get extension
599 // registration out of the global scope and into a real format.
600 // @see https://phabricator.wikimedia.org/T69440
601 global $wgAutoloadClasses;
602 $wgAutoloadClasses = [];
603
604 // LocalSettings.php should not call functions, except wfLoadSkin/wfLoadExtensions
605 // Define the required globals here, to ensure, the functions can do it work correctly.
606 // phpcs:ignore MediaWiki.VariableAnalysis.UnusedGlobalVariables
607 global $wgExtensionDirectory, $wgStyleDirectory;
608
609 Wikimedia\suppressWarnings();
610 $_lsExists = file_exists( "$IP/LocalSettings.php" );
611 Wikimedia\restoreWarnings();
612
613 if ( !$_lsExists ) {
614 return false;
615 }
616 unset( $_lsExists );
617
618 require "$IP/includes/DefaultSettings.php";
619 require "$IP/LocalSettings.php";
620
621 return get_defined_vars();
622 }
623
624 /**
625 * Get a fake password for sending back to the user in HTML.
626 * This is a security mechanism to avoid compromise of the password in the
627 * event of session ID compromise.
628 *
629 * @param string $realPassword
630 *
631 * @return string
632 */
633 public function getFakePassword( $realPassword ) {
634 return str_repeat( '*', strlen( $realPassword ) );
635 }
636
637 /**
638 * Set a variable which stores a password, except if the new value is a
639 * fake password in which case leave it as it is.
640 *
641 * @param string $name
642 * @param mixed $value
643 */
644 public function setPassword( $name, $value ) {
645 if ( !preg_match( '/^\*+$/', $value ) ) {
646 $this->setVar( $name, $value );
647 }
648 }
649
650 /**
651 * On POSIX systems return the primary group of the webserver we're running under.
652 * On other systems just returns null.
653 *
654 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
655 * webserver user before he can install.
656 *
657 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
658 *
659 * @return mixed
660 */
661 public static function maybeGetWebserverPrimaryGroup() {
662 if ( !function_exists( 'posix_getegid' ) || !function_exists( 'posix_getpwuid' ) ) {
663 # I don't know this, this isn't UNIX.
664 return null;
665 }
666
667 # posix_getegid() *not* getmygid() because we want the group of the webserver,
668 # not whoever owns the current script.
669 $gid = posix_getegid();
670 $group = posix_getpwuid( $gid )['name'];
671
672 return $group;
673 }
674
675 /**
676 * Convert wikitext $text to HTML.
677 *
678 * This is potentially error prone since many parser features require a complete
679 * installed MW database. The solution is to just not use those features when you
680 * write your messages. This appears to work well enough. Basic formatting and
681 * external links work just fine.
682 *
683 * But in case a translator decides to throw in a "#ifexist" or internal link or
684 * whatever, this function is guarded to catch the attempted DB access and to present
685 * some fallback text.
686 *
687 * @param string $text
688 * @param bool $lineStart
689 * @return string
690 */
691 public function parse( $text, $lineStart = false ) {
692 $parser = MediaWikiServices::getInstance()->getParser();
693
694 try {
695 $out = $parser->parse( $text, $this->parserTitle, $this->parserOptions, $lineStart );
696 $html = $out->getText( [
697 'enableSectionEditLinks' => false,
698 'unwrap' => true,
699 ] );
700 $html = Parser::stripOuterParagraph( $html );
701 } catch ( Wikimedia\Services\ServiceDisabledException $e ) {
702 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
703 }
704
705 return $html;
706 }
707
708 /**
709 * @return ParserOptions
710 */
711 public function getParserOptions() {
712 return $this->parserOptions;
713 }
714
715 public function disableLinkPopups() {
716 $this->parserOptions->setExternalLinkTarget( false );
717 }
718
719 public function restoreLinkPopups() {
720 global $wgExternalLinkTarget;
721 $this->parserOptions->setExternalLinkTarget( $wgExternalLinkTarget );
722 }
723
724 /**
725 * Install step which adds a row to the site_stats table with appropriate
726 * initial values.
727 *
728 * @param DatabaseInstaller $installer
729 *
730 * @return Status
731 */
732 public function populateSiteStats( DatabaseInstaller $installer ) {
733 $status = $installer->getConnection();
734 if ( !$status->isOK() ) {
735 return $status;
736 }
737 $status->value->insert(
738 'site_stats',
739 [
740 'ss_row_id' => 1,
741 'ss_total_edits' => 0,
742 'ss_good_articles' => 0,
743 'ss_total_pages' => 0,
744 'ss_users' => 0,
745 'ss_active_users' => 0,
746 'ss_images' => 0
747 ],
748 __METHOD__, 'IGNORE'
749 );
750
751 return Status::newGood();
752 }
753
754 /**
755 * Environment check for DB types.
756 * @return bool
757 */
758 protected function envCheckDB() {
759 global $wgLang;
760 /** @var string|null $dbType The user-specified database type */
761 $dbType = $this->getVar( 'wgDBtype' );
762
763 $allNames = [];
764
765 // Messages: config-type-mysql, config-type-postgres, config-type-sqlite
766 foreach ( self::getDBTypes() as $name ) {
767 $allNames[] = wfMessage( "config-type-$name" )->text();
768 }
769
770 $databases = $this->getCompiledDBs();
771
772 $databases = array_flip( $databases );
773 $ok = true;
774 foreach ( array_keys( $databases ) as $db ) {
775 $installer = $this->getDBInstaller( $db );
776 $status = $installer->checkPrerequisites();
777 if ( !$status->isGood() ) {
778 if ( !$this instanceof WebInstaller && $db === $dbType ) {
779 // Strictly check the key database type instead of just outputting message
780 // Note: No perform this check run from the web installer, since this method always called by
781 // the welcome page under web installation, so $dbType will always be 'mysql'
782 $ok = false;
783 }
784 $this->showStatusMessage( $status );
785 unset( $databases[$db] );
786 }
787 }
788 $databases = array_flip( $databases );
789 if ( !$databases ) {
790 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
791 return false;
792 }
793 return $ok;
794 }
795
796 /**
797 * Some versions of libxml+PHP break < and > encoding horribly
798 * @return bool
799 */
800 protected function envCheckBrokenXML() {
801 $test = new PhpXmlBugTester();
802 if ( !$test->ok ) {
803 $this->showError( 'config-brokenlibxml' );
804
805 return false;
806 }
807
808 return true;
809 }
810
811 /**
812 * Environment check for the PCRE module.
813 *
814 * @note If this check were to fail, the parser would
815 * probably throw an exception before the result
816 * of this check is shown to the user.
817 * @return bool
818 */
819 protected function envCheckPCRE() {
820 Wikimedia\suppressWarnings();
821 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
822 // Need to check for \p support too, as PCRE can be compiled
823 // with utf8 support, but not unicode property support.
824 // check that \p{Zs} (space separators) matches
825 // U+3000 (Ideographic space)
826 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\u{3000}-" );
827 Wikimedia\restoreWarnings();
828 if ( $regexd != '--' || $regexprop != '--' ) {
829 $this->showError( 'config-pcre-no-utf8' );
830
831 return false;
832 }
833
834 return true;
835 }
836
837 /**
838 * Environment check for available memory.
839 * @return bool
840 */
841 protected function envCheckMemory() {
842 $limit = ini_get( 'memory_limit' );
843
844 if ( !$limit || $limit == -1 ) {
845 return true;
846 }
847
848 $n = wfShorthandToInteger( $limit );
849
850 if ( $n < $this->minMemorySize * 1024 * 1024 ) {
851 $newLimit = "{$this->minMemorySize}M";
852
853 if ( ini_set( "memory_limit", $newLimit ) === false ) {
854 $this->showMessage( 'config-memory-bad', $limit );
855 } else {
856 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
857 $this->setVar( '_RaiseMemory', true );
858 }
859 }
860
861 return true;
862 }
863
864 /**
865 * Environment check for compiled object cache types.
866 */
867 protected function envCheckCache() {
868 $caches = [];
869 foreach ( $this->objectCaches as $name => $function ) {
870 if ( function_exists( $function ) ) {
871 $caches[$name] = true;
872 }
873 }
874
875 if ( !$caches ) {
876 $this->showMessage( 'config-no-cache-apcu' );
877 }
878
879 $this->setVar( '_Caches', $caches );
880 }
881
882 /**
883 * Scare user to death if they have mod_security or mod_security2
884 * @return bool
885 */
886 protected function envCheckModSecurity() {
887 if ( self::apacheModulePresent( 'mod_security' )
888 || self::apacheModulePresent( 'mod_security2' ) ) {
889 $this->showMessage( 'config-mod-security' );
890 }
891
892 return true;
893 }
894
895 /**
896 * Search for GNU diff3.
897 * @return bool
898 */
899 protected function envCheckDiff3() {
900 $names = [ "gdiff3", "diff3" ];
901 if ( wfIsWindows() ) {
902 $names[] = 'diff3.exe';
903 }
904 $versionInfo = [ '--version', 'GNU diffutils' ];
905
906 $diff3 = ExecutableFinder::findInDefaultPaths( $names, $versionInfo );
907
908 if ( $diff3 ) {
909 $this->setVar( 'wgDiff3', $diff3 );
910 } else {
911 $this->setVar( 'wgDiff3', false );
912 $this->showMessage( 'config-diff3-bad' );
913 }
914
915 return true;
916 }
917
918 /**
919 * Environment check for ImageMagick and GD.
920 * @return bool
921 */
922 protected function envCheckGraphics() {
923 $names = wfIsWindows() ? 'convert.exe' : 'convert';
924 $versionInfo = [ '-version', 'ImageMagick' ];
925 $convert = ExecutableFinder::findInDefaultPaths( $names, $versionInfo );
926
927 $this->setVar( 'wgImageMagickConvertCommand', '' );
928 if ( $convert ) {
929 $this->setVar( 'wgImageMagickConvertCommand', $convert );
930 $this->showMessage( 'config-imagemagick', $convert );
931
932 return true;
933 } elseif ( function_exists( 'imagejpeg' ) ) {
934 $this->showMessage( 'config-gd' );
935 } else {
936 $this->showMessage( 'config-no-scaling' );
937 }
938
939 return true;
940 }
941
942 /**
943 * Search for git.
944 *
945 * @since 1.22
946 * @return bool
947 */
948 protected function envCheckGit() {
949 $names = wfIsWindows() ? 'git.exe' : 'git';
950 $versionInfo = [ '--version', 'git version' ];
951
952 $git = ExecutableFinder::findInDefaultPaths( $names, $versionInfo );
953
954 if ( $git ) {
955 $this->setVar( 'wgGitBin', $git );
956 $this->showMessage( 'config-git', $git );
957 } else {
958 $this->setVar( 'wgGitBin', false );
959 $this->showMessage( 'config-git-bad' );
960 }
961
962 return true;
963 }
964
965 /**
966 * Environment check to inform user which server we've assumed.
967 *
968 * @return bool
969 */
970 protected function envCheckServer() {
971 $server = $this->envGetDefaultServer();
972 if ( $server !== null ) {
973 $this->showMessage( 'config-using-server', $server );
974 }
975 return true;
976 }
977
978 /**
979 * Environment check to inform user which paths we've assumed.
980 *
981 * @return bool
982 */
983 protected function envCheckPath() {
984 $this->showMessage(
985 'config-using-uri',
986 $this->getVar( 'wgServer' ),
987 $this->getVar( 'wgScriptPath' )
988 );
989 return true;
990 }
991
992 /**
993 * Environment check for preferred locale in shell
994 * @return bool
995 */
996 protected function envCheckShellLocale() {
997 $os = php_uname( 's' );
998 $supported = [ 'Linux', 'SunOS', 'HP-UX', 'Darwin' ]; # Tested these
999
1000 if ( !in_array( $os, $supported ) ) {
1001 return true;
1002 }
1003
1004 if ( Shell::isDisabled() ) {
1005 return true;
1006 }
1007
1008 # Get a list of available locales.
1009 $result = Shell::command( '/usr/bin/locale', '-a' )
1010 ->execute();
1011
1012 if ( $result->getExitCode() != 0 ) {
1013 return true;
1014 }
1015
1016 $lines = $result->getStdout();
1017 $lines = array_map( 'trim', explode( "\n", $lines ) );
1018 $candidatesByLocale = [];
1019 $candidatesByLang = [];
1020 foreach ( $lines as $line ) {
1021 if ( $line === '' ) {
1022 continue;
1023 }
1024
1025 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1026 continue;
1027 }
1028
1029 list( , $lang, , , ) = $m;
1030
1031 $candidatesByLocale[$m[0]] = $m;
1032 $candidatesByLang[$lang][] = $m;
1033 }
1034
1035 # Try the current value of LANG.
1036 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1037 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1038
1039 return true;
1040 }
1041
1042 # Try the most common ones.
1043 $commonLocales = [ 'C.UTF-8', 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' ];
1044 foreach ( $commonLocales as $commonLocale ) {
1045 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1046 $this->setVar( 'wgShellLocale', $commonLocale );
1047
1048 return true;
1049 }
1050 }
1051
1052 # Is there an available locale in the Wiki's language?
1053 $wikiLang = $this->getVar( 'wgLanguageCode' );
1054
1055 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1056 $m = reset( $candidatesByLang[$wikiLang] );
1057 $this->setVar( 'wgShellLocale', $m[0] );
1058
1059 return true;
1060 }
1061
1062 # Are there any at all?
1063 if ( count( $candidatesByLocale ) ) {
1064 $m = reset( $candidatesByLocale );
1065 $this->setVar( 'wgShellLocale', $m[0] );
1066
1067 return true;
1068 }
1069
1070 # Give up.
1071 return true;
1072 }
1073
1074 /**
1075 * Environment check for the permissions of the uploads directory
1076 * @return bool
1077 */
1078 protected function envCheckUploadsDirectory() {
1079 global $IP;
1080
1081 $dir = $IP . '/images/';
1082 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1083 $safe = !$this->dirIsExecutable( $dir, $url );
1084
1085 if ( !$safe ) {
1086 $this->showMessage( 'config-uploads-not-safe', $dir );
1087 }
1088
1089 return true;
1090 }
1091
1092 /**
1093 * Checks if suhosin.get.max_value_length is set, and if so generate
1094 * a warning because it decreases ResourceLoader performance.
1095 * @return bool
1096 */
1097 protected function envCheckSuhosinMaxValueLength() {
1098 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1099 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1100 // Only warn if the value is below the sane 1024
1101 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1102 }
1103
1104 return true;
1105 }
1106
1107 /**
1108 * Checks if we're running on 64 bit or not. 32 bit is becoming increasingly
1109 * hard to support, so let's at least warn people.
1110 *
1111 * @return bool
1112 */
1113 protected function envCheck64Bit() {
1114 if ( PHP_INT_SIZE == 4 ) {
1115 $this->showMessage( 'config-using-32bit' );
1116 }
1117
1118 return true;
1119 }
1120
1121 /**
1122 * Check the libicu version
1123 */
1124 protected function envCheckLibicu() {
1125 /**
1126 * This needs to be updated something that the latest libicu
1127 * will properly normalize. This normalization was found at
1128 * https://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1129 * Note that we use the hex representation to create the code
1130 * points in order to avoid any Unicode-destroying during transit.
1131 */
1132 $not_normal_c = "\u{FA6C}";
1133 $normal_c = "\u{242EE}";
1134
1135 $useNormalizer = 'php';
1136 $needsUpdate = false;
1137
1138 if ( function_exists( 'normalizer_normalize' ) ) {
1139 $useNormalizer = 'intl';
1140 $intl = normalizer_normalize( $not_normal_c, Normalizer::FORM_C );
1141 if ( $intl !== $normal_c ) {
1142 $needsUpdate = true;
1143 }
1144 }
1145
1146 // Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
1147 if ( $useNormalizer === 'php' ) {
1148 $this->showMessage( 'config-unicode-pure-php-warning' );
1149 } else {
1150 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1151 if ( $needsUpdate ) {
1152 $this->showMessage( 'config-unicode-update-warning' );
1153 }
1154 }
1155 }
1156
1157 /**
1158 * Environment prep for the server hostname.
1159 */
1160 protected function envPrepServer() {
1161 $server = $this->envGetDefaultServer();
1162 if ( $server !== null ) {
1163 $this->setVar( 'wgServer', $server );
1164 }
1165 }
1166
1167 /**
1168 * Helper function to be called from envPrepServer()
1169 * @return string
1170 */
1171 abstract protected function envGetDefaultServer();
1172
1173 /**
1174 * Environment prep for setting $IP and $wgScriptPath.
1175 */
1176 protected function envPrepPath() {
1177 global $IP;
1178 $IP = dirname( dirname( __DIR__ ) );
1179 $this->setVar( 'IP', $IP );
1180 }
1181
1182 /**
1183 * Checks if scripts located in the given directory can be executed via the given URL.
1184 *
1185 * Used only by environment checks.
1186 * @param string $dir
1187 * @param string $url
1188 * @return bool|int|string
1189 */
1190 public function dirIsExecutable( $dir, $url ) {
1191 $scriptTypes = [
1192 'php' => [
1193 "<?php echo 'exec';",
1194 "#!/var/env php\n<?php echo 'exec';",
1195 ],
1196 ];
1197
1198 // it would be good to check other popular languages here, but it'll be slow.
1199
1200 Wikimedia\suppressWarnings();
1201
1202 foreach ( $scriptTypes as $ext => $contents ) {
1203 foreach ( $contents as $source ) {
1204 $file = 'exectest.' . $ext;
1205
1206 if ( !file_put_contents( $dir . $file, $source ) ) {
1207 break;
1208 }
1209
1210 try {
1211 $text = MediaWikiServices::getInstance()->getHttpRequestFactory()->
1212 get( $url . $file, [ 'timeout' => 3 ], __METHOD__ );
1213 } catch ( Exception $e ) {
1214 // HttpRequestFactory::get can throw with allow_url_fopen = false and no curl
1215 // extension.
1216 $text = null;
1217 }
1218 unlink( $dir . $file );
1219
1220 if ( $text == 'exec' ) {
1221 Wikimedia\restoreWarnings();
1222
1223 return $ext;
1224 }
1225 }
1226 }
1227
1228 Wikimedia\restoreWarnings();
1229
1230 return false;
1231 }
1232
1233 /**
1234 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1235 *
1236 * @param string $moduleName Name of module to check.
1237 * @return bool
1238 */
1239 public static function apacheModulePresent( $moduleName ) {
1240 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1241 return true;
1242 }
1243 // try it the hard way
1244 ob_start();
1245 phpinfo( INFO_MODULES );
1246 $info = ob_get_clean();
1247
1248 return strpos( $info, $moduleName ) !== false;
1249 }
1250
1251 /**
1252 * ParserOptions are constructed before we determined the language, so fix it
1253 *
1254 * @param Language $lang
1255 */
1256 public function setParserLanguage( $lang ) {
1257 $this->parserOptions->setTargetLanguage( $lang );
1258 $this->parserOptions->setUserLang( $lang );
1259 }
1260
1261 /**
1262 * Overridden by WebInstaller to provide lastPage parameters.
1263 * @param string $page
1264 * @return string
1265 */
1266 protected function getDocUrl( $page ) {
1267 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1268 }
1269
1270 /**
1271 * Find extensions or skins in a subdirectory of $IP.
1272 * Returns an array containing the value for 'Name' for each found extension.
1273 *
1274 * @param string $directory Directory to search in, relative to $IP, must be either "extensions"
1275 * or "skins"
1276 * @return array [ $extName => [ 'screenshots' => [ '...' ] ]
1277 */
1278 public function findExtensions( $directory = 'extensions' ) {
1279 switch ( $directory ) {
1280 case 'extensions':
1281 return $this->findExtensionsByType( 'extension', 'extensions' );
1282 case 'skins':
1283 return $this->findExtensionsByType( 'skin', 'skins' );
1284 default:
1285 throw new InvalidArgumentException( "Invalid extension type" );
1286 }
1287 }
1288
1289 /**
1290 * Find extensions or skins, and return an array containing the value for 'Name' for each found
1291 * extension.
1292 *
1293 * @param string $type Either "extension" or "skin"
1294 * @param string $directory Directory to search in, relative to $IP
1295 * @return array [ $extName => [ 'screenshots' => [ '...' ] ]
1296 */
1297 protected function findExtensionsByType( $type = 'extension', $directory = 'extensions' ) {
1298 if ( $this->getVar( 'IP' ) === null ) {
1299 return [];
1300 }
1301
1302 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1303 if ( !is_readable( $extDir ) || !is_dir( $extDir ) ) {
1304 return [];
1305 }
1306
1307 $dh = opendir( $extDir );
1308 $exts = [];
1309 while ( ( $file = readdir( $dh ) ) !== false ) {
1310 if ( !is_dir( "$extDir/$file" ) ) {
1311 continue;
1312 }
1313 $status = $this->getExtensionInfo( $type, $directory, $file );
1314 if ( $status->isOK() ) {
1315 $exts[$file] = $status->value;
1316 }
1317 }
1318 closedir( $dh );
1319 uksort( $exts, 'strnatcasecmp' );
1320
1321 return $exts;
1322 }
1323
1324 /**
1325 * @param string $type Either "extension" or "skin"
1326 * @param string $parentRelPath The parent directory relative to $IP
1327 * @param string $name The extension or skin name
1328 * @return Status An object containing an error list. If there were no errors, an associative
1329 * array of information about the extension can be found in $status->value.
1330 */
1331 protected function getExtensionInfo( $type, $parentRelPath, $name ) {
1332 if ( $this->getVar( 'IP' ) === null ) {
1333 throw new Exception( 'Cannot find extensions since the IP variable is not yet set' );
1334 }
1335 if ( $type !== 'extension' && $type !== 'skin' ) {
1336 throw new InvalidArgumentException( "Invalid extension type" );
1337 }
1338 $absDir = $this->getVar( 'IP' ) . "/$parentRelPath/$name";
1339 $relDir = "../$parentRelPath/$name";
1340 if ( !is_dir( $absDir ) ) {
1341 return Status::newFatal( 'config-extension-not-found', $name );
1342 }
1343 $jsonFile = $type . '.json';
1344 $fullJsonFile = "$absDir/$jsonFile";
1345 $isJson = file_exists( $fullJsonFile );
1346 $isPhp = false;
1347 if ( !$isJson ) {
1348 // Only fallback to PHP file if JSON doesn't exist
1349 $fullPhpFile = "$absDir/$name.php";
1350 $isPhp = file_exists( $fullPhpFile );
1351 }
1352 if ( !$isJson && !$isPhp ) {
1353 return Status::newFatal( 'config-extension-not-found', $name );
1354 }
1355
1356 // Extension exists. Now see if there are screenshots
1357 $info = [];
1358 if ( is_dir( "$absDir/screenshots" ) ) {
1359 $paths = glob( "$absDir/screenshots/*.png" );
1360 foreach ( $paths as $path ) {
1361 $info['screenshots'][] = str_replace( $absDir, $relDir, $path );
1362 }
1363 }
1364
1365 if ( $isJson ) {
1366 $jsonStatus = $this->readExtension( $fullJsonFile );
1367 if ( !$jsonStatus->isOK() ) {
1368 return $jsonStatus;
1369 }
1370 $info += $jsonStatus->value;
1371 }
1372
1373 return Status::newGood( $info );
1374 }
1375
1376 /**
1377 * @param string $fullJsonFile
1378 * @param array $extDeps
1379 * @param array $skinDeps
1380 *
1381 * @return Status On success, an array of extension information is in $status->value. On
1382 * failure, the Status object will have an error list.
1383 */
1384 private function readExtension( $fullJsonFile, $extDeps = [], $skinDeps = [] ) {
1385 $load = [
1386 $fullJsonFile => 1
1387 ];
1388 if ( $extDeps ) {
1389 $extDir = $this->getVar( 'IP' ) . '/extensions';
1390 foreach ( $extDeps as $dep ) {
1391 $fname = "$extDir/$dep/extension.json";
1392 if ( !file_exists( $fname ) ) {
1393 return Status::newFatal( 'config-extension-not-found', $dep );
1394 }
1395 $load[$fname] = 1;
1396 }
1397 }
1398 if ( $skinDeps ) {
1399 $skinDir = $this->getVar( 'IP' ) . '/skins';
1400 foreach ( $skinDeps as $dep ) {
1401 $fname = "$skinDir/$dep/skin.json";
1402 if ( !file_exists( $fname ) ) {
1403 return Status::newFatal( 'config-extension-not-found', $dep );
1404 }
1405 $load[$fname] = 1;
1406 }
1407 }
1408 $registry = new ExtensionRegistry();
1409 try {
1410 $info = $registry->readFromQueue( $load );
1411 } catch ( ExtensionDependencyError $e ) {
1412 if ( $e->incompatibleCore || $e->incompatibleSkins
1413 || $e->incompatibleExtensions
1414 ) {
1415 // If something is incompatible with a dependency, we have no real
1416 // option besides skipping it
1417 return Status::newFatal( 'config-extension-dependency',
1418 basename( dirname( $fullJsonFile ) ), $e->getMessage() );
1419 } elseif ( $e->missingExtensions || $e->missingSkins ) {
1420 // There's an extension missing in the dependency tree,
1421 // so add those to the dependency list and try again
1422 return $this->readExtension(
1423 $fullJsonFile,
1424 array_merge( $extDeps, $e->missingExtensions ),
1425 array_merge( $skinDeps, $e->missingSkins )
1426 );
1427 }
1428 // Some other kind of dependency error?
1429 return Status::newFatal( 'config-extension-dependency',
1430 basename( dirname( $fullJsonFile ) ), $e->getMessage() );
1431 }
1432 $ret = [];
1433 // The order of credits will be the order of $load,
1434 // so the first extension is the one we want to load,
1435 // everything else is a dependency
1436 $i = 0;
1437 foreach ( $info['credits'] as $name => $credit ) {
1438 $i++;
1439 if ( $i == 1 ) {
1440 // Extension we want to load
1441 continue;
1442 }
1443 $type = basename( $credit['path'] ) === 'skin.json' ? 'skins' : 'extensions';
1444 $ret['requires'][$type][] = $credit['name'];
1445 }
1446 $credits = array_values( $info['credits'] )[0];
1447 if ( isset( $credits['url'] ) ) {
1448 $ret['url'] = $credits['url'];
1449 }
1450 $ret['type'] = $credits['type'];
1451
1452 return Status::newGood( $ret );
1453 }
1454
1455 /**
1456 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1457 * but will fall back to another if the default skin is missing and some other one is present
1458 * instead.
1459 *
1460 * @param string[] $skinNames Names of installed skins.
1461 * @return string
1462 */
1463 public function getDefaultSkin( array $skinNames ) {
1464 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1465 if ( !$skinNames || in_array( $defaultSkin, $skinNames ) ) {
1466 return $defaultSkin;
1467 } else {
1468 return $skinNames[0];
1469 }
1470 }
1471
1472 /**
1473 * Installs the auto-detected extensions.
1474 *
1475 * @suppress SecurityCheck-OTHER It thinks $exts/$IP is user controlled but they are not.
1476 * @return Status
1477 */
1478 protected function includeExtensions() {
1479 global $IP;
1480 $exts = $this->getVar( '_Extensions' );
1481 $IP = $this->getVar( 'IP' );
1482
1483 // Marker for DatabaseUpdater::loadExtensions so we don't
1484 // double load extensions
1485 define( 'MW_EXTENSIONS_LOADED', true );
1486
1487 /**
1488 * We need to include DefaultSettings before including extensions to avoid
1489 * warnings about unset variables. However, the only thing we really
1490 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1491 * if the extension has hidden hook registration in $wgExtensionFunctions,
1492 * but we're not opening that can of worms
1493 * @see https://phabricator.wikimedia.org/T28857
1494 */
1495 global $wgAutoloadClasses;
1496 $wgAutoloadClasses = [];
1497 $queue = [];
1498
1499 require "$IP/includes/DefaultSettings.php";
1500
1501 foreach ( $exts as $e ) {
1502 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1503 $queue["$IP/extensions/$e/extension.json"] = 1;
1504 } else {
1505 require_once "$IP/extensions/$e/$e.php";
1506 }
1507 }
1508
1509 $registry = new ExtensionRegistry();
1510 $data = $registry->readFromQueue( $queue );
1511 $wgAutoloadClasses += $data['autoload'];
1512
1513 // @phan-suppress-next-line PhanUndeclaredVariable $wgHooks is set by DefaultSettings
1514 $hooksWeWant = $wgHooks['LoadExtensionSchemaUpdates'] ?? [];
1515
1516 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1517 $hooksWeWant = array_merge_recursive(
1518 $hooksWeWant,
1519 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1520 );
1521 }
1522 // Unset everyone else's hooks. Lord knows what someone might be doing
1523 // in ParserFirstCallInit (see T29171)
1524 $GLOBALS['wgHooks'] = [ 'LoadExtensionSchemaUpdates' => $hooksWeWant ];
1525
1526 return Status::newGood();
1527 }
1528
1529 /**
1530 * Get an array of install steps. Should always be in the format of
1531 * [
1532 * 'name' => 'someuniquename',
1533 * 'callback' => [ $obj, 'method' ],
1534 * ]
1535 * There must be a config-install-$name message defined per step, which will
1536 * be shown on install.
1537 *
1538 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1539 * @return array
1540 */
1541 protected function getInstallSteps( DatabaseInstaller $installer ) {
1542 $coreInstallSteps = [
1543 [ 'name' => 'database', 'callback' => [ $installer, 'setupDatabase' ] ],
1544 [ 'name' => 'tables', 'callback' => [ $installer, 'createTables' ] ],
1545 [ 'name' => 'interwiki', 'callback' => [ $installer, 'populateInterwikiTable' ] ],
1546 [ 'name' => 'stats', 'callback' => [ $this, 'populateSiteStats' ] ],
1547 [ 'name' => 'keys', 'callback' => [ $this, 'generateKeys' ] ],
1548 [ 'name' => 'updates', 'callback' => [ $installer, 'insertUpdateKeys' ] ],
1549 [ 'name' => 'sysop', 'callback' => [ $this, 'createSysop' ] ],
1550 [ 'name' => 'mainpage', 'callback' => [ $this, 'createMainpage' ] ],
1551 ];
1552
1553 // Build the array of install steps starting from the core install list,
1554 // then adding any callbacks that wanted to attach after a given step
1555 foreach ( $coreInstallSteps as $step ) {
1556 $this->installSteps[] = $step;
1557 if ( isset( $this->extraInstallSteps[$step['name']] ) ) {
1558 $this->installSteps = array_merge(
1559 $this->installSteps,
1560 $this->extraInstallSteps[$step['name']]
1561 );
1562 }
1563 }
1564
1565 // Prepend any steps that want to be at the beginning
1566 if ( isset( $this->extraInstallSteps['BEGINNING'] ) ) {
1567 $this->installSteps = array_merge(
1568 $this->extraInstallSteps['BEGINNING'],
1569 $this->installSteps
1570 );
1571 }
1572
1573 // Extensions should always go first, chance to tie into hooks and such
1574 if ( count( $this->getVar( '_Extensions' ) ) ) {
1575 array_unshift( $this->installSteps,
1576 [ 'name' => 'extensions', 'callback' => [ $this, 'includeExtensions' ] ]
1577 );
1578 $this->installSteps[] = [
1579 'name' => 'extension-tables',
1580 'callback' => [ $installer, 'createExtensionTables' ]
1581 ];
1582 }
1583
1584 return $this->installSteps;
1585 }
1586
1587 /**
1588 * Actually perform the installation.
1589 *
1590 * @param callable $startCB A callback array for the beginning of each step
1591 * @param callable $endCB A callback array for the end of each step
1592 *
1593 * @return Status[] Array of Status objects
1594 */
1595 public function performInstallation( $startCB, $endCB ) {
1596 $installResults = [];
1597 $installer = $this->getDBInstaller();
1598 $installer->preInstall();
1599 $steps = $this->getInstallSteps( $installer );
1600 foreach ( $steps as $stepObj ) {
1601 $name = $stepObj['name'];
1602 call_user_func_array( $startCB, [ $name ] );
1603
1604 // Perform the callback step
1605 $status = call_user_func( $stepObj['callback'], $installer );
1606
1607 // Output and save the results
1608 call_user_func( $endCB, $name, $status );
1609 $installResults[$name] = $status;
1610
1611 // If we've hit some sort of fatal, we need to bail.
1612 // Callback already had a chance to do output above.
1613 if ( !$status->isOk() ) {
1614 break;
1615 }
1616 }
1617 if ( $status->isOk() ) {
1618 $this->showMessage(
1619 'config-install-db-success'
1620 );
1621 $this->setVar( '_InstallDone', true );
1622 }
1623
1624 return $installResults;
1625 }
1626
1627 /**
1628 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1629 *
1630 * @return Status
1631 */
1632 public function generateKeys() {
1633 $keys = [ 'wgSecretKey' => 64 ];
1634 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1635 $keys['wgUpgradeKey'] = 16;
1636 }
1637
1638 return $this->doGenerateKeys( $keys );
1639 }
1640
1641 /**
1642 * Generate a secret value for variables using a secure generator.
1643 *
1644 * @param array $keys
1645 * @return Status
1646 */
1647 protected function doGenerateKeys( $keys ) {
1648 $status = Status::newGood();
1649
1650 foreach ( $keys as $name => $length ) {
1651 $secretKey = MWCryptRand::generateHex( $length );
1652 $this->setVar( $name, $secretKey );
1653 }
1654
1655 return $status;
1656 }
1657
1658 /**
1659 * Create the first user account, grant it sysop, bureaucrat and interface-admin rights
1660 *
1661 * @return Status
1662 */
1663 protected function createSysop() {
1664 $name = $this->getVar( '_AdminName' );
1665 $user = User::newFromName( $name );
1666
1667 if ( !$user ) {
1668 // We should've validated this earlier anyway!
1669 return Status::newFatal( 'config-admin-error-user', $name );
1670 }
1671
1672 if ( $user->idForName() == 0 ) {
1673 $user->addToDatabase();
1674
1675 try {
1676 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1677 } catch ( PasswordError $pwe ) {
1678 return Status::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1679 }
1680
1681 $user->addGroup( 'sysop' );
1682 $user->addGroup( 'bureaucrat' );
1683 $user->addGroup( 'interface-admin' );
1684 if ( $this->getVar( '_AdminEmail' ) ) {
1685 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1686 }
1687 $user->saveSettings();
1688
1689 // Update user count
1690 $ssUpdate = SiteStatsUpdate::factory( [ 'users' => 1 ] );
1691 $ssUpdate->doUpdate();
1692 }
1693 $status = Status::newGood();
1694
1695 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1696 $this->subscribeToMediaWikiAnnounce( $status );
1697 }
1698
1699 return $status;
1700 }
1701
1702 /**
1703 * @param Status $s
1704 */
1705 private function subscribeToMediaWikiAnnounce( Status $s ) {
1706 $params = [
1707 'email' => $this->getVar( '_AdminEmail' ),
1708 'language' => 'en',
1709 'digest' => 0
1710 ];
1711
1712 // Mailman doesn't support as many languages as we do, so check to make
1713 // sure their selected language is available
1714 $myLang = $this->getVar( '_UserLang' );
1715 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages ) ) {
1716 $myLang = $myLang == 'pt-br' ? 'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1717 $params['language'] = $myLang;
1718 }
1719
1720 if ( MWHttpRequest::canMakeRequests() ) {
1721 $res = MWHttpRequest::factory( $this->mediaWikiAnnounceUrl,
1722 [ 'method' => 'POST', 'postData' => $params ], __METHOD__ )->execute();
1723 if ( !$res->isOK() ) {
1724 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1725 }
1726 } else {
1727 $s->warning( 'config-install-subscribe-notpossible' );
1728 }
1729 }
1730
1731 /**
1732 * Insert Main Page with default content.
1733 *
1734 * @param DatabaseInstaller $installer
1735 * @return Status
1736 */
1737 protected function createMainpage( DatabaseInstaller $installer ) {
1738 $status = Status::newGood();
1739 $title = Title::newMainPage();
1740 if ( $title->exists() ) {
1741 $status->warning( 'config-install-mainpage-exists' );
1742 return $status;
1743 }
1744 try {
1745 $page = WikiPage::factory( $title );
1746 $content = new WikitextContent(
1747 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1748 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1749 );
1750
1751 $status = $page->doEditContent( $content,
1752 '',
1753 EDIT_NEW,
1754 false,
1755 User::newFromName( 'MediaWiki default' )
1756 );
1757 } catch ( Exception $e ) {
1758 // using raw, because $wgShowExceptionDetails can not be set yet
1759 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1760 }
1761
1762 return $status;
1763 }
1764
1765 /**
1766 * Override the necessary bits of the config to run an installation.
1767 */
1768 public static function overrideConfig() {
1769 // Use PHP's built-in session handling, since MediaWiki's
1770 // SessionHandler can't work before we have an object cache set up.
1771 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
1772 define( 'MW_NO_SESSION_HANDLER', 1 );
1773 }
1774
1775 // Don't access the database
1776 $GLOBALS['wgUseDatabaseMessages'] = false;
1777 // Don't cache langconv tables
1778 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE;
1779 // Debug-friendly
1780 $GLOBALS['wgShowExceptionDetails'] = true;
1781 $GLOBALS['wgShowHostnames'] = true;
1782 // Don't break forms
1783 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1784
1785 // Allow multiple ob_flush() calls
1786 $GLOBALS['wgDisableOutputCompression'] = true;
1787
1788 // Use a sensible cookie prefix (not my_wiki)
1789 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1790
1791 // Some of the environment checks make shell requests, remove limits
1792 $GLOBALS['wgMaxShellMemory'] = 0;
1793
1794 // Override the default CookieSessionProvider with a dummy
1795 // implementation that won't stomp on PHP's cookies.
1796 $GLOBALS['wgSessionProviders'] = [
1797 [
1798 'class' => InstallerSessionProvider::class,
1799 'args' => [ [
1800 'priority' => 1,
1801 ] ]
1802 ]
1803 ];
1804
1805 // Don't try to use any object cache for SessionManager either.
1806 $GLOBALS['wgSessionCacheType'] = CACHE_NONE;
1807 }
1808
1809 /**
1810 * Add an installation step following the given step.
1811 *
1812 * @param array $callback A valid installation callback array, in this form:
1813 * [ 'name' => 'some-unique-name', 'callback' => [ $obj, 'function' ] ];
1814 * @param string $findStep The step to find. Omit to put the step at the beginning
1815 */
1816 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1817 $this->extraInstallSteps[$findStep][] = $callback;
1818 }
1819
1820 /**
1821 * Disable the time limit for execution.
1822 * Some long-running pages (Install, Upgrade) will want to do this
1823 */
1824 protected function disableTimeLimit() {
1825 Wikimedia\suppressWarnings();
1826 set_time_limit( 0 );
1827 Wikimedia\restoreWarnings();
1828 }
1829 }