Source for file JSON.php

Documentation is available at JSON.php

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

Documentation generated on Thu, 22 Oct 2009 12:54:41 -0700 by phpDocumentor 1.4.3