add wordpress hash routine
[pear] / Console / Getopt.php
1 <?php
2 /* vim: set expandtab tabstop=4 shiftwidth=4: */
3 /**
4  * PHP Version 5
5  *
6  * Copyright (c) 1997-2004 The PHP Group
7  *
8  * This source file is subject to version 3.0 of the PHP license,
9  * that is bundled with this package in the file LICENSE, and is
10  * available through the world-wide-web at the following url:
11  * http://www.php.net/license/3_0.txt.
12  * If you did not receive a copy of the PHP license and are unable to
13  * obtain it through the world-wide-web, please send a note to
14  * license@php.net so we can mail you a copy immediately.
15  *
16  * @category Console
17  * @package  Console_Getopt
18  * @author   Andrei Zmievski <andrei@php.net>
19  * @license  http://www.php.net/license/3_0.txt PHP 3.0
20  * @version  CVS: $Id: Getopt.php 306067 2010-12-08 00:13:31Z dufuz $
21  * @link     http://pear.php.net/package/Console_Getopt
22  */
23
24 require_once 'PEAR.php';
25
26 /**
27  * Command-line options parsing class.
28  *
29  * @category Console
30  * @package  Console_Getopt
31  * @author   Andrei Zmievski <andrei@php.net>
32  * @license  http://www.php.net/license/3_0.txt PHP 3.0
33  * @link     http://pear.php.net/package/Console_Getopt
34  */
35 class Console_Getopt
36 {
37
38     /**
39      * Parses the command-line options.
40      *
41      * The first parameter to this function should be the list of command-line
42      * arguments without the leading reference to the running program.
43      *
44      * The second parameter is a string of allowed short options. Each of the
45      * option letters can be followed by a colon ':' to specify that the option
46      * requires an argument, or a double colon '::' to specify that the option
47      * takes an optional argument.
48      *
49      * The third argument is an optional array of allowed long options. The
50      * leading '--' should not be included in the option name. Options that
51      * require an argument should be followed by '=', and options that take an
52      * option argument should be followed by '=='.
53      *
54      * The return value is an array of two elements: the list of parsed
55      * options and the list of non-option command-line arguments. Each entry in
56      * the list of parsed options is a pair of elements - the first one
57      * specifies the option, and the second one specifies the option argument,
58      * if there was one.
59      *
60      * Long and short options can be mixed.
61      *
62      * Most of the semantics of this function are based on GNU getopt_long().
63      *
64      * @param array  $args          an array of command-line arguments
65      * @param string $short_options specifies the list of allowed short options
66      * @param array  $long_options  specifies the list of allowed long options
67      * @param boolean $skip_unknown suppresses Console_Getopt: unrecognized option
68      *
69      * @return array two-element array containing the list of parsed options and
70      * the non-option arguments
71      * @access public
72      */
73     static function getopt2($args, $short_options, $long_options = null, $skip_unknown = false)
74     {
75         return Console_Getopt::doGetopt(2, $args, $short_options, $long_options, $skip_unknown);
76     }
77
78     /**
79      * This function expects $args to start with the script name (POSIX-style).
80      * Preserved for backwards compatibility.
81      *
82      * @param array  $args          an array of command-line arguments
83      * @param string $short_options specifies the list of allowed short options
84      * @param array  $long_options  specifies the list of allowed long options
85      *
86      * @see getopt2()
87      * @return array two-element array containing the list of parsed options and
88      * the non-option arguments
89      */
90     function getopt($args, $short_options, $long_options = null, $skip_unknown = false)
91     {
92         return Console_Getopt::doGetopt(1, $args, $short_options, $long_options, $skip_unknown);
93     }
94
95     /**
96      * The actual implementation of the argument parsing code.
97      *
98      * @param int    $version       Version to use
99      * @param array  $args          an array of command-line arguments
100      * @param string $short_options specifies the list of allowed short options
101      * @param array  $long_options  specifies the list of allowed long options
102      * @param boolean $skip_unknown suppresses Console_Getopt: unrecognized option
103      *
104      * @return array
105      */
106     static function doGetopt($version, $args, $short_options, $long_options = null, $skip_unknown = false)
107     {
108         // in case you pass directly readPHPArgv() as the first arg
109         if (PEAR::isError($args)) {
110             return $args;
111         }
112
113         if (empty($args)) {
114             return array(array(), array());
115         }
116
117         $non_opts = $opts = array();
118
119         settype($args, 'array');
120
121         if ($long_options) {
122             sort($long_options);
123         }
124
125         /*
126          * Preserve backwards compatibility with callers that relied on
127          * erroneous POSIX fix.
128          */
129         if ($version < 2) {
130             if (isset($args[0][0]) && $args[0][0] != '-') {
131                 array_shift($args);
132             }
133         }
134         
135         for ($i = 0; $i < count($args); $i++) {
136             $arg = $args[$i];
137             /* The special element '--' means explicit end of
138                options. Treat the rest of the arguments as non-options
139                and end the loop. */
140             if ($arg == '--') {
141                 $non_opts = array_merge($non_opts, array_slice($args, $i + 1));
142                 break;
143             }
144
145             if ($arg[0] != '-' || (strlen($arg) > 1 && $arg[1] == '-' && !$long_options)) {
146                 $non_opts = array_merge($non_opts, array_slice($args, $i));
147                 break;
148             } elseif (strlen($arg) > 1 && $arg[1] == '-') {
149                 $error = Console_Getopt::_parseLongOption(substr($arg, 2),
150                                                           $long_options,
151                                                           $opts,
152                                                           $args,
153                                                           $skip_unknown,$i);
154                 if (PEAR::isError($error)) {
155                     return $error;
156                 }
157             } elseif ($arg == '-') {
158                 // - is stdin
159                 $non_opts = array_merge($non_opts, array_slice($args, $i));
160                 break;
161             } else {
162                 $error = Console_Getopt::_parseShortOption(substr($arg, 1),
163                                                            $short_options,
164                                                            $opts,
165                                                            $args,
166                                                            $skip_unknown,$i);
167                 if (PEAR::isError($error)) {
168                     return $error;
169                 }
170             }
171         }
172
173         return array($opts, $non_opts);
174     }
175
176     /**
177      * Parse short option
178      *
179      * @param string     $arg           Argument
180      * @param string[]   $short_options Available short options
181      * @param string[][] &$opts
182      * @param string[]   &$args
183      * @param boolean    $skip_unknown suppresses Console_Getopt: unrecognized option
184      *
185      * @access private
186      * @return void
187      */
188     static function _parseShortOption($arg, $short_options, &$opts, &$args, $skip_unknown, &$arg_pos)
189     {
190         for ($i = 0; $i < strlen($arg); $i++) {
191             $opt     = $arg[$i];
192             $opt_arg = null;
193
194             /* Try to find the short option in the specifier string. */
195             if (($spec = strstr($short_options, $opt)) === false || $arg[$i] == ':') {
196                 if ($skip_unknown === true) {
197                     break;
198                 }
199
200                 $msg = "Console_Getopt: unrecognized option -- $opt";
201                 return PEAR::raiseError($msg);
202             }
203
204             if (strlen($spec) > 1 && $spec[1] == ':') {
205                 if (strlen($spec) > 2 && $spec[2] == ':') {
206                     if ($i + 1 < strlen($arg)) {
207                         /* Option takes an optional argument. Use the remainder of
208                            the arg string if there is anything left. */
209                         $opts[] = array($opt, substr($arg, $i + 1));
210                         break;
211                     }
212                 } else {
213                     /* Option requires an argument. Use the remainder of the arg
214                        string if there is anything left. */
215                     if ($i + 1 < strlen($arg)) {
216                         $opts[] = array($opt,  substr($arg, $i + 1));
217                         break;
218                     } else if (isset($args[$arg_pos+1])) {
219                         /* Else use the next argument. */;
220                         $opt_arg = $args[$arg_pos+1];
221                         if (Console_Getopt::_isShortOpt($args[$arg_pos+1])
222                             || Console_Getopt::_isLongOpt($args[$arg_pos+1])) {
223                             $msg = "option requires an argument --$opt";
224                             return PEAR::raiseError("Console_Getopt:" . $msg);
225                         }
226                         $arg_pos++;
227                     } else {
228                         $msg = "option requires an argument --$opt";
229                         return PEAR::raiseError("Console_Getopt:" . $msg);
230                     }
231                 }
232             }
233
234             $opts[] = array($opt, $opt_arg );
235         }
236     }
237
238     /**
239      * Checks if an argument is a short option
240      *
241      * @param string $arg Argument to check
242      *
243      * @access private
244      * @return bool
245      */
246     static function _isShortOpt($arg)
247     {
248         return strlen($arg) == 2 && $arg[0] == '-'
249                && preg_match('/[a-zA-Z]/', $arg[1]);
250     }
251
252     /**
253      * Checks if an argument is a long option
254      *
255      * @param string $arg Argument to check
256      *
257      * @access private
258      * @return bool
259      */
260     static function _isLongOpt($arg)
261     {
262         $arg = (string) $arg;
263         return strlen($arg) > 2 && $arg[0] == '-' && $arg[1] == '-' &&
264                preg_match('/[a-zA-Z]+$/', substr($arg, 2));
265     }
266
267     /**
268      * Parse long option
269      *
270      * @param string     $arg          Argument
271      * @param string[]   $long_options Available long options
272      * @param string[][] &$opts
273      * @param string[]   &$args
274      *
275      * @access private
276      * @return void|PEAR_Error
277      */
278     function _parseLongOption($arg, $long_options, &$opts, &$args, $skip_unknown, &$arg_pos)
279     {
280         @list($opt, $opt_arg) = explode('=', $arg, 2);
281
282         $opt_len = strlen($opt);
283
284         for ($i = 0; $i < count($long_options); $i++) {
285             $long_opt  = $long_options[$i];
286             $opt_start = substr($long_opt, 0, $opt_len);
287
288             $long_opt_name = str_replace('=', '', $long_opt);
289
290             /* Option doesn't match. Go on to the next one. */
291             if ($long_opt_name != $opt) {
292                 continue;
293             }
294
295             $opt_rest = substr($long_opt, $opt_len);
296
297             /* Check that the options uniquely matches one of the allowed
298                options. */
299             if ($i + 1 < count($long_options)) {
300                 $next_option_rest = substr($long_options[$i + 1], $opt_len);
301             } else {
302                 $next_option_rest = '';
303             }
304
305             if ($opt_rest != '' && $opt[0] != '=' &&
306                 $i + 1 < count($long_options) &&
307                 $opt == substr($long_options[$i+1], 0, $opt_len) &&
308                 $next_option_rest != '' &&
309                 $next_option_rest[0] != '=') {
310
311                 $msg = "Console_Getopt: option --$opt is ambiguous";
312                 return PEAR::raiseError($msg);
313             }
314
315             if (substr($long_opt, -1) == '=') {
316                 if (substr($long_opt, -2) != '==') {
317                     /* Long option requires an argument.
318                        Take the next argument if one wasn't specified. */;
319                     if (!strlen($opt_arg) && !isset($args[$arg_pos + 1])) {
320                         $msg = "Console_Getopt: option requires an argument --$opt";
321                         return PEAR::raiseError($msg);
322                     }
323                     $opt_arg = $args[$arg_pos + 1];
324                     if (Console_Getopt::_isShortOpt($opt_arg)
325                         || Console_Getopt::_isLongOpt($opt_arg)) {
326                         $msg = "Console_Getopt: option requires an argument --$opt";
327                         return PEAR::raiseError($msg);
328                     }
329                     $arg_pos++;
330                 }
331             } else if ($opt_arg) {
332                 $msg = "Console_Getopt: option --$opt doesn't allow an argument";
333                 return PEAR::raiseError($msg);
334             }
335
336             $opts[] = array('--' . $opt, $opt_arg);
337             return;
338         }
339
340         if ($skip_unknown === true) {
341             return;
342         }
343
344         return PEAR::raiseError("Console_Getopt: unrecognized option --$opt");
345     }
346
347     /**
348      * Safely read the $argv PHP array across different PHP configurations.
349      * Will take care on register_globals and register_argc_argv ini directives
350      *
351      * @access public
352      * @return mixed the $argv PHP array or PEAR error if not registered
353      */
354     function readPHPArgv()
355     {
356         global $argv;
357         if (!is_array($argv)) {
358             if (!@is_array($_SERVER['argv'])) {
359                 if (!@is_array($GLOBALS['HTTP_SERVER_VARS']['argv'])) {
360                     $msg = "Could not read cmd args (register_argc_argv=Off?)";
361                     return PEAR::raiseError("Console_Getopt: " . $msg);
362                 }
363                 return $GLOBALS['HTTP_SERVER_VARS']['argv'];
364             }
365             return $_SERVER['argv'];
366         }
367         return $argv;
368     }
369
370 }