Oss.php 20 KB

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