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