PageRenderTime 46ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/system/helpers/json.php

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