PageRenderTime 63ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/pear/HTML/AJAX/JSON.php

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