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

/upload/libraries/JSON.php

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