Oss.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 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\basic\BaseUpload;
  13. use crmeb\exceptions\UploadException;
  14. use GuzzleHttp\Psr7\Utils;
  15. use OSS\Core\OssException;
  16. use OSS\Model\CorsConfig;
  17. use OSS\Model\CorsRule;
  18. use OSS\OssClient;
  19. use think\exception\ValidateException;
  20. /**
  21. * 阿里云OSS上传
  22. * Class OSS
  23. */
  24. class Oss extends BaseUpload
  25. {
  26. /**
  27. * accessKey
  28. * @var mixed
  29. */
  30. protected $accessKey;
  31. /**
  32. * secretKey
  33. * @var mixed
  34. */
  35. protected $secretKey;
  36. /**
  37. * 句柄
  38. * @var \OSS\OssClient
  39. */
  40. protected $handle;
  41. /**
  42. * 空间域名 Domain
  43. * @var mixed
  44. */
  45. protected $uploadUrl;
  46. /**
  47. * 存储空间名称 公开空间
  48. * @var mixed
  49. */
  50. protected $storageName;
  51. /**
  52. * COS使用 所属地域
  53. * @var mixed|null
  54. */
  55. protected $storageRegion;
  56. /**
  57. * 水印位置
  58. * @var string[]
  59. */
  60. protected $position = [
  61. '1' => 'nw',//:左上
  62. '2' => 'north',//:中上
  63. '3' => 'ne',//:右上
  64. '4' => 'west',//:左中
  65. '5' => 'center',//:中部
  66. '6' => 'east',//:右中
  67. '7' => 'sw',//:左下
  68. '8' => 'south',//:中下
  69. '9' => 'se',//:右下
  70. ];
  71. /**
  72. * 初始化
  73. * @param array $config
  74. * @return mixed|void
  75. */
  76. protected function initialize(array $config)
  77. {
  78. parent::initialize($config);
  79. $this->accessKey = $config['accessKey'] ?? null;
  80. $this->secretKey = $config['secretKey'] ?? null;
  81. $this->uploadUrl = $this->checkUploadUrl($config['uploadUrl'] ?? '');
  82. $this->storageName = $config['storageName'] ?? null;
  83. $this->storageRegion = $config['storageRegion'] ?? null;
  84. }
  85. /**
  86. * 初始化oss
  87. * @return OssClient
  88. * @throws OssException
  89. */
  90. protected function app()
  91. {
  92. if (!$this->accessKey || !$this->secretKey) {
  93. throw new UploadException('Please configure accessKey and secretKey');
  94. }
  95. $this->handle = new OssClient($this->accessKey, $this->secretKey, $this->storageRegion);
  96. //不再自动创建
  97. // if (!$this->handle->doesBucketExist($this->storageName)) {
  98. // $this->handle->createBucket($this->storageName, OssClient::OSS_ACL_TYPE_PUBLIC_READ_WRITE);
  99. // }
  100. return $this->handle;
  101. }
  102. /**
  103. * 上传文件
  104. * @param string $file
  105. * @return array|bool|mixed|\StdClass
  106. */
  107. public function move(string $file = 'file')
  108. {
  109. $fileHandle = app()->request->file($file);
  110. if (!$fileHandle) {
  111. return $this->setError('Upload file does not exist');
  112. }
  113. if ($this->validate) {
  114. try {
  115. $error = [
  116. $file . '.filesize' => 'Upload filesize error',
  117. $file . '.fileExt' => 'Upload fileExt error',
  118. $file . '.fileMime' => 'Upload fileMine error'
  119. ];
  120. validate([$file => $this->validate], $error)->check([$file => $fileHandle]);
  121. } catch (ValidateException $e) {
  122. return $this->setError($e->getMessage());
  123. }
  124. }
  125. $key = $this->saveFileName($fileHandle->getRealPath(), $fileHandle->getOriginalExtension());
  126. $key = $this->getUploadPath($key);
  127. try {
  128. $uploadInfo = $this->app()->putObject($this->storageName, $key, file_get_contents($fileHandle->getRealPath()));
  129. if (!isset($uploadInfo['info']['url'])) {
  130. return $this->setError('Upload failure');
  131. }
  132. $this->fileInfo->uploadInfo = $uploadInfo;
  133. $this->fileInfo->realName = $fileHandle->getOriginalName();
  134. $this->fileInfo->filePath = $this->uploadUrl . '/' . $key;
  135. $this->fileInfo->fileName = $key;
  136. $this->fileInfo->filePathWater = $this->water($this->fileInfo->filePath);
  137. $this->authThumb && $this->thumb($this->fileInfo->filePath);
  138. return $this->fileInfo;
  139. } catch (UploadException $e) {
  140. return $this->setError($e->getMessage());
  141. }
  142. }
  143. /**
  144. * 文件流上传
  145. * @param string $fileContent
  146. * @param string|null $key
  147. * @return bool|mixed
  148. */
  149. public function stream(string $fileContent, string $key = null)
  150. {
  151. try {
  152. if (!$key) {
  153. $key = $this->saveFileName();
  154. }
  155. $key = $this->getUploadPath($key);
  156. $fileContent = (string)Utils::streamFor($fileContent);
  157. $uploadInfo = $this->app()->putObject($this->storageName, $key, $fileContent);
  158. if (!isset($uploadInfo['info']['url'])) {
  159. return $this->setError('Upload failure');
  160. }
  161. $this->fileInfo->uploadInfo = $uploadInfo;
  162. $this->fileInfo->realName = $key;
  163. $this->fileInfo->filePath = $this->uploadUrl . '/' . $key;
  164. $this->fileInfo->fileName = $key;
  165. $this->fileInfo->filePathWater = $this->water($this->fileInfo->filePath);
  166. $this->authThumb && $this->thumb($this->fileInfo->filePath);
  167. return $this->fileInfo;
  168. } catch (UploadException $e) {
  169. return $this->setError($e->getMessage());
  170. }
  171. }
  172. /**
  173. * 缩略图
  174. * @param string $filePath
  175. * @param string $type
  176. * @return mixed|string[]
  177. */
  178. public function thumb(string $filePath = '', string $type = 'all')
  179. {
  180. $filePath = $this->getFilePath($filePath);
  181. $data = ['big' => $filePath, 'mid' => $filePath, 'small' => $filePath];
  182. $this->fileInfo->filePathBig = $this->fileInfo->filePathMid = $this->fileInfo->filePathSmall = $this->fileInfo->filePathWater = $filePath;
  183. if ($filePath) {
  184. $config = $this->thumbConfig;
  185. foreach ($this->thumb as $v) {
  186. if ($type == 'all' || $type == $v) {
  187. $height = 'thumb_' . $v . '_height';
  188. $width = 'thumb_' . $v . '_width';
  189. if (isset($config[$height]) && isset($config[$width]) && $config[$height] && $config[$width]) {
  190. $key = 'filePath' . ucfirst($v);
  191. $this->fileInfo->$key = $filePath . '?x-oss-process=image/resize,h_' . $config[$height] . ',w_' . $config[$width];
  192. $this->fileInfo->$key = $this->water($this->fileInfo->$key);
  193. $data[$v] = $this->fileInfo->$key;
  194. }
  195. }
  196. }
  197. }
  198. return $data;
  199. }
  200. /**
  201. * 水印
  202. * @param string $filePath
  203. * @return mixed|string
  204. */
  205. public function water(string $filePath = '')
  206. {
  207. $filePath = $this->getFilePath($filePath);
  208. $waterConfig = $this->waterConfig;
  209. $waterPath = $filePath;
  210. if ($waterConfig['image_watermark_status'] && $filePath) {
  211. if (strpos($filePath, '?x-oss-process') === false) {
  212. $filePath .= '?x-oss-process=image';
  213. }
  214. switch ($waterConfig['watermark_type']) {
  215. case 1://图片
  216. if (!$waterConfig['watermark_image']) {
  217. throw new ValidateException('请先配置水印图片');
  218. }
  219. $waterPath = $filePath .= '/watermark,image_' . base64_encode($waterConfig['watermark_image']) . ',t_' . $waterConfig['watermark_opacity'] . ',g_' . ($this->position[$waterConfig['watermark_position']] ?? 'nw') . ',x_' . $waterConfig['watermark_x'] . ',y_' . $waterConfig['watermark_y'];
  220. break;
  221. case 2://文字
  222. if (!$waterConfig['watermark_text']) {
  223. throw new ValidateException('请先配置水印文字');
  224. }
  225. $waterConfig['watermark_text_color'] = str_replace('#', '', $waterConfig['watermark_text_color']);
  226. $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'];
  227. break;
  228. }
  229. }
  230. return $waterPath;
  231. }
  232. /**
  233. * 获取视频封面图
  234. * @param string $filePath
  235. * @param string $type
  236. * @param int $time
  237. * @return array
  238. */
  239. public function videoCoverImage(string $filePath = '', string $type = 'all', int $time = 1)
  240. {
  241. $data = ['big' => $filePath, 'mid' => $filePath, 'small' => $filePath];
  242. $this->fileInfo->filePathBig = $this->fileInfo->filePathMid = $this->fileInfo->filePathSmall = $this->fileInfo->filePathWater = $filePath;
  243. if ($filePath) {
  244. //?x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast
  245. foreach ($this->thumb as $v) {
  246. if ($type == 'all' || $type == $v) {
  247. $height = 600;
  248. $width = 400;
  249. $key = 'filePath' . ucfirst($v);
  250. $this->fileInfo->$key = $filePath . '?x-oss-process=video/snapshot,t_' . ($time * 1000) . ',f_jpg,w_' . $width . ',h_' . $height . ',m_fast';
  251. $data[$v] = $this->fileInfo->$key;
  252. }
  253. }
  254. }
  255. return $data;
  256. }
  257. /**
  258. * 删除资源
  259. * @param $key
  260. * @return mixed
  261. */
  262. public function delete(string $key)
  263. {
  264. try {
  265. return $this->app()->deleteObject($this->storageName, $key);
  266. } catch (OssException $e) {
  267. return $this->setError($e->getMessage());
  268. }
  269. }
  270. /**
  271. * 获取OSS上传密钥
  272. * @return mixed|void
  273. */
  274. public function getTempKeys($callbackUrl = '', $dir = '')
  275. {
  276. //
  277. $base64CallbackBody = base64_encode(json_encode([
  278. 'callbackUrl' => $callbackUrl,
  279. 'callbackBody' => 'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}',
  280. 'callbackBodyType' => "application/x-www-form-urlencoded"
  281. ]));
  282. $policy = json_encode([
  283. 'expiration' => $this->gmtIso8601(time() + 30),
  284. 'conditions' =>
  285. [
  286. [0 => 'content-length-range', 1 => 0, 2 => 1048576000],
  287. [0 => 'starts-with', 1 => '$key', 2 => $dir]
  288. ]
  289. ]);
  290. $base64Policy = base64_encode($policy);
  291. $signature = base64_encode(hash_hmac('sha1', $base64Policy, $this->secretKey, true));
  292. return [
  293. 'accessid' => $this->accessKey,
  294. 'host' => $this->uploadUrl,
  295. 'policy' => $base64Policy,
  296. 'signature' => $signature,
  297. 'expire' => time() + 30,
  298. 'callback' => $base64CallbackBody,
  299. 'type' => 'OSS'
  300. ];
  301. }
  302. /**
  303. * 获取ISO时间格式
  304. * @param $time
  305. * @return string
  306. */
  307. protected function gmtIso8601($time)
  308. {
  309. $dtStr = date("c", $time);
  310. $mydatetime = new \DateTime($dtStr);
  311. $expiration = $mydatetime->format(\DateTime::ISO8601);
  312. $pos = strpos($expiration, '+');
  313. $expiration = substr($expiration, 0, $pos);
  314. return $expiration . "Z";
  315. }
  316. /**
  317. * 获取当前管理下的所有桶
  318. * @param string|null $region
  319. * @param bool $line
  320. * @param bool $shared
  321. * @return mixed|\OSS\Model\BucketListInfo
  322. * @throws OssException
  323. */
  324. public function listbuckets(string $region = 'oss-cn-hangzhou.aliyuncs.com', bool $line = false, bool $shared = false)
  325. {
  326. $handle = new OssClient($this->accessKey, $this->secretKey, $region);
  327. $response = $handle->listBuckets();
  328. $data = $response->getBucketList();
  329. $list = [];
  330. foreach ($data as $item) {
  331. $list[] = [
  332. 'location' => $item->getLocation(),
  333. 'name' => $item->getName(),
  334. 'createTime' => $item->getCreateDate()
  335. ];
  336. }
  337. return $list;
  338. }
  339. /**
  340. * @param string $name
  341. * @param string $region
  342. * @param string $acl
  343. * @return mixed|void
  344. */
  345. public function createBucket(string $name, string $region = '', string $acl = OssClient::OSS_ACL_TYPE_PUBLIC_READ)
  346. {
  347. $regionData = $this->getRegion();
  348. if (!in_array($region, array_column($regionData, 'value'))) {
  349. return $this->setError('OSS:无效的区域');
  350. }
  351. try {
  352. $handle = new OssClient($this->accessKey, $this->secretKey, $region);
  353. if ($handle->doesBucketExist($name)) {
  354. return $this->setError('OSS:空间已经存在,请更换空间名');
  355. }
  356. return $handle->createBucket($name, $acl);
  357. } catch (\Throwable $e) {
  358. if (strstr('The bucket you access does not belong to you', $e->getMessage())) {
  359. return $this->setError('OSS:空间已被使用,请更换空间名');
  360. }
  361. return $this->setError('OSS:' . $e->getMessage());
  362. }
  363. }
  364. /**
  365. * @param string $name
  366. * @param string $region
  367. * @return bool|mixed|null
  368. */
  369. public function deleteBucket(string $name, string $region = '')
  370. {
  371. try {
  372. $handle = new OssClient($this->accessKey, $this->secretKey, $region);
  373. return $handle->deleteBucket($name);
  374. } catch (\Throwable $e) {
  375. return $this->setError($e->getMessage());
  376. }
  377. }
  378. /**
  379. * @param string $name
  380. * @param string|null $region
  381. * @return array|bool
  382. */
  383. public function getDomian(string $name, string $region = null)
  384. {
  385. try {
  386. $handle = new OssClient($this->accessKey, $this->secretKey, $region);
  387. $res = $handle->getBucketCname($name);
  388. $data = $res->getCnames();
  389. return array_column($data, 'Domain');
  390. } catch (\Throwable $e) {
  391. }
  392. return [];
  393. }
  394. /**
  395. * 绑定域名
  396. * @param string $name
  397. * @param string $domain
  398. * @param string|null $region
  399. * @return bool|mixed
  400. */
  401. public function bindDomian(string $name, string $domain, string $region = null)
  402. {
  403. $parseDomin = parse_url($domain);
  404. try {
  405. $handle = new OssClient($this->accessKey, $this->secretKey, $region);
  406. $res = $handle->getBucketCname($name);
  407. $data = $res->getCnames();
  408. if (in_array($parseDomin['host'], array_column($data, 'Domain'))) {
  409. return true;
  410. }
  411. return $handle->addBucketCname($name, $parseDomin['host']);
  412. } catch (\Throwable $e) {
  413. return $this->setError($e->getMessage());
  414. }
  415. }
  416. /**
  417. * 设置跨域
  418. * @param string $name
  419. * @param string $region
  420. * @return bool|null
  421. */
  422. public function setBucketCors(string $name, string $region)
  423. {
  424. try {
  425. $handle = new OssClient($this->accessKey, $this->secretKey, $region);
  426. $corsConfig = new CorsConfig();
  427. $rule = new CorsRule();
  428. // 设置允许跨域请求的响应头。AllowedHeader可以设置多个,每个AllowedHeader中最多只能使用一个通配符星号(*)。
  429. // 建议无特殊需求时设置AllowedHeader为星号(*)。
  430. $rule->addAllowedHeader("*");
  431. // 设置允许用户从应用程序中访问的响应头。ExposeHeader可以设置多个,ExposeHeader中不支持使用通配符星号(*)。
  432. $rule->addExposeHeader("ETag");
  433. // 设置允许的跨域请求的来源。AllowedOrigin可以设置多个,每个AllowedOrigin中最多只能使用一个通配符星号(*)。
  434. // 设置AllowedOrigin为星号(*)时,表示允许所有域的来源。
  435. $rule->addAllowedOrigin("*");
  436. // 设置允许的跨域请求方法。
  437. $rule->addAllowedMethod("POST");
  438. $rule->addAllowedMethod("GET");
  439. $rule->addAllowedMethod("DELETE");
  440. $rule->addAllowedMethod("PUT");
  441. $rule->addAllowedMethod("HEAD");
  442. // 设置浏览器对特定资源的预取(OPTIONS)请求返回结果的缓存时间,单位为秒。
  443. $rule->setMaxAgeSeconds(600);
  444. // 每个Bucket最多支持添加10条规则。
  445. $corsConfig->addRule($rule);
  446. return $handle->putBucketCors($name, $corsConfig);
  447. } catch (\Throwable $e) {
  448. return $this->setError($e->getMessage());
  449. }
  450. }
  451. /**
  452. * 数据中心
  453. * @return mixed|\string[][]
  454. */
  455. public function getRegion()
  456. {
  457. return [
  458. [
  459. 'value' => 'oss-cn-hangzhou.aliyuncs.com',
  460. 'label' => '华东1(杭州)'
  461. ],
  462. [
  463. 'value' => 'oss-cn-shanghai.aliyuncs.com',
  464. 'label' => '华东2(上海)'
  465. ],
  466. [
  467. 'value' => 'oss-cn-qingdao.aliyuncs.com',
  468. 'label' => '华北1(青岛)'
  469. ],
  470. [
  471. 'value' => 'oss-cn-beijing.aliyuncs.com',
  472. 'label' => '华北2(北京)'
  473. ],
  474. [
  475. 'value' => 'oss-cn-zhangjiakou.aliyuncs.com',
  476. 'label' => '华北 3(张家口)'
  477. ],
  478. [
  479. 'value' => 'oss-cn-huhehaote.aliyuncs.com',
  480. 'label' => '华北5(呼和浩特)'
  481. ],
  482. [
  483. 'value' => 'oss-cn-wulanchabu.aliyuncs.com',
  484. 'label' => '华北6(乌兰察布)'
  485. ],
  486. [
  487. 'value' => 'oss-cn-shenzhen.aliyuncs.com',
  488. 'label' => '华南1(深圳)'
  489. ],
  490. [
  491. 'value' => 'oss-cn-heyuan.aliyuncs.com',
  492. 'label' => '华南2(河源)'
  493. ],
  494. [
  495. 'value' => 'oss-cn-guangzhou.aliyuncs.com',
  496. 'label' => '华南3(广州)'
  497. ],
  498. [
  499. 'value' => 'oss-cn-chengdu.aliyuncs.com',
  500. 'label' => '西南1(成都)'
  501. ],
  502. [
  503. 'value' => 'oss-cn-hongkong.aliyuncs.com',
  504. 'label' => '中国(香港)'
  505. ],
  506. [
  507. 'value' => 'oss-us-west-1.aliyuncs.com',
  508. 'label' => '美国(硅谷)*'
  509. ],
  510. [
  511. 'value' => 'oss-us-east-1.aliyuncs.com',
  512. 'label' => '美国(弗吉尼亚)*'
  513. ],
  514. [
  515. 'value' => 'oss-ap-southeast-1.aliyuncs.com',
  516. 'label' => '新加坡*'
  517. ],
  518. [
  519. 'value' => 'oss-ap-southeast-2.aliyuncs.com',
  520. 'label' => '澳大利亚(悉尼)*'
  521. ],
  522. [
  523. 'value' => 'oss-ap-southeast-3.aliyuncs.com',
  524. 'label' => '马来西亚(吉隆坡)*'
  525. ],
  526. [
  527. 'value' => 'oss-ap-southeast-5.aliyuncs.com',
  528. 'label' => '印度尼西亚(雅加达)*'
  529. ],
  530. [
  531. 'value' => 'oss-ap-northeast-1.aliyuncs.com',
  532. 'label' => '日本(东京)*'
  533. ],
  534. [
  535. 'value' => 'oss-ap-south-1.aliyuncs.com',
  536. 'label' => '印度(孟买)*'
  537. ],
  538. [
  539. 'value' => 'oss-eu-central-1.aliyuncs.com',
  540. 'label' => '德国(法兰克福)*'
  541. ],
  542. [
  543. 'value' => 'oss-eu-west-1.aliyuncs.com',
  544. 'label' => '英国(伦敦)'
  545. ],
  546. [
  547. 'value' => 'oss-me-east-1.aliyuncs.com',
  548. 'label' => '阿联酋(迪拜)*'
  549. ],
  550. [
  551. 'value' => 'oss-ap-southeast-6.aliyuncs.com',
  552. 'label' => '菲律宾(马尼拉)'
  553. ]
  554. ];
  555. }
  556. }