PageRenderTime 139ms CodeModel.GetById 45ms RepoModel.GetById 0ms app.codeStats 0ms

/examples/jsonrpc/public/services/phpolait/JSON.php

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