Merge "objectcache: Always use interim values on WAN cache tombstones"
[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
28 /**
29 * This documentation group collects source code files with deployment functionality.
30 *
31 * @defgroup Deployment Deployment
32 */
33
34 /**
35 * Base installer class.
36 *
37 * This class provides the base for installation and update functionality
38 * for both MediaWiki core and extensions.
39 *
40 * @ingroup Deployment
41 * @since 1.17
42 */
43 abstract class Installer {
44
45 /**
46 * The oldest version of PCRE we can support.
47 *
48 * Defining this is necessary because PHP may be linked with a system version
49 * of PCRE, which may be older than that bundled with the minimum PHP version.
50 */
51 const MINIMUM_PCRE_VERSION = '7.2';
52
53 /**
54 * @var array
55 */
56 protected $settings;
57
58 /**
59 * List of detected DBs, access using getCompiledDBs().
60 *
61 * @var array
62 */
63 protected $compiledDBs;
64
65 /**
66 * Cached DB installer instances, access using getDBInstaller().
67 *
68 * @var array
69 */
70 protected $dbInstallers = [];
71
72 /**
73 * Minimum memory size in MB.
74 *
75 * @var int
76 */
77 protected $minMemorySize = 50;
78
79 /**
80 * Cached Title, used by parse().
81 *
82 * @var Title
83 */
84 protected $parserTitle;
85
86 /**
87 * Cached ParserOptions, used by parse().
88 *
89 * @var ParserOptions
90 */
91 protected $parserOptions;
92
93 /**
94 * Known database types. These correspond to the class names <type>Installer,
95 * and are also MediaWiki database types valid for $wgDBtype.
96 *
97 * To add a new type, create a <type>Installer class and a Database<type>
98 * class, and add a config-type-<type> message to MessagesEn.php.
99 *
100 * @var array
101 */
102 protected static $dbTypes = [
103 'mysql',
104 'postgres',
105 'oracle',
106 'mssql',
107 'sqlite',
108 ];
109
110 /**
111 * A list of environment check methods called by doEnvironmentChecks().
112 * These may output warnings using showMessage(), and/or abort the
113 * installation process by returning false.
114 *
115 * For the WebInstaller these are only called on the Welcome page,
116 * if these methods have side-effects that should affect later page loads
117 * (as well as the generated stylesheet), use envPreps instead.
118 *
119 * @var array
120 */
121 protected $envChecks = [
122 'envCheckDB',
123 'envCheckBrokenXML',
124 'envCheckPCRE',
125 'envCheckMemory',
126 'envCheckCache',
127 'envCheckModSecurity',
128 'envCheckDiff3',
129 'envCheckGraphics',
130 'envCheckGit',
131 'envCheckServer',
132 'envCheckPath',
133 'envCheckShellLocale',
134 'envCheckUploadsDirectory',
135 'envCheckLibicu',
136 'envCheckSuhosinMaxValueLength',
137 'envCheck64Bit',
138 ];
139
140 /**
141 * A list of environment preparation methods called by doEnvironmentPreps().
142 *
143 * @var array
144 */
145 protected $envPreps = [
146 'envPrepServer',
147 'envPrepPath',
148 ];
149
150 /**
151 * MediaWiki configuration globals that will eventually be passed through
152 * to LocalSettings.php. The names only are given here, the defaults
153 * typically come from DefaultSettings.php.
154 *
155 * @var array
156 */
157 protected $defaultVarNames = [
158 'wgSitename',
159 'wgPasswordSender',
160 'wgLanguageCode',
161 'wgRightsIcon',
162 'wgRightsText',
163 'wgRightsUrl',
164 'wgEnableEmail',
165 'wgEnableUserEmail',
166 'wgEnotifUserTalk',
167 'wgEnotifWatchlist',
168 'wgEmailAuthentication',
169 'wgDBname',
170 'wgDBtype',
171 'wgDiff3',
172 'wgImageMagickConvertCommand',
173 'wgGitBin',
174 'IP',
175 'wgScriptPath',
176 'wgMetaNamespace',
177 'wgDeletedDirectory',
178 'wgEnableUploads',
179 'wgShellLocale',
180 'wgSecretKey',
181 'wgUseInstantCommons',
182 'wgUpgradeKey',
183 'wgDefaultSkin',
184 'wgPingback',
185 ];
186
187 /**
188 * Variables that are stored alongside globals, and are used for any
189 * configuration of the installation process aside from the MediaWiki
190 * configuration. Map of names to defaults.
191 *
192 * @var array
193 */
194 protected $internalDefaults = [
195 '_UserLang' => 'en',
196 '_Environment' => false,
197 '_RaiseMemory' => false,
198 '_UpgradeDone' => false,
199 '_InstallDone' => false,
200 '_Caches' => [],
201 '_InstallPassword' => '',
202 '_SameAccount' => true,
203 '_CreateDBAccount' => false,
204 '_NamespaceType' => 'site-name',
205 '_AdminName' => '', // will be set later, when the user selects language
206 '_AdminPassword' => '',
207 '_AdminPasswordConfirm' => '',
208 '_AdminEmail' => '',
209 '_Subscribe' => false,
210 '_SkipOptional' => 'continue',
211 '_RightsProfile' => 'wiki',
212 '_LicenseCode' => 'none',
213 '_CCDone' => false,
214 '_Extensions' => [],
215 '_Skins' => [],
216 '_MemCachedServers' => '',
217 '_UpgradeKeySupplied' => false,
218 '_ExistingDBSettings' => false,
219
220 // $wgLogo is probably wrong (T50084); set something that will work.
221 // Single quotes work fine here, as LocalSettingsGenerator outputs this unescaped.
222 'wgLogo' => '$wgResourceBasePath/resources/assets/wiki.png',
223 'wgAuthenticationTokenVersion' => 1,
224 ];
225
226 /**
227 * The actual list of installation steps. This will be initialized by getInstallSteps()
228 *
229 * @var array
230 */
231 private $installSteps = [];
232
233 /**
234 * Extra steps for installation, for things like DatabaseInstallers to modify
235 *
236 * @var array
237 */
238 protected $extraInstallSteps = [];
239
240 /**
241 * Known object cache types and the functions used to test for their existence.
242 *
243 * @var array
244 */
245 protected $objectCaches = [
246 'xcache' => 'xcache_get',
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' ];
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 $this->parserOptions->setEditSection( false );
450 $this->parserOptions->setWrapOutputClass( false );
451 // Don't try to access DB before user language is initialised
452 $this->setParserLanguage( Language::factory( 'en' ) );
453 }
454
455 /**
456 * Get a list of known DB types.
457 *
458 * @return array
459 */
460 public static function getDBTypes() {
461 return self::$dbTypes;
462 }
463
464 /**
465 * Do initial checks of the PHP environment. Set variables according to
466 * the observed environment.
467 *
468 * It's possible that this may be called under the CLI SAPI, not the SAPI
469 * that the wiki will primarily run under. In that case, the subclass should
470 * initialise variables such as wgScriptPath, before calling this function.
471 *
472 * Under the web subclass, it can already be assumed that PHP 5+ is in use
473 * and that sessions are working.
474 *
475 * @return Status
476 */
477 public function doEnvironmentChecks() {
478 // Php version has already been checked by entry scripts
479 // Show message here for information purposes
480 if ( wfIsHHVM() ) {
481 $this->showMessage( 'config-env-hhvm', HHVM_VERSION );
482 } else {
483 $this->showMessage( 'config-env-php', PHP_VERSION );
484 }
485
486 $good = true;
487 // Must go here because an old version of PCRE can prevent other checks from completing
488 list( $pcreVersion ) = explode( ' ', PCRE_VERSION, 2 );
489 if ( version_compare( $pcreVersion, self::MINIMUM_PCRE_VERSION, '<' ) ) {
490 $this->showError( 'config-pcre-old', self::MINIMUM_PCRE_VERSION, $pcreVersion );
491 $good = false;
492 } else {
493 foreach ( $this->envChecks as $check ) {
494 $status = $this->$check();
495 if ( $status === false ) {
496 $good = false;
497 }
498 }
499 }
500
501 $this->setVar( '_Environment', $good );
502
503 return $good ? Status::newGood() : Status::newFatal( 'config-env-bad' );
504 }
505
506 public function doEnvironmentPreps() {
507 foreach ( $this->envPreps as $prep ) {
508 $this->$prep();
509 }
510 }
511
512 /**
513 * Set a MW configuration variable, or internal installer configuration variable.
514 *
515 * @param string $name
516 * @param mixed $value
517 */
518 public function setVar( $name, $value ) {
519 $this->settings[$name] = $value;
520 }
521
522 /**
523 * Get an MW configuration variable, or internal installer configuration variable.
524 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
525 * Installer variables are typically prefixed by an underscore.
526 *
527 * @param string $name
528 * @param mixed $default
529 *
530 * @return mixed
531 */
532 public function getVar( $name, $default = null ) {
533 if ( !isset( $this->settings[$name] ) ) {
534 return $default;
535 } else {
536 return $this->settings[$name];
537 }
538 }
539
540 /**
541 * Get a list of DBs supported by current PHP setup
542 *
543 * @return array
544 */
545 public function getCompiledDBs() {
546 return $this->compiledDBs;
547 }
548
549 /**
550 * Get the DatabaseInstaller class name for this type
551 *
552 * @param string $type database type ($wgDBtype)
553 * @return string Class name
554 * @since 1.30
555 */
556 public static function getDBInstallerClass( $type ) {
557 return ucfirst( $type ) . 'Installer';
558 }
559
560 /**
561 * Get an instance of DatabaseInstaller for the specified DB type.
562 *
563 * @param mixed $type DB installer for which is needed, false to use default.
564 *
565 * @return DatabaseInstaller
566 */
567 public function getDBInstaller( $type = false ) {
568 if ( !$type ) {
569 $type = $this->getVar( 'wgDBtype' );
570 }
571
572 $type = strtolower( $type );
573
574 if ( !isset( $this->dbInstallers[$type] ) ) {
575 $class = self::getDBInstallerClass( $type );
576 $this->dbInstallers[$type] = new $class( $this );
577 }
578
579 return $this->dbInstallers[$type];
580 }
581
582 /**
583 * Determine if LocalSettings.php exists. If it does, return its variables.
584 *
585 * @return array|false
586 */
587 public static function getExistingLocalSettings() {
588 global $IP;
589
590 // You might be wondering why this is here. Well if you don't do this
591 // then some poorly-formed extensions try to call their own classes
592 // after immediately registering them. We really need to get extension
593 // registration out of the global scope and into a real format.
594 // @see https://phabricator.wikimedia.org/T69440
595 global $wgAutoloadClasses;
596 $wgAutoloadClasses = [];
597
598 // @codingStandardsIgnoreStart
599 // LocalSettings.php should not call functions, except wfLoadSkin/wfLoadExtensions
600 // Define the required globals here, to ensure, the functions can do it work correctly.
601 global $wgExtensionDirectory, $wgStyleDirectory;
602 // @codingStandardsIgnoreEnd
603
604 MediaWiki\suppressWarnings();
605 $_lsExists = file_exists( "$IP/LocalSettings.php" );
606 MediaWiki\restoreWarnings();
607
608 if ( !$_lsExists ) {
609 return false;
610 }
611 unset( $_lsExists );
612
613 require "$IP/includes/DefaultSettings.php";
614 require "$IP/LocalSettings.php";
615
616 return get_defined_vars();
617 }
618
619 /**
620 * Get a fake password for sending back to the user in HTML.
621 * This is a security mechanism to avoid compromise of the password in the
622 * event of session ID compromise.
623 *
624 * @param string $realPassword
625 *
626 * @return string
627 */
628 public function getFakePassword( $realPassword ) {
629 return str_repeat( '*', strlen( $realPassword ) );
630 }
631
632 /**
633 * Set a variable which stores a password, except if the new value is a
634 * fake password in which case leave it as it is.
635 *
636 * @param string $name
637 * @param mixed $value
638 */
639 public function setPassword( $name, $value ) {
640 if ( !preg_match( '/^\*+$/', $value ) ) {
641 $this->setVar( $name, $value );
642 }
643 }
644
645 /**
646 * On POSIX systems return the primary group of the webserver we're running under.
647 * On other systems just returns null.
648 *
649 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
650 * webserver user before he can install.
651 *
652 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
653 *
654 * @return mixed
655 */
656 public static function maybeGetWebserverPrimaryGroup() {
657 if ( !function_exists( 'posix_getegid' ) || !function_exists( 'posix_getpwuid' ) ) {
658 # I don't know this, this isn't UNIX.
659 return null;
660 }
661
662 # posix_getegid() *not* getmygid() because we want the group of the webserver,
663 # not whoever owns the current script.
664 $gid = posix_getegid();
665 $group = posix_getpwuid( $gid )['name'];
666
667 return $group;
668 }
669
670 /**
671 * Convert wikitext $text to HTML.
672 *
673 * This is potentially error prone since many parser features require a complete
674 * installed MW database. The solution is to just not use those features when you
675 * write your messages. This appears to work well enough. Basic formatting and
676 * external links work just fine.
677 *
678 * But in case a translator decides to throw in a "#ifexist" or internal link or
679 * whatever, this function is guarded to catch the attempted DB access and to present
680 * some fallback text.
681 *
682 * @param string $text
683 * @param bool $lineStart
684 * @return string
685 */
686 public function parse( $text, $lineStart = false ) {
687 global $wgParser;
688
689 try {
690 $out = $wgParser->parse( $text, $this->parserTitle, $this->parserOptions, $lineStart );
691 $html = $out->getText();
692 } catch ( MediaWiki\Services\ServiceDisabledException $e ) {
693 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
694
695 if ( !empty( $this->debug ) ) {
696 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
697 }
698 }
699
700 return $html;
701 }
702
703 /**
704 * @return ParserOptions
705 */
706 public function getParserOptions() {
707 return $this->parserOptions;
708 }
709
710 public function disableLinkPopups() {
711 $this->parserOptions->setExternalLinkTarget( false );
712 }
713
714 public function restoreLinkPopups() {
715 global $wgExternalLinkTarget;
716 $this->parserOptions->setExternalLinkTarget( $wgExternalLinkTarget );
717 }
718
719 /**
720 * Install step which adds a row to the site_stats table with appropriate
721 * initial values.
722 *
723 * @param DatabaseInstaller $installer
724 *
725 * @return Status
726 */
727 public function populateSiteStats( DatabaseInstaller $installer ) {
728 $status = $installer->getConnection();
729 if ( !$status->isOK() ) {
730 return $status;
731 }
732 $status->value->insert(
733 'site_stats',
734 [
735 'ss_row_id' => 1,
736 'ss_total_edits' => 0,
737 'ss_good_articles' => 0,
738 'ss_total_pages' => 0,
739 'ss_users' => 0,
740 'ss_active_users' => 0,
741 'ss_images' => 0
742 ],
743 __METHOD__, 'IGNORE'
744 );
745
746 return Status::newGood();
747 }
748
749 /**
750 * Environment check for DB types.
751 * @return bool
752 */
753 protected function envCheckDB() {
754 global $wgLang;
755
756 $allNames = [];
757
758 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
759 // config-type-sqlite
760 foreach ( self::getDBTypes() as $name ) {
761 $allNames[] = wfMessage( "config-type-$name" )->text();
762 }
763
764 $databases = $this->getCompiledDBs();
765
766 $databases = array_flip( $databases );
767 foreach ( array_keys( $databases ) as $db ) {
768 $installer = $this->getDBInstaller( $db );
769 $status = $installer->checkPrerequisites();
770 if ( !$status->isGood() ) {
771 $this->showStatusMessage( $status );
772 }
773 if ( !$status->isOK() ) {
774 unset( $databases[$db] );
775 }
776 }
777 $databases = array_flip( $databases );
778 if ( !$databases ) {
779 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
780
781 // @todo FIXME: This only works for the web installer!
782 return false;
783 }
784
785 return true;
786 }
787
788 /**
789 * Some versions of libxml+PHP break < and > encoding horribly
790 * @return bool
791 */
792 protected function envCheckBrokenXML() {
793 $test = new PhpXmlBugTester();
794 if ( !$test->ok ) {
795 $this->showError( 'config-brokenlibxml' );
796
797 return false;
798 }
799
800 return true;
801 }
802
803 /**
804 * Environment check for the PCRE module.
805 *
806 * @note If this check were to fail, the parser would
807 * probably throw an exception before the result
808 * of this check is shown to the user.
809 * @return bool
810 */
811 protected function envCheckPCRE() {
812 MediaWiki\suppressWarnings();
813 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
814 // Need to check for \p support too, as PCRE can be compiled
815 // with utf8 support, but not unicode property support.
816 // check that \p{Zs} (space separators) matches
817 // U+3000 (Ideographic space)
818 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
819 MediaWiki\restoreWarnings();
820 if ( $regexd != '--' || $regexprop != '--' ) {
821 $this->showError( 'config-pcre-no-utf8' );
822
823 return false;
824 }
825
826 return true;
827 }
828
829 /**
830 * Environment check for available memory.
831 * @return bool
832 */
833 protected function envCheckMemory() {
834 $limit = ini_get( 'memory_limit' );
835
836 if ( !$limit || $limit == -1 ) {
837 return true;
838 }
839
840 $n = wfShorthandToInteger( $limit );
841
842 if ( $n < $this->minMemorySize * 1024 * 1024 ) {
843 $newLimit = "{$this->minMemorySize}M";
844
845 if ( ini_set( "memory_limit", $newLimit ) === false ) {
846 $this->showMessage( 'config-memory-bad', $limit );
847 } else {
848 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
849 $this->setVar( '_RaiseMemory', true );
850 }
851 }
852
853 return true;
854 }
855
856 /**
857 * Environment check for compiled object cache types.
858 */
859 protected function envCheckCache() {
860 $caches = [];
861 foreach ( $this->objectCaches as $name => $function ) {
862 if ( function_exists( $function ) ) {
863 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
864 continue;
865 }
866 $caches[$name] = true;
867 }
868 }
869
870 if ( !$caches ) {
871 $key = 'config-no-cache-apcu';
872 $this->showMessage( $key );
873 }
874
875 $this->setVar( '_Caches', $caches );
876 }
877
878 /**
879 * Scare user to death if they have mod_security or mod_security2
880 * @return bool
881 */
882 protected function envCheckModSecurity() {
883 if ( self::apacheModulePresent( 'mod_security' )
884 || self::apacheModulePresent( 'mod_security2' ) ) {
885 $this->showMessage( 'config-mod-security' );
886 }
887
888 return true;
889 }
890
891 /**
892 * Search for GNU diff3.
893 * @return bool
894 */
895 protected function envCheckDiff3() {
896 $names = [ "gdiff3", "diff3", "diff3.exe" ];
897 $versionInfo = [ '$1 --version 2>&1', 'GNU diffutils' ];
898
899 $diff3 = self::locateExecutableInDefaultPaths( $names, $versionInfo );
900
901 if ( $diff3 ) {
902 $this->setVar( 'wgDiff3', $diff3 );
903 } else {
904 $this->setVar( 'wgDiff3', false );
905 $this->showMessage( 'config-diff3-bad' );
906 }
907
908 return true;
909 }
910
911 /**
912 * Environment check for ImageMagick and GD.
913 * @return bool
914 */
915 protected function envCheckGraphics() {
916 $names = [ wfIsWindows() ? 'convert.exe' : 'convert' ];
917 $versionInfo = [ '$1 -version', 'ImageMagick' ];
918 $convert = self::locateExecutableInDefaultPaths( $names, $versionInfo );
919
920 $this->setVar( 'wgImageMagickConvertCommand', '' );
921 if ( $convert ) {
922 $this->setVar( 'wgImageMagickConvertCommand', $convert );
923 $this->showMessage( 'config-imagemagick', $convert );
924
925 return true;
926 } elseif ( function_exists( 'imagejpeg' ) ) {
927 $this->showMessage( 'config-gd' );
928 } else {
929 $this->showMessage( 'config-no-scaling' );
930 }
931
932 return true;
933 }
934
935 /**
936 * Search for git.
937 *
938 * @since 1.22
939 * @return bool
940 */
941 protected function envCheckGit() {
942 $names = [ wfIsWindows() ? 'git.exe' : 'git' ];
943 $versionInfo = [ '$1 --version', 'git version' ];
944
945 $git = self::locateExecutableInDefaultPaths( $names, $versionInfo );
946
947 if ( $git ) {
948 $this->setVar( 'wgGitBin', $git );
949 $this->showMessage( 'config-git', $git );
950 } else {
951 $this->setVar( 'wgGitBin', false );
952 $this->showMessage( 'config-git-bad' );
953 }
954
955 return true;
956 }
957
958 /**
959 * Environment check to inform user which server we've assumed.
960 *
961 * @return bool
962 */
963 protected function envCheckServer() {
964 $server = $this->envGetDefaultServer();
965 if ( $server !== null ) {
966 $this->showMessage( 'config-using-server', $server );
967 }
968 return true;
969 }
970
971 /**
972 * Environment check to inform user which paths we've assumed.
973 *
974 * @return bool
975 */
976 protected function envCheckPath() {
977 $this->showMessage(
978 'config-using-uri',
979 $this->getVar( 'wgServer' ),
980 $this->getVar( 'wgScriptPath' )
981 );
982 return true;
983 }
984
985 /**
986 * Environment check for preferred locale in shell
987 * @return bool
988 */
989 protected function envCheckShellLocale() {
990 $os = php_uname( 's' );
991 $supported = [ 'Linux', 'SunOS', 'HP-UX', 'Darwin' ]; # Tested these
992
993 if ( !in_array( $os, $supported ) ) {
994 return true;
995 }
996
997 # Get a list of available locales.
998 $ret = false;
999 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1000
1001 if ( $ret ) {
1002 return true;
1003 }
1004
1005 $lines = array_map( 'trim', explode( "\n", $lines ) );
1006 $candidatesByLocale = [];
1007 $candidatesByLang = [];
1008
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 * Convert a hex string representing a Unicode code point to that code point.
1112 * @param string $c
1113 * @return string|false
1114 */
1115 protected function unicodeChar( $c ) {
1116 $c = hexdec( $c );
1117 if ( $c <= 0x7F ) {
1118 return chr( $c );
1119 } elseif ( $c <= 0x7FF ) {
1120 return chr( 0xC0 | $c >> 6 ) . chr( 0x80 | $c & 0x3F );
1121 } elseif ( $c <= 0xFFFF ) {
1122 return chr( 0xE0 | $c >> 12 ) . chr( 0x80 | $c >> 6 & 0x3F ) .
1123 chr( 0x80 | $c & 0x3F );
1124 } elseif ( $c <= 0x10FFFF ) {
1125 return chr( 0xF0 | $c >> 18 ) . chr( 0x80 | $c >> 12 & 0x3F ) .
1126 chr( 0x80 | $c >> 6 & 0x3F ) .
1127 chr( 0x80 | $c & 0x3F );
1128 } else {
1129 return false;
1130 }
1131 }
1132
1133 /**
1134 * Check the libicu version
1135 */
1136 protected function envCheckLibicu() {
1137 /**
1138 * This needs to be updated something that the latest libicu
1139 * will properly normalize. This normalization was found at
1140 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1141 * Note that we use the hex representation to create the code
1142 * points in order to avoid any Unicode-destroying during transit.
1143 */
1144 $not_normal_c = $this->unicodeChar( "FA6C" );
1145 $normal_c = $this->unicodeChar( "242EE" );
1146
1147 $useNormalizer = 'php';
1148 $needsUpdate = false;
1149
1150 if ( function_exists( 'normalizer_normalize' ) ) {
1151 $useNormalizer = 'intl';
1152 $intl = normalizer_normalize( $not_normal_c, Normalizer::FORM_C );
1153 if ( $intl !== $normal_c ) {
1154 $needsUpdate = true;
1155 }
1156 }
1157
1158 // Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
1159 if ( $useNormalizer === 'php' ) {
1160 $this->showMessage( 'config-unicode-pure-php-warning' );
1161 } else {
1162 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1163 if ( $needsUpdate ) {
1164 $this->showMessage( 'config-unicode-update-warning' );
1165 }
1166 }
1167 }
1168
1169 /**
1170 * Environment prep for the server hostname.
1171 */
1172 protected function envPrepServer() {
1173 $server = $this->envGetDefaultServer();
1174 if ( $server !== null ) {
1175 $this->setVar( 'wgServer', $server );
1176 }
1177 }
1178
1179 /**
1180 * Helper function to be called from envPrepServer()
1181 * @return string
1182 */
1183 abstract protected function envGetDefaultServer();
1184
1185 /**
1186 * Environment prep for setting $IP and $wgScriptPath.
1187 */
1188 protected function envPrepPath() {
1189 global $IP;
1190 $IP = dirname( dirname( __DIR__ ) );
1191 $this->setVar( 'IP', $IP );
1192 }
1193
1194 /**
1195 * Get an array of likely places we can find executables. Check a bunch
1196 * of known Unix-like defaults, as well as the PATH environment variable
1197 * (which should maybe make it work for Windows?)
1198 *
1199 * @return array
1200 */
1201 protected static function getPossibleBinPaths() {
1202 return array_merge(
1203 [ '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1204 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ],
1205 explode( PATH_SEPARATOR, getenv( 'PATH' ) )
1206 );
1207 }
1208
1209 /**
1210 * Search a path for any of the given executable names. Returns the
1211 * executable name if found. Also checks the version string returned
1212 * by each executable.
1213 *
1214 * Used only by environment checks.
1215 *
1216 * @param string $path Path to search
1217 * @param array $names Array of executable names
1218 * @param array|bool $versionInfo False or array with two members:
1219 * 0 => Command to run for version check, with $1 for the full executable name
1220 * 1 => String to compare the output with
1221 *
1222 * If $versionInfo is not false, only executables with a version
1223 * matching $versionInfo[1] will be returned.
1224 * @return bool|string
1225 */
1226 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1227 if ( !is_array( $names ) ) {
1228 $names = [ $names ];
1229 }
1230
1231 foreach ( $names as $name ) {
1232 $command = $path . DIRECTORY_SEPARATOR . $name;
1233
1234 MediaWiki\suppressWarnings();
1235 $file_exists = is_executable( $command );
1236 MediaWiki\restoreWarnings();
1237
1238 if ( $file_exists ) {
1239 if ( !$versionInfo ) {
1240 return $command;
1241 }
1242
1243 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1244 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1245 return $command;
1246 }
1247 }
1248 }
1249
1250 return false;
1251 }
1252
1253 /**
1254 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1255 * @see locateExecutable()
1256 * @param array $names Array of possible names.
1257 * @param array|bool $versionInfo Default: false or array with two members:
1258 * 0 => Command to run for version check, with $1 for the full executable name
1259 * 1 => String to compare the output with
1260 *
1261 * If $versionInfo is not false, only executables with a version
1262 * matching $versionInfo[1] will be returned.
1263 * @return bool|string
1264 */
1265 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1266 foreach ( self::getPossibleBinPaths() as $path ) {
1267 $exe = self::locateExecutable( $path, $names, $versionInfo );
1268 if ( $exe !== false ) {
1269 return $exe;
1270 }
1271 }
1272
1273 return false;
1274 }
1275
1276 /**
1277 * Checks if scripts located in the given directory can be executed via the given URL.
1278 *
1279 * Used only by environment checks.
1280 * @param string $dir
1281 * @param string $url
1282 * @return bool|int|string
1283 */
1284 public function dirIsExecutable( $dir, $url ) {
1285 $scriptTypes = [
1286 'php' => [
1287 "<?php echo 'ex' . 'ec';",
1288 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1289 ],
1290 ];
1291
1292 // it would be good to check other popular languages here, but it'll be slow.
1293
1294 MediaWiki\suppressWarnings();
1295
1296 foreach ( $scriptTypes as $ext => $contents ) {
1297 foreach ( $contents as $source ) {
1298 $file = 'exectest.' . $ext;
1299
1300 if ( !file_put_contents( $dir . $file, $source ) ) {
1301 break;
1302 }
1303
1304 try {
1305 $text = Http::get( $url . $file, [ 'timeout' => 3 ], __METHOD__ );
1306 } catch ( Exception $e ) {
1307 // Http::get throws with allow_url_fopen = false and no curl extension.
1308 $text = null;
1309 }
1310 unlink( $dir . $file );
1311
1312 if ( $text == 'exec' ) {
1313 MediaWiki\restoreWarnings();
1314
1315 return $ext;
1316 }
1317 }
1318 }
1319
1320 MediaWiki\restoreWarnings();
1321
1322 return false;
1323 }
1324
1325 /**
1326 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1327 *
1328 * @param string $moduleName Name of module to check.
1329 * @return bool
1330 */
1331 public static function apacheModulePresent( $moduleName ) {
1332 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1333 return true;
1334 }
1335 // try it the hard way
1336 ob_start();
1337 phpinfo( INFO_MODULES );
1338 $info = ob_get_clean();
1339
1340 return strpos( $info, $moduleName ) !== false;
1341 }
1342
1343 /**
1344 * ParserOptions are constructed before we determined the language, so fix it
1345 *
1346 * @param Language $lang
1347 */
1348 public function setParserLanguage( $lang ) {
1349 $this->parserOptions->setTargetLanguage( $lang );
1350 $this->parserOptions->setUserLang( $lang );
1351 }
1352
1353 /**
1354 * Overridden by WebInstaller to provide lastPage parameters.
1355 * @param string $page
1356 * @return string
1357 */
1358 protected function getDocUrl( $page ) {
1359 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1360 }
1361
1362 /**
1363 * Finds extensions that follow the format /$directory/Name/Name.php,
1364 * and returns an array containing the value for 'Name' for each found extension.
1365 *
1366 * Reasonable values for $directory include 'extensions' (the default) and 'skins'.
1367 *
1368 * @param string $directory Directory to search in
1369 * @return array [ $extName => [ 'screenshots' => [ '...' ] ]
1370 */
1371 public function findExtensions( $directory = 'extensions' ) {
1372 if ( $this->getVar( 'IP' ) === null ) {
1373 return [];
1374 }
1375
1376 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1377 if ( !is_readable( $extDir ) || !is_dir( $extDir ) ) {
1378 return [];
1379 }
1380
1381 // extensions -> extension.json, skins -> skin.json
1382 $jsonFile = substr( $directory, 0, strlen( $directory ) - 1 ) . '.json';
1383
1384 $dh = opendir( $extDir );
1385 $exts = [];
1386 while ( ( $file = readdir( $dh ) ) !== false ) {
1387 if ( !is_dir( "$extDir/$file" ) ) {
1388 continue;
1389 }
1390 if ( file_exists( "$extDir/$file/$jsonFile" ) || file_exists( "$extDir/$file/$file.php" ) ) {
1391 // Extension exists. Now see if there are screenshots
1392 $exts[$file] = [];
1393 if ( is_dir( "$extDir/$file/screenshots" ) ) {
1394 $paths = glob( "$extDir/$file/screenshots/*.png" );
1395 foreach ( $paths as $path ) {
1396 $exts[$file]['screenshots'][] = str_replace( $extDir, "../$directory", $path );
1397 }
1398
1399 }
1400 }
1401 }
1402 closedir( $dh );
1403 uksort( $exts, 'strnatcasecmp' );
1404
1405 return $exts;
1406 }
1407
1408 /**
1409 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1410 * but will fall back to another if the default skin is missing and some other one is present
1411 * instead.
1412 *
1413 * @param string[] $skinNames Names of installed skins.
1414 * @return string
1415 */
1416 public function getDefaultSkin( array $skinNames ) {
1417 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1418 if ( !$skinNames || in_array( $defaultSkin, $skinNames ) ) {
1419 return $defaultSkin;
1420 } else {
1421 return $skinNames[0];
1422 }
1423 }
1424
1425 /**
1426 * Installs the auto-detected extensions.
1427 *
1428 * @return Status
1429 */
1430 protected function includeExtensions() {
1431 global $IP;
1432 $exts = $this->getVar( '_Extensions' );
1433 $IP = $this->getVar( 'IP' );
1434
1435 /**
1436 * We need to include DefaultSettings before including extensions to avoid
1437 * warnings about unset variables. However, the only thing we really
1438 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1439 * if the extension has hidden hook registration in $wgExtensionFunctions,
1440 * but we're not opening that can of worms
1441 * @see https://phabricator.wikimedia.org/T28857
1442 */
1443 global $wgAutoloadClasses;
1444 $wgAutoloadClasses = [];
1445 $queue = [];
1446
1447 require "$IP/includes/DefaultSettings.php";
1448
1449 foreach ( $exts as $e ) {
1450 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1451 $queue["$IP/extensions/$e/extension.json"] = 1;
1452 } else {
1453 require_once "$IP/extensions/$e/$e.php";
1454 }
1455 }
1456
1457 $registry = new ExtensionRegistry();
1458 $data = $registry->readFromQueue( $queue );
1459 $wgAutoloadClasses += $data['autoload'];
1460
1461 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1462 /** @suppress PhanUndeclaredVariable $wgHooks is set by DefaultSettings */
1463 $wgHooks['LoadExtensionSchemaUpdates'] : [];
1464
1465 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1466 $hooksWeWant = array_merge_recursive(
1467 $hooksWeWant,
1468 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1469 );
1470 }
1471 // Unset everyone else's hooks. Lord knows what someone might be doing
1472 // in ParserFirstCallInit (see T29171)
1473 $GLOBALS['wgHooks'] = [ 'LoadExtensionSchemaUpdates' => $hooksWeWant ];
1474
1475 return Status::newGood();
1476 }
1477
1478 /**
1479 * Get an array of install steps. Should always be in the format of
1480 * [
1481 * 'name' => 'someuniquename',
1482 * 'callback' => [ $obj, 'method' ],
1483 * ]
1484 * There must be a config-install-$name message defined per step, which will
1485 * be shown on install.
1486 *
1487 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1488 * @return array
1489 */
1490 protected function getInstallSteps( DatabaseInstaller $installer ) {
1491 $coreInstallSteps = [
1492 [ 'name' => 'database', 'callback' => [ $installer, 'setupDatabase' ] ],
1493 [ 'name' => 'tables', 'callback' => [ $installer, 'createTables' ] ],
1494 [ 'name' => 'interwiki', 'callback' => [ $installer, 'populateInterwikiTable' ] ],
1495 [ 'name' => 'stats', 'callback' => [ $this, 'populateSiteStats' ] ],
1496 [ 'name' => 'keys', 'callback' => [ $this, 'generateKeys' ] ],
1497 [ 'name' => 'updates', 'callback' => [ $installer, 'insertUpdateKeys' ] ],
1498 [ 'name' => 'sysop', 'callback' => [ $this, 'createSysop' ] ],
1499 [ 'name' => 'mainpage', 'callback' => [ $this, 'createMainpage' ] ],
1500 ];
1501
1502 // Build the array of install steps starting from the core install list,
1503 // then adding any callbacks that wanted to attach after a given step
1504 foreach ( $coreInstallSteps as $step ) {
1505 $this->installSteps[] = $step;
1506 if ( isset( $this->extraInstallSteps[$step['name']] ) ) {
1507 $this->installSteps = array_merge(
1508 $this->installSteps,
1509 $this->extraInstallSteps[$step['name']]
1510 );
1511 }
1512 }
1513
1514 // Prepend any steps that want to be at the beginning
1515 if ( isset( $this->extraInstallSteps['BEGINNING'] ) ) {
1516 $this->installSteps = array_merge(
1517 $this->extraInstallSteps['BEGINNING'],
1518 $this->installSteps
1519 );
1520 }
1521
1522 // Extensions should always go first, chance to tie into hooks and such
1523 if ( count( $this->getVar( '_Extensions' ) ) ) {
1524 array_unshift( $this->installSteps,
1525 [ 'name' => 'extensions', 'callback' => [ $this, 'includeExtensions' ] ]
1526 );
1527 $this->installSteps[] = [
1528 'name' => 'extension-tables',
1529 'callback' => [ $installer, 'createExtensionTables' ]
1530 ];
1531 }
1532
1533 return $this->installSteps;
1534 }
1535
1536 /**
1537 * Actually perform the installation.
1538 *
1539 * @param callable $startCB A callback array for the beginning of each step
1540 * @param callable $endCB A callback array for the end of each step
1541 *
1542 * @return array Array of Status objects
1543 */
1544 public function performInstallation( $startCB, $endCB ) {
1545 $installResults = [];
1546 $installer = $this->getDBInstaller();
1547 $installer->preInstall();
1548 $steps = $this->getInstallSteps( $installer );
1549 foreach ( $steps as $stepObj ) {
1550 $name = $stepObj['name'];
1551 call_user_func_array( $startCB, [ $name ] );
1552
1553 // Perform the callback step
1554 $status = call_user_func( $stepObj['callback'], $installer );
1555
1556 // Output and save the results
1557 call_user_func( $endCB, $name, $status );
1558 $installResults[$name] = $status;
1559
1560 // If we've hit some sort of fatal, we need to bail.
1561 // Callback already had a chance to do output above.
1562 if ( !$status->isOk() ) {
1563 break;
1564 }
1565 }
1566 if ( $status->isOk() ) {
1567 $this->setVar( '_InstallDone', true );
1568 }
1569
1570 return $installResults;
1571 }
1572
1573 /**
1574 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1575 *
1576 * @return Status
1577 */
1578 public function generateKeys() {
1579 $keys = [ 'wgSecretKey' => 64 ];
1580 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1581 $keys['wgUpgradeKey'] = 16;
1582 }
1583
1584 return $this->doGenerateKeys( $keys );
1585 }
1586
1587 /**
1588 * Generate a secret value for variables using our CryptRand generator.
1589 * Produce a warning if the random source was insecure.
1590 *
1591 * @param array $keys
1592 * @return Status
1593 */
1594 protected function doGenerateKeys( $keys ) {
1595 $status = Status::newGood();
1596
1597 $strong = true;
1598 foreach ( $keys as $name => $length ) {
1599 $secretKey = MWCryptRand::generateHex( $length, true );
1600 if ( !MWCryptRand::wasStrong() ) {
1601 $strong = false;
1602 }
1603
1604 $this->setVar( $name, $secretKey );
1605 }
1606
1607 if ( !$strong ) {
1608 $names = array_keys( $keys );
1609 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1610 global $wgLang;
1611 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1612 }
1613
1614 return $status;
1615 }
1616
1617 /**
1618 * Create the first user account, grant it sysop and bureaucrat rights
1619 *
1620 * @return Status
1621 */
1622 protected function createSysop() {
1623 $name = $this->getVar( '_AdminName' );
1624 $user = User::newFromName( $name );
1625
1626 if ( !$user ) {
1627 // We should've validated this earlier anyway!
1628 return Status::newFatal( 'config-admin-error-user', $name );
1629 }
1630
1631 if ( $user->idForName() == 0 ) {
1632 $user->addToDatabase();
1633
1634 try {
1635 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1636 } catch ( PasswordError $pwe ) {
1637 return Status::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1638 }
1639
1640 $user->addGroup( 'sysop' );
1641 $user->addGroup( 'bureaucrat' );
1642 if ( $this->getVar( '_AdminEmail' ) ) {
1643 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1644 }
1645 $user->saveSettings();
1646
1647 // Update user count
1648 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1649 $ssUpdate->doUpdate();
1650 }
1651 $status = Status::newGood();
1652
1653 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1654 $this->subscribeToMediaWikiAnnounce( $status );
1655 }
1656
1657 return $status;
1658 }
1659
1660 /**
1661 * @param Status $s
1662 */
1663 private function subscribeToMediaWikiAnnounce( Status $s ) {
1664 $params = [
1665 'email' => $this->getVar( '_AdminEmail' ),
1666 'language' => 'en',
1667 'digest' => 0
1668 ];
1669
1670 // Mailman doesn't support as many languages as we do, so check to make
1671 // sure their selected language is available
1672 $myLang = $this->getVar( '_UserLang' );
1673 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages ) ) {
1674 $myLang = $myLang == 'pt-br' ? 'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1675 $params['language'] = $myLang;
1676 }
1677
1678 if ( MWHttpRequest::canMakeRequests() ) {
1679 $res = MWHttpRequest::factory( $this->mediaWikiAnnounceUrl,
1680 [ 'method' => 'POST', 'postData' => $params ], __METHOD__ )->execute();
1681 if ( !$res->isOK() ) {
1682 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1683 }
1684 } else {
1685 $s->warning( 'config-install-subscribe-notpossible' );
1686 }
1687 }
1688
1689 /**
1690 * Insert Main Page with default content.
1691 *
1692 * @param DatabaseInstaller $installer
1693 * @return Status
1694 */
1695 protected function createMainpage( DatabaseInstaller $installer ) {
1696 $status = Status::newGood();
1697 $title = Title::newMainPage();
1698 if ( $title->exists() ) {
1699 $status->warning( 'config-install-mainpage-exists' );
1700 return $status;
1701 }
1702 try {
1703 $page = WikiPage::factory( $title );
1704 $content = new WikitextContent(
1705 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1706 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1707 );
1708
1709 $status = $page->doEditContent( $content,
1710 '',
1711 EDIT_NEW,
1712 false,
1713 User::newFromName( 'MediaWiki default' )
1714 );
1715 } catch ( Exception $e ) {
1716 // using raw, because $wgShowExceptionDetails can not be set yet
1717 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1718 }
1719
1720 return $status;
1721 }
1722
1723 /**
1724 * Override the necessary bits of the config to run an installation.
1725 */
1726 public static function overrideConfig() {
1727 // Use PHP's built-in session handling, since MediaWiki's
1728 // SessionHandler can't work before we have an object cache set up.
1729 define( 'MW_NO_SESSION_HANDLER', 1 );
1730
1731 // Don't access the database
1732 $GLOBALS['wgUseDatabaseMessages'] = false;
1733 // Don't cache langconv tables
1734 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE;
1735 // Debug-friendly
1736 $GLOBALS['wgShowExceptionDetails'] = true;
1737 // Don't break forms
1738 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1739
1740 // Extended debugging
1741 $GLOBALS['wgShowSQLErrors'] = true;
1742 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1743
1744 // Allow multiple ob_flush() calls
1745 $GLOBALS['wgDisableOutputCompression'] = true;
1746
1747 // Use a sensible cookie prefix (not my_wiki)
1748 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1749
1750 // Some of the environment checks make shell requests, remove limits
1751 $GLOBALS['wgMaxShellMemory'] = 0;
1752
1753 // Override the default CookieSessionProvider with a dummy
1754 // implementation that won't stomp on PHP's cookies.
1755 $GLOBALS['wgSessionProviders'] = [
1756 [
1757 'class' => 'InstallerSessionProvider',
1758 'args' => [ [
1759 'priority' => 1,
1760 ] ]
1761 ]
1762 ];
1763
1764 // Don't try to use any object cache for SessionManager either.
1765 $GLOBALS['wgSessionCacheType'] = CACHE_NONE;
1766 }
1767
1768 /**
1769 * Add an installation step following the given step.
1770 *
1771 * @param callable $callback A valid installation callback array, in this form:
1772 * [ 'name' => 'some-unique-name', 'callback' => [ $obj, 'function' ] ];
1773 * @param string $findStep The step to find. Omit to put the step at the beginning
1774 */
1775 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1776 $this->extraInstallSteps[$findStep][] = $callback;
1777 }
1778
1779 /**
1780 * Disable the time limit for execution.
1781 * Some long-running pages (Install, Upgrade) will want to do this
1782 */
1783 protected function disableTimeLimit() {
1784 MediaWiki\suppressWarnings();
1785 set_time_limit( 0 );
1786 MediaWiki\restoreWarnings();
1787 }
1788 }