Drop Oracle and Mssql
[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 the i18n cache
416 // TODO: manage LocalisationCache singleton in MediaWikiServices
417 Language::getLocalisationCache()->disableBackend();
418
419 // Disable all global services, since we don't have any configuration yet!
420 MediaWikiServices::disableStorageBackend();
421
422 $mwServices = MediaWikiServices::getInstance();
423 // Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
424 // SqlBagOStuff will then throw since we just disabled wfGetDB)
425 $wgObjectCaches = $mwServices->getMainConfig()->get( 'ObjectCaches' );
426 $wgMemc = ObjectCache::getInstance( CACHE_NONE );
427
428 // Disable interwiki lookup, to avoid database access during parses
429 $mwServices->redefineService( 'InterwikiLookup', function () {
430 return new NullInterwikiLookup();
431 } );
432
433 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
434 $wgUser = User::newFromId( 0 );
435 RequestContext::getMain()->setUser( $wgUser );
436
437 $this->settings = $this->internalDefaults;
438
439 foreach ( $this->defaultVarNames as $var ) {
440 $this->settings[$var] = $GLOBALS[$var];
441 }
442
443 $this->doEnvironmentPreps();
444
445 $this->compiledDBs = [];
446 foreach ( self::getDBTypes() as $type ) {
447 $installer = $this->getDBInstaller( $type );
448
449 if ( !$installer->isCompiled() ) {
450 continue;
451 }
452 $this->compiledDBs[] = $type;
453 }
454
455 $this->parserTitle = Title::newFromText( 'Installer' );
456 $this->parserOptions = new ParserOptions( $wgUser ); // language will be wrong :(
457 $this->parserOptions->setTidy( true );
458 // Don't try to access DB before user language is initialised
459 $this->setParserLanguage( Language::factory( 'en' ) );
460 }
461
462 /**
463 * Get a list of known DB types.
464 *
465 * @return array
466 */
467 public static function getDBTypes() {
468 return self::$dbTypes;
469 }
470
471 /**
472 * Do initial checks of the PHP environment. Set variables according to
473 * the observed environment.
474 *
475 * It's possible that this may be called under the CLI SAPI, not the SAPI
476 * that the wiki will primarily run under. In that case, the subclass should
477 * initialise variables such as wgScriptPath, before calling this function.
478 *
479 * Under the web subclass, it can already be assumed that PHP 5+ is in use
480 * and that sessions are working.
481 *
482 * @return Status
483 */
484 public function doEnvironmentChecks() {
485 // Php version has already been checked by entry scripts
486 // Show message here for information purposes
487 if ( wfIsHHVM() ) {
488 $this->showMessage( 'config-env-hhvm', HHVM_VERSION );
489 } else {
490 $this->showMessage( 'config-env-php', PHP_VERSION );
491 }
492
493 $good = true;
494 // Must go here because an old version of PCRE can prevent other checks from completing
495 $pcreVersion = explode( ' ', PCRE_VERSION, 2 )[0];
496 if ( version_compare( $pcreVersion, self::MINIMUM_PCRE_VERSION, '<' ) ) {
497 $this->showError( 'config-pcre-old', self::MINIMUM_PCRE_VERSION, $pcreVersion );
498 $good = false;
499 } else {
500 foreach ( $this->envChecks as $check ) {
501 $status = $this->$check();
502 if ( $status === false ) {
503 $good = false;
504 }
505 }
506 }
507
508 $this->setVar( '_Environment', $good );
509
510 return $good ? Status::newGood() : Status::newFatal( 'config-env-bad' );
511 }
512
513 public function doEnvironmentPreps() {
514 foreach ( $this->envPreps as $prep ) {
515 $this->$prep();
516 }
517 }
518
519 /**
520 * Set a MW configuration variable, or internal installer configuration variable.
521 *
522 * @param string $name
523 * @param mixed $value
524 */
525 public function setVar( $name, $value ) {
526 $this->settings[$name] = $value;
527 }
528
529 /**
530 * Get an MW configuration variable, or internal installer configuration variable.
531 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
532 * Installer variables are typically prefixed by an underscore.
533 *
534 * @param string $name
535 * @param mixed|null $default
536 *
537 * @return mixed
538 */
539 public function getVar( $name, $default = null ) {
540 return $this->settings[$name] ?? $default;
541 }
542
543 /**
544 * Get a list of DBs supported by current PHP setup
545 *
546 * @return array
547 */
548 public function getCompiledDBs() {
549 return $this->compiledDBs;
550 }
551
552 /**
553 * Get the DatabaseInstaller class name for this type
554 *
555 * @param string $type database type ($wgDBtype)
556 * @return string Class name
557 * @since 1.30
558 */
559 public static function getDBInstallerClass( $type ) {
560 return ucfirst( $type ) . 'Installer';
561 }
562
563 /**
564 * Get an instance of DatabaseInstaller for the specified DB type.
565 *
566 * @param mixed $type DB installer for which is needed, false to use default.
567 *
568 * @return DatabaseInstaller
569 */
570 public function getDBInstaller( $type = false ) {
571 if ( !$type ) {
572 $type = $this->getVar( 'wgDBtype' );
573 }
574
575 $type = strtolower( $type );
576
577 if ( !isset( $this->dbInstallers[$type] ) ) {
578 $class = self::getDBInstallerClass( $type );
579 $this->dbInstallers[$type] = new $class( $this );
580 }
581
582 return $this->dbInstallers[$type];
583 }
584
585 /**
586 * Determine if LocalSettings.php exists. If it does, return its variables.
587 *
588 * @return array|false
589 */
590 public static function getExistingLocalSettings() {
591 global $IP;
592
593 // You might be wondering why this is here. Well if you don't do this
594 // then some poorly-formed extensions try to call their own classes
595 // after immediately registering them. We really need to get extension
596 // registration out of the global scope and into a real format.
597 // @see https://phabricator.wikimedia.org/T69440
598 global $wgAutoloadClasses;
599 $wgAutoloadClasses = [];
600
601 // LocalSettings.php should not call functions, except wfLoadSkin/wfLoadExtensions
602 // Define the required globals here, to ensure, the functions can do it work correctly.
603 // phpcs:ignore MediaWiki.VariableAnalysis.UnusedGlobalVariables
604 global $wgExtensionDirectory, $wgStyleDirectory;
605
606 Wikimedia\suppressWarnings();
607 $_lsExists = file_exists( "$IP/LocalSettings.php" );
608 Wikimedia\restoreWarnings();
609
610 if ( !$_lsExists ) {
611 return false;
612 }
613 unset( $_lsExists );
614
615 require "$IP/includes/DefaultSettings.php";
616 require "$IP/LocalSettings.php";
617
618 return get_defined_vars();
619 }
620
621 /**
622 * Get a fake password for sending back to the user in HTML.
623 * This is a security mechanism to avoid compromise of the password in the
624 * event of session ID compromise.
625 *
626 * @param string $realPassword
627 *
628 * @return string
629 */
630 public function getFakePassword( $realPassword ) {
631 return str_repeat( '*', strlen( $realPassword ) );
632 }
633
634 /**
635 * Set a variable which stores a password, except if the new value is a
636 * fake password in which case leave it as it is.
637 *
638 * @param string $name
639 * @param mixed $value
640 */
641 public function setPassword( $name, $value ) {
642 if ( !preg_match( '/^\*+$/', $value ) ) {
643 $this->setVar( $name, $value );
644 }
645 }
646
647 /**
648 * On POSIX systems return the primary group of the webserver we're running under.
649 * On other systems just returns null.
650 *
651 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
652 * webserver user before he can install.
653 *
654 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
655 *
656 * @return mixed
657 */
658 public static function maybeGetWebserverPrimaryGroup() {
659 if ( !function_exists( 'posix_getegid' ) || !function_exists( 'posix_getpwuid' ) ) {
660 # I don't know this, this isn't UNIX.
661 return null;
662 }
663
664 # posix_getegid() *not* getmygid() because we want the group of the webserver,
665 # not whoever owns the current script.
666 $gid = posix_getegid();
667 $group = posix_getpwuid( $gid )['name'];
668
669 return $group;
670 }
671
672 /**
673 * Convert wikitext $text to HTML.
674 *
675 * This is potentially error prone since many parser features require a complete
676 * installed MW database. The solution is to just not use those features when you
677 * write your messages. This appears to work well enough. Basic formatting and
678 * external links work just fine.
679 *
680 * But in case a translator decides to throw in a "#ifexist" or internal link or
681 * whatever, this function is guarded to catch the attempted DB access and to present
682 * some fallback text.
683 *
684 * @param string $text
685 * @param bool $lineStart
686 * @return string
687 */
688 public function parse( $text, $lineStart = false ) {
689 $parser = MediaWikiServices::getInstance()->getParser();
690
691 try {
692 $out = $parser->parse( $text, $this->parserTitle, $this->parserOptions, $lineStart );
693 $html = $out->getText( [
694 'enableSectionEditLinks' => false,
695 'unwrap' => true,
696 ] );
697 $html = Parser::stripOuterParagraph( $html );
698 } catch ( Wikimedia\Services\ServiceDisabledException $e ) {
699 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
700 }
701
702 return $html;
703 }
704
705 /**
706 * @return ParserOptions
707 */
708 public function getParserOptions() {
709 return $this->parserOptions;
710 }
711
712 public function disableLinkPopups() {
713 $this->parserOptions->setExternalLinkTarget( false );
714 }
715
716 public function restoreLinkPopups() {
717 global $wgExternalLinkTarget;
718 $this->parserOptions->setExternalLinkTarget( $wgExternalLinkTarget );
719 }
720
721 /**
722 * Install step which adds a row to the site_stats table with appropriate
723 * initial values.
724 *
725 * @param DatabaseInstaller $installer
726 *
727 * @return Status
728 */
729 public function populateSiteStats( DatabaseInstaller $installer ) {
730 $status = $installer->getConnection();
731 if ( !$status->isOK() ) {
732 return $status;
733 }
734 $status->value->insert(
735 'site_stats',
736 [
737 'ss_row_id' => 1,
738 'ss_total_edits' => 0,
739 'ss_good_articles' => 0,
740 'ss_total_pages' => 0,
741 'ss_users' => 0,
742 'ss_active_users' => 0,
743 'ss_images' => 0
744 ],
745 __METHOD__, 'IGNORE'
746 );
747
748 return Status::newGood();
749 }
750
751 /**
752 * Environment check for DB types.
753 * @return bool
754 */
755 protected function envCheckDB() {
756 global $wgLang;
757 /** @var string|null $dbType The user-specified database type */
758 $dbType = $this->getVar( 'wgDBtype' );
759
760 $allNames = [];
761
762 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
763 // config-type-sqlite
764 foreach ( self::getDBTypes() as $name ) {
765 $allNames[] = wfMessage( "config-type-$name" )->text();
766 }
767
768 $databases = $this->getCompiledDBs();
769
770 $databases = array_flip( $databases );
771 $ok = true;
772 foreach ( array_keys( $databases ) as $db ) {
773 $installer = $this->getDBInstaller( $db );
774 $status = $installer->checkPrerequisites();
775 if ( !$status->isGood() ) {
776 if ( !$this instanceof WebInstaller && $db === $dbType ) {
777 // Strictly check the key database type instead of just outputting message
778 // Note: No perform this check run from the web installer, since this method always called by
779 // the welcome page under web installation, so $dbType will always be 'mysql'
780 $ok = false;
781 }
782 $this->showStatusMessage( $status );
783 unset( $databases[$db] );
784 }
785 }
786 $databases = array_flip( $databases );
787 if ( !$databases ) {
788 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
789 return false;
790 }
791 return $ok;
792 }
793
794 /**
795 * Some versions of libxml+PHP break < and > encoding horribly
796 * @return bool
797 */
798 protected function envCheckBrokenXML() {
799 $test = new PhpXmlBugTester();
800 if ( !$test->ok ) {
801 $this->showError( 'config-brokenlibxml' );
802
803 return false;
804 }
805
806 return true;
807 }
808
809 /**
810 * Environment check for the PCRE module.
811 *
812 * @note If this check were to fail, the parser would
813 * probably throw an exception before the result
814 * of this check is shown to the user.
815 * @return bool
816 */
817 protected function envCheckPCRE() {
818 Wikimedia\suppressWarnings();
819 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
820 // Need to check for \p support too, as PCRE can be compiled
821 // with utf8 support, but not unicode property support.
822 // check that \p{Zs} (space separators) matches
823 // U+3000 (Ideographic space)
824 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\u{3000}-" );
825 Wikimedia\restoreWarnings();
826 if ( $regexd != '--' || $regexprop != '--' ) {
827 $this->showError( 'config-pcre-no-utf8' );
828
829 return false;
830 }
831
832 return true;
833 }
834
835 /**
836 * Environment check for available memory.
837 * @return bool
838 */
839 protected function envCheckMemory() {
840 $limit = ini_get( 'memory_limit' );
841
842 if ( !$limit || $limit == -1 ) {
843 return true;
844 }
845
846 $n = wfShorthandToInteger( $limit );
847
848 if ( $n < $this->minMemorySize * 1024 * 1024 ) {
849 $newLimit = "{$this->minMemorySize}M";
850
851 if ( ini_set( "memory_limit", $newLimit ) === false ) {
852 $this->showMessage( 'config-memory-bad', $limit );
853 } else {
854 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
855 $this->setVar( '_RaiseMemory', true );
856 }
857 }
858
859 return true;
860 }
861
862 /**
863 * Environment check for compiled object cache types.
864 */
865 protected function envCheckCache() {
866 $caches = [];
867 foreach ( $this->objectCaches as $name => $function ) {
868 if ( function_exists( $function ) ) {
869 $caches[$name] = true;
870 }
871 }
872
873 if ( !$caches ) {
874 $this->showMessage( 'config-no-cache-apcu' );
875 }
876
877 $this->setVar( '_Caches', $caches );
878 }
879
880 /**
881 * Scare user to death if they have mod_security or mod_security2
882 * @return bool
883 */
884 protected function envCheckModSecurity() {
885 if ( self::apacheModulePresent( 'mod_security' )
886 || self::apacheModulePresent( 'mod_security2' ) ) {
887 $this->showMessage( 'config-mod-security' );
888 }
889
890 return true;
891 }
892
893 /**
894 * Search for GNU diff3.
895 * @return bool
896 */
897 protected function envCheckDiff3() {
898 $names = [ "gdiff3", "diff3" ];
899 if ( wfIsWindows() ) {
900 $names[] = 'diff3.exe';
901 }
902 $versionInfo = [ '--version', 'GNU diffutils' ];
903
904 $diff3 = ExecutableFinder::findInDefaultPaths( $names, $versionInfo );
905
906 if ( $diff3 ) {
907 $this->setVar( 'wgDiff3', $diff3 );
908 } else {
909 $this->setVar( 'wgDiff3', false );
910 $this->showMessage( 'config-diff3-bad' );
911 }
912
913 return true;
914 }
915
916 /**
917 * Environment check for ImageMagick and GD.
918 * @return bool
919 */
920 protected function envCheckGraphics() {
921 $names = wfIsWindows() ? 'convert.exe' : 'convert';
922 $versionInfo = [ '-version', 'ImageMagick' ];
923 $convert = ExecutableFinder::findInDefaultPaths( $names, $versionInfo );
924
925 $this->setVar( 'wgImageMagickConvertCommand', '' );
926 if ( $convert ) {
927 $this->setVar( 'wgImageMagickConvertCommand', $convert );
928 $this->showMessage( 'config-imagemagick', $convert );
929
930 return true;
931 } elseif ( function_exists( 'imagejpeg' ) ) {
932 $this->showMessage( 'config-gd' );
933 } else {
934 $this->showMessage( 'config-no-scaling' );
935 }
936
937 return true;
938 }
939
940 /**
941 * Search for git.
942 *
943 * @since 1.22
944 * @return bool
945 */
946 protected function envCheckGit() {
947 $names = wfIsWindows() ? 'git.exe' : 'git';
948 $versionInfo = [ '--version', 'git version' ];
949
950 $git = ExecutableFinder::findInDefaultPaths( $names, $versionInfo );
951
952 if ( $git ) {
953 $this->setVar( 'wgGitBin', $git );
954 $this->showMessage( 'config-git', $git );
955 } else {
956 $this->setVar( 'wgGitBin', false );
957 $this->showMessage( 'config-git-bad' );
958 }
959
960 return true;
961 }
962
963 /**
964 * Environment check to inform user which server we've assumed.
965 *
966 * @return bool
967 */
968 protected function envCheckServer() {
969 $server = $this->envGetDefaultServer();
970 if ( $server !== null ) {
971 $this->showMessage( 'config-using-server', $server );
972 }
973 return true;
974 }
975
976 /**
977 * Environment check to inform user which paths we've assumed.
978 *
979 * @return bool
980 */
981 protected function envCheckPath() {
982 $this->showMessage(
983 'config-using-uri',
984 $this->getVar( 'wgServer' ),
985 $this->getVar( 'wgScriptPath' )
986 );
987 return true;
988 }
989
990 /**
991 * Environment check for preferred locale in shell
992 * @return bool
993 */
994 protected function envCheckShellLocale() {
995 $os = php_uname( 's' );
996 $supported = [ 'Linux', 'SunOS', 'HP-UX', 'Darwin' ]; # Tested these
997
998 if ( !in_array( $os, $supported ) ) {
999 return true;
1000 }
1001
1002 if ( Shell::isDisabled() ) {
1003 return true;
1004 }
1005
1006 # Get a list of available locales.
1007 $result = Shell::command( '/usr/bin/locale', '-a' )
1008 ->execute();
1009
1010 if ( $result->getExitCode() != 0 ) {
1011 return true;
1012 }
1013
1014 $lines = $result->getStdout();
1015 $lines = array_map( 'trim', explode( "\n", $lines ) );
1016 $candidatesByLocale = [];
1017 $candidatesByLang = [];
1018 foreach ( $lines as $line ) {
1019 if ( $line === '' ) {
1020 continue;
1021 }
1022
1023 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1024 continue;
1025 }
1026
1027 list( , $lang, , , ) = $m;
1028
1029 $candidatesByLocale[$m[0]] = $m;
1030 $candidatesByLang[$lang][] = $m;
1031 }
1032
1033 # Try the current value of LANG.
1034 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1035 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1036
1037 return true;
1038 }
1039
1040 # Try the most common ones.
1041 $commonLocales = [ 'C.UTF-8', 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' ];
1042 foreach ( $commonLocales as $commonLocale ) {
1043 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1044 $this->setVar( 'wgShellLocale', $commonLocale );
1045
1046 return true;
1047 }
1048 }
1049
1050 # Is there an available locale in the Wiki's language?
1051 $wikiLang = $this->getVar( 'wgLanguageCode' );
1052
1053 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1054 $m = reset( $candidatesByLang[$wikiLang] );
1055 $this->setVar( 'wgShellLocale', $m[0] );
1056
1057 return true;
1058 }
1059
1060 # Are there any at all?
1061 if ( count( $candidatesByLocale ) ) {
1062 $m = reset( $candidatesByLocale );
1063 $this->setVar( 'wgShellLocale', $m[0] );
1064
1065 return true;
1066 }
1067
1068 # Give up.
1069 return true;
1070 }
1071
1072 /**
1073 * Environment check for the permissions of the uploads directory
1074 * @return bool
1075 */
1076 protected function envCheckUploadsDirectory() {
1077 global $IP;
1078
1079 $dir = $IP . '/images/';
1080 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1081 $safe = !$this->dirIsExecutable( $dir, $url );
1082
1083 if ( !$safe ) {
1084 $this->showMessage( 'config-uploads-not-safe', $dir );
1085 }
1086
1087 return true;
1088 }
1089
1090 /**
1091 * Checks if suhosin.get.max_value_length is set, and if so generate
1092 * a warning because it decreases ResourceLoader performance.
1093 * @return bool
1094 */
1095 protected function envCheckSuhosinMaxValueLength() {
1096 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1097 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1098 // Only warn if the value is below the sane 1024
1099 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1100 }
1101
1102 return true;
1103 }
1104
1105 /**
1106 * Checks if we're running on 64 bit or not. 32 bit is becoming increasingly
1107 * hard to support, so let's at least warn people.
1108 *
1109 * @return bool
1110 */
1111 protected function envCheck64Bit() {
1112 if ( PHP_INT_SIZE == 4 ) {
1113 $this->showMessage( 'config-using-32bit' );
1114 }
1115
1116 return true;
1117 }
1118
1119 /**
1120 * Check the libicu version
1121 */
1122 protected function envCheckLibicu() {
1123 /**
1124 * This needs to be updated something that the latest libicu
1125 * will properly normalize. This normalization was found at
1126 * https://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1127 * Note that we use the hex representation to create the code
1128 * points in order to avoid any Unicode-destroying during transit.
1129 */
1130 $not_normal_c = "\u{FA6C}";
1131 $normal_c = "\u{242EE}";
1132
1133 $useNormalizer = 'php';
1134 $needsUpdate = false;
1135
1136 if ( function_exists( 'normalizer_normalize' ) ) {
1137 $useNormalizer = 'intl';
1138 $intl = normalizer_normalize( $not_normal_c, Normalizer::FORM_C );
1139 if ( $intl !== $normal_c ) {
1140 $needsUpdate = true;
1141 }
1142 }
1143
1144 // Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
1145 if ( $useNormalizer === 'php' ) {
1146 $this->showMessage( 'config-unicode-pure-php-warning' );
1147 } else {
1148 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1149 if ( $needsUpdate ) {
1150 $this->showMessage( 'config-unicode-update-warning' );
1151 }
1152 }
1153 }
1154
1155 /**
1156 * Environment prep for the server hostname.
1157 */
1158 protected function envPrepServer() {
1159 $server = $this->envGetDefaultServer();
1160 if ( $server !== null ) {
1161 $this->setVar( 'wgServer', $server );
1162 }
1163 }
1164
1165 /**
1166 * Helper function to be called from envPrepServer()
1167 * @return string
1168 */
1169 abstract protected function envGetDefaultServer();
1170
1171 /**
1172 * Environment prep for setting $IP and $wgScriptPath.
1173 */
1174 protected function envPrepPath() {
1175 global $IP;
1176 $IP = dirname( dirname( __DIR__ ) );
1177 $this->setVar( 'IP', $IP );
1178 }
1179
1180 /**
1181 * Checks if scripts located in the given directory can be executed via the given URL.
1182 *
1183 * Used only by environment checks.
1184 * @param string $dir
1185 * @param string $url
1186 * @return bool|int|string
1187 */
1188 public function dirIsExecutable( $dir, $url ) {
1189 $scriptTypes = [
1190 'php' => [
1191 "<?php echo 'exec';",
1192 "#!/var/env php\n<?php echo 'exec';",
1193 ],
1194 ];
1195
1196 // it would be good to check other popular languages here, but it'll be slow.
1197
1198 Wikimedia\suppressWarnings();
1199
1200 foreach ( $scriptTypes as $ext => $contents ) {
1201 foreach ( $contents as $source ) {
1202 $file = 'exectest.' . $ext;
1203
1204 if ( !file_put_contents( $dir . $file, $source ) ) {
1205 break;
1206 }
1207
1208 try {
1209 $text = MediaWikiServices::getInstance()->getHttpRequestFactory()->
1210 get( $url . $file, [ 'timeout' => 3 ], __METHOD__ );
1211 } catch ( Exception $e ) {
1212 // HttpRequestFactory::get can throw with allow_url_fopen = false and no curl
1213 // extension.
1214 $text = null;
1215 }
1216 unlink( $dir . $file );
1217
1218 if ( $text == 'exec' ) {
1219 Wikimedia\restoreWarnings();
1220
1221 return $ext;
1222 }
1223 }
1224 }
1225
1226 Wikimedia\restoreWarnings();
1227
1228 return false;
1229 }
1230
1231 /**
1232 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1233 *
1234 * @param string $moduleName Name of module to check.
1235 * @return bool
1236 */
1237 public static function apacheModulePresent( $moduleName ) {
1238 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1239 return true;
1240 }
1241 // try it the hard way
1242 ob_start();
1243 phpinfo( INFO_MODULES );
1244 $info = ob_get_clean();
1245
1246 return strpos( $info, $moduleName ) !== false;
1247 }
1248
1249 /**
1250 * ParserOptions are constructed before we determined the language, so fix it
1251 *
1252 * @param Language $lang
1253 */
1254 public function setParserLanguage( $lang ) {
1255 $this->parserOptions->setTargetLanguage( $lang );
1256 $this->parserOptions->setUserLang( $lang );
1257 }
1258
1259 /**
1260 * Overridden by WebInstaller to provide lastPage parameters.
1261 * @param string $page
1262 * @return string
1263 */
1264 protected function getDocUrl( $page ) {
1265 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1266 }
1267
1268 /**
1269 * Find extensions or skins in a subdirectory of $IP.
1270 * Returns an array containing the value for 'Name' for each found extension.
1271 *
1272 * @param string $directory Directory to search in, relative to $IP, must be either "extensions"
1273 * or "skins"
1274 * @return array [ $extName => [ 'screenshots' => [ '...' ] ]
1275 */
1276 public function findExtensions( $directory = 'extensions' ) {
1277 switch ( $directory ) {
1278 case 'extensions':
1279 return $this->findExtensionsByType( 'extension', 'extensions' );
1280 case 'skins':
1281 return $this->findExtensionsByType( 'skin', 'skins' );
1282 default:
1283 throw new InvalidArgumentException( "Invalid extension type" );
1284 }
1285 }
1286
1287 /**
1288 * Find extensions or skins, and return an array containing the value for 'Name' for each found
1289 * extension.
1290 *
1291 * @param string $type Either "extension" or "skin"
1292 * @param string $directory Directory to search in, relative to $IP
1293 * @return array [ $extName => [ 'screenshots' => [ '...' ] ]
1294 */
1295 protected function findExtensionsByType( $type = 'extension', $directory = 'extensions' ) {
1296 if ( $this->getVar( 'IP' ) === null ) {
1297 return [];
1298 }
1299
1300 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1301 if ( !is_readable( $extDir ) || !is_dir( $extDir ) ) {
1302 return [];
1303 }
1304
1305 $dh = opendir( $extDir );
1306 $exts = [];
1307 while ( ( $file = readdir( $dh ) ) !== false ) {
1308 if ( !is_dir( "$extDir/$file" ) ) {
1309 continue;
1310 }
1311 $status = $this->getExtensionInfo( $type, $directory, $file );
1312 if ( $status->isOK() ) {
1313 $exts[$file] = $status->value;
1314 }
1315 }
1316 closedir( $dh );
1317 uksort( $exts, 'strnatcasecmp' );
1318
1319 return $exts;
1320 }
1321
1322 /**
1323 * @param string $type Either "extension" or "skin"
1324 * @param string $parentRelPath The parent directory relative to $IP
1325 * @param string $name The extension or skin name
1326 * @return Status An object containing an error list. If there were no errors, an associative
1327 * array of information about the extension can be found in $status->value.
1328 */
1329 protected function getExtensionInfo( $type, $parentRelPath, $name ) {
1330 if ( $this->getVar( 'IP' ) === null ) {
1331 throw new Exception( 'Cannot find extensions since the IP variable is not yet set' );
1332 }
1333 if ( $type !== 'extension' && $type !== 'skin' ) {
1334 throw new InvalidArgumentException( "Invalid extension type" );
1335 }
1336 $absDir = $this->getVar( 'IP' ) . "/$parentRelPath/$name";
1337 $relDir = "../$parentRelPath/$name";
1338 if ( !is_dir( $absDir ) ) {
1339 return Status::newFatal( 'config-extension-not-found', $name );
1340 }
1341 $jsonFile = $type . '.json';
1342 $fullJsonFile = "$absDir/$jsonFile";
1343 $isJson = file_exists( $fullJsonFile );
1344 $isPhp = false;
1345 if ( !$isJson ) {
1346 // Only fallback to PHP file if JSON doesn't exist
1347 $fullPhpFile = "$absDir/$name.php";
1348 $isPhp = file_exists( $fullPhpFile );
1349 }
1350 if ( !$isJson && !$isPhp ) {
1351 return Status::newFatal( 'config-extension-not-found', $name );
1352 }
1353
1354 // Extension exists. Now see if there are screenshots
1355 $info = [];
1356 if ( is_dir( "$absDir/screenshots" ) ) {
1357 $paths = glob( "$absDir/screenshots/*.png" );
1358 foreach ( $paths as $path ) {
1359 $info['screenshots'][] = str_replace( $absDir, $relDir, $path );
1360 }
1361 }
1362
1363 if ( $isJson ) {
1364 $jsonStatus = $this->readExtension( $fullJsonFile );
1365 if ( !$jsonStatus->isOK() ) {
1366 return $jsonStatus;
1367 }
1368 $info += $jsonStatus->value;
1369 }
1370
1371 return Status::newGood( $info );
1372 }
1373
1374 /**
1375 * @param string $fullJsonFile
1376 * @param array $extDeps
1377 * @param array $skinDeps
1378 *
1379 * @return Status On success, an array of extension information is in $status->value. On
1380 * failure, the Status object will have an error list.
1381 */
1382 private function readExtension( $fullJsonFile, $extDeps = [], $skinDeps = [] ) {
1383 $load = [
1384 $fullJsonFile => 1
1385 ];
1386 if ( $extDeps ) {
1387 $extDir = $this->getVar( 'IP' ) . '/extensions';
1388 foreach ( $extDeps as $dep ) {
1389 $fname = "$extDir/$dep/extension.json";
1390 if ( !file_exists( $fname ) ) {
1391 return Status::newFatal( 'config-extension-not-found', $dep );
1392 }
1393 $load[$fname] = 1;
1394 }
1395 }
1396 if ( $skinDeps ) {
1397 $skinDir = $this->getVar( 'IP' ) . '/skins';
1398 foreach ( $skinDeps as $dep ) {
1399 $fname = "$skinDir/$dep/skin.json";
1400 if ( !file_exists( $fname ) ) {
1401 return Status::newFatal( 'config-extension-not-found', $dep );
1402 }
1403 $load[$fname] = 1;
1404 }
1405 }
1406 $registry = new ExtensionRegistry();
1407 try {
1408 $info = $registry->readFromQueue( $load );
1409 } catch ( ExtensionDependencyError $e ) {
1410 if ( $e->incompatibleCore || $e->incompatibleSkins
1411 || $e->incompatibleExtensions
1412 ) {
1413 // If something is incompatible with a dependency, we have no real
1414 // option besides skipping it
1415 return Status::newFatal( 'config-extension-dependency',
1416 basename( dirname( $fullJsonFile ) ), $e->getMessage() );
1417 } elseif ( $e->missingExtensions || $e->missingSkins ) {
1418 // There's an extension missing in the dependency tree,
1419 // so add those to the dependency list and try again
1420 return $this->readExtension(
1421 $fullJsonFile,
1422 array_merge( $extDeps, $e->missingExtensions ),
1423 array_merge( $skinDeps, $e->missingSkins )
1424 );
1425 }
1426 // Some other kind of dependency error?
1427 return Status::newFatal( 'config-extension-dependency',
1428 basename( dirname( $fullJsonFile ) ), $e->getMessage() );
1429 }
1430 $ret = [];
1431 // The order of credits will be the order of $load,
1432 // so the first extension is the one we want to load,
1433 // everything else is a dependency
1434 $i = 0;
1435 foreach ( $info['credits'] as $name => $credit ) {
1436 $i++;
1437 if ( $i == 1 ) {
1438 // Extension we want to load
1439 continue;
1440 }
1441 $type = basename( $credit['path'] ) === 'skin.json' ? 'skins' : 'extensions';
1442 $ret['requires'][$type][] = $credit['name'];
1443 }
1444 $credits = array_values( $info['credits'] )[0];
1445 if ( isset( $credits['url'] ) ) {
1446 $ret['url'] = $credits['url'];
1447 }
1448 $ret['type'] = $credits['type'];
1449
1450 return Status::newGood( $ret );
1451 }
1452
1453 /**
1454 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1455 * but will fall back to another if the default skin is missing and some other one is present
1456 * instead.
1457 *
1458 * @param string[] $skinNames Names of installed skins.
1459 * @return string
1460 */
1461 public function getDefaultSkin( array $skinNames ) {
1462 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1463 if ( !$skinNames || in_array( $defaultSkin, $skinNames ) ) {
1464 return $defaultSkin;
1465 } else {
1466 return $skinNames[0];
1467 }
1468 }
1469
1470 /**
1471 * Installs the auto-detected extensions.
1472 *
1473 * @suppress SecurityCheck-OTHER It thinks $exts/$IP is user controlled but they are not.
1474 * @return Status
1475 */
1476 protected function includeExtensions() {
1477 global $IP;
1478 $exts = $this->getVar( '_Extensions' );
1479 $IP = $this->getVar( 'IP' );
1480
1481 // Marker for DatabaseUpdater::loadExtensions so we don't
1482 // double load extensions
1483 define( 'MW_EXTENSIONS_LOADED', true );
1484
1485 /**
1486 * We need to include DefaultSettings before including extensions to avoid
1487 * warnings about unset variables. However, the only thing we really
1488 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1489 * if the extension has hidden hook registration in $wgExtensionFunctions,
1490 * but we're not opening that can of worms
1491 * @see https://phabricator.wikimedia.org/T28857
1492 */
1493 global $wgAutoloadClasses;
1494 $wgAutoloadClasses = [];
1495 $queue = [];
1496
1497 require "$IP/includes/DefaultSettings.php";
1498
1499 foreach ( $exts as $e ) {
1500 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1501 $queue["$IP/extensions/$e/extension.json"] = 1;
1502 } else {
1503 require_once "$IP/extensions/$e/$e.php";
1504 }
1505 }
1506
1507 $registry = new ExtensionRegistry();
1508 $data = $registry->readFromQueue( $queue );
1509 $wgAutoloadClasses += $data['autoload'];
1510
1511 // @phan-suppress-next-line PhanUndeclaredVariable $wgHooks is set by DefaultSettings
1512 $hooksWeWant = $wgHooks['LoadExtensionSchemaUpdates'] ?? [];
1513
1514 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1515 $hooksWeWant = array_merge_recursive(
1516 $hooksWeWant,
1517 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1518 );
1519 }
1520 // Unset everyone else's hooks. Lord knows what someone might be doing
1521 // in ParserFirstCallInit (see T29171)
1522 $GLOBALS['wgHooks'] = [ 'LoadExtensionSchemaUpdates' => $hooksWeWant ];
1523
1524 return Status::newGood();
1525 }
1526
1527 /**
1528 * Get an array of install steps. Should always be in the format of
1529 * [
1530 * 'name' => 'someuniquename',
1531 * 'callback' => [ $obj, 'method' ],
1532 * ]
1533 * There must be a config-install-$name message defined per step, which will
1534 * be shown on install.
1535 *
1536 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1537 * @return array
1538 */
1539 protected function getInstallSteps( DatabaseInstaller $installer ) {
1540 $coreInstallSteps = [
1541 [ 'name' => 'database', 'callback' => [ $installer, 'setupDatabase' ] ],
1542 [ 'name' => 'tables', 'callback' => [ $installer, 'createTables' ] ],
1543 [ 'name' => 'interwiki', 'callback' => [ $installer, 'populateInterwikiTable' ] ],
1544 [ 'name' => 'stats', 'callback' => [ $this, 'populateSiteStats' ] ],
1545 [ 'name' => 'keys', 'callback' => [ $this, 'generateKeys' ] ],
1546 [ 'name' => 'updates', 'callback' => [ $installer, 'insertUpdateKeys' ] ],
1547 [ 'name' => 'sysop', 'callback' => [ $this, 'createSysop' ] ],
1548 [ 'name' => 'mainpage', 'callback' => [ $this, 'createMainpage' ] ],
1549 ];
1550
1551 // Build the array of install steps starting from the core install list,
1552 // then adding any callbacks that wanted to attach after a given step
1553 foreach ( $coreInstallSteps as $step ) {
1554 $this->installSteps[] = $step;
1555 if ( isset( $this->extraInstallSteps[$step['name']] ) ) {
1556 $this->installSteps = array_merge(
1557 $this->installSteps,
1558 $this->extraInstallSteps[$step['name']]
1559 );
1560 }
1561 }
1562
1563 // Prepend any steps that want to be at the beginning
1564 if ( isset( $this->extraInstallSteps['BEGINNING'] ) ) {
1565 $this->installSteps = array_merge(
1566 $this->extraInstallSteps['BEGINNING'],
1567 $this->installSteps
1568 );
1569 }
1570
1571 // Extensions should always go first, chance to tie into hooks and such
1572 if ( count( $this->getVar( '_Extensions' ) ) ) {
1573 array_unshift( $this->installSteps,
1574 [ 'name' => 'extensions', 'callback' => [ $this, 'includeExtensions' ] ]
1575 );
1576 $this->installSteps[] = [
1577 'name' => 'extension-tables',
1578 'callback' => [ $installer, 'createExtensionTables' ]
1579 ];
1580 }
1581
1582 return $this->installSteps;
1583 }
1584
1585 /**
1586 * Actually perform the installation.
1587 *
1588 * @param callable $startCB A callback array for the beginning of each step
1589 * @param callable $endCB A callback array for the end of each step
1590 *
1591 * @return Status[] Array of Status objects
1592 */
1593 public function performInstallation( $startCB, $endCB ) {
1594 $installResults = [];
1595 $installer = $this->getDBInstaller();
1596 $installer->preInstall();
1597 $steps = $this->getInstallSteps( $installer );
1598 foreach ( $steps as $stepObj ) {
1599 $name = $stepObj['name'];
1600 call_user_func_array( $startCB, [ $name ] );
1601
1602 // Perform the callback step
1603 $status = call_user_func( $stepObj['callback'], $installer );
1604
1605 // Output and save the results
1606 call_user_func( $endCB, $name, $status );
1607 $installResults[$name] = $status;
1608
1609 // If we've hit some sort of fatal, we need to bail.
1610 // Callback already had a chance to do output above.
1611 if ( !$status->isOk() ) {
1612 break;
1613 }
1614 }
1615 if ( $status->isOk() ) {
1616 $this->showMessage(
1617 'config-install-db-success'
1618 );
1619 $this->setVar( '_InstallDone', true );
1620 }
1621
1622 return $installResults;
1623 }
1624
1625 /**
1626 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1627 *
1628 * @return Status
1629 */
1630 public function generateKeys() {
1631 $keys = [ 'wgSecretKey' => 64 ];
1632 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1633 $keys['wgUpgradeKey'] = 16;
1634 }
1635
1636 return $this->doGenerateKeys( $keys );
1637 }
1638
1639 /**
1640 * Generate a secret value for variables using a secure generator.
1641 *
1642 * @param array $keys
1643 * @return Status
1644 */
1645 protected function doGenerateKeys( $keys ) {
1646 $status = Status::newGood();
1647
1648 foreach ( $keys as $name => $length ) {
1649 $secretKey = MWCryptRand::generateHex( $length );
1650 $this->setVar( $name, $secretKey );
1651 }
1652
1653 return $status;
1654 }
1655
1656 /**
1657 * Create the first user account, grant it sysop, bureaucrat and interface-admin rights
1658 *
1659 * @return Status
1660 */
1661 protected function createSysop() {
1662 $name = $this->getVar( '_AdminName' );
1663 $user = User::newFromName( $name );
1664
1665 if ( !$user ) {
1666 // We should've validated this earlier anyway!
1667 return Status::newFatal( 'config-admin-error-user', $name );
1668 }
1669
1670 if ( $user->idForName() == 0 ) {
1671 $user->addToDatabase();
1672
1673 try {
1674 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1675 } catch ( PasswordError $pwe ) {
1676 return Status::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1677 }
1678
1679 $user->addGroup( 'sysop' );
1680 $user->addGroup( 'bureaucrat' );
1681 $user->addGroup( 'interface-admin' );
1682 if ( $this->getVar( '_AdminEmail' ) ) {
1683 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1684 }
1685 $user->saveSettings();
1686
1687 // Update user count
1688 $ssUpdate = SiteStatsUpdate::factory( [ 'users' => 1 ] );
1689 $ssUpdate->doUpdate();
1690 }
1691 $status = Status::newGood();
1692
1693 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1694 $this->subscribeToMediaWikiAnnounce( $status );
1695 }
1696
1697 return $status;
1698 }
1699
1700 /**
1701 * @param Status $s
1702 */
1703 private function subscribeToMediaWikiAnnounce( Status $s ) {
1704 $params = [
1705 'email' => $this->getVar( '_AdminEmail' ),
1706 'language' => 'en',
1707 'digest' => 0
1708 ];
1709
1710 // Mailman doesn't support as many languages as we do, so check to make
1711 // sure their selected language is available
1712 $myLang = $this->getVar( '_UserLang' );
1713 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages ) ) {
1714 $myLang = $myLang == 'pt-br' ? 'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1715 $params['language'] = $myLang;
1716 }
1717
1718 if ( MWHttpRequest::canMakeRequests() ) {
1719 $res = MWHttpRequest::factory( $this->mediaWikiAnnounceUrl,
1720 [ 'method' => 'POST', 'postData' => $params ], __METHOD__ )->execute();
1721 if ( !$res->isOK() ) {
1722 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1723 }
1724 } else {
1725 $s->warning( 'config-install-subscribe-notpossible' );
1726 }
1727 }
1728
1729 /**
1730 * Insert Main Page with default content.
1731 *
1732 * @param DatabaseInstaller $installer
1733 * @return Status
1734 */
1735 protected function createMainpage( DatabaseInstaller $installer ) {
1736 $status = Status::newGood();
1737 $title = Title::newMainPage();
1738 if ( $title->exists() ) {
1739 $status->warning( 'config-install-mainpage-exists' );
1740 return $status;
1741 }
1742 try {
1743 $page = WikiPage::factory( $title );
1744 $content = new WikitextContent(
1745 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1746 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1747 );
1748
1749 $status = $page->doEditContent( $content,
1750 '',
1751 EDIT_NEW,
1752 false,
1753 User::newFromName( 'MediaWiki default' )
1754 );
1755 } catch ( Exception $e ) {
1756 // using raw, because $wgShowExceptionDetails can not be set yet
1757 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1758 }
1759
1760 return $status;
1761 }
1762
1763 /**
1764 * Override the necessary bits of the config to run an installation.
1765 */
1766 public static function overrideConfig() {
1767 // Use PHP's built-in session handling, since MediaWiki's
1768 // SessionHandler can't work before we have an object cache set up.
1769 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
1770 define( 'MW_NO_SESSION_HANDLER', 1 );
1771 }
1772
1773 // Don't access the database
1774 $GLOBALS['wgUseDatabaseMessages'] = false;
1775 // Don't cache langconv tables
1776 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE;
1777 // Debug-friendly
1778 $GLOBALS['wgShowExceptionDetails'] = true;
1779 $GLOBALS['wgShowHostnames'] = true;
1780 // Don't break forms
1781 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1782
1783 // Allow multiple ob_flush() calls
1784 $GLOBALS['wgDisableOutputCompression'] = true;
1785
1786 // Use a sensible cookie prefix (not my_wiki)
1787 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1788
1789 // Some of the environment checks make shell requests, remove limits
1790 $GLOBALS['wgMaxShellMemory'] = 0;
1791
1792 // Override the default CookieSessionProvider with a dummy
1793 // implementation that won't stomp on PHP's cookies.
1794 $GLOBALS['wgSessionProviders'] = [
1795 [
1796 'class' => InstallerSessionProvider::class,
1797 'args' => [ [
1798 'priority' => 1,
1799 ] ]
1800 ]
1801 ];
1802
1803 // Don't try to use any object cache for SessionManager either.
1804 $GLOBALS['wgSessionCacheType'] = CACHE_NONE;
1805 }
1806
1807 /**
1808 * Add an installation step following the given step.
1809 *
1810 * @param array $callback A valid installation callback array, in this form:
1811 * [ 'name' => 'some-unique-name', 'callback' => [ $obj, 'function' ] ];
1812 * @param string $findStep The step to find. Omit to put the step at the beginning
1813 */
1814 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1815 $this->extraInstallSteps[$findStep][] = $callback;
1816 }
1817
1818 /**
1819 * Disable the time limit for execution.
1820 * Some long-running pages (Install, Upgrade) will want to do this
1821 */
1822 protected function disableTimeLimit() {
1823 Wikimedia\suppressWarnings();
1824 set_time_limit( 0 );
1825 Wikimedia\restoreWarnings();
1826 }
1827 }