[CLEANUP] Ensure variables initalized and fix code smell
[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 null|array $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 $cmdLine = $path . ' ' . $parameters;
126 // It is needed to change the parameters order when a mask image has been specified
127 if ($command === 'composite') {
128 $paramsArr = GeneralUtility::unQuoteFilenames($parameters);
129 $paramsArrCount = count($paramsArr);
130 if ($paramsArrCount > 5) {
131 $tmp = $paramsArr[$paramsArrCount - 3];
132 $paramsArr[$paramsArrCount - 3] = $paramsArr[$paramsArrCount - 4];
133 $paramsArr[$paramsArrCount - 4] = $tmp;
134 }
135 $cmdLine = $path . ' ' . implode(' ', $paramsArr);
136 }
137 return $cmdLine;
138 }
139
140 /**
141 * Checks if a command is valid or not, updates global variables
142 *
143 * @param string $cmd The command that should be executed. eg: "convert"
144 * @param string $handler Executer for the command. eg: "perl"
145 * @return bool FALSE if cmd is not found, or -1 if the handler is not found
146 */
147 public static function checkCommand($cmd, $handler = '')
148 {
149 if (!self::init()) {
150 return false;
151 }
152
153 if ($handler && !self::checkCommand($handler)) {
154 return -1;
155 }
156 // Already checked and valid
157 if (self::$applications[$cmd]['valid']) {
158 return true;
159 }
160 // Is set but was (above) not TRUE
161 if (isset(self::$applications[$cmd]['valid'])) {
162 return false;
163 }
164
165 foreach (self::$paths as $path => $validPath) {
166 // Ignore invalid (FALSE) paths
167 if ($validPath) {
168 if (TYPO3_OS === 'WIN') {
169 // Windows OS
170 // @todo Why is_executable() is not called here?
171 if (@is_file($path . $cmd)) {
172 self::$applications[$cmd]['app'] = $cmd;
173 self::$applications[$cmd]['path'] = $path;
174 self::$applications[$cmd]['valid'] = true;
175 return true;
176 }
177 if (@is_file($path . $cmd . '.exe')) {
178 self::$applications[$cmd]['app'] = $cmd . '.exe';
179 self::$applications[$cmd]['path'] = $path;
180 self::$applications[$cmd]['valid'] = true;
181 return true;
182 }
183 } else {
184 // Unix-like OS
185 $filePath = realpath($path . $cmd);
186 if ($filePath && @is_executable($filePath)) {
187 self::$applications[$cmd]['app'] = $cmd;
188 self::$applications[$cmd]['path'] = $path;
189 self::$applications[$cmd]['valid'] = true;
190 return true;
191 }
192 }
193 }
194 }
195
196 // Try to get the executable with the command 'which'.
197 // It does the same like already done, but maybe on other paths
198 if (TYPO3_OS !== 'WIN') {
199 $cmd = @self::exec('which ' . $cmd);
200 if (@is_executable($cmd)) {
201 self::$applications[$cmd]['app'] = $cmd;
202 self::$applications[$cmd]['path'] = dirname($cmd) . '/';
203 self::$applications[$cmd]['valid'] = true;
204 return true;
205 }
206 }
207
208 return false;
209 }
210
211 /**
212 * Returns a command string for exec(), system()
213 *
214 * @param string $cmd The command that should be executed. eg: "convert"
215 * @param string $handler Handler (executor) for the command. eg: "perl"
216 * @param string $handlerOpt Options for the handler, like '-w' for "perl"
217 * @return mixed Returns command string, or FALSE if cmd is not found, or -1 if the handler is not found
218 */
219 public static function getCommand($cmd, $handler = '', $handlerOpt = '')
220 {
221 if (!self::init()) {
222 return false;
223 }
224
225 // Handler
226 if ($handler) {
227 $handler = self::getCommand($handler);
228
229 if (!$handler) {
230 return -1;
231 }
232 $handler .= ' ' . $handlerOpt . ' ';
233 }
234
235 // Command
236 if (!self::checkCommand($cmd)) {
237 return false;
238 }
239 $cmd = self::$applications[$cmd]['path'] . self::$applications[$cmd]['app'] . ' ';
240
241 return trim($handler . $cmd);
242 }
243
244 /**
245 * Extend the preset paths. This way an extension can install an executable and provide the path to \TYPO3\CMS\Core\Utility\CommandUtility
246 *
247 * @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).
248 * @return void
249 */
250 public static function addPaths($paths)
251 {
252 self::initPaths($paths);
253 }
254
255 /**
256 * Returns an array of search paths
257 *
258 * @param bool $addInvalid If set the array contains invalid path too. Then the key is the path and the value is empty
259 * @return array Array of search paths (empty if exec is disabled)
260 */
261 public static function getPaths($addInvalid = false)
262 {
263 if (!self::init()) {
264 return [];
265 }
266
267 $paths = self::$paths;
268
269 if (!$addInvalid) {
270 foreach ($paths as $path => $validPath) {
271 if (!$validPath) {
272 unset($paths[$path]);
273 }
274 }
275 }
276 return $paths;
277 }
278
279 /**
280 * Initializes this class
281 *
282 * @return bool
283 */
284 protected static function init()
285 {
286 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['disable_exec_function']) {
287 return false;
288 }
289 if (!self::$initialized) {
290 self::initPaths();
291 self::$applications = self::getConfiguredApps();
292 self::$initialized = true;
293 }
294 return true;
295 }
296
297 /**
298 * Initializes and extends the preset paths with own
299 *
300 * @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).
301 * @return void
302 */
303 protected static function initPaths($paths = '')
304 {
305 $doCheck = false;
306
307 // Init global paths array if not already done
308 if (!is_array(self::$paths)) {
309 self::$paths = self::getPathsInternal();
310 $doCheck = true;
311 }
312 // Merge the submitted paths array to the global
313 if ($paths) {
314 $paths = GeneralUtility::trimExplode(',', $paths, true);
315 if (is_array($paths)) {
316 foreach ($paths as $path) {
317 // Make absolute path of relative
318 if (!preg_match('#^/#', $path)) {
319 $path = PATH_site . $path;
320 }
321 if (!isset(self::$paths[$path])) {
322 if (@is_dir($path)) {
323 self::$paths[$path] = $path;
324 } else {
325 self::$paths[$path] = false;
326 }
327 }
328 }
329 }
330 }
331 // Check if new paths are invalid
332 if ($doCheck) {
333 foreach (self::$paths as $path => $valid) {
334 // Ignore invalid (FALSE) paths
335 if ($valid && !@is_dir($path)) {
336 self::$paths[$path] = false;
337 }
338 }
339 }
340 }
341
342 /**
343 * Processes and returns the paths from $GLOBALS['TYPO3_CONF_VARS']['SYS']['binSetup']
344 *
345 * @return array Array of commands and path
346 */
347 protected static function getConfiguredApps()
348 {
349 $cmdArr = [];
350
351 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['binSetup']) {
352 $binSetup = str_replace(['\'.chr(10).\'', '\' . LF . \''], LF, $GLOBALS['TYPO3_CONF_VARS']['SYS']['binSetup']);
353 $pathSetup = preg_split('/[\n,]+/', $binSetup);
354 foreach ($pathSetup as $val) {
355 if (trim($val) === '') {
356 continue;
357 }
358 list($cmd, $cmdPath) = GeneralUtility::trimExplode('=', $val, true, 2);
359 $cmdArr[$cmd]['app'] = basename($cmdPath);
360 $cmdArr[$cmd]['path'] = dirname($cmdPath) . '/';
361 $cmdArr[$cmd]['valid'] = true;
362 }
363 }
364
365 return $cmdArr;
366 }
367
368 /**
369 * Sets the search paths from different sources, internal
370 *
371 * @return array Array of absolute paths (keys and values are equal)
372 */
373 protected static function getPathsInternal()
374 {
375 $pathsArr = [];
376 $sysPathArr = [];
377
378 // Image magick paths first
379 // processor_path_lzw take precedence over processor_path
380 if ($imPath = $GLOBALS['TYPO3_CONF_VARS']['GFX']['processor_path_lzw'] ?: $GLOBALS['TYPO3_CONF_VARS']['GFX']['processor_path']) {
381 $imPath = self::fixPath($imPath);
382 $pathsArr[$imPath] = $imPath;
383 }
384
385 // Add configured paths
386 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['binPath']) {
387 $sysPath = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['SYS']['binPath'], true);
388 foreach ($sysPath as $val) {
389 $val = self::fixPath($val);
390 $sysPathArr[$val] = $val;
391 }
392 }
393
394 // Add path from environment
395 // @todo how does this work for WIN
396 if ($GLOBALS['_SERVER']['PATH']) {
397 $sep = (TYPO3_OS === 'WIN' ? ';' : ':');
398 $envPath = GeneralUtility::trimExplode($sep, $GLOBALS['_SERVER']['PATH'], true);
399 foreach ($envPath as $val) {
400 $val = self::fixPath($val);
401 $sysPathArr[$val] = $val;
402 }
403 }
404
405 // Set common paths for Unix (only)
406 if (TYPO3_OS !== 'WIN') {
407 $sysPathArr = array_merge($sysPathArr, [
408 '/usr/bin/' => '/usr/bin/',
409 '/usr/local/bin/' => '/usr/local/bin/',
410 ]);
411 }
412
413 $pathsArr = array_merge($pathsArr, $sysPathArr);
414
415 return $pathsArr;
416 }
417
418 /**
419 * Set a path to the right format
420 *
421 * @param string $path Input path
422 * @return string Output path
423 */
424 protected static function fixPath($path)
425 {
426 return str_replace('//', '/', $path . '/');
427 }
428
429 /**
430 * Escape shell arguments (for example filenames) to be used on the local system.
431 *
432 * The setting UTF8filesystem will be taken into account.
433 *
434 * @param string[] $input Input arguments to be escaped
435 * @return string[] Escaped shell arguments
436 */
437 public static function escapeShellArguments(array $input)
438 {
439 $isUTF8Filesystem = !empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']);
440 $currentLocale = false;
441 if ($isUTF8Filesystem) {
442 $currentLocale = setlocale(LC_CTYPE, 0);
443 setlocale(LC_CTYPE, $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLocale']);
444 }
445
446 $output = array_map('escapeshellarg', $input);
447
448 if ($isUTF8Filesystem && $currentLocale !== false) {
449 setlocale(LC_CTYPE, $currentLocale);
450 }
451
452 return $output;
453 }
454
455 /**
456 * Escape a shell argument (for example a filename) to be used on the local system.
457 *
458 * The setting UTF8filesystem will be taken into account.
459 *
460 * @param string $input Input-argument to be escaped
461 * @return string Escaped shell argument
462 */
463 public static function escapeShellArgument($input)
464 {
465 return self::escapeShellArguments([$input])[0];
466 }
467 }