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

/sites/all/modules/seesmic_api/json.class.php

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