PageRenderTime 63ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/library/paypal/json.php

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