08763fdc77664e86ebdd3c231d99da16590220a7
[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 /**
27 * TODO: make protected?
28 *
29 * @var array
30 */
31 public $settings;
32
33 /**
34 * Cached DB installer instances, access using getDBInstaller().
35 *
36 * @var array
37 */
38 protected $dbInstallers = array();
39
40 /**
41 * Minimum memory size in MB.
42 *
43 * @var integer
44 */
45 protected $minMemorySize = 50;
46
47 /**
48 * Cached Title, used by parse().
49 *
50 * @var Title
51 */
52 protected $parserTitle;
53
54 /**
55 * Cached ParserOptions, used by parse().
56 *
57 * @var ParserOptions
58 */
59 protected $parserOptions;
60
61 /**
62 * Known database types. These correspond to the class names <type>Installer,
63 * and are also MediaWiki database types valid for $wgDBtype.
64 *
65 * To add a new type, create a <type>Installer class and a Database<type>
66 * class, and add a config-type-<type> message to MessagesEn.php.
67 *
68 * @var array
69 */
70 protected static $dbTypes = array(
71 'mysql',
72 'postgres',
73 'oracle',
74 'sqlite',
75 );
76
77 /**
78 * A list of environment check methods called by doEnvironmentChecks().
79 * These may output warnings using showMessage(), and/or abort the
80 * installation process by returning false.
81 *
82 * @var array
83 */
84 protected $envChecks = array(
85 'envCheckDB',
86 'envCheckRegisterGlobals',
87 'envCheckBrokenXML',
88 'envCheckPHP531',
89 'envCheckMagicQuotes',
90 'envCheckMagicSybase',
91 'envCheckMbstring',
92 'envCheckZE1',
93 'envCheckSafeMode',
94 'envCheckXML',
95 'envCheckPCRE',
96 'envCheckMemory',
97 'envCheckCache',
98 'envCheckDiff3',
99 'envCheckGraphics',
100 'envCheckPath',
101 'envCheckExtension',
102 'envCheckShellLocale',
103 'envCheckUploadsDirectory',
104 'envCheckLibicu'
105 );
106
107 /**
108 * UI interface for displaying a short message
109 * The parameters are like parameters to wfMsg().
110 * The messages will be in wikitext format, which will be converted to an
111 * output format such as HTML or text before being sent to the user.
112 */
113 public abstract function showMessage( $msg /*, ... */ );
114
115 /**
116 * Constructor, always call this from child classes.
117 */
118 public function __construct() {
119 // Disable the i18n cache and LoadBalancer
120 Language::getLocalisationCache()->disableBackend();
121 LBFactory::disableBackend();
122 }
123
124 /**
125 * Get a list of known DB types.
126 */
127 public static function getDBTypes() {
128 return self::$dbTypes;
129 }
130
131 /**
132 * Do initial checks of the PHP environment. Set variables according to
133 * the observed environment.
134 *
135 * It's possible that this may be called under the CLI SAPI, not the SAPI
136 * that the wiki will primarily run under. In that case, the subclass should
137 * initialise variables such as wgScriptPath, before calling this function.
138 *
139 * Under the web subclass, it can already be assumed that PHP 5+ is in use
140 * and that sessions are working.
141 *
142 * @return boolean
143 */
144 public function doEnvironmentChecks() {
145 $good = true;
146
147 foreach ( $this->envChecks as $check ) {
148 $status = $this->$check();
149 if ( $status === false ) {
150 $good = false;
151 }
152 }
153
154 $this->setVar( '_Environment', $good );
155
156 if ( $good ) {
157 $this->showMessage( 'config-env-good' );
158 } else {
159 $this->showMessage( 'config-env-bad' );
160 }
161
162 return $good;
163 }
164
165 /**
166 * Set a MW configuration variable, or internal installer configuration variable.
167 *
168 * @param $name String
169 * @param $value Mixed
170 */
171 public function setVar( $name, $value ) {
172 $this->settings[$name] = $value;
173 }
174
175 /**
176 * Get an MW configuration variable, or internal installer configuration variable.
177 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
178 * Installer variables are typically prefixed by an underscore.
179 *
180 * @param $name String
181 * @param $default Mixed
182 *
183 * @return mixed
184 */
185 public function getVar( $name, $default = null ) {
186 if ( !isset( $this->settings[$name] ) ) {
187 return $default;
188 } else {
189 return $this->settings[$name];
190 }
191 }
192
193 /**
194 * Get an instance of DatabaseInstaller for the specified DB type.
195 *
196 * @param $type Mixed: DB installer for which is needed, false to use default.
197 *
198 * @return DatabaseInstaller
199 */
200 public function getDBInstaller( $type = false ) {
201 if ( !$type ) {
202 $type = $this->getVar( 'wgDBtype' );
203 }
204
205 $type = strtolower( $type );
206
207 if ( !isset( $this->dbInstallers[$type] ) ) {
208 $class = ucfirst( $type ). 'Installer';
209 $this->dbInstallers[$type] = new $class( $this );
210 }
211
212 return $this->dbInstallers[$type];
213 }
214
215 /**
216 * Determine if LocalSettings.php exists. If it does, return its variables,
217 * merged with those from AdminSettings.php, as an array.
218 *
219 * @return Array
220 */
221 public function getExistingLocalSettings() {
222 global $IP;
223
224 wfSuppressWarnings();
225 $_lsExists = file_exists( "$IP/LocalSettings.php" );
226 wfRestoreWarnings();
227
228 if( !$_lsExists ) {
229 return false;
230 }
231 unset($_lsExists);
232
233 require( "$IP/includes/DefaultSettings.php" );
234 require( "$IP/LocalSettings.php" );
235 if ( file_exists( "$IP/AdminSettings.php" ) ) {
236 require( "$IP/AdminSettings.php" );
237 }
238 return get_defined_vars();
239 }
240
241 /**
242 * Get a fake password for sending back to the user in HTML.
243 * This is a security mechanism to avoid compromise of the password in the
244 * event of session ID compromise.
245 *
246 * @param $realPassword String
247 *
248 * @return string
249 */
250 public function getFakePassword( $realPassword ) {
251 return str_repeat( '*', strlen( $realPassword ) );
252 }
253
254 /**
255 * Set a variable which stores a password, except if the new value is a
256 * fake password in which case leave it as it is.
257 *
258 * @param $name String
259 * @param $value Mixed
260 */
261 public function setPassword( $name, $value ) {
262 if ( !preg_match( '/^\*+$/', $value ) ) {
263 $this->setVar( $name, $value );
264 }
265 }
266
267 /**
268 * On POSIX systems return the primary group of the webserver we're running under.
269 * On other systems just returns null.
270 *
271 * This is used to advice the user that he should chgrp his config/data/images directory as the
272 * webserver user before he can install.
273 *
274 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
275 *
276 * @return mixed
277 */
278 public static function maybeGetWebserverPrimaryGroup() {
279 if ( !function_exists( 'posix_getegid' ) || !function_exists( 'posix_getpwuid' ) ) {
280 # I don't know this, this isn't UNIX.
281 return null;
282 }
283
284 # posix_getegid() *not* getmygid() because we want the group of the webserver,
285 # not whoever owns the current script.
286 $gid = posix_getegid();
287 $getpwuid = posix_getpwuid( $gid );
288 $group = $getpwuid['name'];
289
290 return $group;
291 }
292
293 /**
294 * Convert wikitext $text to HTML.
295 *
296 * This is potentially error prone since many parser features require a complete
297 * installed MW database. The solution is to just not use those features when you
298 * write your messages. This appears to work well enough. Basic formatting and
299 * external links work just fine.
300 *
301 * But in case a translator decides to throw in a #ifexist or internal link or
302 * whatever, this function is guarded to catch the attempted DB access and to present
303 * some fallback text.
304 *
305 * @param $text String
306 * @param $lineStart Boolean
307 * @return String
308 */
309 public function parse( $text, $lineStart = false ) {
310 global $wgParser;
311
312 try {
313 $out = $wgParser->parse( $text, $this->parserTitle, $this->parserOptions, $lineStart );
314 $html = $out->getText();
315 } catch ( DBAccessError $e ) {
316 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
317
318 if ( !empty( $this->debug ) ) {
319 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
320 }
321 }
322
323 return $html;
324 }
325
326 public function getParserOptions() {
327 return $this->parserOptions;
328 }
329
330 public function disableLinkPopups() {
331 $this->parserOptions->setExternalLinkTarget( false );
332 }
333
334 public function restoreLinkPopups() {
335 global $wgExternalLinkTarget;
336 $this->parserOptions->setExternalLinkTarget( $wgExternalLinkTarget );
337 }
338
339 /**
340 * TODO: document
341 *
342 * @param $installer DatabaseInstaller
343 *
344 * @return Status
345 */
346 public function installTables( DatabaseInstaller &$installer ) {
347 $status = $installer->createTables();
348
349 if( $status->isOK() ) {
350 LBFactory::enableBackend();
351 }
352
353 return $status;
354 }
355
356 /**
357 * Exports all wg* variables stored by the installer into global scope.
358 */
359 public function exportVars() {
360 foreach ( $this->settings as $name => $value ) {
361 if ( substr( $name, 0, 2 ) == 'wg' ) {
362 $GLOBALS[$name] = $value;
363 }
364 }
365 }
366
367 /**
368 * Environment check for DB types.
369 */
370 protected function envCheckDB() {
371 global $wgLang;
372
373 $compiledDBs = array();
374 $goodNames = array();
375 $allNames = array();
376
377 foreach ( self::getDBTypes() as $name ) {
378 $db = $this->getDBInstaller( $name );
379 $readableName = wfMsg( 'config-type-' . $name );
380
381 if ( $db->isCompiled() ) {
382 $compiledDBs[] = $name;
383 $goodNames[] = $readableName;
384 }
385
386 $allNames[] = $readableName;
387 }
388
389 $this->setVar( '_CompiledDBs', $compiledDBs );
390
391 if ( !$compiledDBs ) {
392 $this->showMessage( 'config-no-db' );
393 // FIXME: this only works for the web installer!
394 $this->showHelpBox( 'config-no-db-help', $wgLang->commaList( $allNames ) );
395 return false;
396 }
397
398 // Check for FTS3 full-text search module
399 $sqlite = $this->getDBInstaller( 'sqlite' );
400 if ( $sqlite->isCompiled() ) {
401 $db = new DatabaseSqliteStandalone( ':memory:' );
402 if( $db->getFulltextSearchModule() != 'FTS3' ) {
403 $this->showMessage( 'config-no-fts3' );
404 }
405 }
406 }
407
408 /**
409 * Environment check for register_globals.
410 */
411 protected function envCheckRegisterGlobals() {
412 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
413 $this->showMessage( 'config-register-globals' );
414 }
415 }
416
417 /**
418 * Some versions of libxml+PHP break < and > encoding horribly
419 */
420 protected function envCheckBrokenXML() {
421 $test = new PhpXmlBugTester();
422 if ( !$test->ok ) {
423 $this->showMessage( 'config-brokenlibxml' );
424 return false;
425 }
426 }
427
428 /**
429 * Test PHP (probably 5.3.1, but it could regress again) to make sure that
430 * reference parameters to __call() are not converted to null
431 */
432 protected function envCheckPHP531() {
433 $test = new PhpRefCallBugTester;
434 $test->execute();
435 if ( !$test->ok ) {
436 $this->showMessage( 'config-using531' );
437 return false;
438 }
439 }
440
441 /**
442 * Environment check for magic_quotes_runtime.
443 */
444 protected function envCheckMagicQuotes() {
445 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
446 $this->showMessage( 'config-magic-quotes-runtime' );
447 return false;
448 }
449 }
450
451 /**
452 * Environment check for magic_quotes_sybase.
453 */
454 protected function envCheckMagicSybase() {
455 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
456 $this->showMessage( 'config-magic-quotes-sybase' );
457 return false;
458 }
459 }
460
461 /**
462 * Environment check for mbstring.func_overload.
463 */
464 protected function envCheckMbstring() {
465 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
466 $this->showMessage( 'config-mbstring' );
467 return false;
468 }
469 }
470
471 /**
472 * Environment check for zend.ze1_compatibility_mode.
473 */
474 protected function envCheckZE1() {
475 if ( wfIniGetBool( 'zend.ze1_compatibility_mode' ) ) {
476 $this->showMessage( 'config-ze1' );
477 return false;
478 }
479 }
480
481 /**
482 * Environment check for safe_mode.
483 */
484 protected function envCheckSafeMode() {
485 if ( wfIniGetBool( 'safe_mode' ) ) {
486 $this->setVar( '_SafeMode', true );
487 $this->showMessage( 'config-safe-mode' );
488 }
489 }
490
491 /**
492 * Environment check for the XML module.
493 */
494 protected function envCheckXML() {
495 if ( !function_exists( "utf8_encode" ) ) {
496 $this->showMessage( 'config-xml-bad' );
497 return false;
498 }
499 }
500
501 /**
502 * Environment check for the PCRE module.
503 */
504 protected function envCheckPCRE() {
505 if ( !function_exists( 'preg_match' ) ) {
506 $this->showMessage( 'config-pcre' );
507 return false;
508 }
509 wfSuppressWarnings();
510 $regexd = preg_replace( '/[\x{0400}-\x{04FF}]/u', '', '-АБВГД-' );
511 wfRestoreWarnings();
512 if ( $regexd != '--' ) {
513 $this->showMessage( 'config-pcre-no-utf8' );
514 return false;
515 }
516 }
517
518 /**
519 * Environment check for available memory.
520 */
521 protected function envCheckMemory() {
522 $limit = ini_get( 'memory_limit' );
523
524 if ( !$limit || $limit == -1 ) {
525 return true;
526 }
527
528 $n = intval( $limit );
529
530 if( preg_match( '/^([0-9]+)[Mm]$/', trim( $limit ), $m ) ) {
531 $n = intval( $m[1] * ( 1024 * 1024 ) );
532 }
533
534 if( $n < $this->minMemorySize * 1024 * 1024 ) {
535 $newLimit = "{$this->minMemorySize}M";
536
537 if( ini_set( "memory_limit", $newLimit ) === false ) {
538 $this->showMessage( 'config-memory-bad', $limit );
539 } else {
540 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
541 $this->setVar( '_RaiseMemory', true );
542 }
543 } else {
544 return true;
545 }
546 }
547
548 /**
549 * Environment check for compiled object cache types.
550 */
551 protected function envCheckCache() {
552 $caches = array();
553 foreach ( $this->objectCaches as $name => $function ) {
554 if ( function_exists( $function ) ) {
555 $caches[$name] = true;
556 }
557 }
558
559 if ( !$caches ) {
560 $this->showMessage( 'config-no-cache' );
561 }
562
563 $this->setVar( '_Caches', $caches );
564 }
565
566 /**
567 * Search for GNU diff3.
568 */
569 protected function envCheckDiff3() {
570 $names = array( "gdiff3", "diff3", "diff3.exe" );
571 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
572
573 $diff3 = self::locateExecutableInDefaultPaths( $names, $versionInfo );
574
575 if ( $diff3 ) {
576 $this->setVar( 'wgDiff3', $diff3 );
577 } else {
578 $this->setVar( 'wgDiff3', false );
579 $this->showMessage( 'config-diff3-bad' );
580 }
581 }
582
583 /**
584 * Environment check for ImageMagick and GD.
585 */
586 protected function envCheckGraphics() {
587 $names = array( wfIsWindows() ? 'convert.exe' : 'convert' );
588 $convert = self::locateExecutableInDefaultPaths( $names, array( '$1 -version', 'ImageMagick' ) );
589
590 if ( $convert ) {
591 $this->setVar( 'wgImageMagickConvertCommand', $convert );
592 $this->showMessage( 'config-imagemagick', $convert );
593 return true;
594 } elseif ( function_exists( 'imagejpeg' ) ) {
595 $this->showMessage( 'config-gd' );
596 return true;
597 } else {
598 $this->showMessage( 'no-scaling' );
599 }
600 }
601
602 /**
603 * Environment check for setting $IP and $wgScriptPath.
604 */
605 protected function envCheckPath() {
606 global $IP;
607 $IP = dirname( dirname( dirname( __FILE__ ) ) );
608
609 $this->setVar( 'IP', $IP );
610
611 // PHP_SELF isn't available sometimes, such as when PHP is CGI but
612 // cgi.fix_pathinfo is disabled. In that case, fall back to SCRIPT_NAME
613 // to get the path to the current script... hopefully it's reliable. SIGH
614 if ( !empty( $_SERVER['PHP_SELF'] ) ) {
615 $path = $_SERVER['PHP_SELF'];
616 } elseif ( !empty( $_SERVER['SCRIPT_NAME'] ) ) {
617 $path = $_SERVER['SCRIPT_NAME'];
618 } elseif ( $this->getVar( 'wgScriptPath' ) ) {
619 // Some kind soul has set it for us already (e.g. debconf)
620 return true;
621 } else {
622 $this->showMessage( 'config-no-uri' );
623 return false;
624 }
625
626 $uri = preg_replace( '{^(.*)/config.*$}', '$1', $path );
627 $this->setVar( 'wgScriptPath', $uri );
628 }
629
630 /**
631 * Environment check for setting the preferred PHP file extension.
632 */
633 protected function envCheckExtension() {
634 // FIXME: detect this properly
635 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
636 $ext = 'php5';
637 } else {
638 $ext = 'php';
639 }
640 $this->setVar( 'wgScriptExtension', ".$ext" );
641 }
642
643 /**
644 * TODO: document
645 */
646 protected function envCheckShellLocale() {
647 $os = php_uname( 's' );
648 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
649
650 if ( !in_array( $os, $supported ) ) {
651 return true;
652 }
653
654 # Get a list of available locales.
655 $ret = false;
656 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
657
658 if ( $ret ) {
659 return true;
660 }
661
662 $lines = wfArrayMap( 'trim', explode( "\n", $lines ) );
663 $candidatesByLocale = array();
664 $candidatesByLang = array();
665
666 foreach ( $lines as $line ) {
667 if ( $line === '' ) {
668 continue;
669 }
670
671 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
672 continue;
673 }
674
675 list( $all, $lang, $territory, $charset, $modifier ) = $m;
676
677 $candidatesByLocale[$m[0]] = $m;
678 $candidatesByLang[$lang][] = $m;
679 }
680
681 # Try the current value of LANG.
682 if ( isset( $candidatesByLocale[ getenv( 'LANG' ) ] ) ) {
683 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
684 return true;
685 }
686
687 # Try the most common ones.
688 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
689 foreach ( $commonLocales as $commonLocale ) {
690 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
691 $this->setVar( 'wgShellLocale', $commonLocale );
692 return true;
693 }
694 }
695
696 # Is there an available locale in the Wiki's language?
697 $wikiLang = $this->getVar( 'wgLanguageCode' );
698
699 if ( isset( $candidatesByLang[$wikiLang] ) ) {
700 $m = reset( $candidatesByLang[$wikiLang] );
701 $this->setVar( 'wgShellLocale', $m[0] );
702 return true;
703 }
704
705 # Are there any at all?
706 if ( count( $candidatesByLocale ) ) {
707 $m = reset( $candidatesByLocale );
708 $this->setVar( 'wgShellLocale', $m[0] );
709 return true;
710 }
711
712 # Give up.
713 return true;
714 }
715
716 /**
717 * TODO: document
718 */
719 protected function envCheckUploadsDirectory() {
720 global $IP, $wgServer;
721
722 $dir = $IP . '/images/';
723 $url = $wgServer . $this->getVar( 'wgScriptPath' ) . '/images/';
724 $safe = !$this->dirIsExecutable( $dir, $url );
725
726 if ( $safe ) {
727 return true;
728 } else {
729 $this->showMessage( 'config-uploads-not-safe', $dir );
730 }
731 }
732
733 /**
734 * Convert a hex string representing a Unicode code point to that code point.
735 * @param $c String
736 * @return string
737 */
738 protected function unicodeChar( $c ) {
739 $c = hexdec($c);
740 if ($c <= 0x7F) {
741 return chr($c);
742 } else if ($c <= 0x7FF) {
743 return chr(0xC0 | $c >> 6) . chr(0x80 | $c & 0x3F);
744 } else if ($c <= 0xFFFF) {
745 return chr(0xE0 | $c >> 12) . chr(0x80 | $c >> 6 & 0x3F)
746 . chr(0x80 | $c & 0x3F);
747 } else if ($c <= 0x10FFFF) {
748 return chr(0xF0 | $c >> 18) . chr(0x80 | $c >> 12 & 0x3F)
749 . chr(0x80 | $c >> 6 & 0x3F)
750 . chr(0x80 | $c & 0x3F);
751 } else {
752 return false;
753 }
754 }
755
756
757 /**
758 * Check the libicu version
759 */
760 protected function envCheckLibicu() {
761 $utf8 = function_exists( 'utf8_normalize' );
762 $intl = function_exists( 'normalizer_normalize' );
763
764 /**
765 * This needs to be updated something that the latest libicu
766 * will properly normalize. This normalization was found at
767 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
768 * Note that we use the hex representation to create the code
769 * points in order to avoid any Unicode-destroying during transit.
770 */
771 $not_normal_c = $this->unicodeChar("FA6C");
772 $normal_c = $this->unicodeChar("242EE");
773
774 $useNormalizer = 'php';
775 $needsUpdate = false;
776
777 /**
778 * We're going to prefer the pecl extension here unless
779 * utf8_normalize is more up to date.
780 */
781 if( $utf8 ) {
782 $useNormalizer = 'utf8';
783 $utf8 = utf8_normalize( $not_normal_c, UNORM_NFC );
784 if ( $utf8 !== $normal_c ) $needsUpdate = true;
785 }
786 if( $intl ) {
787 $useNormalizer = 'intl';
788 $intl = normalizer_normalize( $not_normal_c, Normalizer::FORM_C );
789 if ( $intl !== $normal_c ) $needsUpdate = true;
790 }
791
792 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8', 'config-unicode-using-intl'
793 if( $useNormalizer === 'php' ) {
794 $this->showMessage( 'config-unicode-pure-php-warning' );
795 } else {
796 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
797 if( $needsUpdate ) {
798 $this->showMessage( 'config-unicode-update-warning' );
799 }
800 }
801 }
802
803 /**
804 * Get an array of likely places we can find executables. Check a bunch
805 * of known Unix-like defaults, as well as the PATH environment variable
806 * (which should maybe make it work for Windows?)
807 *
808 * @return Array
809 */
810 protected static function getPossibleBinPaths() {
811 return array_merge(
812 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
813 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
814 explode( PATH_SEPARATOR, getenv( 'PATH' ) )
815 );
816 }
817
818 /**
819 * Search a path for any of the given executable names. Returns the
820 * executable name if found. Also checks the version string returned
821 * by each executable.
822 *
823 * Used only by environment checks.
824 *
825 * @param $path String: path to search
826 * @param $names Array of executable names
827 * @param $versionInfo Boolean false or array with two members:
828 * 0 => Command to run for version check, with $1 for the full executable name
829 * 1 => String to compare the output with
830 *
831 * If $versionInfo is not false, only executables with a version
832 * matching $versionInfo[1] will be returned.
833 */
834 public static function locateExecutable( $path, $names, $versionInfo = false ) {
835 if ( !is_array( $names ) ) {
836 $names = array( $names );
837 }
838
839 foreach ( $names as $name ) {
840 $command = $path . DIRECTORY_SEPARATOR . $name;
841
842 wfSuppressWarnings();
843 $file_exists = file_exists( $command );
844 wfRestoreWarnings();
845
846 if ( $file_exists ) {
847 if ( !$versionInfo ) {
848 return $command;
849 }
850
851 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
852 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
853 return $command;
854 }
855 }
856 }
857 return false;
858 }
859
860 /**
861 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
862 * @see locateExecutable()
863 */
864 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
865 foreach( self::getPossibleBinPaths() as $path ) {
866 $exe = self::locateExecutable( $path, $names, $versionInfo );
867 if( $exe !== false ) {
868 return $exe;
869 }
870 }
871 return false;
872 }
873
874 /**
875 * Checks if scripts located in the given directory can be executed via the given URL.
876 *
877 * Used only by environment checks.
878 */
879 public function dirIsExecutable( $dir, $url ) {
880 $scriptTypes = array(
881 'php' => array(
882 "<?php echo 'ex' . 'ec';",
883 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
884 ),
885 );
886
887 // it would be good to check other popular languages here, but it'll be slow.
888
889 wfSuppressWarnings();
890
891 foreach ( $scriptTypes as $ext => $contents ) {
892 foreach ( $contents as $source ) {
893 $file = 'exectest.' . $ext;
894
895 if ( !file_put_contents( $dir . $file, $source ) ) {
896 break;
897 }
898
899 $text = Http::get( $url . $file );
900 unlink( $dir . $file );
901
902 if ( $text == 'exec' ) {
903 wfRestoreWarnings();
904 return $ext;
905 }
906 }
907 }
908
909 wfRestoreWarnings();
910
911 return false;
912 }
913
914 }