Services_JSON
[ class tree: Services_JSON ] [ index: Services_JSON ] [ all elements ]

Source for file JSON.php

Documentation is available at JSON.php

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

Documentation generated on Fri, 18 Jul 2008 21:47:05 +0200 by phpDocumentor 1.4.1