dolibarr  9.0.0
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 <http://www.gnu.org/licenses/>.
17  * or see http://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  }
57  else
58  {
59  $num=count($elements);
60  }
61  //var_dump($num);
62 
63  // determine type
64  if (is_numeric(key($elements)) && key($elements) == 0)
65  {
66  // indexed (list)
67  $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.
68  $output = '[';
69  for ($i = 0, $last = ($num - 1); $i < $num; $i++)
70  {
71  if (! isset($elements[$keysofelements[$i]])) continue;
72  if (is_array($elements[$keysofelements[$i]]) || is_object($elements[$keysofelements[$i]])) $output.= json_encode($elements[$keysofelements[$i]]);
73  else $output .= _val($elements[$keysofelements[$i]]);
74  if ($i !== $last) $output.= ',';
75  }
76  $output.= ']';
77  }
78  else
79  {
80  // associative (object)
81  $output = '{';
82  $last = $num - 1;
83  $i = 0;
84  $tmpelements=array();
85  if (is_array($elements)) $tmpelements=$elements;
86  if (is_object($elements)) $tmpelements=get_object_vars($elements);
87  foreach($tmpelements as $key => $value)
88  {
89  $output .= '"'.$key.'":';
90  if (is_array($value)) $output.= json_encode($value);
91  else $output .= _val($value);
92  if ($i !== $last) $output.= ',';
93  ++$i;
94  }
95  $output.= '}';
96  }
97 
98  // return
99  return $output;
100 }
101 
108 function _val($val)
109 {
110  if (is_string($val))
111  {
112  // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
113  $ascii = '';
114  $strlen_var = strlen($val);
115 
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 
122  $ord_var_c = ord($val{$c});
123 
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 
141  case $ord_var_c == 0x22:
142  case $ord_var_c == 0x2F:
143  case $ord_var_c == 0x5C:
144  // double quote, slash, slosh
145  $ascii .= '\\'.$val{$c};
146  break;
147 
148  case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
149  // characters U-00000000 - U-0000007F (same as ASCII)
150  $ascii .= $val{$c};
151  break;
152 
153  case (($ord_var_c & 0xE0) == 0xC0):
154  // characters U-00000080 - U-000007FF, mask 110XXXXX
155  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
156  $char = pack('C*', $ord_var_c, ord($val{$c + 1}));
157  $c += 1;
158  $utf16 = utf82utf16($char);
159  $ascii .= sprintf('\u%04s', bin2hex($utf16));
160  break;
161 
162  case (($ord_var_c & 0xF0) == 0xE0):
163  // characters U-00000800 - U-0000FFFF, mask 1110XXXX
164  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
165  $char = pack('C*', $ord_var_c, ord($val{$c + 1}), ord($val{$c + 2}));
166  $c += 2;
167  $utf16 = utf82utf16($char);
168  $ascii .= sprintf('\u%04s', bin2hex($utf16));
169  break;
170 
171  case (($ord_var_c & 0xF8) == 0xF0):
172  // characters U-00010000 - U-001FFFFF, mask 11110XXX
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}), ord($val{$c + 3}));
175  $c += 3;
176  $utf16 = utf82utf16($char);
177  $ascii .= sprintf('\u%04s', bin2hex($utf16));
178  break;
179 
180  case (($ord_var_c & 0xFC) == 0xF8):
181  // characters U-00200000 - U-03FFFFFF, mask 111110XX
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}));
184  $c += 4;
185  $utf16 = utf82utf16($char);
186  $ascii .= sprintf('\u%04s', bin2hex($utf16));
187  break;
188 
189  case (($ord_var_c & 0xFE) == 0xFC):
190  // characters U-04000000 - U-7FFFFFFF, mask 1111110X
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}), ord($val{$c + 5}));
193  $c += 5;
194  $utf16 = utf82utf16($char);
195  $ascii .= sprintf('\u%04s', bin2hex($utf16));
196  break;
197  }
198  }
199 
200  return '"'.$ascii.'"';
201  }
202  elseif (is_int($val)) return sprintf('%d', $val);
203  elseif (is_float($val)) return sprintf('%F', $val);
204  elseif (is_bool($val)) return ($val ? 'true' : 'false');
205  else return 'null';
206 }
207 
208 if (! function_exists('json_decode'))
209 {
217  function json_decode($json, $assoc=false)
218  {
219  return dol_json_decode($json, $assoc);
220  }
221 }
222 
232 function dol_json_decode($json, $assoc=false)
233 {
234  dol_syslog("For better performance, enable the native json in your PHP", LOG_WARNING);
235 
236  $comment = false;
237 
238  $out='';
239  $strLength = strlen($json); // Must stay strlen and not dol_strlen because we want technical length, not visible length
240  for ($i=0; $i<$strLength; $i++)
241  {
242  if (! $comment)
243  {
244  if (($json[$i] == '{') || ($json[$i] == '[')) $out.= 'array(';
245  else if (($json[$i] == '}') || ($json[$i] == ']')) $out.= ')';
246  else if ($json[$i] == ':') $out.= ' => ';
247  else $out.=$json[$i];
248  }
249  else $out.= $json[$i];
250  if ($json[$i] == '"' && $json[($i-1)]!="\\") $comment = !$comment;
251  }
252 
253  $out=_unval($out);
254 
255  // Return an array
256  if ($out != '') eval('$array = '.$out.';');
257  else $array=array();
258 
259  // Return an object
260  if (! $assoc)
261  {
262  if (! empty($array))
263  {
264  $object = false;
265  if (count($array)>0) {
266  $object = (object) array();
267  }
268  foreach ($array as $key => $value)
269  {
270  if ($key) $object->{$key} = $value;
271  }
272 
273  return $object;
274  }
275 
276  return false;
277  }
278 
279  return $array;
280 }
281 
288 function _unval($val)
289 {
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:108
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='')
Write log message into outputs.
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:232
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:288
utf82utf16($utf8)
Convert a string from one UTF-8 char to one UTF-16 char.
Definition: json.lib.php:353
if(! function_exists('json_encode')) dol_json_encode($elements)
Implement json_encode for PHP that does not support it.
Definition: json.lib.php:48