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