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