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