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