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