install.php: Allow extensions and skins to be specified
[lhc/web/wiklou.git] / includes / installer / Installer.php
1 <?php
2 /**
3 * Base code for MediaWiki installer.
4 *
5 * DO NOT PATCH THIS FILE IF YOU NEED TO CHANGE INSTALLER BEHAVIOR IN YOUR PACKAGE!
6 * See mw-config/overrides/README for details.
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup Deployment
25 */
26
27 use MediaWiki\Interwiki\NullInterwikiLookup;
28 use MediaWiki\MediaWikiServices;
29 use MediaWiki\Shell\Shell;
30
31 /**
32 * This documentation group collects source code files with deployment functionality.
33 *
34 * @defgroup Deployment Deployment
35 */
36
37 /**
38 * Base installer class.
39 *
40 * This class provides the base for installation and update functionality
41 * for both MediaWiki core and extensions.
42 *
43 * @ingroup Deployment
44 * @since 1.17
45 */
46 abstract class Installer {
47
48 /**
49 * The oldest version of PCRE we can support.
50 *
51 * Defining this is necessary because PHP may be linked with a system version
52 * of PCRE, which may be older than that bundled with the minimum PHP version.
53 */
54 const MINIMUM_PCRE_VERSION = '7.2';
55
56 /**
57 * @var array
58 */
59 protected $settings;
60
61 /**
62 * List of detected DBs, access using getCompiledDBs().
63 *
64 * @var array
65 */
66 protected $compiledDBs;
67
68 /**
69 * Cached DB installer instances, access using getDBInstaller().
70 *
71 * @var array
72 */
73 protected $dbInstallers = [];
74
75 /**
76 * Minimum memory size in MB.
77 *
78 * @var int
79 */
80 protected $minMemorySize = 50;
81
82 /**
83 * Cached Title, used by parse().
84 *
85 * @var Title
86 */
87 protected $parserTitle;
88
89 /**
90 * Cached ParserOptions, used by parse().
91 *
92 * @var ParserOptions
93 */
94 protected $parserOptions;
95
96 /**
97 * Known database types. These correspond to the class names <type>Installer,
98 * and are also MediaWiki database types valid for $wgDBtype.
99 *
100 * To add a new type, create a <type>Installer class and a Database<type>
101 * class, and add a config-type-<type> message to MessagesEn.php.
102 *
103 * @var array
104 */
105 protected static $dbTypes = [
106 'mysql',
107 'postgres',
108 'oracle',
109 'mssql',
110 'sqlite',
111 ];
112
113 /**
114 * A list of environment check methods called by doEnvironmentChecks().
115 * These may output warnings using showMessage(), and/or abort the
116 * installation process by returning false.
117 *
118 * For the WebInstaller these are only called on the Welcome page,
119 * if these methods have side-effects that should affect later page loads
120 * (as well as the generated stylesheet), use envPreps instead.
121 *
122 * @var array
123 */
124 protected $envChecks = [
125 'envCheckDB',
126 'envCheckBrokenXML',
127 'envCheckPCRE',
128 'envCheckMemory',
129 'envCheckCache',
130 'envCheckModSecurity',
131 'envCheckDiff3',
132 'envCheckGraphics',
133 'envCheckGit',
134 'envCheckServer',
135 'envCheckPath',
136 'envCheckShellLocale',
137 'envCheckUploadsDirectory',
138 'envCheckLibicu',
139 'envCheckSuhosinMaxValueLength',
140 'envCheck64Bit',
141 ];
142
143 /**
144 * A list of environment preparation methods called by doEnvironmentPreps().
145 *
146 * @var array
147 */
148 protected $envPreps = [
149 'envPrepServer',
150 'envPrepPath',
151 ];
152
153 /**
154 * MediaWiki configuration globals that will eventually be passed through
155 * to LocalSettings.php. The names only are given here, the defaults
156 * typically come from DefaultSettings.php.
157 *
158 * @var array
159 */
160 protected $defaultVarNames = [
161 'wgSitename',
162 'wgPasswordSender',
163 'wgLanguageCode',
164 'wgRightsIcon',
165 'wgRightsText',
166 'wgRightsUrl',
167 'wgEnableEmail',
168 'wgEnableUserEmail',
169 'wgEnotifUserTalk',
170 'wgEnotifWatchlist',
171 'wgEmailAuthentication',
172 'wgDBname',
173 'wgDBtype',
174 'wgDiff3',
175 'wgImageMagickConvertCommand',
176 'wgGitBin',
177 'IP',
178 'wgScriptPath',
179 'wgMetaNamespace',
180 'wgDeletedDirectory',
181 'wgEnableUploads',
182 'wgShellLocale',
183 'wgSecretKey',
184 'wgUseInstantCommons',
185 'wgUpgradeKey',
186 'wgDefaultSkin',
187 'wgPingback',
188 ];
189
190 /**
191 * Variables that are stored alongside globals, and are used for any
192 * configuration of the installation process aside from the MediaWiki
193 * configuration. Map of names to defaults.
194 *
195 * @var array
196 */
197 protected $internalDefaults = [
198 '_UserLang' => 'en',
199 '_Environment' => false,
200 '_RaiseMemory' => false,
201 '_UpgradeDone' => false,
202 '_InstallDone' => false,
203 '_Caches' => [],
204 '_InstallPassword' => '',
205 '_SameAccount' => true,
206 '_CreateDBAccount' => false,
207 '_NamespaceType' => 'site-name',
208 '_AdminName' => '', // will be set later, when the user selects language
209 '_AdminPassword' => '',
210 '_AdminPasswordConfirm' => '',
211 '_AdminEmail' => '',
212 '_Subscribe' => false,
213 '_SkipOptional' => 'continue',
214 '_RightsProfile' => 'wiki',
215 '_LicenseCode' => 'none',
216 '_CCDone' => false,
217 '_Extensions' => [],
218 '_Skins' => [],
219 '_MemCachedServers' => '',
220 '_UpgradeKeySupplied' => false,
221 '_ExistingDBSettings' => false,
222
223 // $wgLogo is probably wrong (T50084); set something that will work.
224 // Single quotes work fine here, as LocalSettingsGenerator outputs this unescaped.
225 'wgLogo' => '$wgResourceBasePath/resources/assets/wiki.png',
226 'wgAuthenticationTokenVersion' => 1,
227 ];
228
229 /**
230 * The actual list of installation steps. This will be initialized by getInstallSteps()
231 *
232 * @var array
233 */
234 private $installSteps = [];
235
236 /**
237 * Extra steps for installation, for things like DatabaseInstallers to modify
238 *
239 * @var array
240 */
241 protected $extraInstallSteps = [];
242
243 /**
244 * Known object cache types and the functions used to test for their existence.
245 *
246 * @var array
247 */
248 protected $objectCaches = [
249 'apc' => 'apc_fetch',
250 'apcu' => 'apcu_fetch',
251 'wincache' => 'wincache_ucache_get'
252 ];
253
254 /**
255 * User rights profiles.
256 *
257 * @var array
258 */
259 public $rightsProfiles = [
260 'wiki' => [],
261 'no-anon' => [
262 '*' => [ 'edit' => false ]
263 ],
264 'fishbowl' => [
265 '*' => [
266 'createaccount' => false,
267 'edit' => false,
268 ],
269 ],
270 'private' => [
271 '*' => [
272 'createaccount' => false,
273 'edit' => false,
274 'read' => false,
275 ],
276 ],
277 ];
278
279 /**
280 * License types.
281 *
282 * @var array
283 */
284 public $licenses = [
285 'cc-by' => [
286 'url' => 'https://creativecommons.org/licenses/by/4.0/',
287 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by.png',
288 ],
289 'cc-by-sa' => [
290 'url' => 'https://creativecommons.org/licenses/by-sa/4.0/',
291 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-sa.png',
292 ],
293 'cc-by-nc-sa' => [
294 'url' => 'https://creativecommons.org/licenses/by-nc-sa/4.0/',
295 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-nc-sa.png',
296 ],
297 'cc-0' => [
298 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
299 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-0.png',
300 ],
301 'gfdl' => [
302 'url' => 'https://www.gnu.org/copyleft/fdl.html',
303 'icon' => '$wgResourceBasePath/resources/assets/licenses/gnu-fdl.png',
304 ],
305 'none' => [
306 'url' => '',
307 'icon' => '',
308 'text' => ''
309 ],
310 'cc-choose' => [
311 // Details will be filled in by the selector.
312 'url' => '',
313 'icon' => '',
314 'text' => '',
315 ],
316 ];
317
318 /**
319 * URL to mediawiki-announce subscription
320 */
321 protected $mediaWikiAnnounceUrl =
322 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
323
324 /**
325 * Supported language codes for Mailman
326 */
327 protected $mediaWikiAnnounceLanguages = [
328 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
329 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
330 'sl', 'sr', 'sv', 'tr', 'uk'
331 ];
332
333 /**
334 * UI interface for displaying a short message
335 * The parameters are like parameters to wfMessage().
336 * The messages will be in wikitext format, which will be converted to an
337 * output format such as HTML or text before being sent to the user.
338 * @param string $msg
339 */
340 abstract public function showMessage( $msg /*, ... */ );
341
342 /**
343 * Same as showMessage(), but for displaying errors
344 * @param string $msg
345 */
346 abstract public function showError( $msg /*, ... */ );
347
348 /**
349 * Show a message to the installing user by using a Status object
350 * @param Status $status
351 */
352 abstract public function showStatusMessage( Status $status );
353
354 /**
355 * Constructs a Config object that contains configuration settings that should be
356 * overwritten for the installation process.
357 *
358 * @since 1.27
359 *
360 * @param Config $baseConfig
361 *
362 * @return Config The config to use during installation.
363 */
364 public static function getInstallerConfig( Config $baseConfig ) {
365 $configOverrides = new HashConfig();
366
367 // disable (problematic) object cache types explicitly, preserving all other (working) ones
368 // bug T113843
369 $emptyCache = [ 'class' => EmptyBagOStuff::class ];
370
371 $objectCaches = [
372 CACHE_NONE => $emptyCache,
373 CACHE_DB => $emptyCache,
374 CACHE_ANYTHING => $emptyCache,
375 CACHE_MEMCACHED => $emptyCache,
376 ] + $baseConfig->get( 'ObjectCaches' );
377
378 $configOverrides->set( 'ObjectCaches', $objectCaches );
379
380 // Load the installer's i18n.
381 $messageDirs = $baseConfig->get( 'MessagesDirs' );
382 $messageDirs['MediawikiInstaller'] = __DIR__ . '/i18n';
383
384 $configOverrides->set( 'MessagesDirs', $messageDirs );
385
386 $installerConfig = new MultiConfig( [ $configOverrides, $baseConfig ] );
387
388 // make sure we use the installer config as the main config
389 $configRegistry = $baseConfig->get( 'ConfigRegistry' );
390 $configRegistry['main'] = function () use ( $installerConfig ) {
391 return $installerConfig;
392 };
393
394 $configOverrides->set( 'ConfigRegistry', $configRegistry );
395
396 return $installerConfig;
397 }
398
399 /**
400 * Constructor, always call this from child classes.
401 */
402 public function __construct() {
403 global $wgMemc, $wgUser, $wgObjectCaches;
404
405 $defaultConfig = new GlobalVarConfig(); // all the stuff from DefaultSettings.php
406 $installerConfig = self::getInstallerConfig( $defaultConfig );
407
408 // Reset all services and inject config overrides
409 MediaWikiServices::resetGlobalInstance( $installerConfig );
410
411 // Don't attempt to load user language options (T126177)
412 // This will be overridden in the web installer with the user-specified language
413 RequestContext::getMain()->setLanguage( 'en' );
414
415 // Disable the i18n cache
416 // TODO: manage LocalisationCache singleton in MediaWikiServices
417 Language::getLocalisationCache()->disableBackend();
418
419 // Disable all global services, since we don't have any configuration yet!
420 MediaWikiServices::disableStorageBackend();
421
422 $mwServices = MediaWikiServices::getInstance();
423 // Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
424 // SqlBagOStuff will then throw since we just disabled wfGetDB)
425 $wgObjectCaches = $mwServices->getMainConfig()->get( 'ObjectCaches' );
426 $wgMemc = ObjectCache::getInstance( CACHE_NONE );
427
428 // Disable interwiki lookup, to avoid database access during parses
429 $mwServices->redefineService( 'InterwikiLookup', function () {
430 return new NullInterwikiLookup();
431 } );
432
433 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
434 $wgUser = User::newFromId( 0 );
435 RequestContext::getMain()->setUser( $wgUser );
436
437 $this->settings = $this->internalDefaults;
438
439 foreach ( $this->defaultVarNames as $var ) {
440 $this->settings[$var] = $GLOBALS[$var];
441 }
442
443 $this->doEnvironmentPreps();
444
445 $this->compiledDBs = [];
446 foreach ( self::getDBTypes() as $type ) {
447 $installer = $this->getDBInstaller( $type );
448
449 if ( !$installer->isCompiled() ) {
450 continue;
451 }
452 $this->compiledDBs[] = $type;
453 }
454
455 $this->parserTitle = Title::newFromText( 'Installer' );
456 $this->parserOptions = new ParserOptions( $wgUser ); // language will be wrong :(
457 $this->parserOptions->setTidy( true );
458 // Don't try to access DB before user language is initialised
459 $this->setParserLanguage( Language::factory( 'en' ) );
460 }
461
462 /**
463 * Get a list of known DB types.
464 *
465 * @return array
466 */
467 public static function getDBTypes() {
468 return self::$dbTypes;
469 }
470
471 /**
472 * Do initial checks of the PHP environment. Set variables according to
473 * the observed environment.
474 *
475 * It's possible that this may be called under the CLI SAPI, not the SAPI
476 * that the wiki will primarily run under. In that case, the subclass should
477 * initialise variables such as wgScriptPath, before calling this function.
478 *
479 * Under the web subclass, it can already be assumed that PHP 5+ is in use
480 * and that sessions are working.
481 *
482 * @return Status
483 */
484 public function doEnvironmentChecks() {
485 // Php version has already been checked by entry scripts
486 // Show message here for information purposes
487 if ( wfIsHHVM() ) {
488 $this->showMessage( 'config-env-hhvm', HHVM_VERSION );
489 } else {
490 $this->showMessage( 'config-env-php', PHP_VERSION );
491 }
492
493 $good = true;
494 // Must go here because an old version of PCRE can prevent other checks from completing
495 list( $pcreVersion ) = explode( ' ', PCRE_VERSION, 2 );
496 if ( version_compare( $pcreVersion, self::MINIMUM_PCRE_VERSION, '<' ) ) {
497 $this->showError( 'config-pcre-old', self::MINIMUM_PCRE_VERSION, $pcreVersion );
498 $good = false;
499 } else {
500 foreach ( $this->envChecks as $check ) {
501 $status = $this->$check();
502 if ( $status === false ) {
503 $good = false;
504 }
505 }
506 }
507
508 $this->setVar( '_Environment', $good );
509
510 return $good ? Status::newGood() : Status::newFatal( 'config-env-bad' );
511 }
512
513 public function doEnvironmentPreps() {
514 foreach ( $this->envPreps as $prep ) {
515 $this->$prep();
516 }
517 }
518
519 /**
520 * Set a MW configuration variable, or internal installer configuration variable.
521 *
522 * @param string $name
523 * @param mixed $value
524 */
525 public function setVar( $name, $value ) {
526 $this->settings[$name] = $value;
527 }
528
529 /**
530 * Get an MW configuration variable, or internal installer configuration variable.
531 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
532 * Installer variables are typically prefixed by an underscore.
533 *
534 * @param string $name
535 * @param mixed|null $default
536 *
537 * @return mixed
538 */
539 public function getVar( $name, $default = null ) {
540 if ( !isset( $this->settings[$name] ) ) {
541 return $default;
542 } else {
543 return $this->settings[$name];
544 }
545 }
546
547 /**
548 * Get a list of DBs supported by current PHP setup
549 *
550 * @return array
551 */
552 public function getCompiledDBs() {
553 return $this->compiledDBs;
554 }
555
556 /**
557 * Get the DatabaseInstaller class name for this type
558 *
559 * @param string $type database type ($wgDBtype)
560 * @return string Class name
561 * @since 1.30
562 */
563 public static function getDBInstallerClass( $type ) {
564 return ucfirst( $type ) . 'Installer';
565 }
566
567 /**
568 * Get an instance of DatabaseInstaller for the specified DB type.
569 *
570 * @param mixed $type DB installer for which is needed, false to use default.
571 *
572 * @return DatabaseInstaller
573 */
574 public function getDBInstaller( $type = false ) {
575 if ( !$type ) {
576 $type = $this->getVar( 'wgDBtype' );
577 }
578
579 $type = strtolower( $type );
580
581 if ( !isset( $this->dbInstallers[$type] ) ) {
582 $class = self::getDBInstallerClass( $type );
583 $this->dbInstallers[$type] = new $class( $this );
584 }
585
586 return $this->dbInstallers[$type];
587 }
588
589 /**
590 * Determine if LocalSettings.php exists. If it does, return its variables.
591 *
592 * @return array|false
593 */
594 public static function getExistingLocalSettings() {
595 global $IP;
596
597 // You might be wondering why this is here. Well if you don't do this
598 // then some poorly-formed extensions try to call their own classes
599 // after immediately registering them. We really need to get extension
600 // registration out of the global scope and into a real format.
601 // @see https://phabricator.wikimedia.org/T69440
602 global $wgAutoloadClasses;
603 $wgAutoloadClasses = [];
604
605 // LocalSettings.php should not call functions, except wfLoadSkin/wfLoadExtensions
606 // Define the required globals here, to ensure, the functions can do it work correctly.
607 // phpcs:ignore MediaWiki.VariableAnalysis.UnusedGlobalVariables
608 global $wgExtensionDirectory, $wgStyleDirectory;
609
610 Wikimedia\suppressWarnings();
611 $_lsExists = file_exists( "$IP/LocalSettings.php" );
612 Wikimedia\restoreWarnings();
613
614 if ( !$_lsExists ) {
615 return false;
616 }
617 unset( $_lsExists );
618
619 require "$IP/includes/DefaultSettings.php";
620 require "$IP/LocalSettings.php";
621
622 return get_defined_vars();
623 }
624
625 /**
626 * Get a fake password for sending back to the user in HTML.
627 * This is a security mechanism to avoid compromise of the password in the
628 * event of session ID compromise.
629 *
630 * @param string $realPassword
631 *
632 * @return string
633 */
634 public function getFakePassword( $realPassword ) {
635 return str_repeat( '*', strlen( $realPassword ) );
636 }
637
638 /**
639 * Set a variable which stores a password, except if the new value is a
640 * fake password in which case leave it as it is.
641 *
642 * @param string $name
643 * @param mixed $value
644 */
645 public function setPassword( $name, $value ) {
646 if ( !preg_match( '/^\*+$/', $value ) ) {
647 $this->setVar( $name, $value );
648 }
649 }
650
651 /**
652 * On POSIX systems return the primary group of the webserver we're running under.
653 * On other systems just returns null.
654 *
655 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
656 * webserver user before he can install.
657 *
658 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
659 *
660 * @return mixed
661 */
662 public static function maybeGetWebserverPrimaryGroup() {
663 if ( !function_exists( 'posix_getegid' ) || !function_exists( 'posix_getpwuid' ) ) {
664 # I don't know this, this isn't UNIX.
665 return null;
666 }
667
668 # posix_getegid() *not* getmygid() because we want the group of the webserver,
669 # not whoever owns the current script.
670 $gid = posix_getegid();
671 $group = posix_getpwuid( $gid )['name'];
672
673 return $group;
674 }
675
676 /**
677 * Convert wikitext $text to HTML.
678 *
679 * This is potentially error prone since many parser features require a complete
680 * installed MW database. The solution is to just not use those features when you
681 * write your messages. This appears to work well enough. Basic formatting and
682 * external links work just fine.
683 *
684 * But in case a translator decides to throw in a "#ifexist" or internal link or
685 * whatever, this function is guarded to catch the attempted DB access and to present
686 * some fallback text.
687 *
688 * @param string $text
689 * @param bool $lineStart
690 * @return string
691 */
692 public function parse( $text, $lineStart = false ) {
693 global $wgParser;
694
695 try {
696 $out = $wgParser->parse( $text, $this->parserTitle, $this->parserOptions, $lineStart );
697 $html = $out->getText( [
698 'enableSectionEditLinks' => false,
699 'unwrap' => true,
700 ] );
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', '', "-\u{3000}-" );
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 * Check the libicu version
1121 */
1122 protected function envCheckLibicu() {
1123 /**
1124 * This needs to be updated something that the latest libicu
1125 * will properly normalize. This normalization was found at
1126 * https://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1127 * Note that we use the hex representation to create the code
1128 * points in order to avoid any Unicode-destroying during transit.
1129 */
1130 $not_normal_c = "\u{FA6C}";
1131 $normal_c = "\u{242EE}";
1132
1133 $useNormalizer = 'php';
1134 $needsUpdate = false;
1135
1136 if ( function_exists( 'normalizer_normalize' ) ) {
1137 $useNormalizer = 'intl';
1138 $intl = normalizer_normalize( $not_normal_c, Normalizer::FORM_C );
1139 if ( $intl !== $normal_c ) {
1140 $needsUpdate = true;
1141 }
1142 }
1143
1144 // Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
1145 if ( $useNormalizer === 'php' ) {
1146 $this->showMessage( 'config-unicode-pure-php-warning' );
1147 } else {
1148 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1149 if ( $needsUpdate ) {
1150 $this->showMessage( 'config-unicode-update-warning' );
1151 }
1152 }
1153 }
1154
1155 /**
1156 * Environment prep for the server hostname.
1157 */
1158 protected function envPrepServer() {
1159 $server = $this->envGetDefaultServer();
1160 if ( $server !== null ) {
1161 $this->setVar( 'wgServer', $server );
1162 }
1163 }
1164
1165 /**
1166 * Helper function to be called from envPrepServer()
1167 * @return string
1168 */
1169 abstract protected function envGetDefaultServer();
1170
1171 /**
1172 * Environment prep for setting $IP and $wgScriptPath.
1173 */
1174 protected function envPrepPath() {
1175 global $IP;
1176 $IP = dirname( dirname( __DIR__ ) );
1177 $this->setVar( 'IP', $IP );
1178 }
1179
1180 /**
1181 * Checks if scripts located in the given directory can be executed via the given URL.
1182 *
1183 * Used only by environment checks.
1184 * @param string $dir
1185 * @param string $url
1186 * @return bool|int|string
1187 */
1188 public function dirIsExecutable( $dir, $url ) {
1189 $scriptTypes = [
1190 'php' => [
1191 "<?php echo 'ex' . 'ec';",
1192 "#!/var/env php\n<?php echo 'ex' . 'ec';",
1193 ],
1194 ];
1195
1196 // it would be good to check other popular languages here, but it'll be slow.
1197
1198 Wikimedia\suppressWarnings();
1199
1200 foreach ( $scriptTypes as $ext => $contents ) {
1201 foreach ( $contents as $source ) {
1202 $file = 'exectest.' . $ext;
1203
1204 if ( !file_put_contents( $dir . $file, $source ) ) {
1205 break;
1206 }
1207
1208 try {
1209 $text = Http::get( $url . $file, [ 'timeout' => 3 ], __METHOD__ );
1210 } catch ( Exception $e ) {
1211 // Http::get throws with allow_url_fopen = false and no curl extension.
1212 $text = null;
1213 }
1214 unlink( $dir . $file );
1215
1216 if ( $text == 'exec' ) {
1217 Wikimedia\restoreWarnings();
1218
1219 return $ext;
1220 }
1221 }
1222 }
1223
1224 Wikimedia\restoreWarnings();
1225
1226 return false;
1227 }
1228
1229 /**
1230 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1231 *
1232 * @param string $moduleName Name of module to check.
1233 * @return bool
1234 */
1235 public static function apacheModulePresent( $moduleName ) {
1236 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1237 return true;
1238 }
1239 // try it the hard way
1240 ob_start();
1241 phpinfo( INFO_MODULES );
1242 $info = ob_get_clean();
1243
1244 return strpos( $info, $moduleName ) !== false;
1245 }
1246
1247 /**
1248 * ParserOptions are constructed before we determined the language, so fix it
1249 *
1250 * @param Language $lang
1251 */
1252 public function setParserLanguage( $lang ) {
1253 $this->parserOptions->setTargetLanguage( $lang );
1254 $this->parserOptions->setUserLang( $lang );
1255 }
1256
1257 /**
1258 * Overridden by WebInstaller to provide lastPage parameters.
1259 * @param string $page
1260 * @return string
1261 */
1262 protected function getDocUrl( $page ) {
1263 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1264 }
1265
1266 /**
1267 * Find extensions or skins in a subdirectory of $IP.
1268 * Returns an array containing the value for 'Name' for each found extension.
1269 *
1270 * @param string $directory Directory to search in, relative to $IP, must be either "extensions"
1271 * or "skins"
1272 * @return array [ $extName => [ 'screenshots' => [ '...' ] ]
1273 */
1274 public function findExtensions( $directory = 'extensions' ) {
1275 switch ( $directory ) {
1276 case 'extensions':
1277 return $this->findExtensionsByType( 'extension', 'extensions' );
1278 case 'skins':
1279 return $this->findExtensionsByType( 'skin', 'skins' );
1280 default:
1281 throw new InvalidArgumentException( "Invalid extension type" );
1282 }
1283 }
1284
1285 /**
1286 * Find extensions or skins, and return an array containing the value for 'Name' for each found
1287 * extension.
1288 *
1289 * @param string $type Either "extension" or "skin"
1290 * @param string $directory Directory to search in, relative to $IP
1291 * @return array [ $extName => [ 'screenshots' => [ '...' ] ]
1292 */
1293 protected function findExtensionsByType( $type = 'extension', $directory = 'extensions' ) {
1294 if ( $this->getVar( 'IP' ) === null ) {
1295 return [];
1296 }
1297
1298 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1299 if ( !is_readable( $extDir ) || !is_dir( $extDir ) ) {
1300 return [];
1301 }
1302
1303 $dh = opendir( $extDir );
1304 $exts = [];
1305 while ( ( $file = readdir( $dh ) ) !== false ) {
1306 if ( !is_dir( "$extDir/$file" ) ) {
1307 continue;
1308 }
1309 $status = $this->getExtensionInfo( $type, $directory, $file );
1310 if ( $status->isOK() ) {
1311 $exts[$file] = $status->value;
1312 }
1313 }
1314 closedir( $dh );
1315 uksort( $exts, 'strnatcasecmp' );
1316
1317 return $exts;
1318 }
1319
1320 /**
1321 * @param string $type Either "extension" or "skin"
1322 * @param string $parentRelPath The parent directory relative to $IP
1323 * @param string $name The extension or skin name
1324 * @return Status An object containing an error list. If there were no errors, an associative
1325 * array of information about the extension can be found in $status->value.
1326 */
1327 protected function getExtensionInfo( $type, $parentRelPath, $name ) {
1328 if ( $this->getVar( 'IP' ) === null ) {
1329 throw new Exception( 'Cannot find extensions since the IP variable is not yet set' );
1330 }
1331 if ( $type !== 'extension' && $type !== 'skin' ) {
1332 throw new InvalidArgumentException( "Invalid extension type" );
1333 }
1334 $absDir = $this->getVar( 'IP' ) . "/$parentRelPath/$name";
1335 $relDir = "../$parentRelPath/$name";
1336 if ( !is_dir( $absDir ) ) {
1337 return Status::newFatal( 'config-extension-not-found', $name );
1338 }
1339 $jsonFile = $type . '.json';
1340 $fullJsonFile = "$absDir/$jsonFile";
1341 $isJson = file_exists( $fullJsonFile );
1342 $isPhp = false;
1343 if ( !$isJson ) {
1344 // Only fallback to PHP file if JSON doesn't exist
1345 $fullPhpFile = "$absDir/$name.php";
1346 $isPhp = file_exists( $fullPhpFile );
1347 }
1348 if ( !$isJson && !$isPhp ) {
1349 return Status::newFatal( 'config-extension-not-found', $name );
1350 }
1351
1352 // Extension exists. Now see if there are screenshots
1353 $info = [];
1354 if ( is_dir( "$absDir/screenshots" ) ) {
1355 $paths = glob( "$absDir/screenshots/*.png" );
1356 foreach ( $paths as $path ) {
1357 $info['screenshots'][] = str_replace( $absDir, $relDir, $path );
1358 }
1359 }
1360
1361 if ( $isJson ) {
1362 $jsonStatus = $this->readExtension( $fullJsonFile );
1363 if ( !$jsonStatus->isOK() ) {
1364 return $jsonStatus;
1365 }
1366 $info += $jsonStatus->value;
1367 }
1368
1369 return Status::newGood( $info );
1370 }
1371
1372 /**
1373 * @param string $fullJsonFile
1374 * @param array $extDeps
1375 * @param array $skinDeps
1376 *
1377 * @return Status On success, an array of extension information is in $status->value. On
1378 * failure, the Status object will have an error list.
1379 */
1380 private function readExtension( $fullJsonFile, $extDeps = [], $skinDeps = [] ) {
1381 $load = [
1382 $fullJsonFile => 1
1383 ];
1384 if ( $extDeps ) {
1385 $extDir = $this->getVar( 'IP' ) . '/extensions';
1386 foreach ( $extDeps as $dep ) {
1387 $fname = "$extDir/$dep/extension.json";
1388 if ( !file_exists( $fname ) ) {
1389 return Status::newFatal( 'config-extension-not-found', $dep );
1390 }
1391 $load[$fname] = 1;
1392 }
1393 }
1394 if ( $skinDeps ) {
1395 $skinDir = $this->getVar( 'IP' ) . '/skins';
1396 foreach ( $skinDeps as $dep ) {
1397 $fname = "$skinDir/$dep/skin.json";
1398 if ( !file_exists( $fname ) ) {
1399 return Status::newFatal( 'config-extension-not-found', $dep );
1400 }
1401 $load[$fname] = 1;
1402 }
1403 }
1404 $registry = new ExtensionRegistry();
1405 try {
1406 $info = $registry->readFromQueue( $load );
1407 } catch ( ExtensionDependencyError $e ) {
1408 if ( $e->incompatibleCore || $e->incompatibleSkins
1409 || $e->incompatibleExtensions
1410 ) {
1411 // If something is incompatible with a dependency, we have no real
1412 // option besides skipping it
1413 return Status::newFatal( 'config-extension-dependency',
1414 basename( dirname( $fullJsonFile ) ), $e->getMessage() );
1415 } elseif ( $e->missingExtensions || $e->missingSkins ) {
1416 // There's an extension missing in the dependency tree,
1417 // so add those to the dependency list and try again
1418 return $this->readExtension(
1419 $fullJsonFile,
1420 array_merge( $extDeps, $e->missingExtensions ),
1421 array_merge( $skinDeps, $e->missingSkins )
1422 );
1423 }
1424 // Some other kind of dependency error?
1425 return Status::newFatal( 'config-extension-dependency',
1426 basename( dirname( $fullJsonFile ) ), $e->getMessage() );
1427 }
1428 $ret = [];
1429 // The order of credits will be the order of $load,
1430 // so the first extension is the one we want to load,
1431 // everything else is a dependency
1432 $i = 0;
1433 foreach ( $info['credits'] as $name => $credit ) {
1434 $i++;
1435 if ( $i == 1 ) {
1436 // Extension we want to load
1437 continue;
1438 }
1439 $type = basename( $credit['path'] ) === 'skin.json' ? 'skins' : 'extensions';
1440 $ret['requires'][$type][] = $credit['name'];
1441 }
1442 $credits = array_values( $info['credits'] )[0];
1443 if ( isset( $credits['url'] ) ) {
1444 $ret['url'] = $credits['url'];
1445 }
1446 $ret['type'] = $credits['type'];
1447
1448 return Status::newGood( $ret );
1449 }
1450
1451 /**
1452 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1453 * but will fall back to another if the default skin is missing and some other one is present
1454 * instead.
1455 *
1456 * @param string[] $skinNames Names of installed skins.
1457 * @return string
1458 */
1459 public function getDefaultSkin( array $skinNames ) {
1460 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1461 if ( !$skinNames || in_array( $defaultSkin, $skinNames ) ) {
1462 return $defaultSkin;
1463 } else {
1464 return $skinNames[0];
1465 }
1466 }
1467
1468 /**
1469 * Installs the auto-detected extensions.
1470 *
1471 * @return Status
1472 */
1473 protected function includeExtensions() {
1474 global $IP;
1475 $exts = $this->getVar( '_Extensions' );
1476 $IP = $this->getVar( 'IP' );
1477
1478 // Marker for DatabaseUpdater::loadExtensions so we don't
1479 // double load extensions
1480 define( 'MW_EXTENSIONS_LOADED', true );
1481
1482 /**
1483 * We need to include DefaultSettings before including extensions to avoid
1484 * warnings about unset variables. However, the only thing we really
1485 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1486 * if the extension has hidden hook registration in $wgExtensionFunctions,
1487 * but we're not opening that can of worms
1488 * @see https://phabricator.wikimedia.org/T28857
1489 */
1490 global $wgAutoloadClasses;
1491 $wgAutoloadClasses = [];
1492 $queue = [];
1493
1494 require "$IP/includes/DefaultSettings.php";
1495
1496 foreach ( $exts as $e ) {
1497 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1498 $queue["$IP/extensions/$e/extension.json"] = 1;
1499 } else {
1500 require_once "$IP/extensions/$e/$e.php";
1501 }
1502 }
1503
1504 $registry = new ExtensionRegistry();
1505 $data = $registry->readFromQueue( $queue );
1506 $wgAutoloadClasses += $data['autoload'];
1507
1508 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1509 /** @suppress PhanUndeclaredVariable $wgHooks is set by DefaultSettings */
1510 $wgHooks['LoadExtensionSchemaUpdates'] : [];
1511
1512 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1513 $hooksWeWant = array_merge_recursive(
1514 $hooksWeWant,
1515 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1516 );
1517 }
1518 // Unset everyone else's hooks. Lord knows what someone might be doing
1519 // in ParserFirstCallInit (see T29171)
1520 $GLOBALS['wgHooks'] = [ 'LoadExtensionSchemaUpdates' => $hooksWeWant ];
1521
1522 return Status::newGood();
1523 }
1524
1525 /**
1526 * Get an array of install steps. Should always be in the format of
1527 * [
1528 * 'name' => 'someuniquename',
1529 * 'callback' => [ $obj, 'method' ],
1530 * ]
1531 * There must be a config-install-$name message defined per step, which will
1532 * be shown on install.
1533 *
1534 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1535 * @return array
1536 */
1537 protected function getInstallSteps( DatabaseInstaller $installer ) {
1538 $coreInstallSteps = [
1539 [ 'name' => 'database', 'callback' => [ $installer, 'setupDatabase' ] ],
1540 [ 'name' => 'tables', 'callback' => [ $installer, 'createTables' ] ],
1541 [ 'name' => 'interwiki', 'callback' => [ $installer, 'populateInterwikiTable' ] ],
1542 [ 'name' => 'stats', 'callback' => [ $this, 'populateSiteStats' ] ],
1543 [ 'name' => 'keys', 'callback' => [ $this, 'generateKeys' ] ],
1544 [ 'name' => 'updates', 'callback' => [ $installer, 'insertUpdateKeys' ] ],
1545 [ 'name' => 'sysop', 'callback' => [ $this, 'createSysop' ] ],
1546 [ 'name' => 'mainpage', 'callback' => [ $this, 'createMainpage' ] ],
1547 ];
1548
1549 // Build the array of install steps starting from the core install list,
1550 // then adding any callbacks that wanted to attach after a given step
1551 foreach ( $coreInstallSteps as $step ) {
1552 $this->installSteps[] = $step;
1553 if ( isset( $this->extraInstallSteps[$step['name']] ) ) {
1554 $this->installSteps = array_merge(
1555 $this->installSteps,
1556 $this->extraInstallSteps[$step['name']]
1557 );
1558 }
1559 }
1560
1561 // Prepend any steps that want to be at the beginning
1562 if ( isset( $this->extraInstallSteps['BEGINNING'] ) ) {
1563 $this->installSteps = array_merge(
1564 $this->extraInstallSteps['BEGINNING'],
1565 $this->installSteps
1566 );
1567 }
1568
1569 // Extensions should always go first, chance to tie into hooks and such
1570 if ( count( $this->getVar( '_Extensions' ) ) ) {
1571 array_unshift( $this->installSteps,
1572 [ 'name' => 'extensions', 'callback' => [ $this, 'includeExtensions' ] ]
1573 );
1574 $this->installSteps[] = [
1575 'name' => 'extension-tables',
1576 'callback' => [ $installer, 'createExtensionTables' ]
1577 ];
1578 }
1579
1580 return $this->installSteps;
1581 }
1582
1583 /**
1584 * Actually perform the installation.
1585 *
1586 * @param callable $startCB A callback array for the beginning of each step
1587 * @param callable $endCB A callback array for the end of each step
1588 *
1589 * @return array Array of Status objects
1590 */
1591 public function performInstallation( $startCB, $endCB ) {
1592 $installResults = [];
1593 $installer = $this->getDBInstaller();
1594 $installer->preInstall();
1595 $steps = $this->getInstallSteps( $installer );
1596 foreach ( $steps as $stepObj ) {
1597 $name = $stepObj['name'];
1598 call_user_func_array( $startCB, [ $name ] );
1599
1600 // Perform the callback step
1601 $status = call_user_func( $stepObj['callback'], $installer );
1602
1603 // Output and save the results
1604 call_user_func( $endCB, $name, $status );
1605 $installResults[$name] = $status;
1606
1607 // If we've hit some sort of fatal, we need to bail.
1608 // Callback already had a chance to do output above.
1609 if ( !$status->isOk() ) {
1610 break;
1611 }
1612 }
1613 if ( $status->isOk() ) {
1614 $this->showMessage(
1615 'config-install-success',
1616 $this->getVar( 'wgServer' ),
1617 $this->getVar( 'wgScriptPath' )
1618 );
1619 $this->setVar( '_InstallDone', true );
1620 }
1621
1622 return $installResults;
1623 }
1624
1625 /**
1626 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1627 *
1628 * @return Status
1629 */
1630 public function generateKeys() {
1631 $keys = [ 'wgSecretKey' => 64 ];
1632 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1633 $keys['wgUpgradeKey'] = 16;
1634 }
1635
1636 return $this->doGenerateKeys( $keys );
1637 }
1638
1639 /**
1640 * Generate a secret value for variables using our CryptRand generator.
1641 * Produce a warning if the random source was insecure.
1642 *
1643 * @param array $keys
1644 * @return Status
1645 */
1646 protected function doGenerateKeys( $keys ) {
1647 $status = Status::newGood();
1648
1649 foreach ( $keys as $name => $length ) {
1650 $secretKey = MWCryptRand::generateHex( $length );
1651 $this->setVar( $name, $secretKey );
1652 }
1653
1654 return $status;
1655 }
1656
1657 /**
1658 * Create the first user account, grant it sysop, bureaucrat and interface-admin rights
1659 *
1660 * @return Status
1661 */
1662 protected function createSysop() {
1663 $name = $this->getVar( '_AdminName' );
1664 $user = User::newFromName( $name );
1665
1666 if ( !$user ) {
1667 // We should've validated this earlier anyway!
1668 return Status::newFatal( 'config-admin-error-user', $name );
1669 }
1670
1671 if ( $user->idForName() == 0 ) {
1672 $user->addToDatabase();
1673
1674 try {
1675 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1676 } catch ( PasswordError $pwe ) {
1677 return Status::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1678 }
1679
1680 $user->addGroup( 'sysop' );
1681 $user->addGroup( 'bureaucrat' );
1682 $user->addGroup( 'interface-admin' );
1683 if ( $this->getVar( '_AdminEmail' ) ) {
1684 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1685 }
1686 $user->saveSettings();
1687
1688 // Update user count
1689 $ssUpdate = SiteStatsUpdate::factory( [ 'users' => 1 ] );
1690 $ssUpdate->doUpdate();
1691 }
1692 $status = Status::newGood();
1693
1694 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1695 $this->subscribeToMediaWikiAnnounce( $status );
1696 }
1697
1698 return $status;
1699 }
1700
1701 /**
1702 * @param Status $s
1703 */
1704 private function subscribeToMediaWikiAnnounce( Status $s ) {
1705 $params = [
1706 'email' => $this->getVar( '_AdminEmail' ),
1707 'language' => 'en',
1708 'digest' => 0
1709 ];
1710
1711 // Mailman doesn't support as many languages as we do, so check to make
1712 // sure their selected language is available
1713 $myLang = $this->getVar( '_UserLang' );
1714 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages ) ) {
1715 $myLang = $myLang == 'pt-br' ? 'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1716 $params['language'] = $myLang;
1717 }
1718
1719 if ( MWHttpRequest::canMakeRequests() ) {
1720 $res = MWHttpRequest::factory( $this->mediaWikiAnnounceUrl,
1721 [ 'method' => 'POST', 'postData' => $params ], __METHOD__ )->execute();
1722 if ( !$res->isOK() ) {
1723 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1724 }
1725 } else {
1726 $s->warning( 'config-install-subscribe-notpossible' );
1727 }
1728 }
1729
1730 /**
1731 * Insert Main Page with default content.
1732 *
1733 * @param DatabaseInstaller $installer
1734 * @return Status
1735 */
1736 protected function createMainpage( DatabaseInstaller $installer ) {
1737 $status = Status::newGood();
1738 $title = Title::newMainPage();
1739 if ( $title->exists() ) {
1740 $status->warning( 'config-install-mainpage-exists' );
1741 return $status;
1742 }
1743 try {
1744 $page = WikiPage::factory( $title );
1745 $content = new WikitextContent(
1746 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1747 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1748 );
1749
1750 $status = $page->doEditContent( $content,
1751 '',
1752 EDIT_NEW,
1753 false,
1754 User::newFromName( 'MediaWiki default' )
1755 );
1756 } catch ( Exception $e ) {
1757 // using raw, because $wgShowExceptionDetails can not be set yet
1758 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1759 }
1760
1761 return $status;
1762 }
1763
1764 /**
1765 * Override the necessary bits of the config to run an installation.
1766 */
1767 public static function overrideConfig() {
1768 // Use PHP's built-in session handling, since MediaWiki's
1769 // SessionHandler can't work before we have an object cache set up.
1770 define( 'MW_NO_SESSION_HANDLER', 1 );
1771
1772 // Don't access the database
1773 $GLOBALS['wgUseDatabaseMessages'] = false;
1774 // Don't cache langconv tables
1775 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE;
1776 // Debug-friendly
1777 $GLOBALS['wgShowExceptionDetails'] = true;
1778 $GLOBALS['wgShowHostnames'] = true;
1779 // Don't break forms
1780 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1781
1782 // Allow multiple ob_flush() calls
1783 $GLOBALS['wgDisableOutputCompression'] = true;
1784
1785 // Use a sensible cookie prefix (not my_wiki)
1786 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1787
1788 // Some of the environment checks make shell requests, remove limits
1789 $GLOBALS['wgMaxShellMemory'] = 0;
1790
1791 // Override the default CookieSessionProvider with a dummy
1792 // implementation that won't stomp on PHP's cookies.
1793 $GLOBALS['wgSessionProviders'] = [
1794 [
1795 'class' => InstallerSessionProvider::class,
1796 'args' => [ [
1797 'priority' => 1,
1798 ] ]
1799 ]
1800 ];
1801
1802 // Don't try to use any object cache for SessionManager either.
1803 $GLOBALS['wgSessionCacheType'] = CACHE_NONE;
1804 }
1805
1806 /**
1807 * Add an installation step following the given step.
1808 *
1809 * @param callable $callback A valid installation callback array, in this form:
1810 * [ 'name' => 'some-unique-name', 'callback' => [ $obj, 'function' ] ];
1811 * @param string $findStep The step to find. Omit to put the step at the beginning
1812 */
1813 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1814 $this->extraInstallSteps[$findStep][] = $callback;
1815 }
1816
1817 /**
1818 * Disable the time limit for execution.
1819 * Some long-running pages (Install, Upgrade) will want to do this
1820 */
1821 protected function disableTimeLimit() {
1822 Wikimedia\suppressWarnings();
1823 set_time_limit( 0 );
1824 Wikimedia\restoreWarnings();
1825 }
1826 }