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