Advertisement
konyakov

JSON.php | AJAX+PHP+MySQL Autosuggest (Cyr & Utf-8)

Dec 26th, 2011
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 23.47 KB | None | 0 0
  1. <?php
  2.     // +----------------------------------------------------------------------+
  3.     // | PHP version 4                                                        |
  4.     // +----------------------------------------------------------------------+
  5.     // | Copyright (c) 2005 Michal Migurski                                   |
  6.     // +----------------------------------------------------------------------+
  7.     // | This source file is subject to version 3.0 of the PHP license,       |
  8.     // | that is bundled with this package in the file LICENSE, and is        |
  9.     // | available through the world-wide-web at the following url:           |
  10.     // | http://www.php.net/license/3_0.txt.                                  |
  11.     // | If you did not receive a copy of the PHP license and are unable to   |
  12.     // | obtain it through the world-wide-web, please send a note to          |
  13.     // | license@php.net so we can mail you a copy immediately.               |
  14.     // +----------------------------------------------------------------------+
  15.     // | Author: Michal Migurski, mike-json[at]teczno[dot]com                 |
  16.     // | with contributions from:                                             |
  17.     // |   Matt Knapp, mdknapp[at]gmail[dot]com                               |
  18.     // |   Brett Stimmerman, brettstimmerman[at]gmail[dot]com                 |
  19.     // +----------------------------------------------------------------------+
  20.     //
  21.     // $Id: JSON.php,v 1.16 2005/06/19 00:46:05 migurski Exp $
  22.     /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  23.  
  24.     define('JSON_SLICE',   1);
  25.     define('JSON_IN_STR',  2);
  26.     define('JSON_IN_ARR',  4);
  27.     define('JSON_IN_OBJ',  8);
  28.     define('JSON_IN_CMT', 16);
  29.     define('JSON_LOOSE_TYPE', 10);
  30.     define('JSON_STRICT_TYPE', 11);
  31.    
  32.    /** JSON
  33.     * Conversion to and from JSON format.
  34.     * See http://json.org for details.
  35.     *
  36.     * note all strings should be in ASCII or UTF-8 format!
  37.     */
  38.     class JSON
  39.     {
  40.        /** function JSON
  41.         * constructor
  42.         *
  43.         * @param    use     int     object behavior: when encoding or decoding,
  44.         *                           be loose or strict about object/array usage
  45.         *
  46.         *                           possible values:
  47.         *                              JSON_STRICT_TYPE - strict typing, default
  48.         *                                                 "{...}" syntax creates objects in decode
  49.         *                               JSON_LOOSE_TYPE - loose typing
  50.         *                                                 "{...}" syntax creates associative arrays in decode
  51.         */
  52.         function JSON($use=JSON_STRICT_TYPE)
  53.         {
  54.             $this->use = $use;
  55.         }
  56.  
  57.        /** function encode
  58.         * encode an arbitrary variable into JSON format
  59.         *
  60.         * @param    var     mixed   any number, boolean, string, array, or object to be encoded.
  61.         *                           see argument 1 to JSON() above for array-parsing behavior.
  62.         *                           if var is a strng, note that encode() always expects it
  63.         *                           to be in ASCII or UTF-8 format!
  64.         *
  65.         * @return   string  JSON string representation of input var
  66.         */
  67.         function encode($var)
  68.         {
  69.             switch(gettype($var)) {
  70.                 case 'boolean':
  71.                     return $var ? 'true' : 'false';
  72.                
  73.                 case 'NULL':
  74.                     return 'null';
  75.                
  76.                 case 'integer':
  77.                     return sprintf('%d', $var);
  78.                    
  79.                 case 'double':
  80.                 case 'float':
  81.                     return sprintf('%f', $var);
  82.                    
  83.                 case 'string': // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
  84.                     $ascii = '';
  85.                     $strlen_var = strlen($var);
  86.    
  87.                     for($c = 0; $c < $strlen_var; $c++) {
  88.                        
  89.                         $ord_var_c = ord($var{$c});
  90.                
  91.                         if($ord_var_c == 0x08) {
  92.                             $ascii .= '\b';
  93.                        
  94.                         } elseif($ord_var_c == 0x09) {
  95.                             $ascii .= '\t';
  96.                        
  97.                         } elseif($ord_var_c == 0x0A) {
  98.                             $ascii .= '\n';
  99.                        
  100.                         } elseif($ord_var_c == 0x0C) {
  101.                             $ascii .= '\f';
  102.                        
  103.                         } elseif($ord_var_c == 0x0D) {
  104.                             $ascii .= '\r';
  105.                        
  106.                         } elseif(($ord_var_c == 0x22) || ($ord_var_c == 0x2F) || ($ord_var_c == 0x5C)) {
  107.                             $ascii .= '\\'.$var{$c}; // double quote, slash, slosh
  108.                        
  109.                         } elseif(($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)) {
  110.                             // characters U-00000000 - U-0000007F (same as ASCII)
  111.                             $ascii .= $var{$c}; // most normal ASCII chars
  112.                
  113.                         } elseif(($ord_var_c & 0xE0) == 0xC0) {
  114.                             // characters U-00000080 - U-000007FF, mask 110XXXXX, see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  115.                             $char = pack('C*', $ord_var_c, ord($var{$c+1})); $c+=1;
  116.                             $ascii .= sprintf('\u%04s', bin2hex(mb_convert_encoding($char, 'UTF-16', 'UTF-8')));
  117.    
  118.                         } elseif(($ord_var_c & 0xF0) == 0xE0) {
  119.                             // characters U-00000800 - U-0000FFFF, mask 1110XXXX, see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  120.                             $char = pack('C*', $ord_var_c, ord($var{$c+1}), ord($var{$c+2})); $c+=2;
  121.                             $ascii .= sprintf('\u%04s', bin2hex(mb_convert_encoding($char, 'UTF-16', 'UTF-8')));
  122.    
  123.                         } elseif(($ord_var_c & 0xF8) == 0xF0) {
  124.                             // characters U-00010000 - U-001FFFFF, mask 11110XXX, see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  125.                             $char = pack('C*', $ord_var_c, ord($var{$c+1}), ord($var{$c+2}), ord($var{$c+3})); $c+=3;
  126.                             $ascii .= sprintf('\u%04s', bin2hex(mb_convert_encoding($char, 'UTF-16', 'UTF-8')));
  127.    
  128.                         } elseif(($ord_var_c & 0xFC) == 0xF8) {
  129.                             // characters U-00200000 - U-03FFFFFF, mask 111110XX, see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  130.                             $char = pack('C*', $ord_var_c, ord($var{$c+1}), ord($var{$c+2}), ord($var{$c+3}), ord($var{$c+4})); $c+=4;
  131.                             $ascii .= sprintf('\u%04s', bin2hex(mb_convert_encoding($char, 'UTF-16', 'UTF-8')));
  132.    
  133.                         } elseif(($ord_var_c & 0xFE) == 0xFC) {
  134.                             // characters U-04000000 - U-7FFFFFFF, mask 1111110X, see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  135.                             $char = pack('C*', $ord_var_c, ord($var{$c+1}), ord($var{$c+2}), ord($var{$c+3}), ord($var{$c+4}), ord($var{$c+5})); $c+=5;
  136.                             $ascii .= sprintf('\u%04s', bin2hex(mb_convert_encoding($char, 'UTF-16', 'UTF-8')));
  137.    
  138.                         }
  139.                     }
  140.                    
  141.                     return sprintf('"%s"', $ascii);
  142.                    
  143.                 case 'array':
  144.                     // As per JSON spec if any array key is not an integer we must treat the the whole array as an object.
  145.                     // We also try to catch a sparsely populated associative array with numeric keys here because some JS
  146.                     // engines will create an array with empty indexes up to max_index which can cause memory issues
  147.                     // and because the keys, which may be relevant, will be remapped otherwise.
  148.                     //
  149.                     // As per the ECMA and JSON specification an object may have any string as a property. Unfortunately due to a
  150.                     // hole in the ECMA specification if the key is a ECMA reserved word or starts with a digit the parameter is only
  151.                     // accessible using ECMAScript's bracket notation.  
  152.          
  153.                     // treat as a JSON object  
  154.                     if(is_array($var) && count($var) > 0 &&  (array_keys($var) !== range(0, sizeof($var) - 1))) {
  155.                         return sprintf('{%s}', join(',', array_map(array($this, 'name_value'), array_keys($var), array_values($var))));
  156.                      }
  157.                     // treat it like a regular array
  158.                     return sprintf('[%s]', join(',', array_map(array($this, 'encode'), $var)));
  159.                    
  160.                 case 'object':
  161.                     $vars = get_object_vars($var);
  162.                     return sprintf('{%s}', join(',', array_map(array($this, 'name_value'), array_keys($vars), array_values($vars))));                    
  163.  
  164.                 default:
  165.                     return '';
  166.             }
  167.         }
  168.        
  169.        /** function enc
  170.         * alias for encode()
  171.         */
  172.         function enc($var)
  173.         {
  174.             return $this->encode($var);
  175.         }
  176.        
  177.        /** function name_value
  178.         * array-walking function for use in generating JSON-formatted name-value pairs
  179.         *
  180.         * @param    name    string  name of key to use
  181.         * @param    value   mixed   reference to an array element to be encoded
  182.         *
  183.         * @return   string  JSON-formatted name-value pair, like '"name":value'
  184.         */
  185.         function name_value($name, $value)
  186.         {
  187.             return (sprintf("%s:%s", $this->encode(strval($name)), $this->encode($value)));
  188.         }        
  189.  
  190.        /** function reduce_string
  191.         * reduce a string by removing leading and trailing comments and whitespace
  192.         *
  193.         * @param    str     string      string value to strip of comments and whitespace
  194.         *
  195.         * @return   string  string value stripped of comments and whitespace
  196.         */
  197.         function reduce_string($str)
  198.         {
  199.             $str = preg_replace('#^\s*//(.+)$#m', '', $str); // eliminate single line comments in '// ...' form
  200.             $str = preg_replace('#^\s*/\*(.+)\*/#Us', '', $str); // eliminate multi-line comments in '/* ... */' form, at start of string
  201.             $str = preg_replace('#/\*(.+)\*/\s*$#Us', '', $str); // eliminate multi-line comments in '/* ... */' form, at end of string
  202.             $str = trim($str); // eliminate extraneous space
  203.            
  204.             return $str;
  205.         }
  206.  
  207.        /** function decode
  208.         * decode a JSON string into appropriate variable
  209.         *
  210.         * @param    str     string  JSON-formatted string
  211.         *
  212.         * @return   mixed   number, boolean, string, array, or object
  213.         *                   corresponding to given JSON input string.
  214.         *                   see argument 1 to JSON() above for object-output behavior.
  215.         *                   note that decode() always returns strings
  216.         *                   in ASCII or UTF-8 format!
  217.         */
  218.         function decode($str)
  219.         {
  220.             $str = $this->reduce_string($str);
  221.        
  222.             switch(strtolower($str)) {
  223.                 case 'true':
  224.                     return true;
  225.    
  226.                 case 'false':
  227.                     return false;
  228.                
  229.                 case 'null':
  230.                     return null;
  231.                
  232.                 default:
  233.                     if(is_numeric($str)) { // Lookie-loo, it's a number
  234.                         // return (float)$str; // This would work on its own, but I'm trying to be good about returning integers where appropriate
  235.                         return ((float)$str == (integer)$str)
  236.                             ? (integer)$str
  237.                             : (float)$str;
  238.                        
  239.                     } elseif(preg_match('/^".+"$/s', $str) || preg_match('/^\'.+\'$/s', $str)) { // STRINGS RETURNED IN UTF-8 FORMAT
  240.                         $delim = substr($str, 0, 1);
  241.                         $chrs = substr($str, 1, -1);
  242.                         $utf8 = '';
  243.                         $strlen_chrs = strlen($chrs);
  244.                        
  245.                         for($c = 0; $c < $strlen_chrs; $c++) {
  246.                        
  247.                             $substr_chrs_c_2 = substr($chrs, $c, 2);
  248.                             $ord_chrs_c = ord($chrs{$c});
  249.  
  250.                             if($substr_chrs_c_2 == '\b') {
  251.                                 $utf8 .= chr(0x08); $c+=1;
  252.    
  253.                             } elseif($substr_chrs_c_2 == '\t') {
  254.                                 $utf8 .= chr(0x09); $c+=1;
  255.    
  256.                             } elseif($substr_chrs_c_2 == '\n') {
  257.                                 $utf8 .= chr(0x0A); $c+=1;
  258.    
  259.                             } elseif($substr_chrs_c_2 == '\f') {
  260.                                 $utf8 .= chr(0x0C); $c+=1;
  261.    
  262.                             } elseif($substr_chrs_c_2 == '\r') {
  263.                                 $utf8 .= chr(0x0D); $c+=1;
  264.    
  265.                             } elseif(($delim == '"') && (($substr_chrs_c_2 == '\\"') || ($substr_chrs_c_2 == '\\\\') || ($substr_chrs_c_2 == '\\/'))) {
  266.                                 $utf8 .= $chrs{++$c};
  267.    
  268.                             } elseif(($delim == "'") && (($substr_chrs_c_2 == '\\\'') || ($substr_chrs_c_2 == '\\\\') || ($substr_chrs_c_2 == '\\/'))) {
  269.                                 $utf8 .= $chrs{++$c};
  270.    
  271.                             } elseif(preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6))) { // single, escaped unicode character
  272.                                 $utf16 = chr(hexdec(substr($chrs, ($c+2), 2))) . chr(hexdec(substr($chrs, ($c+4), 2)));
  273.                                 $utf8 .= mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
  274.                                 $c+=5;
  275.    
  276.                             } elseif(($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F)) {
  277.                                 $utf8 .= $chrs{$c};
  278.    
  279.                             } elseif(($ord_chrs_c & 0xE0) == 0xC0) {
  280.                                 // characters U-00000080 - U-000007FF, mask 110XXXXX, see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  281.                                 $utf8 .= substr($chrs, $c, 2); $c += 1;
  282.  
  283.                             } elseif(($ord_chrs_c & 0xF0) == 0xE0) {
  284.                                 // characters U-00000800 - U-0000FFFF, mask 1110XXXX, see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  285.                                 $utf8 .= substr($chrs, $c, 3); $c += 2;
  286.  
  287.                             } elseif(($ord_chrs_c & 0xF8) == 0xF0) {
  288.                                 // characters U-00010000 - U-001FFFFF, mask 11110XXX, see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  289.                                 $utf8 .= substr($chrs, $c, 4); $c += 3;
  290.  
  291.                             } elseif(($ord_chrs_c & 0xFC) == 0xF8) {
  292.                                 // characters U-00200000 - U-03FFFFFF, mask 111110XX, see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  293.                                 $utf8 .= substr($chrs, $c, 5); $c += 4;
  294.  
  295.                             } elseif(($ord_chrs_c & 0xFE) == 0xFC) {
  296.                                 // characters U-04000000 - U-7FFFFFFF, mask 1111110X, see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  297.                                 $utf8 .= substr($chrs, $c, 6); $c += 5;
  298.  
  299.                             }
  300.                        
  301.                         }
  302.                        
  303.                         return $utf8;
  304.                    
  305.                     } elseif(preg_match('/^\[.*\]$/s', $str) || preg_match('/^{.*}$/s', $str)) { // array, or object notation
  306.    
  307.                         if($str{0} == '[') {
  308.                             $stk = array(JSON_IN_ARR);
  309.                             $arr = array();
  310.                         } else {
  311.                             if($this->use == JSON_LOOSE_TYPE) {
  312.                                 $stk = array(JSON_IN_OBJ);
  313.                                 $obj = array();
  314.                             } else {
  315.                                 $stk = array(JSON_IN_OBJ);
  316.                                 $obj = new ObjectFromJSON();
  317.                             }
  318.                         }
  319.                        
  320.                         array_push($stk, array('what' => JSON_SLICE, 'where' => 0, 'delim' => false));
  321.                         $chrs = substr($str, 1, -1);
  322.                         $chrs = $this->reduce_string($chrs);
  323.                        
  324.                         if($chrs == '') {
  325.                             if(reset($stk) == JSON_IN_ARR) {
  326.                                 return $arr;
  327.  
  328.                             } else {
  329.                                 return $obj;
  330.  
  331.                             }
  332.                         }
  333.  
  334.                         //print("\nparsing {$chrs}\n");
  335.                        
  336.                         $strlen_chrs = strlen($chrs);
  337.                        
  338.                         for($c = 0; $c <= $strlen_chrs; $c++) {
  339.                        
  340.                             $top = end($stk);
  341.                             $substr_chrs_c_2 = substr($chrs, $c, 2);
  342.                        
  343.                             if(($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == JSON_SLICE))) { // found a comma that is not inside a string, array, etc., OR we've reached the end of the character list
  344.                                 $slice = substr($chrs, $top['where'], ($c - $top['where']));
  345.                                 array_push($stk, array('what' => JSON_SLICE, 'where' => ($c + 1), 'delim' => false));
  346.                                 //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  347.    
  348.                                 if(reset($stk) == JSON_IN_ARR) { // we are in an array, so just push an element onto the stack
  349.                                     array_push($arr, $this->decode($slice));
  350.    
  351.                                 } elseif(reset($stk) == JSON_IN_OBJ) { // we are in an object, so figure out the property name and set an element in an associative array, for now
  352.                                     if(preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { // "name":value pair
  353.                                         $key = $this->decode($parts[1]);
  354.                                         $val = $this->decode($parts[2]);
  355.  
  356.                                         if($this->use == JSON_LOOSE_TYPE) {
  357.                                             $obj[$key] = $val;
  358.                                         } else {
  359.                                             $obj->$key = $val;
  360.                                         }
  361.                                     } elseif(preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { // name:value pair, where name is unquoted
  362.                                         $key = $parts[1];
  363.                                         $val = $this->decode($parts[2]);
  364.  
  365.                                         if($this->use == JSON_LOOSE_TYPE) {
  366.                                             $obj[$key] = $val;
  367.                                         } else {
  368.                                             $obj->$key = $val;
  369.                                         }
  370.                                     }
  371.    
  372.                                 }
  373.    
  374.                             } elseif((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != JSON_IN_STR)) { // found a quote, and we are not inside a string
  375.                                 array_push($stk, array('what' => JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c}));
  376.                                 //print("Found start of string at {$c}\n");
  377.    
  378.                             } elseif(($chrs{$c} == $top['delim']) && ($top['what'] == JSON_IN_STR) && (($chrs{$c - 1} != "\\") || ($chrs{$c - 1} == "\\" && $chrs{$c - 2} == "\\"))) { // found a quote, we're in a string, and it's not escaped
  379.                                 array_pop($stk);
  380.                                 //print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");
  381.    
  382.                             } elseif(($chrs{$c} == '[') && in_array($top['what'], array(JSON_SLICE, JSON_IN_ARR, JSON_IN_OBJ))) { // found a left-bracket, and we are in an array, object, or slice
  383.                                 array_push($stk, array('what' => JSON_IN_ARR, 'where' => $c, 'delim' => false));
  384.                                 //print("Found start of array at {$c}\n");
  385.    
  386.                             } elseif(($chrs{$c} == ']') && ($top['what'] == JSON_IN_ARR)) { // found a right-bracket, and we're in an array
  387.                                 array_pop($stk);
  388.                                 //print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  389.    
  390.                             } elseif(($chrs{$c} == '{') && in_array($top['what'], array(JSON_SLICE, JSON_IN_ARR, JSON_IN_OBJ))) { // found a left-brace, and we are in an array, object, or slice
  391.                                 array_push($stk, array('what' => JSON_IN_OBJ, 'where' => $c, 'delim' => false));
  392.                                 //print("Found start of object at {$c}\n");
  393.    
  394.                             } elseif(($chrs{$c} == '}') && ($top['what'] == JSON_IN_OBJ)) { // found a right-brace, and we're in an object
  395.                                 array_pop($stk);
  396.                                 //print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  397.    
  398.                             } elseif(($substr_chrs_c_2 == '/*') && in_array($top['what'], array(JSON_SLICE, JSON_IN_ARR, JSON_IN_OBJ))) { // found a comment start, and we are in an array, object, or slice
  399.                                 array_push($stk, array('what' => JSON_IN_CMT, 'where' => $c, 'delim' => false));
  400.                                 $c++;
  401.                                 //print("Found start of comment at {$c}\n");
  402.    
  403.                             } elseif(($substr_chrs_c_2 == '*/') && ($top['what'] == JSON_IN_CMT)) { // found a comment end, and we're in one now
  404.                                 array_pop($stk);
  405.                                 $c++;
  406.                                
  407.                                 for($i = $top['where']; $i <= $c; $i++)
  408.                                     $chrs = substr_replace($chrs, ' ', $i, 1);
  409.                                
  410.                                 //print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  411.    
  412.                             }
  413.                        
  414.                         }
  415.                        
  416.                         if(reset($stk) == JSON_IN_ARR) {
  417.                             return $arr;
  418.    
  419.                         } elseif(reset($stk) == JSON_IN_OBJ) {
  420.                             return $obj;
  421.    
  422.                         }
  423.                    
  424.                     }
  425.             }
  426.         }
  427.        
  428.        /** function dec
  429.         * alias for decode()
  430.         */
  431.         function dec($var)
  432.         {
  433.             return $this->decode($var);
  434.         }
  435.        
  436.     }
  437.  
  438.    /** ObjectFromJSON
  439.     * Generic object wrapper, used in object returns from decode()
  440.     */
  441.     class ObjectFromJSON { function ObjectFromJSON() {} }
  442.    
  443. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement