PageRenderTime 29ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/plugins/wordpress-console/lib/FastJSON.class.php

https://gitlab.com/blueprintmrk/bladencountyrecords
PHP | 368 lines | 186 code | 5 blank | 177 comment | 12 complexity | d6b7b4d64ab11aa6521b9a3231fe6a37 MD5 | raw file
  1. <?php
  2. /**_______________________________________
  3. *
  4. * FastJSON,
  5. * simple and fast Pear Service_JSON encoder/decoder alternative
  6. * [http://pear.php.net/pepr/pepr-proposal-show.php?id=198]
  7. * ---------------------------------------
  8. * This class is about two time faster than Pear Service_JSON class.
  9. * This class is probably not powerful as Service_JSON but it has
  10. * no dependencies and converts correctly ASCII range 0x00 - 0x1F too.
  11. * There's any string convertion, just regular RFC specific characters are converted
  12. * into \u00XX string.
  13. * To don't have problems with other chars try to use utf8_encode($json_encoded_string).
  14. * To recieve correctly JSON strings from JavaScript use encodeURIComponent then
  15. * use, if is necessary, utef8_decode before JS to PHP convertion.
  16. * decode method doesn't returns a standard object class but You can
  17. * create the corret class directly with FastJSON::convert method
  18. * and with them You can manage JS Date objects too.
  19. * ---------------------------------------
  20. * Summary of static public methods
  21. *
  22. * convert
  23. * extra, special method
  24. *
  25. * decode
  26. * converts a valid JSON string
  27. * into a native PHP variable
  28. *
  29. * encode
  30. * converts a native php variable
  31. * into a valid JSON string
  32. * ---------------------------------------
  33. *
  34. * Special FastJSON::convert method Informations
  35. * _______________________________________
  36. * ---------------------------------------
  37. * This method is used by FastJSON::encode method but should be used
  38. * to do these convertions too:
  39. *
  40. * - JSON string to time() integer:
  41. *
  42. * FastJSON::convert(decodedDate:String):time()
  43. *
  44. * If You recieve a date string rappresentation You
  45. * could convert into respective time() integer.
  46. * Example:
  47. * FastJSON::convert(FastJSON::decode($clienttime));
  48. * // i.e. $clienttime = 2006-11-09T14:42:30
  49. * // returned time will be an integer useful with gmdate or date
  50. * // to create, for example, this string
  51. * // Thu Nov 09 2006 14:42:30 GMT+0100 (Rome, Europe)
  52. *
  53. * - time() to JSON string:
  54. *
  55. * FastJSON::convert(time():Int32, true:Boolean):JSON Date String format
  56. *
  57. * You could send server time() informations and send them to clients.
  58. * Example:
  59. * FastJSON::convert(time(), true);
  60. * // i.e. 2006-11-09T14:42:30
  61. *
  62. * - associative array to generic class:
  63. *
  64. * FastJSON::convert(array(params=>values), new GenericClass):new Instance of GenericClass
  65. *
  66. * With a decoded JSON object You could convert them
  67. * into a new instance of your Generic Class.
  68. * Example:
  69. * class MyClass {
  70. * var $param = "somevalue";
  71. * function MyClass($somevar) {
  72. * $this->somevar = $somevar;
  73. * };
  74. * function getVar = function(){
  75. * return $this->somevar;
  76. * };
  77. * };
  78. *
  79. * $instance = new MyClass("example");
  80. * $encoded = FastJSON::encode($instance);
  81. * // {"param":"somevalue"}
  82. *
  83. * $decoded = FastJSON::decode($encoded);
  84. * // $decoded instanceof Object => true
  85. * // $decoded instanceof MyClass => false
  86. *
  87. * $decoded = FastJSON::convert($decoded, new MyClass("example"));
  88. * // $decoded instanceof Object => true
  89. * // $decoded instanceof MyClass => true
  90. *
  91. * $decoded->getVar(); // example
  92. *
  93. * ---------------------------------------
  94. *
  95. * @author Andrea Giammarchi
  96. * @site http://www.devpro.it/
  97. * @version 0.4 [fixed string convertion problems, add stdClass optional convertion instead of associative array (used by default)]
  98. * @requires anything
  99. * @compatibility PHP >= 4
  100. * @license
  101. * ---------------------------------------
  102. *
  103. * Copyright (c) 2006 - 2007 Andrea Giammarchi
  104. *
  105. * Permission is hereby granted, free of charge,
  106. * to any person obtaining a copy of this software and associated
  107. * documentation files (the "Software"),
  108. * to deal in the Software without restriction,
  109. * including without limitation the rights to use, copy, modify, merge,
  110. * publish, distribute, sublicense, and/or sell copies of the Software,
  111. * and to permit persons to whom the Software is furnished to do so,
  112. * subject to the following conditions:
  113. *
  114. * The above copyright notice and this permission notice shall be included
  115. * in all copies or substantial portions of the Software.
  116. *
  117. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  118. * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  119. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  120. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  121. * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  122. * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
  123. * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  124. * _______________________________________
  125. */
  126. class FastJSON {
  127. // public methods
  128. /**
  129. * public static method
  130. *
  131. * FastJSON::convert(params:* [, result:Instance]):*
  132. *
  133. * @param * String or Object
  134. * @param Instance optional new generic class instance if first
  135. * parameter is an object.
  136. * @return * time() value or new Instance with object parameters.
  137. *
  138. * @note please read Special FastJSON::convert method Informations
  139. */
  140. function convert($params, $result = null){
  141. switch(gettype($params)){
  142. case 'array':
  143. $tmp = array();
  144. foreach($params as $key => $value) {
  145. if(($value = FastJSON::encode($value)) !== '')
  146. array_push($tmp, FastJSON::encode(strval($key)).':'.$value);
  147. };
  148. $result = '{'.implode(',', $tmp).'}';
  149. break;
  150. case 'boolean':
  151. $result = $params ? 'true' : 'false';
  152. break;
  153. case 'double':
  154. case 'float':
  155. case 'integer':
  156. $result = $result !== null ? strftime('%Y-%m-%dT%H:%M:%S', $params) : strval($params);
  157. break;
  158. case 'NULL':
  159. $result = 'null';
  160. break;
  161. case 'string':
  162. $i = create_function('&$e, $p, $l', 'return intval(substr($e, $p, $l));');
  163. if(preg_match('/^[0-9]{4}\-[0-9]{2}\-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $params))
  164. $result = mktime($i($params, 11, 2), $i($params, 14, 2), $i($params, 17, 2), $i($params, 5, 2), $i($params, 9, 2), $i($params, 0, 4));
  165. break;
  166. case 'object':
  167. $tmp = array();
  168. if(is_object($result)) {
  169. foreach($params as $key => $value)
  170. $result->$key = $value;
  171. } else {
  172. $result = get_object_vars($params);
  173. foreach($result as $key => $value) {
  174. if(($value = FastJSON::encode($value)) !== '')
  175. array_push($tmp, FastJSON::encode($key).':'.$value);
  176. };
  177. $result = '{'.implode(',', $tmp).'}';
  178. }
  179. break;
  180. }
  181. return $result;
  182. }
  183. /**
  184. * public method
  185. *
  186. * FastJSON::decode(params:String[, useStdClass:Boolean]):*
  187. *
  188. * @param String valid JSON encoded string
  189. * @param Bolean uses stdClass instead of associative array if params contains objects (default false)
  190. * @return * converted variable or null
  191. * is params is not a JSON compatible string.
  192. * @note This method works in an optimist way. If JSON string is not valid
  193. * the code execution will die using exit.
  194. * This is probably not so good but JSON is often used combined with
  195. * XMLHttpRequest then I suppose that's better more protection than
  196. * just some WARNING.
  197. * With every kind of valid JSON string the old error_reporting level
  198. * and the old error_handler will be restored.
  199. *
  200. * @example
  201. * FastJSON::decode('{"param":"value"}'); // associative array
  202. * FastJSON::decode('{"param":"value"}', true); // stdClass
  203. * FastJSON::decode('["one",two,true,false,null,{},[1,2]]'); // array
  204. */
  205. function decode($encode, $stdClass = false){
  206. $pos = 0;
  207. $slen = is_string($encode) ? strlen($encode) : null;
  208. if($slen !== null) {
  209. $error = error_reporting(0);
  210. set_error_handler(array('FastJSON', '__exit'));
  211. $result = FastJSON::__decode($encode, $pos, $slen, $stdClass);
  212. error_reporting($error);
  213. restore_error_handler();
  214. }
  215. else
  216. $result = null;
  217. return $result;
  218. }
  219. /**
  220. * public method
  221. *
  222. * FastJSON::encode(params:*):String
  223. *
  224. * @param * Array, Boolean, Float, Int, Object, String or NULL variable.
  225. * @return String JSON genric object rappresentation
  226. * or empty string if param is not compatible.
  227. *
  228. * @example
  229. * FastJSON::encode(array(1,"two")); // '[1,"two"]'
  230. *
  231. * $obj = new MyClass();
  232. * obj->param = "value";
  233. * obj->param2 = "value2";
  234. * FastJSON::encode(obj); // '{"param":"value","param2":"value2"}'
  235. */
  236. function encode($decode){
  237. $result = '';
  238. switch(gettype($decode)){
  239. case 'array':
  240. if(!count($decode) || array_keys($decode) === range(0, count($decode) - 1)) {
  241. $keys = array();
  242. foreach($decode as $value) {
  243. if(($value = FastJSON::encode($value)) !== '')
  244. array_push($keys, $value);
  245. }
  246. $result = '['.implode(',', $keys).']';
  247. }
  248. else
  249. $result = FastJSON::convert($decode);
  250. break;
  251. case 'string':
  252. $replacement = FastJSON::__getStaticReplacement();
  253. $result = '"'.str_replace($replacement['find'], $replacement['replace'], $decode).'"';
  254. break;
  255. default:
  256. if(!is_callable($decode))
  257. $result = FastJSON::convert($decode);
  258. break;
  259. }
  260. return $result;
  261. }
  262. // private methods, uncommented, sorry
  263. function __getStaticReplacement(){
  264. static $replacement = array('find'=>array(), 'replace'=>array());
  265. if($replacement['find'] == array()) {
  266. foreach(array_merge(range(0, 7), array(11), range(14, 31)) as $v) {
  267. $replacement['find'][] = chr($v);
  268. $replacement['replace'][] = "\\u00".sprintf("%02x", $v);
  269. }
  270. $replacement['find'] = array_merge(array(chr(0x5c), chr(0x2F), chr(0x22), chr(0x0d), chr(0x0c), chr(0x0a), chr(0x09), chr(0x08)), $replacement['find']);
  271. $replacement['replace'] = array_merge(array('\\\\', '\\/', '\\"', '\r', '\f', '\n', '\t', '\b'), $replacement['replace']);
  272. }
  273. return $replacement;
  274. }
  275. function __decode(&$encode, &$pos, &$slen, &$stdClass){
  276. switch($encode{$pos}) {
  277. case 't':
  278. $result = true;
  279. $pos += 4;
  280. break;
  281. case 'f':
  282. $result = false;
  283. $pos += 5;
  284. break;
  285. case 'n':
  286. $result = null;
  287. $pos += 4;
  288. break;
  289. case '[':
  290. $result = array();
  291. ++$pos;
  292. while($encode{$pos} !== ']') {
  293. array_push($result, FastJSON::__decode($encode, $pos, $slen, $stdClass));
  294. if($encode{$pos} === ',')
  295. ++$pos;
  296. }
  297. ++$pos;
  298. break;
  299. case '{':
  300. $result = $stdClass ? new stdClass : array();
  301. ++$pos;
  302. while($encode{$pos} !== '}') {
  303. $tmp = FastJSON::__decodeString($encode, $pos);
  304. ++$pos;
  305. if($stdClass)
  306. $result->$tmp = FastJSON::__decode($encode, $pos, $slen, $stdClass);
  307. else
  308. $result[$tmp] = FastJSON::__decode($encode, $pos, $slen, $stdClass);
  309. if($encode{$pos} === ',')
  310. ++$pos;
  311. }
  312. ++$pos;
  313. break;
  314. case '"':
  315. switch($encode{++$pos}) {
  316. case '"':
  317. $result = "";
  318. break;
  319. default:
  320. $result = FastJSON::__decodeString($encode, $pos);
  321. break;
  322. }
  323. ++$pos;
  324. break;
  325. default:
  326. $tmp = '';
  327. preg_replace('/^(\-)?([0-9]+)(\.[0-9]+)?([eE]\+[0-9]+)?/e', '$tmp = "\\1\\2\\3\\4"', substr($encode, $pos));
  328. if($tmp !== '') {
  329. $pos += strlen($tmp);
  330. $nint = intval($tmp);
  331. $nfloat = floatval($tmp);
  332. $result = $nfloat == $nint ? $nint : $nfloat;
  333. }
  334. break;
  335. }
  336. return $result;
  337. }
  338. function __decodeString(&$encode, &$pos) {
  339. $replacement = FastJSON::__getStaticReplacement();
  340. $endString = FastJSON::__endString($encode, $pos, $pos);
  341. $result = str_replace($replacement['replace'], $replacement['find'], substr($encode, $pos, $endString));
  342. $pos += $endString;
  343. return $result;
  344. }
  345. function __endString(&$encode, $position, &$pos) {
  346. do {
  347. $position = strpos($encode, '"', $position + 1);
  348. }while($position !== false && FastJSON::__slashedChar($encode, $position - 1));
  349. if($position === false)
  350. trigger_error('', E_USER_WARNING);
  351. return $position - $pos;
  352. }
  353. function __exit($str, $a, $b) {
  354. exit($a.'FATAL: FastJSON decode method failure [malicious or incorrect JSON string]');
  355. }
  356. function __slashedChar(&$encode, $position) {
  357. $pos = 0;
  358. while($encode{$position--} === '\\')
  359. $pos++;
  360. return $pos % 2;
  361. }
  362. }
  363. ?>