PageRenderTime 42ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/class-json.php

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