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