json.lib.php 11 KB

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