Merge "Fix sessionfailure i18n message during authentication"
[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 'apc' => 'apc_fetch',
247 'apcu' => 'apcu_fetch',
248 'wincache' => 'wincache_ucache_get'
249 ];
250
251 /**
252 * User rights profiles.
253 *
254 * @var array
255 */
256 public $rightsProfiles = [
257 'wiki' => [],
258 'no-anon' => [
259 '*' => [ 'edit' => false ]
260 ],
261 'fishbowl' => [
262 '*' => [
263 'createaccount' => false,
264 'edit' => false,
265 ],
266 ],
267 'private' => [
268 '*' => [
269 'createaccount' => false,
270 'edit' => false,
271 'read' => false,
272 ],
273 ],
274 ];
275
276 /**
277 * License types.
278 *
279 * @var array
280 */
281 public $licenses = [
282 'cc-by' => [
283 'url' => 'https://creativecommons.org/licenses/by/4.0/',
284 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by.png',
285 ],
286 'cc-by-sa' => [
287 'url' => 'https://creativecommons.org/licenses/by-sa/4.0/',
288 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-sa.png',
289 ],
290 'cc-by-nc-sa' => [
291 'url' => 'https://creativecommons.org/licenses/by-nc-sa/4.0/',
292 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-nc-sa.png',
293 ],
294 'cc-0' => [
295 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
296 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-0.png',
297 ],
298 'gfdl' => [
299 'url' => 'https://www.gnu.org/copyleft/fdl.html',
300 'icon' => '$wgResourceBasePath/resources/assets/licenses/gnu-fdl.png',
301 ],
302 'none' => [
303 'url' => '',
304 'icon' => '',
305 'text' => ''
306 ],
307 'cc-choose' => [
308 // Details will be filled in by the selector.
309 'url' => '',
310 'icon' => '',
311 'text' => '',
312 ],
313 ];
314
315 /**
316 * URL to mediawiki-announce subscription
317 */
318 protected $mediaWikiAnnounceUrl =
319 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
320
321 /**
322 * Supported language codes for Mailman
323 */
324 protected $mediaWikiAnnounceLanguages = [
325 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
326 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
327 'sl', 'sr', 'sv', 'tr', 'uk'
328 ];
329
330 /**
331 * UI interface for displaying a short message
332 * The parameters are like parameters to wfMessage().
333 * The messages will be in wikitext format, which will be converted to an
334 * output format such as HTML or text before being sent to the user.
335 * @param string $msg
336 */
337 abstract public function showMessage( $msg /*, ... */ );
338
339 /**
340 * Same as showMessage(), but for displaying errors
341 * @param string $msg
342 */
343 abstract public function showError( $msg /*, ... */ );
344
345 /**
346 * Show a message to the installing user by using a Status object
347 * @param Status $status
348 */
349 abstract public function showStatusMessage( Status $status );
350
351 /**
352 * Constructs a Config object that contains configuration settings that should be
353 * overwritten for the installation process.
354 *
355 * @since 1.27
356 *
357 * @param Config $baseConfig
358 *
359 * @return Config The config to use during installation.
360 */
361 public static function getInstallerConfig( Config $baseConfig ) {
362 $configOverrides = new HashConfig();
363
364 // disable (problematic) object cache types explicitly, preserving all other (working) ones
365 // bug T113843
366 $emptyCache = [ 'class' => EmptyBagOStuff::class ];
367
368 $objectCaches = [
369 CACHE_NONE => $emptyCache,
370 CACHE_DB => $emptyCache,
371 CACHE_ANYTHING => $emptyCache,
372 CACHE_MEMCACHED => $emptyCache,
373 ] + $baseConfig->get( 'ObjectCaches' );
374
375 $configOverrides->set( 'ObjectCaches', $objectCaches );
376
377 // Load the installer's i18n.
378 $messageDirs = $baseConfig->get( 'MessagesDirs' );
379 $messageDirs['MediawikiInstaller'] = __DIR__ . '/i18n';
380
381 $configOverrides->set( 'MessagesDirs', $messageDirs );
382
383 $installerConfig = new MultiConfig( [ $configOverrides, $baseConfig ] );
384
385 // make sure we use the installer config as the main config
386 $configRegistry = $baseConfig->get( 'ConfigRegistry' );
387 $configRegistry['main'] = function () use ( $installerConfig ) {
388 return $installerConfig;
389 };
390
391 $configOverrides->set( 'ConfigRegistry', $configRegistry );
392
393 return $installerConfig;
394 }
395
396 /**
397 * Constructor, always call this from child classes.
398 */
399 public function __construct() {
400 global $wgMemc, $wgUser, $wgObjectCaches;
401
402 $defaultConfig = new GlobalVarConfig(); // all the stuff from DefaultSettings.php
403 $installerConfig = self::getInstallerConfig( $defaultConfig );
404
405 // Reset all services and inject config overrides
406 MediaWiki\MediaWikiServices::resetGlobalInstance( $installerConfig );
407
408 // Don't attempt to load user language options (T126177)
409 // This will be overridden in the web installer with the user-specified language
410 RequestContext::getMain()->setLanguage( 'en' );
411
412 // Disable the i18n cache
413 // TODO: manage LocalisationCache singleton in MediaWikiServices
414 Language::getLocalisationCache()->disableBackend();
415
416 // Disable all global services, since we don't have any configuration yet!
417 MediaWiki\MediaWikiServices::disableStorageBackend();
418
419 // Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
420 // SqlBagOStuff will then throw since we just disabled wfGetDB)
421 $wgObjectCaches = MediaWikiServices::getInstance()->getMainConfig()->get( 'ObjectCaches' );
422 $wgMemc = ObjectCache::getInstance( CACHE_NONE );
423
424 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
425 $wgUser = User::newFromId( 0 );
426 RequestContext::getMain()->setUser( $wgUser );
427
428 $this->settings = $this->internalDefaults;
429
430 foreach ( $this->defaultVarNames as $var ) {
431 $this->settings[$var] = $GLOBALS[$var];
432 }
433
434 $this->doEnvironmentPreps();
435
436 $this->compiledDBs = [];
437 foreach ( self::getDBTypes() as $type ) {
438 $installer = $this->getDBInstaller( $type );
439
440 if ( !$installer->isCompiled() ) {
441 continue;
442 }
443 $this->compiledDBs[] = $type;
444 }
445
446 $this->parserTitle = Title::newFromText( 'Installer' );
447 $this->parserOptions = new ParserOptions( $wgUser ); // language will be wrong :(
448 $this->parserOptions->setEditSection( false );
449 // 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 MediaWiki\suppressWarnings();
602 $_lsExists = file_exists( "$IP/LocalSettings.php" );
603 MediaWiki\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 MediaWiki\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 MediaWiki\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 $ret = false;
995 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
996
997 if ( $ret ) {
998 return true;
999 }
1000
1001 $lines = array_map( 'trim', explode( "\n", $lines ) );
1002 $candidatesByLocale = [];
1003 $candidatesByLang = [];
1004
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 MediaWiki\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 MediaWiki\restoreWarnings();
1228
1229 return $ext;
1230 }
1231 }
1232 }
1233
1234 MediaWiki\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 /**
1350 * We need to include DefaultSettings before including extensions to avoid
1351 * warnings about unset variables. However, the only thing we really
1352 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1353 * if the extension has hidden hook registration in $wgExtensionFunctions,
1354 * but we're not opening that can of worms
1355 * @see https://phabricator.wikimedia.org/T28857
1356 */
1357 global $wgAutoloadClasses;
1358 $wgAutoloadClasses = [];
1359 $queue = [];
1360
1361 require "$IP/includes/DefaultSettings.php";
1362
1363 foreach ( $exts as $e ) {
1364 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1365 $queue["$IP/extensions/$e/extension.json"] = 1;
1366 } else {
1367 require_once "$IP/extensions/$e/$e.php";
1368 }
1369 }
1370
1371 $registry = new ExtensionRegistry();
1372 $data = $registry->readFromQueue( $queue );
1373 $wgAutoloadClasses += $data['autoload'];
1374
1375 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1376 /** @suppress PhanUndeclaredVariable $wgHooks is set by DefaultSettings */
1377 $wgHooks['LoadExtensionSchemaUpdates'] : [];
1378
1379 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1380 $hooksWeWant = array_merge_recursive(
1381 $hooksWeWant,
1382 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1383 );
1384 }
1385 // Unset everyone else's hooks. Lord knows what someone might be doing
1386 // in ParserFirstCallInit (see T29171)
1387 $GLOBALS['wgHooks'] = [ 'LoadExtensionSchemaUpdates' => $hooksWeWant ];
1388
1389 return Status::newGood();
1390 }
1391
1392 /**
1393 * Get an array of install steps. Should always be in the format of
1394 * [
1395 * 'name' => 'someuniquename',
1396 * 'callback' => [ $obj, 'method' ],
1397 * ]
1398 * There must be a config-install-$name message defined per step, which will
1399 * be shown on install.
1400 *
1401 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1402 * @return array
1403 */
1404 protected function getInstallSteps( DatabaseInstaller $installer ) {
1405 $coreInstallSteps = [
1406 [ 'name' => 'database', 'callback' => [ $installer, 'setupDatabase' ] ],
1407 [ 'name' => 'tables', 'callback' => [ $installer, 'createTables' ] ],
1408 [ 'name' => 'interwiki', 'callback' => [ $installer, 'populateInterwikiTable' ] ],
1409 [ 'name' => 'stats', 'callback' => [ $this, 'populateSiteStats' ] ],
1410 [ 'name' => 'keys', 'callback' => [ $this, 'generateKeys' ] ],
1411 [ 'name' => 'updates', 'callback' => [ $installer, 'insertUpdateKeys' ] ],
1412 [ 'name' => 'sysop', 'callback' => [ $this, 'createSysop' ] ],
1413 [ 'name' => 'mainpage', 'callback' => [ $this, 'createMainpage' ] ],
1414 ];
1415
1416 // Build the array of install steps starting from the core install list,
1417 // then adding any callbacks that wanted to attach after a given step
1418 foreach ( $coreInstallSteps as $step ) {
1419 $this->installSteps[] = $step;
1420 if ( isset( $this->extraInstallSteps[$step['name']] ) ) {
1421 $this->installSteps = array_merge(
1422 $this->installSteps,
1423 $this->extraInstallSteps[$step['name']]
1424 );
1425 }
1426 }
1427
1428 // Prepend any steps that want to be at the beginning
1429 if ( isset( $this->extraInstallSteps['BEGINNING'] ) ) {
1430 $this->installSteps = array_merge(
1431 $this->extraInstallSteps['BEGINNING'],
1432 $this->installSteps
1433 );
1434 }
1435
1436 // Extensions should always go first, chance to tie into hooks and such
1437 if ( count( $this->getVar( '_Extensions' ) ) ) {
1438 array_unshift( $this->installSteps,
1439 [ 'name' => 'extensions', 'callback' => [ $this, 'includeExtensions' ] ]
1440 );
1441 $this->installSteps[] = [
1442 'name' => 'extension-tables',
1443 'callback' => [ $installer, 'createExtensionTables' ]
1444 ];
1445 }
1446
1447 return $this->installSteps;
1448 }
1449
1450 /**
1451 * Actually perform the installation.
1452 *
1453 * @param callable $startCB A callback array for the beginning of each step
1454 * @param callable $endCB A callback array for the end of each step
1455 *
1456 * @return array Array of Status objects
1457 */
1458 public function performInstallation( $startCB, $endCB ) {
1459 $installResults = [];
1460 $installer = $this->getDBInstaller();
1461 $installer->preInstall();
1462 $steps = $this->getInstallSteps( $installer );
1463 foreach ( $steps as $stepObj ) {
1464 $name = $stepObj['name'];
1465 call_user_func_array( $startCB, [ $name ] );
1466
1467 // Perform the callback step
1468 $status = call_user_func( $stepObj['callback'], $installer );
1469
1470 // Output and save the results
1471 call_user_func( $endCB, $name, $status );
1472 $installResults[$name] = $status;
1473
1474 // If we've hit some sort of fatal, we need to bail.
1475 // Callback already had a chance to do output above.
1476 if ( !$status->isOk() ) {
1477 break;
1478 }
1479 }
1480 if ( $status->isOk() ) {
1481 $this->showMessage(
1482 'config-install-success',
1483 $this->getVar( 'wgServer' ),
1484 $this->getVar( 'wgScriptPath' )
1485 );
1486 $this->setVar( '_InstallDone', true );
1487 }
1488
1489 return $installResults;
1490 }
1491
1492 /**
1493 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1494 *
1495 * @return Status
1496 */
1497 public function generateKeys() {
1498 $keys = [ 'wgSecretKey' => 64 ];
1499 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1500 $keys['wgUpgradeKey'] = 16;
1501 }
1502
1503 return $this->doGenerateKeys( $keys );
1504 }
1505
1506 /**
1507 * Generate a secret value for variables using our CryptRand generator.
1508 * Produce a warning if the random source was insecure.
1509 *
1510 * @param array $keys
1511 * @return Status
1512 */
1513 protected function doGenerateKeys( $keys ) {
1514 $status = Status::newGood();
1515
1516 $strong = true;
1517 foreach ( $keys as $name => $length ) {
1518 $secretKey = MWCryptRand::generateHex( $length, true );
1519 if ( !MWCryptRand::wasStrong() ) {
1520 $strong = false;
1521 }
1522
1523 $this->setVar( $name, $secretKey );
1524 }
1525
1526 if ( !$strong ) {
1527 $names = array_keys( $keys );
1528 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1529 global $wgLang;
1530 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1531 }
1532
1533 return $status;
1534 }
1535
1536 /**
1537 * Create the first user account, grant it sysop and bureaucrat rights
1538 *
1539 * @return Status
1540 */
1541 protected function createSysop() {
1542 $name = $this->getVar( '_AdminName' );
1543 $user = User::newFromName( $name );
1544
1545 if ( !$user ) {
1546 // We should've validated this earlier anyway!
1547 return Status::newFatal( 'config-admin-error-user', $name );
1548 }
1549
1550 if ( $user->idForName() == 0 ) {
1551 $user->addToDatabase();
1552
1553 try {
1554 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1555 } catch ( PasswordError $pwe ) {
1556 return Status::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1557 }
1558
1559 $user->addGroup( 'sysop' );
1560 $user->addGroup( 'bureaucrat' );
1561 if ( $this->getVar( '_AdminEmail' ) ) {
1562 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1563 }
1564 $user->saveSettings();
1565
1566 // Update user count
1567 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1568 $ssUpdate->doUpdate();
1569 }
1570 $status = Status::newGood();
1571
1572 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1573 $this->subscribeToMediaWikiAnnounce( $status );
1574 }
1575
1576 return $status;
1577 }
1578
1579 /**
1580 * @param Status $s
1581 */
1582 private function subscribeToMediaWikiAnnounce( Status $s ) {
1583 $params = [
1584 'email' => $this->getVar( '_AdminEmail' ),
1585 'language' => 'en',
1586 'digest' => 0
1587 ];
1588
1589 // Mailman doesn't support as many languages as we do, so check to make
1590 // sure their selected language is available
1591 $myLang = $this->getVar( '_UserLang' );
1592 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages ) ) {
1593 $myLang = $myLang == 'pt-br' ? 'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1594 $params['language'] = $myLang;
1595 }
1596
1597 if ( MWHttpRequest::canMakeRequests() ) {
1598 $res = MWHttpRequest::factory( $this->mediaWikiAnnounceUrl,
1599 [ 'method' => 'POST', 'postData' => $params ], __METHOD__ )->execute();
1600 if ( !$res->isOK() ) {
1601 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1602 }
1603 } else {
1604 $s->warning( 'config-install-subscribe-notpossible' );
1605 }
1606 }
1607
1608 /**
1609 * Insert Main Page with default content.
1610 *
1611 * @param DatabaseInstaller $installer
1612 * @return Status
1613 */
1614 protected function createMainpage( DatabaseInstaller $installer ) {
1615 $status = Status::newGood();
1616 $title = Title::newMainPage();
1617 if ( $title->exists() ) {
1618 $status->warning( 'config-install-mainpage-exists' );
1619 return $status;
1620 }
1621 try {
1622 $page = WikiPage::factory( $title );
1623 $content = new WikitextContent(
1624 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1625 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1626 );
1627
1628 $status = $page->doEditContent( $content,
1629 '',
1630 EDIT_NEW,
1631 false,
1632 User::newFromName( 'MediaWiki default' )
1633 );
1634 } catch ( Exception $e ) {
1635 // using raw, because $wgShowExceptionDetails can not be set yet
1636 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1637 }
1638
1639 return $status;
1640 }
1641
1642 /**
1643 * Override the necessary bits of the config to run an installation.
1644 */
1645 public static function overrideConfig() {
1646 // Use PHP's built-in session handling, since MediaWiki's
1647 // SessionHandler can't work before we have an object cache set up.
1648 define( 'MW_NO_SESSION_HANDLER', 1 );
1649
1650 // Don't access the database
1651 $GLOBALS['wgUseDatabaseMessages'] = false;
1652 // Don't cache langconv tables
1653 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE;
1654 // Debug-friendly
1655 $GLOBALS['wgShowExceptionDetails'] = true;
1656 // Don't break forms
1657 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1658
1659 // Extended debugging
1660 $GLOBALS['wgShowSQLErrors'] = true;
1661 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1662
1663 // Allow multiple ob_flush() calls
1664 $GLOBALS['wgDisableOutputCompression'] = true;
1665
1666 // Use a sensible cookie prefix (not my_wiki)
1667 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1668
1669 // Some of the environment checks make shell requests, remove limits
1670 $GLOBALS['wgMaxShellMemory'] = 0;
1671
1672 // Override the default CookieSessionProvider with a dummy
1673 // implementation that won't stomp on PHP's cookies.
1674 $GLOBALS['wgSessionProviders'] = [
1675 [
1676 'class' => InstallerSessionProvider::class,
1677 'args' => [ [
1678 'priority' => 1,
1679 ] ]
1680 ]
1681 ];
1682
1683 // Don't try to use any object cache for SessionManager either.
1684 $GLOBALS['wgSessionCacheType'] = CACHE_NONE;
1685 }
1686
1687 /**
1688 * Add an installation step following the given step.
1689 *
1690 * @param callable $callback A valid installation callback array, in this form:
1691 * [ 'name' => 'some-unique-name', 'callback' => [ $obj, 'function' ] ];
1692 * @param string $findStep The step to find. Omit to put the step at the beginning
1693 */
1694 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1695 $this->extraInstallSteps[$findStep][] = $callback;
1696 }
1697
1698 /**
1699 * Disable the time limit for execution.
1700 * Some long-running pages (Install, Upgrade) will want to do this
1701 */
1702 protected function disableTimeLimit() {
1703 MediaWiki\suppressWarnings();
1704 set_time_limit( 0 );
1705 MediaWiki\restoreWarnings();
1706 }
1707 }