dolibarr  13.0.2
json.lib.php
Go to the documentation of this file.
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 
26 if (!function_exists('json_encode'))
27 {
34  function json_encode($elements)
35  {
36  return dol_json_encode($elements);
37  }
38 }
39 
48 function dol_json_encode($elements)
49 {
50  dol_syslog("For better performance, enable the native json in your PHP", LOG_WARNING);
51 
52  $num = 0;
53  if (is_object($elements)) // Count number of properties for an object
54  {
55  foreach ($elements as $key => $value) $num++;
56  } else {
57  $num = count($elements);
58  }
59  //var_dump($num);
60 
61  // determine type
62  if (is_numeric(key($elements)) && key($elements) == 0)
63  {
64  // indexed (list)
65  $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.
66  $output = '[';
67  for ($i = 0, $last = ($num - 1); $i < $num; $i++)
68  {
69  if (!isset($elements[$keysofelements[$i]])) continue;
70  if (is_array($elements[$keysofelements[$i]]) || is_object($elements[$keysofelements[$i]])) $output .= json_encode($elements[$keysofelements[$i]]);
71  else $output .= _val($elements[$keysofelements[$i]]);
72  if ($i !== $last) $output .= ',';
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)) $tmpelements = $elements;
82  if (is_object($elements)) $tmpelements = get_object_vars($elements);
83  foreach ($tmpelements as $key => $value)
84  {
85  $output .= '"'.$key.'":';
86  if (is_array($value)) $output .= json_encode($value);
87  else $output .= _val($value);
88  if ($i !== $last) $output .= ',';
89  ++$i;
90  }
91  $output .= '}';
92  }
93 
94  // return
95  return $output;
96 }
97 
104 function _val($val)
105 {
106  if (is_string($val)) {
107  // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
108  $ascii = '';
109  $strlen_var = strlen($val);
110 
111  /*
112  * Iterate over every character in the string,
113  * escaping with a slash or encoding to UTF-8 where necessary
114  */
115  for ($c = 0; $c < $strlen_var; ++$c) {
116  $ord_var_c = ord($val[$c]);
117 
118  switch (true) {
119  case $ord_var_c == 0x08:
120  $ascii .= '\b';
121  break;
122  case $ord_var_c == 0x09:
123  $ascii .= '\t';
124  break;
125  case $ord_var_c == 0x0A:
126  $ascii .= '\n';
127  break;
128  case $ord_var_c == 0x0C:
129  $ascii .= '\f';
130  break;
131  case $ord_var_c == 0x0D:
132  $ascii .= '\r';
133  break;
134 
135  case $ord_var_c == 0x22:
136  case $ord_var_c == 0x2F:
137  case $ord_var_c == 0x5C:
138  // double quote, slash, slosh
139  $ascii .= '\\'.$val[$c];
140  break;
141 
142  case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
143  // characters U-00000000 - U-0000007F (same as ASCII)
144  $ascii .= $val[$c];
145  break;
146 
147  case (($ord_var_c & 0xE0) == 0xC0):
148  // characters U-00000080 - U-000007FF, mask 110XXXXX
149  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
150  $char = pack('C*', $ord_var_c, ord($val[$c + 1]));
151  $c += 1;
152  $utf16 = utf82utf16($char);
153  $ascii .= sprintf('\u%04s', bin2hex($utf16));
154  break;
155 
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 
165  case (($ord_var_c & 0xF8) == 0xF0):
166  // characters U-00010000 - U-001FFFFF, mask 11110XXX
167  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
168  $char = pack('C*', $ord_var_c, ord($val[$c + 1]), ord($val[$c + 2]), ord($val[$c + 3]));
169  $c += 3;
170  $utf16 = utf82utf16($char);
171  $ascii .= sprintf('\u%04s', bin2hex($utf16));
172  break;
173 
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 
183  case (($ord_var_c & 0xFE) == 0xFC):
184  // characters U-04000000 - U-7FFFFFFF, mask 1111110X
185  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
186  $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]));
187  $c += 5;
188  $utf16 = utf82utf16($char);
189  $ascii .= sprintf('\u%04s', bin2hex($utf16));
190  break;
191  }
192  }
193 
194  return '"'.$ascii.'"';
195  } elseif (is_int($val)) return sprintf('%d', $val);
196  elseif (is_float($val)) return sprintf('%F', $val);
197  elseif (is_bool($val)) return ($val ? 'true' : 'false');
198  else return 'null';
199 }
200 
201 if (!function_exists('json_decode'))
202 {
210  function json_decode($json, $assoc = false)
211  {
212  return dol_json_decode($json, $assoc);
213  }
214 }
215 
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 
229  $comment = false;
230 
231  $out = '';
232  $strLength = strlen($json); // Must stay strlen and not dol_strlen because we want technical length, not visible length
233  for ($i = 0; $i < $strLength; $i++)
234  {
235  if (!$comment)
236  {
237  if (($json[$i] == '{') || ($json[$i] == '[')) $out .= 'array(';
238  elseif (($json[$i] == '}') || ($json[$i] == ']')) $out .= ')';
239  elseif ($json[$i] == ':') $out .= ' => ';
240  else $out .= $json[$i];
241  } else $out .= $json[$i];
242  if ($json[$i] == '"' && $json[($i - 1)] != "\\") $comment = !$comment;
243  }
244 
245  $out = _unval($out);
246 
247  $array = array();
248 
249  // Return an array
250  if ($out != '') {
251  try {
252  eval('$array = '.$out.';');
253  } catch (Exception $e) {
254  $array = array();
255  }
256  }
257 
258  // Return an object
259  if (!$assoc)
260  {
261  if (!empty($array))
262  {
263  $object = false;
264  if (count($array) > 0) {
265  $object = (object) array();
266  }
267  foreach ($array as $key => $value)
268  {
269  if ($key) $object->{$key} = $value;
270  }
271 
272  return $object;
273  }
274 
275  return false;
276  }
277 
278  return $array;
279 }
280 
287 function _unval($val)
288 {
289  $reg = array();
290  while (preg_match('/\\\u([0-9A-F]{2})([0-9A-F]{2})/i', $val, $reg))
291  {
292  // single, escaped unicode character
293  $utf16 = chr(hexdec($reg[1])).chr(hexdec($reg[2]));
294  $utf8 = utf162utf8($utf16);
295  $val = preg_replace('/\\\u'.$reg[1].$reg[2].'/i', $utf8, $val);
296  }
297  return $val;
298 }
299 
310 function utf162utf8($utf16)
311 {
312  // oh please oh please oh please oh please oh please
313  if (function_exists('mb_convert_encoding')) {
314  return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
315  }
316 
317  $bytes = (ord($utf16[0]) << 8) | ord($utf16[1]);
318 
319  switch (true) {
320  case ((0x7F & $bytes) == $bytes):
321  // this case should never be reached, because we are in ASCII range
322  // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
323  return chr($bytes);
324 
325  case (0x07FF & $bytes) == $bytes:
326  // return a 2-byte UTF-8 character
327  // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
328  return chr(0xC0 | (($bytes >> 6) & 0x1F))
329  . chr(0x80 | ($bytes & 0x3F));
330 
331  case (0xFFFF & $bytes) == $bytes:
332  // return a 3-byte UTF-8 character
333  // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
334  return chr(0xE0 | (($bytes >> 12) & 0x0F))
335  . chr(0x80 | (($bytes >> 6) & 0x3F))
336  . chr(0x80 | ($bytes & 0x3F));
337  }
338 
339  // ignoring UTF-32 for now, sorry
340  return '';
341 }
342 
353 function utf82utf16($utf8)
354 {
355  // oh please oh please oh please oh please oh please
356  if (function_exists('mb_convert_encoding')) {
357  return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
358  }
359 
360  switch (strlen($utf8)) {
361  case 1:
362  // this case should never be reached, because we are in ASCII range
363  // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
364  return $utf8;
365 
366  case 2:
367  // return a UTF-16 character from a 2-byte UTF-8 char
368  // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
369  return chr(0x07 & (ord($utf8[0]) >> 2)).chr((0xC0 & (ord($utf8[0]) << 6)) | (0x3F & ord($utf8[1])));
370 
371  case 3:
372  // return a UTF-16 character from a 3-byte UTF-8 char
373  // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
374  return chr((0xF0 & (ord($utf8[0]) << 4)) | (0x0F & (ord($utf8[1]) >> 2))).chr((0xC0 & (ord($utf8[1]) << 6)) | (0x7F & ord($utf8[2])));
375  }
376 
377  // ignoring UTF-32 for now, sorry
378  return '';
379 }
_val($val)
Return text according to type.
Definition: json.lib.php:104
if(!function_exists('json_decode')) dol_json_decode($json, $assoc=false)
Implement json_decode for PHP that does not support it Use json_encode and json_decode in your code !...
Definition: json.lib.php:225
if(!function_exists('json_encode')) dol_json_encode($elements)
Implement json_encode for PHP that does not support it.
Definition: json.lib.php:48
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
utf162utf8($utf16)
Convert a string from one UTF-16 char to one UTF-8 char.
Definition: json.lib.php:310
_unval($val)
Return text according to type.
Definition: json.lib.php:287
utf82utf16($utf8)
Convert a string from one UTF-8 char to one UTF-16 char.
Definition: json.lib.php:353