2 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4 * Converts to and from JSON format.
6 * JSON (JavaScript Object Notation) is a lightweight data-interchange
7 * format. It is easy for humans to read and write. It is easy for machines
8 * to parse and generate. It is based on a subset of the JavaScript
9 * Programming Language, Standard ECMA-262 3rd Edition - December 1999.
10 * This feature can also be found in Python. JSON is a text format that is
11 * completely language independent but uses conventions that are familiar
12 * to programmers of the C-family of languages, including C, C++, C#, Java,
13 * JavaScript, Perl, TCL, and many others. These properties make JSON an
14 * ideal data-interchange language.
16 * This package provides a simple encoder and decoder for JSON notation. It
17 * is intended for use with client-side Javascript applications that make
18 * use of HTTPRequest to perform server communication functions - data can
19 * be encoded into JSON notation for use in a client-side javascript, or
20 * decoded from incoming Javascript requests. JSON format is native to
21 * Javascript, and can be directly eval()'ed with no further parsing
24 * All strings should be in ASCII or UTF-8 format!
26 * LICENSE: Redistribution and use in source and binary forms, with or
27 * without modification, are permitted provided that the following
28 * conditions are met: Redistributions of source code must retain the
29 * above copyright notice, this list of conditions and the following
30 * disclaimer. Redistributions in binary form must reproduce the above
31 * copyright notice, this list of conditions and the following disclaimer
32 * in the documentation and/or other materials provided with the
35 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
36 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
37 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
38 * NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
39 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
40 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
41 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
42 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
43 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
44 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
48 * @package 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 305040 2010-11-02 23:19:03Z alan_k $
54 * @license http://www.opensource.org/licenses/bsd-license.php
55 * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198
59 * Marker constant for Services_JSON::decode(), used to flag stack state
61 define('SERVICES_JSON_SLICE', 1);
64 * Marker constant for Services_JSON::decode(), used to flag stack state
66 define('SERVICES_JSON_IN_STR', 2);
69 * Marker constant for Services_JSON::decode(), used to flag stack state
71 define('SERVICES_JSON_IN_ARR', 3);
74 * Marker constant for Services_JSON::decode(), used to flag stack state
76 define('SERVICES_JSON_IN_OBJ', 4);
79 * Marker constant for Services_JSON::decode(), used to flag stack state
81 define('SERVICES_JSON_IN_CMT', 5);
84 * Behavior switch for Services_JSON::decode()
86 define('SERVICES_JSON_LOOSE_TYPE', 16);
89 * Behavior switch for Services_JSON::decode()
91 define('SERVICES_JSON_SUPPRESS_ERRORS', 32);
94 * Behavior switch for Services_JSON::decode()
96 define('SERVICES_JSON_USE_TO_JSON', 64);
99 * Converts to and from JSON format.
101 * Brief example of use:
104 * // create a new instance of Services_JSON
105 * $json = new Services_JSON();
107 * // convert a complexe value to JSON notation, and send it to the browser
108 * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4)));
109 * $output = $json->encode($value);
112 * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]]
114 * // accept incoming POST data, assumed to be in JSON notation
115 * $input = file_get_contents('php://input', 1000000);
116 * $value = $json->decode($input);
122 * constructs a new JSON instance
124 * @param int $use object behavior flags; combine with boolean-OR
127 * - SERVICES_JSON_LOOSE_TYPE: loose typing.
128 * "{...}" syntax creates associative arrays
129 * instead of objects in decode().
130 * - SERVICES_JSON_SUPPRESS_ERRORS: error suppression.
131 * Values which can't be encoded (e.g. resources)
132 * appear as NULL instead of throwing errors.
133 * By default, a deeply-nested resource will
134 * bubble up with an error, so all return values
135 * from encode() should be checked with isError()
136 * - SERVICES_JSON_USE_TO_JSON: call toJSON when serializing objects
137 * It serializes the return value from the toJSON call rather
138 * than the object it'self, toJSON can return associative arrays,
139 * strings or numbers, if you return an object, make sure it does
140 * not have a toJSON method, otherwise an error will occur.
142 function Services_JSON($use = 0)
145 $this->_mb_strlen = function_exists('mb_strlen');
146 $this->_mb_convert_encoding = function_exists('mb_convert_encoding');
147 $this->_mb_substr = function_exists('mb_substr');
149 // private - cache the mbstring lookup results..
150 var $_mb_strlen = false;
151 var $_mb_substr = false;
152 var $_mb_convert_encoding = false;
155 * convert a string from one UTF-16 char to one UTF-8 char
157 * Normally should be handled by mb_convert_encoding, but
158 * provides a slower PHP-only method for installations
159 * that lack the multibye string extension.
161 * @param string $utf16 UTF-16 character
162 * @return string UTF-8 character
165 function utf162utf8($utf16)
167 // oh please oh please oh please oh please oh please
168 if($this->_mb_convert_encoding) {
169 return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
172 $bytes = (ord($utf16{0}) << 8) | ord($utf16{1});
175 case ((0x7F & $bytes) == $bytes):
176 // this case should never be reached, because we are in ASCII range
177 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
178 return chr(0x7F & $bytes);
180 case (0x07FF & $bytes) == $bytes:
181 // return a 2-byte UTF-8 character
182 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
183 return chr(0xC0 | (($bytes >> 6) & 0x1F))
184 . chr(0x80 | ($bytes & 0x3F));
186 case (0xFFFF & $bytes) == $bytes:
187 // return a 3-byte UTF-8 character
188 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
189 return chr(0xE0 | (($bytes >> 12) & 0x0F))
190 . chr(0x80 | (($bytes >> 6) & 0x3F))
191 . chr(0x80 | ($bytes & 0x3F));
194 // ignoring UTF-32 for now, sorry
199 * convert a string from one UTF-8 char to one UTF-16 char
201 * Normally should be handled by mb_convert_encoding, but
202 * provides a slower PHP-only method for installations
203 * that lack the multibye string extension.
205 * @param string $utf8 UTF-8 character
206 * @return string UTF-16 character
209 function utf82utf16($utf8)
211 // oh please oh please oh please oh please oh please
212 if($this->_mb_convert_encoding) {
213 return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
216 switch($this->strlen8($utf8)) {
218 // this case should never be reached, because we are in ASCII range
219 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
223 // return a UTF-16 character from a 2-byte UTF-8 char
224 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
225 return chr(0x07 & (ord($utf8{0}) >> 2))
226 . chr((0xC0 & (ord($utf8{0}) << 6))
227 | (0x3F & ord($utf8{1})));
230 // return a UTF-16 character from a 3-byte UTF-8 char
231 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
232 return chr((0xF0 & (ord($utf8{0}) << 4))
233 | (0x0F & (ord($utf8{1}) >> 2)))
234 . chr((0xC0 & (ord($utf8{1}) << 6))
235 | (0x7F & ord($utf8{2})));
238 // ignoring UTF-32 for now, sorry
243 * encodes an arbitrary variable into JSON format (and sends JSON Header)
245 * @param mixed $var any number, boolean, string, array, or object to be encoded.
246 * see argument 1 to Services_JSON() above for array-parsing behavior.
247 * if var is a strng, note that encode() always expects it
248 * to be in ASCII or UTF-8 format!
250 * @return mixed JSON string representation of input var or an error if a problem occurs
253 function encode($var)
255 header('Content-type: application/json');
256 return $this->encodeUnsafe($var);
259 * encodes an arbitrary variable into JSON format without JSON Header - warning - may allow XSS!!!!)
261 * @param mixed $var any number, boolean, string, array, or object to be encoded.
262 * see argument 1 to Services_JSON() above for array-parsing behavior.
263 * if var is a strng, note that encode() always expects it
264 * to be in ASCII or UTF-8 format!
266 * @return mixed JSON string representation of input var or an error if a problem occurs
269 function encodeUnsafe($var)
271 // see bug #16908 - regarding numeric locale printing
272 $lc = setlocale(LC_NUMERIC, 0);
273 setlocale(LC_NUMERIC, 'C');
274 $ret = $this->_encode($var);
275 setlocale(LC_NUMERIC, $lc);
280 * PRIVATE CODE that does the work of encodes an arbitrary variable into JSON format
282 * @param mixed $var any number, boolean, string, array, or object to be encoded.
283 * see argument 1 to Services_JSON() above for array-parsing behavior.
284 * if var is a strng, note that encode() always expects it
285 * to be in ASCII or UTF-8 format!
287 * @return mixed JSON string representation of input var or an error if a problem occurs
290 function _encode($var)
293 switch (gettype($var)) {
295 return $var ? 'true' : 'false';
308 // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
310 $strlen_var = $this->strlen8($var);
313 * Iterate over every character in the string,
314 * escaping with a slash or encoding to UTF-8 where necessary
316 for ($c = 0; $c < $strlen_var; ++$c) {
318 $ord_var_c = ord($var{$c});
321 case $ord_var_c == 0x08:
324 case $ord_var_c == 0x09:
327 case $ord_var_c == 0x0A:
330 case $ord_var_c == 0x0C:
333 case $ord_var_c == 0x0D:
337 case $ord_var_c == 0x22:
338 case $ord_var_c == 0x2F:
339 case $ord_var_c == 0x5C:
340 // double quote, slash, slosh
341 $ascii .= '\\'.$var{$c};
344 case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
345 // characters U-00000000 - U-0000007F (same as ASCII)
349 case (($ord_var_c & 0xE0) == 0xC0):
350 // characters U-00000080 - U-000007FF, mask 110XXXXX
351 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
352 if ($c+1 >= $strlen_var) {
358 $char = pack('C*', $ord_var_c, ord($var{$c + 1}));
360 $utf16 = $this->utf82utf16($char);
361 $ascii .= sprintf('\u%04s', bin2hex($utf16));
364 case (($ord_var_c & 0xF0) == 0xE0):
365 if ($c+2 >= $strlen_var) {
370 // characters U-00000800 - U-0000FFFF, mask 1110XXXX
371 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
372 $char = pack('C*', $ord_var_c,
376 $utf16 = $this->utf82utf16($char);
377 $ascii .= sprintf('\u%04s', bin2hex($utf16));
380 case (($ord_var_c & 0xF8) == 0xF0):
381 if ($c+3 >= $strlen_var) {
386 // characters U-00010000 - U-001FFFFF, mask 11110XXX
387 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
388 $char = pack('C*', $ord_var_c,
393 $utf16 = $this->utf82utf16($char);
394 $ascii .= sprintf('\u%04s', bin2hex($utf16));
397 case (($ord_var_c & 0xFC) == 0xF8):
398 // characters U-00200000 - U-03FFFFFF, mask 111110XX
399 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
400 if ($c+4 >= $strlen_var) {
405 $char = pack('C*', $ord_var_c,
411 $utf16 = $this->utf82utf16($char);
412 $ascii .= sprintf('\u%04s', bin2hex($utf16));
415 case (($ord_var_c & 0xFE) == 0xFC):
416 if ($c+5 >= $strlen_var) {
421 // characters U-04000000 - U-7FFFFFFF, mask 1111110X
422 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
423 $char = pack('C*', $ord_var_c,
430 $utf16 = $this->utf82utf16($char);
431 $ascii .= sprintf('\u%04s', bin2hex($utf16));
435 return '"'.$ascii.'"';
439 * As per JSON spec if any array key is not an integer
440 * we must treat the the whole array as an object. We
441 * also try to catch a sparsely populated associative
442 * array with numeric keys here because some JS engines
443 * will create an array with empty indexes up to
444 * max_index which can cause memory issues and because
445 * the keys, which may be relevant, will be remapped
448 * As per the ECMA and JSON specification an object may
449 * have any string as a property. Unfortunately due to
450 * a hole in the ECMA specification if the key is a
451 * ECMA reserved word or starts with a digit the
452 * parameter is only accessible using ECMAScript's
456 // treat as a JSON object
457 if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
458 $properties = array_map(array($this, 'name_value'),
462 foreach($properties as $property) {
463 if(Services_JSON::isError($property)) {
468 return '{' . join(',', $properties) . '}';
471 // treat it like a regular array
472 $elements = array_map(array($this, '_encode'), $var);
474 foreach($elements as $element) {
475 if(Services_JSON::isError($element)) {
480 return '[' . join(',', $elements) . ']';
484 // support toJSON methods.
485 if (($this->use & SERVICES_JSON_USE_TO_JSON) && method_exists($var, 'toJSON')) {
486 // this may end up allowing unlimited recursion
487 // so we check the return value to make sure it's not got the same method.
488 $recode = $var->toJSON();
490 if (method_exists($recode, 'toJSON')) {
492 return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
494 : new Services_JSON_Error(class_name($var).
495 " toJSON returned an object with a toJSON method.");
499 return $this->_encode( $recode );
502 $vars = get_object_vars($var);
504 $properties = array_map(array($this, 'name_value'),
506 array_values($vars));
508 foreach($properties as $property) {
509 if(Services_JSON::isError($property)) {
514 return '{' . join(',', $properties) . '}';
517 return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
519 : new Services_JSON_Error(gettype($var)." can not be encoded as JSON string");
524 * array-walking function for use in generating JSON-formatted name-value pairs
526 * @param string $name name of key to use
527 * @param mixed $value reference to an array element to be encoded
529 * @return string JSON-formatted name-value pair, like '"name":value'
532 function name_value($name, $value)
534 $encoded_value = $this->_encode($value);
536 if(Services_JSON::isError($encoded_value)) {
537 return $encoded_value;
540 return $this->_encode(strval($name)) . ':' . $encoded_value;
544 * reduce a string by removing leading and trailing comments and whitespace
546 * @param $str string string value to strip of comments and whitespace
548 * @return string string value stripped of comments and whitespace
551 function reduce_string($str)
553 $str = preg_replace(array(
555 // eliminate single line comments in '// ...' form
558 // eliminate multi-line comments in '/* ... */' form, at start of string
559 '#^\s*/\*(.+)\*/#Us',
561 // eliminate multi-line comments in '/* ... */' form, at end of string
566 // eliminate extraneous space
571 * decodes a JSON string into appropriate variable
573 * @param string $str JSON-formatted string
575 * @return mixed number, boolean, string, array, or object
576 * corresponding to given JSON input string.
577 * See argument 1 to Services_JSON() above for object-output behavior.
578 * Note that decode() always returns strings
579 * in ASCII or UTF-8 format!
582 function decode($str)
584 $str = $this->reduce_string($str);
586 switch (strtolower($str)) {
599 if (is_numeric($str)) {
600 // Lookie-loo, it's a number
602 // This would work on its own, but I'm trying to be
603 // good about returning integers where appropriate:
604 // return (float)$str;
606 // Return float or int, as appropriate
607 return ((float)$str == (integer)$str)
611 } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) {
612 // STRINGS RETURNED IN UTF-8 FORMAT
613 $delim = $this->substr8($str, 0, 1);
614 $chrs = $this->substr8($str, 1, -1);
616 $strlen_chrs = $this->strlen8($chrs);
618 for ($c = 0; $c < $strlen_chrs; ++$c) {
620 $substr_chrs_c_2 = $this->substr8($chrs, $c, 2);
621 $ord_chrs_c = ord($chrs{$c});
624 case $substr_chrs_c_2 == '\b':
628 case $substr_chrs_c_2 == '\t':
632 case $substr_chrs_c_2 == '\n':
636 case $substr_chrs_c_2 == '\f':
640 case $substr_chrs_c_2 == '\r':
645 case $substr_chrs_c_2 == '\\"':
646 case $substr_chrs_c_2 == '\\\'':
647 case $substr_chrs_c_2 == '\\\\':
648 case $substr_chrs_c_2 == '\\/':
649 if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
650 ($delim == "'" && $substr_chrs_c_2 != '\\"')) {
651 $utf8 .= $chrs{++$c};
655 case preg_match('/\\\u[0-9A-F]{4}/i', $this->substr8($chrs, $c, 6)):
656 // single, escaped unicode character
657 $utf16 = chr(hexdec($this->substr8($chrs, ($c + 2), 2)))
658 . chr(hexdec($this->substr8($chrs, ($c + 4), 2)));
659 $utf8 .= $this->utf162utf8($utf16);
663 case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
667 case ($ord_chrs_c & 0xE0) == 0xC0:
668 // characters U-00000080 - U-000007FF, mask 110XXXXX
669 //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
670 $utf8 .= $this->substr8($chrs, $c, 2);
674 case ($ord_chrs_c & 0xF0) == 0xE0:
675 // characters U-00000800 - U-0000FFFF, mask 1110XXXX
676 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
677 $utf8 .= $this->substr8($chrs, $c, 3);
681 case ($ord_chrs_c & 0xF8) == 0xF0:
682 // characters U-00010000 - U-001FFFFF, mask 11110XXX
683 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
684 $utf8 .= $this->substr8($chrs, $c, 4);
688 case ($ord_chrs_c & 0xFC) == 0xF8:
689 // characters U-00200000 - U-03FFFFFF, mask 111110XX
690 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
691 $utf8 .= $this->substr8($chrs, $c, 5);
695 case ($ord_chrs_c & 0xFE) == 0xFC:
696 // characters U-04000000 - U-7FFFFFFF, mask 1111110X
697 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
698 $utf8 .= $this->substr8($chrs, $c, 6);
708 } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) {
709 // array, or object notation
711 if ($str{0} == '[') {
712 $stk = array(SERVICES_JSON_IN_ARR);
715 if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
716 $stk = array(SERVICES_JSON_IN_OBJ);
719 $stk = array(SERVICES_JSON_IN_OBJ);
720 $obj = new stdClass();
724 array_push($stk, array('what' => SERVICES_JSON_SLICE,
728 $chrs = $this->substr8($str, 1, -1);
729 $chrs = $this->reduce_string($chrs);
732 if (reset($stk) == SERVICES_JSON_IN_ARR) {
741 //print("\nparsing {$chrs}\n");
743 $strlen_chrs = $this->strlen8($chrs);
745 for ($c = 0; $c <= $strlen_chrs; ++$c) {
748 $substr_chrs_c_2 = $this->substr8($chrs, $c, 2);
750 if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) {
751 // found a comma that is not inside a string, array, etc.,
752 // OR we've reached the end of the character list
753 $slice = $this->substr8($chrs, $top['where'], ($c - $top['where']));
754 array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false));
755 //print("Found split at {$c}: ".$this->substr8($chrs, $top['where'], (1 + $c - $top['where']))."\n");
757 if (reset($stk) == SERVICES_JSON_IN_ARR) {
758 // we are in an array, so just push an element onto the stack
759 array_push($arr, $this->decode($slice));
761 } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
762 // we are in an object, so figure
763 // out the property name and set an
764 // element in an associative array,
768 if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:/Uis', $slice, $parts)) {
770 $key = $this->decode($parts[1]);
771 $val = $this->decode(trim(substr($slice, strlen($parts[0])), ", \t\n\r\0\x0B"));
772 if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
777 } elseif (preg_match('/^\s*(\w+)\s*:/Uis', $slice, $parts)) {
778 // name:value pair, where name is unquoted
780 $val = $this->decode(trim(substr($slice, strlen($parts[0])), ", \t\n\r\0\x0B"));
782 if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
791 } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) {
792 // found a quote, and we are not inside a string
793 array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c}));
794 //print("Found start of string at {$c}\n");
796 } elseif (($chrs{$c} == $top['delim']) &&
797 ($top['what'] == SERVICES_JSON_IN_STR) &&
798 (($this->strlen8($this->substr8($chrs, 0, $c)) - $this->strlen8(rtrim($this->substr8($chrs, 0, $c), '\\'))) % 2 != 1)) {
799 // found a quote, we're in a string, and it's not escaped
800 // we know that it's not escaped becase there is _not_ an
801 // odd number of backslashes at the end of the string so far
803 //print("Found end of string at {$c}: ".$this->substr8($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");
805 } elseif (($chrs{$c} == '[') &&
806 in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
807 // found a left-bracket, and we are in an array, object, or slice
808 array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false));
809 //print("Found start of array at {$c}\n");
811 } elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) {
812 // found a right-bracket, and we're in an array
814 //print("Found end of array at {$c}: ".$this->substr8($chrs, $top['where'], (1 + $c - $top['where']))."\n");
816 } elseif (($chrs{$c} == '{') &&
817 in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
818 // found a left-brace, and we are in an array, object, or slice
819 array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false));
820 //print("Found start of object at {$c}\n");
822 } elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) {
823 // found a right-brace, and we're in an object
825 //print("Found end of object at {$c}: ".$this->substr8($chrs, $top['where'], (1 + $c - $top['where']))."\n");
827 } elseif (($substr_chrs_c_2 == '/*') &&
828 in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
829 // found a comment start, and we are in an array, object, or slice
830 array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false));
832 //print("Found start of comment at {$c}\n");
834 } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) {
835 // found a comment end, and we're in one now
839 for ($i = $top['where']; $i <= $c; ++$i)
840 $chrs = substr_replace($chrs, ' ', $i, 1);
842 //print("Found end of comment at {$c}: ".$this->substr8($chrs, $top['where'], (1 + $c - $top['where']))."\n");
848 if (reset($stk) == SERVICES_JSON_IN_ARR) {
851 } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
861 * @todo Ultimately, this should just call PEAR::isError()
863 function isError($data, $code = null)
865 if (class_exists('pear')) {
866 return PEAR::isError($data, $code);
867 } elseif (is_object($data) && (get_class($data) == 'services_json_error' ||
868 is_subclass_of($data, 'services_json_error'))) {
876 * Calculates length of string in bytes
878 * @return integer length
880 function strlen8( $str )
882 if ( $this->_mb_strlen ) {
883 return mb_strlen( $str, "8bit" );
885 return strlen( $str );
889 * Returns part of a string, interpreting $start and $length as number of bytes.
891 * @param integer start
892 * @param integer length
893 * @return integer length
895 function substr8( $string, $start, $length=false )
897 if ( $length === false ) {
898 $length = $this->strlen8( $string ) - $start;
900 if ( $this->_mb_substr ) {
901 return mb_substr( $string, $start, $length, "8bit" );
903 return substr( $string, $start, $length );
908 if (class_exists('PEAR_Error')) {
910 class Services_JSON_Error extends PEAR_Error
912 function Services_JSON_Error($message = 'unknown error', $code = null,
913 $mode = null, $options = null, $userinfo = null)
915 parent::PEAR_Error($message, $code, $mode, $options, $userinfo);
922 * @todo Ultimately, this class shall be descended from PEAR_Error
924 class Services_JSON_Error
926 function Services_JSON_Error($message = 'unknown error', $code = null,
927 $mode = null, $options = null, $userinfo = null)