PageRenderTime 43ms CodeModel.GetById 8ms RepoModel.GetById 1ms app.codeStats 0ms

/open-dm-mi/multi-domain/webapp/src/web/scripts/dojox/grid/compat/tests/support/json.php

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