PageRenderTime 51ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

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

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