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