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