PageRenderTime 58ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/include/api/json-pear.php

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