Json.php 17 KB

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