Tools.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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 (class_exists('CURLFile')) {
  103. return new \CURLFile($filename, $mimetype, $postname);
  104. } else {
  105. return "@{$filename};filename={$postname};type={$mimetype}";
  106. }
  107. }
  108. return $filename;
  109. }
  110. /**
  111. * 数组转XML内容
  112. * @param array $data
  113. * @return string
  114. */
  115. public static function arr2xml($data)
  116. {
  117. return "<xml>" . self::_arr2xml($data) . "</xml>";
  118. }
  119. /**
  120. * XML内容生成
  121. * @param array $data 数据
  122. * @param string $content
  123. * @return string
  124. */
  125. private static function _arr2xml($data, $content = '')
  126. {
  127. foreach ($data as $key => $val) {
  128. is_numeric($key) && $key = 'item';
  129. $content .= "<{$key}>";
  130. if (is_array($val) || is_object($val)) {
  131. $content .= self::_arr2xml($val);
  132. } elseif (is_string($val)) {
  133. $content .= '<![CDATA[' . preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/", '', $val) . ']]>';
  134. } else {
  135. $content .= $val;
  136. }
  137. $content .= "</{$key}>";
  138. }
  139. return $content;
  140. }
  141. /**
  142. * 解析XML内容到数组
  143. * @param string $xml
  144. * @return array
  145. */
  146. public static function xml2arr($xml)
  147. {
  148. $entity = libxml_disable_entity_loader(true);
  149. $data = (array)simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
  150. libxml_disable_entity_loader($entity);
  151. return json_decode(json_encode($data), true);
  152. }
  153. /**
  154. * 解析XML文本内容
  155. * @param string $xml
  156. * @return boolean|mixed
  157. */
  158. public static function xml3arr($xml)
  159. {
  160. $state = xml_parse($parser = xml_parser_create(), $xml, true);
  161. return xml_parser_free($parser) && $state ? self::xml2arr($xml) : false;
  162. }
  163. /**
  164. * 数组转xml内容
  165. * @param array $data
  166. * @return null|string
  167. */
  168. public static function arr2json($data)
  169. {
  170. $json = json_encode($data, JSON_UNESCAPED_UNICODE);
  171. return $json === '[]' ? '{}' : $json;
  172. }
  173. /**
  174. * 数组对象Emoji编译处理
  175. * @param array $data
  176. * @return array
  177. */
  178. public static function buildEnEmojiData(array $data)
  179. {
  180. foreach ($data as $key => $value) {
  181. if (is_array($value)) {
  182. $data[$key] = self::buildEnEmojiData($value);
  183. } elseif (is_string($value)) {
  184. $data[$key] = self::emojiEncode($value);
  185. } else {
  186. $data[$key] = $value;
  187. }
  188. }
  189. return $data;
  190. }
  191. /**
  192. * 数组对象Emoji反解析处理
  193. * @param array $data
  194. * @return array
  195. */
  196. public static function buildDeEmojiData(array $data)
  197. {
  198. foreach ($data as $key => $value) {
  199. if (is_array($value)) {
  200. $data[$key] = self::buildDeEmojiData($value);
  201. } elseif (is_string($value)) {
  202. $data[$key] = self::emojiDecode($value);
  203. } else {
  204. $data[$key] = $value;
  205. }
  206. }
  207. return $data;
  208. }
  209. /**
  210. * Emoji原形转换为String
  211. * @param string $content
  212. * @return string
  213. */
  214. public static function emojiEncode($content)
  215. {
  216. return json_decode(preg_replace_callback("/(\\\u[ed][0-9a-f]{3})/i", function ($string) {
  217. return addslashes($string[0]);
  218. }, json_encode($content)));
  219. }
  220. /**
  221. * Emoji字符串转换为原形
  222. * @param string $content
  223. * @return string
  224. */
  225. public static function emojiDecode($content)
  226. {
  227. return json_decode(preg_replace_callback('/\\\\\\\\/i', function () {
  228. return '\\';
  229. }, json_encode($content)));
  230. }
  231. /**
  232. * 解析JSON内容到数组
  233. * @param string $json
  234. * @return array
  235. * @throws InvalidResponseException
  236. */
  237. public static function json2arr($json)
  238. {
  239. $result = json_decode($json, true);
  240. if (empty($result)) {
  241. throw new InvalidResponseException('invalid response.', '0');
  242. }
  243. if (!empty($result['errcode'])) {
  244. throw new InvalidResponseException($result['errmsg'], $result['errcode'], $result);
  245. }
  246. return $result;
  247. }
  248. /**
  249. * 以get访问模拟访问
  250. * @param string $url 访问URL
  251. * @param array $query GET数
  252. * @param array $options
  253. * @return boolean|string
  254. * @throws LocalCacheException
  255. */
  256. public static function get($url, $query = [], $options = [])
  257. {
  258. $options['query'] = $query;
  259. return self::doRequest('get', $url, $options);
  260. }
  261. /**
  262. * 以post访问模拟访问
  263. * @param string $url 访问URL
  264. * @param array $data POST数据
  265. * @param array $options
  266. * @return boolean|string
  267. * @throws LocalCacheException
  268. */
  269. public static function post($url, $data = [], $options = [])
  270. {
  271. $options['data'] = $data;
  272. return self::doRequest('post', $url, $options);
  273. }
  274. /**
  275. * CURL模拟网络请求
  276. * @param string $method 请求方法
  277. * @param string $url 请求方法
  278. * @param array $options 请求参数[headers,data,ssl_cer,ssl_key]
  279. * @return boolean|string
  280. * @throws LocalCacheException
  281. */
  282. public static function doRequest($method, $url, $options = [])
  283. {
  284. $curl = curl_init();
  285. // GET参数设置
  286. if (!empty($options['query'])) {
  287. $url .= (stripos($url, '?') !== false ? '&' : '?') . http_build_query($options['query']);
  288. }
  289. // CURL头信息设置
  290. if (!empty($options['headers'])) {
  291. curl_setopt($curl, CURLOPT_HTTPHEADER, $options['headers']);
  292. }
  293. // POST数据设置
  294. if (strtolower($method) === 'post') {
  295. curl_setopt($curl, CURLOPT_POST, true);
  296. curl_setopt($curl, CURLOPT_POSTFIELDS, self::_buildHttpData($options['data']));
  297. }
  298. // 证书文件设置
  299. if (!empty($options['ssl_cer'])) if (file_exists($options['ssl_cer'])) {
  300. curl_setopt($curl, CURLOPT_SSLCERTTYPE, 'PEM');
  301. curl_setopt($curl, CURLOPT_SSLCERT, $options['ssl_cer']);
  302. } else throw new InvalidArgumentException("Certificate files that do not exist. --- [ssl_cer]");
  303. // 证书文件设置
  304. if (!empty($options['ssl_key'])) if (file_exists($options['ssl_key'])) {
  305. curl_setopt($curl, CURLOPT_SSLKEYTYPE, 'PEM');
  306. curl_setopt($curl, CURLOPT_SSLKEY, $options['ssl_key']);
  307. } else throw new InvalidArgumentException("Certificate files that do not exist. --- [ssl_key]");
  308. curl_setopt($curl, CURLOPT_URL, $url);
  309. curl_setopt($curl, CURLOPT_TIMEOUT, 60);
  310. curl_setopt($curl, CURLOPT_HEADER, false);
  311. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  312. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  313. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  314. list($content) = [curl_exec($curl), curl_close($curl)];
  315. // 清理 CURL 缓存文件
  316. if (!empty(self::$cache_curl)) foreach (self::$cache_curl as $key => $file) {
  317. Tools::delCache($file);
  318. unset(self::$cache_curl[$key]);
  319. }
  320. return $content;
  321. }
  322. /**
  323. * POST数据过滤处理
  324. * @param array $data 需要处理的数据
  325. * @param boolean $build 是否编译数据
  326. * @return array|string
  327. * @throws \WeChat\Exceptions\LocalCacheException
  328. */
  329. private static function _buildHttpData($data, $build = true)
  330. {
  331. if (!is_array($data)) return $data;
  332. foreach ($data as $key => $value) if (is_object($value) && $value instanceof \CURLFile) {
  333. $build = false;
  334. } elseif (is_object($value) && isset($value->datatype) && $value->datatype === 'MY_CURL_FILE') {
  335. $build = false;
  336. $mycurl = new MyCurlFile((array)$value);
  337. $data[$key] = $mycurl->get();
  338. array_push(self::$cache_curl, $mycurl->tempname);
  339. } elseif (is_array($value) && isset($value['datatype']) && $value['datatype'] === 'MY_CURL_FILE') {
  340. $build = false;
  341. $mycurl = new MyCurlFile($value);
  342. $data[$key] = $mycurl->get();
  343. array_push(self::$cache_curl, $mycurl->tempname);
  344. } elseif (is_string($value) && class_exists('CURLFile', false) && stripos($value, '@') === 0) {
  345. if (($filename = realpath(trim($value, '@'))) && file_exists($filename)) {
  346. $build = false;
  347. $data[$key] = self::createCurlFile($filename);
  348. }
  349. }
  350. return $build ? http_build_query($data) : $data;
  351. }
  352. /**
  353. * 写入文件
  354. * @param string $name 文件名称
  355. * @param string $content 文件内容
  356. * @return string
  357. * @throws LocalCacheException
  358. */
  359. public static function pushFile($name, $content)
  360. {
  361. if (is_callable(self::$cache_callable['put'])) {
  362. return call_user_func_array(self::$cache_callable['put'], func_get_args());
  363. }
  364. $file = self::_getCacheName($name);
  365. if (!file_put_contents($file, $content)) {
  366. throw new LocalCacheException('local file write error.', '0');
  367. }
  368. return $file;
  369. }
  370. /**
  371. * 缓存配置与存储
  372. * @param string $name 缓存名称
  373. * @param string $value 缓存内容
  374. * @param int $expired 缓存时间(0表示永久缓存)
  375. * @return string
  376. * @throws LocalCacheException
  377. */
  378. public static function setCache($name, $value = '', $expired = 3600)
  379. {
  380. if (is_callable(self::$cache_callable['set'])) {
  381. return call_user_func_array(self::$cache_callable['set'], func_get_args());
  382. }
  383. $file = self::_getCacheName($name);
  384. $data = ['name' => $name, 'value' => $value, 'expired' => time() + intval($expired)];
  385. if (!file_put_contents($file, serialize($data))) {
  386. throw new LocalCacheException('local cache error.', '0');
  387. }
  388. return $file;
  389. }
  390. /**
  391. * 获取缓存内容
  392. * @param string $name 缓存名称
  393. * @return null|mixed
  394. */
  395. public static function getCache($name)
  396. {
  397. if (is_callable(self::$cache_callable['get'])) {
  398. return call_user_func_array(self::$cache_callable['get'], func_get_args());
  399. }
  400. $file = self::_getCacheName($name);
  401. if (file_exists($file) && is_file($file) && ($content = file_get_contents($file))) {
  402. $data = unserialize($content);
  403. if (isset($data['expired']) && (intval($data['expired']) === 0 || intval($data['expired']) >= time())) {
  404. return $data['value'];
  405. }
  406. self::delCache($name);
  407. }
  408. return null;
  409. }
  410. /**
  411. * 移除缓存文件
  412. * @param string $name 缓存名称
  413. * @return boolean
  414. */
  415. public static function delCache($name)
  416. {
  417. if (is_callable(self::$cache_callable['del'])) {
  418. return call_user_func_array(self::$cache_callable['del'], func_get_args());
  419. }
  420. $file = self::_getCacheName($name);
  421. return file_exists($file) ? unlink($file) : true;
  422. }
  423. /**
  424. * 应用缓存目录
  425. * @param string $name
  426. * @return string
  427. */
  428. private static function _getCacheName($name)
  429. {
  430. if (empty(self::$cache_path)) {
  431. self::$cache_path = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'Cache' . DIRECTORY_SEPARATOR;
  432. }
  433. self::$cache_path = rtrim(self::$cache_path, '/\\') . DIRECTORY_SEPARATOR;
  434. file_exists(self::$cache_path) || mkdir(self::$cache_path, 0755, true);
  435. return self::$cache_path . $name;
  436. }
  437. }