PageRenderTime 50ms CodeModel.GetById 30ms app.highlight 14ms RepoModel.GetById 1ms app.codeStats 1ms

/html/AppCode/expressionengine/libraries/Services_json.php

https://github.com/w3bg/www.hsifin.com
PHP | 504 lines | 227 code | 79 blank | 198 comment | 74 complexity | 8294ed542330ba1833d615aa6027c007 MD5 | raw file
  1<?php
  2/**
  3 * PEAR JSON Services Library for PHP 4 json_decode compatibility.
  4 *
  5 * Removed json_encode and all related references, please use the EE
  6 * native generate_json method of the javascript library instead.
  7 */
  8
  9/**
 10 * Converts to and from JSON format.
 11 *
 12 * JSON (JavaScript Object Notation) is a lightweight data-interchange
 13 * format. It is easy for humans to read and write. It is easy for machines
 14 * to parse and generate. It is based on a subset of the JavaScript
 15 * Programming Language, Standard ECMA-262 3rd Edition - December 1999.
 16 * This feature can also be found in  Python. JSON is a text format that is
 17 * completely language independent but uses conventions that are familiar
 18 * to programmers of the C-family of languages, including C, C++, C#, Java,
 19 * JavaScript, Perl, TCL, and many others. These properties make JSON an
 20 * ideal data-interchange language.
 21 *
 22 * This package provides a simple encoder and decoder for JSON notation. It
 23 * is intended for use with client-side Javascript applications that make
 24 * use of HTTPRequest to perform server communication functions - data can
 25 * be encoded into JSON notation for use in a client-side javascript, or
 26 * decoded from incoming Javascript requests. JSON format is native to
 27 * Javascript, and can be directly eval()'ed with no further parsing
 28 * overhead
 29 *
 30 * All strings should be in ASCII or UTF-8 format!
 31 *
 32 * LICENSE: Redistribution and use in source and binary forms, with or
 33 * without modification, are permitted provided that the following
 34 * conditions are met: Redistributions of source code must retain the
 35 * above copyright notice, this list of conditions and the following
 36 * disclaimer. Redistributions in binary form must reproduce the above
 37 * copyright notice, this list of conditions and the following disclaimer
 38 * in the documentation and/or other materials provided with the
 39 * distribution.
 40 *
 41 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
 42 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 43 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
 44 * NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 45 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 46 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 47 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 48 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 49 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 50 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 51 * DAMAGE.
 52 *
 53 * @category
 54 * @package     Services_JSON
 55 * @author      Michal Migurski <mike-json@teczno.com>
 56 * @author      Matt Knapp <mdknapp[at]gmail[dot]com>
 57 * @author      Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
 58 * @copyright   2005 Michal Migurski
 59 * @version     CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $
 60 * @license     http://www.opensource.org/licenses/bsd-license.php
 61 * @link        http://pear.php.net/pepr/pepr-proposal-show.php?id=198
 62 */
 63
 64/**
 65 * Marker constant for Services_JSON::decode(), used to flag stack state
 66 */
 67define('SERVICES_JSON_SLICE',   1);
 68
 69/**
 70 * Marker constant for Services_JSON::decode(), used to flag stack state
 71 */
 72define('SERVICES_JSON_IN_STR',  2);
 73
 74/**
 75 * Marker constant for Services_JSON::decode(), used to flag stack state
 76 */
 77define('SERVICES_JSON_IN_ARR',  3);
 78
 79/**
 80 * Marker constant for Services_JSON::decode(), used to flag stack state
 81 */
 82define('SERVICES_JSON_IN_OBJ',  4);
 83
 84/**
 85 * Marker constant for Services_JSON::decode(), used to flag stack state
 86 */
 87define('SERVICES_JSON_IN_CMT', 5);
 88
 89/**
 90 * Behavior switch for Services_JSON::decode()
 91 */
 92define('SERVICES_JSON_LOOSE_TYPE', 16);
 93
 94/**
 95 * Converts to and from JSON format.
 96 *
 97 * Brief example of use:
 98 *
 99 * <code>
100 * // create a new instance of Services_JSON
101 * $json = new Services_JSON();
102 *
103 * // convert a complexe value to JSON notation, and send it to the browser
104 * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4)));
105 * $output = $json->encode($value);
106 *
107 * print($output);
108 * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]]
109 *
110 * // accept incoming POST data, assumed to be in JSON notation
111 * $input = file_get_contents('php://input', 1000000);
112 * $value = $json->decode($input);
113 * </code>
114 */
115class Services_JSON
116{
117   /**
118    * constructs a new JSON instance
119    *
120    * @param    int     $use    object behavior flags; combine with boolean-OR
121    *
122    *                           possible values:
123    *                           - SERVICES_JSON_LOOSE_TYPE:  loose typing.
124    *                                   "{...}" syntax creates associative arrays
125    *                                   instead of objects in decode().
126    */
127    function Services_JSON($use = 0)
128    {
129        $this->use = $use;
130    }
131
132   /**
133    * convert a string from one UTF-16 char to one UTF-8 char
134    *
135    * Normally should be handled by mb_convert_encoding, but
136    * provides a slower PHP-only method for installations
137    * that lack the multibye string extension.
138    *
139    * @param    string  $utf16  UTF-16 character
140    * @return   string  UTF-8 character
141    * @access   private
142    */
143    function utf162utf8($utf16)
144    {
145        // oh please oh please oh please oh please oh please
146        if(function_exists('mb_convert_encoding')) {
147            return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
148        }
149
150        $bytes = (ord($utf16{0}) << 8) | ord($utf16{1});
151
152        switch(true) {
153            case ((0x7F & $bytes) == $bytes):
154                // this case should never be reached, because we are in ASCII range
155                // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
156                return chr(0x7F & $bytes);
157
158            case (0x07FF & $bytes) == $bytes:
159                // return a 2-byte UTF-8 character
160                // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
161                return chr(0xC0 | (($bytes >> 6) & 0x1F))
162                     . chr(0x80 | ($bytes & 0x3F));
163
164            case (0xFFFF & $bytes) == $bytes:
165                // return a 3-byte UTF-8 character
166                // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
167                return chr(0xE0 | (($bytes >> 12) & 0x0F))
168                     . chr(0x80 | (($bytes >> 6) & 0x3F))
169                     . chr(0x80 | ($bytes & 0x3F));
170        }
171
172        // ignoring UTF-32 for now, sorry
173        return '';
174    }
175
176   /**
177    * reduce a string by removing leading and trailing comments and whitespace
178    *
179    * @param    $str    string      string value to strip of comments and whitespace
180    *
181    * @return   string  string value stripped of comments and whitespace
182    * @access   private
183    */
184    function reduce_string($str)
185    {
186        $str = preg_replace(array(
187
188                // eliminate single line comments in '// ...' form
189                '#^\s*//(.+)$#m',
190
191                // eliminate multi-line comments in '/* ... */' form, at start of string
192                '#^\s*/\*(.+)\*/#Us',
193
194                // eliminate multi-line comments in '/* ... */' form, at end of string
195                '#/\*(.+)\*/\s*$#Us'
196
197            ), '', $str);
198
199        // eliminate extraneous space
200        return trim($str);
201    }
202
203   /**
204    * decodes a JSON string into appropriate variable
205    *
206    * @param    string  $str    JSON-formatted string
207    *
208    * @return   mixed   number, boolean, string, array, or object
209    *                   corresponding to given JSON input string.
210    *                   See argument 1 to Services_JSON() above for object-output behavior.
211    *                   Note that decode() always returns strings
212    *                   in ASCII or UTF-8 format!
213    * @access   public
214    */
215    function decode($str)
216    {
217        $str = $this->reduce_string($str);
218
219        switch (strtolower($str)) {
220            case 'true':
221                return true;
222
223            case 'false':
224                return false;
225
226            case 'null':
227                return null;
228
229            default:
230                $m = array();
231
232                if (is_numeric($str)) {
233                    // Lookie-loo, it's a number
234
235                    // This would work on its own, but I'm trying to be
236                    // good about returning integers where appropriate:
237                    // return (float)$str;
238
239                    // Return float or int, as appropriate
240                    return ((float)$str == (integer)$str)
241                        ? (integer)$str
242                        : (float)$str;
243
244                } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) {
245                    // STRINGS RETURNED IN UTF-8 FORMAT
246                    $delim = substr($str, 0, 1);
247                    $chrs = substr($str, 1, -1);
248                    $utf8 = '';
249                    $strlen_chrs = strlen($chrs);
250
251                    for ($c = 0; $c < $strlen_chrs; ++$c) {
252
253                        $substr_chrs_c_2 = substr($chrs, $c, 2);
254                        $ord_chrs_c = ord($chrs{$c});
255
256                        switch (true) {
257                            case $substr_chrs_c_2 == '\b':
258                                $utf8 .= chr(0x08);
259                                ++$c;
260                                break;
261                            case $substr_chrs_c_2 == '\t':
262                                $utf8 .= chr(0x09);
263                                ++$c;
264                                break;
265                            case $substr_chrs_c_2 == '\n':
266                                $utf8 .= chr(0x0A);
267                                ++$c;
268                                break;
269                            case $substr_chrs_c_2 == '\f':
270                                $utf8 .= chr(0x0C);
271                                ++$c;
272                                break;
273                            case $substr_chrs_c_2 == '\r':
274                                $utf8 .= chr(0x0D);
275                                ++$c;
276                                break;
277
278                            case $substr_chrs_c_2 == '\\"':
279                            case $substr_chrs_c_2 == '\\\'':
280                            case $substr_chrs_c_2 == '\\\\':
281                            case $substr_chrs_c_2 == '\\/':
282                                if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
283                                   ($delim == "'" && $substr_chrs_c_2 != '\\"')) {
284                                    $utf8 .= $chrs{++$c};
285                                }
286                                break;
287
288                            case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)):
289                                // single, escaped unicode character
290                                $utf16 = chr(hexdec(substr($chrs, ($c + 2), 2)))
291                                       . chr(hexdec(substr($chrs, ($c + 4), 2)));
292                                $utf8 .= $this->utf162utf8($utf16);
293                                $c += 5;
294                                break;
295
296                            case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
297                                $utf8 .= $chrs{$c};
298                                break;
299
300                            case ($ord_chrs_c & 0xE0) == 0xC0:
301                                // characters U-00000080 - U-000007FF, mask 110XXXXX
302                                //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
303                                $utf8 .= substr($chrs, $c, 2);
304                                ++$c;
305                                break;
306
307                            case ($ord_chrs_c & 0xF0) == 0xE0:
308                                // characters U-00000800 - U-0000FFFF, mask 1110XXXX
309                                // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
310                                $utf8 .= substr($chrs, $c, 3);
311                                $c += 2;
312                                break;
313
314                            case ($ord_chrs_c & 0xF8) == 0xF0:
315                                // characters U-00010000 - U-001FFFFF, mask 11110XXX
316                                // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
317                                $utf8 .= substr($chrs, $c, 4);
318                                $c += 3;
319                                break;
320
321                            case ($ord_chrs_c & 0xFC) == 0xF8:
322                                // characters U-00200000 - U-03FFFFFF, mask 111110XX
323                                // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
324                                $utf8 .= substr($chrs, $c, 5);
325                                $c += 4;
326                                break;
327
328                            case ($ord_chrs_c & 0xFE) == 0xFC:
329                                // characters U-04000000 - U-7FFFFFFF, mask 1111110X
330                                // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
331                                $utf8 .= substr($chrs, $c, 6);
332                                $c += 5;
333                                break;
334
335                        }
336
337                    }
338
339                    return $utf8;
340
341                } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) {
342                    // array, or object notation
343
344                    if ($str{0} == '[') {
345                        $stk = array(SERVICES_JSON_IN_ARR);
346                        $arr = array();
347                    } else {
348                        if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
349                            $stk = array(SERVICES_JSON_IN_OBJ);
350                            $obj = array();
351                        } else {
352                            $stk = array(SERVICES_JSON_IN_OBJ);
353                            $obj = new stdClass();
354                        }
355                    }
356
357                    array_push($stk, array('what'  => SERVICES_JSON_SLICE,
358                                           'where' => 0,
359                                           'delim' => false));
360
361                    $chrs = substr($str, 1, -1);
362                    $chrs = $this->reduce_string($chrs);
363
364                    if ($chrs == '') {
365                        if (reset($stk) == SERVICES_JSON_IN_ARR) {
366                            return $arr;
367
368                        } else {
369                            return $obj;
370
371                        }
372                    }
373
374                    //print("\nparsing {$chrs}\n");
375
376                    $strlen_chrs = strlen($chrs);
377
378                    for ($c = 0; $c <= $strlen_chrs; ++$c) {
379
380                        $top = end($stk);
381                        $substr_chrs_c_2 = substr($chrs, $c, 2);
382
383                        if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) {
384                            // found a comma that is not inside a string, array, etc.,
385                            // OR we've reached the end of the character list
386                            $slice = substr($chrs, $top['where'], ($c - $top['where']));
387                            array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false));
388                            //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
389
390                            if (reset($stk) == SERVICES_JSON_IN_ARR) {
391                                // we are in an array, so just push an element onto the stack
392                                array_push($arr, $this->decode($slice));
393
394                            } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
395                                // we are in an object, so figure
396                                // out the property name and set an
397                                // element in an associative array,
398                                // for now
399                                $parts = array();
400                                
401                                if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
402                                    // "name":value pair
403                                    $key = $this->decode($parts[1]);
404                                    $val = $this->decode($parts[2]);
405
406                                    if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
407                                        $obj[$key] = $val;
408                                    } else {
409                                        $obj->$key = $val;
410                                    }
411                                } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
412                                    // name:value pair, where name is unquoted
413                                    $key = $parts[1];
414                                    $val = $this->decode($parts[2]);
415
416                                    if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
417                                        $obj[$key] = $val;
418                                    } else {
419                                        $obj->$key = $val;
420                                    }
421                                }
422
423                            }
424
425                        } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) {
426                            // found a quote, and we are not inside a string
427                            array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c}));
428                            //print("Found start of string at {$c}\n");
429
430                        } elseif (($chrs{$c} == $top['delim']) &&
431                                 ($top['what'] == SERVICES_JSON_IN_STR) &&
432                                 ((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) {
433                            // found a quote, we're in a string, and it's not escaped
434                            // we know that it's not escaped becase there is _not_ an
435                            // odd number of backslashes at the end of the string so far
436                            array_pop($stk);
437                            //print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");
438
439                        } elseif (($chrs{$c} == '[') &&
440                                 in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
441                            // found a left-bracket, and we are in an array, object, or slice
442                            array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false));
443                            //print("Found start of array at {$c}\n");
444
445                        } elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) {
446                            // found a right-bracket, and we're in an array
447                            array_pop($stk);
448                            //print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
449
450                        } elseif (($chrs{$c} == '{') &&
451                                 in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
452                            // found a left-brace, and we are in an array, object, or slice
453                            array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false));
454                            //print("Found start of object at {$c}\n");
455
456                        } elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) {
457                            // found a right-brace, and we're in an object
458                            array_pop($stk);
459                            //print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
460
461                        } elseif (($substr_chrs_c_2 == '/*') &&
462                                 in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
463                            // found a comment start, and we are in an array, object, or slice
464                            array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false));
465                            $c++;
466                            //print("Found start of comment at {$c}\n");
467
468                        } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) {
469                            // found a comment end, and we're in one now
470                            array_pop($stk);
471                            $c++;
472
473                            for ($i = $top['where']; $i <= $c; ++$i)
474                                $chrs = substr_replace($chrs, ' ', $i, 1);
475
476                            //print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
477
478                        }
479
480                    }
481
482                    if (reset($stk) == SERVICES_JSON_IN_ARR) {
483                        return $arr;
484
485                    } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
486                        return $obj;
487
488                    }
489
490                }
491        }
492    }
493}
494
495
496// Future-friendly json_decode
497if( !function_exists('json_decode') ) {
498	function json_decode($data) {
499		$json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
500        return( $json->decode($data) );
501    }
502}
503
504?>