json.lib.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. <?php
  2. /* Copyright (C) 2011-2012 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2011-2012 Regis Houssin <regis.houssin@inodbox.com>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. * or see https://www.gnu.org/
  18. */
  19. /**
  20. * \file htdocs/core/lib/json.lib.php
  21. * \brief Functions to emulate json function when there were not activated
  22. * \ingroup core
  23. */
  24. if (!function_exists('json_encode'))
  25. {
  26. /**
  27. * Implement json_encode for PHP that does not have module enabled.
  28. *
  29. * @param mixed $elements PHP Object to json encode
  30. * @return string Json encoded string
  31. */
  32. function json_encode($elements)
  33. {
  34. return dol_json_encode($elements);
  35. }
  36. }
  37. /**
  38. * Implement json_encode for PHP that does not support it.
  39. * Use json_encode and json_decode in your code !
  40. *
  41. * @param mixed $elements PHP Object to json encode
  42. * @return string Json encoded string
  43. * @see json_encode()
  44. */
  45. function dol_json_encode($elements)
  46. {
  47. dol_syslog("For better performance, enable the native json in your PHP", LOG_WARNING);
  48. $num = 0;
  49. if (is_object($elements)) // Count number of properties for an object
  50. {
  51. foreach ($elements as $key => $value) $num++;
  52. } else {
  53. $num = count($elements);
  54. }
  55. //var_dump($num);
  56. // determine type
  57. if (is_numeric(key($elements)) && key($elements) == 0)
  58. {
  59. // indexed (list)
  60. $keysofelements = array_keys($elements); // Elements array mus have key that does not start with 0 and end with num-1, so we will use this later.
  61. $output = '[';
  62. for ($i = 0, $last = ($num - 1); $i < $num; $i++)
  63. {
  64. if (!isset($elements[$keysofelements[$i]])) continue;
  65. if (is_array($elements[$keysofelements[$i]]) || is_object($elements[$keysofelements[$i]])) $output .= json_encode($elements[$keysofelements[$i]]);
  66. else $output .= _val($elements[$keysofelements[$i]]);
  67. if ($i !== $last) $output .= ',';
  68. }
  69. $output .= ']';
  70. } else {
  71. // associative (object)
  72. $output = '{';
  73. $last = $num - 1;
  74. $i = 0;
  75. $tmpelements = array();
  76. if (is_array($elements)) $tmpelements = $elements;
  77. if (is_object($elements)) $tmpelements = get_object_vars($elements);
  78. foreach ($tmpelements as $key => $value)
  79. {
  80. $output .= '"'.$key.'":';
  81. if (is_array($value)) $output .= json_encode($value);
  82. else $output .= _val($value);
  83. if ($i !== $last) $output .= ',';
  84. ++$i;
  85. }
  86. $output .= '}';
  87. }
  88. // return
  89. return $output;
  90. }
  91. /**
  92. * Return text according to type
  93. *
  94. * @param mixed $val Value to show
  95. * @return string Formated value
  96. */
  97. function _val($val)
  98. {
  99. if (is_string($val))
  100. {
  101. // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
  102. $ascii = '';
  103. $strlen_var = strlen($val);
  104. /*
  105. * Iterate over every character in the string,
  106. * escaping with a slash or encoding to UTF-8 where necessary
  107. */
  108. for ($c = 0; $c < $strlen_var; ++$c) {
  109. $ord_var_c = ord($val[$c]);
  110. switch (true) {
  111. case $ord_var_c == 0x08:
  112. $ascii .= '\b';
  113. break;
  114. case $ord_var_c == 0x09:
  115. $ascii .= '\t';
  116. break;
  117. case $ord_var_c == 0x0A:
  118. $ascii .= '\n';
  119. break;
  120. case $ord_var_c == 0x0C:
  121. $ascii .= '\f';
  122. break;
  123. case $ord_var_c == 0x0D:
  124. $ascii .= '\r';
  125. break;
  126. case $ord_var_c == 0x22:
  127. case $ord_var_c == 0x2F:
  128. case $ord_var_c == 0x5C:
  129. // double quote, slash, slosh
  130. $ascii .= '\\'.$val[$c];
  131. break;
  132. case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
  133. // characters U-00000000 - U-0000007F (same as ASCII)
  134. $ascii .= $val[$c];
  135. break;
  136. case (($ord_var_c & 0xE0) == 0xC0):
  137. // characters U-00000080 - U-000007FF, mask 110XXXXX
  138. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  139. $char = pack('C*', $ord_var_c, ord($val[$c + 1]));
  140. $c += 1;
  141. $utf16 = utf82utf16($char);
  142. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  143. break;
  144. case (($ord_var_c & 0xF0) == 0xE0):
  145. // characters U-00000800 - U-0000FFFF, mask 1110XXXX
  146. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  147. $char = pack('C*', $ord_var_c, ord($val[$c + 1]), ord($val[$c + 2]));
  148. $c += 2;
  149. $utf16 = utf82utf16($char);
  150. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  151. break;
  152. case (($ord_var_c & 0xF8) == 0xF0):
  153. // characters U-00010000 - U-001FFFFF, mask 11110XXX
  154. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  155. $char = pack('C*', $ord_var_c, ord($val[$c + 1]), ord($val[$c + 2]), ord($val[$c + 3]));
  156. $c += 3;
  157. $utf16 = utf82utf16($char);
  158. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  159. break;
  160. case (($ord_var_c & 0xFC) == 0xF8):
  161. // characters U-00200000 - U-03FFFFFF, mask 111110XX
  162. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  163. $char = pack('C*', $ord_var_c, ord($val[$c + 1]), ord($val[$c + 2]), ord($val[$c + 3]), ord($val[$c + 4]));
  164. $c += 4;
  165. $utf16 = utf82utf16($char);
  166. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  167. break;
  168. case (($ord_var_c & 0xFE) == 0xFC):
  169. // characters U-04000000 - U-7FFFFFFF, mask 1111110X
  170. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  171. $char = pack('C*', $ord_var_c, ord($val[$c + 1]), ord($val[$c + 2]), ord($val[$c + 3]), ord($val[$c + 4]), ord($val[$c + 5]));
  172. $c += 5;
  173. $utf16 = utf82utf16($char);
  174. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  175. break;
  176. }
  177. }
  178. return '"'.$ascii.'"';
  179. } elseif (is_int($val)) return sprintf('%d', $val);
  180. elseif (is_float($val)) return sprintf('%F', $val);
  181. elseif (is_bool($val)) return ($val ? 'true' : 'false');
  182. else return 'null';
  183. }
  184. if (!function_exists('json_decode'))
  185. {
  186. /**
  187. * Implement json_decode for PHP that does not support it
  188. *
  189. * @param string $json Json encoded to PHP Object or Array
  190. * @param bool $assoc False return an object, true return an array
  191. * @return mixed Object or Array
  192. */
  193. function json_decode($json, $assoc = false)
  194. {
  195. return dol_json_decode($json, $assoc);
  196. }
  197. }
  198. /**
  199. * Implement json_decode for PHP that does not support it
  200. * Use json_encode and json_decode in your code !
  201. *
  202. * @param string $json Json encoded to PHP Object or Array
  203. * @param bool $assoc False return an object, true return an array. Try to always use it with true !
  204. * @return mixed Object or Array or false on error
  205. * @see json_decode()
  206. */
  207. function dol_json_decode($json, $assoc = false)
  208. {
  209. dol_syslog("For better performance, enable the native json in your PHP", LOG_WARNING);
  210. $comment = false;
  211. $out = '';
  212. $strLength = strlen($json); // Must stay strlen and not dol_strlen because we want technical length, not visible length
  213. for ($i = 0; $i < $strLength; $i++)
  214. {
  215. if (!$comment)
  216. {
  217. if (($json[$i] == '{') || ($json[$i] == '[')) $out .= 'array(';
  218. elseif (($json[$i] == '}') || ($json[$i] == ']')) $out .= ')';
  219. elseif ($json[$i] == ':') $out .= ' => ';
  220. else $out .= $json[$i];
  221. } else $out .= $json[$i];
  222. if ($json[$i] == '"' && $json[($i - 1)] != "\\") $comment = !$comment;
  223. }
  224. $out = _unval($out);
  225. $array = array();
  226. // Return an array
  227. if ($out != '') {
  228. try {
  229. eval('$array = '.$out.';');
  230. } catch (Exception $e) {
  231. $array = array();
  232. }
  233. }
  234. // Return an object
  235. if (!$assoc)
  236. {
  237. if (!empty($array))
  238. {
  239. $object = false;
  240. if (count($array) > 0) {
  241. $object = (object) array();
  242. }
  243. foreach ($array as $key => $value)
  244. {
  245. if ($key) $object->{$key} = $value;
  246. }
  247. return $object;
  248. }
  249. return false;
  250. }
  251. return $array;
  252. }
  253. /**
  254. * Return text according to type
  255. *
  256. * @param string $val Value to decode
  257. * @return string Formated value
  258. */
  259. function _unval($val)
  260. {
  261. $reg = array();
  262. while (preg_match('/\\\u([0-9A-F]{2})([0-9A-F]{2})/i', $val, $reg))
  263. {
  264. // single, escaped unicode character
  265. $utf16 = chr(hexdec($reg[1])).chr(hexdec($reg[2]));
  266. $utf8 = utf162utf8($utf16);
  267. $val = preg_replace('/\\\u'.$reg[1].$reg[2].'/i', $utf8, $val);
  268. }
  269. return $val;
  270. }
  271. /**
  272. * Convert a string from one UTF-16 char to one UTF-8 char
  273. *
  274. * Normally should be handled by mb_convert_encoding, but
  275. * provides a slower PHP-only method for installations
  276. * that lack the multibye string extension.
  277. *
  278. * @param string $utf16 UTF-16 character
  279. * @return string UTF-8 character
  280. */
  281. function utf162utf8($utf16)
  282. {
  283. // oh please oh please oh please oh please oh please
  284. if (function_exists('mb_convert_encoding')) {
  285. return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
  286. }
  287. $bytes = (ord($utf16[0]) << 8) | ord($utf16[1]);
  288. switch (true) {
  289. case ((0x7F & $bytes) == $bytes):
  290. // this case should never be reached, because we are in ASCII range
  291. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  292. return chr($bytes);
  293. case (0x07FF & $bytes) == $bytes:
  294. // return a 2-byte UTF-8 character
  295. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  296. return chr(0xC0 | (($bytes >> 6) & 0x1F))
  297. . chr(0x80 | ($bytes & 0x3F));
  298. case (0xFFFF & $bytes) == $bytes:
  299. // return a 3-byte UTF-8 character
  300. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  301. return chr(0xE0 | (($bytes >> 12) & 0x0F))
  302. . chr(0x80 | (($bytes >> 6) & 0x3F))
  303. . chr(0x80 | ($bytes & 0x3F));
  304. }
  305. // ignoring UTF-32 for now, sorry
  306. return '';
  307. }
  308. /**
  309. * Convert a string from one UTF-8 char to one UTF-16 char
  310. *
  311. * Normally should be handled by mb_convert_encoding, but
  312. * provides a slower PHP-only method for installations
  313. * that lack the multibye string extension.
  314. *
  315. * @param string $utf8 UTF-8 character
  316. * @return string UTF-16 character
  317. */
  318. function utf82utf16($utf8)
  319. {
  320. // oh please oh please oh please oh please oh please
  321. if (function_exists('mb_convert_encoding')) {
  322. return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
  323. }
  324. switch (strlen($utf8)) {
  325. case 1:
  326. // this case should never be reached, because we are in ASCII range
  327. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  328. return $utf8;
  329. case 2:
  330. // return a UTF-16 character from a 2-byte UTF-8 char
  331. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  332. return chr(0x07 & (ord($utf8[0]) >> 2)).chr((0xC0 & (ord($utf8[0]) << 6)) | (0x3F & ord($utf8[1])));
  333. case 3:
  334. // return a UTF-16 character from a 3-byte UTF-8 char
  335. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  336. return chr((0xF0 & (ord($utf8[0]) << 4)) | (0x0F & (ord($utf8[1]) >> 2))).chr((0xC0 & (ord($utf8[1]) << 6)) | (0x7F & ord($utf8[2])));
  337. }
  338. // ignoring UTF-32 for now, sorry
  339. return '';
  340. }