Tools.php 15 KB

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