PageRenderTime 49ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/inc/php/json.class.php

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