PageRenderTime 49ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/administrator/components/com_akeeba/helpers/jsonlib.php

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