Tools.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | WeChatDeveloper
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2014~2020 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://think.ctolog.com
  8. // +----------------------------------------------------------------------
  9. // | 开源协议 ( https://mit-license.org )
  10. // +----------------------------------------------------------------------
  11. // | github开源项目:https://github.com/zoujingli/WeChatDeveloper
  12. // +----------------------------------------------------------------------
  13. namespace WeChat\Contracts;
  14. use WeChat\Exceptions\InvalidArgumentException;
  15. use WeChat\Exceptions\InvalidResponseException;
  16. use WeChat\Exceptions\LocalCacheException;
  17. /**
  18. * 网络请求支持
  19. * Class Tools
  20. * @package WeChat\Contracts
  21. */
  22. class Tools
  23. {
  24. /**
  25. * 缓存路径
  26. * @var null
  27. */
  28. public static $cache_path = null;
  29. /**
  30. * 缓存写入操作
  31. * @var array
  32. */
  33. public static $cache_callable = [
  34. 'set' => null, // 写入缓存
  35. 'get' => null, // 获取缓存
  36. 'del' => null, // 删除缓存
  37. 'put' => null, // 写入文件
  38. ];
  39. /**
  40. * 网络缓存
  41. * @var array
  42. */
  43. private static $cache_curl = [];
  44. /**
  45. * 产生随机字符串
  46. * @param int $length 指定字符长度
  47. * @param string $str 字符串前缀
  48. * @return string
  49. */
  50. public static function createNoncestr($length = 32, $str = "")
  51. {
  52. $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
  53. for ($i = 0; $i < $length; $i++) {
  54. $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
  55. }
  56. return $str;
  57. }
  58. /**
  59. * 根据文件后缀获取文件类型
  60. * @param string|array $ext 文件后缀
  61. * @param array $mine 文件后缀MINE信息
  62. * @return string
  63. * @throws LocalCacheException
  64. */
  65. public static function getExtMine($ext, $mine = [])
  66. {
  67. $mines = self::getMines();
  68. foreach (is_string($ext) ? explode(',', $ext) : $ext as $e) {
  69. $mine[] = isset($mines[strtolower($e)]) ? $mines[strtolower($e)] : 'application/octet-stream';
  70. }
  71. return join(',', array_unique($mine));
  72. }
  73. /**
  74. * 获取所有文件扩展的类型
  75. * @return array
  76. * @throws LocalCacheException
  77. */
  78. private static function getMines()
  79. {
  80. $mines = self::getCache('all_ext_mine');
  81. if (empty($mines)) {
  82. $content = file_get_contents('http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types');
  83. preg_match_all('#^([^\s]{2,}?)\s+(.+?)$#ism', $content, $matches, PREG_SET_ORDER);
  84. foreach ($matches as $match) foreach (explode(" ", $match[2]) as $ext) $mines[$ext] = $match[1];
  85. self::setCache('all_ext_mine', $mines);
  86. }
  87. return $mines;
  88. }
  89. /**
  90. * 创建CURL文件对象
  91. * @param $filename
  92. * @param string $mimetype
  93. * @param string $postname
  94. * @return \CURLFile|string
  95. * @throws LocalCacheException
  96. */
  97. public static function createCurlFile($filename, $mimetype = null, $postname = null)
  98. {
  99. if (is_string($filename) && file_exists($filename)) {
  100. if (is_null($postname)) $postname = basename($filename);
  101. if (is_null($mimetype)) $mimetype = self::getExtMine(pathinfo($filename, 4));
  102. if (function_exists('curl_file_create')) {
  103. return curl_file_create($filename, $mimetype, $postname);
  104. }
  105. return "@{$filename};filename={$postname};type={$mimetype}";
  106. }
  107. return $filename;
  108. }
  109. /**
  110. * 数组转XML内容
  111. * @param array $data
  112. * @return string
  113. */
  114. public static function arr2xml($data)
  115. {
  116. return "<xml>" . self::_arr2xml($data) . "</xml>";
  117. }
  118. /**
  119. * XML内容生成
  120. * @param array $data 数据
  121. * @param string $content
  122. * @return string
  123. */
  124. private static function _arr2xml($data, $content = '')
  125. {
  126. foreach ($data as $key => $val) {
  127. is_numeric($key) && $key = 'item';
  128. $content .= "<{$key}>";
  129. if (is_array($val) || is_object($val)) {
  130. $content .= self::_arr2xml($val);
  131. } elseif (is_string($val)) {
  132. $content .= '<![CDATA[' . preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/", '', $val) . ']]>';
  133. } else {
  134. $content .= $val;
  135. }
  136. $content .= "</{$key}>";
  137. }
  138. return $content;
  139. }
  140. /**
  141. * 解析XML内容到数组
  142. * @param string $xml
  143. * @return array
  144. */
  145. public static function xml2arr($xml)
  146. {
  147. $entity = libxml_disable_entity_loader(true);
  148. $data = (array)simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
  149. libxml_disable_entity_loader($entity);
  150. return json_decode(json_encode($data), true);
  151. }
  152. /**
  153. * 解析XML文本内容
  154. * @param string $xml
  155. * @return boolean|mixed
  156. */
  157. public static function xml3arr($xml)
  158. {
  159. $state = xml_parse($parser = xml_parser_create(), $xml, true);
  160. return xml_parser_free($parser) && $state ? self::xml2arr($xml) : false;
  161. }
  162. /**
  163. * 数组转xml内容
  164. * @param array $data
  165. * @return null|string
  166. */
  167. public static function arr2json($data)
  168. {
  169. $json = json_encode(self::buildEnEmojiData($data), JSON_UNESCAPED_UNICODE);
  170. return $json === '[]' ? '{}' : $json;
  171. }
  172. /**
  173. * 数组对象Emoji编译处理
  174. * @param array $data
  175. * @return array
  176. */
  177. public static function buildEnEmojiData(array $data)
  178. {
  179. foreach ($data as $key => $value) {
  180. if (is_array($value)) {
  181. $data[$key] = self::buildEnEmojiData($value);
  182. } elseif (is_string($value)) {
  183. $data[$key] = self::emojiEncode($value);
  184. } else {
  185. $data[$key] = $value;
  186. }
  187. }
  188. return $data;
  189. }
  190. /**
  191. * 数组对象Emoji反解析处理
  192. * @param array $data
  193. * @return array
  194. */
  195. public static function buildDeEmojiData(array $data)
  196. {
  197. foreach ($data as $key => $value) {
  198. if (is_array($value)) {
  199. $data[$key] = self::buildDeEmojiData($value);
  200. } elseif (is_string($value)) {
  201. $data[$key] = self::emojiDecode($value);
  202. } else {
  203. $data[$key] = $value;
  204. }
  205. }
  206. return $data;
  207. }
  208. /**
  209. * Emoji原形转换为String
  210. * @param string $content
  211. * @return string
  212. */
  213. public static function emojiEncode($content)
  214. {
  215. return json_decode(preg_replace_callback("/(\\\u[ed][0-9a-f]{3})/i", function ($string) {
  216. return addslashes($string[0]);
  217. }, json_encode($content)));
  218. }
  219. /**
  220. * Emoji字符串转换为原形
  221. * @param string $content
  222. * @return string
  223. */
  224. public static function emojiDecode($content)
  225. {
  226. return json_decode(preg_replace_callback('/\\\\\\\\/i', function () {
  227. return '\\';
  228. }, json_encode($content)));
  229. }
  230. /**
  231. * 解析JSON内容到数组
  232. * @param string $json
  233. * @return array
  234. * @throws InvalidResponseException
  235. */
  236. public static function json2arr($json)
  237. {
  238. $result = json_decode($json, true);
  239. if (empty($result)) {
  240. throw new InvalidResponseException('invalid response.', '0');
  241. }
  242. if (!empty($result['errcode'])) {
  243. throw new InvalidResponseException($result['errmsg'], $result['errcode'], $result);
  244. }
  245. return $result;
  246. }
  247. /**
  248. * 以get访问模拟访问
  249. * @param string $url 访问URL
  250. * @param array $query GET数
  251. * @param array $options
  252. * @return boolean|string
  253. * @throws LocalCacheException
  254. */
  255. public static function get($url, $query = [], $options = [])
  256. {
  257. $options['query'] = $query;
  258. return self::doRequest('get', $url, $options);
  259. }
  260. /**
  261. * 以post访问模拟访问
  262. * @param string $url 访问URL
  263. * @param array $data POST数据
  264. * @param array $options
  265. * @return boolean|string
  266. * @throws LocalCacheException
  267. */
  268. public static function post($url, $data = [], $options = [])
  269. {
  270. $options['data'] = $data;
  271. return self::doRequest('post', $url, $options);
  272. }
  273. /**
  274. * CURL模拟网络请求
  275. * @param string $method 请求方法
  276. * @param string $url 请求方法
  277. * @param array $options 请求参数[headers,data,ssl_cer,ssl_key]
  278. * @return boolean|string
  279. * @throws LocalCacheException
  280. */
  281. public static function doRequest($method, $url, $options = [])
  282. {
  283. $curl = curl_init();
  284. // GET参数设置
  285. if (!empty($options['query'])) {
  286. $url .= (stripos($url, '?') !== false ? '&' : '?') . http_build_query($options['query']);
  287. }
  288. // CURL头信息设置
  289. if (!empty($options['headers'])) {
  290. curl_setopt($curl, CURLOPT_HTTPHEADER, $options['headers']);
  291. }
  292. // POST数据设置
  293. if (strtolower($method) === 'post') {
  294. curl_setopt($curl, CURLOPT_POST, true);
  295. curl_setopt($curl, CURLOPT_POSTFIELDS, self::_buildHttpData($options['data']));
  296. }
  297. // 证书文件设置
  298. if (!empty($options['ssl_cer'])) if (file_exists($options['ssl_cer'])) {
  299. curl_setopt($curl, CURLOPT_SSLCERTTYPE, 'PEM');
  300. curl_setopt($curl, CURLOPT_SSLCERT, $options['ssl_cer']);
  301. } else throw new InvalidArgumentException("Certificate files that do not exist. --- [ssl_cer]");
  302. // 证书文件设置
  303. if (!empty($options['ssl_key'])) if (file_exists($options['ssl_key'])) {
  304. curl_setopt($curl, CURLOPT_SSLKEYTYPE, 'PEM');
  305. curl_setopt($curl, CURLOPT_SSLKEY, $options['ssl_key']);
  306. } else throw new InvalidArgumentException("Certificate files that do not exist. --- [ssl_key]");
  307. curl_setopt($curl, CURLOPT_URL, $url);
  308. curl_setopt($curl, CURLOPT_TIMEOUT, 60);
  309. curl_setopt($curl, CURLOPT_HEADER, false);
  310. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  311. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  312. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  313. list($content) = [curl_exec($curl), curl_close($curl)];
  314. // 清理 CURL 缓存文件
  315. if (!empty(self::$cache_curl)) foreach (self::$cache_curl as $key => $file) {
  316. Tools::delCache($file);
  317. unset(self::$cache_curl[$key]);
  318. }
  319. return $content;
  320. }
  321. /**
  322. * POST数据过滤处理
  323. * @param array $data 需要处理的数据
  324. * @param boolean $build 是否编译数据
  325. * @return array|string
  326. * @throws \WeChat\Exceptions\LocalCacheException
  327. */
  328. private static function _buildHttpData($data, $build = true)
  329. {
  330. if (!is_array($data)) return $data;
  331. foreach ($data as $key => $value) if (is_object($value) && $value instanceof \CURLFile) {
  332. $build = false;
  333. } elseif (is_object($value) && isset($value->datatype) && $value->datatype === 'MY_CURL_FILE') {
  334. $build = false;
  335. $mycurl = new MyCurlFile((array)$value);
  336. $data[$key] = $mycurl->get();
  337. array_push(self::$cache_curl, $mycurl->tempname);
  338. } elseif (is_array($value) && isset($value['datatype']) && $value['datatype'] === 'MY_CURL_FILE') {
  339. $build = false;
  340. $mycurl = new MyCurlFile($value);
  341. $data[$key] = $mycurl->get();
  342. array_push(self::$cache_curl, $mycurl->tempname);
  343. } elseif (is_string($value) && class_exists('CURLFile', false) && stripos($value, '@') === 0) {
  344. if (($filename = realpath(trim($value, '@'))) && file_exists($filename)) {
  345. $build = false;
  346. $data[$key] = self::createCurlFile($filename);
  347. }
  348. }
  349. return $build ? http_build_query($data) : $data;
  350. }
  351. /**
  352. * 写入文件
  353. * @param string $name 文件名称
  354. * @param string $content 文件内容
  355. * @return string
  356. * @throws LocalCacheException
  357. */
  358. public static function pushFile($name, $content)
  359. {
  360. if (is_callable(self::$cache_callable['put'])) {
  361. return call_user_func_array(self::$cache_callable['put'], func_get_args());
  362. }
  363. $file = self::_getCacheName($name);
  364. if (!file_put_contents($file, $content)) {
  365. throw new LocalCacheException('local file write error.', '0');
  366. }
  367. return $file;
  368. }
  369. /**
  370. * 缓存配置与存储
  371. * @param string $name 缓存名称
  372. * @param string $value 缓存内容
  373. * @param int $expired 缓存时间(0表示永久缓存)
  374. * @return string
  375. * @throws LocalCacheException
  376. */
  377. public static function setCache($name, $value = '', $expired = 3600)
  378. {
  379. if (is_callable(self::$cache_callable['set'])) {
  380. return call_user_func_array(self::$cache_callable['set'], func_get_args());
  381. }
  382. $file = self::_getCacheName($name);
  383. $data = ['name' => $name, 'value' => $value, 'expired' => time() + intval($expired)];
  384. if (!file_put_contents($file, serialize($data))) {
  385. throw new LocalCacheException('local cache error.', '0');
  386. }
  387. return $file;
  388. }
  389. /**
  390. * 获取缓存内容
  391. * @param string $name 缓存名称
  392. * @return null|mixed
  393. */
  394. public static function getCache($name)
  395. {
  396. if (is_callable(self::$cache_callable['get'])) {
  397. return call_user_func_array(self::$cache_callable['get'], func_get_args());
  398. }
  399. $file = self::_getCacheName($name);
  400. if (file_exists($file) && ($content = file_get_contents($file))) {
  401. $data = unserialize($content);
  402. if (isset($data['expired']) && (intval($data['expired']) === 0 || intval($data['expired']) >= time())) {
  403. return $data['value'];
  404. }
  405. self::delCache($name);
  406. }
  407. return null;
  408. }
  409. /**
  410. * 移除缓存文件
  411. * @param string $name 缓存名称
  412. * @return boolean
  413. */
  414. public static function delCache($name)
  415. {
  416. if (is_callable(self::$cache_callable['del'])) {
  417. return call_user_func_array(self::$cache_callable['del'], func_get_args());
  418. }
  419. $file = self::_getCacheName($name);
  420. return file_exists($file) ? unlink($file) : true;
  421. }
  422. /**
  423. * 应用缓存目录
  424. * @param string $name
  425. * @return string
  426. */
  427. private static function _getCacheName($name)
  428. {
  429. if (empty(self::$cache_path)) {
  430. self::$cache_path = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'Cache' . DIRECTORY_SEPARATOR;
  431. }
  432. self::$cache_path = rtrim(self::$cache_path, '/\\') . DIRECTORY_SEPARATOR;
  433. file_exists(self::$cache_path) || mkdir(self::$cache_path, 0755, true);
  434. return self::$cache_path . $name;
  435. }
  436. }