PageRenderTime 42ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/src/application/libraries/Zend/Json.php

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