PageRenderTime 64ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/php-webclient-ajax/server/PEAR/JSON.php

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