Us3.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2024 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\exceptions\AdminException;
  13. use crmeb\services\upload\BaseUpload;
  14. use crmeb\exceptions\UploadException;
  15. use think\exception\ValidateException;
  16. use UCloud\Storage\UploadManager as UcloudUploadManager;
  17. use UCloud\Auth;
  18. use UCloud\UFile\Apis\DeleteBucketRequest;
  19. use UCloud\UFile\Apis\DescribeBucketRequest;
  20. use UCloud\UFile\UFileClient;
  21. use UCloud\UFile\Apis\CreateBucketRequest;
  22. use UCloud\Core\Logger\DisabledLogger;
  23. /**
  24. * Ucloud us3
  25. * Class Us3
  26. */
  27. class Us3 extends BaseUpload
  28. {
  29. /**
  30. * accessKey
  31. * @var mixed
  32. */
  33. protected $accessKey;
  34. /**
  35. * secretKey
  36. * @var mixed
  37. */
  38. protected $secretKey;
  39. /**
  40. * 句柄
  41. * @var object
  42. */
  43. public $handle;
  44. /**
  45. * 空间域名 Domain
  46. * @var mixed
  47. */
  48. protected $uploadUrl;
  49. /**
  50. * 存储空间名称 公开空间
  51. * @var mixed
  52. */
  53. protected $storageName;
  54. /**
  55. * COS使用 所属地域
  56. * @var mixed|null
  57. */
  58. protected $storageRegion;
  59. /**
  60. * cdn 域名
  61. * @var
  62. */
  63. protected $cdn;
  64. /**
  65. * 缩略图开关
  66. * @var mixed|null
  67. */
  68. protected $thumb_status;
  69. /**
  70. * 缩略图比例
  71. * @var mixed|null
  72. */
  73. protected $thumb_rate;
  74. /**
  75. * 水印位置
  76. * @var string[]
  77. */
  78. protected $position = [
  79. '1' => 'NorthWest',//:左上
  80. '2' => 'North',//:中上
  81. '3' => 'NorthEast',//:右上
  82. '4' => 'West',//:左中
  83. '5' => 'Center',//:中部
  84. '6' => 'East',//:右中
  85. '7' => 'SouthWest',//:左下
  86. '8' => 'South',//:中下
  87. '9' => 'SouthEast',//:右下
  88. ];
  89. /**
  90. * 初始化
  91. * @param array $config
  92. * @return mixed|void
  93. */
  94. public function initialize(array $config)
  95. {
  96. parent::initialize($config);
  97. $this->accessKey = $config['accessKey'] ?? null;
  98. $this->secretKey = $config['secretKey'] ?? null;
  99. $this->storageName = $config['storageName'] ?? null;
  100. $this->storageRegion = $config['storageRegion'] ?? null;
  101. $this->cdn = $config['cdn'] ?? null;
  102. if(isset($config['uploadUrl']) && $config['uploadUrl']){
  103. $host = parse_url($config['uploadUrl']);
  104. $this->uploadUrl = substr($host['host'], strlen($config['storageName']));
  105. }
  106. }
  107. /**
  108. * 实例化
  109. * @return object|Auth
  110. */
  111. public function app()
  112. {
  113. if (!$this->accessKey || !$this->secretKey) {
  114. throw new UploadException('请填写存储配置或者更换存储方式');
  115. }
  116. if (!$this->handle) {
  117. $this->handle = new Auth($this->accessKey, $this->secretKey, $this->uploadUrl);
  118. }
  119. return $this->handle;
  120. }
  121. /**
  122. * @param string $name 创建Bucket的名称
  123. * @param string $region 地域
  124. * @param string $type Bucket访问类型,public或private; 默认为private
  125. * @return array
  126. */
  127. public function createBucket(string $name, string $region, string $type = 'public')
  128. {
  129. try {
  130. $uFileClient = new UFileClient([
  131. 'publicKey' => $this->accessKey,
  132. 'privateKey' => $this->secretKey,
  133. 'logger' => new DisabledLogger()
  134. ]);
  135. $type = $type == 'public-read' || $type == 'public-read-write' ? 'public' : 'private';//适配US3入参
  136. $createBucketRequest = new CreateBucketRequest();
  137. $createBucketRequest->setBucketName($name);
  138. $createBucketRequest->setRegion($region);
  139. $createBucketRequest->setType($type);
  140. return $uFileClient->createBucket($createBucketRequest)->toArray();
  141. } catch (\Exception $e) {
  142. throw new UploadException($e->getMessage());
  143. }
  144. }
  145. /**
  146. * 获取区域列表
  147. * @return array
  148. */
  149. public function getRegion()
  150. {
  151. try {
  152. return [
  153. [
  154. 'value' => 'cn-bj2',
  155. 'label' => '华北一',
  156. ],
  157. [
  158. 'value' => 'cn-gd',
  159. 'label' => '广州'
  160. ],
  161. [
  162. 'value' => 'cn-qz',
  163. 'label' => '福建'
  164. ],
  165. [
  166. 'value' => 'cn-sh2',
  167. 'label' => '上海二'
  168. ],
  169. [
  170. 'value' => 'cn-wlcb',
  171. 'label' => '华北二'
  172. ],
  173. [
  174. 'value' => 'afr-nigeria',
  175. 'label' => '拉各斯'
  176. ],
  177. [
  178. 'value' => 'bra-saopaulo',
  179. 'label' => '圣保罗'
  180. ],
  181. [
  182. 'value' => 'ge-fra',
  183. 'label' => '法兰克福'
  184. ],
  185. [
  186. 'value' => 'hk',
  187. 'label' => '香港'
  188. ],
  189. [
  190. 'value' => 'idn-jakarta',
  191. 'label' => '雅加达'
  192. ],
  193. [
  194. 'value' => 'ind-mumbai',
  195. 'label' => '孟买'
  196. ],
  197. [
  198. 'value' => 'jpn-tky',
  199. 'label' => '东京'
  200. ],
  201. [
  202. 'value' => 'kr-seoul',
  203. 'label' => '首尔'
  204. ],
  205. [
  206. 'value' => 'ph-mnl',
  207. 'label' => '马尼拉'
  208. ],
  209. [
  210. 'value' => 'sg',
  211. 'label' => '新加坡'
  212. ],
  213. [
  214. 'value' => 'th-bkk',
  215. 'label' => '曼谷'
  216. ],
  217. [
  218. 'value' => 'tw-tp',
  219. 'label' => '台北'
  220. ],
  221. [
  222. 'value' => 'uae-dubai',
  223. 'label' => '迪拜'
  224. ],
  225. [
  226. 'value' => 'uk-london',
  227. 'label' => '伦敦'
  228. ],
  229. [
  230. 'value' => 'us-ca',
  231. 'label' => '洛杉矶'
  232. ],
  233. [
  234. 'value' => 'us-ws',
  235. 'label' => '华盛顿'
  236. ],
  237. [
  238. 'value' => 'vn-sng',
  239. 'label' => '胡志明市'
  240. ]
  241. ];
  242. // 接口调用获取region 暂未返回中文
  243. // $accountClient = new UAccountClient([
  244. // 'publicKey' => $this->accessKey,
  245. // 'privateKey' => $this->secretKey,
  246. // 'logger' => new DisabledLogger()
  247. // ]);
  248. // $result = $accountClient->getRegion(new GetRegionRequest())->toArray();
  249. // $list = [];
  250. // if(isset($result['Regions']) && !empty($result['Regions'])){
  251. // foreach ($result['Regions'] as $item){
  252. // $list[] = ['lable'=>$item['RegionName'],'value'=>$item['Region']];
  253. // }
  254. // }
  255. } catch (\Exception $e) {
  256. throw new UploadException($e->getMessage());
  257. }
  258. }
  259. /**
  260. * 获取空间列表
  261. * @return array
  262. */
  263. public function listbuckets(string $region = null, bool $line = false, bool $shared = false): array
  264. {
  265. $uFileClient = new UFileClient([
  266. 'publicKey' => $this->accessKey,
  267. 'privateKey' => $this->secretKey,
  268. 'logger' => new DisabledLogger()
  269. ]);
  270. $result = $uFileClient->describeBucket(new DescribeBucketRequest())->toArray();
  271. if (!isset($result['RetCode']) || $result['RetCode'] !== 0) {
  272. throw new UploadException('获取Bucket列表失败');
  273. }
  274. return $result['DataSet'];
  275. }
  276. /**
  277. * 删除存储空间
  278. * @param string $name
  279. * @param string $region
  280. * @return bool
  281. */
  282. public function deleteBucket(string $name, string $region = '')
  283. {
  284. try {
  285. $uFileClient = new UFileClient([
  286. 'publicKey' => $this->accessKey,
  287. 'privateKey' => $this->secretKey,
  288. 'logger' => new DisabledLogger()
  289. ]);
  290. $deleteBucketRequest = new DeleteBucketRequest();
  291. $deleteBucketRequest->setBucketName($name);
  292. $result = $uFileClient->deleteBucket($deleteBucketRequest)->toArray();
  293. if (!isset($result['RetCode']) || $result['RetCode'] !== 0) {
  294. throw new UploadException('删除Bucket失败');
  295. }
  296. return true;
  297. } catch (\Throwable $e) {
  298. throw new UploadException($e->getMessage() ?? '删除失败');
  299. }
  300. }
  301. /**
  302. * 修改域名 暂无
  303. * @return void
  304. */
  305. public function updateDomain()
  306. {
  307. }
  308. /**
  309. * 绑定自定义域名
  310. * @param string $name
  311. * @param string $domain
  312. * @param string|null $region
  313. * @return mixed
  314. */
  315. public function bindDomian(string $name, string $domain, string $region = null)
  316. {
  317. }
  318. /**
  319. * 上传文件
  320. * @param string $file
  321. * @return array|bool|mixed|\StdClass|string
  322. */
  323. public function move(string $file = 'file')
  324. {
  325. $fileHandle = app()->request->file($file);
  326. if (!$fileHandle) {
  327. return $this->setError('上传的文件不存在');
  328. }
  329. if ($this->validate) {
  330. if (!in_array($fileHandle->getOriginalExtension(), $this->validate['fileExt'])) {
  331. return $this->setError('不合法的文件后缀:'.$fileHandle->getOriginalExtension());
  332. }
  333. if (filesize($fileHandle) > $this->validate['filesize']) {
  334. return $this->setError('文件过大');
  335. }
  336. if (!in_array($fileHandle->getOriginalMime(), $this->validate['fileMime'])) {
  337. return $this->setError('不合法的文件类型:'.$fileHandle->getOriginalMime());
  338. }
  339. }
  340. $key = $this->saveFileName($fileHandle->getRealPath(), $fileHandle->getOriginalExtension());
  341. $path = ($this->path ? trim($this->path, '/') . '/' : '');
  342. try {
  343. $uploadMgr = new UcloudUploadManager($this->app());
  344. [$result, $error] = $uploadMgr->PutFile($this->storageName, $path . $key, $fileHandle->getRealPath());
  345. if ($error !== null) {
  346. return $this->setError($error->ErrMsg);
  347. }
  348. if ($this->cdn) {
  349. $src = $this->cdn . $path . $key;
  350. } else {
  351. $src = 'https://' . $uploadMgr->MakePublicUrl($this->storageName, $path . $key);
  352. }
  353. $this->fileInfo->uploadInfo = $result;
  354. $this->fileInfo->filePath = $src;
  355. $this->fileInfo->fileName = $key;
  356. return $this->fileInfo;
  357. } catch (UploadException $e) {
  358. return $this->setError($e->getMessage());
  359. }
  360. }
  361. /**
  362. * 文件流上传
  363. * @param string $fileContent
  364. * @param string|null $key
  365. * @return array|bool|mixed|\StdClass
  366. */
  367. public function stream($fileContent, string $key = null)
  368. {
  369. $file = sys_get_temp_dir() . $key;
  370. file_put_contents($file, $fileContent, true);
  371. if (!$key) {
  372. $key = $this->saveFileName();
  373. }
  374. $path = ($this->path ? trim($this->path, '/') . '/' : '');
  375. try {
  376. $uploadMgr = new UcloudUploadManager($this->app());
  377. list($result, $err) = $uploadMgr->MultipartForm($this->storageName, $path . $key, $file);
  378. unlink($file);
  379. if ($err !== null) {
  380. return array(null, $err);
  381. }
  382. if ($this->cdn) {
  383. $src = $this->cdn . '/' . $path . $key;
  384. } else {
  385. $src = 'https://' . $uploadMgr->MakePublicUrl($this->storageName, $path . $key);
  386. }
  387. if ($this->thumb_status) $src = $this->thumb($src);
  388. $this->fileInfo->uploadInfo = $result;
  389. $this->fileInfo->filePath = $src;
  390. $this->fileInfo->fileName = $key;
  391. return $this->fileInfo;
  392. } catch (UploadException $e) {
  393. return $this->setError($e->getMessage());
  394. }
  395. }
  396. public function thumb(string $filePath = '', string $fileName = '', string $type = 'all')
  397. {
  398. $filePath = $this->getFilePath($filePath);
  399. $data = ['big' => $filePath, 'mid' => $filePath, 'small' => $filePath];
  400. $this->fileInfo->filePathBig = $this->fileInfo->filePathMid = $this->fileInfo->filePathSmall = $this->fileInfo->filePathWater = $filePath;
  401. if ($filePath) {
  402. $config = $this->thumbConfig;
  403. foreach ($this->thumb as $v) {
  404. if ($type == 'all' || $type == $v) {
  405. $height = 'thumb_' . $v . '_height';
  406. $width = 'thumb_' . $v . '_width';
  407. $key = 'filePath' . ucfirst($v);
  408. // if (systemConfig('image_thumbnail_status') && isset($config[$height]) && isset($config[$width])) {
  409. if (isset($config[$height]) && isset($config[$width])) {
  410. if (!strpos($filePath, '?iopcmd=thumbnail')) {
  411. $this->fileInfo->$key = $filePath . '?iopcmd=thumbnail&type=5&width=' . $config[$width] . '&height=' . $config[$height];
  412. }
  413. $this->fileInfo->$key = $this->water($this->fileInfo->$key);
  414. $data[$v] = $this->fileInfo->$key;
  415. } else {
  416. $this->fileInfo->$key = $this->water($this->fileInfo->$key);
  417. $data[$v] = $this->fileInfo->$key;
  418. }
  419. }
  420. }
  421. }
  422. return $data;
  423. }
  424. /**
  425. * 添加水印
  426. * @return mixed
  427. */
  428. public function water(string $filePath = '')
  429. {
  430. $waterPath = $filePath;
  431. if ($this->waterConfig['image_watermark_status'] && $filePath) {
  432. if (strpos($filePath, '?') === false) {
  433. $filePath .= '?iopcmd=watermark';
  434. } else {
  435. $filePath .= '|iopcmd=watermark';
  436. }
  437. switch ($this->waterConfig['watermark_type']) {
  438. case 1://图片
  439. if (!$this->waterConfig['watermark_image']) {
  440. throw new AdminException('请上传水印图');
  441. }
  442. $waterPath = $filePath .= '&type=2&imageurl=' . base64_encode($this->waterConfig['watermark_image']) . '&gravity=' . ($this->position[$this->waterConfig['watermark_position']] ?? 'SouthEest') . '&opacity=' . $this->waterConfig['watermark_opacity'] . '&ax=' . $this->waterConfig['watermark_x'] . '&ay=' . $this->waterConfig['watermark_y'];
  443. break;
  444. case 2://文字
  445. if (!$this->waterConfig['watermark_text']) {
  446. throw new AdminException('请填写水印文字');
  447. }
  448. $waterPath = $filePath .= '&type=1&text=' . base64_encode($this->waterConfig['watermark_text']) . '&fill=' . base64_encode($this->waterConfig['watermark_text_color']) . '&fontsize=' . $this->waterConfig['watermark_text_size'] . '&gravity=' . ($this->position[$this->waterConfig['watermark_position']] ?? 'SouthWest') . '&ax=' . $this->waterConfig['watermark_x'] . '&ay=' . $this->waterConfig['watermark_y'];
  449. break;
  450. }
  451. return $waterPath;
  452. }
  453. }
  454. /**
  455. * 获取上传配置信息
  456. * @return array
  457. */
  458. public function getSystem()
  459. {
  460. $token = $this->app()->uploadToken($this->storageName);
  461. $domain = $this->uploadUrl;
  462. $key = $this->saveFileName();
  463. return compact('token', 'domain', 'key');
  464. }
  465. /**
  466. * 删除资源
  467. * @param $key
  468. * @param $bucket
  469. * @return mixed
  470. */
  471. public function delete(string $key)
  472. {
  473. $bucketManager = new UcloudUploadManager($this->app());
  474. return $bucketManager->delete($this->storageName, $key);
  475. }
  476. /**
  477. *
  478. * @return mixed|string
  479. */
  480. public function getTempKeys()
  481. {
  482. return [
  483. 'accessid' => $this->accessKey,
  484. 'secretKey' => $this->secretKey,
  485. 'host' => $this->uploadUrl,
  486. 'storageName' => $this->storageName,
  487. 'cdn' => $this->cdn,
  488. 'type' => 'US3'
  489. ];
  490. }
  491. /**
  492. * 设置跨域
  493. * @param string $name
  494. * @param string $region
  495. * @return mixed
  496. */
  497. public function setBucketCors(string $name, string $region)
  498. {
  499. return true;
  500. }
  501. }