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