Ctoss.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. <?php
  2. namespace crmeb\services\upload\storage;
  3. use crmeb\exceptions\AdminException;
  4. use crmeb\exceptions\UploadException;
  5. use crmeb\services\upload\extend\obs\Client as TyClient;
  6. use crmeb\services\upload\BaseUpload;
  7. use DateTimeInterface;
  8. use GuzzleHttp\Psr7\Utils;
  9. use think\exception\ValidateException;
  10. class Ctoss extends BaseUpload
  11. {
  12. /**
  13. * accessKey
  14. * @var mixed
  15. */
  16. protected $accessKey;
  17. /**
  18. * secretKey
  19. * @var mixed
  20. */
  21. protected $secretKey;
  22. /**
  23. * 句柄
  24. * @var TyClient
  25. */
  26. protected $handle;
  27. /**
  28. * 空间域名 Domain
  29. * @var mixed
  30. */
  31. protected $uploadUrl;
  32. /**
  33. * 存储空间名称 公开空间
  34. * @var mixed
  35. */
  36. protected $storageName;
  37. /**
  38. * COS使用 所属地域
  39. * @var mixed|null
  40. */
  41. protected $storageRegion;
  42. /**
  43. * 水印位置
  44. * @var string[]
  45. */
  46. protected $position = [
  47. '1' => 'tl',//:左上
  48. '2' => 'top',//:中上
  49. '3' => 'tr',//:右上
  50. '4' => 'left',//:左中
  51. '5' => 'center',//:中部
  52. '6' => 'right',//:右中
  53. '7' => 'bl',//:左下
  54. '8' => 'bottom',//:中下
  55. '9' => 'br',//:右下
  56. ];
  57. /**
  58. * 初始化
  59. * @param array $config
  60. * @return mixed|void
  61. */
  62. public function initialize(array $config)
  63. {
  64. parent::initialize($config);
  65. $this->accessKey = $config['accessKey'] ?? null;
  66. $this->secretKey = $config['secretKey'] ?? null;
  67. $this->uploadUrl = $this->checkUploadUrl($config['uploadUrl'] ?? '');
  68. $this->storageName = $config['storageName'] ?? null;
  69. $this->storageRegion = $config['storageRegion'] ?? null;
  70. $this->cdn = $config['cdn'] ?? null;
  71. $this->waterConfig['watermark_text_font'] = 'simfang仿宋.ttf';
  72. }
  73. /**
  74. * 实例化cos
  75. * @return TyClient
  76. */
  77. protected function app()
  78. {
  79. if (!$this->accessKey || !$this->secretKey) {
  80. throw new UploadException('请填写存储配置或者更换存储方式');
  81. }
  82. $this->handle = new TyClient([
  83. 'accessKey' => $this->accessKey,
  84. 'secretKey' => $this->secretKey,
  85. 'region' => $this->storageRegion ?: 'cn-qhxn1',
  86. 'bucket' => $this->storageName,
  87. 'uploadUrl' => $this->uploadUrl,
  88. 'type' => 'ty'
  89. ]);
  90. return $this->handle;
  91. }
  92. /**
  93. * @var string
  94. */
  95. protected $cdn;
  96. public function move(string $file = 'file', bool $isStream = false, string $fileContent = null)
  97. {
  98. if (!$isStream) {
  99. $fileHandle = app()->request->file($file);
  100. if (!$fileHandle) {
  101. return $this->setError('上传的文件不存在');
  102. }
  103. if ($this->validate) {
  104. if (!in_array($fileHandle->getOriginalExtension(), $this->validate['fileExt'])) {
  105. return $this->setError('不合法的文件后缀:'.$fileHandle->getOriginalExtension());
  106. }
  107. if (filesize($fileHandle) > $this->validate['filesize']) {
  108. return $this->setError('文件过大');
  109. }
  110. if (!in_array($fileHandle->getOriginalMime(), $this->validate['fileMime'])) {
  111. return $this->setError('不合法的文件类型:'.$fileHandle->getOriginalMime());
  112. }
  113. }
  114. $key = $this->saveFileName($fileHandle->getRealPath(), $fileHandle->getOriginalExtension());
  115. $body = fopen($fileHandle->getRealPath(), 'rb');
  116. $body = (string)Utils::streamFor($body);
  117. } else {
  118. $key = $file;
  119. $body = $fileContent;
  120. }
  121. $key = $this->getUploadPath($key);
  122. try {
  123. $uploadInfo = $this->app()->putObject($key, $body, 'application/octet-stream');
  124. $this->fileInfo->uploadInfo = $uploadInfo;
  125. $this->fileInfo->realName = isset($fileHandle) ? $fileHandle->getOriginalName() : $key;
  126. $this->fileInfo->filePath = ($this->cdn ?: $this->uploadUrl) . '/' . $key;
  127. $this->fileInfo->fileName = $key;
  128. $this->fileInfo->filePathWater = $this->water($this->fileInfo->filePath);
  129. $this->authThumb && $this->thumb($this->fileInfo->filePath);
  130. return $this->fileInfo;
  131. } catch (\Throwable $e) {
  132. return $this->setError($e->getMessage());
  133. }
  134. }
  135. public function stream($fileContent, string $key = null)
  136. {
  137. if (!$key) {
  138. $key = $this->saveFileName();
  139. }
  140. return $this->move($key, true, $fileContent);
  141. }
  142. public function delete(string $filePath)
  143. {
  144. try {
  145. return $this->app()->deleteObject($filePath);
  146. } catch (\Exception $e) {
  147. return $this->setError($e->getMessage());
  148. }
  149. }
  150. public function listbuckets(string $region = null, bool $line = false, bool $shared = false)
  151. {
  152. try {
  153. $res = $this->app()->listBuckets();
  154. return $res['Buckets']['Bucket'] ?? [];
  155. } catch (\Throwable $e) {
  156. return [];
  157. }
  158. }
  159. public function createBucket(string $name, string $region, string $acl = TyClient::DEFAULT_OBS_ACL)
  160. {
  161. $regionData = $this->getRegion();
  162. $regionData = array_column($regionData, 'value');
  163. if (!in_array($region, $regionData)) {
  164. return $this->setError('COS:无效的区域!');
  165. }
  166. $this->storageRegion = $region;
  167. $app = $this->app();
  168. //创建桶
  169. try {
  170. $app->createBucket($name, $region, $acl);
  171. $data = [
  172. 'Statement' => [
  173. 'Sid' => '公共读' . $name,
  174. 'Effect' => 'Allow',
  175. 'Principal' => [
  176. 'ID' => ['*']
  177. ],
  178. 'Action' => ['HeadBucket', 'GetBucketLocation', 'ListBucketVersions', 'GetObject', 'RestoreObject', 'GetObjectVersion'],
  179. 'Resource' => [$name, $name . '/*']
  180. ]
  181. ];
  182. $app->putPolicy($name, $region, $data);
  183. } catch (\Throwable $e) {
  184. return $this->setError('COS:' . $e->getMessage());
  185. }
  186. return true;
  187. }
  188. public function getRegion()
  189. {
  190. return [
  191. [
  192. 'value' => 'cn-gz1',
  193. 'label' => '贵州'
  194. ],
  195. [
  196. 'value' => 'cn-fz1',
  197. 'label' => '福州'
  198. ],
  199. [
  200. 'value' => 'cn-hz1',
  201. 'label' => '杭州'
  202. ],
  203. [
  204. 'value' => 'cn-sz1',
  205. 'label' => '深圳'
  206. ],
  207. [
  208. 'value' => 'cn-gdgz1',
  209. 'label' => '广州'
  210. ],
  211. [
  212. 'value' => 'cn-jssz1',
  213. 'label' => '苏州'
  214. ],
  215. [
  216. 'value' => 'cn-sh1',
  217. 'label' => '上海'
  218. ],
  219. [
  220. 'value' => 'cn-ahwh1',
  221. 'label' => '芜湖'
  222. ],
  223. [
  224. 'value' => 'cn-bj1',
  225. 'label' => '北京'
  226. ],
  227. [
  228. 'value' => 'cn-sccd1',
  229. 'label' => '成都'
  230. ],
  231. [
  232. 'value' => 'cn-hazz1',
  233. 'label' => '郑州'
  234. ],
  235. [
  236. 'value' => 'cn-hncs1',
  237. 'label' => '长沙'
  238. ],
  239. [
  240. 'value' => 'cn-gxnn1',
  241. 'label' => '南宁'
  242. ],
  243. [
  244. 'value' => 'cn-jxnc1',
  245. 'label' => '南昌'
  246. ],
  247. [
  248. 'value' => 'cn-sdqd1',
  249. 'label' => '青岛'
  250. ],
  251. [
  252. 'value' => 'cn-snxy1',
  253. 'label' => '咸阳'
  254. ],
  255. [
  256. 'value' => 'cn-xjcj1',
  257. 'label' => '新疆'
  258. ],
  259. [
  260. 'value' => 'cn-ynkm1',
  261. 'label' => '昆明'
  262. ],
  263. [
  264. 'value' => 'cn-hihk1',
  265. 'label' => '海口'
  266. ],
  267. [
  268. 'value' => 'cn-hbwh1',
  269. 'label' => '武汉'
  270. ],
  271. [
  272. 'value' => 'cn-cq1',
  273. 'label' => '重庆'
  274. ],
  275. [
  276. 'value' => 'cn-qhxn1',
  277. 'label' => '西宁'
  278. ],
  279. [
  280. 'value' => 'cn-gslz1',
  281. 'label' => '兰州'
  282. ],
  283. [
  284. 'value' => 'cn-nxyc1',
  285. 'label' => '银川'
  286. ],
  287. [
  288. 'value' => 'cn-sxty1',
  289. 'label' => '太原'
  290. ],
  291. [
  292. 'value' => 'cn-hesjz1',
  293. 'label' => '石家庄'
  294. ],
  295. [
  296. 'value' => 'cn-tj1',
  297. 'label' => '天津'
  298. ],
  299. [
  300. 'value' => 'cn-jlcc1',
  301. 'label' => '长春'
  302. ],
  303. [
  304. 'value' => 'cn-hlhrb1',
  305. 'label' => '哈尔滨'
  306. ],
  307. [
  308. 'value' => 'cn-nmhh1',
  309. 'label' => '内蒙古'
  310. ],
  311. [
  312. 'value' => 'cn-lnsy1',
  313. 'label' => '沈阳'
  314. ],
  315. [
  316. 'value' => 'cn-north1',
  317. 'label' => '华北'
  318. ]
  319. ];
  320. }
  321. public function deleteBucket(string $name, string $region = '')
  322. {
  323. try {
  324. $this->app()->deleteBucket($name, $region);
  325. return true;
  326. } catch (\Throwable $e) {
  327. return $this->setError($e->getMessage());
  328. }
  329. }
  330. public function getDomian($name, $region)
  331. {
  332. try {
  333. $res = $this->app()->getBucketDomain($name, $region);
  334. if ($res) {
  335. $domainRules = $res->toArray()['ListBucketCustomDomainsResult'];
  336. return array_column($domainRules, 'DomainName');
  337. } else {
  338. return [];
  339. }
  340. } catch (\Throwable $e) {
  341. }
  342. return [];
  343. }
  344. public function bindDomian(string $name, string $domain, string $region = null)
  345. {
  346. $parseDomin = parse_url($domain);
  347. try {
  348. $this->app()->putBucketDomain($name, $region, [
  349. 'domainname' => $parseDomin['host'],
  350. ]);
  351. return true;
  352. } catch (\Throwable $e) {
  353. return $this->setError($e->getMessage());
  354. }
  355. }
  356. public function setBucketCors(string $name, string $region)
  357. {
  358. try {
  359. $this->app()->putBucketCors($name, $region, [
  360. 'AllowedHeader' => ['*'],
  361. 'AllowedMethod' => ['PUT', 'GET', 'POST', 'DELETE', 'HEAD'],
  362. 'AllowedOrigin' => ['*'],
  363. 'ExposeHeader' => ['ETag'],
  364. 'MaxAgeSeconds' => 0
  365. ]);
  366. return true;
  367. } catch (\Throwable $e) {
  368. return $this->setError($e->getMessage());
  369. }
  370. }
  371. /**
  372. * @param string $callbackUrl
  373. * @param string $dir
  374. * @return array
  375. * @throws \Exception
  376. * @author 吴汐
  377. * @email 442384644@qq.com
  378. * @date 2023/06/19
  379. */
  380. public function getTempKeys($callbackUrl = '', $dir = '')
  381. {
  382. // TODO: Implement getTempKeys() method.
  383. $base64CallbackBody = base64_encode(json_encode([
  384. 'callbackUrl' => $callbackUrl,
  385. 'callbackBody' => 'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}',
  386. 'callbackBodyType' => "application/x-www-form-urlencoded"
  387. ]));
  388. $policy = json_encode([
  389. 'expiration' => $this->gmtIso8601(time() + 300),
  390. 'conditions' =>
  391. [
  392. [0 => 'content-length-range', 1 => 0, 2 => 1048576000],
  393. ['bucket' => $this->storageName],
  394. [0 => 'starts-with', 1 => '$key', 2 => $dir],
  395. ]
  396. ]);
  397. $base64Policy = base64_encode($policy);
  398. $signature = base64_encode(hash_hmac('sha1', $base64Policy, $this->secretKey, true));
  399. return [
  400. 'accessid' => $this->accessKey,
  401. 'host' => $this->uploadUrl,
  402. 'policy' => $base64Policy,
  403. 'signature' => $signature,
  404. 'expire' => time() + 30,
  405. 'callback' => $base64CallbackBody,
  406. 'cdn' => $this->cdn,
  407. 'type' => 'OBS'
  408. ];
  409. }
  410. /**
  411. * 获取ISO时间格式
  412. * @param $time
  413. * @return string
  414. * @throws \Exception
  415. */
  416. protected function gmtIso8601($time): string
  417. {
  418. $dtStr = date("c", $time);
  419. $myDateTime = new \DateTime($dtStr);
  420. $expiration = $myDateTime->format(DateTimeInterface::ISO8601);
  421. $pos = strpos($expiration, '+');
  422. $expiration = substr($expiration, 0, $pos);
  423. return $expiration . "Z";
  424. }
  425. public function thumb(string $filePath = '', string $fileName = '', string $type = 'all')
  426. {
  427. $filePath = $this->getFilePath($filePath);
  428. $data = ['big' => $filePath, 'mid' => $filePath, 'small' => $filePath];
  429. $this->fileInfo->filePathBig = $this->fileInfo->filePathMid = $this->fileInfo->filePathSmall = $this->fileInfo->filePathWater = $filePath;
  430. if ($filePath) {
  431. $config = $this->thumbConfig;
  432. foreach ($this->thumb as $v) {
  433. if ($type == 'all' || $type == $v) {
  434. $height = 'thumb_' . $v . '_height';
  435. $width = 'thumb_' . $v . '_width';
  436. $key = 'filePath' . ucfirst($v);
  437. if (isset($config[$height]) && isset($config[$width]) && $config[$height] && $config[$width]) {
  438. if (!strpos($filePath, '?x-oss-process')) {
  439. $this->fileInfo->$key = $filePath . '?x-oss-process=image/resize,h_' . $config[$height] . ',w_' . $config[$width];
  440. }
  441. $this->fileInfo->$key = $this->water($this->fileInfo->$key);
  442. $data[$v] = $this->fileInfo->$key;
  443. } else {
  444. $this->fileInfo->$key = $this->water($this->fileInfo->$key);
  445. $data[$v] = $this->fileInfo->$key;
  446. }
  447. }
  448. }
  449. }
  450. return $data;
  451. }
  452. /**
  453. * 水印
  454. * @param string $filePath
  455. * @return mixed|string
  456. */
  457. public function water(string $filePath = '')
  458. {
  459. $filePath = $this->getFilePath($filePath);
  460. $waterConfig = $this->waterConfig;
  461. $waterPath = $filePath;
  462. if ($waterConfig['image_watermark_status'] && $filePath) {
  463. if (strpos($filePath, '?x-oss-process') === false) {
  464. $filePath .= '&x-oss-process=image';
  465. }
  466. switch ($waterConfig['watermark_type']) {
  467. case 1://图片
  468. if (!$waterConfig['watermark_image']) {
  469. throw new AdminException(400722);
  470. }
  471. $waterFileName = substr(parse_url($waterConfig['watermark_image'],PHP_URL_PATH), 1);
  472. $waterPath = $filePath .= '/watermark,image_' . base64_encode($waterFileName) . ',t_' . $waterConfig['watermark_opacity'] . ',g_' . ($this->position[$waterConfig['watermark_position']] ?? 'nw') . ',x_' . $waterConfig['watermark_x'] . ',y_' . $waterConfig['watermark_y'];
  473. break;
  474. case 2://文字
  475. if (!$waterConfig['watermark_text']) {
  476. throw new AdminException(400723);
  477. }
  478. $waterConfig['watermark_text_color'] = str_replace('#', '', $waterConfig['watermark_text_color']);
  479. $waterPath = $filePath .= '/watermark,text_' . base64_encode($waterConfig['watermark_text']) . ',color_' . $waterConfig['watermark_text_color'] . ',size_' . $waterConfig['watermark_text_size'] . ',g_' . ($this->position[$waterConfig['watermark_position']] ?? 'nw') . ',x_' . $waterConfig['watermark_x'] . ',y_' . $waterConfig['watermark_y'];
  480. break;
  481. }
  482. }
  483. return $waterPath;
  484. }
  485. }