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