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

/pacore/ext/Facebook/jsonwrapper/JSON/JSON.php

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