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