[TASK] Replace TYPO3_OS constant with Environment check
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Utility / CommandUtility.php
1 <?php
2 namespace TYPO3\CMS\Core\Utility;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Core\Core\Environment;
18
19 /**
20 * Class to handle system commands.
21 * finds executables (programs) on Unix and Windows without knowing where they are
22 *
23 * returns exec command for a program
24 * or FALSE
25 *
26 * This class is meant to be used without instance:
27 * $cmd = CommandUtility::getCommand ('awstats','perl');
28 *
29 * The data of this class is cached.
30 * That means if a program is found once it don't have to be searched again.
31 *
32 * user functions:
33 *
34 * addPaths() could be used to extend the search paths
35 * getCommand() get a command string
36 * checkCommand() returns TRUE if a command is available
37 *
38 * Search paths that are included:
39 * $TYPO3_CONF_VARS['GFX']['processor_path_lzw'] or $TYPO3_CONF_VARS['GFX']['processor_path']
40 * $TYPO3_CONF_VARS['SYS']['binPath']
41 * $GLOBALS['_SERVER']['PATH']
42 * '/usr/bin/,/usr/local/bin/' on Unix
43 *
44 * binaries can be preconfigured with
45 * $TYPO3_CONF_VARS['SYS']['binSetup']
46 */
47 class CommandUtility
48 {
49 /**
50 * Tells if object is already initialized
51 *
52 * @var bool
53 */
54 protected static $initialized = false;
55
56 /**
57 * Contains application list. This is an array with the following structure:
58 * - app => file name to the application (like 'tar' or 'bzip2')
59 * - path => full path to the application without application name (like '/usr/bin/' for '/usr/bin/tar')
60 * - valid => TRUE or FALSE
61 * Array key is identical to 'app'.
62 *
63 * @var array
64 */
65 protected static $applications = [];
66
67 /**
68 * Paths where to search for applications
69 *
70 * @var array
71 */
72 protected static $paths = null;
73
74 /**
75 * Wrapper function for php exec function
76 * Needs to be central to have better control and possible fix for issues
77 *
78 * @param string $command
79 * @param array|null $output
80 * @param int $returnValue
81 * @return string
82 */
83 public static function exec($command, &$output = null, &$returnValue = 0)
84 {
85 return exec($command, $output, $returnValue);
86 }
87
88 /**
89 * Compile the command for running ImageMagick/GraphicsMagick.
90 *
91 * @param string $command Command to be run: identify, convert or combine/composite
92 * @param string $parameters The parameters string
93 * @param string $path Override the default path (e.g. used by the install tool)
94 * @return string Compiled command that deals with ImageMagick & GraphicsMagick
95 */
96 public static function imageMagickCommand($command, $parameters, $path = '')
97 {
98 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
99 $isExt = Environment::isWindows() ? '.exe' : '';
100 if (!$path) {
101 $path = $gfxConf['processor_path'];
102 }
103 $path = GeneralUtility::fixWindowsFilePath($path);
104 // This is only used internally, has no effect outside
105 if ($command === 'combine') {
106 $command = 'composite';
107 }
108 // Compile the path & command
109 if ($gfxConf['processor'] === 'GraphicsMagick') {
110 $path = self::escapeShellArgument($path . 'gm' . $isExt) . ' ' . self::escapeShellArgument($command);
111 } else {
112 $path = self::escapeShellArgument($path . $command . $isExt);
113 }
114 // strip profile information for thumbnails and reduce their size
115 if ($parameters && $command !== 'identify') {
116 // Determine whether the strip profile action has be disabled by TypoScript:
117 if ($gfxConf['processor_stripColorProfileByDefault']
118 && $gfxConf['processor_stripColorProfileCommand'] !== ''
119 && strpos($parameters, $gfxConf['processor_stripColorProfileCommand']) === false
120 && $parameters !== '-version'
121 && strpos($parameters, '###SkipStripProfile###') === false
122 ) {
123 $parameters = $gfxConf['processor_stripColorProfileCommand'] . ' ' . $parameters;
124 } else {
125 $parameters = str_replace('###SkipStripProfile###', '', $parameters);
126 }
127 }
128 // set interlace parameter for convert command
129 if ($command !== 'identify' && $gfxConf['processor_interlace']) {
130 $parameters = '-interlace ' . $gfxConf['processor_interlace'] . ' ' . $parameters;
131 }
132 $cmdLine = $path . ' ' . $parameters;
133 // It is needed to change the parameters order when a mask image has been specified
134 if ($command === 'composite') {
135 $paramsArr = GeneralUtility::unQuoteFilenames($parameters);
136 $paramsArrCount = count($paramsArr);
137 if ($paramsArrCount > 5) {
138 $tmp = $paramsArr[$paramsArrCount - 3];
139 $paramsArr[$paramsArrCount - 3] = $paramsArr[$paramsArrCount - 4];
140 $paramsArr[$paramsArrCount - 4] = $tmp;
141 }
142 $cmdLine = $path . ' ' . implode(' ', $paramsArr);
143 }
144 return $cmdLine;
145 }
146
147 /**
148 * Checks if a command is valid or not, updates global variables
149 *
150 * @param string $cmd The command that should be executed. eg: "convert"
151 * @param string $handler Executer for the command. eg: "perl"
152 * @return bool FALSE if cmd is not found, or -1 if the handler is not found
153 */
154 public static function checkCommand($cmd, $handler = '')
155 {
156 if (!self::init()) {
157 return false;
158 }
159
160 if ($handler && !self::checkCommand($handler)) {
161 return -1;
162 }
163 // Already checked and valid
164 if (self::$applications[$cmd]['valid'] ?? false) {
165 return true;
166 }
167 // Is set but was (above) not TRUE
168 if (isset(self::$applications[$cmd]['valid'])) {
169 return false;
170 }
171
172 foreach (self::$paths as $path => $validPath) {
173 // Ignore invalid (FALSE) paths
174 if ($validPath) {
175 if (Environment::isWindows()) {
176 // Windows OS
177 // @todo Why is_executable() is not called here?
178 if (@is_file($path . $cmd)) {
179 self::$applications[$cmd]['app'] = $cmd;
180 self::$applications[$cmd]['path'] = $path;
181 self::$applications[$cmd]['valid'] = true;
182 return true;
183 }
184 if (@is_file($path . $cmd . '.exe')) {
185 self::$applications[$cmd]['app'] = $cmd . '.exe';
186 self::$applications[$cmd]['path'] = $path;
187 self::$applications[$cmd]['valid'] = true;
188 return true;
189 }
190 } else {
191 // Unix-like OS
192 $filePath = realpath($path . $cmd);
193 if ($filePath && @is_executable($filePath)) {
194 self::$applications[$cmd]['app'] = $cmd;
195 self::$applications[$cmd]['path'] = $path;
196 self::$applications[$cmd]['valid'] = true;
197 return true;
198 }
199 }
200 }
201 }
202
203 // Try to get the executable with the command 'which'.
204 // It does the same like already done, but maybe on other paths
205 if (!Environment::isWindows()) {
206 $cmd = @self::exec('which ' . $cmd);
207 if (@is_executable($cmd)) {
208 self::$applications[$cmd]['app'] = $cmd;
209 self::$applications[$cmd]['path'] = dirname($cmd) . '/';
210 self::$applications[$cmd]['valid'] = true;
211 return true;
212 }
213 }
214
215 return false;
216 }
217
218 /**
219 * Returns a command string for exec(), system()
220 *
221 * @param string $cmd The command that should be executed. eg: "convert"
222 * @param string $handler Handler (executor) for the command. eg: "perl"
223 * @param string $handlerOpt Options for the handler, like '-w' for "perl"
224 * @return mixed Returns command string, or FALSE if cmd is not found, or -1 if the handler is not found
225 */
226 public static function getCommand($cmd, $handler = '', $handlerOpt = '')
227 {
228 if (!self::init()) {
229 return false;
230 }
231
232 // Handler
233 if ($handler) {
234 $handler = self::getCommand($handler);
235
236 if (!$handler) {
237 return -1;
238 }
239 $handler .= ' ' . $handlerOpt . ' ';
240 }
241
242 // Command
243 if (!self::checkCommand($cmd)) {
244 return false;
245 }
246 $cmd = self::$applications[$cmd]['path'] . self::$applications[$cmd]['app'] . ' ';
247
248 return trim($handler . $cmd);
249 }
250
251 /**
252 * Extend the preset paths. This way an extension can install an executable and provide the path to \TYPO3\CMS\Core\Utility\CommandUtility
253 *
254 * @param string $paths Comma separated list of extra paths where a command should be searched. Relative paths (without leading "/") are prepend with site root path (PATH_site).
255 */
256 public static function addPaths($paths)
257 {
258 self::initPaths($paths);
259 }
260
261 /**
262 * Returns an array of search paths
263 *
264 * @param bool $addInvalid If set the array contains invalid path too. Then the key is the path and the value is empty
265 * @return array Array of search paths (empty if exec is disabled)
266 */
267 public static function getPaths($addInvalid = false)
268 {
269 if (!self::init()) {
270 return [];
271 }
272
273 $paths = self::$paths;
274
275 if (!$addInvalid) {
276 foreach ($paths as $path => $validPath) {
277 if (!$validPath) {
278 unset($paths[$path]);
279 }
280 }
281 }
282 return $paths;
283 }
284
285 /**
286 * Initializes this class
287 *
288 * @return bool
289 */
290 protected static function init()
291 {
292 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['disable_exec_function']) {
293 return false;
294 }
295 if (!self::$initialized) {
296 self::initPaths();
297 self::$applications = self::getConfiguredApps();
298 self::$initialized = true;
299 }
300 return true;
301 }
302
303 /**
304 * Initializes and extends the preset paths with own
305 *
306 * @param string $paths Comma separated list of extra paths where a command should be searched. Relative paths (without leading "/") are prepend with site root path (PATH_site).
307 */
308 protected static function initPaths($paths = '')
309 {
310 $doCheck = false;
311
312 // Init global paths array if not already done
313 if (!is_array(self::$paths)) {
314 self::$paths = self::getPathsInternal();
315 $doCheck = true;
316 }
317 // Merge the submitted paths array to the global
318 if ($paths) {
319 $paths = GeneralUtility::trimExplode(',', $paths, true);
320 if (is_array($paths)) {
321 foreach ($paths as $path) {
322 // Make absolute path of relative
323 if (!preg_match('#^/#', $path)) {
324 $path = PATH_site . $path;
325 }
326 if (!isset(self::$paths[$path])) {
327 if (@is_dir($path)) {
328 self::$paths[$path] = $path;
329 } else {
330 self::$paths[$path] = false;
331 }
332 }
333 }
334 }
335 }
336 // Check if new paths are invalid
337 if ($doCheck) {
338 foreach (self::$paths as $path => $valid) {
339 // Ignore invalid (FALSE) paths
340 if ($valid && !@is_dir($path)) {
341 self::$paths[$path] = false;
342 }
343 }
344 }
345 }
346
347 /**
348 * Processes and returns the paths from $GLOBALS['TYPO3_CONF_VARS']['SYS']['binSetup']
349 *
350 * @return array Array of commands and path
351 */
352 protected static function getConfiguredApps()
353 {
354 $cmdArr = [];
355
356 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['binSetup']) {
357 $binSetup = str_replace(['\'.chr(10).\'', '\' . LF . \''], LF, $GLOBALS['TYPO3_CONF_VARS']['SYS']['binSetup']);
358 $pathSetup = preg_split('/[\n,]+/', $binSetup);
359 foreach ($pathSetup as $val) {
360 if (trim($val) === '') {
361 continue;
362 }
363 list($cmd, $cmdPath) = GeneralUtility::trimExplode('=', $val, true, 2);
364 $cmdArr[$cmd]['app'] = basename($cmdPath);
365 $cmdArr[$cmd]['path'] = dirname($cmdPath) . '/';
366 $cmdArr[$cmd]['valid'] = true;
367 }
368 }
369
370 return $cmdArr;
371 }
372
373 /**
374 * Sets the search paths from different sources, internal
375 *
376 * @return array Array of absolute paths (keys and values are equal)
377 */
378 protected static function getPathsInternal()
379 {
380 $pathsArr = [];
381 $sysPathArr = [];
382
383 // Image magick paths first
384 // processor_path_lzw take precedence over processor_path
385 if ($imPath = $GLOBALS['TYPO3_CONF_VARS']['GFX']['processor_path_lzw'] ?: $GLOBALS['TYPO3_CONF_VARS']['GFX']['processor_path']) {
386 $imPath = self::fixPath($imPath);
387 $pathsArr[$imPath] = $imPath;
388 }
389
390 // Add configured paths
391 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['binPath']) {
392 $sysPath = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['SYS']['binPath'], true);
393 foreach ($sysPath as $val) {
394 $val = self::fixPath($val);
395 $sysPathArr[$val] = $val;
396 }
397 }
398
399 // Add path from environment
400 if (!empty($GLOBALS['_SERVER']['PATH']) || !empty($GLOBALS['_SERVER']['Path'])) {
401 $sep = Environment::isWindows() ? ';' : ':';
402 $serverPath = $GLOBALS['_SERVER']['PATH'] ?? $GLOBALS['_SERVER']['Path'];
403 $envPath = GeneralUtility::trimExplode($sep, $serverPath, true);
404 foreach ($envPath as $val) {
405 $val = self::fixPath($val);
406 $sysPathArr[$val] = $val;
407 }
408 }
409
410 // Set common paths for Unix (only)
411 if (!Environment::isWindows()) {
412 $sysPathArr = array_merge($sysPathArr, [
413 '/usr/bin/' => '/usr/bin/',
414 '/usr/local/bin/' => '/usr/local/bin/',
415 ]);
416 }
417
418 $pathsArr = array_merge($pathsArr, $sysPathArr);
419
420 return $pathsArr;
421 }
422
423 /**
424 * Set a path to the right format
425 *
426 * @param string $path Input path
427 * @return string Output path
428 */
429 protected static function fixPath($path)
430 {
431 return str_replace('//', '/', $path . '/');
432 }
433
434 /**
435 * Escape shell arguments (for example filenames) to be used on the local system.
436 *
437 * The setting UTF8filesystem will be taken into account.
438 *
439 * @param string[] $input Input arguments to be escaped
440 * @return string[] Escaped shell arguments
441 */
442 public static function escapeShellArguments(array $input)
443 {
444 $isUTF8Filesystem = !empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']);
445 $currentLocale = false;
446 if ($isUTF8Filesystem) {
447 $currentLocale = setlocale(LC_CTYPE, 0);
448 setlocale(LC_CTYPE, $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLocale']);
449 }
450
451 $output = array_map('escapeshellarg', $input);
452
453 if ($isUTF8Filesystem && $currentLocale !== false) {
454 setlocale(LC_CTYPE, $currentLocale);
455 }
456
457 return $output;
458 }
459
460 /**
461 * Escape a shell argument (for example a filename) to be used on the local system.
462 *
463 * The setting UTF8filesystem will be taken into account.
464 *
465 * @param string $input Input-argument to be escaped
466 * @return string Escaped shell argument
467 */
468 public static function escapeShellArgument($input)
469 {
470 return self::escapeShellArguments([$input])[0];
471 }
472 }