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