a272720f382a1b2d605f7e3d70e4fc7a9ecfc31c
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Controller / CommandLineController.php
1 <?php
2 namespace TYPO3\CMS\Core\Controller;
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\Utility\GeneralUtility;
18
19 /**
20 * TYPO3 cli script basis
21 * @deprecated since TYPO3 v8, will be removed in TYPO3 v9, use a custom Command instead
22 */
23 class CommandLineController
24 {
25 /**
26 * Command line arguments, exploded into key => value-array pairs
27 *
28 * @var array
29 */
30 public $cli_args = [];
31
32 /**
33 * @var array
34 */
35 public $cli_options = [
36 ['-s', 'Silent operation, will only output errors and important messages.'],
37 ['--silent', 'Same as -s'],
38 ['-ss', 'Super silent, will not even output errors or important messages.']
39 ];
40
41 /**
42 * @var array
43 */
44 public $cli_help = [
45 'name' => 'CLI base class (overwrite this...)',
46 'synopsis' => '###OPTIONS###',
47 'description' => 'Class with basic functionality for CLI scripts (overwrite this...)',
48 'examples' => 'Give examples...',
49 'options' => '',
50 'license' => 'GNU GPL - free software!',
51 'author' => '[Author name]'
52 ];
53
54 /**
55 * @var resource
56 */
57 public $stdin = null;
58
59 /**
60 * Constructor
61 * Make sure child classes also call this!
62 *
63 * @deprecated the CommandLineController is deprecated since TYPO3 v8 and will be removed in TYPO3 v9, use a separate CLI Command instead
64 */
65 public function __construct()
66 {
67 GeneralUtility::logDeprecatedFunction();
68 // Loads the cli_args array with command line arguments
69 $this->cli_setArguments($_SERVER['argv']);
70 }
71
72 /**
73 * Finds the arg token (like "-s") in argv and returns the rest of argv from that point on.
74 * This should only be used in special cases since this->cli_args should already be prepared with an index of values!
75 *
76 * @param string $option Option string, eg. "-s
77 * @param array $argv Input argv array
78 * @return array Output argv array with all options AFTER the found option.
79 */
80 public function cli_getArgArray($option, $argv)
81 {
82 while (count($argv) && (string)$argv[0] !== (string)$option) {
83 array_shift($argv);
84 }
85 if ((string)$argv[0] === (string)$option) {
86 array_shift($argv);
87 return !empty($argv) ? $argv : [''];
88 }
89 }
90
91 /**
92 * Return TRUE if option is found
93 *
94 * @param string $option Option string, eg. "-s
95 * @return bool TRUE if option found
96 */
97 public function cli_isArg($option)
98 {
99 return isset($this->cli_args[$option]);
100 }
101
102 /**
103 * Return argument value
104 *
105 * @param string $option Option string, eg. "-s
106 * @param int $idx Value index, default is 0 (zero) = the first one...
107 * @return bool TRUE if option found
108 */
109 public function cli_argValue($option, $idx = 0)
110 {
111 return is_array($this->cli_args[$option]) ? $this->cli_args[$option][$idx] : '';
112 }
113
114 /**
115 * Will parse "_SERVER[argv]" into an index of options and values
116 * Argument names (eg. "-s") will be keys and values after (eg. "-s value1 value2 ..." or "-s=value1") will be in the array.
117 * Array is empty if no values
118 *
119 * @param array $argv Configuration options
120 * @return array
121 */
122 public function cli_getArgIndex(array $argv = [])
123 {
124 $cli_options = [];
125 $index = '_DEFAULT';
126 foreach ($argv as $token) {
127 // Options starting with a number is invalid - they could be negative values!
128 if ($token[0] === '-' && !\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($token[1])) {
129 list($index, $opt) = explode('=', $token, 2);
130 if (isset($cli_options[$index])) {
131 echo 'ERROR: Option ' . $index . ' was used twice!' . LF;
132 die;
133 }
134 $cli_options[$index] = [];
135 if (isset($opt)) {
136 $cli_options[$index][] = $opt;
137 }
138 } else {
139 $cli_options[$index][] = $token;
140 }
141 }
142 return $cli_options;
143 }
144
145 /**
146 * Validates if the input arguments in this->cli_args are all listed in this->cli_options and if not,
147 * will exit with an error.
148 */
149 public function cli_validateArgs()
150 {
151 $cli_args_copy = $this->cli_args;
152 unset($cli_args_copy['_DEFAULT']);
153 $allOptions = [];
154 foreach ($this->cli_options as $cfg) {
155 $allOptions[] = $cfg[0];
156 $argSplit = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(' ', $cfg[0], true);
157 if (isset($cli_args_copy[$argSplit[0]])) {
158 $ii = 0;
159 foreach ($argSplit as $i => $v) {
160 $ii = $i;
161 if ($i > 0) {
162 if (!isset($cli_args_copy[$argSplit[0]][$i - 1]) && $v[0] !== '[') {
163 // Using "[]" around a parameter makes it optional
164 echo 'ERROR: Option "' . $argSplit[0] . '" requires a value ("' . $v . '") on position ' . $i . LF;
165 die;
166 }
167 }
168 }
169 $ii++;
170 if (isset($cli_args_copy[$argSplit[0]][$ii - 1])) {
171 echo 'ERROR: Option "' . $argSplit[0] . '" does not support a value on position ' . $ii . LF;
172 die;
173 }
174 unset($cli_args_copy[$argSplit[0]]);
175 }
176 }
177 if (!empty($cli_args_copy)) {
178 echo wordwrap('ERROR: Option ' . implode(',', array_keys($cli_args_copy)) . ' was unknown to this script!' . LF . '(Options are: ' . implode(', ', $allOptions) . ')' . LF);
179 die;
180 }
181 }
182
183 /**
184 * Set environment array to $cli_args
185 *
186 * @param array $argv Configuration options
187 */
188 public function cli_setArguments(array $argv = [])
189 {
190 $this->cli_args = $this->cli_getArgIndex($argv);
191 }
192
193 /**
194 * Asks stdin for keyboard input and returns the line (after enter is pressed)
195 *
196 * @return string
197 */
198 public function cli_keyboardInput()
199 {
200 // Have to open the stdin stream only ONCE! otherwise I cannot read multiple lines from it... :
201 if (!$this->stdin) {
202 $this->stdin = fopen('php://stdin', 'r');
203 }
204 while (false == ($line = fgets($this->stdin, 1000))) {
205 }
206 return trim($line);
207 }
208
209 /**
210 * Asks for Yes/No from shell and returns TRUE if "y" or "yes" is found as input.
211 *
212 * @param string $msg String to ask before...
213 * @return bool TRUE if "y" or "yes" is the input (case insensitive)
214 */
215 public function cli_keyboardInput_yes($msg = '')
216 {
217 // ONLY makes sense to echo it out since we are awaiting keyboard input - that cannot be silenced
218 echo $msg . ' (Yes/No + return): ';
219 $input = strtolower($this->cli_keyboardInput());
220 return $input === 'y' || $input === 'yes';
221 }
222
223 /**
224 * Echos strings to shell, but respective silent-modes
225 *
226 * @param string $string The string
227 * @param bool $force If string should be written even if -s is set (-ss will subdue it!)
228 * @return bool Returns TRUE if string was outputted.
229 */
230 public function cli_echo($string = '', $force = false)
231 {
232 if (isset($this->cli_args['-ss'])) {
233 } elseif (isset($this->cli_args['-s']) || isset($this->cli_args['--silent'])) {
234 if ($force) {
235 echo $string;
236 return true;
237 }
238 } else {
239 echo $string;
240 return true;
241 }
242 return false;
243 }
244
245 /**
246 * Prints help-output from ->cli_help array
247 */
248 public function cli_help()
249 {
250 foreach ($this->cli_help as $key => $value) {
251 $this->cli_echo(strtoupper($key) . ':
252 ');
253 switch ($key) {
254 case 'synopsis':
255 $optStr = '';
256 foreach ($this->cli_options as $v) {
257 $optStr .= ' [' . $v[0] . ']';
258 }
259 $this->cli_echo($this->cli_indent(str_replace('###OPTIONS###', trim($optStr), $value), 4) . '
260
261 ');
262 break;
263 case 'options':
264 $this->cli_echo($this->cli_indent($value, 4) . LF);
265 $maxLen = 0;
266 foreach ($this->cli_options as $v) {
267 if (strlen($v[0]) > $maxLen) {
268 $maxLen = strlen($v[0]);
269 }
270 }
271 foreach ($this->cli_options as $v) {
272 $this->cli_echo($v[0] . substr($this->cli_indent(rtrim($v[1] . LF . $v[2]), $maxLen + 4), strlen($v[0])) . LF);
273 }
274 $this->cli_echo(LF);
275 break;
276 default:
277 $this->cli_echo($this->cli_indent($value, 4) . '
278
279 ');
280 }
281 }
282 }
283
284 /**
285 * Indentation function for 75 char wide lines.
286 *
287 * @param string $str String to break and indent.
288 * @param int $indent Number of space chars to indent.
289 * @return string Result
290 */
291 public function cli_indent($str, $indent)
292 {
293 $lines = explode(LF, wordwrap($str, 75 - $indent));
294 $indentStr = str_pad('', $indent, ' ');
295 foreach ($lines as $k => $v) {
296 $lines[$k] = $indentStr . $lines[$k];
297 }
298 return implode(LF, $lines);
299 }
300 }