PageRenderTime 49ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/protected/vendors/Zend/Json.php

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