PageRenderTime 48ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/class-json.php

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