Merge "Add tablesUsed to RevisionStoreDbTest"
[lhc/web/wiklou.git] / includes / installer / Installer.php
1 <?php
2 /**
3 * Base code for MediaWiki installer.
4 *
5 * DO NOT PATCH THIS FILE IF YOU NEED TO CHANGE INSTALLER BEHAVIOR IN YOUR PACKAGE!
6 * See mw-config/overrides/README for details.
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup Deployment
25 */
26 use MediaWiki\MediaWikiServices;
27
28 /**
29 * This documentation group collects source code files with deployment functionality.
30 *
31 * @defgroup Deployment Deployment
32 */
33
34 /**
35 * Base installer class.
36 *
37 * This class provides the base for installation and update functionality
38 * for both MediaWiki core and extensions.
39 *
40 * @ingroup Deployment
41 * @since 1.17
42 */
43 abstract class Installer {
44
45 /**
46 * The oldest version of PCRE we can support.
47 *
48 * Defining this is necessary because PHP may be linked with a system version
49 * of PCRE, which may be older than that bundled with the minimum PHP version.
50 */
51 const MINIMUM_PCRE_VERSION = '7.2';
52
53 /**
54 * @var array
55 */
56 protected $settings;
57
58 /**
59 * List of detected DBs, access using getCompiledDBs().
60 *
61 * @var array
62 */
63 protected $compiledDBs;
64
65 /**
66 * Cached DB installer instances, access using getDBInstaller().
67 *
68 * @var array
69 */
70 protected $dbInstallers = [];
71
72 /**
73 * Minimum memory size in MB.
74 *
75 * @var int
76 */
77 protected $minMemorySize = 50;
78
79 /**
80 * Cached Title, used by parse().
81 *
82 * @var Title
83 */
84 protected $parserTitle;
85
86 /**
87 * Cached ParserOptions, used by parse().
88 *
89 * @var ParserOptions
90 */
91 protected $parserOptions;
92
93 /**
94 * Known database types. These correspond to the class names <type>Installer,
95 * and are also MediaWiki database types valid for $wgDBtype.
96 *
97 * To add a new type, create a <type>Installer class and a Database<type>
98 * class, and add a config-type-<type> message to MessagesEn.php.
99 *
100 * @var array
101 */
102 protected static $dbTypes = [
103 'mysql',
104 'postgres',
105 'oracle',
106 'mssql',
107 'sqlite',
108 ];
109
110 /**
111 * A list of environment check methods called by doEnvironmentChecks().
112 * These may output warnings using showMessage(), and/or abort the
113 * installation process by returning false.
114 *
115 * For the WebInstaller these are only called on the Welcome page,
116 * if these methods have side-effects that should affect later page loads
117 * (as well as the generated stylesheet), use envPreps instead.
118 *
119 * @var array
120 */
121 protected $envChecks = [
122 'envCheckDB',
123 'envCheckBrokenXML',
124 'envCheckPCRE',
125 'envCheckMemory',
126 'envCheckCache',
127 'envCheckModSecurity',
128 'envCheckDiff3',
129 'envCheckGraphics',
130 'envCheckGit',
131 'envCheckServer',
132 'envCheckPath',
133 'envCheckShellLocale',
134 'envCheckUploadsDirectory',
135 'envCheckLibicu',
136 'envCheckSuhosinMaxValueLength',
137 'envCheck64Bit',
138 ];
139
140 /**
141 * A list of environment preparation methods called by doEnvironmentPreps().
142 *
143 * @var array
144 */
145 protected $envPreps = [
146 'envPrepServer',
147 'envPrepPath',
148 ];
149
150 /**
151 * MediaWiki configuration globals that will eventually be passed through
152 * to LocalSettings.php. The names only are given here, the defaults
153 * typically come from DefaultSettings.php.
154 *
155 * @var array
156 */
157 protected $defaultVarNames = [
158 'wgSitename',
159 'wgPasswordSender',
160 'wgLanguageCode',
161 'wgRightsIcon',
162 'wgRightsText',
163 'wgRightsUrl',
164 'wgEnableEmail',
165 'wgEnableUserEmail',
166 'wgEnotifUserTalk',
167 'wgEnotifWatchlist',
168 'wgEmailAuthentication',
169 'wgDBname',
170 'wgDBtype',
171 'wgDiff3',
172 'wgImageMagickConvertCommand',
173 'wgGitBin',
174 'IP',
175 'wgScriptPath',
176 'wgMetaNamespace',
177 'wgDeletedDirectory',
178 'wgEnableUploads',
179 'wgShellLocale',
180 'wgSecretKey',
181 'wgUseInstantCommons',
182 'wgUpgradeKey',
183 'wgDefaultSkin',
184 'wgPingback',
185 ];
186
187 /**
188 * Variables that are stored alongside globals, and are used for any
189 * configuration of the installation process aside from the MediaWiki
190 * configuration. Map of names to defaults.
191 *
192 * @var array
193 */
194 protected $internalDefaults = [
195 '_UserLang' => 'en',
196 '_Environment' => false,
197 '_RaiseMemory' => false,
198 '_UpgradeDone' => false,
199 '_InstallDone' => false,
200 '_Caches' => [],
201 '_InstallPassword' => '',
202 '_SameAccount' => true,
203 '_CreateDBAccount' => false,
204 '_NamespaceType' => 'site-name',
205 '_AdminName' => '', // will be set later, when the user selects language
206 '_AdminPassword' => '',
207 '_AdminPasswordConfirm' => '',
208 '_AdminEmail' => '',
209 '_Subscribe' => false,
210 '_SkipOptional' => 'continue',
211 '_RightsProfile' => 'wiki',
212 '_LicenseCode' => 'none',
213 '_CCDone' => false,
214 '_Extensions' => [],
215 '_Skins' => [],
216 '_MemCachedServers' => '',
217 '_UpgradeKeySupplied' => false,
218 '_ExistingDBSettings' => false,
219
220 // $wgLogo is probably wrong (T50084); set something that will work.
221 // Single quotes work fine here, as LocalSettingsGenerator outputs this unescaped.
222 'wgLogo' => '$wgResourceBasePath/resources/assets/wiki.png',
223 'wgAuthenticationTokenVersion' => 1,
224 ];
225
226 /**
227 * The actual list of installation steps. This will be initialized by getInstallSteps()
228 *
229 * @var array
230 */
231 private $installSteps = [];
232
233 /**
234 * Extra steps for installation, for things like DatabaseInstallers to modify
235 *
236 * @var array
237 */
238 protected $extraInstallSteps = [];
239
240 /**
241 * Known object cache types and the functions used to test for their existence.
242 *
243 * @var array
244 */
245 protected $objectCaches = [
246 'xcache' => 'xcache_get',
247 'apc' => 'apc_fetch',
248 'apcu' => 'apcu_fetch',
249 'wincache' => 'wincache_ucache_get'
250 ];
251
252 /**
253 * User rights profiles.
254 *
255 * @var array
256 */
257 public $rightsProfiles = [
258 'wiki' => [],
259 'no-anon' => [
260 '*' => [ 'edit' => false ]
261 ],
262 'fishbowl' => [
263 '*' => [
264 'createaccount' => false,
265 'edit' => false,
266 ],
267 ],
268 'private' => [
269 '*' => [
270 'createaccount' => false,
271 'edit' => false,
272 'read' => false,
273 ],
274 ],
275 ];
276
277 /**
278 * License types.
279 *
280 * @var array
281 */
282 public $licenses = [
283 'cc-by' => [
284 'url' => 'https://creativecommons.org/licenses/by/4.0/',
285 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by.png',
286 ],
287 'cc-by-sa' => [
288 'url' => 'https://creativecommons.org/licenses/by-sa/4.0/',
289 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-sa.png',
290 ],
291 'cc-by-nc-sa' => [
292 'url' => 'https://creativecommons.org/licenses/by-nc-sa/4.0/',
293 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-nc-sa.png',
294 ],
295 'cc-0' => [
296 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
297 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-0.png',
298 ],
299 'gfdl' => [
300 'url' => 'https://www.gnu.org/copyleft/fdl.html',
301 'icon' => '$wgResourceBasePath/resources/assets/licenses/gnu-fdl.png',
302 ],
303 'none' => [
304 'url' => '',
305 'icon' => '',
306 'text' => ''
307 ],
308 'cc-choose' => [
309 // Details will be filled in by the selector.
310 'url' => '',
311 'icon' => '',
312 'text' => '',
313 ],
314 ];
315
316 /**
317 * URL to mediawiki-announce subscription
318 */
319 protected $mediaWikiAnnounceUrl =
320 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
321
322 /**
323 * Supported language codes for Mailman
324 */
325 protected $mediaWikiAnnounceLanguages = [
326 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
327 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
328 'sl', 'sr', 'sv', 'tr', 'uk'
329 ];
330
331 /**
332 * UI interface for displaying a short message
333 * The parameters are like parameters to wfMessage().
334 * The messages will be in wikitext format, which will be converted to an
335 * output format such as HTML or text before being sent to the user.
336 * @param string $msg
337 */
338 abstract public function showMessage( $msg /*, ... */ );
339
340 /**
341 * Same as showMessage(), but for displaying errors
342 * @param string $msg
343 */
344 abstract public function showError( $msg /*, ... */ );
345
346 /**
347 * Show a message to the installing user by using a Status object
348 * @param Status $status
349 */
350 abstract public function showStatusMessage( Status $status );
351
352 /**
353 * Constructs a Config object that contains configuration settings that should be
354 * overwritten for the installation process.
355 *
356 * @since 1.27
357 *
358 * @param Config $baseConfig
359 *
360 * @return Config The config to use during installation.
361 */
362 public static function getInstallerConfig( Config $baseConfig ) {
363 $configOverrides = new HashConfig();
364
365 // disable (problematic) object cache types explicitly, preserving all other (working) ones
366 // bug T113843
367 $emptyCache = [ 'class' => EmptyBagOStuff::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 $this->parserOptions->setEditSection( 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 the DatabaseInstaller class name for this type
550 *
551 * @param string $type database type ($wgDBtype)
552 * @return string Class name
553 * @since 1.30
554 */
555 public static function getDBInstallerClass( $type ) {
556 return ucfirst( $type ) . 'Installer';
557 }
558
559 /**
560 * Get an instance of DatabaseInstaller for the specified DB type.
561 *
562 * @param mixed $type DB installer for which is needed, false to use default.
563 *
564 * @return DatabaseInstaller
565 */
566 public function getDBInstaller( $type = false ) {
567 if ( !$type ) {
568 $type = $this->getVar( 'wgDBtype' );
569 }
570
571 $type = strtolower( $type );
572
573 if ( !isset( $this->dbInstallers[$type] ) ) {
574 $class = self::getDBInstallerClass( $type );
575 $this->dbInstallers[$type] = new $class( $this );
576 }
577
578 return $this->dbInstallers[$type];
579 }
580
581 /**
582 * Determine if LocalSettings.php exists. If it does, return its variables.
583 *
584 * @return array|false
585 */
586 public static function getExistingLocalSettings() {
587 global $IP;
588
589 // You might be wondering why this is here. Well if you don't do this
590 // then some poorly-formed extensions try to call their own classes
591 // after immediately registering them. We really need to get extension
592 // registration out of the global scope and into a real format.
593 // @see https://phabricator.wikimedia.org/T69440
594 global $wgAutoloadClasses;
595 $wgAutoloadClasses = [];
596
597 // LocalSettings.php should not call functions, except wfLoadSkin/wfLoadExtensions
598 // Define the required globals here, to ensure, the functions can do it work correctly.
599 // phpcs:ignore MediaWiki.VariableAnalysis.UnusedGlobalVariables
600 global $wgExtensionDirectory, $wgStyleDirectory;
601
602 MediaWiki\suppressWarnings();
603 $_lsExists = file_exists( "$IP/LocalSettings.php" );
604 MediaWiki\restoreWarnings();
605
606 if ( !$_lsExists ) {
607 return false;
608 }
609 unset( $_lsExists );
610
611 require "$IP/includes/DefaultSettings.php";
612 require "$IP/LocalSettings.php";
613
614 return get_defined_vars();
615 }
616
617 /**
618 * Get a fake password for sending back to the user in HTML.
619 * This is a security mechanism to avoid compromise of the password in the
620 * event of session ID compromise.
621 *
622 * @param string $realPassword
623 *
624 * @return string
625 */
626 public function getFakePassword( $realPassword ) {
627 return str_repeat( '*', strlen( $realPassword ) );
628 }
629
630 /**
631 * Set a variable which stores a password, except if the new value is a
632 * fake password in which case leave it as it is.
633 *
634 * @param string $name
635 * @param mixed $value
636 */
637 public function setPassword( $name, $value ) {
638 if ( !preg_match( '/^\*+$/', $value ) ) {
639 $this->setVar( $name, $value );
640 }
641 }
642
643 /**
644 * On POSIX systems return the primary group of the webserver we're running under.
645 * On other systems just returns null.
646 *
647 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
648 * webserver user before he can install.
649 *
650 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
651 *
652 * @return mixed
653 */
654 public static function maybeGetWebserverPrimaryGroup() {
655 if ( !function_exists( 'posix_getegid' ) || !function_exists( 'posix_getpwuid' ) ) {
656 # I don't know this, this isn't UNIX.
657 return null;
658 }
659
660 # posix_getegid() *not* getmygid() because we want the group of the webserver,
661 # not whoever owns the current script.
662 $gid = posix_getegid();
663 $group = posix_getpwuid( $gid )['name'];
664
665 return $group;
666 }
667
668 /**
669 * Convert wikitext $text to HTML.
670 *
671 * This is potentially error prone since many parser features require a complete
672 * installed MW database. The solution is to just not use those features when you
673 * write your messages. This appears to work well enough. Basic formatting and
674 * external links work just fine.
675 *
676 * But in case a translator decides to throw in a "#ifexist" or internal link or
677 * whatever, this function is guarded to catch the attempted DB access and to present
678 * some fallback text.
679 *
680 * @param string $text
681 * @param bool $lineStart
682 * @return string
683 */
684 public function parse( $text, $lineStart = false ) {
685 global $wgParser;
686
687 try {
688 $out = $wgParser->parse( $text, $this->parserTitle, $this->parserOptions, $lineStart );
689 $html = $out->getText( [
690 'enableSectionEditLinks' => false,
691 'unwrap' => true,
692 ] );
693 } catch ( MediaWiki\Services\ServiceDisabledException $e ) {
694 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
695 }
696
697 return $html;
698 }
699
700 /**
701 * @return ParserOptions
702 */
703 public function getParserOptions() {
704 return $this->parserOptions;
705 }
706
707 public function disableLinkPopups() {
708 $this->parserOptions->setExternalLinkTarget( false );
709 }
710
711 public function restoreLinkPopups() {
712 global $wgExternalLinkTarget;
713 $this->parserOptions->setExternalLinkTarget( $wgExternalLinkTarget );
714 }
715
716 /**
717 * Install step which adds a row to the site_stats table with appropriate
718 * initial values.
719 *
720 * @param DatabaseInstaller $installer
721 *
722 * @return Status
723 */
724 public function populateSiteStats( DatabaseInstaller $installer ) {
725 $status = $installer->getConnection();
726 if ( !$status->isOK() ) {
727 return $status;
728 }
729 $status->value->insert(
730 'site_stats',
731 [
732 'ss_row_id' => 1,
733 'ss_total_edits' => 0,
734 'ss_good_articles' => 0,
735 'ss_total_pages' => 0,
736 'ss_users' => 0,
737 'ss_active_users' => 0,
738 'ss_images' => 0
739 ],
740 __METHOD__, 'IGNORE'
741 );
742
743 return Status::newGood();
744 }
745
746 /**
747 * Environment check for DB types.
748 * @return bool
749 */
750 protected function envCheckDB() {
751 global $wgLang;
752
753 $allNames = [];
754
755 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
756 // config-type-sqlite
757 foreach ( self::getDBTypes() as $name ) {
758 $allNames[] = wfMessage( "config-type-$name" )->text();
759 }
760
761 $databases = $this->getCompiledDBs();
762
763 $databases = array_flip( $databases );
764 foreach ( array_keys( $databases ) as $db ) {
765 $installer = $this->getDBInstaller( $db );
766 $status = $installer->checkPrerequisites();
767 if ( !$status->isGood() ) {
768 $this->showStatusMessage( $status );
769 }
770 if ( !$status->isOK() ) {
771 unset( $databases[$db] );
772 }
773 }
774 $databases = array_flip( $databases );
775 if ( !$databases ) {
776 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
777
778 // @todo FIXME: This only works for the web installer!
779 return false;
780 }
781
782 return true;
783 }
784
785 /**
786 * Some versions of libxml+PHP break < and > encoding horribly
787 * @return bool
788 */
789 protected function envCheckBrokenXML() {
790 $test = new PhpXmlBugTester();
791 if ( !$test->ok ) {
792 $this->showError( 'config-brokenlibxml' );
793
794 return false;
795 }
796
797 return true;
798 }
799
800 /**
801 * Environment check for the PCRE module.
802 *
803 * @note If this check were to fail, the parser would
804 * probably throw an exception before the result
805 * of this check is shown to the user.
806 * @return bool
807 */
808 protected function envCheckPCRE() {
809 MediaWiki\suppressWarnings();
810 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
811 // Need to check for \p support too, as PCRE can be compiled
812 // with utf8 support, but not unicode property support.
813 // check that \p{Zs} (space separators) matches
814 // U+3000 (Ideographic space)
815 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
816 MediaWiki\restoreWarnings();
817 if ( $regexd != '--' || $regexprop != '--' ) {
818 $this->showError( 'config-pcre-no-utf8' );
819
820 return false;
821 }
822
823 return true;
824 }
825
826 /**
827 * Environment check for available memory.
828 * @return bool
829 */
830 protected function envCheckMemory() {
831 $limit = ini_get( 'memory_limit' );
832
833 if ( !$limit || $limit == -1 ) {
834 return true;
835 }
836
837 $n = wfShorthandToInteger( $limit );
838
839 if ( $n < $this->minMemorySize * 1024 * 1024 ) {
840 $newLimit = "{$this->minMemorySize}M";
841
842 if ( ini_set( "memory_limit", $newLimit ) === false ) {
843 $this->showMessage( 'config-memory-bad', $limit );
844 } else {
845 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
846 $this->setVar( '_RaiseMemory', true );
847 }
848 }
849
850 return true;
851 }
852
853 /**
854 * Environment check for compiled object cache types.
855 */
856 protected function envCheckCache() {
857 $caches = [];
858 foreach ( $this->objectCaches as $name => $function ) {
859 if ( function_exists( $function ) ) {
860 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
861 continue;
862 }
863 $caches[$name] = true;
864 }
865 }
866
867 if ( !$caches ) {
868 $key = 'config-no-cache-apcu';
869 $this->showMessage( $key );
870 }
871
872 $this->setVar( '_Caches', $caches );
873 }
874
875 /**
876 * Scare user to death if they have mod_security or mod_security2
877 * @return bool
878 */
879 protected function envCheckModSecurity() {
880 if ( self::apacheModulePresent( 'mod_security' )
881 || self::apacheModulePresent( 'mod_security2' ) ) {
882 $this->showMessage( 'config-mod-security' );
883 }
884
885 return true;
886 }
887
888 /**
889 * Search for GNU diff3.
890 * @return bool
891 */
892 protected function envCheckDiff3() {
893 $names = [ "gdiff3", "diff3" ];
894 if ( wfIsWindows() ) {
895 $names[] = 'diff3.exe';
896 }
897 $versionInfo = [ '--version', 'GNU diffutils' ];
898
899 $diff3 = ExecutableFinder::findInDefaultPaths( $names, $versionInfo );
900
901 if ( $diff3 ) {
902 $this->setVar( 'wgDiff3', $diff3 );
903 } else {
904 $this->setVar( 'wgDiff3', false );
905 $this->showMessage( 'config-diff3-bad' );
906 }
907
908 return true;
909 }
910
911 /**
912 * Environment check for ImageMagick and GD.
913 * @return bool
914 */
915 protected function envCheckGraphics() {
916 $names = wfIsWindows() ? 'convert.exe' : 'convert';
917 $versionInfo = [ '-version', 'ImageMagick' ];
918 $convert = ExecutableFinder::findInDefaultPaths( $names, $versionInfo );
919
920 $this->setVar( 'wgImageMagickConvertCommand', '' );
921 if ( $convert ) {
922 $this->setVar( 'wgImageMagickConvertCommand', $convert );
923 $this->showMessage( 'config-imagemagick', $convert );
924
925 return true;
926 } elseif ( function_exists( 'imagejpeg' ) ) {
927 $this->showMessage( 'config-gd' );
928 } else {
929 $this->showMessage( 'config-no-scaling' );
930 }
931
932 return true;
933 }
934
935 /**
936 * Search for git.
937 *
938 * @since 1.22
939 * @return bool
940 */
941 protected function envCheckGit() {
942 $names = wfIsWindows() ? 'git.exe' : 'git';
943 $versionInfo = [ '--version', 'git version' ];
944
945 $git = ExecutableFinder::findInDefaultPaths( $names, $versionInfo );
946
947 if ( $git ) {
948 $this->setVar( 'wgGitBin', $git );
949 $this->showMessage( 'config-git', $git );
950 } else {
951 $this->setVar( 'wgGitBin', false );
952 $this->showMessage( 'config-git-bad' );
953 }
954
955 return true;
956 }
957
958 /**
959 * Environment check to inform user which server we've assumed.
960 *
961 * @return bool
962 */
963 protected function envCheckServer() {
964 $server = $this->envGetDefaultServer();
965 if ( $server !== null ) {
966 $this->showMessage( 'config-using-server', $server );
967 }
968 return true;
969 }
970
971 /**
972 * Environment check to inform user which paths we've assumed.
973 *
974 * @return bool
975 */
976 protected function envCheckPath() {
977 $this->showMessage(
978 'config-using-uri',
979 $this->getVar( 'wgServer' ),
980 $this->getVar( 'wgScriptPath' )
981 );
982 return true;
983 }
984
985 /**
986 * Environment check for preferred locale in shell
987 * @return bool
988 */
989 protected function envCheckShellLocale() {
990 $os = php_uname( 's' );
991 $supported = [ 'Linux', 'SunOS', 'HP-UX', 'Darwin' ]; # Tested these
992
993 if ( !in_array( $os, $supported ) ) {
994 return true;
995 }
996
997 # Get a list of available locales.
998 $ret = false;
999 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1000
1001 if ( $ret ) {
1002 return true;
1003 }
1004
1005 $lines = array_map( 'trim', explode( "\n", $lines ) );
1006 $candidatesByLocale = [];
1007 $candidatesByLang = [];
1008
1009 foreach ( $lines as $line ) {
1010 if ( $line === '' ) {
1011 continue;
1012 }
1013
1014 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1015 continue;
1016 }
1017
1018 list( , $lang, , , ) = $m;
1019
1020 $candidatesByLocale[$m[0]] = $m;
1021 $candidatesByLang[$lang][] = $m;
1022 }
1023
1024 # Try the current value of LANG.
1025 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1026 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1027
1028 return true;
1029 }
1030
1031 # Try the most common ones.
1032 $commonLocales = [ 'C.UTF-8', 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' ];
1033 foreach ( $commonLocales as $commonLocale ) {
1034 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1035 $this->setVar( 'wgShellLocale', $commonLocale );
1036
1037 return true;
1038 }
1039 }
1040
1041 # Is there an available locale in the Wiki's language?
1042 $wikiLang = $this->getVar( 'wgLanguageCode' );
1043
1044 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1045 $m = reset( $candidatesByLang[$wikiLang] );
1046 $this->setVar( 'wgShellLocale', $m[0] );
1047
1048 return true;
1049 }
1050
1051 # Are there any at all?
1052 if ( count( $candidatesByLocale ) ) {
1053 $m = reset( $candidatesByLocale );
1054 $this->setVar( 'wgShellLocale', $m[0] );
1055
1056 return true;
1057 }
1058
1059 # Give up.
1060 return true;
1061 }
1062
1063 /**
1064 * Environment check for the permissions of the uploads directory
1065 * @return bool
1066 */
1067 protected function envCheckUploadsDirectory() {
1068 global $IP;
1069
1070 $dir = $IP . '/images/';
1071 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1072 $safe = !$this->dirIsExecutable( $dir, $url );
1073
1074 if ( !$safe ) {
1075 $this->showMessage( 'config-uploads-not-safe', $dir );
1076 }
1077
1078 return true;
1079 }
1080
1081 /**
1082 * Checks if suhosin.get.max_value_length is set, and if so generate
1083 * a warning because it decreases ResourceLoader performance.
1084 * @return bool
1085 */
1086 protected function envCheckSuhosinMaxValueLength() {
1087 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1088 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1089 // Only warn if the value is below the sane 1024
1090 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1091 }
1092
1093 return true;
1094 }
1095
1096 /**
1097 * Checks if we're running on 64 bit or not. 32 bit is becoming increasingly
1098 * hard to support, so let's at least warn people.
1099 *
1100 * @return bool
1101 */
1102 protected function envCheck64Bit() {
1103 if ( PHP_INT_SIZE == 4 ) {
1104 $this->showMessage( 'config-using-32bit' );
1105 }
1106
1107 return true;
1108 }
1109
1110 /**
1111 * Convert a hex string representing a Unicode code point to that code point.
1112 * @param string $c
1113 * @return string|false
1114 */
1115 protected function unicodeChar( $c ) {
1116 $c = hexdec( $c );
1117 if ( $c <= 0x7F ) {
1118 return chr( $c );
1119 } elseif ( $c <= 0x7FF ) {
1120 return chr( 0xC0 | $c >> 6 ) . chr( 0x80 | $c & 0x3F );
1121 } elseif ( $c <= 0xFFFF ) {
1122 return chr( 0xE0 | $c >> 12 ) . chr( 0x80 | $c >> 6 & 0x3F ) .
1123 chr( 0x80 | $c & 0x3F );
1124 } elseif ( $c <= 0x10FFFF ) {
1125 return chr( 0xF0 | $c >> 18 ) . chr( 0x80 | $c >> 12 & 0x3F ) .
1126 chr( 0x80 | $c >> 6 & 0x3F ) .
1127 chr( 0x80 | $c & 0x3F );
1128 } else {
1129 return false;
1130 }
1131 }
1132
1133 /**
1134 * Check the libicu version
1135 */
1136 protected function envCheckLibicu() {
1137 /**
1138 * This needs to be updated something that the latest libicu
1139 * will properly normalize. This normalization was found at
1140 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1141 * Note that we use the hex representation to create the code
1142 * points in order to avoid any Unicode-destroying during transit.
1143 */
1144 $not_normal_c = $this->unicodeChar( "FA6C" );
1145 $normal_c = $this->unicodeChar( "242EE" );
1146
1147 $useNormalizer = 'php';
1148 $needsUpdate = false;
1149
1150 if ( function_exists( 'normalizer_normalize' ) ) {
1151 $useNormalizer = 'intl';
1152 $intl = normalizer_normalize( $not_normal_c, Normalizer::FORM_C );
1153 if ( $intl !== $normal_c ) {
1154 $needsUpdate = true;
1155 }
1156 }
1157
1158 // Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
1159 if ( $useNormalizer === 'php' ) {
1160 $this->showMessage( 'config-unicode-pure-php-warning' );
1161 } else {
1162 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1163 if ( $needsUpdate ) {
1164 $this->showMessage( 'config-unicode-update-warning' );
1165 }
1166 }
1167 }
1168
1169 /**
1170 * Environment prep for the server hostname.
1171 */
1172 protected function envPrepServer() {
1173 $server = $this->envGetDefaultServer();
1174 if ( $server !== null ) {
1175 $this->setVar( 'wgServer', $server );
1176 }
1177 }
1178
1179 /**
1180 * Helper function to be called from envPrepServer()
1181 * @return string
1182 */
1183 abstract protected function envGetDefaultServer();
1184
1185 /**
1186 * Environment prep for setting $IP and $wgScriptPath.
1187 */
1188 protected function envPrepPath() {
1189 global $IP;
1190 $IP = dirname( dirname( __DIR__ ) );
1191 $this->setVar( 'IP', $IP );
1192 }
1193
1194 /**
1195 * Checks if scripts located in the given directory can be executed via the given URL.
1196 *
1197 * Used only by environment checks.
1198 * @param string $dir
1199 * @param string $url
1200 * @return bool|int|string
1201 */
1202 public function dirIsExecutable( $dir, $url ) {
1203 $scriptTypes = [
1204 'php' => [
1205 "<?php echo 'ex' . 'ec';",
1206 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1207 ],
1208 ];
1209
1210 // it would be good to check other popular languages here, but it'll be slow.
1211
1212 MediaWiki\suppressWarnings();
1213
1214 foreach ( $scriptTypes as $ext => $contents ) {
1215 foreach ( $contents as $source ) {
1216 $file = 'exectest.' . $ext;
1217
1218 if ( !file_put_contents( $dir . $file, $source ) ) {
1219 break;
1220 }
1221
1222 try {
1223 $text = Http::get( $url . $file, [ 'timeout' => 3 ], __METHOD__ );
1224 } catch ( Exception $e ) {
1225 // Http::get throws with allow_url_fopen = false and no curl extension.
1226 $text = null;
1227 }
1228 unlink( $dir . $file );
1229
1230 if ( $text == 'exec' ) {
1231 MediaWiki\restoreWarnings();
1232
1233 return $ext;
1234 }
1235 }
1236 }
1237
1238 MediaWiki\restoreWarnings();
1239
1240 return false;
1241 }
1242
1243 /**
1244 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1245 *
1246 * @param string $moduleName Name of module to check.
1247 * @return bool
1248 */
1249 public static function apacheModulePresent( $moduleName ) {
1250 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1251 return true;
1252 }
1253 // try it the hard way
1254 ob_start();
1255 phpinfo( INFO_MODULES );
1256 $info = ob_get_clean();
1257
1258 return strpos( $info, $moduleName ) !== false;
1259 }
1260
1261 /**
1262 * ParserOptions are constructed before we determined the language, so fix it
1263 *
1264 * @param Language $lang
1265 */
1266 public function setParserLanguage( $lang ) {
1267 $this->parserOptions->setTargetLanguage( $lang );
1268 $this->parserOptions->setUserLang( $lang );
1269 }
1270
1271 /**
1272 * Overridden by WebInstaller to provide lastPage parameters.
1273 * @param string $page
1274 * @return string
1275 */
1276 protected function getDocUrl( $page ) {
1277 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1278 }
1279
1280 /**
1281 * Finds extensions that follow the format /$directory/Name/Name.php,
1282 * and returns an array containing the value for 'Name' for each found extension.
1283 *
1284 * Reasonable values for $directory include 'extensions' (the default) and 'skins'.
1285 *
1286 * @param string $directory Directory to search in
1287 * @return array [ $extName => [ 'screenshots' => [ '...' ] ]
1288 */
1289 public function findExtensions( $directory = 'extensions' ) {
1290 if ( $this->getVar( 'IP' ) === null ) {
1291 return [];
1292 }
1293
1294 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1295 if ( !is_readable( $extDir ) || !is_dir( $extDir ) ) {
1296 return [];
1297 }
1298
1299 // extensions -> extension.json, skins -> skin.json
1300 $jsonFile = substr( $directory, 0, strlen( $directory ) - 1 ) . '.json';
1301
1302 $dh = opendir( $extDir );
1303 $exts = [];
1304 while ( ( $file = readdir( $dh ) ) !== false ) {
1305 if ( !is_dir( "$extDir/$file" ) ) {
1306 continue;
1307 }
1308 if ( file_exists( "$extDir/$file/$jsonFile" ) || file_exists( "$extDir/$file/$file.php" ) ) {
1309 // Extension exists. Now see if there are screenshots
1310 $exts[$file] = [];
1311 if ( is_dir( "$extDir/$file/screenshots" ) ) {
1312 $paths = glob( "$extDir/$file/screenshots/*.png" );
1313 foreach ( $paths as $path ) {
1314 $exts[$file]['screenshots'][] = str_replace( $extDir, "../$directory", $path );
1315 }
1316
1317 }
1318 }
1319 }
1320 closedir( $dh );
1321 uksort( $exts, 'strnatcasecmp' );
1322
1323 return $exts;
1324 }
1325
1326 /**
1327 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1328 * but will fall back to another if the default skin is missing and some other one is present
1329 * instead.
1330 *
1331 * @param string[] $skinNames Names of installed skins.
1332 * @return string
1333 */
1334 public function getDefaultSkin( array $skinNames ) {
1335 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1336 if ( !$skinNames || in_array( $defaultSkin, $skinNames ) ) {
1337 return $defaultSkin;
1338 } else {
1339 return $skinNames[0];
1340 }
1341 }
1342
1343 /**
1344 * Installs the auto-detected extensions.
1345 *
1346 * @return Status
1347 */
1348 protected function includeExtensions() {
1349 global $IP;
1350 $exts = $this->getVar( '_Extensions' );
1351 $IP = $this->getVar( 'IP' );
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 = new SiteStatsUpdate( 0, 0, 0, 0, 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 MediaWiki\suppressWarnings();
1708 set_time_limit( 0 );
1709 MediaWiki\restoreWarnings();
1710 }
1711 }