json.lib.php 11 KB

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