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