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