installer: Remove obsolete config-no-cache message
[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 $getpwuid = posix_getpwuid( $gid );
613 $group = $getpwuid['name'];
614
615 return $group;
616 }
617
618 /**
619 * Convert wikitext $text to HTML.
620 *
621 * This is potentially error prone since many parser features require a complete
622 * installed MW database. The solution is to just not use those features when you
623 * write your messages. This appears to work well enough. Basic formatting and
624 * external links work just fine.
625 *
626 * But in case a translator decides to throw in a "#ifexist" or internal link or
627 * whatever, this function is guarded to catch the attempted DB access and to present
628 * some fallback text.
629 *
630 * @param string $text
631 * @param bool $lineStart
632 * @return string
633 */
634 public function parse( $text, $lineStart = false ) {
635 global $wgParser;
636
637 try {
638 $out = $wgParser->parse( $text, $this->parserTitle, $this->parserOptions, $lineStart );
639 $html = $out->getText();
640 } catch ( DBAccessError $e ) {
641 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
642
643 if ( !empty( $this->debug ) ) {
644 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
645 }
646 }
647
648 return $html;
649 }
650
651 /**
652 * @return ParserOptions
653 */
654 public function getParserOptions() {
655 return $this->parserOptions;
656 }
657
658 public function disableLinkPopups() {
659 $this->parserOptions->setExternalLinkTarget( false );
660 }
661
662 public function restoreLinkPopups() {
663 global $wgExternalLinkTarget;
664 $this->parserOptions->setExternalLinkTarget( $wgExternalLinkTarget );
665 }
666
667 /**
668 * Install step which adds a row to the site_stats table with appropriate
669 * initial values.
670 *
671 * @param DatabaseInstaller $installer
672 *
673 * @return Status
674 */
675 public function populateSiteStats( DatabaseInstaller $installer ) {
676 $status = $installer->getConnection();
677 if ( !$status->isOK() ) {
678 return $status;
679 }
680 $status->value->insert(
681 'site_stats',
682 [
683 'ss_row_id' => 1,
684 'ss_total_edits' => 0,
685 'ss_good_articles' => 0,
686 'ss_total_pages' => 0,
687 'ss_users' => 0,
688 'ss_images' => 0
689 ],
690 __METHOD__, 'IGNORE'
691 );
692
693 return Status::newGood();
694 }
695
696 /**
697 * Environment check for DB types.
698 * @return bool
699 */
700 protected function envCheckDB() {
701 global $wgLang;
702
703 $allNames = [];
704
705 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
706 // config-type-sqlite
707 foreach ( self::getDBTypes() as $name ) {
708 $allNames[] = wfMessage( "config-type-$name" )->text();
709 }
710
711 $databases = $this->getCompiledDBs();
712
713 $databases = array_flip( $databases );
714 foreach ( array_keys( $databases ) as $db ) {
715 $installer = $this->getDBInstaller( $db );
716 $status = $installer->checkPrerequisites();
717 if ( !$status->isGood() ) {
718 $this->showStatusMessage( $status );
719 }
720 if ( !$status->isOK() ) {
721 unset( $databases[$db] );
722 }
723 }
724 $databases = array_flip( $databases );
725 if ( !$databases ) {
726 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
727
728 // @todo FIXME: This only works for the web installer!
729 return false;
730 }
731
732 return true;
733 }
734
735 /**
736 * Some versions of libxml+PHP break < and > encoding horribly
737 * @return bool
738 */
739 protected function envCheckBrokenXML() {
740 $test = new PhpXmlBugTester();
741 if ( !$test->ok ) {
742 $this->showError( 'config-brokenlibxml' );
743
744 return false;
745 }
746
747 return true;
748 }
749
750 /**
751 * Environment check for mbstring.func_overload.
752 * @return bool
753 */
754 protected function envCheckMbstring() {
755 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
756 $this->showError( 'config-mbstring' );
757
758 return false;
759 }
760
761 return true;
762 }
763
764 /**
765 * Environment check for the XML module.
766 * @return bool
767 */
768 protected function envCheckXML() {
769 if ( !function_exists( "utf8_encode" ) ) {
770 $this->showError( 'config-xml-bad' );
771
772 return false;
773 }
774
775 return true;
776 }
777
778 /**
779 * Environment check for the PCRE module.
780 *
781 * @note If this check were to fail, the parser would
782 * probably throw an exception before the result
783 * of this check is shown to the user.
784 * @return bool
785 */
786 protected function envCheckPCRE() {
787 MediaWiki\suppressWarnings();
788 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
789 // Need to check for \p support too, as PCRE can be compiled
790 // with utf8 support, but not unicode property support.
791 // check that \p{Zs} (space separators) matches
792 // U+3000 (Ideographic space)
793 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
794 MediaWiki\restoreWarnings();
795 if ( $regexd != '--' || $regexprop != '--' ) {
796 $this->showError( 'config-pcre-no-utf8' );
797
798 return false;
799 }
800
801 return true;
802 }
803
804 /**
805 * Environment check for available memory.
806 * @return bool
807 */
808 protected function envCheckMemory() {
809 $limit = ini_get( 'memory_limit' );
810
811 if ( !$limit || $limit == -1 ) {
812 return true;
813 }
814
815 $n = wfShorthandToInteger( $limit );
816
817 if ( $n < $this->minMemorySize * 1024 * 1024 ) {
818 $newLimit = "{$this->minMemorySize}M";
819
820 if ( ini_set( "memory_limit", $newLimit ) === false ) {
821 $this->showMessage( 'config-memory-bad', $limit );
822 } else {
823 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
824 $this->setVar( '_RaiseMemory', true );
825 }
826 }
827
828 return true;
829 }
830
831 /**
832 * Environment check for compiled object cache types.
833 */
834 protected function envCheckCache() {
835 $caches = [];
836 foreach ( $this->objectCaches as $name => $function ) {
837 if ( function_exists( $function ) ) {
838 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
839 continue;
840 }
841 $caches[$name] = true;
842 }
843 }
844
845 if ( !$caches ) {
846 $key = 'config-no-cache-apcu';
847 $this->showMessage( $key );
848 }
849
850 $this->setVar( '_Caches', $caches );
851 }
852
853 /**
854 * Scare user to death if they have mod_security or mod_security2
855 * @return bool
856 */
857 protected function envCheckModSecurity() {
858 if ( self::apacheModulePresent( 'mod_security' )
859 || self::apacheModulePresent( 'mod_security2' ) ) {
860 $this->showMessage( 'config-mod-security' );
861 }
862
863 return true;
864 }
865
866 /**
867 * Search for GNU diff3.
868 * @return bool
869 */
870 protected function envCheckDiff3() {
871 $names = [ "gdiff3", "diff3", "diff3.exe" ];
872 $versionInfo = [ '$1 --version 2>&1', 'GNU diffutils' ];
873
874 $diff3 = self::locateExecutableInDefaultPaths( $names, $versionInfo );
875
876 if ( $diff3 ) {
877 $this->setVar( 'wgDiff3', $diff3 );
878 } else {
879 $this->setVar( 'wgDiff3', false );
880 $this->showMessage( 'config-diff3-bad' );
881 }
882
883 return true;
884 }
885
886 /**
887 * Environment check for ImageMagick and GD.
888 * @return bool
889 */
890 protected function envCheckGraphics() {
891 $names = [ wfIsWindows() ? 'convert.exe' : 'convert' ];
892 $versionInfo = [ '$1 -version', 'ImageMagick' ];
893 $convert = self::locateExecutableInDefaultPaths( $names, $versionInfo );
894
895 $this->setVar( 'wgImageMagickConvertCommand', '' );
896 if ( $convert ) {
897 $this->setVar( 'wgImageMagickConvertCommand', $convert );
898 $this->showMessage( 'config-imagemagick', $convert );
899
900 return true;
901 } elseif ( function_exists( 'imagejpeg' ) ) {
902 $this->showMessage( 'config-gd' );
903 } else {
904 $this->showMessage( 'config-no-scaling' );
905 }
906
907 return true;
908 }
909
910 /**
911 * Search for git.
912 *
913 * @since 1.22
914 * @return bool
915 */
916 protected function envCheckGit() {
917 $names = [ wfIsWindows() ? 'git.exe' : 'git' ];
918 $versionInfo = [ '$1 --version', 'git version' ];
919
920 $git = self::locateExecutableInDefaultPaths( $names, $versionInfo );
921
922 if ( $git ) {
923 $this->setVar( 'wgGitBin', $git );
924 $this->showMessage( 'config-git', $git );
925 } else {
926 $this->setVar( 'wgGitBin', false );
927 $this->showMessage( 'config-git-bad' );
928 }
929
930 return true;
931 }
932
933 /**
934 * Environment check to inform user which server we've assumed.
935 *
936 * @return bool
937 */
938 protected function envCheckServer() {
939 $server = $this->envGetDefaultServer();
940 if ( $server !== null ) {
941 $this->showMessage( 'config-using-server', $server );
942 }
943 return true;
944 }
945
946 /**
947 * Environment check to inform user which paths we've assumed.
948 *
949 * @return bool
950 */
951 protected function envCheckPath() {
952 $this->showMessage(
953 'config-using-uri',
954 $this->getVar( 'wgServer' ),
955 $this->getVar( 'wgScriptPath' )
956 );
957 return true;
958 }
959
960 /**
961 * Environment check for preferred locale in shell
962 * @return bool
963 */
964 protected function envCheckShellLocale() {
965 $os = php_uname( 's' );
966 $supported = [ 'Linux', 'SunOS', 'HP-UX', 'Darwin' ]; # Tested these
967
968 if ( !in_array( $os, $supported ) ) {
969 return true;
970 }
971
972 # Get a list of available locales.
973 $ret = false;
974 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
975
976 if ( $ret ) {
977 return true;
978 }
979
980 $lines = array_map( 'trim', explode( "\n", $lines ) );
981 $candidatesByLocale = [];
982 $candidatesByLang = [];
983
984 foreach ( $lines as $line ) {
985 if ( $line === '' ) {
986 continue;
987 }
988
989 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
990 continue;
991 }
992
993 list( , $lang, , , ) = $m;
994
995 $candidatesByLocale[$m[0]] = $m;
996 $candidatesByLang[$lang][] = $m;
997 }
998
999 # Try the current value of LANG.
1000 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1001 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1002
1003 return true;
1004 }
1005
1006 # Try the most common ones.
1007 $commonLocales = [ 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' ];
1008 foreach ( $commonLocales as $commonLocale ) {
1009 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1010 $this->setVar( 'wgShellLocale', $commonLocale );
1011
1012 return true;
1013 }
1014 }
1015
1016 # Is there an available locale in the Wiki's language?
1017 $wikiLang = $this->getVar( 'wgLanguageCode' );
1018
1019 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1020 $m = reset( $candidatesByLang[$wikiLang] );
1021 $this->setVar( 'wgShellLocale', $m[0] );
1022
1023 return true;
1024 }
1025
1026 # Are there any at all?
1027 if ( count( $candidatesByLocale ) ) {
1028 $m = reset( $candidatesByLocale );
1029 $this->setVar( 'wgShellLocale', $m[0] );
1030
1031 return true;
1032 }
1033
1034 # Give up.
1035 return true;
1036 }
1037
1038 /**
1039 * Environment check for the permissions of the uploads directory
1040 * @return bool
1041 */
1042 protected function envCheckUploadsDirectory() {
1043 global $IP;
1044
1045 $dir = $IP . '/images/';
1046 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1047 $safe = !$this->dirIsExecutable( $dir, $url );
1048
1049 if ( !$safe ) {
1050 $this->showMessage( 'config-uploads-not-safe', $dir );
1051 }
1052
1053 return true;
1054 }
1055
1056 /**
1057 * Checks if suhosin.get.max_value_length is set, and if so generate
1058 * a warning because it decreases ResourceLoader performance.
1059 * @return bool
1060 */
1061 protected function envCheckSuhosinMaxValueLength() {
1062 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1063 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1064 // Only warn if the value is below the sane 1024
1065 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1066 }
1067
1068 return true;
1069 }
1070
1071 /**
1072 * Convert a hex string representing a Unicode code point to that code point.
1073 * @param string $c
1074 * @return string
1075 */
1076 protected function unicodeChar( $c ) {
1077 $c = hexdec( $c );
1078 if ( $c <= 0x7F ) {
1079 return chr( $c );
1080 } elseif ( $c <= 0x7FF ) {
1081 return chr( 0xC0 | $c >> 6 ) . chr( 0x80 | $c & 0x3F );
1082 } elseif ( $c <= 0xFFFF ) {
1083 return chr( 0xE0 | $c >> 12 ) . chr( 0x80 | $c >> 6 & 0x3F ) .
1084 chr( 0x80 | $c & 0x3F );
1085 } elseif ( $c <= 0x10FFFF ) {
1086 return chr( 0xF0 | $c >> 18 ) . chr( 0x80 | $c >> 12 & 0x3F ) .
1087 chr( 0x80 | $c >> 6 & 0x3F ) .
1088 chr( 0x80 | $c & 0x3F );
1089 } else {
1090 return false;
1091 }
1092 }
1093
1094 /**
1095 * Check the libicu version
1096 */
1097 protected function envCheckLibicu() {
1098 /**
1099 * This needs to be updated something that the latest libicu
1100 * will properly normalize. This normalization was found at
1101 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1102 * Note that we use the hex representation to create the code
1103 * points in order to avoid any Unicode-destroying during transit.
1104 */
1105 $not_normal_c = $this->unicodeChar( "FA6C" );
1106 $normal_c = $this->unicodeChar( "242EE" );
1107
1108 $useNormalizer = 'php';
1109 $needsUpdate = false;
1110
1111 if ( function_exists( 'normalizer_normalize' ) ) {
1112 $useNormalizer = 'intl';
1113 $intl = normalizer_normalize( $not_normal_c, Normalizer::FORM_C );
1114 if ( $intl !== $normal_c ) {
1115 $needsUpdate = true;
1116 }
1117 }
1118
1119 // Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
1120 if ( $useNormalizer === 'php' ) {
1121 $this->showMessage( 'config-unicode-pure-php-warning' );
1122 } else {
1123 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1124 if ( $needsUpdate ) {
1125 $this->showMessage( 'config-unicode-update-warning' );
1126 }
1127 }
1128 }
1129
1130 /**
1131 * @return bool
1132 */
1133 protected function envCheckCtype() {
1134 if ( !function_exists( 'ctype_digit' ) ) {
1135 $this->showError( 'config-ctype' );
1136
1137 return false;
1138 }
1139
1140 return true;
1141 }
1142
1143 /**
1144 * @return bool
1145 */
1146 protected function envCheckIconv() {
1147 if ( !function_exists( 'iconv' ) ) {
1148 $this->showError( 'config-iconv' );
1149
1150 return false;
1151 }
1152
1153 return true;
1154 }
1155
1156 /**
1157 * @return bool
1158 */
1159 protected function envCheckJSON() {
1160 if ( !function_exists( 'json_decode' ) ) {
1161 $this->showError( 'config-json' );
1162
1163 return false;
1164 }
1165
1166 return true;
1167 }
1168
1169 /**
1170 * Environment prep for the server hostname.
1171 */
1172 protected function envPrepServer() {
1173 $server = $this->envGetDefaultServer();
1174 if ( $server !== null ) {
1175 $this->setVar( 'wgServer', $server );
1176 }
1177 }
1178
1179 /**
1180 * Helper function to be called from envPrepServer()
1181 * @return string
1182 */
1183 abstract protected function envGetDefaultServer();
1184
1185 /**
1186 * Environment prep for setting $IP and $wgScriptPath.
1187 */
1188 protected function envPrepPath() {
1189 global $IP;
1190 $IP = dirname( dirname( __DIR__ ) );
1191 $this->setVar( 'IP', $IP );
1192 }
1193
1194 /**
1195 * Get an array of likely places we can find executables. Check a bunch
1196 * of known Unix-like defaults, as well as the PATH environment variable
1197 * (which should maybe make it work for Windows?)
1198 *
1199 * @return array
1200 */
1201 protected static function getPossibleBinPaths() {
1202 return array_merge(
1203 [ '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1204 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ],
1205 explode( PATH_SEPARATOR, getenv( 'PATH' ) )
1206 );
1207 }
1208
1209 /**
1210 * Search a path for any of the given executable names. Returns the
1211 * executable name if found. Also checks the version string returned
1212 * by each executable.
1213 *
1214 * Used only by environment checks.
1215 *
1216 * @param string $path Path to search
1217 * @param array $names Array of executable names
1218 * @param array|bool $versionInfo False or array with two members:
1219 * 0 => Command to run for version check, with $1 for the full executable name
1220 * 1 => String to compare the output with
1221 *
1222 * If $versionInfo is not false, only executables with a version
1223 * matching $versionInfo[1] will be returned.
1224 * @return bool|string
1225 */
1226 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1227 if ( !is_array( $names ) ) {
1228 $names = [ $names ];
1229 }
1230
1231 foreach ( $names as $name ) {
1232 $command = $path . DIRECTORY_SEPARATOR . $name;
1233
1234 MediaWiki\suppressWarnings();
1235 $file_exists = file_exists( $command );
1236 MediaWiki\restoreWarnings();
1237
1238 if ( $file_exists ) {
1239 if ( !$versionInfo ) {
1240 return $command;
1241 }
1242
1243 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1244 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1245 return $command;
1246 }
1247 }
1248 }
1249
1250 return false;
1251 }
1252
1253 /**
1254 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1255 * @see locateExecutable()
1256 * @param array $names Array of possible names.
1257 * @param array|bool $versionInfo Default: false or array with two members:
1258 * 0 => Command to run for version check, with $1 for the full executable name
1259 * 1 => String to compare the output with
1260 *
1261 * If $versionInfo is not false, only executables with a version
1262 * matching $versionInfo[1] will be returned.
1263 * @return bool|string
1264 */
1265 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1266 foreach ( self::getPossibleBinPaths() as $path ) {
1267 $exe = self::locateExecutable( $path, $names, $versionInfo );
1268 if ( $exe !== false ) {
1269 return $exe;
1270 }
1271 }
1272
1273 return false;
1274 }
1275
1276 /**
1277 * Checks if scripts located in the given directory can be executed via the given URL.
1278 *
1279 * Used only by environment checks.
1280 * @param string $dir
1281 * @param string $url
1282 * @return bool|int|string
1283 */
1284 public function dirIsExecutable( $dir, $url ) {
1285 $scriptTypes = [
1286 'php' => [
1287 "<?php echo 'ex' . 'ec';",
1288 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1289 ],
1290 ];
1291
1292 // it would be good to check other popular languages here, but it'll be slow.
1293
1294 MediaWiki\suppressWarnings();
1295
1296 foreach ( $scriptTypes as $ext => $contents ) {
1297 foreach ( $contents as $source ) {
1298 $file = 'exectest.' . $ext;
1299
1300 if ( !file_put_contents( $dir . $file, $source ) ) {
1301 break;
1302 }
1303
1304 try {
1305 $text = Http::get( $url . $file, [ 'timeout' => 3 ], __METHOD__ );
1306 } catch ( Exception $e ) {
1307 // Http::get throws with allow_url_fopen = false and no curl extension.
1308 $text = null;
1309 }
1310 unlink( $dir . $file );
1311
1312 if ( $text == 'exec' ) {
1313 MediaWiki\restoreWarnings();
1314
1315 return $ext;
1316 }
1317 }
1318 }
1319
1320 MediaWiki\restoreWarnings();
1321
1322 return false;
1323 }
1324
1325 /**
1326 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1327 *
1328 * @param string $moduleName Name of module to check.
1329 * @return bool
1330 */
1331 public static function apacheModulePresent( $moduleName ) {
1332 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1333 return true;
1334 }
1335 // try it the hard way
1336 ob_start();
1337 phpinfo( INFO_MODULES );
1338 $info = ob_get_clean();
1339
1340 return strpos( $info, $moduleName ) !== false;
1341 }
1342
1343 /**
1344 * ParserOptions are constructed before we determined the language, so fix it
1345 *
1346 * @param Language $lang
1347 */
1348 public function setParserLanguage( $lang ) {
1349 $this->parserOptions->setTargetLanguage( $lang );
1350 $this->parserOptions->setUserLang( $lang );
1351 }
1352
1353 /**
1354 * Overridden by WebInstaller to provide lastPage parameters.
1355 * @param string $page
1356 * @return string
1357 */
1358 protected function getDocUrl( $page ) {
1359 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1360 }
1361
1362 /**
1363 * Finds extensions that follow the format /$directory/Name/Name.php,
1364 * and returns an array containing the value for 'Name' for each found extension.
1365 *
1366 * Reasonable values for $directory include 'extensions' (the default) and 'skins'.
1367 *
1368 * @param string $directory Directory to search in
1369 * @return array
1370 */
1371 public function findExtensions( $directory = 'extensions' ) {
1372 if ( $this->getVar( 'IP' ) === null ) {
1373 return [];
1374 }
1375
1376 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1377 if ( !is_readable( $extDir ) || !is_dir( $extDir ) ) {
1378 return [];
1379 }
1380
1381 // extensions -> extension.json, skins -> skin.json
1382 $jsonFile = substr( $directory, 0, strlen( $directory ) -1 ) . '.json';
1383
1384 $dh = opendir( $extDir );
1385 $exts = [];
1386 while ( ( $file = readdir( $dh ) ) !== false ) {
1387 if ( !is_dir( "$extDir/$file" ) ) {
1388 continue;
1389 }
1390 if ( file_exists( "$extDir/$file/$jsonFile" ) || file_exists( "$extDir/$file/$file.php" ) ) {
1391 $exts[] = $file;
1392 }
1393 }
1394 closedir( $dh );
1395 natcasesort( $exts );
1396
1397 return $exts;
1398 }
1399
1400 /**
1401 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1402 * but will fall back to another if the default skin is missing and some other one is present
1403 * instead.
1404 *
1405 * @param string[] $skinNames Names of installed skins.
1406 * @return string
1407 */
1408 public function getDefaultSkin( array $skinNames ) {
1409 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1410 if ( !$skinNames || in_array( $defaultSkin, $skinNames ) ) {
1411 return $defaultSkin;
1412 } else {
1413 return $skinNames[0];
1414 }
1415 }
1416
1417 /**
1418 * Installs the auto-detected extensions.
1419 *
1420 * @return Status
1421 */
1422 protected function includeExtensions() {
1423 global $IP;
1424 $exts = $this->getVar( '_Extensions' );
1425 $IP = $this->getVar( 'IP' );
1426
1427 /**
1428 * We need to include DefaultSettings before including extensions to avoid
1429 * warnings about unset variables. However, the only thing we really
1430 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1431 * if the extension has hidden hook registration in $wgExtensionFunctions,
1432 * but we're not opening that can of worms
1433 * @see https://phabricator.wikimedia.org/T28857
1434 */
1435 global $wgAutoloadClasses;
1436 $wgAutoloadClasses = [];
1437 $queue = [];
1438
1439 require "$IP/includes/DefaultSettings.php";
1440
1441 foreach ( $exts as $e ) {
1442 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1443 $queue["$IP/extensions/$e/extension.json"] = 1;
1444 } else {
1445 require_once "$IP/extensions/$e/$e.php";
1446 }
1447 }
1448
1449 $registry = new ExtensionRegistry();
1450 $data = $registry->readFromQueue( $queue );
1451 $wgAutoloadClasses += $data['autoload'];
1452
1453 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1454 $wgHooks['LoadExtensionSchemaUpdates'] : [];
1455
1456 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1457 $hooksWeWant = array_merge_recursive(
1458 $hooksWeWant,
1459 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1460 );
1461 }
1462 // Unset everyone else's hooks. Lord knows what someone might be doing
1463 // in ParserFirstCallInit (see bug 27171)
1464 $GLOBALS['wgHooks'] = [ 'LoadExtensionSchemaUpdates' => $hooksWeWant ];
1465
1466 return Status::newGood();
1467 }
1468
1469 /**
1470 * Get an array of install steps. Should always be in the format of
1471 * array(
1472 * 'name' => 'someuniquename',
1473 * 'callback' => array( $obj, 'method' ),
1474 * )
1475 * There must be a config-install-$name message defined per step, which will
1476 * be shown on install.
1477 *
1478 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1479 * @return array
1480 */
1481 protected function getInstallSteps( DatabaseInstaller $installer ) {
1482 $coreInstallSteps = [
1483 [ 'name' => 'database', 'callback' => [ $installer, 'setupDatabase' ] ],
1484 [ 'name' => 'tables', 'callback' => [ $installer, 'createTables' ] ],
1485 [ 'name' => 'interwiki', 'callback' => [ $installer, 'populateInterwikiTable' ] ],
1486 [ 'name' => 'stats', 'callback' => [ $this, 'populateSiteStats' ] ],
1487 [ 'name' => 'keys', 'callback' => [ $this, 'generateKeys' ] ],
1488 [ 'name' => 'updates', 'callback' => [ $installer, 'insertUpdateKeys' ] ],
1489 [ 'name' => 'sysop', 'callback' => [ $this, 'createSysop' ] ],
1490 [ 'name' => 'mainpage', 'callback' => [ $this, 'createMainpage' ] ],
1491 ];
1492
1493 // Build the array of install steps starting from the core install list,
1494 // then adding any callbacks that wanted to attach after a given step
1495 foreach ( $coreInstallSteps as $step ) {
1496 $this->installSteps[] = $step;
1497 if ( isset( $this->extraInstallSteps[$step['name']] ) ) {
1498 $this->installSteps = array_merge(
1499 $this->installSteps,
1500 $this->extraInstallSteps[$step['name']]
1501 );
1502 }
1503 }
1504
1505 // Prepend any steps that want to be at the beginning
1506 if ( isset( $this->extraInstallSteps['BEGINNING'] ) ) {
1507 $this->installSteps = array_merge(
1508 $this->extraInstallSteps['BEGINNING'],
1509 $this->installSteps
1510 );
1511 }
1512
1513 // Extensions should always go first, chance to tie into hooks and such
1514 if ( count( $this->getVar( '_Extensions' ) ) ) {
1515 array_unshift( $this->installSteps,
1516 [ 'name' => 'extensions', 'callback' => [ $this, 'includeExtensions' ] ]
1517 );
1518 $this->installSteps[] = [
1519 'name' => 'extension-tables',
1520 'callback' => [ $installer, 'createExtensionTables' ]
1521 ];
1522 }
1523
1524 return $this->installSteps;
1525 }
1526
1527 /**
1528 * Actually perform the installation.
1529 *
1530 * @param callable $startCB A callback array for the beginning of each step
1531 * @param callable $endCB A callback array for the end of each step
1532 *
1533 * @return array Array of Status objects
1534 */
1535 public function performInstallation( $startCB, $endCB ) {
1536 $installResults = [];
1537 $installer = $this->getDBInstaller();
1538 $installer->preInstall();
1539 $steps = $this->getInstallSteps( $installer );
1540 foreach ( $steps as $stepObj ) {
1541 $name = $stepObj['name'];
1542 call_user_func_array( $startCB, [ $name ] );
1543
1544 // Perform the callback step
1545 $status = call_user_func( $stepObj['callback'], $installer );
1546
1547 // Output and save the results
1548 call_user_func( $endCB, $name, $status );
1549 $installResults[$name] = $status;
1550
1551 // If we've hit some sort of fatal, we need to bail.
1552 // Callback already had a chance to do output above.
1553 if ( !$status->isOk() ) {
1554 break;
1555 }
1556 }
1557 if ( $status->isOk() ) {
1558 $this->setVar( '_InstallDone', true );
1559 }
1560
1561 return $installResults;
1562 }
1563
1564 /**
1565 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1566 *
1567 * @return Status
1568 */
1569 public function generateKeys() {
1570 $keys = [ 'wgSecretKey' => 64 ];
1571 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1572 $keys['wgUpgradeKey'] = 16;
1573 }
1574
1575 return $this->doGenerateKeys( $keys );
1576 }
1577
1578 /**
1579 * Generate a secret value for variables using our CryptRand generator.
1580 * Produce a warning if the random source was insecure.
1581 *
1582 * @param array $keys
1583 * @return Status
1584 */
1585 protected function doGenerateKeys( $keys ) {
1586 $status = Status::newGood();
1587
1588 $strong = true;
1589 foreach ( $keys as $name => $length ) {
1590 $secretKey = MWCryptRand::generateHex( $length, true );
1591 if ( !MWCryptRand::wasStrong() ) {
1592 $strong = false;
1593 }
1594
1595 $this->setVar( $name, $secretKey );
1596 }
1597
1598 if ( !$strong ) {
1599 $names = array_keys( $keys );
1600 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1601 global $wgLang;
1602 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1603 }
1604
1605 return $status;
1606 }
1607
1608 /**
1609 * Create the first user account, grant it sysop and bureaucrat rights
1610 *
1611 * @return Status
1612 */
1613 protected function createSysop() {
1614 $name = $this->getVar( '_AdminName' );
1615 $user = User::newFromName( $name );
1616
1617 if ( !$user ) {
1618 // We should've validated this earlier anyway!
1619 return Status::newFatal( 'config-admin-error-user', $name );
1620 }
1621
1622 if ( $user->idForName() == 0 ) {
1623 $user->addToDatabase();
1624
1625 try {
1626 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1627 } catch ( PasswordError $pwe ) {
1628 return Status::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1629 }
1630
1631 $user->addGroup( 'sysop' );
1632 $user->addGroup( 'bureaucrat' );
1633 if ( $this->getVar( '_AdminEmail' ) ) {
1634 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1635 }
1636 $user->saveSettings();
1637
1638 // Update user count
1639 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1640 $ssUpdate->doUpdate();
1641 }
1642 $status = Status::newGood();
1643
1644 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1645 $this->subscribeToMediaWikiAnnounce( $status );
1646 }
1647
1648 return $status;
1649 }
1650
1651 /**
1652 * @param Status $s
1653 */
1654 private function subscribeToMediaWikiAnnounce( Status $s ) {
1655 $params = [
1656 'email' => $this->getVar( '_AdminEmail' ),
1657 'language' => 'en',
1658 'digest' => 0
1659 ];
1660
1661 // Mailman doesn't support as many languages as we do, so check to make
1662 // sure their selected language is available
1663 $myLang = $this->getVar( '_UserLang' );
1664 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages ) ) {
1665 $myLang = $myLang == 'pt-br' ? 'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1666 $params['language'] = $myLang;
1667 }
1668
1669 if ( MWHttpRequest::canMakeRequests() ) {
1670 $res = MWHttpRequest::factory( $this->mediaWikiAnnounceUrl,
1671 [ 'method' => 'POST', 'postData' => $params ], __METHOD__ )->execute();
1672 if ( !$res->isOK() ) {
1673 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1674 }
1675 } else {
1676 $s->warning( 'config-install-subscribe-notpossible' );
1677 }
1678 }
1679
1680 /**
1681 * Insert Main Page with default content.
1682 *
1683 * @param DatabaseInstaller $installer
1684 * @return Status
1685 */
1686 protected function createMainpage( DatabaseInstaller $installer ) {
1687 $status = Status::newGood();
1688 try {
1689 $page = WikiPage::factory( Title::newMainPage() );
1690 $content = new WikitextContent(
1691 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1692 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1693 );
1694
1695 $page->doEditContent( $content,
1696 '',
1697 EDIT_NEW,
1698 false,
1699 User::newFromName( 'MediaWiki default' )
1700 );
1701 } catch ( Exception $e ) {
1702 // using raw, because $wgShowExceptionDetails can not be set yet
1703 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1704 }
1705
1706 return $status;
1707 }
1708
1709 /**
1710 * Override the necessary bits of the config to run an installation.
1711 */
1712 public static function overrideConfig() {
1713 // Use PHP's built-in session handling, since MediaWiki's
1714 // SessionHandler can't work before we have an object cache set up.
1715 define( 'MW_NO_SESSION_HANDLER', 1 );
1716
1717 // Don't access the database
1718 $GLOBALS['wgUseDatabaseMessages'] = false;
1719 // Don't cache langconv tables
1720 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE;
1721 // Debug-friendly
1722 $GLOBALS['wgShowExceptionDetails'] = true;
1723 // Don't break forms
1724 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1725
1726 // Extended debugging
1727 $GLOBALS['wgShowSQLErrors'] = true;
1728 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1729
1730 // Allow multiple ob_flush() calls
1731 $GLOBALS['wgDisableOutputCompression'] = true;
1732
1733 // Use a sensible cookie prefix (not my_wiki)
1734 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1735
1736 // Some of the environment checks make shell requests, remove limits
1737 $GLOBALS['wgMaxShellMemory'] = 0;
1738
1739 // Override the default CookieSessionProvider with a dummy
1740 // implementation that won't stomp on PHP's cookies.
1741 $GLOBALS['wgSessionProviders'] = [
1742 [
1743 'class' => 'InstallerSessionProvider',
1744 'args' => [ [
1745 'priority' => 1,
1746 ] ]
1747 ]
1748 ];
1749
1750 // Don't try to use any object cache for SessionManager either.
1751 $GLOBALS['wgSessionCacheType'] = CACHE_NONE;
1752 }
1753
1754 /**
1755 * Add an installation step following the given step.
1756 *
1757 * @param callable $callback A valid installation callback array, in this form:
1758 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1759 * @param string $findStep The step to find. Omit to put the step at the beginning
1760 */
1761 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1762 $this->extraInstallSteps[$findStep][] = $callback;
1763 }
1764
1765 /**
1766 * Disable the time limit for execution.
1767 * Some long-running pages (Install, Upgrade) will want to do this
1768 */
1769 protected function disableTimeLimit() {
1770 MediaWiki\suppressWarnings();
1771 set_time_limit( 0 );
1772 MediaWiki\restoreWarnings();
1773 }
1774 }