class-json.php 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  1. <?php
  2. _deprecated_file( basename( __FILE__ ), '5.3.0', '', '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. * Object behavior flags.
  116. *
  117. * @var int
  118. */
  119. public $use;
  120. // private - cache the mbstring lookup results..
  121. var $_mb_strlen = false;
  122. var $_mb_substr = false;
  123. var $_mb_convert_encoding = false;
  124. /**
  125. * constructs a new JSON instance
  126. *
  127. * @deprecated 5.3.0 Use the PHP native JSON extension instead.
  128. *
  129. * @param int $use object behavior flags; combine with boolean-OR
  130. *
  131. * possible values:
  132. * - SERVICES_JSON_LOOSE_TYPE: loose typing.
  133. * "{...}" syntax creates associative arrays
  134. * instead of objects in decode().
  135. * - SERVICES_JSON_SUPPRESS_ERRORS: error suppression.
  136. * Values which can't be encoded (e.g. resources)
  137. * appear as NULL instead of throwing errors.
  138. * By default, a deeply-nested resource will
  139. * bubble up with an error, so all return values
  140. * from encode() should be checked with isError()
  141. * - SERVICES_JSON_USE_TO_JSON: call toJSON when serializing objects
  142. * It serializes the return value from the toJSON call rather
  143. * than the object itself, toJSON can return associative arrays,
  144. * strings or numbers, if you return an object, make sure it does
  145. * not have a toJSON method, otherwise an error will occur.
  146. */
  147. function __construct( $use = 0 )
  148. {
  149. _deprecated_function( __METHOD__, '5.3.0', 'The PHP native JSON extension' );
  150. $this->use = $use;
  151. $this->_mb_strlen = function_exists('mb_strlen');
  152. $this->_mb_convert_encoding = function_exists('mb_convert_encoding');
  153. $this->_mb_substr = function_exists('mb_substr');
  154. }
  155. /**
  156. * PHP4 constructor.
  157. *
  158. * @deprecated 5.3.0 Use __construct() instead.
  159. *
  160. * @see Services_JSON::__construct()
  161. */
  162. public function Services_JSON( $use = 0 ) {
  163. _deprecated_constructor( 'Services_JSON', '5.3.0', get_class( $this ) );
  164. self::__construct( $use );
  165. }
  166. /**
  167. * convert a string from one UTF-16 char to one UTF-8 char
  168. *
  169. * Normally should be handled by mb_convert_encoding, but
  170. * provides a slower PHP-only method for installations
  171. * that lack the multibye string extension.
  172. *
  173. * @deprecated 5.3.0 Use the PHP native JSON extension instead.
  174. *
  175. * @param string $utf16 UTF-16 character
  176. * @return string UTF-8 character
  177. * @access private
  178. */
  179. function utf162utf8($utf16)
  180. {
  181. _deprecated_function( __METHOD__, '5.3.0', 'The PHP native JSON extension' );
  182. // oh please oh please oh please oh please oh please
  183. if($this->_mb_convert_encoding) {
  184. return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
  185. }
  186. $bytes = (ord($utf16[0]) << 8) | ord($utf16[1]);
  187. switch(true) {
  188. case ((0x7F & $bytes) == $bytes):
  189. // this case should never be reached, because we are in ASCII range
  190. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  191. return chr(0x7F & $bytes);
  192. case (0x07FF & $bytes) == $bytes:
  193. // return a 2-byte UTF-8 character
  194. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  195. return chr(0xC0 | (($bytes >> 6) & 0x1F))
  196. . chr(0x80 | ($bytes & 0x3F));
  197. case (0xFFFF & $bytes) == $bytes:
  198. // return a 3-byte UTF-8 character
  199. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  200. return chr(0xE0 | (($bytes >> 12) & 0x0F))
  201. . chr(0x80 | (($bytes >> 6) & 0x3F))
  202. . chr(0x80 | ($bytes & 0x3F));
  203. }
  204. // ignoring UTF-32 for now, sorry
  205. return '';
  206. }
  207. /**
  208. * convert a string from one UTF-8 char to one UTF-16 char
  209. *
  210. * Normally should be handled by mb_convert_encoding, but
  211. * provides a slower PHP-only method for installations
  212. * that lack the multibyte string extension.
  213. *
  214. * @deprecated 5.3.0 Use the PHP native JSON extension instead.
  215. *
  216. * @param string $utf8 UTF-8 character
  217. * @return string UTF-16 character
  218. * @access private
  219. */
  220. function utf82utf16($utf8)
  221. {
  222. _deprecated_function( __METHOD__, '5.3.0', 'The PHP native JSON extension' );
  223. // oh please oh please oh please oh please oh please
  224. if($this->_mb_convert_encoding) {
  225. return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
  226. }
  227. switch($this->strlen8($utf8)) {
  228. case 1:
  229. // this case should never be reached, because we are in ASCII range
  230. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  231. return $utf8;
  232. case 2:
  233. // return a UTF-16 character from a 2-byte UTF-8 char
  234. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  235. return chr(0x07 & (ord($utf8[0]) >> 2))
  236. . chr((0xC0 & (ord($utf8[0]) << 6))
  237. | (0x3F & ord($utf8[1])));
  238. case 3:
  239. // return a UTF-16 character from a 3-byte UTF-8 char
  240. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  241. return chr((0xF0 & (ord($utf8[0]) << 4))
  242. | (0x0F & (ord($utf8[1]) >> 2)))
  243. . chr((0xC0 & (ord($utf8[1]) << 6))
  244. | (0x7F & ord($utf8[2])));
  245. }
  246. // ignoring UTF-32 for now, sorry
  247. return '';
  248. }
  249. /**
  250. * encodes an arbitrary variable into JSON format (and sends JSON Header)
  251. *
  252. * @deprecated 5.3.0 Use the PHP native JSON extension instead.
  253. *
  254. * @param mixed $var any number, boolean, string, array, or object to be encoded.
  255. * see argument 1 to Services_JSON() above for array-parsing behavior.
  256. * if var is a string, note that encode() always expects it
  257. * to be in ASCII or UTF-8 format!
  258. *
  259. * @return mixed JSON string representation of input var or an error if a problem occurs
  260. * @access public
  261. */
  262. function encode($var)
  263. {
  264. _deprecated_function( __METHOD__, '5.3.0', 'The PHP native JSON extension' );
  265. header('Content-type: application/json');
  266. return $this->encodeUnsafe($var);
  267. }
  268. /**
  269. * encodes an arbitrary variable into JSON format without JSON Header - warning - may allow XSS!!!!)
  270. *
  271. * @deprecated 5.3.0 Use the PHP native JSON extension instead.
  272. *
  273. * @param mixed $var any number, boolean, string, array, or object to be encoded.
  274. * see argument 1 to Services_JSON() above for array-parsing behavior.
  275. * if var is a string, note that encode() always expects it
  276. * to be in ASCII or UTF-8 format!
  277. *
  278. * @return mixed JSON string representation of input var or an error if a problem occurs
  279. * @access public
  280. */
  281. function encodeUnsafe($var)
  282. {
  283. _deprecated_function( __METHOD__, '5.3.0', 'The PHP native JSON extension' );
  284. // see bug #16908 - regarding numeric locale printing
  285. $lc = setlocale(LC_NUMERIC, 0);
  286. setlocale(LC_NUMERIC, 'C');
  287. $ret = $this->_encode($var);
  288. setlocale(LC_NUMERIC, $lc);
  289. return $ret;
  290. }
  291. /**
  292. * PRIVATE CODE that does the work of encodes an arbitrary variable into JSON format
  293. *
  294. * @deprecated 5.3.0 Use the PHP native JSON extension instead.
  295. *
  296. * @param mixed $var any number, boolean, string, array, or object to be encoded.
  297. * see argument 1 to Services_JSON() above for array-parsing behavior.
  298. * if var is a string, note that encode() always expects it
  299. * to be in ASCII or UTF-8 format!
  300. *
  301. * @return mixed JSON string representation of input var or an error if a problem occurs
  302. * @access public
  303. */
  304. function _encode($var)
  305. {
  306. _deprecated_function( __METHOD__, '5.3.0', 'The PHP native JSON extension' );
  307. switch (gettype($var)) {
  308. case 'boolean':
  309. return $var ? 'true' : 'false';
  310. case 'NULL':
  311. return 'null';
  312. case 'integer':
  313. return (int) $var;
  314. case 'double':
  315. case 'float':
  316. return (float) $var;
  317. case 'string':
  318. // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
  319. $ascii = '';
  320. $strlen_var = $this->strlen8($var);
  321. /*
  322. * Iterate over every character in the string,
  323. * escaping with a slash or encoding to UTF-8 where necessary
  324. */
  325. for ($c = 0; $c < $strlen_var; ++$c) {
  326. $ord_var_c = ord($var[$c]);
  327. switch (true) {
  328. case $ord_var_c == 0x08:
  329. $ascii .= '\b';
  330. break;
  331. case $ord_var_c == 0x09:
  332. $ascii .= '\t';
  333. break;
  334. case $ord_var_c == 0x0A:
  335. $ascii .= '\n';
  336. break;
  337. case $ord_var_c == 0x0C:
  338. $ascii .= '\f';
  339. break;
  340. case $ord_var_c == 0x0D:
  341. $ascii .= '\r';
  342. break;
  343. case $ord_var_c == 0x22:
  344. case $ord_var_c == 0x2F:
  345. case $ord_var_c == 0x5C:
  346. // double quote, slash, slosh
  347. $ascii .= '\\'.$var[$c];
  348. break;
  349. case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
  350. // characters U-00000000 - U-0000007F (same as ASCII)
  351. $ascii .= $var[$c];
  352. break;
  353. case (($ord_var_c & 0xE0) == 0xC0):
  354. // characters U-00000080 - U-000007FF, mask 110XXXXX
  355. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  356. if ($c+1 >= $strlen_var) {
  357. $c += 1;
  358. $ascii .= '?';
  359. break;
  360. }
  361. $char = pack('C*', $ord_var_c, ord($var[$c + 1]));
  362. $c += 1;
  363. $utf16 = $this->utf82utf16($char);
  364. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  365. break;
  366. case (($ord_var_c & 0xF0) == 0xE0):
  367. if ($c+2 >= $strlen_var) {
  368. $c += 2;
  369. $ascii .= '?';
  370. break;
  371. }
  372. // characters U-00000800 - U-0000FFFF, mask 1110XXXX
  373. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  374. $char = pack('C*', $ord_var_c,
  375. @ord($var[$c + 1]),
  376. @ord($var[$c + 2]));
  377. $c += 2;
  378. $utf16 = $this->utf82utf16($char);
  379. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  380. break;
  381. case (($ord_var_c & 0xF8) == 0xF0):
  382. if ($c+3 >= $strlen_var) {
  383. $c += 3;
  384. $ascii .= '?';
  385. break;
  386. }
  387. // characters U-00010000 - U-001FFFFF, mask 11110XXX
  388. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  389. $char = pack('C*', $ord_var_c,
  390. ord($var[$c + 1]),
  391. ord($var[$c + 2]),
  392. ord($var[$c + 3]));
  393. $c += 3;
  394. $utf16 = $this->utf82utf16($char);
  395. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  396. break;
  397. case (($ord_var_c & 0xFC) == 0xF8):
  398. // characters U-00200000 - U-03FFFFFF, mask 111110XX
  399. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  400. if ($c+4 >= $strlen_var) {
  401. $c += 4;
  402. $ascii .= '?';
  403. break;
  404. }
  405. $char = pack('C*', $ord_var_c,
  406. ord($var[$c + 1]),
  407. ord($var[$c + 2]),
  408. ord($var[$c + 3]),
  409. ord($var[$c + 4]));
  410. $c += 4;
  411. $utf16 = $this->utf82utf16($char);
  412. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  413. break;
  414. case (($ord_var_c & 0xFE) == 0xFC):
  415. if ($c+5 >= $strlen_var) {
  416. $c += 5;
  417. $ascii .= '?';
  418. break;
  419. }
  420. // characters U-04000000 - U-7FFFFFFF, mask 1111110X
  421. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  422. $char = pack('C*', $ord_var_c,
  423. ord($var[$c + 1]),
  424. ord($var[$c + 2]),
  425. ord($var[$c + 3]),
  426. ord($var[$c + 4]),
  427. ord($var[$c + 5]));
  428. $c += 5;
  429. $utf16 = $this->utf82utf16($char);
  430. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  431. break;
  432. }
  433. }
  434. return '"'.$ascii.'"';
  435. case 'array':
  436. /*
  437. * As per JSON spec if any array key is not an integer
  438. * we must treat the whole array as an object. We
  439. * also try to catch a sparsely populated associative
  440. * array with numeric keys here because some JS engines
  441. * will create an array with empty indexes up to
  442. * max_index which can cause memory issues and because
  443. * the keys, which may be relevant, will be remapped
  444. * otherwise.
  445. *
  446. * As per the ECMA and JSON specification an object may
  447. * have any string as a property. Unfortunately due to
  448. * a hole in the ECMA specification if the key is a
  449. * ECMA reserved word or starts with a digit the
  450. * parameter is only accessible using ECMAScript's
  451. * bracket notation.
  452. */
  453. // treat as a JSON object
  454. if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
  455. $properties = array_map(array($this, 'name_value'),
  456. array_keys($var),
  457. array_values($var));
  458. foreach($properties as $property) {
  459. if(Services_JSON::isError($property)) {
  460. return $property;
  461. }
  462. }
  463. return '{' . join(',', $properties) . '}';
  464. }
  465. // treat it like a regular array
  466. $elements = array_map(array($this, '_encode'), $var);
  467. foreach($elements as $element) {
  468. if(Services_JSON::isError($element)) {
  469. return $element;
  470. }
  471. }
  472. return '[' . join(',', $elements) . ']';
  473. case 'object':
  474. // support toJSON methods.
  475. if (($this->use & SERVICES_JSON_USE_TO_JSON) && method_exists($var, 'toJSON')) {
  476. // this may end up allowing unlimited recursion
  477. // so we check the return value to make sure it's not got the same method.
  478. $recode = $var->toJSON();
  479. if (method_exists($recode, 'toJSON')) {
  480. return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
  481. ? 'null'
  482. : new Services_JSON_Error(get_class($var).
  483. " toJSON returned an object with a toJSON method.");
  484. }
  485. return $this->_encode( $recode );
  486. }
  487. $vars = get_object_vars($var);
  488. $properties = array_map(array($this, 'name_value'),
  489. array_keys($vars),
  490. array_values($vars));
  491. foreach($properties as $property) {
  492. if(Services_JSON::isError($property)) {
  493. return $property;
  494. }
  495. }
  496. return '{' . join(',', $properties) . '}';
  497. default:
  498. return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
  499. ? 'null'
  500. : new Services_JSON_Error(gettype($var)." can not be encoded as JSON string");
  501. }
  502. }
  503. /**
  504. * array-walking function for use in generating JSON-formatted name-value pairs
  505. *
  506. * @deprecated 5.3.0 Use the PHP native JSON extension instead.
  507. *
  508. * @param string $name name of key to use
  509. * @param mixed $value reference to an array element to be encoded
  510. *
  511. * @return string JSON-formatted name-value pair, like '"name":value'
  512. * @access private
  513. */
  514. function name_value($name, $value)
  515. {
  516. _deprecated_function( __METHOD__, '5.3.0', 'The PHP native JSON extension' );
  517. $encoded_value = $this->_encode($value);
  518. if(Services_JSON::isError($encoded_value)) {
  519. return $encoded_value;
  520. }
  521. return $this->_encode((string) $name) . ':' . $encoded_value;
  522. }
  523. /**
  524. * reduce a string by removing leading and trailing comments and whitespace
  525. *
  526. * @deprecated 5.3.0 Use the PHP native JSON extension instead.
  527. *
  528. * @param $str string string value to strip of comments and whitespace
  529. *
  530. * @return string string value stripped of comments and whitespace
  531. * @access private
  532. */
  533. function reduce_string($str)
  534. {
  535. _deprecated_function( __METHOD__, '5.3.0', 'The PHP native JSON extension' );
  536. $str = preg_replace(array(
  537. // eliminate single line comments in '// ...' form
  538. '#^\s*//(.+)$#m',
  539. // eliminate multi-line comments in '/* ... */' form, at start of string
  540. '#^\s*/\*(.+)\*/#Us',
  541. // eliminate multi-line comments in '/* ... */' form, at end of string
  542. '#/\*(.+)\*/\s*$#Us'
  543. ), '', $str);
  544. // eliminate extraneous space
  545. return trim($str);
  546. }
  547. /**
  548. * decodes a JSON string into appropriate variable
  549. *
  550. * @deprecated 5.3.0 Use the PHP native JSON extension instead.
  551. *
  552. * @param string $str JSON-formatted string
  553. *
  554. * @return mixed number, boolean, string, array, or object
  555. * corresponding to given JSON input string.
  556. * See argument 1 to Services_JSON() above for object-output behavior.
  557. * Note that decode() always returns strings
  558. * in ASCII or UTF-8 format!
  559. * @access public
  560. */
  561. function decode($str)
  562. {
  563. _deprecated_function( __METHOD__, '5.3.0', 'The PHP native JSON extension' );
  564. $str = $this->reduce_string($str);
  565. switch (strtolower($str)) {
  566. case 'true':
  567. return true;
  568. case 'false':
  569. return false;
  570. case 'null':
  571. return null;
  572. default:
  573. $m = array();
  574. if (is_numeric($str)) {
  575. // Lookie-loo, it's a number
  576. // This would work on its own, but I'm trying to be
  577. // good about returning integers where appropriate:
  578. // return (float)$str;
  579. // Return float or int, as appropriate
  580. return ((float)$str == (integer)$str)
  581. ? (integer)$str
  582. : (float)$str;
  583. } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) {
  584. // STRINGS RETURNED IN UTF-8 FORMAT
  585. $delim = $this->substr8($str, 0, 1);
  586. $chrs = $this->substr8($str, 1, -1);
  587. $utf8 = '';
  588. $strlen_chrs = $this->strlen8($chrs);
  589. for ($c = 0; $c < $strlen_chrs; ++$c) {
  590. $substr_chrs_c_2 = $this->substr8($chrs, $c, 2);
  591. $ord_chrs_c = ord($chrs[$c]);
  592. switch (true) {
  593. case $substr_chrs_c_2 == '\b':
  594. $utf8 .= chr(0x08);
  595. ++$c;
  596. break;
  597. case $substr_chrs_c_2 == '\t':
  598. $utf8 .= chr(0x09);
  599. ++$c;
  600. break;
  601. case $substr_chrs_c_2 == '\n':
  602. $utf8 .= chr(0x0A);
  603. ++$c;
  604. break;
  605. case $substr_chrs_c_2 == '\f':
  606. $utf8 .= chr(0x0C);
  607. ++$c;
  608. break;
  609. case $substr_chrs_c_2 == '\r':
  610. $utf8 .= chr(0x0D);
  611. ++$c;
  612. break;
  613. case $substr_chrs_c_2 == '\\"':
  614. case $substr_chrs_c_2 == '\\\'':
  615. case $substr_chrs_c_2 == '\\\\':
  616. case $substr_chrs_c_2 == '\\/':
  617. if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
  618. ($delim == "'" && $substr_chrs_c_2 != '\\"')) {
  619. $utf8 .= $chrs[++$c];
  620. }
  621. break;
  622. case preg_match('/\\\u[0-9A-F]{4}/i', $this->substr8($chrs, $c, 6)):
  623. // single, escaped unicode character
  624. $utf16 = chr(hexdec($this->substr8($chrs, ($c + 2), 2)))
  625. . chr(hexdec($this->substr8($chrs, ($c + 4), 2)));
  626. $utf8 .= $this->utf162utf8($utf16);
  627. $c += 5;
  628. break;
  629. case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
  630. $utf8 .= $chrs[$c];
  631. break;
  632. case ($ord_chrs_c & 0xE0) == 0xC0:
  633. // characters U-00000080 - U-000007FF, mask 110XXXXX
  634. //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  635. $utf8 .= $this->substr8($chrs, $c, 2);
  636. ++$c;
  637. break;
  638. case ($ord_chrs_c & 0xF0) == 0xE0:
  639. // characters U-00000800 - U-0000FFFF, mask 1110XXXX
  640. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  641. $utf8 .= $this->substr8($chrs, $c, 3);
  642. $c += 2;
  643. break;
  644. case ($ord_chrs_c & 0xF8) == 0xF0:
  645. // characters U-00010000 - U-001FFFFF, mask 11110XXX
  646. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  647. $utf8 .= $this->substr8($chrs, $c, 4);
  648. $c += 3;
  649. break;
  650. case ($ord_chrs_c & 0xFC) == 0xF8:
  651. // characters U-00200000 - U-03FFFFFF, mask 111110XX
  652. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  653. $utf8 .= $this->substr8($chrs, $c, 5);
  654. $c += 4;
  655. break;
  656. case ($ord_chrs_c & 0xFE) == 0xFC:
  657. // characters U-04000000 - U-7FFFFFFF, mask 1111110X
  658. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  659. $utf8 .= $this->substr8($chrs, $c, 6);
  660. $c += 5;
  661. break;
  662. }
  663. }
  664. return $utf8;
  665. } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) {
  666. // array, or object notation
  667. if ($str[0] == '[') {
  668. $stk = array(SERVICES_JSON_IN_ARR);
  669. $arr = array();
  670. } else {
  671. if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
  672. $stk = array(SERVICES_JSON_IN_OBJ);
  673. $obj = array();
  674. } else {
  675. $stk = array(SERVICES_JSON_IN_OBJ);
  676. $obj = new stdClass();
  677. }
  678. }
  679. array_push($stk, array('what' => SERVICES_JSON_SLICE,
  680. 'where' => 0,
  681. 'delim' => false));
  682. $chrs = $this->substr8($str, 1, -1);
  683. $chrs = $this->reduce_string($chrs);
  684. if ($chrs == '') {
  685. if (reset($stk) == SERVICES_JSON_IN_ARR) {
  686. return $arr;
  687. } else {
  688. return $obj;
  689. }
  690. }
  691. //print("\nparsing {$chrs}\n");
  692. $strlen_chrs = $this->strlen8($chrs);
  693. for ($c = 0; $c <= $strlen_chrs; ++$c) {
  694. $top = end($stk);
  695. $substr_chrs_c_2 = $this->substr8($chrs, $c, 2);
  696. if (($c == $strlen_chrs) || (($chrs[$c] == ',') && ($top['what'] == SERVICES_JSON_SLICE))) {
  697. // found a comma that is not inside a string, array, etc.,
  698. // OR we've reached the end of the character list
  699. $slice = $this->substr8($chrs, $top['where'], ($c - $top['where']));
  700. array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false));
  701. //print("Found split at {$c}: ".$this->substr8($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  702. if (reset($stk) == SERVICES_JSON_IN_ARR) {
  703. // we are in an array, so just push an element onto the stack
  704. array_push($arr, $this->decode($slice));
  705. } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
  706. // we are in an object, so figure
  707. // out the property name and set an
  708. // element in an associative array,
  709. // for now
  710. $parts = array();
  711. if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:/Uis', $slice, $parts)) {
  712. // "name":value pair
  713. $key = $this->decode($parts[1]);
  714. $val = $this->decode(trim(substr($slice, strlen($parts[0])), ", \t\n\r\0\x0B"));
  715. if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
  716. $obj[$key] = $val;
  717. } else {
  718. $obj->$key = $val;
  719. }
  720. } elseif (preg_match('/^\s*(\w+)\s*:/Uis', $slice, $parts)) {
  721. // name:value pair, where name is unquoted
  722. $key = $parts[1];
  723. $val = $this->decode(trim(substr($slice, strlen($parts[0])), ", \t\n\r\0\x0B"));
  724. if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
  725. $obj[$key] = $val;
  726. } else {
  727. $obj->$key = $val;
  728. }
  729. }
  730. }
  731. } elseif ((($chrs[$c] == '"') || ($chrs[$c] == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) {
  732. // found a quote, and we are not inside a string
  733. array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs[$c]));
  734. //print("Found start of string at {$c}\n");
  735. } elseif (($chrs[$c] == $top['delim']) &&
  736. ($top['what'] == SERVICES_JSON_IN_STR) &&
  737. (($this->strlen8($this->substr8($chrs, 0, $c)) - $this->strlen8(rtrim($this->substr8($chrs, 0, $c), '\\'))) % 2 != 1)) {
  738. // found a quote, we're in a string, and it's not escaped
  739. // we know that it's not escaped because there is _not_ an
  740. // odd number of backslashes at the end of the string so far
  741. array_pop($stk);
  742. //print("Found end of string at {$c}: ".$this->substr8($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");
  743. } elseif (($chrs[$c] == '[') &&
  744. in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
  745. // found a left-bracket, and we are in an array, object, or slice
  746. array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false));
  747. //print("Found start of array at {$c}\n");
  748. } elseif (($chrs[$c] == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) {
  749. // found a right-bracket, and we're in an array
  750. array_pop($stk);
  751. //print("Found end of array at {$c}: ".$this->substr8($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  752. } elseif (($chrs[$c] == '{') &&
  753. in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
  754. // found a left-brace, and we are in an array, object, or slice
  755. array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false));
  756. //print("Found start of object at {$c}\n");
  757. } elseif (($chrs[$c] == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) {
  758. // found a right-brace, and we're in an object
  759. array_pop($stk);
  760. //print("Found end of object at {$c}: ".$this->substr8($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  761. } elseif (($substr_chrs_c_2 == '/*') &&
  762. in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
  763. // found a comment start, and we are in an array, object, or slice
  764. array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false));
  765. $c++;
  766. //print("Found start of comment at {$c}\n");
  767. } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) {
  768. // found a comment end, and we're in one now
  769. array_pop($stk);
  770. $c++;
  771. for ($i = $top['where']; $i <= $c; ++$i)
  772. $chrs = substr_replace($chrs, ' ', $i, 1);
  773. //print("Found end of comment at {$c}: ".$this->substr8($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  774. }
  775. }
  776. if (reset($stk) == SERVICES_JSON_IN_ARR) {
  777. return $arr;
  778. } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
  779. return $obj;
  780. }
  781. }
  782. }
  783. }
  784. /**
  785. * @deprecated 5.3.0 Use the PHP native JSON extension instead.
  786. *
  787. * @todo Ultimately, this should just call PEAR::isError()
  788. */
  789. function isError($data, $code = null)
  790. {
  791. _deprecated_function( __METHOD__, '5.3.0', 'The PHP native JSON extension' );
  792. if (class_exists('pear')) {
  793. return PEAR::isError($data, $code);
  794. } elseif (is_object($data) && ($data instanceof services_json_error ||
  795. is_subclass_of($data, 'services_json_error'))) {
  796. return true;
  797. }
  798. return false;
  799. }
  800. /**
  801. * Calculates length of string in bytes
  802. *
  803. * @deprecated 5.3.0 Use the PHP native JSON extension instead.
  804. *
  805. * @param string
  806. * @return integer length
  807. */
  808. function strlen8( $str )
  809. {
  810. _deprecated_function( __METHOD__, '5.3.0', 'The PHP native JSON extension' );
  811. if ( $this->_mb_strlen ) {
  812. return mb_strlen( $str, "8bit" );
  813. }
  814. return strlen( $str );
  815. }
  816. /**
  817. * Returns part of a string, interpreting $start and $length as number of bytes.
  818. *
  819. * @deprecated 5.3.0 Use the PHP native JSON extension instead.
  820. *
  821. * @param string
  822. * @param integer start
  823. * @param integer length
  824. * @return integer length
  825. */
  826. function substr8( $string, $start, $length=false )
  827. {
  828. _deprecated_function( __METHOD__, '5.3.0', 'The PHP native JSON extension' );
  829. if ( $length === false ) {
  830. $length = $this->strlen8( $string ) - $start;
  831. }
  832. if ( $this->_mb_substr ) {
  833. return mb_substr( $string, $start, $length, "8bit" );
  834. }
  835. return substr( $string, $start, $length );
  836. }
  837. }
  838. if (class_exists('PEAR_Error')) {
  839. class Services_JSON_Error extends PEAR_Error
  840. {
  841. /**
  842. * PHP5 constructor.
  843. *
  844. * @deprecated 5.3.0 Use the PHP native JSON extension instead.
  845. */
  846. function __construct($message = 'unknown error', $code = null,
  847. $mode = null, $options = null, $userinfo = null)
  848. {
  849. _deprecated_function( __METHOD__, '5.3.0', 'The PHP native JSON extension' );
  850. parent::PEAR_Error($message, $code, $mode, $options, $userinfo);
  851. }
  852. /**
  853. * PHP4 constructor.
  854. *
  855. * @deprecated 5.3.0 Use __construct() instead.
  856. *
  857. * @see Services_JSON_Error::__construct()
  858. */
  859. public function Services_JSON_Error($message = 'unknown error', $code = null,
  860. $mode = null, $options = null, $userinfo = null) {
  861. _deprecated_constructor( 'Services_JSON_Error', '5.3.0', get_class( $this ) );
  862. self::__construct($message, $code, $mode, $options, $userinfo);
  863. }
  864. }
  865. } else {
  866. /**
  867. * @todo Ultimately, this class shall be descended from PEAR_Error
  868. */
  869. class Services_JSON_Error
  870. {
  871. /**
  872. * PHP5 constructor.
  873. *
  874. * @deprecated 5.3.0 Use the PHP native JSON extension instead.
  875. */
  876. function __construct( $message = 'unknown error', $code = null,
  877. $mode = null, $options = null, $userinfo = null )
  878. {
  879. _deprecated_function( __METHOD__, '5.3.0', 'The PHP native JSON extension' );
  880. }
  881. /**
  882. * PHP4 constructor.
  883. *
  884. * @deprecated 5.3.0 Use __construct() instead.
  885. *
  886. * @see Services_JSON_Error::__construct()
  887. */
  888. public function Services_JSON_Error( $message = 'unknown error', $code = null,
  889. $mode = null, $options = null, $userinfo = null ) {
  890. _deprecated_constructor( 'Services_JSON_Error', '5.3.0', get_class( $this ) );
  891. self::__construct( $message, $code, $mode, $options, $userinfo );
  892. }
  893. }
  894. }
  895. endif;