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