json.lib.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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 <http://www.gnu.org/licenses/>.
  17. * or see http://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. }
  53. else
  54. {
  55. $num=count($elements);
  56. }
  57. //var_dump($num);
  58. // determine type
  59. if (is_numeric(key($elements)) && key($elements) == 0)
  60. {
  61. // indexed (list)
  62. $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.
  63. $output = '[';
  64. for ($i = 0, $last = ($num - 1); $i < $num; $i++)
  65. {
  66. if (! isset($elements[$keysofelements[$i]])) continue;
  67. if (is_array($elements[$keysofelements[$i]]) || is_object($elements[$keysofelements[$i]])) $output.= json_encode($elements[$keysofelements[$i]]);
  68. else $output .= _val($elements[$keysofelements[$i]]);
  69. if ($i !== $last) $output.= ',';
  70. }
  71. $output.= ']';
  72. }
  73. else
  74. {
  75. // associative (object)
  76. $output = '{';
  77. $last = $num - 1;
  78. $i = 0;
  79. $tmpelements=array();
  80. if (is_array($elements)) $tmpelements=$elements;
  81. if (is_object($elements)) $tmpelements=get_object_vars($elements);
  82. foreach($tmpelements as $key => $value)
  83. {
  84. $output .= '"'.$key.'":';
  85. if (is_array($value)) $output.= json_encode($value);
  86. else $output .= _val($value);
  87. if ($i !== $last) $output.= ',';
  88. ++$i;
  89. }
  90. $output.= '}';
  91. }
  92. // return
  93. return $output;
  94. }
  95. /**
  96. * Return text according to type
  97. *
  98. * @param mixed $val Value to show
  99. * @return string Formated value
  100. */
  101. function _val($val)
  102. {
  103. if (is_string($val))
  104. {
  105. // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
  106. $ascii = '';
  107. $strlen_var = strlen($val);
  108. /*
  109. * Iterate over every character in the string,
  110. * escaping with a slash or encoding to UTF-8 where necessary
  111. */
  112. for ($c = 0; $c < $strlen_var; ++$c) {
  113. $ord_var_c = ord($val{$c});
  114. switch (true) {
  115. case $ord_var_c == 0x08:
  116. $ascii .= '\b';
  117. break;
  118. case $ord_var_c == 0x09:
  119. $ascii .= '\t';
  120. break;
  121. case $ord_var_c == 0x0A:
  122. $ascii .= '\n';
  123. break;
  124. case $ord_var_c == 0x0C:
  125. $ascii .= '\f';
  126. break;
  127. case $ord_var_c == 0x0D:
  128. $ascii .= '\r';
  129. break;
  130. case $ord_var_c == 0x22:
  131. case $ord_var_c == 0x2F:
  132. case $ord_var_c == 0x5C:
  133. // double quote, slash, slosh
  134. $ascii .= '\\'.$val{$c};
  135. break;
  136. case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
  137. // characters U-00000000 - U-0000007F (same as ASCII)
  138. $ascii .= $val{$c};
  139. break;
  140. case (($ord_var_c & 0xE0) == 0xC0):
  141. // characters U-00000080 - U-000007FF, mask 110XXXXX
  142. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  143. $char = pack('C*', $ord_var_c, ord($val{$c + 1}));
  144. $c += 1;
  145. $utf16 = utf82utf16($char);
  146. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  147. break;
  148. case (($ord_var_c & 0xF0) == 0xE0):
  149. // characters U-00000800 - U-0000FFFF, mask 1110XXXX
  150. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  151. $char = pack('C*', $ord_var_c, ord($val{$c + 1}), ord($val{$c + 2}));
  152. $c += 2;
  153. $utf16 = utf82utf16($char);
  154. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  155. break;
  156. case (($ord_var_c & 0xF8) == 0xF0):
  157. // characters U-00010000 - U-001FFFFF, mask 11110XXX
  158. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  159. $char = pack('C*', $ord_var_c, ord($val{$c + 1}), ord($val{$c + 2}), ord($val{$c + 3}));
  160. $c += 3;
  161. $utf16 = utf82utf16($char);
  162. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  163. break;
  164. case (($ord_var_c & 0xFC) == 0xF8):
  165. // characters U-00200000 - U-03FFFFFF, mask 111110XX
  166. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  167. $char = pack('C*', $ord_var_c, ord($val{$c + 1}), ord($val{$c + 2}), ord($val{$c + 3}), ord($val{$c + 4}));
  168. $c += 4;
  169. $utf16 = utf82utf16($char);
  170. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  171. break;
  172. case (($ord_var_c & 0xFE) == 0xFC):
  173. // characters U-04000000 - U-7FFFFFFF, mask 1111110X
  174. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  175. $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}));
  176. $c += 5;
  177. $utf16 = utf82utf16($char);
  178. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  179. break;
  180. }
  181. }
  182. return '"'.$ascii.'"';
  183. }
  184. elseif (is_int($val)) return sprintf('%d', $val);
  185. elseif (is_float($val)) return sprintf('%F', $val);
  186. elseif (is_bool($val)) return ($val ? 'true' : 'false');
  187. else return 'null';
  188. }
  189. if (! function_exists('json_decode'))
  190. {
  191. /**
  192. * Implement json_decode for PHP that does not support it
  193. *
  194. * @param string $json Json encoded to PHP Object or Array
  195. * @param bool $assoc False return an object, true return an array
  196. * @return mixed Object or Array
  197. */
  198. function json_decode($json, $assoc=false)
  199. {
  200. return dol_json_decode($json, $assoc);
  201. }
  202. }
  203. /**
  204. * Implement json_decode for PHP that does not support it
  205. * Use json_encode and json_decode in your code !
  206. *
  207. * @param string $json Json encoded to PHP Object or Array
  208. * @param bool $assoc False return an object, true return an array. Try to always use it with true !
  209. * @return mixed Object or Array or false on error
  210. * @see json_decode()
  211. */
  212. function dol_json_decode($json, $assoc=false)
  213. {
  214. dol_syslog("For better performance, enable the native json in your PHP", LOG_WARNING);
  215. $comment = false;
  216. $out='';
  217. $strLength = strlen($json); // Must stay strlen and not dol_strlen because we want technical length, not visible length
  218. for ($i=0; $i<$strLength; $i++)
  219. {
  220. if (! $comment)
  221. {
  222. if (($json[$i] == '{') || ($json[$i] == '[')) $out.= 'array(';
  223. else if (($json[$i] == '}') || ($json[$i] == ']')) $out.= ')';
  224. else if ($json[$i] == ':') $out.= ' => ';
  225. else $out.=$json[$i];
  226. }
  227. else $out.= $json[$i];
  228. if ($json[$i] == '"' && $json[($i-1)]!="\\") $comment = !$comment;
  229. }
  230. $out=_unval($out);
  231. // Return an array
  232. if ($out != '') eval('$array = '.$out.';');
  233. else $array=array();
  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. while (preg_match('/\\\u([0-9A-F]{2})([0-9A-F]{2})/i', $val, $reg))
  262. {
  263. // single, escaped unicode character
  264. $utf16 = chr(hexdec($reg[1])) . chr(hexdec($reg[2]));
  265. $utf8 = utf162utf8($utf16);
  266. $val=preg_replace('/\\\u'.$reg[1].$reg[2].'/i',$utf8,$val);
  267. }
  268. return $val;
  269. }
  270. /**
  271. * Convert a string from one UTF-16 char to one UTF-8 char
  272. *
  273. * Normally should be handled by mb_convert_encoding, but
  274. * provides a slower PHP-only method for installations
  275. * that lack the multibye string extension.
  276. *
  277. * @param string $utf16 UTF-16 character
  278. * @return string UTF-8 character
  279. */
  280. function utf162utf8($utf16)
  281. {
  282. // oh please oh please oh please oh please oh please
  283. if(function_exists('mb_convert_encoding')) {
  284. return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
  285. }
  286. $bytes = (ord($utf16{0}) << 8) | ord($utf16{1});
  287. switch(true) {
  288. case ((0x7F & $bytes) == $bytes):
  289. // this case should never be reached, because we are in ASCII range
  290. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  291. return chr($bytes);
  292. case (0x07FF & $bytes) == $bytes:
  293. // return a 2-byte UTF-8 character
  294. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  295. return chr(0xC0 | (($bytes >> 6) & 0x1F))
  296. . chr(0x80 | ($bytes & 0x3F));
  297. case (0xFFFF & $bytes) == $bytes:
  298. // return a 3-byte UTF-8 character
  299. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  300. return chr(0xE0 | (($bytes >> 12) & 0x0F))
  301. . chr(0x80 | (($bytes >> 6) & 0x3F))
  302. . chr(0x80 | ($bytes & 0x3F));
  303. }
  304. // ignoring UTF-32 for now, sorry
  305. return '';
  306. }
  307. /**
  308. * Convert a string from one UTF-8 char to one UTF-16 char
  309. *
  310. * Normally should be handled by mb_convert_encoding, but
  311. * provides a slower PHP-only method for installations
  312. * that lack the multibye string extension.
  313. *
  314. * @param string $utf8 UTF-8 character
  315. * @return string UTF-16 character
  316. */
  317. function utf82utf16($utf8)
  318. {
  319. // oh please oh please oh please oh please oh please
  320. if(function_exists('mb_convert_encoding')) {
  321. return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
  322. }
  323. switch(strlen($utf8)) {
  324. case 1:
  325. // this case should never be reached, because we are in ASCII range
  326. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  327. return $utf8;
  328. case 2:
  329. // return a UTF-16 character from a 2-byte UTF-8 char
  330. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  331. return chr(0x07 & (ord($utf8{0}) >> 2)) . chr((0xC0 & (ord($utf8{0}) << 6)) | (0x3F & ord($utf8{1})));
  332. case 3:
  333. // return a UTF-16 character from a 3-byte UTF-8 char
  334. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  335. return chr((0xF0 & (ord($utf8{0}) << 4)) | (0x0F & (ord($utf8{1}) >> 2))) . chr((0xC0 & (ord($utf8{1}) << 6)) | (0x7F & ord($utf8{2})));
  336. }
  337. // ignoring UTF-32 for now, sorry
  338. return '';
  339. }