File modules/util/JSON.class.php

Last commit: Fri Feb 26 00:04:49 2021 +0100	Jan Dankert	New: Request may contain JSON,XML in POST data. This is good for API clients.
1 <?php 2 /** 3 * Converts to and from JSON format. 4 * 5 * JSON (JavaScript Object Notation) is a lightweight data-interchange 6 * format. It is easy for humans to read and write. It is easy for machines 7 * to parse and generate. It is based on a subset of the JavaScript 8 * Programming Language, Standard ECMA-262 3rd Edition - December 1999. 9 * This feature can also be found in Python. JSON is a text format that is 10 * completely language independent but uses conventions that are familiar 11 * to programmers of the C-family of languages, including C, C++, C#, Java, 12 * JavaScript, Perl, TCL, and many others. These properties make JSON an 13 * ideal data-interchange language. 14 * 15 * This package provides a simple encoder and decoder for JSON notation. It 16 * is intended for use with client-side Javascript applications that make 17 * use of HTTPRequest to perform server communication functions - data can 18 * be encoded into JSON notation for use in a client-side javascript, or 19 * decoded from incoming Javascript requests. JSON format is native to 20 * Javascript, and can be directly eval()'ed with no further parsing 21 * overhead 22 * 23 * All strings should be in ASCII or UTF-8 format! 24 * 25 * LICENSE: Redistribution and use in source and binary forms, with or 26 * without modification, are permitted provided that the following 27 * conditions are met: Redistributions of source code must retain the 28 * above copyright notice, this list of conditions and the following 29 * disclaimer. Redistributions in binary form must reproduce the above 30 * copyright notice, this list of conditions and the following disclaimer 31 * in the documentation and/or other materials provided with the 32 * distribution. 33 * 34 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED 35 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 36 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN 37 * NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 38 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 39 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS 40 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 41 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR 42 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 43 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 44 * DAMAGE. 45 * 46 * @category 47 * @package Services_JSON 48 * @author Michal Migurski <mike-json@teczno.com> 49 * @author Matt Knapp <mdknapp[at]gmail[dot]com> 50 * @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com> 51 * @author Jan Dankert 52 * @copyright 2005 Michal Migurski 53 * @version CVS: $Id$ 54 * @license http://www.opensource.org/licenses/bsd-license.php 55 * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198 56 */ 57 58 /** 59 * Marker constant for Services_JSON::decode(), used to flag stack state 60 */ 61 define('SERVICES_JSON_INDENT', "\t"); 62 63 /** 64 * Marker constant for Services_JSON::decode(), used to flag stack state 65 */ 66 define('SERVICES_JSON_SLICE', 1); 67 68 /** 69 * Marker constant for Services_JSON::decode(), used to flag stack state 70 */ 71 define('SERVICES_JSON_IN_STR', 2); 72 73 /** 74 * Marker constant for Services_JSON::decode(), used to flag stack state 75 */ 76 define('SERVICES_JSON_IN_ARR', 3); 77 78 /** 79 * Marker constant for Services_JSON::decode(), used to flag stack state 80 */ 81 define('SERVICES_JSON_IN_OBJ', 4); 82 83 /** 84 * Marker constant for Services_JSON::decode(), used to flag stack state 85 */ 86 define('SERVICES_JSON_IN_CMT', 5); 87 88 /** 89 * Behavior switch for Services_JSON::decode() 90 */ 91 define('SERVICES_JSON_LOOSE_TYPE', 16); 92 93 /** 94 * Behavior switch for Services_JSON::decode() 95 */ 96 define('SERVICES_JSON_SUPPRESS_ERRORS', 32); 97 98 /** 99 * Converts to and from JSON format. 100 * 101 * Brief example of use: 102 * 103 * <code> 104 * // create a new instance of Services_JSON 105 * $json = new Services_JSON(); 106 * 107 * // convert a complexe value to JSON notation, and send it to the browser 108 * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4))); 109 * $output = $json->encode($value); 110 * 111 * print($output); 112 * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]] 113 * 114 * // accept incoming POST data, assumed to be in JSON notation 115 * $input = file_get_contents('php://input', 1000000); 116 * $value = $json->decode($input); 117 * </code> 118 */ 119 class JSON 120 { 121 /** 122 * constructs a new JSON instance 123 * 124 * @param int $use object behavior flags; combine with boolean-OR 125 * 126 * possible values: 127 * - SERVICES_JSON_LOOSE_TYPE: loose typing. 128 * "{...}" syntax creates associative arrays 129 * instead of objects in decode(). 130 * - SERVICES_JSON_SUPPRESS_ERRORS: error suppression. 131 * Values which can't be encoded (e.g. resources) 132 * appear as NULL instead of throwing errors. 133 * By default, a deeply-nested resource will 134 * bubble up with an error, so all return values 135 * from encode() should be checked with isError() 136 */ 137 function __construct() 138 { 139 $this->use = SERVICES_JSON_LOOSE_TYPE; 140 } 141 142 /** 143 * convert a string from one UTF-16 char to one UTF-8 char 144 * 145 * Normally should be handled by mb_convert_encoding, but 146 * provides a slower PHP-only method for installations 147 * that lack the multibye string extension. 148 * 149 * @param string $utf16 UTF-16 character 150 * @return string UTF-8 character 151 * @access private 152 */ 153 function utf162utf8($utf16) 154 { 155 // oh please oh please oh please oh please oh please 156 if(function_exists('mb_convert_encoding')) { 157 return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16'); 158 } 159 160 $bytes = (ord($utf16[0]) << 8) | ord($utf16[1]); 161 162 switch(true) { 163 case ((0x7F & $bytes) == $bytes): 164 // this case should never be reached, because we are in ASCII range 165 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 166 return chr(0x7F & $bytes); 167 168 case (0x07FF & $bytes) == $bytes: 169 // return a 2-byte UTF-8 character 170 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 171 return chr(0xC0 | (($bytes >> 6) & 0x1F)) 172 . chr(0x80 | ($bytes & 0x3F)); 173 174 case (0xFFFF & $bytes) == $bytes: 175 // return a 3-byte UTF-8 character 176 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 177 return chr(0xE0 | (($bytes >> 12) & 0x0F)) 178 . chr(0x80 | (($bytes >> 6) & 0x3F)) 179 . chr(0x80 | ($bytes & 0x3F)); 180 } 181 182 // ignoring UTF-32 for now, sorry 183 return ''; 184 } 185 186 /** 187 * convert a string from one UTF-8 char to one UTF-16 char 188 * 189 * Normally should be handled by mb_convert_encoding, but 190 * provides a slower PHP-only method for installations 191 * that lack the multibye string extension. 192 * 193 * @param string $utf8 UTF-8 character 194 * @return string UTF-16 character 195 * @access private 196 */ 197 function utf82utf16($utf8) 198 { 199 // oh please oh please oh please oh please oh please 200 if(function_exists('mb_convert_encoding')) { 201 return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8'); 202 } 203 204 switch(strlen($utf8)) { 205 case 1: 206 // this case should never be reached, because we are in ASCII range 207 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 208 return $utf8; 209 210 case 2: 211 // return a UTF-16 character from a 2-byte UTF-8 char 212 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 213 return chr(0x07 & (ord($utf8[0]) >> 2)) 214 . chr((0xC0 & (ord($utf8[0]) << 6)) 215 | (0x3F & ord($utf8[1]))); 216 217 case 3: 218 // return a UTF-16 character from a 3-byte UTF-8 char 219 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 220 return chr((0xF0 & (ord($utf8[0]) << 4)) 221 | (0x0F & (ord($utf8[1]) >> 2))) 222 . chr((0xC0 & (ord($utf8[1]) << 6)) 223 | (0x7F & ord($utf8[2]))); 224 } 225 226 // ignoring UTF-32 for now, sorry 227 return ''; 228 } 229 230 /** 231 * encodes an arbitrary variable into JSON format 232 * 233 * @param mixed $var any number, boolean, string, array, or object to be encoded. 234 * see argument 1 to Services_JSON() above for array-parsing behavior. 235 * if var is a strng, note that encode() always expects it 236 * to be in ASCII or UTF-8 format! 237 * 238 * @return mixed JSON string representation of input var or an error if a problem occurs 239 * @access public 240 */ 241 function encode($var) 242 { 243 static $indentNr = 0; 244 245 $indent = str_repeat(SERVICES_JSON_INDENT,$indentNr); 246 247 switch (gettype($var)) { 248 case 'boolean': 249 return $var ? 'true' : 'false'; 250 251 case 'NULL': 252 return 'null'; 253 254 case 'integer': 255 return (int) $var; 256 257 case 'double': 258 case 'float': 259 return (float) $var; 260 261 case 'string': 262 // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT 263 $ascii = ''; 264 $strlen_var = strlen($var); 265 266 /* 267 * Iterate over every character in the string, 268 * escaping with a slash or encoding to UTF-8 where necessary 269 */ 270 for ($c = 0; $c < $strlen_var; ++$c) { 271 272 $ord_var_c = ord($var[$c]); 273 274 switch (true) { 275 case $ord_var_c == 0x08: 276 $ascii .= '\b'; 277 break; 278 case $ord_var_c == 0x09: 279 $ascii .= '\t'; 280 break; 281 case $ord_var_c == 0x0A: 282 $ascii .= '\n'; 283 break; 284 case $ord_var_c == 0x0C: 285 $ascii .= '\f'; 286 break; 287 case $ord_var_c == 0x0D: 288 $ascii .= '\r'; 289 break; 290 291 case $ord_var_c == 0x22: 292 case $ord_var_c == 0x2F: 293 case $ord_var_c == 0x5C: 294 // double quote, slash, slosh 295 $ascii .= '\\'.$var[$c]; 296 break; 297 298 case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)): 299 // characters U-00000000 - U-0000007F (same as ASCII) 300 $ascii .= $var[$c]; 301 break; 302 303 case (($ord_var_c & 0xE0) == 0xC0): 304 // characters U-00000080 - U-000007FF, mask 110XXXXX 305 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 306 $char = pack('C*', $ord_var_c, ord($var[$c + 1])); 307 $c += 1; 308 $utf16 = $this->utf82utf16($char); 309 $ascii .= sprintf('\u%04s', bin2hex($utf16)); 310 break; 311 312 case (($ord_var_c & 0xF0) == 0xE0): 313 // characters U-00000800 - U-0000FFFF, mask 1110XXXX 314 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 315 $char = pack('C*', $ord_var_c, 316 @ord($var[$c + 1]), 317 @ord($var[$c + 2])); 318 $c += 2; 319 $utf16 = $this->utf82utf16($char); 320 $ascii .= sprintf('\u%04s', bin2hex($utf16)); 321 break; 322 323 case (($ord_var_c & 0xF8) == 0xF0): 324 // characters U-00010000 - U-001FFFFF, mask 11110XXX 325 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 326 $char = pack('C*', $ord_var_c, 327 @ord($var[$c + 1]), 328 @ord($var[$c + 2]), 329 @ord($var[$c + 3])); 330 $c += 3; 331 $utf16 = $this->utf82utf16($char); 332 $ascii .= sprintf('\u%04s', bin2hex($utf16)); 333 break; 334 335 case (($ord_var_c & 0xFC) == 0xF8): 336 // characters U-00200000 - U-03FFFFFF, mask 111110XX 337 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 338 $char = pack('C*', $ord_var_c, 339 @ord($var[$c + 1]), 340 @ord($var[$c + 2]), 341 @ord($var[$c + 3]), 342 @ord($var[$c + 4])); 343 $c += 4; 344 $utf16 = $this->utf82utf16($char); 345 $ascii .= sprintf('\u%04s', bin2hex($utf16)); 346 break; 347 348 case (($ord_var_c & 0xFE) == 0xFC): 349 // characters U-04000000 - U-7FFFFFFF, mask 1111110X 350 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 351 $char = pack('C*', $ord_var_c, 352 @ord($var[$c + 1]), 353 @ord($var[$c + 2]), 354 @ord($var[$c + 3]), 355 @ord($var[$c + 4]), 356 @ord(@$var[$c + 5])); 357 $c += 5; 358 $utf16 = $this->utf82utf16($char); 359 $ascii .= sprintf('\u%04s', bin2hex($utf16)); 360 break; 361 } 362 } 363 364 return '"'.$ascii.'"'; 365 366 case 'array': 367 /* 368 * As per JSON spec if any array key is not an integer 369 * we must treat the the whole array as an object. We 370 * also try to catch a sparsely populated associative 371 * array with numeric keys here because some JS engines 372 * will create an array with empty indexes up to 373 * max_index which can cause memory issues and because 374 * the keys, which may be relevant, will be remapped 375 * otherwise. 376 * 377 * As per the ECMA and JSON specification an object may 378 * have any string as a property. Unfortunately due to 379 * a hole in the ECMA specification if the key is a 380 * ECMA reserved word or starts with a digit the 381 * parameter is only accessible using ECMAScript's 382 * bracket notation. 383 */ 384 385 // treat as a JSON object 386 if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) { 387 $indentNr++; 388 $properties = array_map(array($this, 'name_value'), 389 array_keys($var), 390 array_values($var)); 391 $indentNr--; 392 393 foreach($properties as $property) { 394 if(JSON::isError($property)) { 395 return $property; 396 } 397 } 398 399 return "\n$indent".'{' ."\n$indent".SERVICES_JSON_INDENT. join(','."\n$indent".SERVICES_JSON_INDENT, $properties) ."\n$indent".'}'."\n$indent"; 400 } 401 402 // treat it like a regular array 403 $indentNr++; 404 $elements = array_map(array($this, 'encode'), $var); 405 $indentNr--; 406 407 foreach($elements as $element) { 408 if(JSON::isError($element)) { 409 return $element; 410 } 411 } 412 413 return "\n$indent".'['."\n$indent".SERVICES_JSON_INDENT. join(','."\n$indent".SERVICES_JSON_INDENT, $elements) . "\n$indent".']'."\n$indent"; 414 415 case 'object': 416 $vars = get_object_vars($var); 417 418 $indentNr++; 419 $properties = array_map(array($this, 'name_value'), 420 array_keys($vars), 421 array_values($vars)); 422 $indentNr--; 423 424 foreach($properties as $property) { 425 if(JSON::isError($property)) { 426 return $property; 427 } 428 } 429 430 return "\n$indent".'{' ."\n$indent".SERVICES_JSON_INDENT. join(','."\n$indent".SERVICES_JSON_INDENT, $properties) . "\n$indent".'}'."\n$indent"; 431 432 default: 433 return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS) 434 ? 'null' 435 : new JSON_Error(gettype($var)." can not be encoded as JSON string"); 436 } 437 } 438 439 440 441 /** 442 * array-walking function for use in generating JSON-formatted name-value pairs 443 * 444 * @param string $name name of key to use 445 * @param mixed $value reference to an array element to be encoded 446 * 447 * @return string JSON-formatted name-value pair, like '"name":value' 448 * @access private 449 */ 450 function name_value($name, $value ) 451 { 452 $encoded_value = $this->encode($value); 453 454 if(JSON::isError($encoded_value)) { 455 return $encoded_value; 456 } 457 458 return $this->encode(strval($name)) . ':' . $encoded_value; 459 } 460 461 /** 462 * reduce a string by removing leading and trailing comments and whitespace 463 * 464 * @param $str string string value to strip of comments and whitespace 465 * 466 * @return string string value stripped of comments and whitespace 467 * @access private 468 */ 469 function reduce_string($str) 470 { 471 $str = preg_replace(array( 472 473 // eliminate single line comments in '// ...' form 474 '#^\s*//(.+)$#m', 475 476 // eliminate multi-line comments in '/* ... */' form, at start of string 477 '#^\s*/\*(.+)\*/#Us', 478 479 // eliminate multi-line comments in '/* ... */' form, at end of string 480 '#/\*(.+)\*/\s*$#Us' 481 482 ), '', $str); 483 484 // eliminate extraneous space 485 return trim($str); 486 } 487 488 /** 489 * decodes a JSON string into appropriate variable 490 * 491 * @param string $str JSON-formatted string 492 * 493 * @return mixed number, boolean, string, array, or object 494 * corresponding to given JSON input string. 495 * See argument 1 to Services_JSON() above for object-output behavior. 496 * Note that decode() always returns strings 497 * in ASCII or UTF-8 format! 498 * @access public 499 */ 500 function decode($str) 501 { 502 $str = $this->reduce_string($str); 503 504 switch (strtolower($str)) { 505 case 'true': 506 return true; 507 508 case 'false': 509 return false; 510 511 case 'null': 512 return null; 513 514 default: 515 $m = array(); 516 517 if (is_numeric($str)) { 518 // Lookie-loo, it's a number 519 520 // This would work on its own, but I'm trying to be 521 // good about returning integers where appropriate: 522 // return (float)$str; 523 524 // Return float or int, as appropriate 525 return ((float)$str == (integer)$str) 526 ? (integer)$str 527 : (float)$str; 528 529 } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) { 530 // STRINGS RETURNED IN UTF-8 FORMAT 531 $delim = substr($str, 0, 1); 532 $chrs = substr($str, 1, -1); 533 $utf8 = ''; 534 $strlen_chrs = strlen($chrs); 535 536 for ($c = 0; $c < $strlen_chrs; ++$c) { 537 538 $substr_chrs_c_2 = substr($chrs, $c, 2); 539 $ord_chrs_c = ord($chrs[$c]); 540 541 switch (true) { 542 case $substr_chrs_c_2 == '\b': 543 $utf8 .= chr(0x08); 544 ++$c; 545 break; 546 case $substr_chrs_c_2 == '\t': 547 $utf8 .= chr(0x09); 548 ++$c; 549 break; 550 case $substr_chrs_c_2 == '\n': 551 $utf8 .= chr(0x0A); 552 ++$c; 553 break; 554 case $substr_chrs_c_2 == '\f': 555 $utf8 .= chr(0x0C); 556 ++$c; 557 break; 558 case $substr_chrs_c_2 == '\r': 559 $utf8 .= chr(0x0D); 560 ++$c; 561 break; 562 563 case $substr_chrs_c_2 == '\\"': 564 case $substr_chrs_c_2 == '\\\'': 565 case $substr_chrs_c_2 == '\\\\': 566 case $substr_chrs_c_2 == '\\/': 567 if (($delim == '"' && $substr_chrs_c_2 != '\\\'') || 568 ($delim == "'" && $substr_chrs_c_2 != '\\"')) { 569 $utf8 .= $chrs[++$c]; 570 } 571 break; 572 573 case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)): 574 // single, escaped unicode character 575 $utf16 = chr(hexdec(substr($chrs, ($c + 2), 2))) 576 . chr(hexdec(substr($chrs, ($c + 4), 2))); 577 $utf8 .= $this->utf162utf8($utf16); 578 $c += 5; 579 break; 580 581 case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F): 582 $utf8 .= $chrs[$c]; 583 break; 584 585 case ($ord_chrs_c & 0xE0) == 0xC0: 586 // characters U-00000080 - U-000007FF, mask 110XXXXX 587 //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 588 $utf8 .= substr($chrs, $c, 2); 589 ++$c; 590 break; 591 592 case ($ord_chrs_c & 0xF0) == 0xE0: 593 // characters U-00000800 - U-0000FFFF, mask 1110XXXX 594 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 595 $utf8 .= substr($chrs, $c, 3); 596 $c += 2; 597 break; 598 599 case ($ord_chrs_c & 0xF8) == 0xF0: 600 // characters U-00010000 - U-001FFFFF, mask 11110XXX 601 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 602 $utf8 .= substr($chrs, $c, 4); 603 $c += 3; 604 break; 605 606 case ($ord_chrs_c & 0xFC) == 0xF8: 607 // characters U-00200000 - U-03FFFFFF, mask 111110XX 608 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 609 $utf8 .= substr($chrs, $c, 5); 610 $c += 4; 611 break; 612 613 case ($ord_chrs_c & 0xFE) == 0xFC: 614 // characters U-04000000 - U-7FFFFFFF, mask 1111110X 615 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 616 $utf8 .= substr($chrs, $c, 6); 617 $c += 5; 618 break; 619 620 } 621 622 } 623 624 return $utf8; 625 626 } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) { 627 // array, or object notation 628 629 if ($str[0] == '[') { 630 $stk = array(SERVICES_JSON_IN_ARR); 631 $arr = array(); 632 } else { 633 if ($this->use & SERVICES_JSON_LOOSE_TYPE) { 634 $stk = array(SERVICES_JSON_IN_OBJ); 635 $obj = array(); 636 } else { 637 $stk = array(SERVICES_JSON_IN_OBJ); 638 $obj = new stdClass(); 639 } 640 } 641 642 array_push($stk, array('what' => SERVICES_JSON_SLICE, 643 'where' => 0, 644 'delim' => false)); 645 646 $chrs = substr($str, 1, -1); 647 $chrs = $this->reduce_string($chrs); 648 649 if ($chrs == '') { 650 if (reset($stk) == SERVICES_JSON_IN_ARR) { 651 return $arr; 652 653 } else { 654 return $obj; 655 656 } 657 } 658 659 //print("\nparsing {$chrs}\n"); 660 661 $strlen_chrs = strlen($chrs); 662 663 for ($c = 0; $c <= $strlen_chrs; ++$c) { 664 665 $top = end($stk); 666 $substr_chrs_c_2 = substr($chrs, $c, 2); 667 668 if (($c == $strlen_chrs) || (($chrs[$c] == ',') && ($top['what'] == SERVICES_JSON_SLICE))) { 669 // found a comma that is not inside a string, array, etc., 670 // OR we've reached the end of the character list 671 $slice = substr($chrs, $top['where'], ($c - $top['where'])); 672 array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false)); 673 //print("Found split at [$c]: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); 674 675 if (reset($stk) == SERVICES_JSON_IN_ARR) { 676 // we are in an array, so just push an element onto the stack 677 array_push($arr, $this->decode($slice)); 678 679 } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { 680 // we are in an object, so figure 681 // out the property name and set an 682 // element in an associative array, 683 // for now 684 $parts = array(); 685 686 if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { 687 // "name":value pair 688 $key = $this->decode($parts[1]); 689 $val = $this->decode($parts[2]); 690 691 if ($this->use & SERVICES_JSON_LOOSE_TYPE) { 692 $obj[$key] = $val; 693 } else { 694 $obj->$key = $val; 695 } 696 } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { 697 // name:value pair, where name is unquoted 698 $key = $parts[1]; 699 $val = $this->decode($parts[2]); 700 701 if ($this->use & SERVICES_JSON_LOOSE_TYPE) { 702 $obj[$key] = $val; 703 } else { 704 $obj->$key = $val; 705 } 706 } 707 708 } 709 710 } elseif ((($chrs[$c] == '"') || ($chrs[$c] == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) { 711 // found a quote, and we are not inside a string 712 array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs[$c])); 713 //print("Found start of string at [$c]\n"); 714 715 } elseif (($chrs[$c] == $top['delim']) && 716 ($top['what'] == SERVICES_JSON_IN_STR) && 717 ((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) { 718 // found a quote, we're in a string, and it's not escaped 719 // we know that it's not escaped becase there is _not_ an 720 // odd number of backslashes at the end of the string so far 721 array_pop($stk); 722 //print("Found end of string at [$c]: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n"); 723 724 } elseif (($chrs[$c] == '[') && 725 in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { 726 // found a left-bracket, and we are in an array, object, or slice 727 array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false)); 728 //print("Found start of array at [$c]\n"); 729 730 } elseif (($chrs[$c] == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) { 731 // found a right-bracket, and we're in an array 732 array_pop($stk); 733 //print("Found end of array at [$c]: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); 734 735 } elseif (($chrs[$c] == '{') && 736 in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { 737 // found a left-brace, and we are in an array, object, or slice 738 array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false)); 739 //print("Found start of object at [$c]\n"); 740 741 } elseif (($chrs[$c] == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) { 742 // found a right-brace, and we're in an object 743 array_pop($stk); 744 //print("Found end of object at [$c]: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); 745 746 } elseif (($substr_chrs_c_2 == '/*') && 747 in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { 748 // found a comment start, and we are in an array, object, or slice 749 array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false)); 750 $c++; 751 //print("Found start of comment at [$c]\n"); 752 753 } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) { 754 // found a comment end, and we're in one now 755 array_pop($stk); 756 $c++; 757 758 for ($i = $top['where']; $i <= $c; ++$i) 759 $chrs = substr_replace($chrs, ' ', $i, 1); 760 761 //print("Found end of comment at [$c]: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); 762 763 } 764 765 } 766 767 if (reset($stk) == SERVICES_JSON_IN_ARR) { 768 return $arr; 769 770 } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { 771 return $obj; 772 773 } 774 775 } 776 } 777 } 778 779 /** 780 * @todo Ultimately, this should just call PEAR::isError() 781 */ 782 function isError($data, $code = null) 783 { 784 if (class_exists('pear')) { 785 return PEAR::isError($data, $code); 786 } elseif (is_object($data) && (get_class($data) == 'json_error' || 787 is_subclass_of($data, 'json_error'))) { 788 return true; 789 } 790 791 return false; 792 } 793 } 794 795 796 /** 797 * @todo Ultimately, this class shall be descended from PEAR_Error 798 */ 799 class JSON_Error 800 { 801 function __construct($message = 'unknown error', $code = null, 802 $mode = null, $options = null, $userinfo = null) 803 { 804 805 } 806 } 807 808 809 ?>
Download modules/util/JSON.class.php
History Fri, 26 Feb 2021 00:04:49 +0100 Jan Dankert New: Request may contain JSON,XML in POST data. This is good for API clients. Mon, 5 Oct 2020 23:32:15 +0200 Jan Dankert Fix: Now compatible with PHP 7.4. Thu, 23 Jan 2020 00:50:55 +0100 Jan Dankert Refactoring: Switching to PHPs newer SimpleXML-extension (pre-work for using XML namespaces) Sat, 16 Dec 2017 23:21:31 +0100 Jan Dankert Eigenes Modul für alle Util-Klassen.