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