Oss.php 20 KB

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