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