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