]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/json/Services_JSON.php
MediaWiki 1.16.1
[autoinstalls/mediawiki.git] / includes / json / Services_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: Services_JSON.php 79562 2011-01-04 06:15:54Z tstarling $
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         private static $mHavePear = null;
140         /**
141          * Returns cached result of class_exists('pear'), to avoid calling AutoLoader numerous times
142          * in cases when PEAR is not present.
143          * @return boolean
144          */
145         private static function pearInstalled() {
146                 if ( self::$mHavePear === null ) {
147                         self::$mHavePear = class_exists( 'pear' );
148                 }
149                 return self::$mHavePear;
150         }
151
152         /**
153          * convert a string from one UTF-16 char to one UTF-8 char
154          *
155          * Normally should be handled by mb_convert_encoding, but
156          * provides a slower PHP-only method for installations
157          * that lack the multibye string extension.
158          *
159          * @param string  $utf16  UTF-16 character
160          * @return string  UTF-8 character
161          * @access private
162          */
163         function utf162utf8($utf16)
164         {
165                 // oh please oh please oh please oh please oh please
166                 if(function_exists('mb_convert_encoding')) {
167                         return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
168                 }
169
170                 $bytes = (ord($utf16{0}) << 8) | ord($utf16{1});
171
172                 switch(true) {
173                         case ((0x7F & $bytes) == $bytes):
174                                 // this case should never be reached, because we are in ASCII range
175                                 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
176                                 return chr(0x7F & $bytes);
177
178                         case (0x07FF & $bytes) == $bytes:
179                                 // return a 2-byte UTF-8 character
180                                 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
181                                 return chr(0xC0 | (($bytes >> 6) & 0x1F))
182                                          . chr(0x80 | ($bytes & 0x3F));
183
184                         case (0xFC00 & $bytes) == 0xD800 && strlen($utf16) >= 4 && (0xFC & ord($utf16{2})) == 0xDC:
185                                 // return a 4-byte UTF-8 character
186                                 $char = ((($bytes & 0x03FF) << 10)
187                                            | ((ord($utf16{2}) & 0x03) << 8)
188                                            | ord($utf16{3}));
189                                 $char += 0x10000;
190                                 return chr(0xF0 | (($char >> 18) & 0x07))
191                                          . chr(0x80 | (($char >> 12) & 0x3F))
192                                          . chr(0x80 | (($char >> 6) & 0x3F))
193                                          . chr(0x80 | ($char & 0x3F));
194
195                         case (0xFFFF & $bytes) == $bytes:
196                                 // return a 3-byte UTF-8 character
197                                 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
198                                 return chr(0xE0 | (($bytes >> 12) & 0x0F))
199                                          . chr(0x80 | (($bytes >> 6) & 0x3F))
200                                          . chr(0x80 | ($bytes & 0x3F));
201                 }
202
203                 // ignoring UTF-32 for now, sorry
204                 return '';
205         }
206
207         /**
208          * convert a string from one UTF-8 char to one UTF-16 char
209          *
210          * Normally should be handled by mb_convert_encoding, but
211          * provides a slower PHP-only method for installations
212          * that lack the multibye string extension.
213          *
214          * @param string  $utf8   UTF-8 character
215          * @return string  UTF-16 character
216          * @access private
217          */
218         function utf82utf16($utf8)
219         {
220                 // oh please oh please oh please oh please oh please
221                 if(function_exists('mb_convert_encoding')) {
222                         return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
223                 }
224
225                 switch(strlen($utf8)) {
226                         case 1:
227                                 // this case should never be reached, because we are in ASCII range
228                                 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
229                                 return $utf8;
230
231                         case 2:
232                                 // return a UTF-16 character from a 2-byte UTF-8 char
233                                 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
234                                 return chr(0x07 & (ord($utf8{0}) >> 2))
235                                          . chr((0xC0 & (ord($utf8{0}) << 6))
236                                                  | (0x3F & ord($utf8{1})));
237
238                         case 3:
239                                 // return a UTF-16 character from a 3-byte UTF-8 char
240                                 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
241                                 return chr((0xF0 & (ord($utf8{0}) << 4))
242                                                  | (0x0F & (ord($utf8{1}) >> 2)))
243                                          . chr((0xC0 & (ord($utf8{1}) << 6))
244                                                  | (0x7F & ord($utf8{2})));
245
246                         case 4:
247                                 // return a UTF-16 surrogate pair from a 4-byte UTF-8 char
248                                 if(ord($utf8{0}) > 0xF4) return ''; # invalid
249                                 $char = ((0x1C0000 & (ord($utf8{0}) << 18))
250                                            | (0x03F000 & (ord($utf8{1}) << 12))
251                                            | (0x000FC0 & (ord($utf8{2}) << 6))
252                                            | (0x00003F & ord($utf8{3})));
253                                 if($char > 0x10FFFF) return ''; # invalid
254                                 $char -= 0x10000;
255                                 return chr(0xD8 | (($char >> 18) & 0x03))
256                                          . chr(($char >> 10) & 0xFF)
257                                          . chr(0xDC | (($char >> 8) & 0x03))
258                                          . chr($char & 0xFF);
259                 }
260
261                 // ignoring UTF-32 for now, sorry
262                 return '';
263         }
264
265         /**
266          * encodes an arbitrary variable into JSON format
267          *
268          * @param mixed $var any number, boolean, string, array, or object to be encoded.
269          *                      see argument 1 to Services_JSON() above for array-parsing behavior.
270          *                      if var is a strng, note that encode() always expects it
271          *                      to be in ASCII or UTF-8 format!
272          * @param bool $pretty pretty-print output with indents and newlines
273          *
274          * @return mixed JSON string representation of input var or an error if a problem occurs
275          * @access public
276          */
277         function encode($var, $pretty=false)
278         {
279                 $this->indent = 0;
280                 $this->pretty = $pretty;
281                 $this->nameValSeparator = $pretty ? ': ' : ':';
282                 return $this->encode2($var);
283         }
284
285         /**
286          * encodes an arbitrary variable into JSON format
287          *
288          * @param mixed $var any number, boolean, string, array, or object to be encoded.
289          *                      see argument 1 to Services_JSON() above for array-parsing behavior.
290          *                      if var is a strng, note that encode() always expects it
291          *                      to be in ASCII or UTF-8 format!
292          *
293          * @return mixed JSON string representation of input var or an error if a problem occurs
294          * @access private
295          */
296         function encode2($var)
297         {
298                 if ($this->pretty) {
299                         $close = "\n" . str_repeat("\t", $this->indent);
300                         $open = $close . "\t";
301                         $mid = ',' . $open;
302                 }
303                 else {
304                         $open = $close = '';
305                         $mid = ',';
306                 }
307
308                 switch (gettype($var)) {
309                         case 'boolean':
310                                 return $var ? 'true' : 'false';
311
312                         case 'NULL':
313                                 return 'null';
314
315                         case 'integer':
316                                 return (int) $var;
317
318                         case 'double':
319                         case 'float':
320                                 return (float) $var;
321
322                         case 'string':
323                                 // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
324                                 $ascii = '';
325                                 $strlen_var = strlen($var);
326
327                            /*
328                                 * Iterate over every character in the string,
329                                 * escaping with a slash or encoding to UTF-8 where necessary
330                                 */
331                                 for ($c = 0; $c < $strlen_var; ++$c) {
332
333                                         $ord_var_c = ord($var{$c});
334
335                                         switch (true) {
336                                                 case $ord_var_c == 0x08:
337                                                         $ascii .= '\b';
338                                                         break;
339                                                 case $ord_var_c == 0x09:
340                                                         $ascii .= '\t';
341                                                         break;
342                                                 case $ord_var_c == 0x0A:
343                                                         $ascii .= '\n';
344                                                         break;
345                                                 case $ord_var_c == 0x0C:
346                                                         $ascii .= '\f';
347                                                         break;
348                                                 case $ord_var_c == 0x0D:
349                                                         $ascii .= '\r';
350                                                         break;
351
352                                                 case $ord_var_c == 0x22:
353                                                 case $ord_var_c == 0x2F:
354                                                 case $ord_var_c == 0x5C:
355                                                         // double quote, slash, slosh
356                                                         $ascii .= '\\'.$var{$c};
357                                                         break;
358
359                                                 case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
360                                                         // characters U-00000000 - U-0000007F (same as ASCII)
361                                                         $ascii .= $var{$c};
362                                                         break;
363
364                                                 case (($ord_var_c & 0xE0) == 0xC0):
365                                                         // characters U-00000080 - U-000007FF, mask 110XXXXX
366                                                         // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
367                                                         $char = pack('C*', $ord_var_c, ord($var{$c + 1}));
368                                                         $c += 1;
369                                                         $utf16 = $this->utf82utf16($char);
370                                                         $ascii .= sprintf('\u%04s', bin2hex($utf16));
371                                                         break;
372
373                                                 case (($ord_var_c & 0xF0) == 0xE0):
374                                                         // characters U-00000800 - U-0000FFFF, mask 1110XXXX
375                                                         // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
376                                                         $char = pack('C*', $ord_var_c,
377                                                                         ord($var{$c + 1}),
378                                                                         ord($var{$c + 2}));
379                                                         $c += 2;
380                                                         $utf16 = $this->utf82utf16($char);
381                                                         $ascii .= sprintf('\u%04s', bin2hex($utf16));
382                                                         break;
383
384                                                 case (($ord_var_c & 0xF8) == 0xF0):
385                                                         // characters U-00010000 - U-001FFFFF, mask 11110XXX
386                                                         // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
387                                                         // These will always return a surrogate pair
388                                                         $char = pack('C*', $ord_var_c,
389                                                                         ord($var{$c + 1}),
390                                                                         ord($var{$c + 2}),
391                                                                         ord($var{$c + 3}));
392                                                         $c += 3;
393                                                         $utf16 = $this->utf82utf16($char);
394                                                         if($utf16 == '') {
395                                                                 $ascii .= '\ufffd';
396                                                         } else {
397                                                                 $utf16 = str_split($utf16, 2);
398                                                                 $ascii .= sprintf('\u%04s\u%04s', bin2hex($utf16[0]), bin2hex($utf16[1]));
399                                                         }
400                                                         break;
401                                         }
402                                 }
403
404                                 return '"'.$ascii.'"';
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                                         $this->indent++;
428                                         $properties = array_map(array($this, 'name_value'),
429                                                                 array_keys($var),
430                                                                 array_values($var));
431                                         $this->indent--;
432
433                                         foreach($properties as $property) {
434                                                 if(Services_JSON::isError($property)) {
435                                                         return $property;
436                                                 }
437                                         }
438
439                                         return '{' . $open . join($mid, $properties) . $close . '}';
440                                 }
441
442                                 // treat it like a regular array
443                                 $this->indent++;
444                                 $elements = array_map(array($this, 'encode2'), $var);
445                                 $this->indent--;
446
447                                 foreach($elements as $element) {
448                                         if(Services_JSON::isError($element)) {
449                                                 return $element;
450                                         }
451                                 }
452
453                                 return '[' . $open . join($mid, $elements) . $close . ']';
454
455                         case 'object':
456                                 $vars = get_object_vars($var);
457
458                                 $this->indent++;
459                                 $properties = array_map(array($this, 'name_value'),
460                                                         array_keys($vars),
461                                                         array_values($vars));
462                                 $this->indent--;
463
464                                 foreach($properties as $property) {
465                                         if(Services_JSON::isError($property)) {
466                                                 return $property;
467                                         }
468                                 }
469
470                                 return '{' . $open . join($mid, $properties) . $close . '}';
471
472                         default:
473                                 return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
474                                         ? 'null'
475                                         : new Services_JSON_Error(gettype($var)." can not be encoded as JSON string");
476                 }
477         }
478
479         /**
480          * array-walking function for use in generating JSON-formatted name-value pairs
481          *
482          * @param string $name name of key to use
483          * @param mixed $value reference to an array element to be encoded
484          *
485          * @return string JSON-formatted name-value pair, like '"name":value'
486          * @access private
487          */
488         function name_value($name, $value)
489         {
490                 $encoded_value = $this->encode2($value);
491
492                 if(Services_JSON::isError($encoded_value)) {
493                         return $encoded_value;
494                 }
495
496                 return $this->encode2(strval($name)) . $this->nameValSeparator . $encoded_value;
497         }
498
499         /**
500          * reduce a string by removing leading and trailing comments and whitespace
501          *
502          * @param $str string string value to strip of comments and whitespace
503          *
504          * @return string string value stripped of comments and whitespace
505          * @access private
506          */
507         function reduce_string($str)
508         {
509                 $str = preg_replace(array(
510
511                                 // eliminate single line comments in '// ...' form
512                                 '#^\s*//(.+)$#m',
513
514                                 // eliminate multi-line comments in '/* ... */' form, at start of string
515                                 '#^\s*/\*(.+)\*/#Us',
516
517                                 // eliminate multi-line comments in '/* ... */' form, at end of string
518                                 '#/\*(.+)\*/\s*$#Us'
519
520                         ), '', $str);
521
522                 // eliminate extraneous space
523                 return trim($str);
524         }
525
526         /**
527          * decodes a JSON string into appropriate variable
528          *
529          * @param string $str JSON-formatted string
530          *
531          * @return mixed number, boolean, string, array, or object
532          *                 corresponding to given JSON input string.
533          *                 See argument 1 to Services_JSON() above for object-output behavior.
534          *                 Note that decode() always returns strings
535          *                 in ASCII or UTF-8 format!
536          * @access public
537          */
538         function decode($str)
539         {
540                 $str = $this->reduce_string($str);
541
542                 switch (strtolower($str)) {
543                         case 'true':
544                                 return true;
545
546                         case 'false':
547                                 return false;
548
549                         case 'null':
550                                 return null;
551
552                         default:
553                                 $m = array();
554
555                                 if (is_numeric($str)) {
556                                         // Lookie-loo, it's a number
557
558                                         // This would work on its own, but I'm trying to be
559                                         // good about returning integers where appropriate:
560                                         // return (float)$str;
561
562                                         // Return float or int, as appropriate
563                                         return ((float)$str == (integer)$str)
564                                                 ? (integer)$str
565                                                 : (float)$str;
566
567                                 } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) {
568                                         // STRINGS RETURNED IN UTF-8 FORMAT
569                                         $delim = substr($str, 0, 1);
570                                         $chrs = substr($str, 1, -1);
571                                         $utf8 = '';
572                                         $strlen_chrs = strlen($chrs);
573
574                                         for ($c = 0; $c < $strlen_chrs; ++$c) {
575
576                                                 $substr_chrs_c_2 = substr($chrs, $c, 2);
577                                                 $ord_chrs_c = ord($chrs{$c});
578
579                                                 switch (true) {
580                                                         case $substr_chrs_c_2 == '\b':
581                                                                 $utf8 .= chr(0x08);
582                                                                 ++$c;
583                                                                 break;
584                                                         case $substr_chrs_c_2 == '\t':
585                                                                 $utf8 .= chr(0x09);
586                                                                 ++$c;
587                                                                 break;
588                                                         case $substr_chrs_c_2 == '\n':
589                                                                 $utf8 .= chr(0x0A);
590                                                                 ++$c;
591                                                                 break;
592                                                         case $substr_chrs_c_2 == '\f':
593                                                                 $utf8 .= chr(0x0C);
594                                                                 ++$c;
595                                                                 break;
596                                                         case $substr_chrs_c_2 == '\r':
597                                                                 $utf8 .= chr(0x0D);
598                                                                 ++$c;
599                                                                 break;
600
601                                                         case $substr_chrs_c_2 == '\\"':
602                                                         case $substr_chrs_c_2 == '\\\'':
603                                                         case $substr_chrs_c_2 == '\\\\':
604                                                         case $substr_chrs_c_2 == '\\/':
605                                                                 if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
606                                                                    ($delim == "'" && $substr_chrs_c_2 != '\\"')) {
607                                                                         $utf8 .= $chrs{++$c};
608                                                                 }
609                                                                 break;
610
611                                                         case preg_match('/\\\uD[89AB][0-9A-F]{2}\\\uD[C-F][0-9A-F]{2}/i', substr($chrs, $c, 12)):
612                                                                 // escaped unicode surrogate pair
613                                                                 $utf16 = chr(hexdec(substr($chrs, ($c + 2), 2)))
614                                                                            . chr(hexdec(substr($chrs, ($c + 4), 2)))
615                                                                            . chr(hexdec(substr($chrs, ($c + 8), 2)))
616                                                                            . chr(hexdec(substr($chrs, ($c + 10), 2)));
617                                                                 $utf8 .= $this->utf162utf8($utf16);
618                                                                 $c += 11;
619                                                                 break;
620
621                                                         case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)):
622                                                                 // single, escaped unicode character
623                                                                 $utf16 = chr(hexdec(substr($chrs, ($c + 2), 2)))
624                                                                            . chr(hexdec(substr($chrs, ($c + 4), 2)));
625                                                                 $utf8 .= $this->utf162utf8($utf16);
626                                                                 $c += 5;
627                                                                 break;
628
629                                                         case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
630                                                                 $utf8 .= $chrs{$c};
631                                                                 break;
632
633                                                         case ($ord_chrs_c & 0xE0) == 0xC0:
634                                                                 // characters U-00000080 - U-000007FF, mask 110XXXXX
635                                                                 //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
636                                                                 $utf8 .= substr($chrs, $c, 2);
637                                                                 ++$c;
638                                                                 break;
639
640                                                         case ($ord_chrs_c & 0xF0) == 0xE0:
641                                                                 // characters U-00000800 - U-0000FFFF, mask 1110XXXX
642                                                                 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
643                                                                 $utf8 .= substr($chrs, $c, 3);
644                                                                 $c += 2;
645                                                                 break;
646
647                                                         case ($ord_chrs_c & 0xF8) == 0xF0:
648                                                                 // characters U-00010000 - U-001FFFFF, mask 11110XXX
649                                                                 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
650                                                                 $utf8 .= substr($chrs, $c, 4);
651                                                                 $c += 3;
652                                                                 break;
653
654                                                         case ($ord_chrs_c & 0xFC) == 0xF8:
655                                                                 // characters U-00200000 - U-03FFFFFF, mask 111110XX
656                                                                 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
657                                                                 $utf8 .= substr($chrs, $c, 5);
658                                                                 $c += 4;
659                                                                 break;
660
661                                                         case ($ord_chrs_c & 0xFE) == 0xFC:
662                                                                 // characters U-04000000 - U-7FFFFFFF, mask 1111110X
663                                                                 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
664                                                                 $utf8 .= substr($chrs, $c, 6);
665                                                                 $c += 5;
666                                                                 break;
667
668                                                 }
669
670                                         }
671
672                                         return $utf8;
673
674                                 } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) {
675                                         // array, or object notation
676
677                                         if ($str{0} == '[') {
678                                                 $stk = array(SERVICES_JSON_IN_ARR);
679                                                 $arr = array();
680                                         } else {
681                                                 if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
682                                                         $stk = array(SERVICES_JSON_IN_OBJ);
683                                                         $obj = array();
684                                                 } else {
685                                                         $stk = array(SERVICES_JSON_IN_OBJ);
686                                                         $obj = new stdClass();
687                                                 }
688                                         }
689
690                                         array_push($stk, array( 'what'  => SERVICES_JSON_SLICE,
691                                                                 'where' => 0,
692                                                                 'delim' => false));
693
694                                         $chrs = substr($str, 1, -1);
695                                         $chrs = $this->reduce_string($chrs);
696
697                                         if ($chrs == '') {
698                                                 if (reset($stk) == SERVICES_JSON_IN_ARR) {
699                                                         return $arr;
700
701                                                 } else {
702                                                         return $obj;
703
704                                                 }
705                                         }
706
707                                         //print("\nparsing {$chrs}\n");
708
709                                         $strlen_chrs = strlen($chrs);
710
711                                         for ($c = 0; $c <= $strlen_chrs; ++$c) {
712
713                                                 $top = end($stk);
714                                                 $substr_chrs_c_2 = substr($chrs, $c, 2);
715
716                                                 if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) {
717                                                         // found a comma that is not inside a string, array, etc.,
718                                                         // OR we've reached the end of the character list
719                                                         $slice = substr($chrs, $top['where'], ($c - $top['where']));
720                                                         array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false));
721                                                         //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
722
723                                                         if (reset($stk) == SERVICES_JSON_IN_ARR) {
724                                                                 // we are in an array, so just push an element onto the stack
725                                                                 array_push($arr, $this->decode($slice));
726
727                                                         } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
728                                                                 // we are in an object, so figure
729                                                                 // out the property name and set an
730                                                                 // element in an associative array,
731                                                                 // for now
732                                                                 $parts = array();
733
734                                                                 if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
735                                                                         // "name":value pair
736                                                                         $key = $this->decode($parts[1]);
737                                                                         $val = $this->decode($parts[2]);
738
739                                                                         if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
740                                                                                 $obj[$key] = $val;
741                                                                         } else {
742                                                                                 $obj->$key = $val;
743                                                                         }
744                                                                 } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
745                                                                         // name:value pair, where name is unquoted
746                                                                         $key = $parts[1];
747                                                                         $val = $this->decode($parts[2]);
748
749                                                                         if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
750                                                                                 $obj[$key] = $val;
751                                                                         } else {
752                                                                                 $obj->$key = $val;
753                                                                         }
754                                                                 }
755
756                                                         }
757
758                                                 } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) {
759                                                         // found a quote, and we are not inside a string
760                                                         array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c}));
761                                                         //print("Found start of string at {$c}\n");
762
763                                                 } elseif (($chrs{$c} == $top['delim']) &&
764                                                                  ($top['what'] == SERVICES_JSON_IN_STR) &&
765                                                                  (($chrs{$c - 1} != '\\') ||
766                                                                  ($chrs{$c - 1} == '\\' && $chrs{$c - 2} == '\\'))) {
767                                                         // found a quote, we're in a string, and it's not escaped
768                                                         array_pop($stk);
769                                                         //print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");
770
771                                                 } elseif (($chrs{$c} == '[') &&
772                                                                  in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
773                                                         // found a left-bracket, and we are in an array, object, or slice
774                                                         array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false));
775                                                         //print("Found start of array at {$c}\n");
776
777                                                 } elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) {
778                                                         // found a right-bracket, and we're in an array
779                                                         array_pop($stk);
780                                                         //print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
781
782                                                 } elseif (($chrs{$c} == '{') &&
783                                                                  in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
784                                                         // found a left-brace, and we are in an array, object, or slice
785                                                         array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false));
786                                                         //print("Found start of object at {$c}\n");
787
788                                                 } elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) {
789                                                         // found a right-brace, and we're in an object
790                                                         array_pop($stk);
791                                                         //print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
792
793                                                 } elseif (($substr_chrs_c_2 == '/*') &&
794                                                                  in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
795                                                         // found a comment start, and we are in an array, object, or slice
796                                                         array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false));
797                                                         $c++;
798                                                         //print("Found start of comment at {$c}\n");
799
800                                                 } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) {
801                                                         // found a comment end, and we're in one now
802                                                         array_pop($stk);
803                                                         $c++;
804
805                                                         for ($i = $top['where']; $i <= $c; ++$i)
806                                                                 $chrs = substr_replace($chrs, ' ', $i, 1);
807
808                                                         //print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
809
810                                                 }
811
812                                         }
813
814                                         if (reset($stk) == SERVICES_JSON_IN_ARR) {
815                                                 return $arr;
816
817                                         } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
818                                                 return $obj;
819
820                                         }
821
822                                 }
823                 }
824         }
825
826         /**
827          * @todo Ultimately, this should just call PEAR::isError()
828          */
829         function isError($data, $code = null)
830         {
831                 if ( self::pearInstalled() ) {
832                         //avoid some strict warnings on PEAR isError check (looks like http://pear.php.net/bugs/bug.php?id=9950 has been around for some time)
833                         return @PEAR::isError($data, $code);
834                 } elseif (is_object($data) && (get_class($data) == 'services_json_error' ||
835                                 is_subclass_of($data, 'services_json_error'))) {
836                         return true;
837                 }
838
839                 return false;
840         }
841 }
842
843
844 // Hide the PEAR_Error variant from Doxygen
845 /// @cond
846 if (class_exists('PEAR_Error')) {
847
848         /**
849          * @ingroup API
850          */
851         class Services_JSON_Error extends PEAR_Error
852         {
853                 function Services_JSON_Error($message = 'unknown error', $code = null,
854                                                 $mode = null, $options = null, $userinfo = null)
855                 {
856                         parent::PEAR_Error($message, $code, $mode, $options, $userinfo);
857                 }
858         }
859
860 } else {
861 /// @endcond
862
863         /**
864          * @todo Ultimately, this class shall be descended from PEAR_Error
865          * @ingroup API
866          */
867         class Services_JSON_Error
868         {
869                 function Services_JSON_Error($message = 'unknown error', $code = null,
870                                                 $mode = null, $options = null, $userinfo = null)
871                 {
872
873                 }
874         }
875 }