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