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