Cos.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace crmeb\services\upload\storage;
  12. use crmeb\services\upload\BaseUpload;
  13. use crmeb\exceptions\AdminException;
  14. use crmeb\exceptions\UploadException;
  15. use GuzzleHttp\Psr7\Utils;
  16. use Qcloud\Cos\Client;
  17. use QCloud\COSSTS\Sts;
  18. use crmeb\services\upload\extend\cos\Client as CrmebClient;
  19. /**
  20. * 腾讯云COS文件上传
  21. * Class COS
  22. * @package crmeb\services\upload\storage
  23. */
  24. class Cos extends BaseUpload
  25. {
  26. /**
  27. * 应用id
  28. * @var string
  29. */
  30. protected $appid;
  31. /**
  32. * accessKey
  33. * @var mixed
  34. */
  35. protected $accessKey;
  36. /**
  37. * secretKey
  38. * @var mixed
  39. */
  40. protected $secretKey;
  41. /**
  42. * 句柄
  43. * @var CrmebClient
  44. */
  45. protected $handle;
  46. /**
  47. * 空间域名 Domain
  48. * @var mixed
  49. */
  50. protected $uploadUrl;
  51. /**
  52. * 存储空间名称 公开空间
  53. * @var mixed
  54. */
  55. protected $storageName;
  56. /**
  57. * COS使用 所属地域
  58. * @var mixed|null
  59. */
  60. protected $storageRegion;
  61. /**
  62. * @var string
  63. */
  64. protected $cdn;
  65. /**
  66. * 水印位置
  67. * @var string[]
  68. */
  69. protected $position = [
  70. '1' => 'northwest',//:左上
  71. '2' => 'north',//:中上
  72. '3' => 'northeast',//:右上
  73. '4' => 'west',//:左中
  74. '5' => 'center',//:中部
  75. '6' => 'east',//:右中
  76. '7' => 'southwest',//:左下
  77. '8' => 'south',//:中下
  78. '9' => 'southeast',//:右下
  79. ];
  80. /**
  81. * 初始化
  82. * @param array $config
  83. * @return mixed|void
  84. */
  85. public function initialize(array $config)
  86. {
  87. parent::initialize($config);
  88. $this->accessKey = $config['accessKey'] ?? null;
  89. $this->appid = $config['appid'] ?? null;
  90. $this->secretKey = $config['secretKey'] ?? null;
  91. $this->uploadUrl = $this->checkUploadUrl($config['uploadUrl'] ?? '');
  92. $this->storageName = $config['storageName'] ?? null;
  93. $this->storageRegion = $config['storageRegion'] ?? null;
  94. $this->cdn = $config['cdn'] ?? null;
  95. $this->waterConfig['watermark_text_font'] = 'simfang仿宋.ttf';
  96. }
  97. /**
  98. * 实例化cos
  99. * @return CrmebClient
  100. */
  101. protected function app()
  102. {
  103. $this->handle = new CrmebClient([
  104. 'accessKey' => $this->accessKey,
  105. 'secretKey' => $this->secretKey,
  106. 'region' => $this->storageRegion ?: 'ap-chengdu',
  107. 'bucket' => $this->storageName,
  108. 'appid' => $this->appid,
  109. 'uploadUrl' => $this->uploadUrl
  110. ]);
  111. return $this->handle;
  112. }
  113. /**
  114. * 上传文件
  115. * @param string|null $file
  116. * @param bool $isStream 是否为流上传
  117. * @param string|null $fileContent 流内容
  118. * @return array|bool|\StdClass
  119. */
  120. protected function upload(string $file = null, bool $isStream = false, string $fileContent = null)
  121. {
  122. if (!$isStream) {
  123. $fileHandle = app()->request->file($file);
  124. if (!$fileHandle) {
  125. return $this->setError('上传的文件不存在');
  126. }
  127. if ($this->validate) {
  128. if (!in_array(strtolower(pathinfo($fileHandle->getOriginalName(), PATHINFO_EXTENSION)), $this->validate['fileExt'])) {
  129. return $this->setError('不合法的文件后缀');
  130. }
  131. if (filesize($fileHandle) > $this->validate['filesize']) {
  132. return $this->setError('文件过大');
  133. }
  134. if (!in_array($fileHandle->getOriginalMime(), $this->validate['fileMime'])) {
  135. return $this->setError('不合法的文件类型');
  136. }
  137. }
  138. $key = $this->saveFileName($fileHandle->getRealPath(), $fileHandle->getOriginalExtension());
  139. $body = fopen($fileHandle->getRealPath(), 'rb');
  140. $body = (string)Utils::streamFor($body);
  141. } else {
  142. $key = $file;
  143. $body = $fileContent;
  144. }
  145. try {
  146. $key = $this->getUploadPath($key);
  147. $this->fileInfo->uploadInfo = $this->app()->putObject($key, $body);
  148. $this->fileInfo->filePath = ($this->cdn ?: $this->uploadUrl) . '/' . $key;
  149. $this->fileInfo->realName = isset($fileHandle) ? $fileHandle->getOriginalName() : $key;
  150. $this->fileInfo->fileName = $key;
  151. $this->fileInfo->filePathWater = $this->water($this->fileInfo->filePath);
  152. $this->authThumb && $this->thumb($this->fileInfo->filePath);
  153. return $this->fileInfo;
  154. } catch (UploadException $e) {
  155. return $this->setError($e->getMessage());
  156. }
  157. }
  158. /**
  159. * 文件流上传
  160. * @param $fileContent
  161. * @param string|null $key
  162. * @return array|bool|mixed|\StdClass
  163. */
  164. public function stream($fileContent, string $key = null)
  165. {
  166. if (!$key) {
  167. $key = $this->saveFileName();
  168. }
  169. return $this->upload($key, true, $fileContent);
  170. }
  171. /**
  172. * 文件上传
  173. * @param string $file
  174. * @param bool $realName
  175. * @return array|bool|mixed|\StdClass
  176. */
  177. public function move(string $file = 'file', $realName = false)
  178. {
  179. return $this->upload($file);
  180. }
  181. /**
  182. * 缩略图
  183. * @param string $filePath
  184. * @param string $fileName
  185. * @param string $type
  186. * @return array|mixed
  187. */
  188. public function thumb(string $filePath = '', string $fileName = '', string $type = 'all')
  189. {
  190. $filePath = $this->getFilePath($filePath);
  191. $data = ['big' => $filePath, 'mid' => $filePath, 'small' => $filePath];
  192. $this->fileInfo->filePathBig = $this->fileInfo->filePathMid = $this->fileInfo->filePathSmall = $this->fileInfo->filePathWater = $filePath;
  193. if ($filePath) {
  194. $config = $this->thumbConfig;
  195. foreach ($this->thumb as $v) {
  196. if ($type == 'all' || $type == $v) {
  197. $height = 'thumb_' . $v . '_height';
  198. $width = 'thumb_' . $v . '_width';
  199. $key = 'filePath' . ucfirst($v);
  200. if (sys_config('image_thumbnail_status', 1) && isset($config[$height]) && isset($config[$width]) && $config[$height] && $config[$width]) {
  201. $this->fileInfo->$key = $filePath . '?imageMogr2/thumbnail/' . $config[$width] . 'x' . $config[$height];
  202. $this->fileInfo->$key = $this->water($this->fileInfo->$key);
  203. $data[$v] = $this->fileInfo->$key;
  204. } else {
  205. $this->fileInfo->$key = $this->water($this->fileInfo->$key);
  206. $data[$v] = $this->fileInfo->$key;
  207. }
  208. }
  209. }
  210. }
  211. return $data;
  212. }
  213. /**
  214. * 水印
  215. * @param string $filePath
  216. * @return mixed|string
  217. */
  218. public function water(string $filePath = '')
  219. {
  220. $filePath = $this->getFilePath($filePath);
  221. $waterConfig = $this->waterConfig;
  222. $waterPath = $filePath;
  223. if ($waterConfig['image_watermark_status'] && $filePath) {
  224. if (strpos($filePath, '?') === false) {
  225. $filePath .= '?watermark';
  226. } else {
  227. $filePath .= '&watermark';
  228. }
  229. switch ($waterConfig['watermark_type']) {
  230. case 1://图片
  231. if (!$waterConfig['watermark_image']) {
  232. throw new AdminException(400722);
  233. }
  234. $waterPath = $filePath .= '/1/image/' . base64_encode($waterConfig['watermark_image']) . '/gravity/' . ($this->position[$waterConfig['watermark_position']] ?? 'northwest') . '/blogo/1/dx/' . $waterConfig['watermark_x'] . '/dy/' . $waterConfig['watermark_y'];
  235. break;
  236. case 2://文字
  237. if (!$waterConfig['watermark_text']) {
  238. throw new AdminException(400723);
  239. }
  240. $waterPath = $filePath .= '/2/text/' . base64_encode($waterConfig['watermark_text']) . '/font/' . base64_encode($waterConfig['watermark_text_font']) . '/fill/' . base64_encode($waterConfig['watermark_text_color']) . '/fontsize/' . $waterConfig['watermark_text_size'] . '/gravity/' . ($this->position[$waterConfig['watermark_position']] ?? 'northwest') . '/dx/' . $waterConfig['watermark_x'] . '/dy/' . $waterConfig['watermark_y'];
  241. break;
  242. }
  243. }
  244. return $waterPath;
  245. }
  246. /**
  247. * TODO 删除资源
  248. * @param $key
  249. * @return mixed
  250. */
  251. public function delete(string $filePath)
  252. {
  253. try {
  254. return $this->app()->deleteObject($this->storageName, $filePath);
  255. } catch (\Exception $e) {
  256. return $this->setError($e->getMessage());
  257. }
  258. }
  259. /**
  260. * 生成签名
  261. * @return array|mixed
  262. * @throws \Exception
  263. */
  264. public function getTempKeys()
  265. {
  266. $sts = new Sts();
  267. $config = [
  268. 'url' => 'https://sts.tencentcloudapi.com/',
  269. 'domain' => 'sts.tencentcloudapi.com',
  270. 'proxy' => '',
  271. 'secretId' => $this->accessKey, // 固定密钥
  272. 'secretKey' => $this->secretKey, // 固定密钥
  273. 'bucket' => $this->storageName, // 换成你的 bucket
  274. 'region' => $this->storageRegion, // 换成 bucket 所在园区
  275. 'durationSeconds' => 1800, // 密钥有效期
  276. 'allowPrefix' => '*', // 这里改成允许的路径前缀,可以根据自己网站的用户登录态判断允许上传的具体路径,例子: a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
  277. // 密钥的权限列表。简单上传和分片需要以下的权限,其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
  278. 'allowActions' => [
  279. // 简单上传
  280. 'name/cos:PutObject',
  281. 'name/cos:PostObject',
  282. // 分片上传
  283. 'name/cos:InitiateMultipartUpload',
  284. 'name/cos:ListMultipartUploads',
  285. 'name/cos:ListParts',
  286. 'name/cos:UploadPart',
  287. 'name/cos:CompleteMultipartUpload'
  288. ]
  289. ];
  290. // 获取临时密钥,计算签名
  291. $result = $sts->getTempKeys($config);
  292. $result['url'] = $this->uploadUrl . '/';
  293. $result['cdn'] = $this->cdn;
  294. $result['type'] = 'COS';
  295. $result['bucket'] = $this->storageName;
  296. $result['region'] = $this->storageRegion;
  297. return $result;
  298. }
  299. /**
  300. * 计算临时密钥用的签名
  301. * @param $opt
  302. * @param $key
  303. * @param $method
  304. * @param $config
  305. * @return string
  306. */
  307. public function getSignature($opt, $key, $method, $config)
  308. {
  309. $formatString = $method . $config['domain'] . '/?' . $this->json2str($opt, 1);
  310. $sign = hash_hmac('sha1', $formatString, $key);
  311. $sign = base64_encode($this->_hex2bin($sign));
  312. return $sign;
  313. }
  314. public function _hex2bin($data)
  315. {
  316. $len = strlen($data);
  317. return pack("H" . $len, $data);
  318. }
  319. // obj 转 query string
  320. public function json2str($obj, $notEncode = false)
  321. {
  322. ksort($obj);
  323. $arr = array();
  324. if (!is_array($obj)) {
  325. return $this->setError($obj . " must be a array");
  326. }
  327. foreach ($obj as $key => $val) {
  328. array_push($arr, $key . '=' . ($notEncode ? $val : rawurlencode($val)));
  329. }
  330. return join('&', $arr);
  331. }
  332. // v2接口的key首字母小写,v3改成大写,此处做了向下兼容
  333. public function backwardCompat($result)
  334. {
  335. if (!is_array($result)) {
  336. return $this->setError($result . " must be a array");
  337. }
  338. $compat = array();
  339. foreach ($result as $key => $value) {
  340. if (is_array($value)) {
  341. $compat[lcfirst($key)] = $this->backwardCompat($value);
  342. } elseif ($key == 'Token') {
  343. $compat['sessionToken'] = $value;
  344. } else {
  345. $compat[lcfirst($key)] = $value;
  346. }
  347. }
  348. return $compat;
  349. }
  350. /**
  351. * 桶列表
  352. * @param string|null $region
  353. * @param bool $line
  354. * @param bool $shared
  355. * @return array|mixed
  356. * "Name" => "record-1254950941"
  357. * "Location" => "ap-chengdu"
  358. * "CreationDate" => "2019-05-16T08:33:29Z"
  359. * "BucketType" => "cos"
  360. */
  361. public function listbuckets(string $region = null, bool $line = false, bool $shared = false)
  362. {
  363. try {
  364. $res = $this->app()->listBuckets();
  365. return $res['Buckets']['Bucket'] ?? [];
  366. } catch (\Throwable $e) {
  367. return [];
  368. }
  369. }
  370. /**
  371. * 创建桶
  372. * @param string $name
  373. * @param string $region
  374. * @param string $acl public-read=公共独写
  375. * @return bool|mixed
  376. */
  377. public function createBucket(string $name, string $region = '', string $acl = 'public-read')
  378. {
  379. $regionData = $this->getRegion();
  380. $regionData = array_column($regionData, 'value');
  381. if (!in_array($region, $regionData)) {
  382. return $this->setError('COS:无效的区域!');
  383. }
  384. $this->storageRegion = $region;
  385. $app = $this->app();
  386. //检测桶
  387. try {
  388. $app->headBucket($name);
  389. } catch (\Throwable $e) {
  390. //桶不存在返回404
  391. if (strstr('404', $e->getMessage())) {
  392. return $this->setError('COS:' . $e->getMessage());
  393. }
  394. }
  395. //创建桶
  396. try {
  397. $res = $app->createBucket($name . '-' . $this->appid, '', $acl);
  398. } catch (\Throwable $e) {
  399. if (strstr('[curl] 6', $e->getMessage())) {
  400. return $this->setError('COS:无效的区域!!');
  401. } else if (strstr('Access Denied.', $e->getMessage())) {
  402. return $this->setError('COS:无权访问');
  403. }
  404. return $this->setError('COS:' . $e->getMessage());
  405. }
  406. return $res;
  407. }
  408. /**
  409. * 删除桶
  410. * @param string $name
  411. * @return bool|mixed
  412. */
  413. public function deleteBucket(string $name)
  414. {
  415. try {
  416. $this->app()->deleteBucket($name);
  417. return true;
  418. } catch (\Throwable $e) {
  419. return $this->setError($e->getMessage());
  420. }
  421. }
  422. /**
  423. * @param string $name
  424. * @param string|null $region
  425. * @return array|object
  426. */
  427. public function getDomian(string $name, string $region = null)
  428. {
  429. $this->storageRegion = $region;
  430. try {
  431. $res = $this->app()->getBucketDomain($name);
  432. $domainRules = $res['DomainRules'];
  433. return array_column($domainRules, 'Name');
  434. } catch (\Throwable $e) {
  435. }
  436. return [];
  437. }
  438. /**
  439. * 绑定域名
  440. * @param string $name
  441. * @param string $domain
  442. * @param string|null $region
  443. * @return bool|mixed
  444. */
  445. public function bindDomian(string $name, string $domain, string $region = null)
  446. {
  447. $this->storageRegion = $region;
  448. $parseDomin = parse_url($domain);
  449. try {
  450. $res = $this->app()->putBucketDomain($name, '', [
  451. 'Name' => $parseDomin['host'],
  452. 'Status' => 'ENABLED',
  453. 'Type' => 'REST',
  454. 'ForcedReplacement' => 'CNAME'
  455. ]);
  456. if (method_exists($res, 'toArray')) {
  457. $res = $res->toArray();
  458. }
  459. if ($res['RequestId'] ?? null) {
  460. return true;
  461. }
  462. } catch (\Throwable $e) {
  463. if ($message = $this->setMessage($e->getMessage())) {
  464. return $this->setError($message);
  465. }
  466. return $this->setError($e->getMessage());
  467. }
  468. return false;
  469. }
  470. /**
  471. * 处理
  472. * @param string $message
  473. * @return string
  474. */
  475. protected function setMessage(string $message)
  476. {
  477. $data = [
  478. 'The specified bucket does not exist.' => '指定的存储桶不存在。',
  479. 'Please add CNAME/TXT record to DNS then try again later. Please allow up to 10 mins before your DNS takes effect.' => '请将CNAME记录添加到DNS,然后稍后重试。在DNS生效前,请等待最多10分钟。'
  480. ];
  481. $msg = $data[$message] ?? '';
  482. if ($msg) {
  483. return $msg;
  484. }
  485. foreach ($data as $item) {
  486. if (strstr($message, $item)) {
  487. return $item;
  488. }
  489. }
  490. return '';
  491. }
  492. /**
  493. * 设置跨域
  494. * @param string $name
  495. * @param string $region
  496. * @return bool
  497. */
  498. public function setBucketCors(string $name, string $region)
  499. {
  500. $this->storageRegion = $region;
  501. try {
  502. $res = $this->app()->putBucketCors($name, [
  503. 'AllowedHeader' => ['*'],
  504. 'AllowedMethod' => ['PUT', 'GET', 'POST', 'DELETE', 'HEAD'],
  505. 'AllowedOrigin' => ['*'],
  506. 'ExposeHeader' => ['ETag', 'Content-Length', 'x-cos-request-id'],
  507. 'MaxAgeSeconds' => 12
  508. ]);
  509. if (isset($res['RequestId'])) {
  510. return true;
  511. }
  512. } catch (\Throwable $e) {
  513. return $this->setError($e->getMessage());
  514. }
  515. return false;
  516. }
  517. /**
  518. * 地域
  519. * @return mixed|\string[][]
  520. */
  521. public function getRegion()
  522. {
  523. return [
  524. [
  525. 'value' => 'ap-chengdu',
  526. 'label' => '成都'
  527. ],
  528. [
  529. 'value' => 'ap-shanghai',
  530. 'label' => '上海'
  531. ],
  532. [
  533. 'value' => 'ap-guangzhou',
  534. 'label' => '广州'
  535. ],
  536. [
  537. 'value' => 'ap-nanjing',
  538. 'label' => '南京'
  539. ],
  540. [
  541. 'value' => 'ap-beijing',
  542. 'label' => '北京'
  543. ],
  544. [
  545. 'value' => 'ap-chongqing',
  546. 'label' => '重庆'
  547. ],
  548. [
  549. 'value' => 'ap-shenzhen-fsi',
  550. 'label' => '深圳金融'
  551. ],
  552. [
  553. 'value' => 'ap-shanghai-fsi',
  554. 'label' => '上海金融'
  555. ],
  556. [
  557. 'value' => 'ap-beijing-fsi',
  558. 'label' => '北京金融'
  559. ],
  560. [
  561. 'value' => 'ap-hongkong',
  562. 'label' => '中国香港'
  563. ],
  564. [
  565. 'value' => 'ap-singapore',
  566. 'label' => '新加坡'
  567. ],
  568. [
  569. 'value' => 'ap-mumbai',
  570. 'label' => '孟买'
  571. ],
  572. [
  573. 'value' => 'ap-jakarta',
  574. 'label' => '雅加达'
  575. ],
  576. [
  577. 'value' => 'ap-seoul',
  578. 'label' => '首尔'
  579. ],
  580. [
  581. 'value' => 'ap-bangkok',
  582. 'label' => '曼谷'
  583. ],
  584. [
  585. 'value' => 'ap-tokyo',
  586. 'label' => '东京'
  587. ],
  588. [
  589. 'value' => 'na-siliconvalley',
  590. 'label' => '硅谷(美西)'
  591. ],
  592. [
  593. 'value' => 'na-ashburn',
  594. 'label' => '弗吉尼亚(美东)'
  595. ],
  596. [
  597. 'value' => 'na-toronto',
  598. 'label' => '多伦多'
  599. ],
  600. [
  601. 'value' => 'sa-saopaulo',
  602. 'label' => '圣保罗'
  603. ],
  604. [
  605. 'value' => 'eu-frankfurt',
  606. 'label' => '法兰克福'
  607. ],
  608. [
  609. 'value' => 'eu-moscow',
  610. 'label' => '莫斯科'
  611. ]
  612. ];
  613. }
  614. }