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