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