029f67d57a362c6bc7774763aed1b97bb70be966
[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 'oracle',
109 'mssql',
110 'sqlite',
111 ];
112
113 /**
114 * A list of environment check methods called by doEnvironmentChecks().
115 * These may output warnings using showMessage(), and/or abort the
116 * installation process by returning false.
117 *
118 * For the WebInstaller these are only called on the Welcome page,
119 * if these methods have side-effects that should affect later page loads
120 * (as well as the generated stylesheet), use envPreps instead.
121 *
122 * @var array
123 */
124 protected $envChecks = [
125 'envCheckDB',
126 'envCheckBrokenXML',
127 'envCheckPCRE',
128 'envCheckMemory',
129 'envCheckCache',
130 'envCheckModSecurity',
131 'envCheckDiff3',
132 'envCheckGraphics',
133 'envCheckGit',
134 'envCheckServer',
135 'envCheckPath',
136 'envCheckShellLocale',
137 'envCheckUploadsDirectory',
138 'envCheckLibicu',
139 'envCheckSuhosinMaxValueLength',
140 'envCheck64Bit',
141 ];
142
143 /**
144 * A list of environment preparation methods called by doEnvironmentPreps().
145 *
146 * @var array
147 */
148 protected $envPreps = [
149 'envPrepServer',
150 'envPrepPath',
151 ];
152
153 /**
154 * MediaWiki configuration globals that will eventually be passed through
155 * to LocalSettings.php. The names only are given here, the defaults
156 * typically come from DefaultSettings.php.
157 *
158 * @var array
159 */
160 protected $defaultVarNames = [
161 'wgSitename',
162 'wgPasswordSender',
163 'wgLanguageCode',
164 'wgRightsIcon',
165 'wgRightsText',
166 'wgRightsUrl',
167 'wgEnableEmail',
168 'wgEnableUserEmail',
169 'wgEnotifUserTalk',
170 'wgEnotifWatchlist',
171 'wgEmailAuthentication',
172 'wgDBname',
173 'wgDBtype',
174 'wgDiff3',
175 'wgImageMagickConvertCommand',
176 'wgGitBin',
177 'IP',
178 'wgScriptPath',
179 'wgMetaNamespace',
180 'wgDeletedDirectory',
181 'wgEnableUploads',
182 'wgShellLocale',
183 'wgSecretKey',
184 'wgUseInstantCommons',
185 'wgUpgradeKey',
186 'wgDefaultSkin',
187 'wgPingback',
188 ];
189
190 /**
191 * Variables that are stored alongside globals, and are used for any
192 * configuration of the installation process aside from the MediaWiki
193 * configuration. Map of names to defaults.
194 *
195 * @var array
196 */
197 protected $internalDefaults = [
198 '_UserLang' => 'en',
199 '_Environment' => false,
200 '_RaiseMemory' => false,
201 '_UpgradeDone' => false,
202 '_InstallDone' => false,
203 '_Caches' => [],
204 '_InstallPassword' => '',
205 '_SameAccount' => true,
206 '_CreateDBAccount' => false,
207 '_NamespaceType' => 'site-name',
208 '_AdminName' => '', // will be set later, when the user selects language
209 '_AdminPassword' => '',
210 '_AdminPasswordConfirm' => '',
211 '_AdminEmail' => '',
212 '_Subscribe' => false,
213 '_SkipOptional' => 'continue',
214 '_RightsProfile' => 'wiki',
215 '_LicenseCode' => 'none',
216 '_CCDone' => false,
217 '_Extensions' => [],
218 '_Skins' => [],
219 '_MemCachedServers' => '',
220 '_UpgradeKeySupplied' => false,
221 '_ExistingDBSettings' => false,
222
223 // $wgLogo is probably wrong (T50084); set something that will work.
224 // Single quotes work fine here, as LocalSettingsGenerator outputs this unescaped.
225 'wgLogo' => '$wgResourceBasePath/resources/assets/wiki.png',
226 'wgAuthenticationTokenVersion' => 1,
227 ];
228
229 /**
230 * The actual list of installation steps. This will be initialized by getInstallSteps()
231 *
232 * @var array
233 */
234 private $installSteps = [];
235
236 /**
237 * Extra steps for installation, for things like DatabaseInstallers to modify
238 *
239 * @var array
240 */
241 protected $extraInstallSteps = [];
242
243 /**
244 * Known object cache types and the functions used to test for their existence.
245 *
246 * @var array
247 */
248 protected $objectCaches = [
249 'apc' => 'apc_fetch',
250 'apcu' => 'apcu_fetch',
251 'wincache' => 'wincache_ucache_get'
252 ];
253
254 /**
255 * User rights profiles.
256 *
257 * @var array
258 */
259 public $rightsProfiles = [
260 'wiki' => [],
261 'no-anon' => [
262 '*' => [ 'edit' => false ]
263 ],
264 'fishbowl' => [
265 '*' => [
266 'createaccount' => false,
267 'edit' => false,
268 ],
269 ],
270 'private' => [
271 '*' => [
272 'createaccount' => false,
273 'edit' => false,
274 'read' => false,
275 ],
276 ],
277 ];
278
279 /**
280 * License types.
281 *
282 * @var array
283 */
284 public $licenses = [
285 'cc-by' => [
286 'url' => 'https://creativecommons.org/licenses/by/4.0/',
287 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by.png',
288 ],
289 'cc-by-sa' => [
290 'url' => 'https://creativecommons.org/licenses/by-sa/4.0/',
291 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-sa.png',
292 ],
293 'cc-by-nc-sa' => [
294 'url' => 'https://creativecommons.org/licenses/by-nc-sa/4.0/',
295 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-nc-sa.png',
296 ],
297 'cc-0' => [
298 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
299 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-0.png',
300 ],
301 'gfdl' => [
302 'url' => 'https://www.gnu.org/copyleft/fdl.html',
303 'icon' => '$wgResourceBasePath/resources/assets/licenses/gnu-fdl.png',
304 ],
305 'none' => [
306 'url' => '',
307 'icon' => '',
308 'text' => ''
309 ],
310 'cc-choose' => [
311 // Details will be filled in by the selector.
312 'url' => '',
313 'icon' => '',
314 'text' => '',
315 ],
316 ];
317
318 /**
319 * URL to mediawiki-announce subscription
320 */
321 protected $mediaWikiAnnounceUrl =
322 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
323
324 /**
325 * Supported language codes for Mailman
326 */
327 protected $mediaWikiAnnounceLanguages = [
328 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
329 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
330 'sl', 'sr', 'sv', 'tr', 'uk'
331 ];
332
333 /**
334 * UI interface for displaying a short message
335 * The parameters are like parameters to wfMessage().
336 * The messages will be in wikitext format, which will be converted to an
337 * output format such as HTML or text before being sent to the user.
338 * @param string $msg
339 */
340 abstract public function showMessage( $msg /*, ... */ );
341
342 /**
343 * Same as showMessage(), but for displaying errors
344 * @param string $msg
345 */
346 abstract public function showError( $msg /*, ... */ );
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 list( $pcreVersion ) = explode( ' ', PCRE_VERSION, 2 );
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 global $wgParser;
690
691 try {
692 $out = $wgParser->parse( $text, $this->parserTitle, $this->parserOptions, $lineStart );
693 $html = $out->getText( [
694 'enableSectionEditLinks' => false,
695 'unwrap' => true,
696 ] );
697 } catch ( MediaWiki\Services\ServiceDisabledException $e ) {
698 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
699 }
700
701 return $html;
702 }
703
704 /**
705 * @return ParserOptions
706 */
707 public function getParserOptions() {
708 return $this->parserOptions;
709 }
710
711 public function disableLinkPopups() {
712 $this->parserOptions->setExternalLinkTarget( false );
713 }
714
715 public function restoreLinkPopups() {
716 global $wgExternalLinkTarget;
717 $this->parserOptions->setExternalLinkTarget( $wgExternalLinkTarget );
718 }
719
720 /**
721 * Install step which adds a row to the site_stats table with appropriate
722 * initial values.
723 *
724 * @param DatabaseInstaller $installer
725 *
726 * @return Status
727 */
728 public function populateSiteStats( DatabaseInstaller $installer ) {
729 $status = $installer->getConnection();
730 if ( !$status->isOK() ) {
731 return $status;
732 }
733 $status->value->insert(
734 'site_stats',
735 [
736 'ss_row_id' => 1,
737 'ss_total_edits' => 0,
738 'ss_good_articles' => 0,
739 'ss_total_pages' => 0,
740 'ss_users' => 0,
741 'ss_active_users' => 0,
742 'ss_images' => 0
743 ],
744 __METHOD__, 'IGNORE'
745 );
746
747 return Status::newGood();
748 }
749
750 /**
751 * Environment check for DB types.
752 * @return bool
753 */
754 protected function envCheckDB() {
755 global $wgLang;
756
757 $allNames = [];
758
759 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
760 // config-type-sqlite
761 foreach ( self::getDBTypes() as $name ) {
762 $allNames[] = wfMessage( "config-type-$name" )->text();
763 }
764
765 $databases = $this->getCompiledDBs();
766
767 $databases = array_flip( $databases );
768 foreach ( array_keys( $databases ) as $db ) {
769 $installer = $this->getDBInstaller( $db );
770 $status = $installer->checkPrerequisites();
771 if ( !$status->isGood() ) {
772 $this->showStatusMessage( $status );
773 }
774 if ( !$status->isOK() ) {
775 unset( $databases[$db] );
776 }
777 }
778 $databases = array_flip( $databases );
779 if ( !$databases ) {
780 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
781
782 // @todo FIXME: This only works for the web installer!
783 return false;
784 }
785
786 return true;
787 }
788
789 /**
790 * Some versions of libxml+PHP break < and > encoding horribly
791 * @return bool
792 */
793 protected function envCheckBrokenXML() {
794 $test = new PhpXmlBugTester();
795 if ( !$test->ok ) {
796 $this->showError( 'config-brokenlibxml' );
797
798 return false;
799 }
800
801 return true;
802 }
803
804 /**
805 * Environment check for the PCRE module.
806 *
807 * @note If this check were to fail, the parser would
808 * probably throw an exception before the result
809 * of this check is shown to the user.
810 * @return bool
811 */
812 protected function envCheckPCRE() {
813 Wikimedia\suppressWarnings();
814 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
815 // Need to check for \p support too, as PCRE can be compiled
816 // with utf8 support, but not unicode property support.
817 // check that \p{Zs} (space separators) matches
818 // U+3000 (Ideographic space)
819 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\u{3000}-" );
820 Wikimedia\restoreWarnings();
821 if ( $regexd != '--' || $regexprop != '--' ) {
822 $this->showError( 'config-pcre-no-utf8' );
823
824 return false;
825 }
826
827 return true;
828 }
829
830 /**
831 * Environment check for available memory.
832 * @return bool
833 */
834 protected function envCheckMemory() {
835 $limit = ini_get( 'memory_limit' );
836
837 if ( !$limit || $limit == -1 ) {
838 return true;
839 }
840
841 $n = wfShorthandToInteger( $limit );
842
843 if ( $n < $this->minMemorySize * 1024 * 1024 ) {
844 $newLimit = "{$this->minMemorySize}M";
845
846 if ( ini_set( "memory_limit", $newLimit ) === false ) {
847 $this->showMessage( 'config-memory-bad', $limit );
848 } else {
849 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
850 $this->setVar( '_RaiseMemory', true );
851 }
852 }
853
854 return true;
855 }
856
857 /**
858 * Environment check for compiled object cache types.
859 */
860 protected function envCheckCache() {
861 $caches = [];
862 foreach ( $this->objectCaches as $name => $function ) {
863 if ( function_exists( $function ) ) {
864 $caches[$name] = true;
865 }
866 }
867
868 if ( !$caches ) {
869 $key = 'config-no-cache-apcu';
870 $this->showMessage( $key );
871 }
872
873 $this->setVar( '_Caches', $caches );
874 }
875
876 /**
877 * Scare user to death if they have mod_security or mod_security2
878 * @return bool
879 */
880 protected function envCheckModSecurity() {
881 if ( self::apacheModulePresent( 'mod_security' )
882 || self::apacheModulePresent( 'mod_security2' ) ) {
883 $this->showMessage( 'config-mod-security' );
884 }
885
886 return true;
887 }
888
889 /**
890 * Search for GNU diff3.
891 * @return bool
892 */
893 protected function envCheckDiff3() {
894 $names = [ "gdiff3", "diff3" ];
895 if ( wfIsWindows() ) {
896 $names[] = 'diff3.exe';
897 }
898 $versionInfo = [ '--version', 'GNU diffutils' ];
899
900 $diff3 = ExecutableFinder::findInDefaultPaths( $names, $versionInfo );
901
902 if ( $diff3 ) {
903 $this->setVar( 'wgDiff3', $diff3 );
904 } else {
905 $this->setVar( 'wgDiff3', false );
906 $this->showMessage( 'config-diff3-bad' );
907 }
908
909 return true;
910 }
911
912 /**
913 * Environment check for ImageMagick and GD.
914 * @return bool
915 */
916 protected function envCheckGraphics() {
917 $names = wfIsWindows() ? 'convert.exe' : 'convert';
918 $versionInfo = [ '-version', 'ImageMagick' ];
919 $convert = ExecutableFinder::findInDefaultPaths( $names, $versionInfo );
920
921 $this->setVar( 'wgImageMagickConvertCommand', '' );
922 if ( $convert ) {
923 $this->setVar( 'wgImageMagickConvertCommand', $convert );
924 $this->showMessage( 'config-imagemagick', $convert );
925
926 return true;
927 } elseif ( function_exists( 'imagejpeg' ) ) {
928 $this->showMessage( 'config-gd' );
929 } else {
930 $this->showMessage( 'config-no-scaling' );
931 }
932
933 return true;
934 }
935
936 /**
937 * Search for git.
938 *
939 * @since 1.22
940 * @return bool
941 */
942 protected function envCheckGit() {
943 $names = wfIsWindows() ? 'git.exe' : 'git';
944 $versionInfo = [ '--version', 'git version' ];
945
946 $git = ExecutableFinder::findInDefaultPaths( $names, $versionInfo );
947
948 if ( $git ) {
949 $this->setVar( 'wgGitBin', $git );
950 $this->showMessage( 'config-git', $git );
951 } else {
952 $this->setVar( 'wgGitBin', false );
953 $this->showMessage( 'config-git-bad' );
954 }
955
956 return true;
957 }
958
959 /**
960 * Environment check to inform user which server we've assumed.
961 *
962 * @return bool
963 */
964 protected function envCheckServer() {
965 $server = $this->envGetDefaultServer();
966 if ( $server !== null ) {
967 $this->showMessage( 'config-using-server', $server );
968 }
969 return true;
970 }
971
972 /**
973 * Environment check to inform user which paths we've assumed.
974 *
975 * @return bool
976 */
977 protected function envCheckPath() {
978 $this->showMessage(
979 'config-using-uri',
980 $this->getVar( 'wgServer' ),
981 $this->getVar( 'wgScriptPath' )
982 );
983 return true;
984 }
985
986 /**
987 * Environment check for preferred locale in shell
988 * @return bool
989 */
990 protected function envCheckShellLocale() {
991 $os = php_uname( 's' );
992 $supported = [ 'Linux', 'SunOS', 'HP-UX', 'Darwin' ]; # Tested these
993
994 if ( !in_array( $os, $supported ) ) {
995 return true;
996 }
997
998 if ( Shell::isDisabled() ) {
999 return true;
1000 }
1001
1002 # Get a list of available locales.
1003 $result = Shell::command( '/usr/bin/locale', '-a' )
1004 ->execute();
1005
1006 if ( $result->getExitCode() != 0 ) {
1007 return true;
1008 }
1009
1010 $lines = $result->getStdout();
1011 $lines = array_map( 'trim', explode( "\n", $lines ) );
1012 $candidatesByLocale = [];
1013 $candidatesByLang = [];
1014 foreach ( $lines as $line ) {
1015 if ( $line === '' ) {
1016 continue;
1017 }
1018
1019 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1020 continue;
1021 }
1022
1023 list( , $lang, , , ) = $m;
1024
1025 $candidatesByLocale[$m[0]] = $m;
1026 $candidatesByLang[$lang][] = $m;
1027 }
1028
1029 # Try the current value of LANG.
1030 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1031 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1032
1033 return true;
1034 }
1035
1036 # Try the most common ones.
1037 $commonLocales = [ 'C.UTF-8', 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' ];
1038 foreach ( $commonLocales as $commonLocale ) {
1039 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1040 $this->setVar( 'wgShellLocale', $commonLocale );
1041
1042 return true;
1043 }
1044 }
1045
1046 # Is there an available locale in the Wiki's language?
1047 $wikiLang = $this->getVar( 'wgLanguageCode' );
1048
1049 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1050 $m = reset( $candidatesByLang[$wikiLang] );
1051 $this->setVar( 'wgShellLocale', $m[0] );
1052
1053 return true;
1054 }
1055
1056 # Are there any at all?
1057 if ( count( $candidatesByLocale ) ) {
1058 $m = reset( $candidatesByLocale );
1059 $this->setVar( 'wgShellLocale', $m[0] );
1060
1061 return true;
1062 }
1063
1064 # Give up.
1065 return true;
1066 }
1067
1068 /**
1069 * Environment check for the permissions of the uploads directory
1070 * @return bool
1071 */
1072 protected function envCheckUploadsDirectory() {
1073 global $IP;
1074
1075 $dir = $IP . '/images/';
1076 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1077 $safe = !$this->dirIsExecutable( $dir, $url );
1078
1079 if ( !$safe ) {
1080 $this->showMessage( 'config-uploads-not-safe', $dir );
1081 }
1082
1083 return true;
1084 }
1085
1086 /**
1087 * Checks if suhosin.get.max_value_length is set, and if so generate
1088 * a warning because it decreases ResourceLoader performance.
1089 * @return bool
1090 */
1091 protected function envCheckSuhosinMaxValueLength() {
1092 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1093 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1094 // Only warn if the value is below the sane 1024
1095 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1096 }
1097
1098 return true;
1099 }
1100
1101 /**
1102 * Checks if we're running on 64 bit or not. 32 bit is becoming increasingly
1103 * hard to support, so let's at least warn people.
1104 *
1105 * @return bool
1106 */
1107 protected function envCheck64Bit() {
1108 if ( PHP_INT_SIZE == 4 ) {
1109 $this->showMessage( 'config-using-32bit' );
1110 }
1111
1112 return true;
1113 }
1114
1115 /**
1116 * Check the libicu version
1117 */
1118 protected function envCheckLibicu() {
1119 /**
1120 * This needs to be updated something that the latest libicu
1121 * will properly normalize. This normalization was found at
1122 * https://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1123 * Note that we use the hex representation to create the code
1124 * points in order to avoid any Unicode-destroying during transit.
1125 */
1126 $not_normal_c = "\u{FA6C}";
1127 $normal_c = "\u{242EE}";
1128
1129 $useNormalizer = 'php';
1130 $needsUpdate = false;
1131
1132 if ( function_exists( 'normalizer_normalize' ) ) {
1133 $useNormalizer = 'intl';
1134 $intl = normalizer_normalize( $not_normal_c, Normalizer::FORM_C );
1135 if ( $intl !== $normal_c ) {
1136 $needsUpdate = true;
1137 }
1138 }
1139
1140 // Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
1141 if ( $useNormalizer === 'php' ) {
1142 $this->showMessage( 'config-unicode-pure-php-warning' );
1143 } else {
1144 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1145 if ( $needsUpdate ) {
1146 $this->showMessage( 'config-unicode-update-warning' );
1147 }
1148 }
1149 }
1150
1151 /**
1152 * Environment prep for the server hostname.
1153 */
1154 protected function envPrepServer() {
1155 $server = $this->envGetDefaultServer();
1156 if ( $server !== null ) {
1157 $this->setVar( 'wgServer', $server );
1158 }
1159 }
1160
1161 /**
1162 * Helper function to be called from envPrepServer()
1163 * @return string
1164 */
1165 abstract protected function envGetDefaultServer();
1166
1167 /**
1168 * Environment prep for setting $IP and $wgScriptPath.
1169 */
1170 protected function envPrepPath() {
1171 global $IP;
1172 $IP = dirname( dirname( __DIR__ ) );
1173 $this->setVar( 'IP', $IP );
1174 }
1175
1176 /**
1177 * Checks if scripts located in the given directory can be executed via the given URL.
1178 *
1179 * Used only by environment checks.
1180 * @param string $dir
1181 * @param string $url
1182 * @return bool|int|string
1183 */
1184 public function dirIsExecutable( $dir, $url ) {
1185 $scriptTypes = [
1186 'php' => [
1187 "<?php echo 'ex' . 'ec';",
1188 "#!/var/env php\n<?php echo 'ex' . 'ec';",
1189 ],
1190 ];
1191
1192 // it would be good to check other popular languages here, but it'll be slow.
1193
1194 Wikimedia\suppressWarnings();
1195
1196 foreach ( $scriptTypes as $ext => $contents ) {
1197 foreach ( $contents as $source ) {
1198 $file = 'exectest.' . $ext;
1199
1200 if ( !file_put_contents( $dir . $file, $source ) ) {
1201 break;
1202 }
1203
1204 try {
1205 $text = Http::get( $url . $file, [ 'timeout' => 3 ], __METHOD__ );
1206 } catch ( Exception $e ) {
1207 // Http::get throws with allow_url_fopen = false and no curl extension.
1208 $text = null;
1209 }
1210 unlink( $dir . $file );
1211
1212 if ( $text == 'exec' ) {
1213 Wikimedia\restoreWarnings();
1214
1215 return $ext;
1216 }
1217 }
1218 }
1219
1220 Wikimedia\restoreWarnings();
1221
1222 return false;
1223 }
1224
1225 /**
1226 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1227 *
1228 * @param string $moduleName Name of module to check.
1229 * @return bool
1230 */
1231 public static function apacheModulePresent( $moduleName ) {
1232 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1233 return true;
1234 }
1235 // try it the hard way
1236 ob_start();
1237 phpinfo( INFO_MODULES );
1238 $info = ob_get_clean();
1239
1240 return strpos( $info, $moduleName ) !== false;
1241 }
1242
1243 /**
1244 * ParserOptions are constructed before we determined the language, so fix it
1245 *
1246 * @param Language $lang
1247 */
1248 public function setParserLanguage( $lang ) {
1249 $this->parserOptions->setTargetLanguage( $lang );
1250 $this->parserOptions->setUserLang( $lang );
1251 }
1252
1253 /**
1254 * Overridden by WebInstaller to provide lastPage parameters.
1255 * @param string $page
1256 * @return string
1257 */
1258 protected function getDocUrl( $page ) {
1259 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1260 }
1261
1262 /**
1263 * Find extensions or skins in a subdirectory of $IP.
1264 * Returns an array containing the value for 'Name' for each found extension.
1265 *
1266 * @param string $directory Directory to search in, relative to $IP, must be either "extensions"
1267 * or "skins"
1268 * @return array [ $extName => [ 'screenshots' => [ '...' ] ]
1269 */
1270 public function findExtensions( $directory = 'extensions' ) {
1271 switch ( $directory ) {
1272 case 'extensions':
1273 return $this->findExtensionsByType( 'extension', 'extensions' );
1274 case 'skins':
1275 return $this->findExtensionsByType( 'skin', 'skins' );
1276 default:
1277 throw new InvalidArgumentException( "Invalid extension type" );
1278 }
1279 }
1280
1281 /**
1282 * Find extensions or skins, and return an array containing the value for 'Name' for each found
1283 * extension.
1284 *
1285 * @param string $type Either "extension" or "skin"
1286 * @param string $directory Directory to search in, relative to $IP
1287 * @return array [ $extName => [ 'screenshots' => [ '...' ] ]
1288 */
1289 protected function findExtensionsByType( $type = 'extension', $directory = 'extensions' ) {
1290 if ( $this->getVar( 'IP' ) === null ) {
1291 return [];
1292 }
1293
1294 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1295 if ( !is_readable( $extDir ) || !is_dir( $extDir ) ) {
1296 return [];
1297 }
1298
1299 $dh = opendir( $extDir );
1300 $exts = [];
1301 while ( ( $file = readdir( $dh ) ) !== false ) {
1302 if ( !is_dir( "$extDir/$file" ) ) {
1303 continue;
1304 }
1305 $status = $this->getExtensionInfo( $type, $directory, $file );
1306 if ( $status->isOK() ) {
1307 $exts[$file] = $status->value;
1308 }
1309 }
1310 closedir( $dh );
1311 uksort( $exts, 'strnatcasecmp' );
1312
1313 return $exts;
1314 }
1315
1316 /**
1317 * @param string $type Either "extension" or "skin"
1318 * @param string $parentRelPath The parent directory relative to $IP
1319 * @param string $name The extension or skin name
1320 * @return Status An object containing an error list. If there were no errors, an associative
1321 * array of information about the extension can be found in $status->value.
1322 */
1323 protected function getExtensionInfo( $type, $parentRelPath, $name ) {
1324 if ( $this->getVar( 'IP' ) === null ) {
1325 throw new Exception( 'Cannot find extensions since the IP variable is not yet set' );
1326 }
1327 if ( $type !== 'extension' && $type !== 'skin' ) {
1328 throw new InvalidArgumentException( "Invalid extension type" );
1329 }
1330 $absDir = $this->getVar( 'IP' ) . "/$parentRelPath/$name";
1331 $relDir = "../$parentRelPath/$name";
1332 if ( !is_dir( $absDir ) ) {
1333 return Status::newFatal( 'config-extension-not-found', $name );
1334 }
1335 $jsonFile = $type . '.json';
1336 $fullJsonFile = "$absDir/$jsonFile";
1337 $isJson = file_exists( $fullJsonFile );
1338 $isPhp = false;
1339 if ( !$isJson ) {
1340 // Only fallback to PHP file if JSON doesn't exist
1341 $fullPhpFile = "$absDir/$name.php";
1342 $isPhp = file_exists( $fullPhpFile );
1343 }
1344 if ( !$isJson && !$isPhp ) {
1345 return Status::newFatal( 'config-extension-not-found', $name );
1346 }
1347
1348 // Extension exists. Now see if there are screenshots
1349 $info = [];
1350 if ( is_dir( "$absDir/screenshots" ) ) {
1351 $paths = glob( "$absDir/screenshots/*.png" );
1352 foreach ( $paths as $path ) {
1353 $info['screenshots'][] = str_replace( $absDir, $relDir, $path );
1354 }
1355 }
1356
1357 if ( $isJson ) {
1358 $jsonStatus = $this->readExtension( $fullJsonFile );
1359 if ( !$jsonStatus->isOK() ) {
1360 return $jsonStatus;
1361 }
1362 $info += $jsonStatus->value;
1363 }
1364
1365 return Status::newGood( $info );
1366 }
1367
1368 /**
1369 * @param string $fullJsonFile
1370 * @param array $extDeps
1371 * @param array $skinDeps
1372 *
1373 * @return Status On success, an array of extension information is in $status->value. On
1374 * failure, the Status object will have an error list.
1375 */
1376 private function readExtension( $fullJsonFile, $extDeps = [], $skinDeps = [] ) {
1377 $load = [
1378 $fullJsonFile => 1
1379 ];
1380 if ( $extDeps ) {
1381 $extDir = $this->getVar( 'IP' ) . '/extensions';
1382 foreach ( $extDeps as $dep ) {
1383 $fname = "$extDir/$dep/extension.json";
1384 if ( !file_exists( $fname ) ) {
1385 return Status::newFatal( 'config-extension-not-found', $dep );
1386 }
1387 $load[$fname] = 1;
1388 }
1389 }
1390 if ( $skinDeps ) {
1391 $skinDir = $this->getVar( 'IP' ) . '/skins';
1392 foreach ( $skinDeps as $dep ) {
1393 $fname = "$skinDir/$dep/skin.json";
1394 if ( !file_exists( $fname ) ) {
1395 return Status::newFatal( 'config-extension-not-found', $dep );
1396 }
1397 $load[$fname] = 1;
1398 }
1399 }
1400 $registry = new ExtensionRegistry();
1401 try {
1402 $info = $registry->readFromQueue( $load );
1403 } catch ( ExtensionDependencyError $e ) {
1404 if ( $e->incompatibleCore || $e->incompatibleSkins
1405 || $e->incompatibleExtensions
1406 ) {
1407 // If something is incompatible with a dependency, we have no real
1408 // option besides skipping it
1409 return Status::newFatal( 'config-extension-dependency',
1410 basename( dirname( $fullJsonFile ) ), $e->getMessage() );
1411 } elseif ( $e->missingExtensions || $e->missingSkins ) {
1412 // There's an extension missing in the dependency tree,
1413 // so add those to the dependency list and try again
1414 return $this->readExtension(
1415 $fullJsonFile,
1416 array_merge( $extDeps, $e->missingExtensions ),
1417 array_merge( $skinDeps, $e->missingSkins )
1418 );
1419 }
1420 // Some other kind of dependency error?
1421 return Status::newFatal( 'config-extension-dependency',
1422 basename( dirname( $fullJsonFile ) ), $e->getMessage() );
1423 }
1424 $ret = [];
1425 // The order of credits will be the order of $load,
1426 // so the first extension is the one we want to load,
1427 // everything else is a dependency
1428 $i = 0;
1429 foreach ( $info['credits'] as $name => $credit ) {
1430 $i++;
1431 if ( $i == 1 ) {
1432 // Extension we want to load
1433 continue;
1434 }
1435 $type = basename( $credit['path'] ) === 'skin.json' ? 'skins' : 'extensions';
1436 $ret['requires'][$type][] = $credit['name'];
1437 }
1438 $credits = array_values( $info['credits'] )[0];
1439 if ( isset( $credits['url'] ) ) {
1440 $ret['url'] = $credits['url'];
1441 }
1442 $ret['type'] = $credits['type'];
1443
1444 return Status::newGood( $ret );
1445 }
1446
1447 /**
1448 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1449 * but will fall back to another if the default skin is missing and some other one is present
1450 * instead.
1451 *
1452 * @param string[] $skinNames Names of installed skins.
1453 * @return string
1454 */
1455 public function getDefaultSkin( array $skinNames ) {
1456 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1457 if ( !$skinNames || in_array( $defaultSkin, $skinNames ) ) {
1458 return $defaultSkin;
1459 } else {
1460 return $skinNames[0];
1461 }
1462 }
1463
1464 /**
1465 * Installs the auto-detected extensions.
1466 *
1467 * @return Status
1468 */
1469 protected function includeExtensions() {
1470 global $IP;
1471 $exts = $this->getVar( '_Extensions' );
1472 $IP = $this->getVar( 'IP' );
1473
1474 // Marker for DatabaseUpdater::loadExtensions so we don't
1475 // double load extensions
1476 define( 'MW_EXTENSIONS_LOADED', true );
1477
1478 /**
1479 * We need to include DefaultSettings before including extensions to avoid
1480 * warnings about unset variables. However, the only thing we really
1481 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1482 * if the extension has hidden hook registration in $wgExtensionFunctions,
1483 * but we're not opening that can of worms
1484 * @see https://phabricator.wikimedia.org/T28857
1485 */
1486 global $wgAutoloadClasses;
1487 $wgAutoloadClasses = [];
1488 $queue = [];
1489
1490 require "$IP/includes/DefaultSettings.php";
1491
1492 foreach ( $exts as $e ) {
1493 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1494 $queue["$IP/extensions/$e/extension.json"] = 1;
1495 } else {
1496 require_once "$IP/extensions/$e/$e.php";
1497 }
1498 }
1499
1500 $registry = new ExtensionRegistry();
1501 $data = $registry->readFromQueue( $queue );
1502 $wgAutoloadClasses += $data['autoload'];
1503
1504 /** @suppress PhanUndeclaredVariable $wgHooks is set by DefaultSettings */
1505 $hooksWeWant = $wgHooks['LoadExtensionSchemaUpdates'] ?? [];
1506
1507 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1508 $hooksWeWant = array_merge_recursive(
1509 $hooksWeWant,
1510 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1511 );
1512 }
1513 // Unset everyone else's hooks. Lord knows what someone might be doing
1514 // in ParserFirstCallInit (see T29171)
1515 $GLOBALS['wgHooks'] = [ 'LoadExtensionSchemaUpdates' => $hooksWeWant ];
1516
1517 return Status::newGood();
1518 }
1519
1520 /**
1521 * Get an array of install steps. Should always be in the format of
1522 * [
1523 * 'name' => 'someuniquename',
1524 * 'callback' => [ $obj, 'method' ],
1525 * ]
1526 * There must be a config-install-$name message defined per step, which will
1527 * be shown on install.
1528 *
1529 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1530 * @return array
1531 */
1532 protected function getInstallSteps( DatabaseInstaller $installer ) {
1533 $coreInstallSteps = [
1534 [ 'name' => 'database', 'callback' => [ $installer, 'setupDatabase' ] ],
1535 [ 'name' => 'tables', 'callback' => [ $installer, 'createTables' ] ],
1536 [ 'name' => 'interwiki', 'callback' => [ $installer, 'populateInterwikiTable' ] ],
1537 [ 'name' => 'stats', 'callback' => [ $this, 'populateSiteStats' ] ],
1538 [ 'name' => 'keys', 'callback' => [ $this, 'generateKeys' ] ],
1539 [ 'name' => 'updates', 'callback' => [ $installer, 'insertUpdateKeys' ] ],
1540 [ 'name' => 'sysop', 'callback' => [ $this, 'createSysop' ] ],
1541 [ 'name' => 'mainpage', 'callback' => [ $this, 'createMainpage' ] ],
1542 ];
1543
1544 // Build the array of install steps starting from the core install list,
1545 // then adding any callbacks that wanted to attach after a given step
1546 foreach ( $coreInstallSteps as $step ) {
1547 $this->installSteps[] = $step;
1548 if ( isset( $this->extraInstallSteps[$step['name']] ) ) {
1549 $this->installSteps = array_merge(
1550 $this->installSteps,
1551 $this->extraInstallSteps[$step['name']]
1552 );
1553 }
1554 }
1555
1556 // Prepend any steps that want to be at the beginning
1557 if ( isset( $this->extraInstallSteps['BEGINNING'] ) ) {
1558 $this->installSteps = array_merge(
1559 $this->extraInstallSteps['BEGINNING'],
1560 $this->installSteps
1561 );
1562 }
1563
1564 // Extensions should always go first, chance to tie into hooks and such
1565 if ( count( $this->getVar( '_Extensions' ) ) ) {
1566 array_unshift( $this->installSteps,
1567 [ 'name' => 'extensions', 'callback' => [ $this, 'includeExtensions' ] ]
1568 );
1569 $this->installSteps[] = [
1570 'name' => 'extension-tables',
1571 'callback' => [ $installer, 'createExtensionTables' ]
1572 ];
1573 }
1574
1575 return $this->installSteps;
1576 }
1577
1578 /**
1579 * Actually perform the installation.
1580 *
1581 * @param callable $startCB A callback array for the beginning of each step
1582 * @param callable $endCB A callback array for the end of each step
1583 *
1584 * @return array Array of Status objects
1585 */
1586 public function performInstallation( $startCB, $endCB ) {
1587 $installResults = [];
1588 $installer = $this->getDBInstaller();
1589 $installer->preInstall();
1590 $steps = $this->getInstallSteps( $installer );
1591 foreach ( $steps as $stepObj ) {
1592 $name = $stepObj['name'];
1593 call_user_func_array( $startCB, [ $name ] );
1594
1595 // Perform the callback step
1596 $status = call_user_func( $stepObj['callback'], $installer );
1597
1598 // Output and save the results
1599 call_user_func( $endCB, $name, $status );
1600 $installResults[$name] = $status;
1601
1602 // If we've hit some sort of fatal, we need to bail.
1603 // Callback already had a chance to do output above.
1604 if ( !$status->isOk() ) {
1605 break;
1606 }
1607 }
1608 if ( $status->isOk() ) {
1609 $this->showMessage(
1610 'config-install-success',
1611 $this->getVar( 'wgServer' ),
1612 $this->getVar( 'wgScriptPath' )
1613 );
1614 $this->setVar( '_InstallDone', true );
1615 }
1616
1617 return $installResults;
1618 }
1619
1620 /**
1621 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1622 *
1623 * @return Status
1624 */
1625 public function generateKeys() {
1626 $keys = [ 'wgSecretKey' => 64 ];
1627 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1628 $keys['wgUpgradeKey'] = 16;
1629 }
1630
1631 return $this->doGenerateKeys( $keys );
1632 }
1633
1634 /**
1635 * Generate a secret value for variables using our CryptRand generator.
1636 * Produce a warning if the random source was insecure.
1637 *
1638 * @param array $keys
1639 * @return Status
1640 */
1641 protected function doGenerateKeys( $keys ) {
1642 $status = Status::newGood();
1643
1644 foreach ( $keys as $name => $length ) {
1645 $secretKey = MWCryptRand::generateHex( $length );
1646 $this->setVar( $name, $secretKey );
1647 }
1648
1649 return $status;
1650 }
1651
1652 /**
1653 * Create the first user account, grant it sysop, bureaucrat and interface-admin rights
1654 *
1655 * @return Status
1656 */
1657 protected function createSysop() {
1658 $name = $this->getVar( '_AdminName' );
1659 $user = User::newFromName( $name );
1660
1661 if ( !$user ) {
1662 // We should've validated this earlier anyway!
1663 return Status::newFatal( 'config-admin-error-user', $name );
1664 }
1665
1666 if ( $user->idForName() == 0 ) {
1667 $user->addToDatabase();
1668
1669 try {
1670 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1671 } catch ( PasswordError $pwe ) {
1672 return Status::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1673 }
1674
1675 $user->addGroup( 'sysop' );
1676 $user->addGroup( 'bureaucrat' );
1677 $user->addGroup( 'interface-admin' );
1678 if ( $this->getVar( '_AdminEmail' ) ) {
1679 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1680 }
1681 $user->saveSettings();
1682
1683 // Update user count
1684 $ssUpdate = SiteStatsUpdate::factory( [ 'users' => 1 ] );
1685 $ssUpdate->doUpdate();
1686 }
1687 $status = Status::newGood();
1688
1689 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1690 $this->subscribeToMediaWikiAnnounce( $status );
1691 }
1692
1693 return $status;
1694 }
1695
1696 /**
1697 * @param Status $s
1698 */
1699 private function subscribeToMediaWikiAnnounce( Status $s ) {
1700 $params = [
1701 'email' => $this->getVar( '_AdminEmail' ),
1702 'language' => 'en',
1703 'digest' => 0
1704 ];
1705
1706 // Mailman doesn't support as many languages as we do, so check to make
1707 // sure their selected language is available
1708 $myLang = $this->getVar( '_UserLang' );
1709 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages ) ) {
1710 $myLang = $myLang == 'pt-br' ? 'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1711 $params['language'] = $myLang;
1712 }
1713
1714 if ( MWHttpRequest::canMakeRequests() ) {
1715 $res = MWHttpRequest::factory( $this->mediaWikiAnnounceUrl,
1716 [ 'method' => 'POST', 'postData' => $params ], __METHOD__ )->execute();
1717 if ( !$res->isOK() ) {
1718 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1719 }
1720 } else {
1721 $s->warning( 'config-install-subscribe-notpossible' );
1722 }
1723 }
1724
1725 /**
1726 * Insert Main Page with default content.
1727 *
1728 * @param DatabaseInstaller $installer
1729 * @return Status
1730 */
1731 protected function createMainpage( DatabaseInstaller $installer ) {
1732 $status = Status::newGood();
1733 $title = Title::newMainPage();
1734 if ( $title->exists() ) {
1735 $status->warning( 'config-install-mainpage-exists' );
1736 return $status;
1737 }
1738 try {
1739 $page = WikiPage::factory( $title );
1740 $content = new WikitextContent(
1741 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1742 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1743 );
1744
1745 $status = $page->doEditContent( $content,
1746 '',
1747 EDIT_NEW,
1748 false,
1749 User::newFromName( 'MediaWiki default' )
1750 );
1751 } catch ( Exception $e ) {
1752 // using raw, because $wgShowExceptionDetails can not be set yet
1753 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1754 }
1755
1756 return $status;
1757 }
1758
1759 /**
1760 * Override the necessary bits of the config to run an installation.
1761 */
1762 public static function overrideConfig() {
1763 // Use PHP's built-in session handling, since MediaWiki's
1764 // SessionHandler can't work before we have an object cache set up.
1765 define( 'MW_NO_SESSION_HANDLER', 1 );
1766
1767 // Don't access the database
1768 $GLOBALS['wgUseDatabaseMessages'] = false;
1769 // Don't cache langconv tables
1770 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE;
1771 // Debug-friendly
1772 $GLOBALS['wgShowExceptionDetails'] = true;
1773 $GLOBALS['wgShowHostnames'] = true;
1774 // Don't break forms
1775 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1776
1777 // Allow multiple ob_flush() calls
1778 $GLOBALS['wgDisableOutputCompression'] = true;
1779
1780 // Use a sensible cookie prefix (not my_wiki)
1781 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1782
1783 // Some of the environment checks make shell requests, remove limits
1784 $GLOBALS['wgMaxShellMemory'] = 0;
1785
1786 // Override the default CookieSessionProvider with a dummy
1787 // implementation that won't stomp on PHP's cookies.
1788 $GLOBALS['wgSessionProviders'] = [
1789 [
1790 'class' => InstallerSessionProvider::class,
1791 'args' => [ [
1792 'priority' => 1,
1793 ] ]
1794 ]
1795 ];
1796
1797 // Don't try to use any object cache for SessionManager either.
1798 $GLOBALS['wgSessionCacheType'] = CACHE_NONE;
1799 }
1800
1801 /**
1802 * Add an installation step following the given step.
1803 *
1804 * @param callable $callback A valid installation callback array, in this form:
1805 * [ 'name' => 'some-unique-name', 'callback' => [ $obj, 'function' ] ];
1806 * @param string $findStep The step to find. Omit to put the step at the beginning
1807 */
1808 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1809 $this->extraInstallSteps[$findStep][] = $callback;
1810 }
1811
1812 /**
1813 * Disable the time limit for execution.
1814 * Some long-running pages (Install, Upgrade) will want to do this
1815 */
1816 protected function disableTimeLimit() {
1817 Wikimedia\suppressWarnings();
1818 set_time_limit( 0 );
1819 Wikimedia\restoreWarnings();
1820 }
1821 }