Json.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Json
  17. * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. * @version $Id$
  20. */
  21. /**
  22. * Zend_Json_Expr.
  23. *
  24. * @see Zend_Json_Expr
  25. */
  26. #require_once 'Zend/Json/Expr.php';
  27. /** @see Zend_Xml_Security */
  28. #require_once 'Zend/Xml/Security.php';
  29. /**
  30. * Class for encoding to and decoding from JSON.
  31. *
  32. * @category Zend
  33. * @package Zend_Json
  34. * @uses Zend_Json_Expr
  35. * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
  36. * @license http://framework.zend.com/license/new-bsd New BSD License
  37. */
  38. class Zend_Json
  39. {
  40. /**
  41. * How objects should be encoded -- arrays or as StdClass. TYPE_ARRAY is 1
  42. * so that it is a boolean true value, allowing it to be used with
  43. * ext/json's functions.
  44. */
  45. const TYPE_ARRAY = 1;
  46. const TYPE_OBJECT = 0;
  47. /**
  48. * To check the allowed nesting depth of the XML tree during xml2json conversion.
  49. *
  50. * @var int
  51. */
  52. public static $maxRecursionDepthAllowed=25;
  53. /**
  54. * @var bool
  55. */
  56. public static $useBuiltinEncoderDecoder = false;
  57. /**
  58. * Decodes the given $encodedValue string which is
  59. * encoded in the JSON format
  60. *
  61. * Uses ext/json's json_decode if available.
  62. *
  63. * @param string $encodedValue Encoded in JSON format
  64. * @param int $objectDecodeType Optional; flag indicating how to decode
  65. * objects. See {@link Zend_Json_Decoder::decode()} for details.
  66. * @return mixed
  67. */
  68. public static function decode($encodedValue, $objectDecodeType = Zend_Json::TYPE_ARRAY)
  69. {
  70. $encodedValue = (string) $encodedValue;
  71. if (function_exists('json_decode') && self::$useBuiltinEncoderDecoder !== true) {
  72. $decode = json_decode($encodedValue, $objectDecodeType);
  73. // php < 5.3
  74. if (!function_exists('json_last_error')) {
  75. if (strtolower($encodedValue) === 'null') {
  76. return null;
  77. } elseif ($decode === null) {
  78. #require_once 'Zend/Json/Exception.php';
  79. throw new Zend_Json_Exception('Decoding failed');
  80. }
  81. // php >= 5.3
  82. } elseif (($jsonLastErr = json_last_error()) != JSON_ERROR_NONE) {
  83. #require_once 'Zend/Json/Exception.php';
  84. switch ($jsonLastErr) {
  85. case JSON_ERROR_DEPTH:
  86. throw new Zend_Json_Exception('Decoding failed: Maximum stack depth exceeded');
  87. case JSON_ERROR_CTRL_CHAR:
  88. throw new Zend_Json_Exception('Decoding failed: Unexpected control character found');
  89. case JSON_ERROR_SYNTAX:
  90. throw new Zend_Json_Exception('Decoding failed: Syntax error');
  91. default:
  92. throw new Zend_Json_Exception('Decoding failed');
  93. }
  94. }
  95. return $decode;
  96. }
  97. #require_once 'Zend/Json/Decoder.php';
  98. return Zend_Json_Decoder::decode($encodedValue, $objectDecodeType);
  99. }
  100. /**
  101. * Encode the mixed $valueToEncode into the JSON format
  102. *
  103. * Encodes using ext/json's json_encode() if available.
  104. *
  105. * NOTE: Object should not contain cycles; the JSON format
  106. * does not allow object reference.
  107. *
  108. * NOTE: Only public variables will be encoded
  109. *
  110. * NOTE: Encoding native javascript expressions are possible using Zend_Json_Expr.
  111. * You can enable this by setting $options['enableJsonExprFinder'] = true
  112. *
  113. * @see Zend_Json_Expr
  114. *
  115. * @param mixed $valueToEncode
  116. * @param boolean $cycleCheck Optional; whether or not to check for object recursion; off by default
  117. * @param array $options Additional options used during encoding
  118. * @return string JSON encoded object
  119. */
  120. public static function encode($valueToEncode, $cycleCheck = false, $options = array())
  121. {
  122. if (is_object($valueToEncode)) {
  123. if (method_exists($valueToEncode, 'toJson')) {
  124. return $valueToEncode->toJson();
  125. } elseif (method_exists($valueToEncode, 'toArray')) {
  126. return self::encode($valueToEncode->toArray(), $cycleCheck, $options);
  127. }
  128. }
  129. // Pre-encoding look for Zend_Json_Expr objects and replacing by tmp ids
  130. $javascriptExpressions = array();
  131. if(isset($options['enableJsonExprFinder'])
  132. && ($options['enableJsonExprFinder'] == true)
  133. ) {
  134. /**
  135. * @see Zend_Json_Encoder
  136. */
  137. #require_once "Zend/Json/Encoder.php";
  138. $valueToEncode = self::_recursiveJsonExprFinder($valueToEncode, $javascriptExpressions);
  139. }
  140. // Encoding
  141. if (function_exists('json_encode') && self::$useBuiltinEncoderDecoder !== true) {
  142. $encodedResult = json_encode($valueToEncode);
  143. } else {
  144. #require_once 'Zend/Json/Encoder.php';
  145. $encodedResult = Zend_Json_Encoder::encode($valueToEncode, $cycleCheck, $options);
  146. }
  147. //only do post-proccessing to revert back the Zend_Json_Expr if any.
  148. if (count($javascriptExpressions) > 0) {
  149. $count = count($javascriptExpressions);
  150. for($i = 0; $i < $count; $i++) {
  151. $magicKey = $javascriptExpressions[$i]['magicKey'];
  152. $value = $javascriptExpressions[$i]['value'];
  153. $encodedResult = str_replace(
  154. //instead of replacing "key:magicKey", we replace directly magicKey by value because "key" never changes.
  155. '"' . $magicKey . '"',
  156. $value,
  157. $encodedResult
  158. );
  159. }
  160. }
  161. return $encodedResult;
  162. }
  163. /**
  164. * Check & Replace Zend_Json_Expr for tmp ids in the valueToEncode
  165. *
  166. * Check if the value is a Zend_Json_Expr, and if replace its value
  167. * with a magic key and save the javascript expression in an array.
  168. *
  169. * NOTE this method is recursive.
  170. *
  171. * NOTE: This method is used internally by the encode method.
  172. *
  173. * @see encode
  174. * @param array|object|Zend_Json_Expr $value a string - object property to be encoded
  175. * @param array $javascriptExpressions
  176. * @param null $currentKey
  177. *
  178. * @internal param mixed $valueToCheck
  179. * @return void
  180. */
  181. protected static function _recursiveJsonExprFinder(&$value, array &$javascriptExpressions, $currentKey = null)
  182. {
  183. if ($value instanceof Zend_Json_Expr) {
  184. // TODO: Optimize with ascii keys, if performance is bad
  185. $magicKey = "____" . $currentKey . "_" . (count($javascriptExpressions));
  186. $javascriptExpressions[] = array(
  187. //if currentKey is integer, encodeUnicodeString call is not required.
  188. "magicKey" => (is_int($currentKey)) ? $magicKey : Zend_Json_Encoder::encodeUnicodeString($magicKey),
  189. "value" => $value->__toString(),
  190. );
  191. $value = $magicKey;
  192. } elseif (is_array($value)) {
  193. foreach ($value as $k => $v) {
  194. $value[$k] = self::_recursiveJsonExprFinder($value[$k], $javascriptExpressions, $k);
  195. }
  196. } elseif (is_object($value)) {
  197. foreach ($value as $k => $v) {
  198. $value->$k = self::_recursiveJsonExprFinder($value->$k, $javascriptExpressions, $k);
  199. }
  200. }
  201. return $value;
  202. }
  203. /**
  204. * Return the value of an XML attribute text or the text between
  205. * the XML tags
  206. *
  207. * In order to allow Zend_Json_Expr from xml, we check if the node
  208. * matchs the pattern that try to detect if it is a new Zend_Json_Expr
  209. * if it matches, we return a new Zend_Json_Expr instead of a text node
  210. *
  211. * @param SimpleXMLElement $simpleXmlElementObject
  212. * @return Zend_Json_Expr|string
  213. */
  214. protected static function _getXmlValue($simpleXmlElementObject) {
  215. $pattern = '/^[\s]*new Zend_Json_Expr[\s]*\([\s]*[\"\']{1}(.*)[\"\']{1}[\s]*\)[\s]*$/';
  216. $matchings = array();
  217. $match = preg_match ($pattern, $simpleXmlElementObject, $matchings);
  218. if ($match) {
  219. return new Zend_Json_Expr($matchings[1]);
  220. } else {
  221. return (trim(strval($simpleXmlElementObject)));
  222. }
  223. }
  224. /**
  225. * _processXml - Contains the logic for xml2json
  226. *
  227. * The logic in this function is a recursive one.
  228. *
  229. * The main caller of this function (i.e. fromXml) needs to provide
  230. * only the first two parameters i.e. the SimpleXMLElement object and
  231. * the flag for ignoring or not ignoring XML attributes. The third parameter
  232. * will be used internally within this function during the recursive calls.
  233. *
  234. * This function converts the SimpleXMLElement object into a PHP array by
  235. * calling a recursive (protected static) function in this class. Once all
  236. * the XML elements are stored in the PHP array, it is returned to the caller.
  237. *
  238. * Throws a Zend_Json_Exception if the XML tree is deeper than the allowed limit.
  239. *
  240. * @param SimpleXMLElement $simpleXmlElementObject
  241. * @param boolean $ignoreXmlAttributes
  242. * @param integer $recursionDepth
  243. * @return array
  244. */
  245. protected static function _processXml($simpleXmlElementObject, $ignoreXmlAttributes, $recursionDepth=0)
  246. {
  247. // Keep an eye on how deeply we are involved in recursion.
  248. if ($recursionDepth > self::$maxRecursionDepthAllowed) {
  249. // XML tree is too deep. Exit now by throwing an exception.
  250. #require_once 'Zend/Json/Exception.php';
  251. throw new Zend_Json_Exception(
  252. "Function _processXml exceeded the allowed recursion depth of " .
  253. self::$maxRecursionDepthAllowed);
  254. } // End of if ($recursionDepth > self::$maxRecursionDepthAllowed)
  255. $children = $simpleXmlElementObject->children();
  256. $name = $simpleXmlElementObject->getName();
  257. $value = self::_getXmlValue($simpleXmlElementObject);
  258. $attributes = (array) $simpleXmlElementObject->attributes();
  259. if (count($children) == 0) {
  260. if (!empty($attributes) && !$ignoreXmlAttributes) {
  261. foreach ($attributes['@attributes'] as $k => $v) {
  262. $attributes['@attributes'][$k]= self::_getXmlValue($v);
  263. }
  264. if (!empty($value)) {
  265. $attributes['@text'] = $value;
  266. }
  267. return array($name => $attributes);
  268. } else {
  269. return array($name => $value);
  270. }
  271. } else {
  272. $childArray= array();
  273. foreach ($children as $child) {
  274. $childname = $child->getName();
  275. $element = self::_processXml($child,$ignoreXmlAttributes,$recursionDepth+1);
  276. if (array_key_exists($childname, $childArray)) {
  277. if (empty($subChild[$childname])) {
  278. $childArray[$childname] = array($childArray[$childname]);
  279. $subChild[$childname] = true;
  280. }
  281. $childArray[$childname][] = $element[$childname];
  282. } else {
  283. $childArray[$childname] = $element[$childname];
  284. }
  285. }
  286. if (!empty($attributes) && !$ignoreXmlAttributes) {
  287. foreach ($attributes['@attributes'] as $k => $v) {
  288. $attributes['@attributes'][$k] = self::_getXmlValue($v);
  289. }
  290. $childArray['@attributes'] = $attributes['@attributes'];
  291. }
  292. if (!empty($value)) {
  293. $childArray['@text'] = $value;
  294. }
  295. return array($name => $childArray);
  296. }
  297. }
  298. /**
  299. * fromXml - Converts XML to JSON
  300. *
  301. * Converts a XML formatted string into a JSON formatted string.
  302. * The value returned will be a string in JSON format.
  303. *
  304. * The caller of this function needs to provide only the first parameter,
  305. * which is an XML formatted String. The second parameter is optional, which
  306. * lets the user to select if the XML attributes in the input XML string
  307. * should be included or ignored in xml2json conversion.
  308. *
  309. * This function converts the XML formatted string into a PHP array by
  310. * calling a recursive (protected static) function in this class. Then, it
  311. * converts that PHP array into JSON by calling the "encode" static funcion.
  312. *
  313. * Throws a Zend_Json_Exception if the input not a XML formatted string.
  314. * NOTE: Encoding native javascript expressions via Zend_Json_Expr is not possible.
  315. *
  316. * @static
  317. * @access public
  318. * @param string $xmlStringContents XML String to be converted
  319. * @param boolean $ignoreXmlAttributes Include or exclude XML attributes in
  320. * the xml2json conversion process.
  321. * @return mixed - JSON formatted string on success
  322. * @throws Zend_Json_Exception
  323. */
  324. public static function fromXml($xmlStringContents, $ignoreXmlAttributes=true)
  325. {
  326. // Load the XML formatted string into a Simple XML Element object.
  327. $simpleXmlElementObject = Zend_Xml_Security::scan($xmlStringContents);
  328. // If it is not a valid XML content, throw an exception.
  329. if ($simpleXmlElementObject == null) {
  330. #require_once 'Zend/Json/Exception.php';
  331. throw new Zend_Json_Exception('Function fromXml was called with an invalid XML formatted string.');
  332. } // End of if ($simpleXmlElementObject == null)
  333. $resultArray = null;
  334. // Call the recursive function to convert the XML into a PHP array.
  335. $resultArray = self::_processXml($simpleXmlElementObject, $ignoreXmlAttributes);
  336. // Convert the PHP array to JSON using Zend_Json encode method.
  337. // It is just that simple.
  338. $jsonStringOutput = self::encode($resultArray);
  339. return($jsonStringOutput);
  340. }
  341. /**
  342. * Pretty-print JSON string
  343. *
  344. * Use 'format' option to select output format - currently html and txt supported, txt is default
  345. * Use 'indent' option to override the indentation string set in the format - by default for the 'txt' format it's a tab
  346. *
  347. * @param string $json Original JSON string
  348. * @param array $options Encoding options
  349. * @return string
  350. */
  351. public static function prettyPrint($json, $options = array())
  352. {
  353. $tokens = preg_split('|([\{\}\]\[,])|', $json, -1, PREG_SPLIT_DELIM_CAPTURE);
  354. $result = '';
  355. $indent = 0;
  356. $format= 'txt';
  357. $ind = "\t";
  358. if (isset($options['format'])) {
  359. $format = $options['format'];
  360. }
  361. switch ($format) {
  362. case 'html':
  363. $lineBreak = '<br />';
  364. $ind = '&nbsp;&nbsp;&nbsp;&nbsp;';
  365. break;
  366. default:
  367. case 'txt':
  368. $lineBreak = "\n";
  369. $ind = "\t";
  370. break;
  371. }
  372. // override the defined indent setting with the supplied option
  373. if (isset($options['indent'])) {
  374. $ind = $options['indent'];
  375. }
  376. $inLiteral = false;
  377. foreach($tokens as $token) {
  378. if($token == '') {
  379. continue;
  380. }
  381. $prefix = str_repeat($ind, $indent);
  382. if (!$inLiteral && ($token == '{' || $token == '[')) {
  383. $indent++;
  384. if (($result != '') && ($result[(strlen($result)-1)] == $lineBreak)) {
  385. $result .= $prefix;
  386. }
  387. $result .= $token . $lineBreak;
  388. } elseif (!$inLiteral && ($token == '}' || $token == ']')) {
  389. $indent--;
  390. $prefix = str_repeat($ind, $indent);
  391. $result .= $lineBreak . $prefix . $token;
  392. } elseif (!$inLiteral && $token == ',') {
  393. $result .= $token . $lineBreak;
  394. } else {
  395. $result .= ( $inLiteral ? '' : $prefix ) . $token;
  396. // Count # of unescaped double-quotes in token, subtract # of
  397. // escaped double-quotes and if the result is odd then we are
  398. // inside a string literal
  399. if ((substr_count($token, "\"")-substr_count($token, "\\\"")) % 2 != 0) {
  400. $inLiteral = !$inLiteral;
  401. }
  402. }
  403. }
  404. return $result;
  405. }
  406. }