json.lib.php 11 KB

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