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