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