dolibarr  7.0.0-beta
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@capnetworks.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 
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  {
54  foreach($elements as $key => $value) $num++;
55  }
56  else
57  {
58  $num=count($elements);
59  }
60  //var_dump($num);
61 
62  // determine type
63  if (is_numeric(key($elements)) && key($elements) == 0)
64  {
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  {
70  if (! isset($elements[$keysofelements[$i]])) continue;
71  if (is_array($elements[$keysofelements[$i]]) || is_object($elements[$keysofelements[$i]])) $output.= json_encode($elements[$keysofelements[$i]]);
72  else $output .= _val($elements[$keysofelements[$i]]);
73  if ($i !== $last) $output.= ',';
74  }
75  $output.= ']';
76  }
77  else
78  {
79  // associative (object)
80  $output = '{';
81  $last = $num - 1;
82  $i = 0;
83  $tmpelements=array();
84  if (is_array($elements)) $tmpelements=$elements;
85  if (is_object($elements)) $tmpelements=get_object_vars($elements);
86  foreach($tmpelements as $key => $value)
87  {
88  $output .= '"'.$key.'":';
89  if (is_array($value)) $output.= json_encode($value);
90  else $output .= _val($value);
91  if ($i !== $last) $output.= ',';
92  ++$i;
93  }
94  $output.= '}';
95  }
96 
97  // return
98  return $output;
99 }
100 
107 function _val($val)
108 {
109  if (is_string($val))
110  {
111  // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
112  $ascii = '';
113  $strlen_var = strlen($val);
114 
115  /*
116  * Iterate over every character in the string,
117  * escaping with a slash or encoding to UTF-8 where necessary
118  */
119  for ($c = 0; $c < $strlen_var; ++$c) {
120 
121  $ord_var_c = ord($val{$c});
122 
123  switch (true) {
124  case $ord_var_c == 0x08:
125  $ascii .= '\b';
126  break;
127  case $ord_var_c == 0x09:
128  $ascii .= '\t';
129  break;
130  case $ord_var_c == 0x0A:
131  $ascii .= '\n';
132  break;
133  case $ord_var_c == 0x0C:
134  $ascii .= '\f';
135  break;
136  case $ord_var_c == 0x0D:
137  $ascii .= '\r';
138  break;
139 
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 
147  case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
148  // characters U-00000000 - U-0000007F (same as ASCII)
149  $ascii .= $val{$c};
150  break;
151 
152  case (($ord_var_c & 0xE0) == 0xC0):
153  // characters U-00000080 - U-000007FF, mask 110XXXXX
154  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
155  $char = pack('C*', $ord_var_c, ord($val{$c + 1}));
156  $c += 1;
157  $utf16 = utf82utf16($char);
158  $ascii .= sprintf('\u%04s', bin2hex($utf16));
159  break;
160 
161  case (($ord_var_c & 0xF0) == 0xE0):
162  // characters U-00000800 - U-0000FFFF, mask 1110XXXX
163  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
164  $char = pack('C*', $ord_var_c, ord($val{$c + 1}), ord($val{$c + 2}));
165  $c += 2;
166  $utf16 = utf82utf16($char);
167  $ascii .= sprintf('\u%04s', bin2hex($utf16));
168  break;
169 
170  case (($ord_var_c & 0xF8) == 0xF0):
171  // characters U-00010000 - U-001FFFFF, mask 11110XXX
172  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
173  $char = pack('C*', $ord_var_c, ord($val{$c + 1}), ord($val{$c + 2}), ord($val{$c + 3}));
174  $c += 3;
175  $utf16 = utf82utf16($char);
176  $ascii .= sprintf('\u%04s', bin2hex($utf16));
177  break;
178 
179  case (($ord_var_c & 0xFC) == 0xF8):
180  // characters U-00200000 - U-03FFFFFF, mask 111110XX
181  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
182  $char = pack('C*', $ord_var_c, ord($val{$c + 1}), ord($val{$c + 2}), ord($val{$c + 3}), ord($val{$c + 4}));
183  $c += 4;
184  $utf16 = utf82utf16($char);
185  $ascii .= sprintf('\u%04s', bin2hex($utf16));
186  break;
187 
188  case (($ord_var_c & 0xFE) == 0xFC):
189  // characters U-04000000 - U-7FFFFFFF, mask 1111110X
190  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
191  $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}));
192  $c += 5;
193  $utf16 = utf82utf16($char);
194  $ascii .= sprintf('\u%04s', bin2hex($utf16));
195  break;
196  }
197  }
198 
199  return '"'.$ascii.'"';
200  }
201  elseif (is_int($val)) return sprintf('%d', $val);
202  elseif (is_float($val)) return sprintf('%F', $val);
203  elseif (is_bool($val)) return ($val ? 'true' : 'false');
204  else return 'null';
205 }
206 
207 if (! function_exists('json_decode'))
208 {
216  function json_decode($json, $assoc=false)
217  {
218  return dol_json_decode($json, $assoc);
219  }
220 }
221 
230 function dol_json_decode($json, $assoc=false)
231 {
232  dol_syslog("For better performance, enable the native json in your PHP", LOG_WARNING);
233 
234  $comment = false;
235 
236  $out='';
237  $strLength = strlen($json); // Must stay strlen and not dol_strlen because we want technical length, not visible length
238  for ($i=0; $i<$strLength; $i++)
239  {
240  if (! $comment)
241  {
242  if (($json[$i] == '{') || ($json[$i] == '[')) $out.= 'array(';
243  else if (($json[$i] == '}') || ($json[$i] == ']')) $out.= ')';
244  else if ($json[$i] == ':') $out.= ' => ';
245  else $out.=$json[$i];
246  }
247  else $out.= $json[$i];
248  if ($json[$i] == '"' && $json[($i-1)]!="\\") $comment = !$comment;
249  }
250 
251  $out=_unval($out);
252 
253  // Return an array
254  if ($out != '') eval('$array = '.$out.';');
255  else $array=array();
256 
257  // Return an object
258  if (! $assoc)
259  {
260  if (! empty($array))
261  {
262  $object = false;
263  if (count($array)>0) {
264  $object = (object) array();
265  }
266  foreach ($array as $key => $value)
267  {
268  if ($key) $object->{$key} = $value;
269  }
270 
271  return $object;
272  }
273 
274  return false;
275  }
276 
277  return $array;
278 }
279 
286 function _unval($val)
287 {
288  while (preg_match('/\\\u([0-9A-F]{2})([0-9A-F]{2})/i', $val, $reg))
289  {
290  // single, escaped unicode character
291  $utf16 = chr(hexdec($reg[1])) . chr(hexdec($reg[2]));
292  $utf8 = utf162utf8($utf16);
293  $val=preg_replace('/\\\u'.$reg[1].$reg[2].'/i',$utf8,$val);
294  }
295  return $val;
296 }
297 
308 function utf162utf8($utf16)
309 {
310  // oh please oh please oh please oh please oh please
311  if(function_exists('mb_convert_encoding')) {
312  return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
313  }
314 
315  $bytes = (ord($utf16{0}) << 8) | ord($utf16{1});
316 
317  switch(true) {
318  case ((0x7F & $bytes) == $bytes):
319  // this case should never be reached, because we are in ASCII range
320  // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
321  return chr($bytes);
322 
323  case (0x07FF & $bytes) == $bytes:
324  // return a 2-byte UTF-8 character
325  // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
326  return chr(0xC0 | (($bytes >> 6) & 0x1F))
327  . chr(0x80 | ($bytes & 0x3F));
328 
329  case (0xFFFF & $bytes) == $bytes:
330  // return a 3-byte UTF-8 character
331  // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
332  return chr(0xE0 | (($bytes >> 12) & 0x0F))
333  . chr(0x80 | (($bytes >> 6) & 0x3F))
334  . chr(0x80 | ($bytes & 0x3F));
335  }
336 
337  // ignoring UTF-32 for now, sorry
338  return '';
339 }
340 
351 function utf82utf16($utf8)
352 {
353  // oh please oh please oh please oh please oh please
354  if(function_exists('mb_convert_encoding')) {
355  return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
356  }
357 
358  switch(strlen($utf8)) {
359  case 1:
360  // this case should never be reached, because we are in ASCII range
361  // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
362  return $utf8;
363 
364  case 2:
365  // return a UTF-16 character from a 2-byte UTF-8 char
366  // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
367  return chr(0x07 & (ord($utf8{0}) >> 2)) . chr((0xC0 & (ord($utf8{0}) << 6)) | (0x3F & ord($utf8{1})));
368 
369  case 3:
370  // return a UTF-16 character from a 3-byte UTF-8 char
371  // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
372  return chr((0xF0 & (ord($utf8{0}) << 4)) | (0x0F & (ord($utf8{1}) >> 2))) . chr((0xC0 & (ord($utf8{1}) << 6)) | (0x7F & ord($utf8{2})));
373  }
374 
375  // ignoring UTF-32 for now, sorry
376  return '';
377 }
_val($val)
Return text according to type.
Definition: json.lib.php:107
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.
Definition: json.lib.php:230
if(!function_exists('json_encode')) dol_json_encode($elements)
Implement json_encode for PHP that does not support it.
Definition: json.lib.php:47
utf162utf8($utf16)
Convert a string from one UTF-16 char to one UTF-8 char.
Definition: json.lib.php:308
_unval($val)
Return text according to type.
Definition: json.lib.php:286
utf82utf16($utf8)
Convert a string from one UTF-8 char to one UTF-16 char.
Definition: json.lib.php:351