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