dolibarr  17.0.4
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')) {
33  function json_encode($elements)
34  {
35  return dol_json_encode($elements);
36  }
37 }
38 
49 function dol_json_encode($elements)
50 {
51  dol_syslog("For better performance, enable the native json in your PHP", LOG_WARNING);
52 
53  $num = 0;
54  if (is_object($elements)) { // Count number of properties for an object
55  foreach ($elements as $key => $value) {
56  $num++;
57  }
58  } else {
59  $num = count($elements);
60  }
61  //var_dump($num);
62 
63  // determine type
64  if (is_numeric(key($elements)) && key($elements) == 0) {
65  // indexed (list)
66  $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.
67  $output = '[';
68  for ($i = 0, $last = ($num - 1); $i < $num; $i++) {
69  if (!isset($elements[$keysofelements[$i]])) {
70  continue;
71  }
72  if (is_array($elements[$keysofelements[$i]]) || is_object($elements[$keysofelements[$i]])) {
73  $output .= json_encode($elements[$keysofelements[$i]]);
74  } else {
75  $output .= _val($elements[$keysofelements[$i]]);
76  }
77  if ($i !== $last) {
78  $output .= ',';
79  }
80  }
81  $output .= ']';
82  } else {
83  // associative (object)
84  $output = '{';
85  $last = $num - 1;
86  $i = 0;
87  $tmpelements = array();
88  if (is_array($elements)) {
89  $tmpelements = $elements;
90  }
91  if (is_object($elements)) {
92  $tmpelements = get_object_vars($elements);
93  }
94  foreach ($tmpelements as $key => $value) {
95  $output .= '"'.$key.'":';
96  if (is_array($value)) {
97  $output .= json_encode($value);
98  } else {
99  $output .= _val($value);
100  }
101  if ($i !== $last) {
102  $output .= ',';
103  }
104  ++$i;
105  }
106  $output .= '}';
107  }
108 
109  // return
110  return $output;
111 }
112 
119 function _val($val)
120 {
121  if (is_string($val)) {
122  // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
123  $ascii = '';
124  $strlen_var = strlen($val);
125 
126  /*
127  * Iterate over every character in the string,
128  * escaping with a slash or encoding to UTF-8 where necessary
129  */
130  for ($c = 0; $c < $strlen_var; ++$c) {
131  $ord_var_c = ord($val[$c]);
132 
133  switch (true) {
134  case $ord_var_c == 0x08:
135  $ascii .= '\b';
136  break;
137  case $ord_var_c == 0x09:
138  $ascii .= '\t';
139  break;
140  case $ord_var_c == 0x0A:
141  $ascii .= '\n';
142  break;
143  case $ord_var_c == 0x0C:
144  $ascii .= '\f';
145  break;
146  case $ord_var_c == 0x0D:
147  $ascii .= '\r';
148  break;
149 
150  case $ord_var_c == 0x22:
151  case $ord_var_c == 0x2F:
152  case $ord_var_c == 0x5C:
153  // double quote, slash, slosh
154  $ascii .= '\\'.$val[$c];
155  break;
156 
157  case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
158  // characters U-00000000 - U-0000007F (same as ASCII)
159  $ascii .= $val[$c];
160  break;
161 
162  case (($ord_var_c & 0xE0) == 0xC0):
163  // characters U-00000080 - U-000007FF, mask 110XXXXX
164  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
165  $char = pack('C*', $ord_var_c, ord($val[$c + 1]));
166  $c += 1;
167  $utf16 = utf82utf16($char);
168  $ascii .= sprintf('\u%04s', bin2hex($utf16));
169  break;
170 
171  case (($ord_var_c & 0xF0) == 0xE0):
172  // characters U-00000800 - U-0000FFFF, mask 1110XXXX
173  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
174  $char = pack('C*', $ord_var_c, ord($val[$c + 1]), ord($val[$c + 2]));
175  $c += 2;
176  $utf16 = utf82utf16($char);
177  $ascii .= sprintf('\u%04s', bin2hex($utf16));
178  break;
179 
180  case (($ord_var_c & 0xF8) == 0xF0):
181  // characters U-00010000 - U-001FFFFF, mask 11110XXX
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]));
184  $c += 3;
185  $utf16 = utf82utf16($char);
186  $ascii .= sprintf('\u%04s', bin2hex($utf16));
187  break;
188 
189  case (($ord_var_c & 0xFC) == 0xF8):
190  // characters U-00200000 - U-03FFFFFF, mask 111110XX
191  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
192  $char = pack('C*', $ord_var_c, ord($val[$c + 1]), ord($val[$c + 2]), ord($val[$c + 3]), ord($val[$c + 4]));
193  $c += 4;
194  $utf16 = utf82utf16($char);
195  $ascii .= sprintf('\u%04s', bin2hex($utf16));
196  break;
197 
198  case (($ord_var_c & 0xFE) == 0xFC):
199  // characters U-04000000 - U-7FFFFFFF, mask 1111110X
200  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
201  $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]));
202  $c += 5;
203  $utf16 = utf82utf16($char);
204  $ascii .= sprintf('\u%04s', bin2hex($utf16));
205  break;
206  }
207  }
208 
209  return '"'.$ascii.'"';
210  } elseif (is_int($val)) {
211  return sprintf('%d', $val);
212  } elseif (is_float($val)) {
213  return sprintf('%F', $val);
214  } elseif (is_bool($val)) {
215  return ($val ? 'true' : 'false');
216  } else {
217  return 'null';
218  }
219 }
220 
221 if (!function_exists('json_decode')) {
229  function json_decode($json, $assoc = false)
230  {
231  return dol_json_decode($json, $assoc);
232  }
233 }
234 
244 function dol_json_decode($json, $assoc = false)
245 {
246  dol_syslog("For better performance, enable the native json in your PHP", LOG_WARNING);
247 
248  $comment = false;
249 
250  $out = '';
251  $strLength = strlen($json); // Must stay strlen and not dol_strlen because we want technical length, not visible length
252  for ($i = 0; $i < $strLength; $i++) {
253  if (!$comment) {
254  if (($json[$i] == '{') || ($json[$i] == '[')) {
255  $out .= 'array(';
256  } elseif (($json[$i] == '}') || ($json[$i] == ']')) {
257  $out .= ')';
258  } elseif ($json[$i] == ':') {
259  $out .= ' => ';
260  } else {
261  $out .= $json[$i];
262  }
263  } else {
264  $out .= $json[$i];
265  }
266  if ($json[$i] == '"' && $json[($i - 1)] != "\\") {
267  $comment = !$comment;
268  }
269  }
270 
271  $out = _unval($out);
272 
273  $array = array();
274 
275  // Return an array
276  if ($out != '') {
277  try {
278  eval('$array = '.$out.';');
279  } catch (Exception $e) {
280  $array = array();
281  }
282  }
283 
284  // Return an object
285  if (!$assoc) {
286  if (!empty($array)) {
287  $object = false;
288  if (count($array) > 0) {
289  $object = (object) array();
290  }
291  foreach ($array as $key => $value) {
292  if ($key) {
293  $object->{$key} = $value;
294  }
295  }
296 
297  return $object;
298  }
299 
300  return false;
301  }
302 
303  return $array;
304 }
305 
312 function _unval($val)
313 {
314  $reg = array();
315  while (preg_match('/\\\u([0-9A-F]{2})([0-9A-F]{2})/i', $val, $reg)) {
316  // single, escaped unicode character
317  $utf16 = chr(hexdec($reg[1])).chr(hexdec($reg[2]));
318  $utf8 = utf162utf8($utf16);
319  $val = preg_replace('/\\\u'.$reg[1].$reg[2].'/i', $utf8, $val);
320  }
321  return $val;
322 }
323 
334 function utf162utf8($utf16)
335 {
336  // oh please oh please oh please oh please oh please
337  if (function_exists('mb_convert_encoding')) {
338  return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
339  }
340 
341  $bytes = (ord($utf16[0]) << 8) | ord($utf16[1]);
342 
343  switch (true) {
344  case ((0x7F & $bytes) == $bytes):
345  // this case should never be reached, because we are in ASCII range
346  // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
347  return chr($bytes);
348 
349  case (0x07FF & $bytes) == $bytes:
350  // return a 2-byte UTF-8 character
351  // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
352  return chr(0xC0 | (($bytes >> 6) & 0x1F))
353  . chr(0x80 | ($bytes & 0x3F));
354 
355  case (0xFFFF & $bytes) == $bytes:
356  // return a 3-byte UTF-8 character
357  // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
358  return chr(0xE0 | (($bytes >> 12) & 0x0F))
359  . chr(0x80 | (($bytes >> 6) & 0x3F))
360  . chr(0x80 | ($bytes & 0x3F));
361  }
362 
363  // ignoring UTF-32 for now, sorry
364  return '';
365 }
366 
377 function utf82utf16($utf8)
378 {
379  // oh please oh please oh please oh please oh please
380  if (function_exists('mb_convert_encoding')) {
381  return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
382  }
383 
384  switch (strlen($utf8)) {
385  case 1:
386  // this case should never be reached, because we are in ASCII range
387  // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
388  return $utf8;
389 
390  case 2:
391  // return a UTF-16 character from a 2-byte UTF-8 char
392  // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
393  return chr(0x07 & (ord($utf8[0]) >> 2)).chr((0xC0 & (ord($utf8[0]) << 6)) | (0x3F & ord($utf8[1])));
394 
395  case 3:
396  // return a UTF-16 character from a 3-byte UTF-8 char
397  // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
398  return chr((0xF0 & (ord($utf8[0]) << 4)) | (0x0F & (ord($utf8[1]) >> 2))).chr((0xC0 & (ord($utf8[1]) << 6)) | (0x7F & ord($utf8[2])));
399  }
400 
401  // ignoring UTF-32 for now, sorry
402  return '';
403 }
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
_val($val)
Return text according to type.
Definition: json.lib.php:119
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:244
utf162utf8($utf16)
Convert a string from one UTF-16 char to one UTF-8 char.
Definition: json.lib.php:334
_unval($val)
Return text according to type.
Definition: json.lib.php:312
if(!function_exists('json_encode')) dol_json_encode($elements)
Implement json_encode for PHP that does not support it.
Definition: json.lib.php:49
utf82utf16($utf8)
Convert a string from one UTF-8 char to one UTF-16 char.
Definition: json.lib.php:377