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