b830b7006a6efb97cab8b47daa155408dafc66af
[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 // @phan-suppress-next-line PhanUndeclaredMethod
735 $status->value->insert(
736 'site_stats',
737 [
738 'ss_row_id' => 1,
739 'ss_total_edits' => 0,
740 'ss_good_articles' => 0,
741 'ss_total_pages' => 0,
742 'ss_users' => 0,
743 'ss_active_users' => 0,
744 'ss_images' => 0
745 ],
746 __METHOD__, 'IGNORE'
747 );
748
749 return Status::newGood();
750 }
751
752 /**
753 * Environment check for DB types.
754 * @return bool
755 */
756 protected function envCheckDB() {
757 global $wgLang;
758 /** @var string|null $dbType The user-specified database type */
759 $dbType = $this->getVar( 'wgDBtype' );
760
761 $allNames = [];
762
763 // Messages: config-type-mysql, config-type-postgres, 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 is incompatible with ResourceLoader.
1093 * @return bool
1094 */
1095 protected function envCheckSuhosinMaxValueLength() {
1096 $currentValue = ini_get( 'suhosin.get.max_value_length' );
1097 $minRequired = 2000;
1098 $recommended = 5000;
1099 if ( $currentValue > 0 && $currentValue < $minRequired ) {
1100 $this->showError( 'config-suhosin-max-value-length', $currentValue, $minRequired, $recommended );
1101 return false;
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 Status An object containing an error list. If there were no errors, an associative
1277 * array of information about the extension can be found in $status->value.
1278 */
1279 public function findExtensions( $directory = 'extensions' ) {
1280 switch ( $directory ) {
1281 case 'extensions':
1282 return $this->findExtensionsByType( 'extension', 'extensions' );
1283 case 'skins':
1284 return $this->findExtensionsByType( 'skin', 'skins' );
1285 default:
1286 throw new InvalidArgumentException( "Invalid extension type" );
1287 }
1288 }
1289
1290 /**
1291 * Find extensions or skins, and return an array containing the value for 'Name' for each found
1292 * extension.
1293 *
1294 * @param string $type Either "extension" or "skin"
1295 * @param string $directory Directory to search in, relative to $IP
1296 * @return Status An object containing an error list. If there were no errors, an associative
1297 * array of information about the extension can be found in $status->value.
1298 */
1299 protected function findExtensionsByType( $type = 'extension', $directory = 'extensions' ) {
1300 if ( $this->getVar( 'IP' ) === null ) {
1301 return Status::newGood( [] );
1302 }
1303
1304 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1305 if ( !is_readable( $extDir ) || !is_dir( $extDir ) ) {
1306 return Status::newGood( [] );
1307 }
1308
1309 $dh = opendir( $extDir );
1310 $exts = [];
1311 $status = new Status;
1312 while ( ( $file = readdir( $dh ) ) !== false ) {
1313 // skip non-dirs and hidden directories
1314 if ( !is_dir( "$extDir/$file" ) || $file[0] === '.' ) {
1315 continue;
1316 }
1317 $extStatus = $this->getExtensionInfo( $type, $directory, $file );
1318 if ( $extStatus->isOK() ) {
1319 $exts[$file] = $extStatus->value;
1320 } elseif ( $extStatus->hasMessage( 'config-extension-not-found' ) ) {
1321 // (T225512) The directory is not actually an extension. Downgrade to warning.
1322 $status->warning( 'config-extension-not-found', $file );
1323 } else {
1324 $status->merge( $extStatus );
1325 }
1326 }
1327 closedir( $dh );
1328 uksort( $exts, 'strnatcasecmp' );
1329
1330 $status->value = $exts;
1331
1332 return $status;
1333 }
1334
1335 /**
1336 * @param string $type Either "extension" or "skin"
1337 * @param string $parentRelPath The parent directory relative to $IP
1338 * @param string $name The extension or skin name
1339 * @return Status An object containing an error list. If there were no errors, an associative
1340 * array of information about the extension can be found in $status->value.
1341 */
1342 protected function getExtensionInfo( $type, $parentRelPath, $name ) {
1343 if ( $this->getVar( 'IP' ) === null ) {
1344 throw new Exception( 'Cannot find extensions since the IP variable is not yet set' );
1345 }
1346 if ( $type !== 'extension' && $type !== 'skin' ) {
1347 throw new InvalidArgumentException( "Invalid extension type" );
1348 }
1349 $absDir = $this->getVar( 'IP' ) . "/$parentRelPath/$name";
1350 $relDir = "../$parentRelPath/$name";
1351 if ( !is_dir( $absDir ) ) {
1352 return Status::newFatal( 'config-extension-not-found', $name );
1353 }
1354 $jsonFile = $type . '.json';
1355 $fullJsonFile = "$absDir/$jsonFile";
1356 $isJson = file_exists( $fullJsonFile );
1357 $isPhp = false;
1358 if ( !$isJson ) {
1359 // Only fallback to PHP file if JSON doesn't exist
1360 $fullPhpFile = "$absDir/$name.php";
1361 $isPhp = file_exists( $fullPhpFile );
1362 }
1363 if ( !$isJson && !$isPhp ) {
1364 return Status::newFatal( 'config-extension-not-found', $name );
1365 }
1366
1367 // Extension exists. Now see if there are screenshots
1368 $info = [];
1369 if ( is_dir( "$absDir/screenshots" ) ) {
1370 $paths = glob( "$absDir/screenshots/*.png" );
1371 foreach ( $paths as $path ) {
1372 $info['screenshots'][] = str_replace( $absDir, $relDir, $path );
1373 }
1374 }
1375
1376 if ( $isJson ) {
1377 $jsonStatus = $this->readExtension( $fullJsonFile );
1378 if ( !$jsonStatus->isOK() ) {
1379 return $jsonStatus;
1380 }
1381 $info += $jsonStatus->value;
1382 }
1383
1384 return Status::newGood( $info );
1385 }
1386
1387 /**
1388 * @param string $fullJsonFile
1389 * @param array $extDeps
1390 * @param array $skinDeps
1391 *
1392 * @return Status On success, an array of extension information is in $status->value. On
1393 * failure, the Status object will have an error list.
1394 */
1395 private function readExtension( $fullJsonFile, $extDeps = [], $skinDeps = [] ) {
1396 $load = [
1397 $fullJsonFile => 1
1398 ];
1399 if ( $extDeps ) {
1400 $extDir = $this->getVar( 'IP' ) . '/extensions';
1401 foreach ( $extDeps as $dep ) {
1402 $fname = "$extDir/$dep/extension.json";
1403 if ( !file_exists( $fname ) ) {
1404 return Status::newFatal( 'config-extension-not-found', $dep );
1405 }
1406 $load[$fname] = 1;
1407 }
1408 }
1409 if ( $skinDeps ) {
1410 $skinDir = $this->getVar( 'IP' ) . '/skins';
1411 foreach ( $skinDeps as $dep ) {
1412 $fname = "$skinDir/$dep/skin.json";
1413 if ( !file_exists( $fname ) ) {
1414 return Status::newFatal( 'config-extension-not-found', $dep );
1415 }
1416 $load[$fname] = 1;
1417 }
1418 }
1419 $registry = new ExtensionRegistry();
1420 try {
1421 $info = $registry->readFromQueue( $load );
1422 } catch ( ExtensionDependencyError $e ) {
1423 if ( $e->incompatibleCore || $e->incompatibleSkins
1424 || $e->incompatibleExtensions
1425 ) {
1426 // If something is incompatible with a dependency, we have no real
1427 // option besides skipping it
1428 return Status::newFatal( 'config-extension-dependency',
1429 basename( dirname( $fullJsonFile ) ), $e->getMessage() );
1430 } elseif ( $e->missingExtensions || $e->missingSkins ) {
1431 // There's an extension missing in the dependency tree,
1432 // so add those to the dependency list and try again
1433 $status = $this->readExtension(
1434 $fullJsonFile,
1435 array_merge( $extDeps, $e->missingExtensions ),
1436 array_merge( $skinDeps, $e->missingSkins )
1437 );
1438 if ( !$status->isOK() && !$status->hasMessage( 'config-extension-dependency' ) ) {
1439 $status = Status::newFatal( 'config-extension-dependency',
1440 basename( dirname( $fullJsonFile ) ), $status->getMessage() );
1441 }
1442 return $status;
1443 }
1444 // Some other kind of dependency error?
1445 return Status::newFatal( 'config-extension-dependency',
1446 basename( dirname( $fullJsonFile ) ), $e->getMessage() );
1447 }
1448 $ret = [];
1449 // The order of credits will be the order of $load,
1450 // so the first extension is the one we want to load,
1451 // everything else is a dependency
1452 $i = 0;
1453 foreach ( $info['credits'] as $name => $credit ) {
1454 $i++;
1455 if ( $i == 1 ) {
1456 // Extension we want to load
1457 continue;
1458 }
1459 $type = basename( $credit['path'] ) === 'skin.json' ? 'skins' : 'extensions';
1460 $ret['requires'][$type][] = $credit['name'];
1461 }
1462 $credits = array_values( $info['credits'] )[0];
1463 if ( isset( $credits['url'] ) ) {
1464 $ret['url'] = $credits['url'];
1465 }
1466 $ret['type'] = $credits['type'];
1467
1468 return Status::newGood( $ret );
1469 }
1470
1471 /**
1472 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1473 * but will fall back to another if the default skin is missing and some other one is present
1474 * instead.
1475 *
1476 * @param string[] $skinNames Names of installed skins.
1477 * @return string
1478 */
1479 public function getDefaultSkin( array $skinNames ) {
1480 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1481 if ( !$skinNames || in_array( $defaultSkin, $skinNames ) ) {
1482 return $defaultSkin;
1483 } else {
1484 return $skinNames[0];
1485 }
1486 }
1487
1488 /**
1489 * Installs the auto-detected extensions.
1490 *
1491 * @suppress SecurityCheck-OTHER It thinks $exts/$IP is user controlled but they are not.
1492 * @return Status
1493 */
1494 protected function includeExtensions() {
1495 global $IP;
1496 $exts = $this->getVar( '_Extensions' );
1497 $IP = $this->getVar( 'IP' );
1498
1499 // Marker for DatabaseUpdater::loadExtensions so we don't
1500 // double load extensions
1501 define( 'MW_EXTENSIONS_LOADED', true );
1502
1503 /**
1504 * We need to include DefaultSettings before including extensions to avoid
1505 * warnings about unset variables. However, the only thing we really
1506 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1507 * if the extension has hidden hook registration in $wgExtensionFunctions,
1508 * but we're not opening that can of worms
1509 * @see https://phabricator.wikimedia.org/T28857
1510 */
1511 global $wgAutoloadClasses;
1512 $wgAutoloadClasses = [];
1513 $queue = [];
1514
1515 require "$IP/includes/DefaultSettings.php";
1516
1517 foreach ( $exts as $e ) {
1518 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1519 $queue["$IP/extensions/$e/extension.json"] = 1;
1520 } else {
1521 require_once "$IP/extensions/$e/$e.php";
1522 }
1523 }
1524
1525 $registry = new ExtensionRegistry();
1526 $data = $registry->readFromQueue( $queue );
1527 $wgAutoloadClasses += $data['autoload'];
1528
1529 // @phan-suppress-next-line PhanUndeclaredVariable $wgHooks is set by DefaultSettings
1530 $hooksWeWant = $wgHooks['LoadExtensionSchemaUpdates'] ?? [];
1531
1532 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1533 $hooksWeWant = array_merge_recursive(
1534 $hooksWeWant,
1535 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1536 );
1537 }
1538 // Unset everyone else's hooks. Lord knows what someone might be doing
1539 // in ParserFirstCallInit (see T29171)
1540 $GLOBALS['wgHooks'] = [ 'LoadExtensionSchemaUpdates' => $hooksWeWant ];
1541
1542 return Status::newGood();
1543 }
1544
1545 /**
1546 * Get an array of install steps. Should always be in the format of
1547 * [
1548 * 'name' => 'someuniquename',
1549 * 'callback' => [ $obj, 'method' ],
1550 * ]
1551 * There must be a config-install-$name message defined per step, which will
1552 * be shown on install.
1553 *
1554 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1555 * @return array
1556 */
1557 protected function getInstallSteps( DatabaseInstaller $installer ) {
1558 $coreInstallSteps = [
1559 [ 'name' => 'database', 'callback' => [ $installer, 'setupDatabase' ] ],
1560 [ 'name' => 'tables', 'callback' => [ $installer, 'createTables' ] ],
1561 [ 'name' => 'interwiki', 'callback' => [ $installer, 'populateInterwikiTable' ] ],
1562 [ 'name' => 'stats', 'callback' => [ $this, 'populateSiteStats' ] ],
1563 [ 'name' => 'keys', 'callback' => [ $this, 'generateKeys' ] ],
1564 [ 'name' => 'updates', 'callback' => [ $installer, 'insertUpdateKeys' ] ],
1565 [ 'name' => 'sysop', 'callback' => [ $this, 'createSysop' ] ],
1566 [ 'name' => 'mainpage', 'callback' => [ $this, 'createMainpage' ] ],
1567 ];
1568
1569 // Build the array of install steps starting from the core install list,
1570 // then adding any callbacks that wanted to attach after a given step
1571 foreach ( $coreInstallSteps as $step ) {
1572 $this->installSteps[] = $step;
1573 if ( isset( $this->extraInstallSteps[$step['name']] ) ) {
1574 $this->installSteps = array_merge(
1575 $this->installSteps,
1576 $this->extraInstallSteps[$step['name']]
1577 );
1578 }
1579 }
1580
1581 // Prepend any steps that want to be at the beginning
1582 if ( isset( $this->extraInstallSteps['BEGINNING'] ) ) {
1583 $this->installSteps = array_merge(
1584 $this->extraInstallSteps['BEGINNING'],
1585 $this->installSteps
1586 );
1587 }
1588
1589 // Extensions should always go first, chance to tie into hooks and such
1590 if ( count( $this->getVar( '_Extensions' ) ) ) {
1591 array_unshift( $this->installSteps,
1592 [ 'name' => 'extensions', 'callback' => [ $this, 'includeExtensions' ] ]
1593 );
1594 $this->installSteps[] = [
1595 'name' => 'extension-tables',
1596 'callback' => [ $installer, 'createExtensionTables' ]
1597 ];
1598 }
1599
1600 return $this->installSteps;
1601 }
1602
1603 /**
1604 * Actually perform the installation.
1605 *
1606 * @param callable $startCB A callback array for the beginning of each step
1607 * @param callable $endCB A callback array for the end of each step
1608 *
1609 * @return Status[] Array of Status objects
1610 */
1611 public function performInstallation( $startCB, $endCB ) {
1612 $installResults = [];
1613 $installer = $this->getDBInstaller();
1614 $installer->preInstall();
1615 $steps = $this->getInstallSteps( $installer );
1616 foreach ( $steps as $stepObj ) {
1617 $name = $stepObj['name'];
1618 call_user_func_array( $startCB, [ $name ] );
1619
1620 // Perform the callback step
1621 $status = call_user_func( $stepObj['callback'], $installer );
1622
1623 // Output and save the results
1624 call_user_func( $endCB, $name, $status );
1625 $installResults[$name] = $status;
1626
1627 // If we've hit some sort of fatal, we need to bail.
1628 // Callback already had a chance to do output above.
1629 if ( !$status->isOK() ) {
1630 break;
1631 }
1632 }
1633 if ( $status->isOK() ) {
1634 $this->showMessage(
1635 'config-install-db-success'
1636 );
1637 $this->setVar( '_InstallDone', true );
1638 }
1639
1640 return $installResults;
1641 }
1642
1643 /**
1644 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1645 *
1646 * @return Status
1647 */
1648 public function generateKeys() {
1649 $keys = [ 'wgSecretKey' => 64 ];
1650 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1651 $keys['wgUpgradeKey'] = 16;
1652 }
1653
1654 return $this->doGenerateKeys( $keys );
1655 }
1656
1657 /**
1658 * Generate a secret value for variables using a secure generator.
1659 *
1660 * @param array $keys
1661 * @return Status
1662 */
1663 protected function doGenerateKeys( $keys ) {
1664 $status = Status::newGood();
1665
1666 foreach ( $keys as $name => $length ) {
1667 $secretKey = MWCryptRand::generateHex( $length );
1668 $this->setVar( $name, $secretKey );
1669 }
1670
1671 return $status;
1672 }
1673
1674 /**
1675 * Create the first user account, grant it sysop, bureaucrat and interface-admin rights
1676 *
1677 * @return Status
1678 */
1679 protected function createSysop() {
1680 $name = $this->getVar( '_AdminName' );
1681 $user = User::newFromName( $name );
1682
1683 if ( !$user ) {
1684 // We should've validated this earlier anyway!
1685 return Status::newFatal( 'config-admin-error-user', $name );
1686 }
1687
1688 if ( $user->idForName() == 0 ) {
1689 $user->addToDatabase();
1690
1691 try {
1692 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1693 } catch ( PasswordError $pwe ) {
1694 return Status::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1695 }
1696
1697 $user->addGroup( 'sysop' );
1698 $user->addGroup( 'bureaucrat' );
1699 $user->addGroup( 'interface-admin' );
1700 if ( $this->getVar( '_AdminEmail' ) ) {
1701 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1702 }
1703 $user->saveSettings();
1704
1705 // Update user count
1706 $ssUpdate = SiteStatsUpdate::factory( [ 'users' => 1 ] );
1707 $ssUpdate->doUpdate();
1708 }
1709 $status = Status::newGood();
1710
1711 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1712 $this->subscribeToMediaWikiAnnounce( $status );
1713 }
1714
1715 return $status;
1716 }
1717
1718 /**
1719 * @param Status $s
1720 */
1721 private function subscribeToMediaWikiAnnounce( Status $s ) {
1722 $params = [
1723 'email' => $this->getVar( '_AdminEmail' ),
1724 'language' => 'en',
1725 'digest' => 0
1726 ];
1727
1728 // Mailman doesn't support as many languages as we do, so check to make
1729 // sure their selected language is available
1730 $myLang = $this->getVar( '_UserLang' );
1731 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages ) ) {
1732 $myLang = $myLang == 'pt-br' ? 'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1733 $params['language'] = $myLang;
1734 }
1735
1736 if ( MWHttpRequest::canMakeRequests() ) {
1737 $res = MWHttpRequest::factory( $this->mediaWikiAnnounceUrl,
1738 [ 'method' => 'POST', 'postData' => $params ], __METHOD__ )->execute();
1739 if ( !$res->isOK() ) {
1740 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1741 }
1742 } else {
1743 $s->warning( 'config-install-subscribe-notpossible' );
1744 }
1745 }
1746
1747 /**
1748 * Insert Main Page with default content.
1749 *
1750 * @param DatabaseInstaller $installer
1751 * @return Status
1752 */
1753 protected function createMainpage( DatabaseInstaller $installer ) {
1754 $status = Status::newGood();
1755 $title = Title::newMainPage();
1756 if ( $title->exists() ) {
1757 $status->warning( 'config-install-mainpage-exists' );
1758 return $status;
1759 }
1760 try {
1761 $page = WikiPage::factory( $title );
1762 $content = new WikitextContent(
1763 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1764 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1765 );
1766
1767 $status = $page->doEditContent( $content,
1768 '',
1769 EDIT_NEW,
1770 false,
1771 User::newFromName( 'MediaWiki default' )
1772 );
1773 } catch ( Exception $e ) {
1774 // using raw, because $wgShowExceptionDetails can not be set yet
1775 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1776 }
1777
1778 return $status;
1779 }
1780
1781 /**
1782 * Override the necessary bits of the config to run an installation.
1783 */
1784 public static function overrideConfig() {
1785 // Use PHP's built-in session handling, since MediaWiki's
1786 // SessionHandler can't work before we have an object cache set up.
1787 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
1788 define( 'MW_NO_SESSION_HANDLER', 1 );
1789 }
1790
1791 // Don't access the database
1792 $GLOBALS['wgUseDatabaseMessages'] = false;
1793 // Don't cache langconv tables
1794 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE;
1795 // Debug-friendly
1796 $GLOBALS['wgShowExceptionDetails'] = true;
1797 $GLOBALS['wgShowHostnames'] = true;
1798 // Don't break forms
1799 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1800
1801 // Allow multiple ob_flush() calls
1802 $GLOBALS['wgDisableOutputCompression'] = true;
1803
1804 // Use a sensible cookie prefix (not my_wiki)
1805 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1806
1807 // Some of the environment checks make shell requests, remove limits
1808 $GLOBALS['wgMaxShellMemory'] = 0;
1809
1810 // Override the default CookieSessionProvider with a dummy
1811 // implementation that won't stomp on PHP's cookies.
1812 $GLOBALS['wgSessionProviders'] = [
1813 [
1814 'class' => InstallerSessionProvider::class,
1815 'args' => [ [
1816 'priority' => 1,
1817 ] ]
1818 ]
1819 ];
1820
1821 // Don't try to use any object cache for SessionManager either.
1822 $GLOBALS['wgSessionCacheType'] = CACHE_NONE;
1823 }
1824
1825 /**
1826 * Add an installation step following the given step.
1827 *
1828 * @param array $callback A valid installation callback array, in this form:
1829 * [ 'name' => 'some-unique-name', 'callback' => [ $obj, 'function' ] ];
1830 * @param string $findStep The step to find. Omit to put the step at the beginning
1831 */
1832 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1833 $this->extraInstallSteps[$findStep][] = $callback;
1834 }
1835
1836 /**
1837 * Disable the time limit for execution.
1838 * Some long-running pages (Install, Upgrade) will want to do this
1839 */
1840 protected function disableTimeLimit() {
1841 Wikimedia\suppressWarnings();
1842 set_time_limit( 0 );
1843 Wikimedia\restoreWarnings();
1844 }
1845 }