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