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