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