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