[TASK] Remove SVN auto properties $Id$
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_cli.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2006-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * Contains base class for TYPO3 cli scripts
29 *
30 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
31 */
32 /**
33 * [CLASS/FUNCTION INDEX of SCRIPT]
34 *
35 *
36 *
37 * 60: class t3lib_cli
38 * 83: function t3lib_cli()
39 * 96: function cli_getArg($option,$argv)
40 * 112: function cli_getArgIndex()
41 * 131: function cli_keyboardInput()
42 * 142: function cli_keyboardInput_yes()
43 * 154: function cli_echo($string='',$force=FALSE)
44 * 169: function cli_help()
45 * 207: function cli_indent($str,$indent)
46 *
47 * TOTAL FUNCTIONS: 8
48 * (This index is automatically created/updated by the extension "extdeveval")
49 *
50 */
51
52
53 /**
54 * TYPO3 cli script basis
55 *
56 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
57 * @package TYPO3
58 * @subpackage t3lib
59 */
60 class t3lib_cli {
61
62 var $cli_args = array(); // Command line arguments, exploded into key => value-array pairs
63 var $cli_options = array(
64 array('-s', 'Silent operation, will only output errors and important messages.'),
65 array('--silent', 'Same as -s'),
66 array('-ss', 'Super silent, will not even output errors or important messages.'),
67 );
68 var $cli_help = array(
69 'name' => 'CLI base class (overwrite this...)',
70 'synopsis' => '###OPTIONS###',
71 'description' => 'Class with basic functionality for CLI scripts (overwrite this...)',
72 'examples' => 'Give examples...',
73 'options' => '',
74 'license' => 'GNU GPL - free software!',
75 'author' => '[Author name]',
76 );
77 var $stdin = NULL;
78
79
80 /**
81 * Constructor
82 * Make sure child classes also call this!
83 *
84 * @return void
85 */
86 function t3lib_cli() {
87 // Loads the cli_args array with command line arguments
88 $this->cli_args = $this->cli_getArgIndex();
89 }
90
91 /**
92 * Finds the arg token (like "-s") in argv and returns the rest of argv from that point on.
93 * This should only be used in special cases since this->cli_args should already be prepared with an index of values!
94 *
95 * @param string Option string, eg. "-s"
96 * @param array Input argv array
97 * @return array Output argv array with all options AFTER the found option.
98 */
99 function cli_getArgArray($option, $argv) {
100 while (count($argv) && strcmp($argv[0], $option)) {
101 array_shift($argv);
102 }
103
104 if (!strcmp($argv[0], $option)) {
105 array_shift($argv);
106 return count($argv) ? $argv : array('');
107 }
108 }
109
110 /**
111 * Return true if option is found
112 *
113 * @param string Option string, eg. "-s"
114 * @return boolean TRUE if option found
115 */
116 function cli_isArg($option) {
117 return isset($this->cli_args[$option]);
118 }
119
120 /**
121 * Return argument value
122 *
123 * @param string Option string, eg. "-s"
124 * @param integer Value index, default is 0 (zero) = the first one...
125 * @return boolean TRUE if option found
126 */
127 function cli_argValue($option, $idx = 0) {
128 return is_array($this->cli_args[$option]) ? $this->cli_args[$option][$idx] : '';
129 }
130
131 /**
132 * Will parse "_SERVER[argv]" into an index of options and values
133 * Argument names (eg. "-s") will be keys and values after (eg. "-s value1 value2 ..." or "-s=value1") will be in the array.
134 * Array is empty if no values
135 *
136 * @return array
137 */
138 function cli_getArgIndex() {
139 $cli_options = array();
140 $index = '_DEFAULT';
141 foreach ($_SERVER['argv'] as $token) {
142 if ($token{0} === '-' && !t3lib_div::testInt($token{1})) { // Options starting with a number is invalid - they could be negative values... !
143 list($index, $opt) = explode('=', $token, 2);
144 if (isset($cli_options[$index])) {
145 echo 'ERROR: Option ' . $index . ' was used twice!' . LF;
146 exit;
147 }
148 $cli_options[$index] = array();
149 if (isset($opt)) {
150 $cli_options[$index][] = $opt;
151 }
152 } else {
153 $cli_options[$index][] = $token;
154 }
155 }
156
157 return $cli_options;
158 }
159
160 /**
161 * Validates if the input arguments in this->cli_args are all listed in this->cli_options and if not, will exit with an error.
162 */
163 function cli_validateArgs() {
164 $cli_args_copy = $this->cli_args;
165 unset($cli_args_copy['_DEFAULT']);
166 $allOptions = array();
167
168 foreach ($this->cli_options as $cfg) {
169 $allOptions[] = $cfg[0];
170 $argSplit = t3lib_div::trimExplode(' ', $cfg[0], 1);
171 if (isset($cli_args_copy[$argSplit[0]])) {
172
173 foreach ($argSplit as $i => $v) {
174 $ii = $i;
175 if ($i > 0) {
176 if (!isset($cli_args_copy[$argSplit[0]][$i - 1]) && $v{0} != '[') { // Using "[]" around a paramter makes it optional
177 echo 'ERROR: Option "' . $argSplit[0] . '" requires a value ("' . $v . '") on position ' . $i . LF;
178 exit;
179 }
180 }
181 }
182
183 $ii++;
184 if (isset($cli_args_copy[$argSplit[0]][$ii - 1])) {
185 echo 'ERROR: Option "' . $argSplit[0] . '" does not support a value on position ' . $ii . LF;
186 exit;
187 }
188
189 unset($cli_args_copy[$argSplit[0]]);
190 }
191 }
192
193 if (count($cli_args_copy)) {
194 echo wordwrap('ERROR: Option ' . implode(',', array_keys($cli_args_copy)) . ' was unknown to this script!' . LF . '(Options are: ' . implode(', ', $allOptions) . ')' . LF);
195 exit;
196 }
197 }
198
199 /**
200 * Asks stdin for keyboard input and returns the line (after enter is pressed)
201 *
202 * @return string
203 */
204 function cli_keyboardInput() {
205
206 // Have to open the stdin stream only ONCE! otherwise I cannot read multiple lines from it... :
207 if (!$this->stdin) {
208 $this->stdin = fopen('php://stdin', 'r');
209 }
210
211 while (FALSE == ($line = fgets($this->stdin, 1000))) {
212 }
213
214 return trim($line);
215 }
216
217 /**
218 * Asks for Yes/No from shell and returns true if "y" or "yes" is found as input.
219 *
220 * @param string String to ask before...
221 * @return boolean TRUE if "y" or "yes" is the input (case insensitive)
222 */
223 function cli_keyboardInput_yes($msg = '') {
224 echo $msg . ' (Yes/No + return): '; // ONLY makes sense to echo it out since we are awaiting keyboard input - that cannot be silenced...
225
226 return t3lib_div::inList('y,yes', strtolower($this->cli_keyboardInput()));
227 }
228
229 /**
230 * Echos strings to shell, but respective silent-modes
231 *
232 * @param string The string
233 * @param boolean If string should be written even if -s is set (-ss will subdue it!)
234 * @return boolean Returns TRUE if string was outputted.
235 */
236 function cli_echo($string = '', $force = FALSE) {
237 if (isset($this->cli_args['-ss'])) {
238 // Nothing to do...
239 } elseif (isset($this->cli_args['-s']) || isset($this->cli_args['--silent'])) {
240 if ($force) {
241 echo $string;
242 return TRUE;
243 }
244 } else {
245 echo $string;
246 return TRUE;
247 }
248
249 return FALSE;
250 }
251
252 /**
253 * Prints help-output from ->cli_help array
254 *
255 * @return void
256 */
257 function cli_help() {
258 foreach ($this->cli_help as $key => $value) {
259 $this->cli_echo(strtoupper($key) . ":\n");
260 switch ($key) {
261 case 'synopsis':
262 $optStr = '';
263 foreach ($this->cli_options as $v) {
264 $optStr .= ' [' . $v[0] . ']';
265 }
266 $this->cli_echo($this->cli_indent(str_replace('###OPTIONS###', trim($optStr), $value), 4) . "\n\n");
267 break;
268 case 'options':
269 $this->cli_echo($this->cli_indent($value, 4) . LF);
270
271 $maxLen = 0;
272 foreach ($this->cli_options as $v) {
273 if (strlen($v[0]) > $maxLen) {
274 $maxLen = strlen($v[0]);
275 }
276 }
277
278 foreach ($this->cli_options as $v) {
279 $this->cli_echo($v[0] . substr($this->cli_indent(rtrim($v[1] . LF . $v[2]), $maxLen + 4), strlen($v[0])) . LF);
280 }
281 $this->cli_echo(LF);
282 break;
283 default:
284 $this->cli_echo($this->cli_indent($value, 4) . "\n\n");
285 break;
286 }
287 }
288 }
289
290 /**
291 * Indentation function for 75 char wide lines.
292 *
293 * @param string String to break and indent.
294 * @param integer Number of space chars to indent.
295 * @return string Result
296 */
297 function cli_indent($str, $indent) {
298 $lines = explode(LF, wordwrap($str, 75 - $indent));
299 $indentStr = str_pad('', $indent, ' ');
300 foreach ($lines as $k => $v) {
301 $lines[$k] = $indentStr . $lines[$k];
302 }
303
304 return implode(LF, $lines);
305 }
306 }
307
308 ?>