]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/api/ApiFormatJson_json.php
MediaWiki 1.11.0
[autoinstalls/mediawiki.git] / includes / api / ApiFormatJson_json.php
1 <?php
2 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
3
4 /**
5 * Converts to and from JSON format.
6 *
7 * JSON (JavaScript Object Notation) is a lightweight data-interchange
8 * format. It is easy for humans to read and write. It is easy for machines
9 * to parse and generate. It is based on a subset of the JavaScript
10 * Programming Language, Standard ECMA-262 3rd Edition - December 1999.
11 * This feature can also be found in  Python. JSON is a text format that is
12 * completely language independent but uses conventions that are familiar
13 * to programmers of the C-family of languages, including C, C++, C#, Java,
14 * JavaScript, Perl, TCL, and many others. These properties make JSON an
15 * ideal data-interchange language.
16 *
17 * This package provides a simple encoder and decoder for JSON notation. It
18 * is intended for use with client-side Javascript applications that make
19 * use of HTTPRequest to perform server communication functions - data can
20 * be encoded into JSON notation for use in a client-side javascript, or
21 * decoded from incoming Javascript requests. JSON format is native to
22 * Javascript, and can be directly eval()'ed with no further parsing
23 * overhead
24 *
25 * All strings should be in ASCII or UTF-8 format!
26 *
27 * LICENSE: Redistribution and use in source and binary forms, with or
28 * without modification, are permitted provided that the following
29 * conditions are met: Redistributions of source code must retain the
30 * above copyright notice, this list of conditions and the following
31 * disclaimer. Redistributions in binary form must reproduce the above
32 * copyright notice, this list of conditions and the following disclaimer
33 * in the documentation and/or other materials provided with the
34 * distribution.
35 *
36 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
37 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
38 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
39 * NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
40 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
41 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
42 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
44 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
45 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
46 * DAMAGE.
47 *
48 * @addtogroup  API
49 * @author      Michal Migurski <mike-json@teczno.com>
50 * @author      Matt Knapp <mdknapp[at]gmail[dot]com>
51 * @author      Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
52 * @copyright   2005 Michal Migurski
53 * @version     CVS: $Id: JSON.php,v 1.30 2006/03/08 16:10:20 migurski Exp $
54 * @license     http://www.opensource.org/licenses/bsd-license.php
55 * @see         http://pear.php.net/pepr/pepr-proposal-show.php?id=198
56 */
57
58 /**
59 * Marker constant for Services_JSON::decode(), used to flag stack state
60 */
61 define('SERVICES_JSON_SLICE',   1);
62
63 /**
64 * Marker constant for Services_JSON::decode(), used to flag stack state
65 */
66 define('SERVICES_JSON_IN_STR',  2);
67
68 /**
69 * Marker constant for Services_JSON::decode(), used to flag stack state
70 */
71 define('SERVICES_JSON_IN_ARR',  3);
72
73 /**
74 * Marker constant for Services_JSON::decode(), used to flag stack state
75 */
76 define('SERVICES_JSON_IN_OBJ',  4);
77
78 /**
79 * Marker constant for Services_JSON::decode(), used to flag stack state
80 */
81 define('SERVICES_JSON_IN_CMT', 5);
82
83 /**
84 * Behavior switch for Services_JSON::decode()
85 */
86 define('SERVICES_JSON_LOOSE_TYPE', 16);
87
88 /**
89 * Behavior switch for Services_JSON::decode()
90 */
91 define('SERVICES_JSON_SUPPRESS_ERRORS', 32);
92
93 /**
94  * Converts to and from JSON format.
95  *
96  * Brief example of use:
97  *
98  * <code>
99  * // create a new instance of Services_JSON
100  * $json = new Services_JSON();
101  *
102  * // convert a complexe value to JSON notation, and send it to the browser
103  * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4)));
104  * $output = $json->encode($value);
105  *
106  * print($output);
107  * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]]
108  *
109  * // accept incoming POST data, assumed to be in JSON notation
110  * $input = file_get_contents('php://input', 1000000);
111  * $value = $json->decode($input);
112  * </code>
113  *
114  * @addtogroup API
115  */
116 class Services_JSON
117 {
118    /**
119     * constructs a new JSON instance
120     *
121     * @param    int     $use    object behavior flags; combine with boolean-OR
122     *
123     *                           possible values:
124     *                           - SERVICES_JSON_LOOSE_TYPE:  loose typing.
125     *                                   "{...}" syntax creates associative arrays
126     *                                   instead of objects in decode().
127     *                           - SERVICES_JSON_SUPPRESS_ERRORS:  error suppression.
128     *                                   Values which can't be encoded (e.g. resources)
129     *                                   appear as NULL instead of throwing errors.
130     *                                   By default, a deeply-nested resource will
131     *                                   bubble up with an error, so all return values
132     *                                   from encode() should be checked with isError()
133     */
134     function Services_JSON($use = 0)
135     {
136         $this->use = $use;
137     }
138
139    /**
140     * convert a string from one UTF-16 char to one UTF-8 char
141     *
142     * Normally should be handled by mb_convert_encoding, but
143     * provides a slower PHP-only method for installations
144     * that lack the multibye string extension.
145     *
146     * @param    string  $utf16  UTF-16 character
147     * @return   string  UTF-8 character
148     * @access   private
149     */
150     function utf162utf8($utf16)
151     {
152         // oh please oh please oh please oh please oh please
153         if(function_exists('mb_convert_encoding')) {
154             return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
155         }
156
157         $bytes = (ord($utf16{0}) << 8) | ord($utf16{1});
158
159         switch(true) {
160             case ((0x7F & $bytes) == $bytes):
161                 // this case should never be reached, because we are in ASCII range
162                 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
163                 return chr(0x7F & $bytes);
164
165             case (0x07FF & $bytes) == $bytes:
166                 // return a 2-byte UTF-8 character
167                 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
168                 return chr(0xC0 | (($bytes >> 6) & 0x1F))
169                      . chr(0x80 | ($bytes & 0x3F));
170
171             case (0xFFFF & $bytes) == $bytes:
172                 // return a 3-byte UTF-8 character
173                 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
174                 return chr(0xE0 | (($bytes >> 12) & 0x0F))
175                      . chr(0x80 | (($bytes >> 6) & 0x3F))
176                      . chr(0x80 | ($bytes & 0x3F));
177         }
178
179         // ignoring UTF-32 for now, sorry
180         return '';
181     }
182
183    /**
184     * convert a string from one UTF-8 char to one UTF-16 char
185     *
186     * Normally should be handled by mb_convert_encoding, but
187     * provides a slower PHP-only method for installations
188     * that lack the multibye string extension.
189     *
190     * @param    string  $utf8   UTF-8 character
191     * @return   string  UTF-16 character
192     * @access   private
193     */
194     function utf82utf16($utf8)
195     {
196         // oh please oh please oh please oh please oh please
197         if(function_exists('mb_convert_encoding')) {
198             return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
199         }
200
201         switch(strlen($utf8)) {
202             case 1:
203                 // this case should never be reached, because we are in ASCII range
204                 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
205                 return $utf8;
206
207             case 2:
208                 // return a UTF-16 character from a 2-byte UTF-8 char
209                 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
210                 return chr(0x07 & (ord($utf8{0}) >> 2))
211                      . chr((0xC0 & (ord($utf8{0}) << 6))
212                          | (0x3F & ord($utf8{1})));
213
214             case 3:
215                 // return a UTF-16 character from a 3-byte UTF-8 char
216                 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
217                 return chr((0xF0 & (ord($utf8{0}) << 4))
218                          | (0x0F & (ord($utf8{1}) >> 2)))
219                      . chr((0xC0 & (ord($utf8{1}) << 6))
220                          | (0x7F & ord($utf8{2})));
221         }
222
223         // ignoring UTF-32 for now, sorry
224         return '';
225     }
226
227    /**
228     * encodes an arbitrary variable into JSON format
229     *
230     * @param    mixed   $var    any number, boolean, string, array, or object to be encoded.
231     *                           see argument 1 to Services_JSON() above for array-parsing behavior.
232     *                           if var is a strng, note that encode() always expects it
233     *                           to be in ASCII or UTF-8 format!
234     * @param    bool    $pretty    pretty-print output with indents and newlines
235     *
236     * @return   mixed   JSON string representation of input var or an error if a problem occurs
237     * @access   public
238     */
239     function encode($var, $pretty=false)
240     {
241         $this->indent = 0;
242         $this->pretty = $pretty;
243         $this->nameValSeparator = $pretty ? ': ' : ':';
244         return $this->encode2($var);
245     }
246
247    /**
248     * encodes an arbitrary variable into JSON format
249     *
250     * @param    mixed   $var    any number, boolean, string, array, or object to be encoded.
251     *                           see argument 1 to Services_JSON() above for array-parsing behavior.
252     *                           if var is a strng, note that encode() always expects it
253     *                           to be in ASCII or UTF-8 format!
254     *
255     * @return   mixed   JSON string representation of input var or an error if a problem occurs
256     * @access   private
257     */
258     function encode2($var)
259     {
260         if ($this->pretty) { 
261             $close = "\n" . str_repeat("\t", $this->indent);
262             $open = $close . "\t";
263             $mid = ',' . $open;
264         }
265         else {
266             $open = $close = '';
267             $mid = ',';
268         }
269
270         switch (gettype($var)) {
271             case 'boolean':
272                 return $var ? 'true' : 'false';
273
274             case 'NULL':
275                 return 'null';
276
277             case 'integer':
278                 return (int) $var;
279
280             case 'double':
281             case 'float':
282                 return (float) $var;
283
284             case 'string':
285                 // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
286                 $ascii = '';
287                 $strlen_var = strlen($var);
288
289                /*
290                 * Iterate over every character in the string,
291                 * escaping with a slash or encoding to UTF-8 where necessary
292                 */
293                 for ($c = 0; $c < $strlen_var; ++$c) {
294
295                     $ord_var_c = ord($var{$c});
296
297                     switch (true) {
298                         case $ord_var_c == 0x08:
299                             $ascii .= '\b';
300                             break;
301                         case $ord_var_c == 0x09:
302                             $ascii .= '\t';
303                             break;
304                         case $ord_var_c == 0x0A:
305                             $ascii .= '\n';
306                             break;
307                         case $ord_var_c == 0x0C:
308                             $ascii .= '\f';
309                             break;
310                         case $ord_var_c == 0x0D:
311                             $ascii .= '\r';
312                             break;
313
314                         case $ord_var_c == 0x22:
315                         case $ord_var_c == 0x2F:
316                         case $ord_var_c == 0x5C:
317                             // double quote, slash, slosh
318                             $ascii .= '\\'.$var{$c};
319                             break;
320
321                         case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
322                             // characters U-00000000 - U-0000007F (same as ASCII)
323                             $ascii .= $var{$c};
324                             break;
325
326                         case (($ord_var_c & 0xE0) == 0xC0):
327                             // characters U-00000080 - U-000007FF, mask 110XXXXX
328                             // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
329                             $char = pack('C*', $ord_var_c, ord($var{$c + 1}));
330                             $c += 1;
331                             $utf16 = $this->utf82utf16($char);
332                             $ascii .= sprintf('\u%04s', bin2hex($utf16));
333                             break;
334
335                         case (($ord_var_c & 0xF0) == 0xE0):
336                             // characters U-00000800 - U-0000FFFF, mask 1110XXXX
337                             // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
338                             $char = pack('C*', $ord_var_c,
339                                          ord($var{$c + 1}),
340                                          ord($var{$c + 2}));
341                             $c += 2;
342                             $utf16 = $this->utf82utf16($char);
343                             $ascii .= sprintf('\u%04s', bin2hex($utf16));
344                             break;
345
346                         case (($ord_var_c & 0xF8) == 0xF0):
347                             // characters U-00010000 - U-001FFFFF, mask 11110XXX
348                             // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
349                             $char = pack('C*', $ord_var_c,
350                                          ord($var{$c + 1}),
351                                          ord($var{$c + 2}),
352                                          ord($var{$c + 3}));
353                             $c += 3;
354                             $utf16 = $this->utf82utf16($char);
355                             $ascii .= sprintf('\u%04s', bin2hex($utf16));
356                             break;
357
358                         case (($ord_var_c & 0xFC) == 0xF8):
359                             // characters U-00200000 - U-03FFFFFF, mask 111110XX
360                             // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
361                             $char = pack('C*', $ord_var_c,
362                                          ord($var{$c + 1}),
363                                          ord($var{$c + 2}),
364                                          ord($var{$c + 3}),
365                                          ord($var{$c + 4}));
366                             $c += 4;
367                             $utf16 = $this->utf82utf16($char);
368                             $ascii .= sprintf('\u%04s', bin2hex($utf16));
369                             break;
370
371                         case (($ord_var_c & 0xFE) == 0xFC):
372                             // characters U-04000000 - U-7FFFFFFF, mask 1111110X
373                             // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
374                             $char = pack('C*', $ord_var_c,
375                                          ord($var{$c + 1}),
376                                          ord($var{$c + 2}),
377                                          ord($var{$c + 3}),
378                                          ord($var{$c + 4}),
379                                          ord($var{$c + 5}));
380                             $c += 5;
381                             $utf16 = $this->utf82utf16($char);
382                             $ascii .= sprintf('\u%04s', bin2hex($utf16));
383                             break;
384                     }
385                 }
386
387                 return '"'.$ascii.'"';
388
389             case 'array':
390                /*
391                 * As per JSON spec if any array key is not an integer
392                 * we must treat the the whole array as an object. We
393                 * also try to catch a sparsely populated associative
394                 * array with numeric keys here because some JS engines
395                 * will create an array with empty indexes up to
396                 * max_index which can cause memory issues and because
397                 * the keys, which may be relevant, will be remapped
398                 * otherwise.
399                 *
400                 * As per the ECMA and JSON specification an object may
401                 * have any string as a property. Unfortunately due to
402                 * a hole in the ECMA specification if the key is a
403                 * ECMA reserved word or starts with a digit the
404                 * parameter is only accessible using ECMAScript's
405                 * bracket notation.
406                 */
407
408                 // treat as a JSON object
409                 if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
410                     $this->indent++;
411                     $properties = array_map(array($this, 'name_value'),
412                                             array_keys($var),
413                                             array_values($var));
414                     $this->indent--;
415
416                     foreach($properties as $property) {
417                         if(Services_JSON::isError($property)) {
418                             return $property;
419                         }
420                     }
421
422                     return '{' . $open . join($mid, $properties) . $close . '}';
423                 }
424
425                 // treat it like a regular array
426                 $this->indent++;
427                 $elements = array_map(array($this, 'encode2'), $var);
428                 $this->indent--;
429                 
430                 foreach($elements as $element) {
431                     if(Services_JSON::isError($element)) {
432                         return $element;
433                     }
434                 }
435
436                 return '[' . $open . join($mid, $elements) . $close . ']';
437
438             case 'object':
439                 $vars = get_object_vars($var);
440
441                 $this->indent++;
442                 $properties = array_map(array($this, 'name_value'),
443                                         array_keys($vars),
444                                         array_values($vars));
445                 $this->indent--;
446
447                 foreach($properties as $property) {
448                     if(Services_JSON::isError($property)) {
449                         return $property;
450                     }
451                 }
452
453                 return '{' . $open . join($mid, $properties) . $close . '}';
454
455             default:
456                 return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
457                     ? 'null'
458                     : new Services_JSON_Error(gettype($var)." can not be encoded as JSON string");
459         }
460     }
461
462    /**
463     * array-walking function for use in generating JSON-formatted name-value pairs
464     *
465     * @param    string  $name   name of key to use
466     * @param    mixed   $value  reference to an array element to be encoded
467     *
468     * @return   string  JSON-formatted name-value pair, like '"name":value'
469     * @access   private
470     */
471     function name_value($name, $value)
472     {
473         $encoded_value = $this->encode2($value);
474
475         if(Services_JSON::isError($encoded_value)) {
476             return $encoded_value;
477         }
478
479         return $this->encode2(strval($name)) . $this->nameValSeparator . $encoded_value;
480     }
481
482    /**
483     * reduce a string by removing leading and trailing comments and whitespace
484     *
485     * @param    $str    string      string value to strip of comments and whitespace
486     *
487     * @return   string  string value stripped of comments and whitespace
488     * @access   private
489     */
490     function reduce_string($str)
491     {
492         $str = preg_replace(array(
493
494                 // eliminate single line comments in '// ...' form
495                 '#^\s*//(.+)$#m',
496
497                 // eliminate multi-line comments in '/* ... */' form, at start of string
498                 '#^\s*/\*(.+)\*/#Us',
499
500                 // eliminate multi-line comments in '/* ... */' form, at end of string
501                 '#/\*(.+)\*/\s*$#Us'
502
503             ), '', $str);
504
505         // eliminate extraneous space
506         return trim($str);
507     }
508
509    /**
510     * decodes a JSON string into appropriate variable
511     *
512     * @param    string  $str    JSON-formatted string
513     *
514     * @return   mixed   number, boolean, string, array, or object
515     *                   corresponding to given JSON input string.
516     *                   See argument 1 to Services_JSON() above for object-output behavior.
517     *                   Note that decode() always returns strings
518     *                   in ASCII or UTF-8 format!
519     * @access   public
520     */
521     function decode($str)
522     {
523         $str = $this->reduce_string($str);
524
525         switch (strtolower($str)) {
526             case 'true':
527                 return true;
528
529             case 'false':
530                 return false;
531
532             case 'null':
533                 return null;
534
535             default:
536                 $m = array();
537
538                 if (is_numeric($str)) {
539                     // Lookie-loo, it's a number
540
541                     // This would work on its own, but I'm trying to be
542                     // good about returning integers where appropriate:
543                     // return (float)$str;
544
545                     // Return float or int, as appropriate
546                     return ((float)$str == (integer)$str)
547                         ? (integer)$str
548                         : (float)$str;
549
550                 } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) {
551                     // STRINGS RETURNED IN UTF-8 FORMAT
552                     $delim = substr($str, 0, 1);
553                     $chrs = substr($str, 1, -1);
554                     $utf8 = '';
555                     $strlen_chrs = strlen($chrs);
556
557                     for ($c = 0; $c < $strlen_chrs; ++$c) {
558
559                         $substr_chrs_c_2 = substr($chrs, $c, 2);
560                         $ord_chrs_c = ord($chrs{$c});
561
562                         switch (true) {
563                             case $substr_chrs_c_2 == '\b':
564                                 $utf8 .= chr(0x08);
565                                 ++$c;
566                                 break;
567                             case $substr_chrs_c_2 == '\t':
568                                 $utf8 .= chr(0x09);
569                                 ++$c;
570                                 break;
571                             case $substr_chrs_c_2 == '\n':
572                                 $utf8 .= chr(0x0A);
573                                 ++$c;
574                                 break;
575                             case $substr_chrs_c_2 == '\f':
576                                 $utf8 .= chr(0x0C);
577                                 ++$c;
578                                 break;
579                             case $substr_chrs_c_2 == '\r':
580                                 $utf8 .= chr(0x0D);
581                                 ++$c;
582                                 break;
583
584                             case $substr_chrs_c_2 == '\\"':
585                             case $substr_chrs_c_2 == '\\\'':
586                             case $substr_chrs_c_2 == '\\\\':
587                             case $substr_chrs_c_2 == '\\/':
588                                 if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
589                                    ($delim == "'" && $substr_chrs_c_2 != '\\"')) {
590                                     $utf8 .= $chrs{++$c};
591                                 }
592                                 break;
593
594                             case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)):
595                                 // single, escaped unicode character
596                                 $utf16 = chr(hexdec(substr($chrs, ($c + 2), 2)))
597                                        . chr(hexdec(substr($chrs, ($c + 4), 2)));
598                                 $utf8 .= $this->utf162utf8($utf16);
599                                 $c += 5;
600                                 break;
601
602                             case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
603                                 $utf8 .= $chrs{$c};
604                                 break;
605
606                             case ($ord_chrs_c & 0xE0) == 0xC0:
607                                 // characters U-00000080 - U-000007FF, mask 110XXXXX
608                                 //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
609                                 $utf8 .= substr($chrs, $c, 2);
610                                 ++$c;
611                                 break;
612
613                             case ($ord_chrs_c & 0xF0) == 0xE0:
614                                 // characters U-00000800 - U-0000FFFF, mask 1110XXXX
615                                 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
616                                 $utf8 .= substr($chrs, $c, 3);
617                                 $c += 2;
618                                 break;
619
620                             case ($ord_chrs_c & 0xF8) == 0xF0:
621                                 // characters U-00010000 - U-001FFFFF, mask 11110XXX
622                                 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
623                                 $utf8 .= substr($chrs, $c, 4);
624                                 $c += 3;
625                                 break;
626
627                             case ($ord_chrs_c & 0xFC) == 0xF8:
628                                 // characters U-00200000 - U-03FFFFFF, mask 111110XX
629                                 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
630                                 $utf8 .= substr($chrs, $c, 5);
631                                 $c += 4;
632                                 break;
633
634                             case ($ord_chrs_c & 0xFE) == 0xFC:
635                                 // characters U-04000000 - U-7FFFFFFF, mask 1111110X
636                                 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
637                                 $utf8 .= substr($chrs, $c, 6);
638                                 $c += 5;
639                                 break;
640
641                         }
642
643                     }
644
645                     return $utf8;
646
647                 } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) {
648                     // array, or object notation
649
650                     if ($str{0} == '[') {
651                         $stk = array(SERVICES_JSON_IN_ARR);
652                         $arr = array();
653                     } else {
654                         if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
655                             $stk = array(SERVICES_JSON_IN_OBJ);
656                             $obj = array();
657                         } else {
658                             $stk = array(SERVICES_JSON_IN_OBJ);
659                             $obj = new stdClass();
660                         }
661                     }
662
663                     array_push($stk, array('what'  => SERVICES_JSON_SLICE,
664                                            'where' => 0,
665                                            'delim' => false));
666
667                     $chrs = substr($str, 1, -1);
668                     $chrs = $this->reduce_string($chrs);
669
670                     if ($chrs == '') {
671                         if (reset($stk) == SERVICES_JSON_IN_ARR) {
672                             return $arr;
673
674                         } else {
675                             return $obj;
676
677                         }
678                     }
679
680                     //print("\nparsing {$chrs}\n");
681
682                     $strlen_chrs = strlen($chrs);
683
684                     for ($c = 0; $c <= $strlen_chrs; ++$c) {
685
686                         $top = end($stk);
687                         $substr_chrs_c_2 = substr($chrs, $c, 2);
688
689                         if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) {
690                             // found a comma that is not inside a string, array, etc.,
691                             // OR we've reached the end of the character list
692                             $slice = substr($chrs, $top['where'], ($c - $top['where']));
693                             array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false));
694                             //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
695
696                             if (reset($stk) == SERVICES_JSON_IN_ARR) {
697                                 // we are in an array, so just push an element onto the stack
698                                 array_push($arr, $this->decode($slice));
699
700                             } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
701                                 // we are in an object, so figure
702                                 // out the property name and set an
703                                 // element in an associative array,
704                                 // for now
705                                 $parts = array();
706                                 
707                                 if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
708                                     // "name":value pair
709                                     $key = $this->decode($parts[1]);
710                                     $val = $this->decode($parts[2]);
711
712                                     if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
713                                         $obj[$key] = $val;
714                                     } else {
715                                         $obj->$key = $val;
716                                     }
717                                 } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
718                                     // name:value pair, where name is unquoted
719                                     $key = $parts[1];
720                                     $val = $this->decode($parts[2]);
721
722                                     if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
723                                         $obj[$key] = $val;
724                                     } else {
725                                         $obj->$key = $val;
726                                     }
727                                 }
728
729                             }
730
731                         } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) {
732                             // found a quote, and we are not inside a string
733                             array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c}));
734                             //print("Found start of string at {$c}\n");
735
736                         } elseif (($chrs{$c} == $top['delim']) &&
737                                  ($top['what'] == SERVICES_JSON_IN_STR) &&
738                                  (($chrs{$c - 1} != '\\') ||
739                                  ($chrs{$c - 1} == '\\' && $chrs{$c - 2} == '\\'))) {
740                             // found a quote, we're in a string, and it's not escaped
741                             array_pop($stk);
742                             //print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");
743
744                         } elseif (($chrs{$c} == '[') &&
745                                  in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
746                             // found a left-bracket, and we are in an array, object, or slice
747                             array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false));
748                             //print("Found start of array at {$c}\n");
749
750                         } elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) {
751                             // found a right-bracket, and we're in an array
752                             array_pop($stk);
753                             //print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
754
755                         } elseif (($chrs{$c} == '{') &&
756                                  in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
757                             // found a left-brace, and we are in an array, object, or slice
758                             array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false));
759                             //print("Found start of object at {$c}\n");
760
761                         } elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) {
762                             // found a right-brace, and we're in an object
763                             array_pop($stk);
764                             //print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
765
766                         } elseif (($substr_chrs_c_2 == '/*') &&
767                                  in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
768                             // found a comment start, and we are in an array, object, or slice
769                             array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false));
770                             $c++;
771                             //print("Found start of comment at {$c}\n");
772
773                         } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) {
774                             // found a comment end, and we're in one now
775                             array_pop($stk);
776                             $c++;
777
778                             for ($i = $top['where']; $i <= $c; ++$i)
779                                 $chrs = substr_replace($chrs, ' ', $i, 1);
780
781                             //print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
782
783                         }
784
785                     }
786
787                     if (reset($stk) == SERVICES_JSON_IN_ARR) {
788                         return $arr;
789
790                     } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
791                         return $obj;
792
793                     }
794
795                 }
796         }
797     }
798
799     /**
800      * @todo Ultimately, this should just call PEAR::isError()
801      */
802     function isError($data, $code = null)
803     {
804         if (class_exists('pear')) {
805             return PEAR::isError($data, $code);
806         } elseif (is_object($data) && (get_class($data) == 'services_json_error' ||
807                                  is_subclass_of($data, 'services_json_error'))) {
808             return true;
809         }
810
811         return false;
812     }
813 }
814
815 if (class_exists('PEAR_Error')) {
816
817     /**
818      * @addtogroup API
819      */
820     class Services_JSON_Error extends PEAR_Error
821     {
822         function Services_JSON_Error($message = 'unknown error', $code = null,
823                                      $mode = null, $options = null, $userinfo = null)
824         {
825             parent::PEAR_Error($message, $code, $mode, $options, $userinfo);
826         }
827     }
828
829 } else {
830
831     /**
832      * @todo Ultimately, this class shall be descended from PEAR_Error
833      * @addtogroup API
834      */
835     class Services_JSON_Error
836     {
837         function Services_JSON_Error($message = 'unknown error', $code = null,
838                                      $mode = null, $options = null, $userinfo = null)
839         {
840
841         }
842     }
843
844 }
845     
846