Client.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. <?php
  2. /**
  3. * +----------------------------------------------------------------------
  4. * | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  5. * +----------------------------------------------------------------------
  6. * | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved.
  7. * +----------------------------------------------------------------------
  8. * | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  9. * +----------------------------------------------------------------------
  10. * | Author: CRMEB Team <admin@crmeb.com>
  11. * +----------------------------------------------------------------------
  12. */
  13. namespace crmeb\services\upload\extend\cos;
  14. use crmeb\exceptions\UploadException;
  15. use crmeb\services\upload\XML;
  16. /**
  17. * Class Client
  18. * @author 等风来
  19. * @email 136327134@qq.com
  20. * @date 2022/9/29
  21. * @package crmeb\services\upload\extend\cos
  22. */
  23. class Client
  24. {
  25. /**
  26. * @var string
  27. */
  28. protected $accessKey;
  29. /**
  30. * @var string
  31. */
  32. protected $secretKey;
  33. /**
  34. * @var string
  35. */
  36. protected $appid;
  37. /**
  38. * @var mixed|string
  39. */
  40. protected $bucket;
  41. /**
  42. * @var mixed|string
  43. */
  44. protected $region;
  45. /**
  46. * @var mixed|string
  47. */
  48. protected $uploadUrl;
  49. /**
  50. * @var string
  51. */
  52. protected $action = '';
  53. /**
  54. * @var array
  55. */
  56. protected $response = ['content' => null, 'code' => 200, 'header' => []];
  57. /**
  58. * @var array
  59. */
  60. protected $request = ['header' => [], 'body' => [], 'host' => ''];
  61. /**
  62. * @var string
  63. */
  64. protected $cosacl = 'public-read';
  65. /**
  66. * Client constructor.
  67. * @param array $config
  68. */
  69. public function __construct(array $config)
  70. {
  71. $this->accessKey = $config['accessKey'] ?? '';
  72. $this->secretKey = $config['secretKey'] ?? '';
  73. $this->appid = $config['appid'] ?? '';
  74. $this->bucket = $config['bucket'] ?? '';
  75. $this->region = $config['region'] ?? 'ap-chengdu';
  76. $this->uploadUrl = $config['uploadUrl'] ?? '';
  77. }
  78. /**
  79. * 获取实际请求
  80. * @return array
  81. * @author 等风来
  82. * @email 136327134@qq.com
  83. * @date 2022/10/17
  84. */
  85. public function getResponse()
  86. {
  87. $response = $this->response;
  88. $this->response = ['content' => null, 'http_code' => 200, 'header' => []];
  89. return $response;
  90. }
  91. /**
  92. * @return array
  93. * @author 等风来
  94. * @email 136327134@qq.com
  95. * @date 2022/10/17
  96. */
  97. public function getRequest()
  98. {
  99. $request = $this->request;
  100. $this->request = ['header' => [], 'body' => [], 'host' => ''];
  101. return $request;
  102. }
  103. /**
  104. * 拼接请求地址
  105. * @return string
  106. * @author 等风来
  107. * @email 136327134@qq.com
  108. * @date 2022/9/29
  109. */
  110. protected function makeUpUrl()
  111. {
  112. return $this->bucket . '.cos.' . $this->region . '.myqcloud.com';
  113. }
  114. /**
  115. * @return bool
  116. * @author 等风来
  117. * @email 136327134@qq.com
  118. * @date 2022/9/29
  119. */
  120. protected function ssl()
  121. {
  122. return strstr($this->uploadUrl, 'https://') !== false;
  123. }
  124. /**
  125. * 检查参数
  126. * @author 等风来
  127. * @email 136327134@qq.com
  128. * @date 2022/9/29
  129. */
  130. protected function checkOptions()
  131. {
  132. if (!$this->bucket) {
  133. throw new UploadException('请传入桶名');
  134. }
  135. if (!$this->region) {
  136. throw new UploadException('请传入所属地域');
  137. }
  138. if (!$this->accessKey) {
  139. throw new UploadException('请传入SecretId');
  140. }
  141. if (!$this->secretKey) {
  142. throw new UploadException('请传入SecretKey');
  143. }
  144. }
  145. /**
  146. * 上传文件
  147. * @param string $key
  148. * @param $body
  149. * @return string[]
  150. * @author 等风来
  151. * @email 136327134@qq.com
  152. * @date 2022/9/29
  153. */
  154. public function putObject(string $key, $body)
  155. {
  156. $this->checkOptions();
  157. $url = $this->makeUpUrl();
  158. $header = [
  159. 'Content-Type' => 'image/jpeg',
  160. 'x-cos-acl' => $this->cosacl,
  161. 'Content-MD5' => base64_encode(md5($body, true)),
  162. 'Host' => $url
  163. ];
  164. $imageUrl = ($this->ssl() ? 'https://' : 'http://') . $url . '/' . $key;
  165. $res = $this->request($imageUrl, 'PUT', ['body' => $body], $header);
  166. if ($res && !empty($res['Message'])) {
  167. throw new UploadException($res['Message']);
  168. }
  169. return [
  170. 'name' => $key,
  171. 'path' => $imageUrl
  172. ];
  173. }
  174. /**
  175. * 删除文件
  176. * @param string $bucket
  177. * @param string $key
  178. * @return array|false
  179. * @author 等风来
  180. * @email 136327134@qq.com
  181. * @date 2022/10/19
  182. */
  183. public function deleteObject(string $bucket, string $key)
  184. {
  185. $url = $this->getRequestHost($bucket);
  186. $header = [
  187. 'Host' => $url
  188. ];
  189. $res = $this->request('https://' . $url . '/' . $key, 'delete', [], $header);
  190. if ($res && !empty($res['Message'])) {
  191. throw new UploadException($res['Message']);
  192. }
  193. return $res;
  194. }
  195. /**
  196. * 获取桶列表
  197. * @return array|false|\SimpleXMLElement|string
  198. * @author 等风来
  199. * @email 136327134@qq.com
  200. * @date 2022/10/19
  201. */
  202. public function listBuckets()
  203. {
  204. $url = 'service.cos.myqcloud.com';
  205. $header = [
  206. 'Host' => $url
  207. ];
  208. $res = $this->request('https://' . $url . '/', 'get', [], $header);
  209. if ($res && !empty($res['Message'])) {
  210. throw new UploadException($res['Message']);
  211. }
  212. return $res;
  213. }
  214. /**
  215. * 检测桶,不存在返回true
  216. * @param string $bucket
  217. * @param string $region
  218. * @return bool
  219. * @author 等风来
  220. * @email 136327134@qq.com
  221. * @date 2022/10/17
  222. */
  223. public function headBucket(string $bucket, string $region = '')
  224. {
  225. $url = $this->getRequestHost($bucket, $region);
  226. $header = [
  227. 'Host' => $url
  228. ];
  229. $this->request('https://' . $url, 'head', [], $header);
  230. $response = $this->getResponse();
  231. return $response['code'] == 404;
  232. }
  233. /**
  234. * 创建桶
  235. * @param string $bucket
  236. * @param string $region
  237. * @param string $acl
  238. * @return array|false|\SimpleXMLElement|string
  239. * @author 等风来
  240. * @email 136327134@qq.com
  241. * @date 2022/10/17
  242. */
  243. public function createBucket(string $bucket, string $region = '', string $acl = 'public-read')
  244. {
  245. return $this->noBodyRequest('put', $bucket, $region, $acl);
  246. }
  247. /**
  248. * 组合成xml
  249. * @param array $data
  250. * @param string $root
  251. * @param string $itemKey
  252. * @return string
  253. * @author 等风来
  254. * @email 136327134@qq.com
  255. * @date 2022/10/17
  256. */
  257. protected function xmlBuild(array $xmlAttr, string $root = 'xml', string $itemKey = 'item')
  258. {
  259. $xml = '<' . $root . '>';
  260. $xml .= '<' . $itemKey . '>';
  261. foreach ($xmlAttr as $kk => $vv) {
  262. if (is_array($vv)) {
  263. foreach ($vv as $v) {
  264. $xml .= '<' . $kk . '>' . $v . '</' . $kk . '>';
  265. }
  266. } else {
  267. $xml .= '<' . $kk . '>' . $vv . '</' . $kk . '>';
  268. }
  269. }
  270. $xml .= '</' . $itemKey . '>';
  271. $xml .= '</' . $root . '>';
  272. return $xml;
  273. }
  274. /**
  275. * 设置跨域
  276. * @param string $bucket
  277. * @param string $region
  278. * @param array $data
  279. * @return string
  280. * @author 等风来
  281. * @email 136327134@qq.com
  282. * @date 2022/10/17
  283. */
  284. public function putBucketCors(string $bucket, array $data, string $region = '')
  285. {
  286. $url = $this->getRequestHost($bucket, $region);
  287. $xml = $this->xmlBuild($data, 'CORSConfiguration', 'CORSRule');
  288. $header = [
  289. 'Host' => $url,
  290. 'Content-Type' => 'application/xml',
  291. 'Content-Length' => strlen($xml),
  292. 'Content-MD5' => base64_encode(md5($xml, true))
  293. ];
  294. $res = $this->request('https://' . $url . '/?cors', 'put', ['xml' => $xml], $header);
  295. if ($res && !empty($res['Message'])) {
  296. throw new UploadException($res['Message']);
  297. }
  298. return $res;
  299. }
  300. /**
  301. * 删除
  302. * @param string $name
  303. * @param string $region
  304. * @return array|false|\SimpleXMLElement|string
  305. * @author 等风来
  306. * @email 136327134@qq.com
  307. * @date 2022/10/17
  308. */
  309. public function deleteBucket(string $name, string $region = '')
  310. {
  311. return $this->noBodyRequest('delete', $name, $region);
  312. }
  313. /**
  314. * 获取桶下的
  315. * @param string $name
  316. * @param string $region
  317. * @return array|false|\SimpleXMLElement|string
  318. * @author 等风来
  319. * @email 136327134@qq.com
  320. * @date 2022/10/17
  321. */
  322. public function getBucketDomain(string $name, string $region = '')
  323. {
  324. $this->action = 'domain';
  325. return $this->noBodyRequest('get', $name, $region);
  326. }
  327. /**
  328. * 绑定域名
  329. * @param string $bucket
  330. * @param string $region
  331. * @param array $data
  332. * @return array|false|\SimpleXMLElement|string
  333. * @author 等风来
  334. * @email 136327134@qq.com
  335. * @date 2022/10/19
  336. */
  337. public function putBucketDomain(string $bucket, string $region, array $data)
  338. {
  339. $url = $this->getRequestHost($bucket, $region);
  340. $xml = $this->xmlBuild($data, 'DomainConfiguration', 'DomainRule');
  341. $header = [
  342. 'Host' => $url,
  343. 'Content-Type' => 'application/xml',
  344. 'Content-Length' => strlen($xml),
  345. 'Content-MD5' => base64_encode(md5($xml, true))
  346. ];
  347. $res = $this->request('https://' . $url . '/?domain', 'put', ['xml' => $xml], $header);
  348. if ($res && !empty($res['Message'])) {
  349. throw new UploadException($res['Message']);
  350. }
  351. return $res;
  352. }
  353. /**
  354. * @param string $bucket
  355. * @param string $region
  356. * @return string
  357. * @author 等风来
  358. * @email 136327134@qq.com
  359. * @date 2022/10/17
  360. */
  361. protected function getRequestHost(string $bucket, string $region = '')
  362. {
  363. if (!$this->accessKey) {
  364. throw new UploadException('请传入SecretId');
  365. }
  366. if (!$this->secretKey) {
  367. throw new UploadException('请传入SecretKey');
  368. }
  369. if (strstr($bucket, '-') === false) {
  370. $bucket = $bucket . '-' . $this->appid;
  371. }
  372. return $bucket . '.cos.' . ($region ?: $this->region) . '.myqcloud.com';
  373. }
  374. /**
  375. * @param string $method
  376. * @param string $bucket
  377. * @param string $region
  378. * @param string|null $acl
  379. * @return array|false|\SimpleXMLElement|string
  380. * @author 等风来
  381. * @email 136327134@qq.com
  382. * @date 2022/10/17
  383. */
  384. public function noBodyRequest(string $method, string $bucket, string $region = '', string $acl = null, bool $isExc = true)
  385. {
  386. $url = $this->getRequestHost($bucket, $region);
  387. $header = [
  388. 'Host' => $url
  389. ];
  390. if ($acl) {
  391. $header['x-cos-acl'] = $acl;
  392. }
  393. if (in_array($method, ['put', 'post'])) {
  394. $header['Content-Length'] = 0;
  395. }
  396. $res = $this->request('https://' . $url . '/' . ($this->action ? '?' . $this->action : ''), $method, [], $header);
  397. $this->action = '';
  398. if ($isExc) {
  399. if ($res && !empty($res['Message'])) {
  400. throw new UploadException($res['Message']);
  401. }
  402. }
  403. return $res;
  404. }
  405. /**
  406. * 发起请求
  407. * @param string $url
  408. * @param string $method
  409. * @param array $data
  410. * @param array $header
  411. * @param int $timeout
  412. * @return array|false|\SimpleXMLElement|string
  413. * @author 等风来
  414. * @email 136327134@qq.com
  415. * @date 2022/9/29
  416. */
  417. public function request(string $url, string $method, array $data, array $header = [], int $timeout = 5)
  418. {
  419. $this->request['body'] = $data;
  420. $this->request['host'] = $url;
  421. $urlAttr = parse_url($url);
  422. $curl = curl_init($url);
  423. $method = strtoupper($method);
  424. //请求方式
  425. curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
  426. //超时时间
  427. curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
  428. //设置header头
  429. $header = array_merge($header, $this->getSign($url, $method, $urlAttr['path'] ?? '', [], $header));
  430. $this->request['header'] = $header;
  431. $clientHeader = [];
  432. foreach ($header as $key => $item) {
  433. $clientHeader[] = $key . ':' . $item;
  434. }
  435. curl_setopt($curl, CURLOPT_HTTPHEADER, $clientHeader);
  436. curl_setopt($curl, CURLOPT_FAILONERROR, false);
  437. //返回抓取数据
  438. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  439. //输出header头信息
  440. curl_setopt($curl, CURLOPT_HEADER, true);
  441. //TRUE 时追踪句柄的请求字符串,从 PHP 5.1.3 开始可用。这个很关键,就是允许你查看请求header
  442. curl_setopt($curl, CURLINFO_HEADER_OUT, true);
  443. //https请求
  444. if (1 == strpos("$" . $url, "https://")) {
  445. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  446. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  447. }
  448. //post请求
  449. if ($method == 'PUT' && !empty($data['body'])) {
  450. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  451. // 注意这里的'file'是上传地址指定的key名
  452. curl_setopt($curl, CURLOPT_POSTFIELDS, $data['body']);
  453. }
  454. if (!empty($data['xml'])) {
  455. curl_setopt($curl, CURLOPT_POSTFIELDS, $data['xml']);
  456. }
  457. list($content, $status) = [curl_exec($curl), curl_getinfo($curl), curl_close($curl)];
  458. $content = trim(substr($content, $status['header_size']));
  459. $this->response['content'] = $content;
  460. $this->response['code'] = $status['http_code'];
  461. $this->response['header'] = $status;
  462. $res = XML::parse($content);
  463. if ($res) {
  464. return $res;
  465. }
  466. return (intval($status["http_code"]) === 200) ? $content : false;
  467. }
  468. /**
  469. * 获取签名
  470. * @param string $method
  471. * @param string $urlPath
  472. * @param array $query
  473. * @param array $headers
  474. * @return array
  475. * @author 等风来
  476. * @email 136327134@qq.com
  477. * @date 2022/9/27
  478. */
  479. public function getSign(string $url, string $method, string $urlPath, array $query = [], array $headers = [])
  480. {
  481. return (new Signature($this->accessKey, $this->secretKey, ['signHost' => $url]))->signRequest($method, $urlPath, $query, $headers);
  482. }
  483. }