00001 <?
00005 define('SERVICES_JSON_SLICE', 1);
00006
00010 define('SERVICES_JSON_IN_STR', 2);
00011
00015 define('SERVICES_JSON_IN_ARR', 3);
00016
00020 define('SERVICES_JSON_IN_OBJ', 4);
00021
00025 define('SERVICES_JSON_IN_CMT', 5);
00026
00030 define('SERVICES_JSON_LOOSE_TYPE', 16);
00031
00035 define('SERVICES_JSON_SUPPRESS_ERRORS', 32);
00036
00110 class Services_JSON
00111 {
00128 function Services_JSON($use = 0)
00129 {
00130 $this->use = $use;
00131 }
00132
00144 function utf162utf8($utf16)
00145 {
00146
00147 if(function_exists('mb_convert_encoding'))
00148 return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
00149
00150 $bytes = (ord($utf16{0}) << 8) | ord($utf16{1});
00151
00152 switch(true)
00153 {
00154 case ((0x7F & $bytes) == $bytes):
00155
00156
00157 return chr(0x7F & $bytes);
00158
00159 case (0x07FF & $bytes) == $bytes:
00160
00161
00162 return chr(0xC0 | (($bytes >> 6) & 0x1F))
00163 . chr(0x80 | ($bytes & 0x3F));
00164
00165 case (0xFFFF & $bytes) == $bytes:
00166
00167
00168 return chr(0xE0 | (($bytes >> 12) & 0x0F))
00169 . chr(0x80 | (($bytes >> 6) & 0x3F))
00170 . chr(0x80 | ($bytes & 0x3F));
00171 }
00172
00173
00174 return '';
00175 }
00176
00188 function utf82utf16($utf8)
00189 {
00190
00191 if(function_exists('mb_convert_encoding'))
00192 return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
00193
00194 switch(strlen($utf8))
00195 {
00196 case 1:
00197
00198
00199 return $utf8;
00200
00201 case 2:
00202
00203
00204 return chr(0x07 & (ord($utf8{0}) >> 2))
00205 . chr((0xC0 & (ord($utf8{0}) << 6))
00206 | (0x3F & ord($utf8{1})));
00207
00208 case 3:
00209
00210
00211 return chr((0xF0 & (ord($utf8{0}) << 4))
00212 | (0x0F & (ord($utf8{1}) >> 2)))
00213 . chr((0xC0 & (ord($utf8{1}) << 6))
00214 | (0x7F & ord($utf8{2})));
00215 }
00216
00217
00218 return '';
00219 }
00220
00232 function encode($var)
00233 {
00234 switch (gettype($var))
00235 {
00236 case 'boolean':
00237 return $var ? 'true' : 'false';
00238
00239 case 'NULL':
00240 return 'null';
00241
00242 case 'integer':
00243 return (int) $var;
00244
00245 case 'double':
00246 case 'float':
00247 return (float) $var;
00248
00249 case 'string':
00250
00251 $ascii = '';
00252 $strlen_var = strlen($var);
00253
00254
00255
00256
00257
00258 for ($c = 0; $c < $strlen_var; ++$c)
00259 {
00260 $ord_var_c = ord($var{$c});
00261
00262 switch (true)
00263 {
00264 case $ord_var_c == 0x08:
00265 $ascii .= '\b';
00266 break;
00267 case $ord_var_c == 0x09:
00268 $ascii .= '\t';
00269 break;
00270 case $ord_var_c == 0x0A:
00271 $ascii .= '\n';
00272 break;
00273 case $ord_var_c == 0x0C:
00274 $ascii .= '\f';
00275 break;
00276 case $ord_var_c == 0x0D:
00277 $ascii .= '\r';
00278 break;
00279
00280 case $ord_var_c == 0x22:
00281 case $ord_var_c == 0x2F:
00282 case $ord_var_c == 0x5C:
00283
00284 $ascii .= '\\'.$var{$c};
00285 break;
00286
00287 case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
00288
00289 $ascii .= $var{$c};
00290 break;
00291
00292 case (($ord_var_c & 0xE0) == 0xC0):
00293
00294
00295 $char = pack('C*', $ord_var_c, ord($var{$c + 1}));
00296 $c += 1;
00297 $utf16 = $this->utf82utf16($char);
00298 $ascii .= sprintf('\u%04s', bin2hex($utf16));
00299 break;
00300
00301 case (($ord_var_c & 0xF0) == 0xE0):
00302
00303
00304 $char = pack('C*', $ord_var_c,
00305 ord($var{$c + 1}),
00306 ord($var{$c + 2}));
00307 $c += 2;
00308 $utf16 = $this->utf82utf16($char);
00309 $ascii .= sprintf('\u%04s', bin2hex($utf16));
00310 break;
00311
00312 case (($ord_var_c & 0xF8) == 0xF0):
00313
00314
00315 $char = pack('C*', $ord_var_c,
00316 ord($var{$c + 1}),
00317 ord($var{$c + 2}),
00318 ord($var{$c + 3}));
00319 $c += 3;
00320 $utf16 = $this->utf82utf16($char);
00321 $ascii .= sprintf('\u%04s', bin2hex($utf16));
00322 break;
00323
00324 case (($ord_var_c & 0xFC) == 0xF8):
00325
00326
00327 $char = pack('C*', $ord_var_c,
00328 ord($var{$c + 1}),
00329 ord($var{$c + 2}),
00330 ord($var{$c + 3}),
00331 ord($var{$c + 4}));
00332 $c += 4;
00333 $utf16 = $this->utf82utf16($char);
00334 $ascii .= sprintf('\u%04s', bin2hex($utf16));
00335 break;
00336
00337 case (($ord_var_c & 0xFE) == 0xFC):
00338
00339
00340 $char = pack('C*', $ord_var_c,
00341 ord($var{$c + 1}),
00342 ord($var{$c + 2}),
00343 ord($var{$c + 3}),
00344 ord($var{$c + 4}),
00345 ord($var{$c + 5}));
00346 $c += 5;
00347 $utf16 = $this->utf82utf16($char);
00348 $ascii .= sprintf('\u%04s', bin2hex($utf16));
00349 break;
00350 }
00351 }
00352
00353 return '"'.$ascii.'"';
00354
00355 case 'array':
00356
00357
00358
00359
00360
00361
00362
00363
00364
00365
00366
00367
00368
00369
00370
00371
00372
00373
00374
00375 if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1)))
00376 {
00377 $properties = array_map(array($this, 'name_value'),
00378 array_keys($var),
00379 array_values($var));
00380
00381 foreach($properties as $property)
00382 if(Services_JSON::isError($property))
00383 return $property;
00384
00385 return '{' . join(',', $properties) . '}';
00386 }
00387
00388
00389 $elements = array_map(array($this, 'encode'), $var);
00390
00391 foreach($elements as $element)
00392 if(Services_JSON::isError($element))
00393 return $element;
00394
00395 return '[' . join(',', $elements) . ']';
00396
00397 case 'object':
00398 $vars = get_object_vars($var);
00399
00400 $properties = array_map(array($this, 'name_value'),
00401 array_keys($vars),
00402 array_values($vars));
00403
00404 foreach($properties as $property)
00405 if(Services_JSON::isError($property))
00406 return $property;
00407
00408 return '{' . join(',', $properties) . '}';
00409
00410 default:
00411 return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
00412 ? 'null'
00413 : new Services_JSON_Error(gettype($var)." can not be encoded as JSON string");
00414 }
00415 }
00416
00426 function name_value($name, $value)
00427 {
00428 $encoded_value = $this->encode($value);
00429
00430 if(Services_JSON::isError($encoded_value))
00431 return $encoded_value;
00432
00433 return $this->encode(strval($name)) . ':' . $encoded_value;
00434 }
00435
00444 function reduce_string($str)
00445 {
00446 $str = preg_replace(array(
00447
00448
00449 '#^\s*
00450
00451
00452 '#^\s*/\*(.+)\*/#Us',
00453
00454
00455 '#/\*(.+)\*/\s*$#Us'
00456
00457 ), '', $str);
00458
00459
00460 return trim($str);
00461 }
00462
00475 function decode($str)
00476 {
00477 $str = $this->reduce_string($str);
00478
00479 switch (strtolower($str))
00480 {
00481 case 'true':
00482 return true;
00483
00484 case 'false':
00485 return false;
00486
00487 case 'null':
00488 return null;
00489
00490 default:
00491 $m = array();
00492 if (is_numeric($str))
00493 {
00494
00495
00496
00497
00498
00499
00500
00501 return ((float)$str == (integer)$str)
00502 ? (integer)$str
00503 : (float)$str;
00504
00505 }
00506 elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2])
00507 {
00508 // STRINGS RETURNED IN UTF-8 FORMAT
00509 $delim = substr($str, 0, 1);
00510 $chrs = substr($str, 1, -1);
00511 $utf8 = '';
00512 $strlen_chrs = strlen($chrs);
00513
00514 for ($c = 0; $c < $strlen_chrs; ++$c)
00515 {
00516
00517 $substr_chrs_c_2 = substr($chrs, $c, 2);
00518 $ord_chrs_c = ord($chrs{$c});
00519
00520 switch (true)
00521 {
00522 case $substr_chrs_c_2 == '\b':
00523 $utf8 .= chr(0x08);
00524 ++$c;
00525 break;
00526 case $substr_chrs_c_2 == '\t':
00527 $utf8 .= chr(0x09);
00528 ++$c;
00529 break;
00530 case $substr_chrs_c_2 == '\n':
00531 $utf8 .= chr(0x0A);
00532 ++$c;
00533 break;
00534 case $substr_chrs_c_2 == '\f':
00535 $utf8 .= chr(0x0C);
00536 ++$c;
00537 break;
00538 case $substr_chrs_c_2 == '\r':
00539 $utf8 .= chr(0x0D);
00540 ++$c;
00541 break;
00542
00543 case $substr_chrs_c_2 == '\\"':
00544 case $substr_chrs_c_2 == '\\\'':
00545 case $substr_chrs_c_2 == '\\\\':
00546 case $substr_chrs_c_2 == '\\/':
00547 if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
00548 ($delim == "'" && $substr_chrs_c_2 != '\\"'))
00549 {
00550 $utf8 .= $chrs{++$c};
00551 }
00552 break;
00553
00554 case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)):
00555 // single, escaped unicode character
00556 $utf16 = chr(hexdec(substr($chrs, ($c + 2), 2)))
00557 . chr(hexdec(substr($chrs, ($c + 4), 2)));
00558 $utf8 .= $this->utf162utf8($utf16);
00559 $c += 5;
00560 break;
00561
00562 case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
00563 $utf8 .= $chrs{$c};
00564 break;
00565
00566 case ($ord_chrs_c & 0xE0) == 0xC0:
00567 // characters U-00000080 - U-000007FF, mask 110XXXXX
00568 //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
00569 $utf8 .= substr($chrs, $c, 2);
00570 ++$c;
00571 break;
00572
00573 case ($ord_chrs_c & 0xF0) == 0xE0:
00574 // characters U-00000800 - U-0000FFFF, mask 1110XXXX
00575 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
00576 $utf8 .= substr($chrs, $c, 3);
00577 $c += 2;
00578 break;
00579
00580 case ($ord_chrs_c & 0xF8) == 0xF0:
00581 // characters U-00010000 - U-001FFFFF, mask 11110XXX
00582 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
00583 $utf8 .= substr($chrs, $c, 4);
00584 $c += 3;
00585 break;
00586
00587 case ($ord_chrs_c & 0xFC) == 0xF8:
00588 // characters U-00200000 - U-03FFFFFF, mask 111110XX
00589 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
00590 $utf8 .= substr($chrs, $c, 5);
00591 $c += 4;
00592 break;
00593
00594 case ($ord_chrs_c & 0xFE) == 0xFC:
00595 // characters U-04000000 - U-7FFFFFFF, mask 1111110X
00596 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
00597 $utf8 .= substr($chrs, $c, 6);
00598 $c += 5;
00599 break;
00600
00601 }
00602
00603 }
00604
00605 return $utf8;
00606
00607 } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str))
00608 {
00609 // array, or object notation
00610
00611 if ($str{0} == '[')
00612 {
00613 $stk = array(SERVICES_JSON_IN_ARR);
00614 $arr = array();
00615 }
00616 else
00617 {
00618 if ($this->use & SERVICES_JSON_LOOSE_TYPE)
00619 {
00620 $stk = array(SERVICES_JSON_IN_OBJ);
00621 $obj = array();
00622 }
00623 else
00624 {
00625 $stk = array(SERVICES_JSON_IN_OBJ);
00626 $obj = new stdClass();
00627 }
00628 }
00629
00630 array_push($stk, array('what' => SERVICES_JSON_SLICE,
00631 'where' => 0,
00632 'delim' => false));
00633
00634 $chrs = substr($str, 1, -1);
00635 $chrs = $this->reduce_string($chrs);
00636
00637 if ($chrs == '')
00638 {
00639 if (reset($stk) == SERVICES_JSON_IN_ARR)
00640 {
00641 return $arr;
00642
00643 } else {
00644 return $obj;
00645
00646 }
00647 }
00648
00649 //print("\nparsing {$chrs}\n");
00650
00651 $strlen_chrs = strlen($chrs);
00652
00653 for ($c = 0; $c <= $strlen_chrs; ++$c)
00654 {
00655
00656 $top = end($stk);
00657 $substr_chrs_c_2 = substr($chrs, $c, 2);
00658
00659 if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE)))
00660 {
00661 // found a comma that is not inside a string, array, etc.,
00662 // OR we've reached the end of the character list
00663 $slice = substr($chrs, $top['where'], ($c - $top['where']));
00664 array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false));
00665 //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
00666
00667 if (reset($stk) == SERVICES_JSON_IN_ARR)
00668 {
00669 // we are in an array, so just push an element onto the stack
00670 array_push($arr, $this->decode($slice));
00671
00672 } elseif (reset($stk) == SERVICES_JSON_IN_OBJ)
00673 {
00674 // we are in an object, so figure
00675 // out the property name and set an
00676 // element in an associative array,
00677 // for now
00678 $parts = array();
00679 if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts))
00680 {
00681 // "name":value pair
00682 $key = $this->decode($parts[1]);
00683 $val = $this->decode($parts[2]);
00684
00685 if ($this->use & SERVICES_JSON_LOOSE_TYPE)
00686 {
00687 $obj[$key] = $val;
00688 } else {
00689 $obj->$key = $val;
00690 }
00691 } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts))
00692 {
00693 // name:value pair, where name is unquoted
00694 $key = $parts[1];
00695 $val = $this->decode($parts[2]);
00696
00697 if ($this->use & SERVICES_JSON_LOOSE_TYPE)
00698 {
00699 $obj[$key] = $val;
00700 } else {
00701 $obj->$key = $val;
00702 }
00703 }
00704
00705 }
00706
00707 } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR))
00708 {
00709
00710 array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c}));
00711
00712
00713 } elseif (($chrs{$c} == $top['delim']) &&
00714 ($top['what'] == SERVICES_JSON_IN_STR) &&
00715 (($chrs{$c - 1} != '\\') ||
00716 ($chrs{$c - 1} == '\\' && $chrs{$c - 2} == '\\')))
00717 {
00718
00719 array_pop($stk);
00720
00721
00722 } elseif (($chrs{$c} == '[') &&
00723 in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ)))
00724 {
00725
00726 array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false));
00727
00728
00729 } elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR))
00730 {
00731
00732 array_pop($stk);
00733
00734
00735 } elseif (($chrs{$c} == '{') &&
00736 in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ)))
00737 {
00738
00739 array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false));
00740
00741
00742 } elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ))
00743 {
00744
00745 array_pop($stk);
00746
00747
00748 } elseif (($substr_chrs_c_2 == '
00749
00750
00751
00752
00753
00754
00755
00756 ') && ($top['what'] == SERVICES_JSON_IN_CMT))
00757 {
00758
00759 array_pop($stk);
00760 $c++;
00761
00762 for ($i = $top['where']; $i <= $c; ++$i)
00763 $chrs = substr_replace($chrs, ' ', $i, 1);
00764
00765
00766
00767 }
00768
00769 }
00770
00771 if (reset($stk) == SERVICES_JSON_IN_ARR)
00772 {
00773 return $arr;
00774
00775 }
00776 elseif (reset($stk) == SERVICES_JSON_IN_OBJ)
00777 {
00778 return $obj;
00779
00780 }
00781
00782 }
00783 }
00784 }
00785
00789 function isError($data, $code = null)
00790 {
00791 if (class_exists('pear'))
00792 {
00793 return PEAR::isError($data, $code);
00794 } elseif (is_object($data) && (get_class($data) == 'services_json_error' ||
00795 is_subclass_of($data, 'services_json_error')))
00796 {
00797 return true;
00798 }
00799
00800 return false;
00801 }
00802 }
00803
00804 if (class_exists('pear_error'))
00805 {
00806
00807 class Services_JSON_Error extends PEAR_Error
00808 {
00809 function Services_JSON_Error($message = 'unknown error', $code = null,
00810 $mode = null, $options = null, $userinfo = null)
00811 {
00812 parent::PEAR_Error($message, $code, $mode, $options, $userinfo);
00813 }
00814 }
00815
00816 }
00817 else
00818 {
00819
00823 class Services_JSON_Error
00824 {
00825 function Services_JSON_Error($message = 'unknown error', $code = null,
00826 $mode = null, $options = null, $userinfo = null)
00827 {
00828
00829 }
00830 }
00831
00832 }
00833
00834 function json_encode($text)
00835 {
00836 $json = new Services_JSON();
00837 return $json->encode($text);
00838 }
00839
00840 function json_decode($text)
00841 {
00842 $json = new Services_JSON();
00843 return $json->decode($text);
00844 }