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