PageRenderTime 47ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/plugins_repo/openXWorkflow/www/admin/plugins/openXWorkflow/library/Zend/Json.php

https://bitbucket.org/valmy/openx
PHP | 338 lines | 125 code | 31 blank | 182 comment | 31 complexity | aa7e5bc872aeaabf599c7900d5c9e455 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-2008 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. */
  20. /**
  21. * Zend_Json_Expr.
  22. *
  23. * @see Zend_Json_Expr
  24. */
  25. require_once 'Zend/Json/Expr.php';
  26. /**
  27. * Class for encoding to and decoding from JSON.
  28. *
  29. * @category Zend
  30. * @package Zend_Json
  31. * @uses Zend_Json_Expr
  32. * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
  33. * @license http://framework.zend.com/license/new-bsd New BSD License
  34. */
  35. class Zend_Json
  36. {
  37. /**
  38. * How objects should be encoded -- arrays or as StdClass. TYPE_ARRAY is 1
  39. * so that it is a boolean true value, allowing it to be used with
  40. * ext/json's functions.
  41. */
  42. const TYPE_ARRAY = 1;
  43. const TYPE_OBJECT = 0;
  44. /**
  45. * To check the allowed nesting depth of the XML tree during xml2json conversion.
  46. *
  47. * @var int
  48. */
  49. public static $maxRecursionDepthAllowed=25;
  50. /**
  51. * @var bool
  52. */
  53. public static $useBuiltinEncoderDecoder = false;
  54. /**
  55. * Decodes the given $encodedValue string which is
  56. * encoded in the JSON format
  57. *
  58. * Uses ext/json's json_decode if available.
  59. *
  60. * @param string $encodedValue Encoded in JSON format
  61. * @param int $objectDecodeType Optional; flag indicating how to decode
  62. * objects. See {@link Zend_Json_Decoder::decode()} for details.
  63. * @return mixed
  64. */
  65. public static function decode($encodedValue, $objectDecodeType = Zend_Json::TYPE_ARRAY)
  66. {
  67. if (function_exists('json_decode') && self::$useBuiltinEncoderDecoder !== true) {
  68. return json_decode($encodedValue, $objectDecodeType);
  69. }
  70. require_once 'Zend/Json/Decoder.php';
  71. return Zend_Json_Decoder::decode($encodedValue, $objectDecodeType);
  72. }
  73. /**
  74. * Encode the mixed $valueToEncode into the JSON format
  75. *
  76. * Encodes using ext/json's json_encode() if available.
  77. *
  78. * NOTE: Object should not contain cycles; the JSON format
  79. * does not allow object reference.
  80. *
  81. * NOTE: Only public variables will be encoded
  82. *
  83. * NOTE: Encoding native javascript expressions are possible using Zend_Json_Expr.
  84. * You can enable this by setting $options['enableJsonExprFinder'] = true
  85. *
  86. * @see Zend_Json_Expr
  87. *
  88. * @param mixed $valueToEncode
  89. * @param boolean $cycleCheck Optional; whether or not to check for object recursion; off by default
  90. * @param array $options Additional options used during encoding
  91. * @return string JSON encoded object
  92. */
  93. public static function encode($valueToEncode, $cycleCheck = false, $options = array())
  94. {
  95. if (is_object($valueToEncode) && method_exists($valueToEncode, 'toJson')) {
  96. return $valueToEncode->toJson();
  97. }
  98. // Pre-encoding look for Zend_Json_Expr objects and replacing by tmp ids
  99. $javascriptExpressions = array();
  100. if(isset($options['enableJsonExprFinder'])
  101. && ($options['enableJsonExprFinder'] == true)
  102. ) {
  103. /**
  104. * @see Zend_Json_Encoder
  105. */
  106. require_once "Zend/Json/Encoder.php";
  107. $valueToEncode = self::_recursiveJsonExprFinder($valueToEncode, $javascriptExpressions);
  108. }
  109. // Encoding
  110. if (function_exists('json_encode') && self::$useBuiltinEncoderDecoder !== true) {
  111. $encodedResult = json_encode($valueToEncode);
  112. } else {
  113. require_once 'Zend/Json/Encoder.php';
  114. $encodedResult = Zend_Json_Encoder::encode($valueToEncode, $cycleCheck, $options);
  115. }
  116. //only do post-proccessing to revert back the Zend_Json_Expr if any.
  117. if (count($javascriptExpressions) > 0) {
  118. $count = count($javascriptExpressions);
  119. for($i = 0; $i < $count; $i++) {
  120. $magicKey = $javascriptExpressions[$i]['magicKey'];
  121. $value = $javascriptExpressions[$i]['value'];
  122. $encodedResult = str_replace(
  123. //instead of replacing "key:magicKey", we replace directly magicKey by value because "key" never changes.
  124. '"' . $magicKey . '"',
  125. $value,
  126. $encodedResult
  127. );
  128. }
  129. }
  130. return $encodedResult;
  131. }
  132. /**
  133. * Check & Replace Zend_Json_Expr for tmp ids in the valueToEncode
  134. *
  135. * Check if the value is a Zend_Json_Expr, and if replace its value
  136. * with a magic key and save the javascript expression in an array.
  137. *
  138. * NOTE this method is recursive.
  139. *
  140. * NOTE: This method is used internally by the encode method.
  141. *
  142. * @see encode
  143. * @param mixed $valueToCheck a string - object property to be encoded
  144. * @return void
  145. */
  146. protected static function _recursiveJsonExprFinder(
  147. &$value, array &$javascriptExpressions, $currentKey = null
  148. ) {
  149. if ($value instanceof Zend_Json_Expr) {
  150. // TODO: Optimize with ascii keys, if performance is bad
  151. $magicKey = "____" . $currentKey . "_" . (count($javascriptExpressions));
  152. $javascriptExpressions[] = array(
  153. //if currentKey is integer, encodeUnicodeString call is not required.
  154. "magicKey" => (is_int($currentKey)) ? $magicKey : Zend_Json_Encoder::encodeUnicodeString($magicKey),
  155. "value" => $value->__toString(),
  156. );
  157. $value = $magicKey;
  158. } elseif (is_array($value)) {
  159. foreach ($value as $k => $v) {
  160. $value[$k] = self::_recursiveJsonExprFinder($value[$k], $javascriptExpressions, $k);
  161. }
  162. } elseif (is_object($value)) {
  163. foreach ($value as $k => $v) {
  164. $value->$k = self::_recursiveJsonExprFinder($value->$k, $javascriptExpressions, $k);
  165. }
  166. }
  167. return $value;
  168. }
  169. /**
  170. * fromXml - Converts XML to JSON
  171. *
  172. * Converts a XML formatted string into a JSON formatted string.
  173. * The value returned will be a string in JSON format.
  174. *
  175. * The caller of this function needs to provide only the first parameter,
  176. * which is an XML formatted String. The second parameter is optional, which
  177. * lets the user to select if the XML attributes in the input XML string
  178. * should be included or ignored in xml2json conversion.
  179. *
  180. * This function converts the XML formatted string into a PHP array by
  181. * calling a recursive (protected static) function in this class. Then, it
  182. * converts that PHP array into JSON by calling the "encode" static funcion.
  183. *
  184. * Throws a Zend_Json_Exception if the input not a XML formatted string.
  185. * NOTE: Encoding native javascript expressions via Zend_Json_Expr is not possible.
  186. *
  187. * @static
  188. * @access public
  189. * @param string $xmlStringContents XML String to be converted
  190. * @param boolean $ignoreXmlAttributes Include or exclude XML attributes in
  191. * the xml2json conversion process.
  192. * @return mixed - JSON formatted string on success
  193. * @throws Zend_Json_Exception
  194. */
  195. public static function fromXml ($xmlStringContents, $ignoreXmlAttributes=true) {
  196. // Load the XML formatted string into a Simple XML Element object.
  197. $simpleXmlElementObject = simplexml_load_string($xmlStringContents);
  198. // If it is not a valid XML content, throw an exception.
  199. if ($simpleXmlElementObject == null) {
  200. require_once 'Zend/Json/Exception.php';
  201. throw new Zend_Json_Exception('Function fromXml was called with an invalid XML formatted string.');
  202. } // End of if ($simpleXmlElementObject == null)
  203. $resultArray = null;
  204. // Call the recursive function to convert the XML into a PHP array.
  205. $resultArray = self::_processXml($simpleXmlElementObject, $ignoreXmlAttributes);
  206. // Convert the PHP array to JSON using Zend_Json encode method.
  207. // It is just that simple.
  208. $jsonStringOutput = self::encode($resultArray);
  209. return($jsonStringOutput);
  210. } // End of function fromXml.
  211. /**
  212. * _processXml - Contains the logic for xml2json
  213. *
  214. * The logic in this function is a recursive one.
  215. *
  216. * The main caller of this function (i.e. fromXml) needs to provide
  217. * only the first two parameters i.e. the SimpleXMLElement object and
  218. * the flag for ignoring or not ignoring XML attributes. The third parameter
  219. * will be used internally within this function during the recursive calls.
  220. *
  221. * This function converts the SimpleXMLElement object into a PHP array by
  222. * calling a recursive (protected static) function in this class. Once all
  223. * the XML elements are stored in the PHP array, it is returned to the caller.
  224. *
  225. * Throws a Zend_Json_Exception if the XML tree is deeper than the allowed limit.
  226. *
  227. * @static
  228. * @access protected
  229. * @param SimpleXMLElement $simpleXmlElementObject XML element to be converted
  230. * @param boolean $ignoreXmlAttributes Include or exclude XML attributes in
  231. * the xml2json conversion process.
  232. * @param int $recursionDepth Current recursion depth of this function
  233. * @return mixed - On success, a PHP associative array of traversed XML elements
  234. * @throws Zend_Json_Exception
  235. */
  236. protected static function _processXml ($simpleXmlElementObject, $ignoreXmlAttributes, $recursionDepth=0) {
  237. // Keep an eye on how deeply we are involved in recursion.
  238. if ($recursionDepth > self::$maxRecursionDepthAllowed) {
  239. // XML tree is too deep. Exit now by throwing an exception.
  240. require_once 'Zend/Json/Exception.php';
  241. throw new Zend_Json_Exception(
  242. "Function _processXml exceeded the allowed recursion depth of " .
  243. self::$maxRecursionDepthAllowed);
  244. } // End of if ($recursionDepth > self::$maxRecursionDepthAllowed)
  245. if ($recursionDepth == 0) {
  246. // Store the original SimpleXmlElementObject sent by the caller.
  247. // We will need it at the very end when we return from here for good.
  248. $callerProvidedSimpleXmlElementObject = $simpleXmlElementObject;
  249. } // End of if ($recursionDepth == 0)
  250. if ($simpleXmlElementObject instanceof SimpleXMLElement) {
  251. // Get a copy of the simpleXmlElementObject
  252. $copyOfSimpleXmlElementObject = $simpleXmlElementObject;
  253. // Get the object variables in the SimpleXmlElement object for us to iterate.
  254. $simpleXmlElementObject = get_object_vars($simpleXmlElementObject);
  255. } // End of if (get_class($simpleXmlElementObject) == "SimpleXMLElement")
  256. // It needs to be an array of object variables.
  257. if (is_array($simpleXmlElementObject)) {
  258. // Initialize a result array.
  259. $resultArray = array();
  260. // Is the input array size 0? Then, we reached the rare CDATA text if any.
  261. if (count($simpleXmlElementObject) <= 0) {
  262. // Let us return the lonely CDATA. It could even be
  263. // an empty element or just filled with whitespaces.
  264. return (trim(strval($copyOfSimpleXmlElementObject)));
  265. } // End of if (count($simpleXmlElementObject) <= 0)
  266. // Let us walk through the child elements now.
  267. foreach($simpleXmlElementObject as $key=>$value) {
  268. // Check if we need to ignore the XML attributes.
  269. // If yes, you can skip processing the XML attributes.
  270. // Otherwise, add the XML attributes to the result array.
  271. if(($ignoreXmlAttributes == true) && (is_string($key)) && ($key == "@attributes")) {
  272. continue;
  273. } // End of if(($ignoreXmlAttributes == true) && ($key == "@attributes"))
  274. // Let us recursively process the current XML element we just visited.
  275. // Increase the recursion depth by one.
  276. $recursionDepth++;
  277. $resultArray[$key] = self::_processXml ($value, $ignoreXmlAttributes, $recursionDepth);
  278. // Decrease the recursion depth by one.
  279. $recursionDepth--;
  280. } // End of foreach($simpleXmlElementObject as $key=>$value) {
  281. if ($recursionDepth == 0) {
  282. // That is it. We are heading to the exit now.
  283. // Set the XML root element name as the root [top-level] key of
  284. // the associative array that we are going to return to the original
  285. // caller of this recursive function.
  286. $tempArray = $resultArray;
  287. $resultArray = array();
  288. $resultArray[$callerProvidedSimpleXmlElementObject->getName()] = $tempArray;
  289. } // End of if ($recursionDepth == 0)
  290. return($resultArray);
  291. } else {
  292. // We are now looking at either the XML attribute text or
  293. // the text between the XML tags.
  294. // In order to allow Zend_Json_Expr from xml, we check if the node
  295. // matchs the pattern that try to detect if it is a new Zend_Json_Expr
  296. // if it matches, we return a new Zend_Json_Expr instead of a text node
  297. $pattern = '/^[\s]*new Zend_Json_Expr[\s]*\([\s]*[\"\']{1}(.*)[\"\']{1}[\s]*\)[\s]*$/';
  298. $matchings = array();
  299. $match = preg_match ($pattern, $simpleXmlElementObject, $matchings);
  300. if ($match) {
  301. return new Zend_Json_Expr($matchings[1]);
  302. } else {
  303. return (trim(strval($simpleXmlElementObject)));
  304. }
  305. } // End of if (is_array($simpleXmlElementObject))
  306. } // End of function _processXml.
  307. }