a9f769d561c9e39b44cc7cb3b60862b08688169a
[pear] / Services / JSON.php
1 <?php
2 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
3 /**
4  * Converts to and from JSON format.
5  *
6  * JSON (JavaScript Object Notation) is a lightweight data-interchange
7  * format. It is easy for humans to read and write. It is easy for machines
8  * to parse and generate. It is based on a subset of the JavaScript
9  * Programming Language, Standard ECMA-262 3rd Edition - December 1999.
10  * This feature can also be found in  Python. JSON is a text format that is
11  * completely language independent but uses conventions that are familiar
12  * to programmers of the C-family of languages, including C, C++, C#, Java,
13  * JavaScript, Perl, TCL, and many others. These properties make JSON an
14  * ideal data-interchange language.
15  *
16  * This package provides a simple encoder and decoder for JSON notation. It
17  * is intended for use with client-side Javascript applications that make
18  * use of HTTPRequest to perform server communication functions - data can
19  * be encoded into JSON notation for use in a client-side javascript, or
20  * decoded from incoming Javascript requests. JSON format is native to
21  * Javascript, and can be directly eval()'ed with no further parsing
22  * overhead
23  *
24  * All strings should be in ASCII or UTF-8 format!
25  *
26  * LICENSE: Redistribution and use in source and binary forms, with or
27  * without modification, are permitted provided that the following
28  * conditions are met: Redistributions of source code must retain the
29  * above copyright notice, this list of conditions and the following
30  * disclaimer. Redistributions in binary form must reproduce the above
31  * copyright notice, this list of conditions and the following disclaimer
32  * in the documentation and/or other materials provided with the
33  * distribution.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
37  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
38  * NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
39  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
40  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
41  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
42  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
43  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
44  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
45  * DAMAGE.
46  *
47  * @category
48  * @package     Services_JSON
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 307804 2011-01-28 00:16:42Z alan_k $
54  * @license     http://www.opensource.org/licenses/bsd-license.php
55  * @link        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  * Behavior switch for Services_JSON::decode()
95  */
96 define('SERVICES_JSON_USE_TO_JSON', 64);
97
98 /**
99  * Converts to and from JSON format.
100  *
101  * Brief example of use:
102  *
103  * <code>
104  * // create a new instance of Services_JSON
105  * $json = new Services_JSON();
106  *
107  * // convert a complexe value to JSON notation, and send it to the browser
108  * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4)));
109  * $output = $json->encode($value);
110  *
111  * print($output);
112  * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]]
113  *
114  * // accept incoming POST data, assumed to be in JSON notation
115  * $input = file_get_contents('php://input', 1000000);
116  * $value = $json->decode($input);
117  * </code>
118  */
119 class Services_JSON
120 {
121    /**
122     * constructs a new JSON instance
123     *
124     * @param    int     $use    object behavior flags; combine with boolean-OR
125     *
126     *                           possible values:
127     *                           - SERVICES_JSON_LOOSE_TYPE:  loose typing.
128     *                                   "{...}" syntax creates associative arrays
129     *                                   instead of objects in decode().
130     *                           - SERVICES_JSON_SUPPRESS_ERRORS:  error suppression.
131     *                                   Values which can't be encoded (e.g. resources)
132     *                                   appear as NULL instead of throwing errors.
133     *                                   By default, a deeply-nested resource will
134     *                                   bubble up with an error, so all return values
135     *                                   from encode() should be checked with isError()
136     *                           - SERVICES_JSON_USE_TO_JSON:  call toJSON when serializing objects
137     *                                   It serializes the return value from the toJSON call rather 
138     *                                   than the object it'self,  toJSON can return associative arrays, 
139     *                                   strings or numbers, if you return an object, make sure it does
140     *                                   not have a toJSON method, otherwise an error will occur.
141     */
142     function __construct($use = 0)
143     {
144         $this->use = $use;
145         $this->_mb_strlen            = function_exists('mb_strlen');
146         $this->_mb_convert_encoding  = function_exists('mb_convert_encoding');
147         $this->_mb_substr            = function_exists('mb_substr');
148     }
149     // private - cache the mbstring lookup results..
150     var $_mb_strlen = false;
151     var $_mb_substr = false;
152     var $_mb_convert_encoding = false;
153     
154     // tab and crlf are used by stringfy to produce pretty JSON.
155     var $_tab = '';
156     var $_crlf = '';
157     var $_indent = 0;
158    /**
159     * convert a string from one UTF-16 char to one UTF-8 char
160     *
161     * Normally should be handled by mb_convert_encoding, but
162     * provides a slower PHP-only method for installations
163     * that lack the multibye string extension.
164     *
165     * @param    string  $utf16  UTF-16 character
166     * @return   string  UTF-8 character
167     * @access   private
168     */
169     function utf162utf8($utf16)
170     {
171         // oh please oh please oh please oh please oh please
172         if($this->_mb_convert_encoding) {
173             return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
174         }
175
176         $bytes = (ord($utf16[0]) << 8) | ord($utf16[1]);
177
178         switch(true) {
179             case ((0x7F & $bytes) == $bytes):
180                 // this case should never be reached, because we are in ASCII range
181                 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
182                 return chr(0x7F & $bytes);
183
184             case (0x07FF & $bytes) == $bytes:
185                 // return a 2-byte UTF-8 character
186                 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
187                 return chr(0xC0 | (($bytes >> 6) & 0x1F))
188                      . chr(0x80 | ($bytes & 0x3F));
189
190             case (0xFFFF & $bytes) == $bytes:
191                 // return a 3-byte UTF-8 character
192                 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
193                 return chr(0xE0 | (($bytes >> 12) & 0x0F))
194                      . chr(0x80 | (($bytes >> 6) & 0x3F))
195                      . chr(0x80 | ($bytes & 0x3F));
196         }
197
198         // ignoring UTF-32 for now, sorry
199         return '';
200     }
201
202    /**
203     * convert a string from one UTF-8 char to one UTF-16 char
204     *
205     * Normally should be handled by mb_convert_encoding, but
206     * provides a slower PHP-only method for installations
207     * that lack the multibye string extension.
208     *
209     * @param    string  $utf8   UTF-8 character
210     * @return   string  UTF-16 character
211     * @access   private
212     */
213     function utf82utf16($utf8)
214     {
215         // oh please oh please oh please oh please oh please
216         if($this->_mb_convert_encoding) {
217             return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
218         }
219
220         switch($this->strlen8($utf8)) {
221             case 1:
222                 // this case should never be reached, because we are in ASCII range
223                 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
224                 return $utf8;
225
226             case 2:
227                 // return a UTF-16 character from a 2-byte UTF-8 char
228                 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
229                 return chr(0x07 & (ord($utf8[0]) >> 2))
230                      . chr((0xC0 & (ord($utf8[0]) << 6))
231                          | (0x3F & ord($utf8[1])));
232
233             case 3:
234                 // return a UTF-16 character from a 3-byte UTF-8 char
235                 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
236                 return chr((0xF0 & (ord($utf8[0]) << 4))
237                          | (0x0F & (ord($utf8[1]) >> 2)))
238                      . chr((0xC0 & (ord($utf8[1]) << 6))
239                          | (0x7F & ord($utf8[2])));
240         }
241
242         // ignoring UTF-32 for now, sorry
243         return '';
244     }
245
246     
247    /**
248     * stringfy an arbitrary variable into JSON format (and sends JSON Header)
249     * UNSAFE - does not send HTTP headers (to be compatible with Javsacript Spec)
250     *
251     * @param    mixed   $var    any number, boolean, string, array, or object to be encoded.
252     *                           see argument 1 to Services_JSON() above for array-parsing behavior.
253     *                           if var is a strng, note that encode() always expects it
254     *                           to be in ASCII or UTF-8 format!
255     * @param    mixed   $replacer    NOT SUPPORTED YET.
256     * @param    number|string   $space 
257     *                           an optional parameter that specifies the indentation
258     *                           of nested structures. If it is omitted, the text will
259     *                           be packed without extra whitespace. If it is a number,
260     *                           it will specify the number of spaces to indent at each
261     *                           level. If it is a string (such as '\t' or '&nbsp;'),
262     *                           it contains the characters used to indent at each level.
263     *
264     * @return   mixed   JSON string representation of input var or an error if a problem occurs
265     * @access   public
266     */
267     static function stringify($var, $replacer=false, $space=false)
268     {
269         //header('Content-type: application/json');
270         $s = new Services_JSON(SERVICES_JSON_USE_TO_JSON);
271         
272         $s->_tab = is_numeric($space) ? str_repeat(' ', $space) : $space;
273         $s->_crlf = "\n";
274         $s->_indent = 0;
275         return  $s->encodeUnsafe($var);
276         
277     }
278     /**
279     * encodes an arbitrary variable into JSON format (and sends JSON Header)
280     *
281     * @param    mixed   $var    any number, boolean, string, array, or object to be encoded.
282     *                           see argument 1 to Services_JSON() above for array-parsing behavior.
283     *                           if var is a strng, note that encode() always expects it
284     *                           to be in ASCII or UTF-8 format!
285     *
286     * @return   mixed   JSON string representation of input var or an error if a problem occurs
287     * @access   public
288     */
289     function encode($var)
290     {
291         header('Content-type: text/javascript'); // changed to make debugging easier.
292         return $this->encodeUnsafe($var);
293     }
294     /**
295     * encodes an arbitrary variable into JSON format without JSON Header - warning - may allow XSS!!!!)
296     *
297     * @param    mixed   $var    any number, boolean, string, array, or object to be encoded.
298     *                           see argument 1 to Services_JSON() above for array-parsing behavior.
299     *                           if var is a strng, note that encode() always expects it
300     *                           to be in ASCII or UTF-8 format!
301     *
302     * @return   mixed   JSON string representation of input var or an error if a problem occurs
303     * @access   public
304     */
305     function encodeUnsafe($var)
306     {
307         // see bug #16908 - regarding numeric locale printing
308         $lc = setlocale(LC_NUMERIC, 0);
309         setlocale(LC_NUMERIC, 'C');
310         $ret = $this->_encode($var);
311         setlocale(LC_NUMERIC, $lc);
312         return $ret;
313         
314     }
315     /**
316     * PRIVATE CODE that does the work of encodes an arbitrary variable into JSON format 
317     *
318     * @param    mixed   $var    any number, boolean, string, array, or object to be encoded.
319     *                           see argument 1 to Services_JSON() above for array-parsing behavior.
320     *                           if var is a strng, note that encode() always expects it
321     *                           to be in ASCII or UTF-8 format!
322     *
323     * @return   mixed   JSON string representation of input var or an error if a problem occurs
324     * @access   public
325     */
326     function _encode($var) 
327     {
328         $ind = str_repeat($this->_tab, $this->_indent);
329         $indx = $ind . $this->_tab; 
330         
331         switch (gettype($var)) {
332             case 'boolean':
333                 return $var ? 'true' : 'false';
334
335             case 'NULL':
336                 return 'null';
337
338             case 'integer':
339                 return (int) $var;
340
341             case 'double':
342             case 'float':
343                 return  (float) $var;
344
345             case 'string':
346                 // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
347                 $ascii = '';
348                 $strlen_var = $this->strlen8($var);
349
350                /*
351                 * Iterate over every character in the string,
352                 * escaping with a slash or encoding to UTF-8 where necessary
353                 */
354                 for ($c = 0; $c < $strlen_var; ++$c) {
355
356                     $ord_var_c = ord($var[$c]);
357
358                     switch (true) {
359                         case $ord_var_c == 0x08:
360                             $ascii .= '\b';
361                             break;
362                         case $ord_var_c == 0x09:
363                             $ascii .= '\t';
364                             break;
365                         case $ord_var_c == 0x0A:
366                             $ascii .= '\n';
367                             break;
368                         case $ord_var_c == 0x0C:
369                             $ascii .= '\f';
370                             break;
371                         case $ord_var_c == 0x0D:
372                             $ascii .= '\r';
373                             break;
374
375                         case $ord_var_c == 0x22:
376                         case $ord_var_c == 0x2F:
377                         case $ord_var_c == 0x5C:
378                             // double quote, slash, slosh
379                             $ascii .= '\\'.$var[$c];
380                             break;
381
382                         case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
383                             // characters U-00000000 - U-0000007F (same as ASCII)
384                             $ascii .= $var[$c];
385                             break;
386
387                         case (($ord_var_c & 0xE0) == 0xC0):
388                             // characters U-00000080 - U-000007FF, mask 110XXXXX
389                             // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
390                             if ($c+1 >= $strlen_var) {
391                                 $c += 1;
392                                 $ascii .= '?';
393                                 break;
394                             }
395                             
396                             $char = pack('C*', $ord_var_c, ord($var[$c + 1]));
397                             $c += 1;
398                             $utf16 = $this->utf82utf16($char);
399                             $ascii .= sprintf('\u%04s', bin2hex($utf16));
400                             break;
401
402                         case (($ord_var_c & 0xF0) == 0xE0):
403                             if ($c+2 >= $strlen_var) {
404                                 $c += 2;
405                                 $ascii .= '?';
406                                 break;
407                             }
408                             // characters U-00000800 - U-0000FFFF, mask 1110XXXX
409                             // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
410                             $char = pack('C*', $ord_var_c,
411                                          @ord($var[$c + 1]),
412                                          @ord($var[$c + 2]));
413                             $c += 2;
414                             $utf16 = $this->utf82utf16($char);
415                             $ascii .= sprintf('\u%04s', bin2hex($utf16));
416                             break;
417
418                         case (($ord_var_c & 0xF8) == 0xF0):
419                             if ($c+3 >= $strlen_var) {
420                                 $c += 3;
421                                 $ascii .= '?';
422                                 break;
423                             }
424                             // characters U-00010000 - U-001FFFFF, mask 11110XXX
425                             // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
426                             $char = pack('C*', $ord_var_c,
427                                          ord($var[$c + 1]),
428                                          ord($var[$c + 2]),
429                                          ord($var[$c + 3]));
430                             $c += 3;
431                             $utf16 = $this->utf82utf16($char);
432                             $ascii .= sprintf('\u%04s', bin2hex($utf16));
433                             break;
434
435                         case (($ord_var_c & 0xFC) == 0xF8):
436                             // characters U-00200000 - U-03FFFFFF, mask 111110XX
437                             // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
438                             if ($c+4 >= $strlen_var) {
439                                 $c += 4;
440                                 $ascii .= '?';
441                                 break;
442                             }
443                             $char = pack('C*', $ord_var_c,
444                                          ord($var[$c + 1]),
445                                          ord($var[$c + 2]),
446                                          ord($var[$c + 3]),
447                                          ord($var[$c + 4]));
448                             $c += 4;
449                             $utf16 = $this->utf82utf16($char);
450                             $ascii .= sprintf('\u%04s', bin2hex($utf16));
451                             break;
452
453                         case (($ord_var_c & 0xFE) == 0xFC):
454                         if ($c+5 >= $strlen_var) {
455                                 $c += 5;
456                                 $ascii .= '?';
457                                 break;
458                             }
459                             // characters U-04000000 - U-7FFFFFFF, mask 1111110X
460                             // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
461                             $char = pack('C*', $ord_var_c,
462                                          ord($var[$c + 1]),
463                                          ord($var[$c + 2]),
464                                          ord($var[$c + 3]),
465                                          ord($var[$c + 4]),
466                                          ord($var[$c + 5]));
467                             $c += 5;
468                             $utf16 = $this->utf82utf16($char);
469                             $ascii .= sprintf('\u%04s', bin2hex($utf16));
470                             break;
471                     }
472                 }
473                 return  '"'.$ascii.'"';
474
475             case 'array':
476                /*
477                 * As per JSON spec if any array key is not an integer
478                 * we must treat the the whole array as an object. We
479                 * also try to catch a sparsely populated associative
480                 * array with numeric keys here because some JS engines
481                 * will create an array with empty indexes up to
482                 * max_index which can cause memory issues and because
483                 * the keys, which may be relevant, will be remapped
484                 * otherwise.
485                 *
486                 * As per the ECMA and JSON specification an object may
487                 * have any string as a property. Unfortunately due to
488                 * a hole in the ECMA specification if the key is a
489                 * ECMA reserved word or starts with a digit the
490                 * parameter is only accessible using ECMAScript's
491                 * bracket notation.
492                 */
493
494                 // treat as a JSON object
495                 if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
496                     $this->_indent++;
497                     $properties = array_map(array($this, 'name_value'),
498                                             array_keys($var),
499                                             array_values($var));
500                     $this->_indent--;
501                     foreach($properties as $property) {
502                         if(Services_JSON::isError($property)) {
503                             return $property;
504                         }
505                     }
506                     
507                     return "{" . $this->_crlf .  $indx .  
508                         join(",". $this->_crlf . $indx, $properties) . $this->_crlf .
509                         $ind."}";
510                     
511                 }
512
513                 // treat it like a regular array
514                 $this->_indent++;
515                 $elements = array_map(array($this, '_encode'), $var);
516                 $this->_indent--;
517                 
518                 foreach($elements as $element) {
519                     if(Services_JSON::isError($element)) {
520                         return $element;
521                     }
522                 }
523                 
524                 $pad = $this->_tab === '' ? '' : ' ';
525                 
526                 // short array, just show it on one line.
527                 if (strlen(join(',' . $pad, $elements)) < 30) {
528                     return '[' . join(',' . $pad, $elements) . ']';
529                 }
530                 
531                 return "[" . $this->_crlf .
532                     $indx .  join(",". $this->_crlf . $indx, $elements) . $this->_crlf .
533                     $ind . "]";
534
535             case 'object':
536             
537                 // support toJSON methods.
538                 if (($this->use & SERVICES_JSON_USE_TO_JSON) && method_exists($var, 'toJSON')) {
539                     // this may end up allowing unlimited recursion
540                     // so we check the return value to make sure it's not got the same method.
541                     $recode = $var->toJSON();
542                     
543                     if (method_exists($recode, 'toJSON')) {
544                         
545                         return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
546                         ? 'null'
547                         : new Services_JSON_Error(get_class($var).
548                             " toJSON returned an object with a toJSON method.");
549                             
550                     }
551                     
552                     return $this->_encode( $recode );
553                 } 
554                 
555                 $vars = get_object_vars($var);
556                 
557                 $this->_indent++;
558                 $properties = array_map(array($this, 'name_value'),
559                                         array_keys($vars),
560                                         array_values($vars));
561                 $this->_indent--;
562                 
563                 foreach($properties as $property) {
564                     if(Services_JSON::isError($property)) {
565                         return $property;
566                     }
567                 }
568                 
569                 return "{" . $this->_crlf .
570                     $indx .  join(",". $this->_crlf . $indx, $properties) . $this->_crlf .
571                     $ind . "}";
572                 
573             default:
574                 return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
575                     ? 'null'
576                     : new Services_JSON_Error(gettype($var)." can not be encoded as JSON string");
577         }
578     }
579
580    /**
581     * array-walking function for use in generating JSON-formatted name-value pairs
582     *
583     * @param    string  $name   name of key to use
584     * @param    mixed   $value  reference to an array element to be encoded
585     *
586     * @return   string  JSON-formatted name-value pair, like '"name":value'
587     * @access   private
588     */
589     function name_value($name, $value)
590     {
591         $encoded_value = $this->_encode($value);
592         
593         if(Services_JSON::isError($encoded_value)) {
594             return $encoded_value;
595         }
596         
597         $pad = $this->_tab === '' ? '' : ' ';
598         
599         return $this->_encode(strval($name)) . $pad . ':' . $pad . $encoded_value;
600     }
601
602    /**
603     * reduce a string by removing leading and trailing comments and whitespace
604     *
605     * @param    $str    string      string value to strip of comments and whitespace
606     *
607     * @return   string  string value stripped of comments and whitespace
608     * @access   private
609     */
610     function reduce_string($str)
611     {
612         $str = preg_replace(array(
613
614                 // eliminate single line comments in '// ...' form
615                 '#^\s*//(.+)$#m',
616
617                 // eliminate multi-line comments in '/* ... */' form, at start of string
618                 '#^\s*/\*(.+)\*/#Us',
619
620                 // eliminate multi-line comments in '/* ... */' form, at end of string
621                 '#/\*(.+)\*/\s*$#Us'
622
623             ), '', $str);
624
625         // eliminate extraneous space
626         return trim($str);
627     }
628
629    /**
630     * decodes a JSON string into appropriate variable
631     *
632     * @param    string  $str    JSON-formatted string
633     *
634     * @return   mixed   number, boolean, string, array, or object
635     *                   corresponding to given JSON input string.
636     *                   See argument 1 to Services_JSON() above for object-output behavior.
637     *                   Note that decode() always returns strings
638     *                   in ASCII or UTF-8 format!
639     * @access   public
640     */
641     function decode($str)
642     {
643         $str = $this->reduce_string($str);
644
645         switch (strtolower($str)) {
646             case 'true':
647                 return true;
648
649             case 'false':
650                 return false;
651
652             case 'null':
653                 return null;
654
655             default:
656                 $m = array();
657
658                 if (is_numeric($str)) {
659                     // Lookie-loo, it's a number
660
661                     // This would work on its own, but I'm trying to be
662                     // good about returning integers where appropriate:
663                     // return (float)$str;
664
665                     // Return float or int, as appropriate
666                     return ((float)$str == (integer)$str)
667                         ? (integer)$str
668                         : (float)$str;
669
670                 } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) {
671                     // STRINGS RETURNED IN UTF-8 FORMAT
672                     $delim = $this->substr8($str, 0, 1);
673                     $chrs = $this->substr8($str, 1, -1);
674                     $utf8 = '';
675                     $strlen_chrs = $this->strlen8($chrs);
676
677                     for ($c = 0; $c < $strlen_chrs; ++$c) {
678
679                         $substr_chrs_c_2 = $this->substr8($chrs, $c, 2);
680                         $ord_chrs_c = ord($chrs[$c]);
681
682                         switch (true) {
683                             case $substr_chrs_c_2 == '\b':
684                                 $utf8 .= chr(0x08);
685                                 ++$c;
686                                 break;
687                             case $substr_chrs_c_2 == '\t':
688                                 $utf8 .= chr(0x09);
689                                 ++$c;
690                                 break;
691                             case $substr_chrs_c_2 == '\n':
692                                 $utf8 .= chr(0x0A);
693                                 ++$c;
694                                 break;
695                             case $substr_chrs_c_2 == '\f':
696                                 $utf8 .= chr(0x0C);
697                                 ++$c;
698                                 break;
699                             case $substr_chrs_c_2 == '\r':
700                                 $utf8 .= chr(0x0D);
701                                 ++$c;
702                                 break;
703
704                             case $substr_chrs_c_2 == '\\"':
705                             case $substr_chrs_c_2 == '\\\'':
706                             case $substr_chrs_c_2 == '\\\\':
707                             case $substr_chrs_c_2 == '\\/':
708                                 if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
709                                    ($delim == "'" && $substr_chrs_c_2 != '\\"')) {
710                                     $utf8 .= $chrs[++$c];
711                                 }
712                                 break;
713
714                             case preg_match('/\\\u[0-9A-F]{4}/i', $this->substr8($chrs, $c, 6)):
715                                 // single, escaped unicode character
716                                 $utf16 = chr(hexdec($this->substr8($chrs, ($c + 2), 2)))
717                                        . chr(hexdec($this->substr8($chrs, ($c + 4), 2)));
718                                 $utf8 .= $this->utf162utf8($utf16);
719                                 $c += 5;
720                                 break;
721
722                             case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
723                                 $utf8 .= $chrs[$c];
724                                 break;
725
726                             case ($ord_chrs_c & 0xE0) == 0xC0:
727                                 // characters U-00000080 - U-000007FF, mask 110XXXXX
728                                 //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
729                                 $utf8 .= $this->substr8($chrs, $c, 2);
730                                 ++$c;
731                                 break;
732
733                             case ($ord_chrs_c & 0xF0) == 0xE0:
734                                 // characters U-00000800 - U-0000FFFF, mask 1110XXXX
735                                 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
736                                 $utf8 .= $this->substr8($chrs, $c, 3);
737                                 $c += 2;
738                                 break;
739
740                             case ($ord_chrs_c & 0xF8) == 0xF0:
741                                 // characters U-00010000 - U-001FFFFF, mask 11110XXX
742                                 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
743                                 $utf8 .= $this->substr8($chrs, $c, 4);
744                                 $c += 3;
745                                 break;
746
747                             case ($ord_chrs_c & 0xFC) == 0xF8:
748                                 // characters U-00200000 - U-03FFFFFF, mask 111110XX
749                                 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
750                                 $utf8 .= $this->substr8($chrs, $c, 5);
751                                 $c += 4;
752                                 break;
753
754                             case ($ord_chrs_c & 0xFE) == 0xFC:
755                                 // characters U-04000000 - U-7FFFFFFF, mask 1111110X
756                                 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
757                                 $utf8 .= $this->substr8($chrs, $c, 6);
758                                 $c += 5;
759                                 break;
760
761                         }
762
763                     }
764
765                     return $utf8;
766
767                 } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) {
768                     // array, or object notation
769
770                     if ($str[0] == '[') {
771                         $stk = array(SERVICES_JSON_IN_ARR);
772                         $arr = array();
773                     } else {
774                         if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
775                             $stk = array(SERVICES_JSON_IN_OBJ);
776                             $obj = array();
777                         } else {
778                             $stk = array(SERVICES_JSON_IN_OBJ);
779                             $obj = new stdClass();
780                         }
781                     }
782
783                     array_push($stk, array('what'  => SERVICES_JSON_SLICE,
784                                            'where' => 0,
785                                            'delim' => false));
786
787                     $chrs = $this->substr8($str, 1, -1);
788                     $chrs = $this->reduce_string($chrs);
789
790                     if ($chrs == '') {
791                         if (reset($stk) == SERVICES_JSON_IN_ARR) {
792                             return $arr;
793
794                         } else {
795                             return $obj;
796
797                         }
798                     }
799
800                     //print("\nparsing {$chrs}\n");
801
802                     $strlen_chrs = $this->strlen8($chrs);
803
804                     for ($c = 0; $c <= $strlen_chrs; ++$c) {
805
806                         $top = end($stk);
807                         $substr_chrs_c_2 = $this->substr8($chrs, $c, 2);
808
809                         if (($c == $strlen_chrs) || (($chrs[$c] == ',') && ($top['what'] == SERVICES_JSON_SLICE))) {
810                             // found a comma that is not inside a string, array, etc.,
811                             // OR we've reached the end of the character list
812                             $slice = $this->substr8($chrs, $top['where'], ($c - $top['where']));
813                             array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false));
814                             //print("Found split at [$c]: ".$this->substr8($chrs, $top['where'], (1 + $c - $top['where']))."\n");
815
816                             if (reset($stk) == SERVICES_JSON_IN_ARR) {
817                                 // we are in an array, so just push an element onto the stack
818                                 array_push($arr, $this->decode($slice));
819
820                             } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
821                                 // we are in an object, so figure
822                                 // out the property name and set an
823                                 // element in an associative array,
824                                 // for now
825                                 $parts = array();
826                                 
827                                if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:/Uis', $slice, $parts)) {
828                                       // "name":value pair
829                                     $key = $this->decode($parts[1]);
830                                     $val = $this->decode(trim(substr($slice, strlen($parts[0])), ", \t\n\r\0\x0B"));
831                                     if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
832                                         $obj[$key] = $val;
833                                     } else {
834                                         $obj->$key = $val;
835                                     }
836                                 } elseif (preg_match('/^\s*(\w+)\s*:/Uis', $slice, $parts)) {
837                                     // name:value pair, where name is unquoted
838                                     $key = $parts[1];
839                                     $val = $this->decode(trim(substr($slice, strlen($parts[0])), ", \t\n\r\0\x0B"));
840
841                                     if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
842                                         $obj[$key] = $val;
843                                     } else {
844                                         $obj->$key = $val;
845                                     }
846                                 }
847
848                             }
849
850                         } elseif ((($chrs[$c] == '"') || ($chrs[$c] == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) {
851                             // found a quote, and we are not inside a string
852                             array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs[$c]));
853                             //print("Found start of string at [$c]\n");
854
855                         } elseif (($chrs[$c] == $top['delim']) &&
856                                  ($top['what'] == SERVICES_JSON_IN_STR) &&
857                                  (($this->strlen8($this->substr8($chrs, 0, $c)) - $this->strlen8(rtrim($this->substr8($chrs, 0, $c), '\\'))) % 2 != 1)) {
858                             // found a quote, we're in a string, and it's not escaped
859                             // we know that it's not escaped becase there is _not_ an
860                             // odd number of backslashes at the end of the string so far
861                             array_pop($stk);
862                             //print("Found end of string at [$c]: ".$this->substr8($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");
863
864                         } elseif (($chrs[$c] == '[') &&
865                                  in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
866                             // found a left-bracket, and we are in an array, object, or slice
867                             array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false));
868                             //print("Found start of array at [$c]\n");
869
870                         } elseif (($chrs[$c] == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) {
871                             // found a right-bracket, and we're in an array
872                             array_pop($stk);
873                             //print("Found end of array at [$c]: ".$this->substr8($chrs, $top['where'], (1 + $c - $top['where']))."\n");
874
875                         } elseif (($chrs[$c] == '{') &&
876                                  in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
877                             // found a left-brace, and we are in an array, object, or slice
878                             array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false));
879                             //print("Found start of object at [$c]\n");
880
881                         } elseif (($chrs[$c] == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) {
882                             // found a right-brace, and we're in an object
883                             array_pop($stk);
884                             //print("Found end of object at [$c]: ".$this->substr8($chrs, $top['where'], (1 + $c - $top['where']))."\n");
885
886                         } elseif (($substr_chrs_c_2 == '/*') &&
887                                  in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
888                             // found a comment start, and we are in an array, object, or slice
889                             array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false));
890                             $c++;
891                             //print("Found start of comment at [$c]\n");
892
893                         } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) {
894                             // found a comment end, and we're in one now
895                             array_pop($stk);
896                             $c++;
897
898                             for ($i = $top['where']; $i <= $c; ++$i)
899                                 $chrs = substr_replace($chrs, ' ', $i, 1);
900
901                             //print("Found end of comment at [$c]: ".$this->substr8($chrs, $top['where'], (1 + $c - $top['where']))."\n");
902
903                         }
904
905                     }
906
907                     if (reset($stk) == SERVICES_JSON_IN_ARR) {
908                         return $arr;
909
910                     } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
911                         return $obj;
912
913                     }
914
915                 }
916         }
917     }
918
919     /**
920      * @todo Ultimately, this should just call PEAR::isError()
921      */
922     function isError($data, $code = null)
923     {
924         if (class_exists('pear')) {
925             return PEAR::isError($data, $code);
926         } elseif (is_object($data) && (get_class($data) == 'services_json_error' ||
927                                  is_subclass_of($data, 'services_json_error'))) {
928             return true;
929         }
930
931         return false;
932     }
933     
934     /**
935     * Calculates length of string in bytes
936     * @param string 
937     * @return integer length
938     */
939     function strlen8( $str ) 
940     {
941         if ( $this->_mb_strlen ) {
942             return mb_strlen( $str, "8bit" );
943         }
944         return strlen( $str );
945     }
946     
947     /**
948     * Returns part of a string, interpreting $start and $length as number of bytes.
949     * @param string 
950     * @param integer start 
951     * @param integer length 
952     * @return integer length
953     */
954     function substr8( $string, $start, $length=false ) 
955     {
956         if ( $length === false ) {
957             $length = $this->strlen8( $string ) - $start;
958         }
959         if ( $this->_mb_substr ) {
960             return mb_substr( $string, $start, $length, "8bit" );
961         }
962         return substr( $string, $start, $length );
963     }
964
965 }
966
967 if (class_exists('PEAR_Error')) {
968
969     class Services_JSON_Error extends PEAR_Error
970     {
971         function __construct($message = 'unknown error', $code = null,
972                                      $mode = null, $options = null, $userinfo = null)
973         {
974             parent::__construct($message, $code, $mode, $options, $userinfo);
975         }
976     }
977
978 } else {
979
980     /**
981      * @todo Ultimately, this class shall be descended from PEAR_Error
982      */
983     class Services_JSON_Error
984     {
985         function __construct($message = 'unknown error', $code = null,
986                                      $mode = null, $options = null, $userinfo = null)
987         {
988             return;
989         }
990     }
991     
992 }