home *** CD-ROM | disk | FTP | other *** search
/ Cricao de Sites - 650 Layouts Prontos / WebMasters.iso / Servidores / xampp-win32-1.6.7-installer.exe / php / PEAR / HTML / AJAX / JSON.php < prev    next >
Encoding:
PHP Script  |  2008-07-02  |  34.0 KB  |  805 lines

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