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