Make config-outdated-sqlite parameter numbers consistent with config-*-old
[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 $pcreVersion = explode( ' ', PCRE_VERSION, 2 )[0];
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 $html = Parser::stripOuterParagraph( $html );
700 } catch ( Wikimedia\Services\ServiceDisabledException $e ) {
701 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
702 }
703
704 return $html;
705 }
706
707 /**
708 * @return ParserOptions
709 */
710 public function getParserOptions() {
711 return $this->parserOptions;
712 }
713
714 public function disableLinkPopups() {
715 $this->parserOptions->setExternalLinkTarget( false );
716 }
717
718 public function restoreLinkPopups() {
719 global $wgExternalLinkTarget;
720 $this->parserOptions->setExternalLinkTarget( $wgExternalLinkTarget );
721 }
722
723 /**
724 * Install step which adds a row to the site_stats table with appropriate
725 * initial values.
726 *
727 * @param DatabaseInstaller $installer
728 *
729 * @return Status
730 */
731 public function populateSiteStats( DatabaseInstaller $installer ) {
732 $status = $installer->getConnection();
733 if ( !$status->isOK() ) {
734 return $status;
735 }
736 $status->value->insert(
737 'site_stats',
738 [
739 'ss_row_id' => 1,
740 'ss_total_edits' => 0,
741 'ss_good_articles' => 0,
742 'ss_total_pages' => 0,
743 'ss_users' => 0,
744 'ss_active_users' => 0,
745 'ss_images' => 0
746 ],
747 __METHOD__, 'IGNORE'
748 );
749
750 return Status::newGood();
751 }
752
753 /**
754 * Environment check for DB types.
755 * @return bool
756 */
757 protected function envCheckDB() {
758 global $wgLang;
759
760 $allNames = [];
761
762 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
763 // config-type-sqlite
764 foreach ( self::getDBTypes() as $name ) {
765 $allNames[] = wfMessage( "config-type-$name" )->text();
766 }
767
768 $databases = $this->getCompiledDBs();
769
770 $databases = array_flip( $databases );
771 foreach ( array_keys( $databases ) as $db ) {
772 $installer = $this->getDBInstaller( $db );
773 $status = $installer->checkPrerequisites();
774 if ( !$status->isGood() ) {
775 $this->showStatusMessage( $status );
776 }
777 if ( !$status->isOK() ) {
778 unset( $databases[$db] );
779 }
780 }
781 $databases = array_flip( $databases );
782 if ( !$databases ) {
783 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
784
785 // @todo FIXME: This only works for the web installer!
786 return false;
787 }
788
789 return true;
790 }
791
792 /**
793 * Some versions of libxml+PHP break < and > encoding horribly
794 * @return bool
795 */
796 protected function envCheckBrokenXML() {
797 $test = new PhpXmlBugTester();
798 if ( !$test->ok ) {
799 $this->showError( 'config-brokenlibxml' );
800
801 return false;
802 }
803
804 return true;
805 }
806
807 /**
808 * Environment check for the PCRE module.
809 *
810 * @note If this check were to fail, the parser would
811 * probably throw an exception before the result
812 * of this check is shown to the user.
813 * @return bool
814 */
815 protected function envCheckPCRE() {
816 Wikimedia\suppressWarnings();
817 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
818 // Need to check for \p support too, as PCRE can be compiled
819 // with utf8 support, but not unicode property support.
820 // check that \p{Zs} (space separators) matches
821 // U+3000 (Ideographic space)
822 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\u{3000}-" );
823 Wikimedia\restoreWarnings();
824 if ( $regexd != '--' || $regexprop != '--' ) {
825 $this->showError( 'config-pcre-no-utf8' );
826
827 return false;
828 }
829
830 return true;
831 }
832
833 /**
834 * Environment check for available memory.
835 * @return bool
836 */
837 protected function envCheckMemory() {
838 $limit = ini_get( 'memory_limit' );
839
840 if ( !$limit || $limit == -1 ) {
841 return true;
842 }
843
844 $n = wfShorthandToInteger( $limit );
845
846 if ( $n < $this->minMemorySize * 1024 * 1024 ) {
847 $newLimit = "{$this->minMemorySize}M";
848
849 if ( ini_set( "memory_limit", $newLimit ) === false ) {
850 $this->showMessage( 'config-memory-bad', $limit );
851 } else {
852 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
853 $this->setVar( '_RaiseMemory', true );
854 }
855 }
856
857 return true;
858 }
859
860 /**
861 * Environment check for compiled object cache types.
862 */
863 protected function envCheckCache() {
864 $caches = [];
865 foreach ( $this->objectCaches as $name => $function ) {
866 if ( function_exists( $function ) ) {
867 $caches[$name] = true;
868 }
869 }
870
871 if ( !$caches ) {
872 $this->showMessage( 'config-no-cache-apcu' );
873 }
874
875 $this->setVar( '_Caches', $caches );
876 }
877
878 /**
879 * Scare user to death if they have mod_security or mod_security2
880 * @return bool
881 */
882 protected function envCheckModSecurity() {
883 if ( self::apacheModulePresent( 'mod_security' )
884 || self::apacheModulePresent( 'mod_security2' ) ) {
885 $this->showMessage( 'config-mod-security' );
886 }
887
888 return true;
889 }
890
891 /**
892 * Search for GNU diff3.
893 * @return bool
894 */
895 protected function envCheckDiff3() {
896 $names = [ "gdiff3", "diff3" ];
897 if ( wfIsWindows() ) {
898 $names[] = 'diff3.exe';
899 }
900 $versionInfo = [ '--version', 'GNU diffutils' ];
901
902 $diff3 = ExecutableFinder::findInDefaultPaths( $names, $versionInfo );
903
904 if ( $diff3 ) {
905 $this->setVar( 'wgDiff3', $diff3 );
906 } else {
907 $this->setVar( 'wgDiff3', false );
908 $this->showMessage( 'config-diff3-bad' );
909 }
910
911 return true;
912 }
913
914 /**
915 * Environment check for ImageMagick and GD.
916 * @return bool
917 */
918 protected function envCheckGraphics() {
919 $names = wfIsWindows() ? 'convert.exe' : 'convert';
920 $versionInfo = [ '-version', 'ImageMagick' ];
921 $convert = ExecutableFinder::findInDefaultPaths( $names, $versionInfo );
922
923 $this->setVar( 'wgImageMagickConvertCommand', '' );
924 if ( $convert ) {
925 $this->setVar( 'wgImageMagickConvertCommand', $convert );
926 $this->showMessage( 'config-imagemagick', $convert );
927
928 return true;
929 } elseif ( function_exists( 'imagejpeg' ) ) {
930 $this->showMessage( 'config-gd' );
931 } else {
932 $this->showMessage( 'config-no-scaling' );
933 }
934
935 return true;
936 }
937
938 /**
939 * Search for git.
940 *
941 * @since 1.22
942 * @return bool
943 */
944 protected function envCheckGit() {
945 $names = wfIsWindows() ? 'git.exe' : 'git';
946 $versionInfo = [ '--version', 'git version' ];
947
948 $git = ExecutableFinder::findInDefaultPaths( $names, $versionInfo );
949
950 if ( $git ) {
951 $this->setVar( 'wgGitBin', $git );
952 $this->showMessage( 'config-git', $git );
953 } else {
954 $this->setVar( 'wgGitBin', false );
955 $this->showMessage( 'config-git-bad' );
956 }
957
958 return true;
959 }
960
961 /**
962 * Environment check to inform user which server we've assumed.
963 *
964 * @return bool
965 */
966 protected function envCheckServer() {
967 $server = $this->envGetDefaultServer();
968 if ( $server !== null ) {
969 $this->showMessage( 'config-using-server', $server );
970 }
971 return true;
972 }
973
974 /**
975 * Environment check to inform user which paths we've assumed.
976 *
977 * @return bool
978 */
979 protected function envCheckPath() {
980 $this->showMessage(
981 'config-using-uri',
982 $this->getVar( 'wgServer' ),
983 $this->getVar( 'wgScriptPath' )
984 );
985 return true;
986 }
987
988 /**
989 * Environment check for preferred locale in shell
990 * @return bool
991 */
992 protected function envCheckShellLocale() {
993 $os = php_uname( 's' );
994 $supported = [ 'Linux', 'SunOS', 'HP-UX', 'Darwin' ]; # Tested these
995
996 if ( !in_array( $os, $supported ) ) {
997 return true;
998 }
999
1000 if ( Shell::isDisabled() ) {
1001 return true;
1002 }
1003
1004 # Get a list of available locales.
1005 $result = Shell::command( '/usr/bin/locale', '-a' )
1006 ->execute();
1007
1008 if ( $result->getExitCode() != 0 ) {
1009 return true;
1010 }
1011
1012 $lines = $result->getStdout();
1013 $lines = array_map( 'trim', explode( "\n", $lines ) );
1014 $candidatesByLocale = [];
1015 $candidatesByLang = [];
1016 foreach ( $lines as $line ) {
1017 if ( $line === '' ) {
1018 continue;
1019 }
1020
1021 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1022 continue;
1023 }
1024
1025 list( , $lang, , , ) = $m;
1026
1027 $candidatesByLocale[$m[0]] = $m;
1028 $candidatesByLang[$lang][] = $m;
1029 }
1030
1031 # Try the current value of LANG.
1032 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1033 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1034
1035 return true;
1036 }
1037
1038 # Try the most common ones.
1039 $commonLocales = [ 'C.UTF-8', 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' ];
1040 foreach ( $commonLocales as $commonLocale ) {
1041 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1042 $this->setVar( 'wgShellLocale', $commonLocale );
1043
1044 return true;
1045 }
1046 }
1047
1048 # Is there an available locale in the Wiki's language?
1049 $wikiLang = $this->getVar( 'wgLanguageCode' );
1050
1051 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1052 $m = reset( $candidatesByLang[$wikiLang] );
1053 $this->setVar( 'wgShellLocale', $m[0] );
1054
1055 return true;
1056 }
1057
1058 # Are there any at all?
1059 if ( count( $candidatesByLocale ) ) {
1060 $m = reset( $candidatesByLocale );
1061 $this->setVar( 'wgShellLocale', $m[0] );
1062
1063 return true;
1064 }
1065
1066 # Give up.
1067 return true;
1068 }
1069
1070 /**
1071 * Environment check for the permissions of the uploads directory
1072 * @return bool
1073 */
1074 protected function envCheckUploadsDirectory() {
1075 global $IP;
1076
1077 $dir = $IP . '/images/';
1078 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1079 $safe = !$this->dirIsExecutable( $dir, $url );
1080
1081 if ( !$safe ) {
1082 $this->showMessage( 'config-uploads-not-safe', $dir );
1083 }
1084
1085 return true;
1086 }
1087
1088 /**
1089 * Checks if suhosin.get.max_value_length is set, and if so generate
1090 * a warning because it decreases ResourceLoader performance.
1091 * @return bool
1092 */
1093 protected function envCheckSuhosinMaxValueLength() {
1094 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1095 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1096 // Only warn if the value is below the sane 1024
1097 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1098 }
1099
1100 return true;
1101 }
1102
1103 /**
1104 * Checks if we're running on 64 bit or not. 32 bit is becoming increasingly
1105 * hard to support, so let's at least warn people.
1106 *
1107 * @return bool
1108 */
1109 protected function envCheck64Bit() {
1110 if ( PHP_INT_SIZE == 4 ) {
1111 $this->showMessage( 'config-using-32bit' );
1112 }
1113
1114 return true;
1115 }
1116
1117 /**
1118 * Check the libicu version
1119 */
1120 protected function envCheckLibicu() {
1121 /**
1122 * This needs to be updated something that the latest libicu
1123 * will properly normalize. This normalization was found at
1124 * https://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1125 * Note that we use the hex representation to create the code
1126 * points in order to avoid any Unicode-destroying during transit.
1127 */
1128 $not_normal_c = "\u{FA6C}";
1129 $normal_c = "\u{242EE}";
1130
1131 $useNormalizer = 'php';
1132 $needsUpdate = false;
1133
1134 if ( function_exists( 'normalizer_normalize' ) ) {
1135 $useNormalizer = 'intl';
1136 $intl = normalizer_normalize( $not_normal_c, Normalizer::FORM_C );
1137 if ( $intl !== $normal_c ) {
1138 $needsUpdate = true;
1139 }
1140 }
1141
1142 // Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
1143 if ( $useNormalizer === 'php' ) {
1144 $this->showMessage( 'config-unicode-pure-php-warning' );
1145 } else {
1146 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1147 if ( $needsUpdate ) {
1148 $this->showMessage( 'config-unicode-update-warning' );
1149 }
1150 }
1151 }
1152
1153 /**
1154 * Environment prep for the server hostname.
1155 */
1156 protected function envPrepServer() {
1157 $server = $this->envGetDefaultServer();
1158 if ( $server !== null ) {
1159 $this->setVar( 'wgServer', $server );
1160 }
1161 }
1162
1163 /**
1164 * Helper function to be called from envPrepServer()
1165 * @return string
1166 */
1167 abstract protected function envGetDefaultServer();
1168
1169 /**
1170 * Environment prep for setting $IP and $wgScriptPath.
1171 */
1172 protected function envPrepPath() {
1173 global $IP;
1174 $IP = dirname( dirname( __DIR__ ) );
1175 $this->setVar( 'IP', $IP );
1176 }
1177
1178 /**
1179 * Checks if scripts located in the given directory can be executed via the given URL.
1180 *
1181 * Used only by environment checks.
1182 * @param string $dir
1183 * @param string $url
1184 * @return bool|int|string
1185 */
1186 public function dirIsExecutable( $dir, $url ) {
1187 $scriptTypes = [
1188 'php' => [
1189 "<?php echo 'exec';",
1190 "#!/var/env php\n<?php echo 'exec';",
1191 ],
1192 ];
1193
1194 // it would be good to check other popular languages here, but it'll be slow.
1195
1196 Wikimedia\suppressWarnings();
1197
1198 foreach ( $scriptTypes as $ext => $contents ) {
1199 foreach ( $contents as $source ) {
1200 $file = 'exectest.' . $ext;
1201
1202 if ( !file_put_contents( $dir . $file, $source ) ) {
1203 break;
1204 }
1205
1206 try {
1207 $text = MediaWikiServices::getInstance()->getHttpRequestFactory()->
1208 get( $url . $file, [ 'timeout' => 3 ], __METHOD__ );
1209 } catch ( Exception $e ) {
1210 // HttpRequestFactory::get can throw with allow_url_fopen = false and no curl
1211 // 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 * @suppress SecurityCheck-OTHER It thinks $exts/$IP is user controlled but they are not.
1472 * @return Status
1473 */
1474 protected function includeExtensions() {
1475 global $IP;
1476 $exts = $this->getVar( '_Extensions' );
1477 $IP = $this->getVar( 'IP' );
1478
1479 // Marker for DatabaseUpdater::loadExtensions so we don't
1480 // double load extensions
1481 define( 'MW_EXTENSIONS_LOADED', true );
1482
1483 /**
1484 * We need to include DefaultSettings before including extensions to avoid
1485 * warnings about unset variables. However, the only thing we really
1486 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1487 * if the extension has hidden hook registration in $wgExtensionFunctions,
1488 * but we're not opening that can of worms
1489 * @see https://phabricator.wikimedia.org/T28857
1490 */
1491 global $wgAutoloadClasses;
1492 $wgAutoloadClasses = [];
1493 $queue = [];
1494
1495 require "$IP/includes/DefaultSettings.php";
1496
1497 foreach ( $exts as $e ) {
1498 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1499 $queue["$IP/extensions/$e/extension.json"] = 1;
1500 } else {
1501 require_once "$IP/extensions/$e/$e.php";
1502 }
1503 }
1504
1505 $registry = new ExtensionRegistry();
1506 $data = $registry->readFromQueue( $queue );
1507 $wgAutoloadClasses += $data['autoload'];
1508
1509 // @phan-suppress-next-line PhanUndeclaredVariable $wgHooks is set by DefaultSettings
1510 $hooksWeWant = $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-db-success'
1616 );
1617 $this->setVar( '_InstallDone', true );
1618 }
1619
1620 return $installResults;
1621 }
1622
1623 /**
1624 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1625 *
1626 * @return Status
1627 */
1628 public function generateKeys() {
1629 $keys = [ 'wgSecretKey' => 64 ];
1630 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1631 $keys['wgUpgradeKey'] = 16;
1632 }
1633
1634 return $this->doGenerateKeys( $keys );
1635 }
1636
1637 /**
1638 * Generate a secret value for variables using a secure generator.
1639 *
1640 * @param array $keys
1641 * @return Status
1642 */
1643 protected function doGenerateKeys( $keys ) {
1644 $status = Status::newGood();
1645
1646 foreach ( $keys as $name => $length ) {
1647 $secretKey = MWCryptRand::generateHex( $length );
1648 $this->setVar( $name, $secretKey );
1649 }
1650
1651 return $status;
1652 }
1653
1654 /**
1655 * Create the first user account, grant it sysop, bureaucrat and interface-admin rights
1656 *
1657 * @return Status
1658 */
1659 protected function createSysop() {
1660 $name = $this->getVar( '_AdminName' );
1661 $user = User::newFromName( $name );
1662
1663 if ( !$user ) {
1664 // We should've validated this earlier anyway!
1665 return Status::newFatal( 'config-admin-error-user', $name );
1666 }
1667
1668 if ( $user->idForName() == 0 ) {
1669 $user->addToDatabase();
1670
1671 try {
1672 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1673 } catch ( PasswordError $pwe ) {
1674 return Status::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1675 }
1676
1677 $user->addGroup( 'sysop' );
1678 $user->addGroup( 'bureaucrat' );
1679 $user->addGroup( 'interface-admin' );
1680 if ( $this->getVar( '_AdminEmail' ) ) {
1681 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1682 }
1683 $user->saveSettings();
1684
1685 // Update user count
1686 $ssUpdate = SiteStatsUpdate::factory( [ 'users' => 1 ] );
1687 $ssUpdate->doUpdate();
1688 }
1689 $status = Status::newGood();
1690
1691 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1692 $this->subscribeToMediaWikiAnnounce( $status );
1693 }
1694
1695 return $status;
1696 }
1697
1698 /**
1699 * @param Status $s
1700 */
1701 private function subscribeToMediaWikiAnnounce( Status $s ) {
1702 $params = [
1703 'email' => $this->getVar( '_AdminEmail' ),
1704 'language' => 'en',
1705 'digest' => 0
1706 ];
1707
1708 // Mailman doesn't support as many languages as we do, so check to make
1709 // sure their selected language is available
1710 $myLang = $this->getVar( '_UserLang' );
1711 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages ) ) {
1712 $myLang = $myLang == 'pt-br' ? 'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1713 $params['language'] = $myLang;
1714 }
1715
1716 if ( MWHttpRequest::canMakeRequests() ) {
1717 $res = MWHttpRequest::factory( $this->mediaWikiAnnounceUrl,
1718 [ 'method' => 'POST', 'postData' => $params ], __METHOD__ )->execute();
1719 if ( !$res->isOK() ) {
1720 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1721 }
1722 } else {
1723 $s->warning( 'config-install-subscribe-notpossible' );
1724 }
1725 }
1726
1727 /**
1728 * Insert Main Page with default content.
1729 *
1730 * @param DatabaseInstaller $installer
1731 * @return Status
1732 */
1733 protected function createMainpage( DatabaseInstaller $installer ) {
1734 $status = Status::newGood();
1735 $title = Title::newMainPage();
1736 if ( $title->exists() ) {
1737 $status->warning( 'config-install-mainpage-exists' );
1738 return $status;
1739 }
1740 try {
1741 $page = WikiPage::factory( $title );
1742 $content = new WikitextContent(
1743 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1744 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1745 );
1746
1747 $status = $page->doEditContent( $content,
1748 '',
1749 EDIT_NEW,
1750 false,
1751 User::newFromName( 'MediaWiki default' )
1752 );
1753 } catch ( Exception $e ) {
1754 // using raw, because $wgShowExceptionDetails can not be set yet
1755 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1756 }
1757
1758 return $status;
1759 }
1760
1761 /**
1762 * Override the necessary bits of the config to run an installation.
1763 */
1764 public static function overrideConfig() {
1765 // Use PHP's built-in session handling, since MediaWiki's
1766 // SessionHandler can't work before we have an object cache set up.
1767 define( 'MW_NO_SESSION_HANDLER', 1 );
1768
1769 // Don't access the database
1770 $GLOBALS['wgUseDatabaseMessages'] = false;
1771 // Don't cache langconv tables
1772 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE;
1773 // Debug-friendly
1774 $GLOBALS['wgShowExceptionDetails'] = true;
1775 $GLOBALS['wgShowHostnames'] = true;
1776 // Don't break forms
1777 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1778
1779 // Allow multiple ob_flush() calls
1780 $GLOBALS['wgDisableOutputCompression'] = true;
1781
1782 // Use a sensible cookie prefix (not my_wiki)
1783 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1784
1785 // Some of the environment checks make shell requests, remove limits
1786 $GLOBALS['wgMaxShellMemory'] = 0;
1787
1788 // Override the default CookieSessionProvider with a dummy
1789 // implementation that won't stomp on PHP's cookies.
1790 $GLOBALS['wgSessionProviders'] = [
1791 [
1792 'class' => InstallerSessionProvider::class,
1793 'args' => [ [
1794 'priority' => 1,
1795 ] ]
1796 ]
1797 ];
1798
1799 // Don't try to use any object cache for SessionManager either.
1800 $GLOBALS['wgSessionCacheType'] = CACHE_NONE;
1801 }
1802
1803 /**
1804 * Add an installation step following the given step.
1805 *
1806 * @param callable $callback A valid installation callback array, in this form:
1807 * [ 'name' => 'some-unique-name', 'callback' => [ $obj, 'function' ] ];
1808 * @param string $findStep The step to find. Omit to put the step at the beginning
1809 */
1810 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1811 $this->extraInstallSteps[$findStep][] = $callback;
1812 }
1813
1814 /**
1815 * Disable the time limit for execution.
1816 * Some long-running pages (Install, Upgrade) will want to do this
1817 */
1818 protected function disableTimeLimit() {
1819 Wikimedia\suppressWarnings();
1820 set_time_limit( 0 );
1821 Wikimedia\restoreWarnings();
1822 }
1823 }