Merge "Install link to Manual:Combating_spam on the home page"
[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 * Environment check for DB types.
696 * @return bool
697 */
698 protected function envCheckDB() {
699 global $wgLang;
700
701 $allNames = array();
702
703 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
704 // config-type-sqlite
705 foreach ( self::getDBTypes() as $name ) {
706 $allNames[] = wfMessage( "config-type-$name" )->text();
707 }
708
709 $databases = $this->getCompiledDBs();
710
711 $databases = array_flip( $databases );
712 foreach ( array_keys( $databases ) as $db ) {
713 $installer = $this->getDBInstaller( $db );
714 $status = $installer->checkPrerequisites();
715 if ( !$status->isGood() ) {
716 $this->showStatusMessage( $status );
717 }
718 if ( !$status->isOK() ) {
719 unset( $databases[$db] );
720 }
721 }
722 $databases = array_flip( $databases );
723 if ( !$databases ) {
724 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
725
726 // @todo FIXME: This only works for the web installer!
727 return false;
728 }
729
730 return true;
731 }
732
733 /**
734 * Environment check for register_globals.
735 * Prevent installation if enabled
736 * @return bool
737 */
738 protected function envCheckRegisterGlobals() {
739 if ( wfIniGetBool( 'register_globals' ) ) {
740 $this->showMessage( 'config-register-globals-error' );
741 return false;
742 }
743
744 return true;
745 }
746
747 /**
748 * Some versions of libxml+PHP break < and > encoding horribly
749 * @return bool
750 */
751 protected function envCheckBrokenXML() {
752 $test = new PhpXmlBugTester();
753 if ( !$test->ok ) {
754 $this->showError( 'config-brokenlibxml' );
755
756 return false;
757 }
758
759 return true;
760 }
761
762 /**
763 * Environment check for magic_quotes_(gpc|runtime|sybase).
764 * @return bool
765 */
766 protected function envCheckMagicQuotes() {
767 $status = true;
768 foreach ( array( 'gpc', 'runtime', 'sybase' ) as $magicJunk ) {
769 if ( wfIniGetBool( "magic_quotes_$magicJunk" ) ) {
770 $this->showError( "config-magic-quotes-$magicJunk" );
771 $status = false;
772 }
773 }
774
775 return $status;
776 }
777
778 /**
779 * Environment check for mbstring.func_overload.
780 * @return bool
781 */
782 protected function envCheckMbstring() {
783 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
784 $this->showError( 'config-mbstring' );
785
786 return false;
787 }
788
789 return true;
790 }
791
792 /**
793 * Environment check for safe_mode.
794 * @return bool
795 */
796 protected function envCheckSafeMode() {
797 if ( wfIniGetBool( 'safe_mode' ) ) {
798 $this->setVar( '_SafeMode', true );
799 $this->showMessage( 'config-safe-mode' );
800 }
801
802 return true;
803 }
804
805 /**
806 * Environment check for the XML module.
807 * @return bool
808 */
809 protected function envCheckXML() {
810 if ( !function_exists( "utf8_encode" ) ) {
811 $this->showError( 'config-xml-bad' );
812
813 return false;
814 }
815
816 return true;
817 }
818
819 /**
820 * Environment check for the PCRE module.
821 *
822 * @note If this check were to fail, the parser would
823 * probably throw an exception before the result
824 * of this check is shown to the user.
825 * @return bool
826 */
827 protected function envCheckPCRE() {
828 MediaWiki\suppressWarnings();
829 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
830 // Need to check for \p support too, as PCRE can be compiled
831 // with utf8 support, but not unicode property support.
832 // check that \p{Zs} (space separators) matches
833 // U+3000 (Ideographic space)
834 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
835 MediaWiki\restoreWarnings();
836 if ( $regexd != '--' || $regexprop != '--' ) {
837 $this->showError( 'config-pcre-no-utf8' );
838
839 return false;
840 }
841
842 return true;
843 }
844
845 /**
846 * Environment check for available memory.
847 * @return bool
848 */
849 protected function envCheckMemory() {
850 $limit = ini_get( 'memory_limit' );
851
852 if ( !$limit || $limit == -1 ) {
853 return true;
854 }
855
856 $n = wfShorthandToInteger( $limit );
857
858 if ( $n < $this->minMemorySize * 1024 * 1024 ) {
859 $newLimit = "{$this->minMemorySize}M";
860
861 if ( ini_set( "memory_limit", $newLimit ) === false ) {
862 $this->showMessage( 'config-memory-bad', $limit );
863 } else {
864 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
865 $this->setVar( '_RaiseMemory', true );
866 }
867 }
868
869 return true;
870 }
871
872 /**
873 * Environment check for compiled object cache types.
874 */
875 protected function envCheckCache() {
876 $caches = array();
877 foreach ( $this->objectCaches as $name => $function ) {
878 if ( function_exists( $function ) ) {
879 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
880 continue;
881 }
882 $caches[$name] = true;
883 }
884 }
885
886 if ( !$caches ) {
887 $this->showMessage( 'config-no-cache' );
888 }
889
890 $this->setVar( '_Caches', $caches );
891 }
892
893 /**
894 * Scare user to death if they have mod_security or mod_security2
895 * @return bool
896 */
897 protected function envCheckModSecurity() {
898 if ( self::apacheModulePresent( 'mod_security' )
899 || self::apacheModulePresent( 'mod_security2' ) ) {
900 $this->showMessage( 'config-mod-security' );
901 }
902
903 return true;
904 }
905
906 /**
907 * Search for GNU diff3.
908 * @return bool
909 */
910 protected function envCheckDiff3() {
911 $names = array( "gdiff3", "diff3", "diff3.exe" );
912 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
913
914 $diff3 = self::locateExecutableInDefaultPaths( $names, $versionInfo );
915
916 if ( $diff3 ) {
917 $this->setVar( 'wgDiff3', $diff3 );
918 } else {
919 $this->setVar( 'wgDiff3', false );
920 $this->showMessage( 'config-diff3-bad' );
921 }
922
923 return true;
924 }
925
926 /**
927 * Environment check for ImageMagick and GD.
928 * @return bool
929 */
930 protected function envCheckGraphics() {
931 $names = array( wfIsWindows() ? 'convert.exe' : 'convert' );
932 $versionInfo = array( '$1 -version', 'ImageMagick' );
933 $convert = self::locateExecutableInDefaultPaths( $names, $versionInfo );
934
935 $this->setVar( 'wgImageMagickConvertCommand', '' );
936 if ( $convert ) {
937 $this->setVar( 'wgImageMagickConvertCommand', $convert );
938 $this->showMessage( 'config-imagemagick', $convert );
939
940 return true;
941 } elseif ( function_exists( 'imagejpeg' ) ) {
942 $this->showMessage( 'config-gd' );
943 } else {
944 $this->showMessage( 'config-no-scaling' );
945 }
946
947 return true;
948 }
949
950 /**
951 * Search for git.
952 *
953 * @since 1.22
954 * @return bool
955 */
956 protected function envCheckGit() {
957 $names = array( wfIsWindows() ? 'git.exe' : 'git' );
958 $versionInfo = array( '$1 --version', 'git version' );
959
960 $git = self::locateExecutableInDefaultPaths( $names, $versionInfo );
961
962 if ( $git ) {
963 $this->setVar( 'wgGitBin', $git );
964 $this->showMessage( 'config-git', $git );
965 } else {
966 $this->setVar( 'wgGitBin', false );
967 $this->showMessage( 'config-git-bad' );
968 }
969
970 return true;
971 }
972
973 /**
974 * Environment check to inform user which server we've assumed.
975 *
976 * @return bool
977 */
978 protected function envCheckServer() {
979 $server = $this->envGetDefaultServer();
980 if ( $server !== null ) {
981 $this->showMessage( 'config-using-server', $server );
982 }
983 return true;
984 }
985
986 /**
987 * Environment check to inform user which paths we've assumed.
988 *
989 * @return bool
990 */
991 protected function envCheckPath() {
992 $this->showMessage(
993 'config-using-uri',
994 $this->getVar( 'wgServer' ),
995 $this->getVar( 'wgScriptPath' )
996 );
997 return true;
998 }
999
1000 /**
1001 * Environment check for preferred locale in shell
1002 * @return bool
1003 */
1004 protected function envCheckShellLocale() {
1005 $os = php_uname( 's' );
1006 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
1007
1008 if ( !in_array( $os, $supported ) ) {
1009 return true;
1010 }
1011
1012 # Get a list of available locales.
1013 $ret = false;
1014 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1015
1016 if ( $ret ) {
1017 return true;
1018 }
1019
1020 $lines = array_map( 'trim', explode( "\n", $lines ) );
1021 $candidatesByLocale = array();
1022 $candidatesByLang = array();
1023
1024 foreach ( $lines as $line ) {
1025 if ( $line === '' ) {
1026 continue;
1027 }
1028
1029 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1030 continue;
1031 }
1032
1033 list( , $lang, , , ) = $m;
1034
1035 $candidatesByLocale[$m[0]] = $m;
1036 $candidatesByLang[$lang][] = $m;
1037 }
1038
1039 # Try the current value of LANG.
1040 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1041 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1042
1043 return true;
1044 }
1045
1046 # Try the most common ones.
1047 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1048 foreach ( $commonLocales as $commonLocale ) {
1049 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1050 $this->setVar( 'wgShellLocale', $commonLocale );
1051
1052 return true;
1053 }
1054 }
1055
1056 # Is there an available locale in the Wiki's language?
1057 $wikiLang = $this->getVar( 'wgLanguageCode' );
1058
1059 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1060 $m = reset( $candidatesByLang[$wikiLang] );
1061 $this->setVar( 'wgShellLocale', $m[0] );
1062
1063 return true;
1064 }
1065
1066 # Are there any at all?
1067 if ( count( $candidatesByLocale ) ) {
1068 $m = reset( $candidatesByLocale );
1069 $this->setVar( 'wgShellLocale', $m[0] );
1070
1071 return true;
1072 }
1073
1074 # Give up.
1075 return true;
1076 }
1077
1078 /**
1079 * Environment check for the permissions of the uploads directory
1080 * @return bool
1081 */
1082 protected function envCheckUploadsDirectory() {
1083 global $IP;
1084
1085 $dir = $IP . '/images/';
1086 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1087 $safe = !$this->dirIsExecutable( $dir, $url );
1088
1089 if ( !$safe ) {
1090 $this->showMessage( 'config-uploads-not-safe', $dir );
1091 }
1092
1093 return true;
1094 }
1095
1096 /**
1097 * Checks if suhosin.get.max_value_length is set, and if so generate
1098 * a warning because it decreases ResourceLoader performance.
1099 * @return bool
1100 */
1101 protected function envCheckSuhosinMaxValueLength() {
1102 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1103 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1104 // Only warn if the value is below the sane 1024
1105 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1106 }
1107
1108 return true;
1109 }
1110
1111 /**
1112 * Convert a hex string representing a Unicode code point to that code point.
1113 * @param string $c
1114 * @return string
1115 */
1116 protected function unicodeChar( $c ) {
1117 $c = hexdec( $c );
1118 if ( $c <= 0x7F ) {
1119 return chr( $c );
1120 } elseif ( $c <= 0x7FF ) {
1121 return chr( 0xC0 | $c >> 6 ) . chr( 0x80 | $c & 0x3F );
1122 } elseif ( $c <= 0xFFFF ) {
1123 return chr( 0xE0 | $c >> 12 ) . chr( 0x80 | $c >> 6 & 0x3F ) .
1124 chr( 0x80 | $c & 0x3F );
1125 } elseif ( $c <= 0x10FFFF ) {
1126 return chr( 0xF0 | $c >> 18 ) . chr( 0x80 | $c >> 12 & 0x3F ) .
1127 chr( 0x80 | $c >> 6 & 0x3F ) .
1128 chr( 0x80 | $c & 0x3F );
1129 } else {
1130 return false;
1131 }
1132 }
1133
1134 /**
1135 * Check the libicu version
1136 */
1137 protected function envCheckLibicu() {
1138 /**
1139 * This needs to be updated something that the latest libicu
1140 * will properly normalize. This normalization was found at
1141 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1142 * Note that we use the hex representation to create the code
1143 * points in order to avoid any Unicode-destroying during transit.
1144 */
1145 $not_normal_c = $this->unicodeChar( "FA6C" );
1146 $normal_c = $this->unicodeChar( "242EE" );
1147
1148 $useNormalizer = 'php';
1149 $needsUpdate = false;
1150
1151 if ( function_exists( 'normalizer_normalize' ) ) {
1152 $useNormalizer = 'intl';
1153 $intl = normalizer_normalize( $not_normal_c, Normalizer::FORM_C );
1154 if ( $intl !== $normal_c ) {
1155 $needsUpdate = true;
1156 }
1157 }
1158
1159 // Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
1160 if ( $useNormalizer === 'php' ) {
1161 $this->showMessage( 'config-unicode-pure-php-warning' );
1162 } else {
1163 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1164 if ( $needsUpdate ) {
1165 $this->showMessage( 'config-unicode-update-warning' );
1166 }
1167 }
1168 }
1169
1170 /**
1171 * @return bool
1172 */
1173 protected function envCheckCtype() {
1174 if ( !function_exists( 'ctype_digit' ) ) {
1175 $this->showError( 'config-ctype' );
1176
1177 return false;
1178 }
1179
1180 return true;
1181 }
1182
1183 /**
1184 * @return bool
1185 */
1186 protected function envCheckIconv() {
1187 if ( !function_exists( 'iconv' ) ) {
1188 $this->showError( 'config-iconv' );
1189
1190 return false;
1191 }
1192
1193 return true;
1194 }
1195
1196 /**
1197 * @return bool
1198 */
1199 protected function envCheckJSON() {
1200 if ( !function_exists( 'json_decode' ) ) {
1201 $this->showError( 'config-json' );
1202
1203 return false;
1204 }
1205
1206 return true;
1207 }
1208
1209 /**
1210 * Environment prep for the server hostname.
1211 */
1212 protected function envPrepServer() {
1213 $server = $this->envGetDefaultServer();
1214 if ( $server !== null ) {
1215 $this->setVar( 'wgServer', $server );
1216 }
1217 }
1218
1219 /**
1220 * Helper function to be called from envPrepServer()
1221 * @return string
1222 */
1223 abstract protected function envGetDefaultServer();
1224
1225 /**
1226 * Environment prep for setting $IP and $wgScriptPath.
1227 */
1228 protected function envPrepPath() {
1229 global $IP;
1230 $IP = dirname( dirname( __DIR__ ) );
1231 $this->setVar( 'IP', $IP );
1232 }
1233
1234 /**
1235 * Get an array of likely places we can find executables. Check a bunch
1236 * of known Unix-like defaults, as well as the PATH environment variable
1237 * (which should maybe make it work for Windows?)
1238 *
1239 * @return array
1240 */
1241 protected static function getPossibleBinPaths() {
1242 return array_merge(
1243 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1244 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1245 explode( PATH_SEPARATOR, getenv( 'PATH' ) )
1246 );
1247 }
1248
1249 /**
1250 * Search a path for any of the given executable names. Returns the
1251 * executable name if found. Also checks the version string returned
1252 * by each executable.
1253 *
1254 * Used only by environment checks.
1255 *
1256 * @param string $path Path to search
1257 * @param array $names Array of executable names
1258 * @param array|bool $versionInfo False or array with two members:
1259 * 0 => Command to run for version check, with $1 for the full executable name
1260 * 1 => String to compare the output with
1261 *
1262 * If $versionInfo is not false, only executables with a version
1263 * matching $versionInfo[1] will be returned.
1264 * @return bool|string
1265 */
1266 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1267 if ( !is_array( $names ) ) {
1268 $names = array( $names );
1269 }
1270
1271 foreach ( $names as $name ) {
1272 $command = $path . DIRECTORY_SEPARATOR . $name;
1273
1274 MediaWiki\suppressWarnings();
1275 $file_exists = file_exists( $command );
1276 MediaWiki\restoreWarnings();
1277
1278 if ( $file_exists ) {
1279 if ( !$versionInfo ) {
1280 return $command;
1281 }
1282
1283 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1284 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1285 return $command;
1286 }
1287 }
1288 }
1289
1290 return false;
1291 }
1292
1293 /**
1294 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1295 * @see locateExecutable()
1296 * @param array $names Array of possible names.
1297 * @param array|bool $versionInfo Default: false or array with two members:
1298 * 0 => Command to run for version check, with $1 for the full executable name
1299 * 1 => String to compare the output with
1300 *
1301 * If $versionInfo is not false, only executables with a version
1302 * matching $versionInfo[1] will be returned.
1303 * @return bool|string
1304 */
1305 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1306 foreach ( self::getPossibleBinPaths() as $path ) {
1307 $exe = self::locateExecutable( $path, $names, $versionInfo );
1308 if ( $exe !== false ) {
1309 return $exe;
1310 }
1311 }
1312
1313 return false;
1314 }
1315
1316 /**
1317 * Checks if scripts located in the given directory can be executed via the given URL.
1318 *
1319 * Used only by environment checks.
1320 * @param string $dir
1321 * @param string $url
1322 * @return bool|int|string
1323 */
1324 public function dirIsExecutable( $dir, $url ) {
1325 $scriptTypes = array(
1326 'php' => array(
1327 "<?php echo 'ex' . 'ec';",
1328 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1329 ),
1330 );
1331
1332 // it would be good to check other popular languages here, but it'll be slow.
1333
1334 MediaWiki\suppressWarnings();
1335
1336 foreach ( $scriptTypes as $ext => $contents ) {
1337 foreach ( $contents as $source ) {
1338 $file = 'exectest.' . $ext;
1339
1340 if ( !file_put_contents( $dir . $file, $source ) ) {
1341 break;
1342 }
1343
1344 try {
1345 $text = Http::get( $url . $file, array( 'timeout' => 3 ), __METHOD__ );
1346 } catch ( Exception $e ) {
1347 // Http::get throws with allow_url_fopen = false and no curl extension.
1348 $text = null;
1349 }
1350 unlink( $dir . $file );
1351
1352 if ( $text == 'exec' ) {
1353 MediaWiki\restoreWarnings();
1354
1355 return $ext;
1356 }
1357 }
1358 }
1359
1360 MediaWiki\restoreWarnings();
1361
1362 return false;
1363 }
1364
1365 /**
1366 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1367 *
1368 * @param string $moduleName Name of module to check.
1369 * @return bool
1370 */
1371 public static function apacheModulePresent( $moduleName ) {
1372 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1373 return true;
1374 }
1375 // try it the hard way
1376 ob_start();
1377 phpinfo( INFO_MODULES );
1378 $info = ob_get_clean();
1379
1380 return strpos( $info, $moduleName ) !== false;
1381 }
1382
1383 /**
1384 * ParserOptions are constructed before we determined the language, so fix it
1385 *
1386 * @param Language $lang
1387 */
1388 public function setParserLanguage( $lang ) {
1389 $this->parserOptions->setTargetLanguage( $lang );
1390 $this->parserOptions->setUserLang( $lang );
1391 }
1392
1393 /**
1394 * Overridden by WebInstaller to provide lastPage parameters.
1395 * @param string $page
1396 * @return string
1397 */
1398 protected function getDocUrl( $page ) {
1399 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1400 }
1401
1402 /**
1403 * Finds extensions that follow the format /$directory/Name/Name.php,
1404 * and returns an array containing the value for 'Name' for each found extension.
1405 *
1406 * Reasonable values for $directory include 'extensions' (the default) and 'skins'.
1407 *
1408 * @param string $directory Directory to search in
1409 * @return array
1410 */
1411 public function findExtensions( $directory = 'extensions' ) {
1412 if ( $this->getVar( 'IP' ) === null ) {
1413 return array();
1414 }
1415
1416 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1417 if ( !is_readable( $extDir ) || !is_dir( $extDir ) ) {
1418 return array();
1419 }
1420
1421 // extensions -> extension.json, skins -> skin.json
1422 $jsonFile = substr( $directory, 0, strlen( $directory ) -1 ) . '.json';
1423
1424 $dh = opendir( $extDir );
1425 $exts = array();
1426 while ( ( $file = readdir( $dh ) ) !== false ) {
1427 if ( !is_dir( "$extDir/$file" ) ) {
1428 continue;
1429 }
1430 if ( file_exists( "$extDir/$file/$jsonFile" ) || file_exists( "$extDir/$file/$file.php" ) ) {
1431 $exts[] = $file;
1432 }
1433 }
1434 closedir( $dh );
1435 natcasesort( $exts );
1436
1437 return $exts;
1438 }
1439
1440 /**
1441 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1442 * but will fall back to another if the default skin is missing and some other one is present
1443 * instead.
1444 *
1445 * @param string[] $skinNames Names of installed skins.
1446 * @return string
1447 */
1448 public function getDefaultSkin( array $skinNames ) {
1449 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1450 if ( !$skinNames || in_array( $defaultSkin, $skinNames ) ) {
1451 return $defaultSkin;
1452 } else {
1453 return $skinNames[0];
1454 }
1455 }
1456
1457 /**
1458 * Installs the auto-detected extensions.
1459 *
1460 * @return Status
1461 */
1462 protected function includeExtensions() {
1463 global $IP;
1464 $exts = $this->getVar( '_Extensions' );
1465 $IP = $this->getVar( 'IP' );
1466
1467 /**
1468 * We need to include DefaultSettings before including extensions to avoid
1469 * warnings about unset variables. However, the only thing we really
1470 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1471 * if the extension has hidden hook registration in $wgExtensionFunctions,
1472 * but we're not opening that can of worms
1473 * @see https://phabricator.wikimedia.org/T28857
1474 */
1475 global $wgAutoloadClasses;
1476 $wgAutoloadClasses = array();
1477 $queue = array();
1478
1479 require "$IP/includes/DefaultSettings.php";
1480
1481 foreach ( $exts as $e ) {
1482 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1483 $queue["$IP/extensions/$e/extension.json"] = 1;
1484 } else {
1485 require_once "$IP/extensions/$e/$e.php";
1486 }
1487 }
1488
1489 $registry = new ExtensionRegistry();
1490 $data = $registry->readFromQueue( $queue );
1491 $wgAutoloadClasses += $data['autoload'];
1492
1493 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1494 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1495
1496 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1497 $hooksWeWant = array_merge_recursive(
1498 $hooksWeWant,
1499 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1500 );
1501 }
1502 // Unset everyone else's hooks. Lord knows what someone might be doing
1503 // in ParserFirstCallInit (see bug 27171)
1504 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1505
1506 return Status::newGood();
1507 }
1508
1509 /**
1510 * Get an array of install steps. Should always be in the format of
1511 * array(
1512 * 'name' => 'someuniquename',
1513 * 'callback' => array( $obj, 'method' ),
1514 * )
1515 * There must be a config-install-$name message defined per step, which will
1516 * be shown on install.
1517 *
1518 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1519 * @return array
1520 */
1521 protected function getInstallSteps( DatabaseInstaller $installer ) {
1522 $coreInstallSteps = array(
1523 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1524 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1525 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1526 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1527 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1528 array( 'name' => 'updates', 'callback' => array( $installer, 'insertUpdateKeys' ) ),
1529 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1530 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1531 );
1532
1533 // Build the array of install steps starting from the core install list,
1534 // then adding any callbacks that wanted to attach after a given step
1535 foreach ( $coreInstallSteps as $step ) {
1536 $this->installSteps[] = $step;
1537 if ( isset( $this->extraInstallSteps[$step['name']] ) ) {
1538 $this->installSteps = array_merge(
1539 $this->installSteps,
1540 $this->extraInstallSteps[$step['name']]
1541 );
1542 }
1543 }
1544
1545 // Prepend any steps that want to be at the beginning
1546 if ( isset( $this->extraInstallSteps['BEGINNING'] ) ) {
1547 $this->installSteps = array_merge(
1548 $this->extraInstallSteps['BEGINNING'],
1549 $this->installSteps
1550 );
1551 }
1552
1553 // Extensions should always go first, chance to tie into hooks and such
1554 if ( count( $this->getVar( '_Extensions' ) ) ) {
1555 array_unshift( $this->installSteps,
1556 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1557 );
1558 $this->installSteps[] = array(
1559 'name' => 'extension-tables',
1560 'callback' => array( $installer, 'createExtensionTables' )
1561 );
1562 }
1563
1564 return $this->installSteps;
1565 }
1566
1567 /**
1568 * Actually perform the installation.
1569 *
1570 * @param callable $startCB A callback array for the beginning of each step
1571 * @param callable $endCB A callback array for the end of each step
1572 *
1573 * @return array Array of Status objects
1574 */
1575 public function performInstallation( $startCB, $endCB ) {
1576 $installResults = array();
1577 $installer = $this->getDBInstaller();
1578 $installer->preInstall();
1579 $steps = $this->getInstallSteps( $installer );
1580 foreach ( $steps as $stepObj ) {
1581 $name = $stepObj['name'];
1582 call_user_func_array( $startCB, array( $name ) );
1583
1584 // Perform the callback step
1585 $status = call_user_func( $stepObj['callback'], $installer );
1586
1587 // Output and save the results
1588 call_user_func( $endCB, $name, $status );
1589 $installResults[$name] = $status;
1590
1591 // If we've hit some sort of fatal, we need to bail.
1592 // Callback already had a chance to do output above.
1593 if ( !$status->isOk() ) {
1594 break;
1595 }
1596 }
1597 if ( $status->isOk() ) {
1598 $this->setVar( '_InstallDone', true );
1599 }
1600
1601 return $installResults;
1602 }
1603
1604 /**
1605 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1606 *
1607 * @return Status
1608 */
1609 public function generateKeys() {
1610 $keys = array( 'wgSecretKey' => 64 );
1611 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1612 $keys['wgUpgradeKey'] = 16;
1613 }
1614
1615 return $this->doGenerateKeys( $keys );
1616 }
1617
1618 /**
1619 * Generate a secret value for variables using our CryptRand generator.
1620 * Produce a warning if the random source was insecure.
1621 *
1622 * @param array $keys
1623 * @return Status
1624 */
1625 protected function doGenerateKeys( $keys ) {
1626 $status = Status::newGood();
1627
1628 $strong = true;
1629 foreach ( $keys as $name => $length ) {
1630 $secretKey = MWCryptRand::generateHex( $length, true );
1631 if ( !MWCryptRand::wasStrong() ) {
1632 $strong = false;
1633 }
1634
1635 $this->setVar( $name, $secretKey );
1636 }
1637
1638 if ( !$strong ) {
1639 $names = array_keys( $keys );
1640 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1641 global $wgLang;
1642 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1643 }
1644
1645 return $status;
1646 }
1647
1648 /**
1649 * Create the first user account, grant it sysop and bureaucrat rights
1650 *
1651 * @return Status
1652 */
1653 protected function createSysop() {
1654 $name = $this->getVar( '_AdminName' );
1655 $user = User::newFromName( $name );
1656
1657 if ( !$user ) {
1658 // We should've validated this earlier anyway!
1659 return Status::newFatal( 'config-admin-error-user', $name );
1660 }
1661
1662 if ( $user->idForName() == 0 ) {
1663 $user->addToDatabase();
1664
1665 try {
1666 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1667 } catch ( PasswordError $pwe ) {
1668 return Status::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1669 }
1670
1671 $user->addGroup( 'sysop' );
1672 $user->addGroup( 'bureaucrat' );
1673 if ( $this->getVar( '_AdminEmail' ) ) {
1674 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1675 }
1676 $user->saveSettings();
1677
1678 // Update user count
1679 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1680 $ssUpdate->doUpdate();
1681 }
1682 $status = Status::newGood();
1683
1684 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1685 $this->subscribeToMediaWikiAnnounce( $status );
1686 }
1687
1688 return $status;
1689 }
1690
1691 /**
1692 * @param Status $s
1693 */
1694 private function subscribeToMediaWikiAnnounce( Status $s ) {
1695 $params = array(
1696 'email' => $this->getVar( '_AdminEmail' ),
1697 'language' => 'en',
1698 'digest' => 0
1699 );
1700
1701 // Mailman doesn't support as many languages as we do, so check to make
1702 // sure their selected language is available
1703 $myLang = $this->getVar( '_UserLang' );
1704 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages ) ) {
1705 $myLang = $myLang == 'pt-br' ? 'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1706 $params['language'] = $myLang;
1707 }
1708
1709 if ( MWHttpRequest::canMakeRequests() ) {
1710 $res = MWHttpRequest::factory( $this->mediaWikiAnnounceUrl,
1711 array( 'method' => 'POST', 'postData' => $params ), __METHOD__ )->execute();
1712 if ( !$res->isOK() ) {
1713 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1714 }
1715 } else {
1716 $s->warning( 'config-install-subscribe-notpossible' );
1717 }
1718 }
1719
1720 /**
1721 * Insert Main Page with default content.
1722 *
1723 * @param DatabaseInstaller $installer
1724 * @return Status
1725 */
1726 protected function createMainpage( DatabaseInstaller $installer ) {
1727 $status = Status::newGood();
1728 try {
1729 $page = WikiPage::factory( Title::newMainPage() );
1730 $content = new WikitextContent(
1731 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1732 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1733 );
1734
1735 $page->doEditContent( $content,
1736 '',
1737 EDIT_NEW,
1738 false,
1739 User::newFromName( 'MediaWiki default' )
1740 );
1741 } catch ( Exception $e ) {
1742 // using raw, because $wgShowExceptionDetails can not be set yet
1743 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1744 }
1745
1746 return $status;
1747 }
1748
1749 /**
1750 * Override the necessary bits of the config to run an installation.
1751 */
1752 public static function overrideConfig() {
1753 define( 'MW_NO_SESSION', 1 );
1754
1755 // Don't access the database
1756 $GLOBALS['wgUseDatabaseMessages'] = false;
1757 // Don't cache langconv tables
1758 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE;
1759 // Debug-friendly
1760 $GLOBALS['wgShowExceptionDetails'] = true;
1761 // Don't break forms
1762 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1763
1764 // Extended debugging
1765 $GLOBALS['wgShowSQLErrors'] = true;
1766 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1767
1768 // Allow multiple ob_flush() calls
1769 $GLOBALS['wgDisableOutputCompression'] = true;
1770
1771 // Use a sensible cookie prefix (not my_wiki)
1772 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1773
1774 // Some of the environment checks make shell requests, remove limits
1775 $GLOBALS['wgMaxShellMemory'] = 0;
1776 }
1777
1778 /**
1779 * Add an installation step following the given step.
1780 *
1781 * @param callable $callback A valid installation callback array, in this form:
1782 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1783 * @param string $findStep The step to find. Omit to put the step at the beginning
1784 */
1785 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1786 $this->extraInstallSteps[$findStep][] = $callback;
1787 }
1788
1789 /**
1790 * Disable the time limit for execution.
1791 * Some long-running pages (Install, Upgrade) will want to do this
1792 */
1793 protected function disableTimeLimit() {
1794 MediaWiki\suppressWarnings();
1795 set_time_limit( 0 );
1796 MediaWiki\restoreWarnings();
1797 }
1798 }