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