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