PageRenderTime 58ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

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