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