Tools.php 16 KB

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