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