Obs.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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 Obs 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. * @var string
  44. */
  45. protected $cdn;
  46. /**
  47. * 水印位置
  48. * @var string[]
  49. */
  50. protected $position = [
  51. '1' => 'tl',//:左上
  52. '2' => 'top',//:中上
  53. '3' => 'tr',//:右上
  54. '4' => 'left',//:左中
  55. '5' => 'center',//:中部
  56. '6' => 'right',//:右中
  57. '7' => 'bl',//:左下
  58. '8' => 'bottom',//:中下
  59. '9' => 'br',//:右下
  60. ];
  61. /**
  62. * 上传图片
  63. * @param string $file
  64. * @param bool $isStream
  65. * @param string|null $fileContent
  66. * @return array|bool|mixed
  67. */
  68. public function move(string $file = 'file', bool $isStream = false, string $fileContent = null)
  69. {
  70. if (!$isStream) {
  71. $fileHandle = app()->request->file($file);
  72. if (!$fileHandle) {
  73. return $this->setError('上传的文件不存在');
  74. }
  75. if ($this->validate) {
  76. if (!in_array($fileHandle->getOriginalExtension(), $this->validate['fileExt'])) {
  77. return $this->setError('不合法的文件后缀:'.$fileHandle->getOriginalExtension());
  78. }
  79. if (filesize($fileHandle) > $this->validate['filesize']) {
  80. return $this->setError('文件过大');
  81. }
  82. if (!in_array($fileHandle->getOriginalMime(), $this->validate['fileMime'])) {
  83. return $this->setError('不合法的文件类型:'.$fileHandle->getOriginalMime());
  84. }
  85. }
  86. $key = $this->saveFileName($fileHandle->getRealPath(), $fileHandle->getOriginalExtension());
  87. $body = fopen($fileHandle->getRealPath(), 'rb');
  88. $body = (string)Utils::streamFor($body);
  89. } else {
  90. $key = $file;
  91. $body = $fileContent;
  92. }
  93. $key = $this->getUploadPath($key);
  94. try {
  95. $uploadInfo = $this->app()->putObject($key, $body, 'application/octet-stream');
  96. $this->fileInfo->uploadInfo = $uploadInfo;
  97. $this->fileInfo->realName = isset($fileHandle) ? $fileHandle->getOriginalName() : $key;
  98. $this->fileInfo->filePath = ($this->cdn ?: $this->uploadUrl) . '/' . $key;
  99. $this->fileInfo->fileName = $key;
  100. // $this->fileInfo->filePathWater = $this->water($this->fileInfo->filePath);
  101. // $this->authThumb && $this->thumb($this->fileInfo->filePath);
  102. return $this->fileInfo;
  103. } catch (\Throwable $e) {
  104. return $this->setError($e->getMessage());
  105. }
  106. }
  107. public function stream($fileContent, string $key = null)
  108. {
  109. if (!$key) {
  110. $key = $this->saveFileName();
  111. }
  112. return $this->move($key, true, $fileContent);
  113. }
  114. public function delete(string $filePath)
  115. {
  116. try {
  117. return $this->app()->deleteObject($filePath);
  118. } catch (\Exception $e) {
  119. return $this->setError($e->getMessage());
  120. }
  121. }
  122. /**
  123. * 初始化
  124. * @param array $config
  125. * @return mixed|void
  126. */
  127. public function initialize(array $config)
  128. {
  129. parent::initialize($config);
  130. $this->accessKey = $config['accessKey'] ?? null;
  131. $this->secretKey = $config['secretKey'] ?? null;
  132. $this->uploadUrl = $this->checkUploadUrl($config['uploadUrl'] ?? '');
  133. $this->storageName = $config['storageName'] ?? null;
  134. $this->storageRegion = $config['storageRegion'] ?? null;
  135. $this->cdn = $config['cdn'] ?? null;
  136. $this->waterConfig['watermark_text_font'] = 'simfang仿宋.ttf';
  137. }
  138. /**
  139. * 实例化cos
  140. * @return TyClient
  141. */
  142. protected function app()
  143. {
  144. if (!$this->accessKey || !$this->secretKey) {
  145. throw new UploadException('请填写存储配置或者更换存储方式');
  146. }
  147. $this->handle = new TyClient([
  148. 'accessKey' => $this->accessKey,
  149. 'secretKey' => $this->secretKey,
  150. 'region' => $this->storageRegion ?: 'cn-north-1',
  151. 'bucket' => $this->storageName,
  152. 'uploadUrl' => $this->uploadUrl
  153. ]);
  154. return $this->handle;
  155. }
  156. public function listbuckets(string $region = null, bool $line = false, bool $shared = false)
  157. {
  158. try {
  159. $res = $this->app()->listBuckets();
  160. return $res['Buckets']['Bucket'] ?? [];
  161. } catch (\Throwable $e) {
  162. return [];
  163. }
  164. }
  165. public function createBucket(string $name, string $region, string $acl = TyClient::DEFAULT_OBS_ACL)
  166. {
  167. $regionData = $this->getRegion();
  168. $regionData = array_column($regionData, 'value');
  169. if (!in_array($region, $regionData)) {
  170. return $this->setError('COS:无效的区域!');
  171. }
  172. $this->storageRegion = $region;
  173. $app = $this->app();
  174. //创建桶
  175. try {
  176. $app->createBucket($name, $region, $acl);
  177. $data = [
  178. 'Statement' => [
  179. 'Sid' => '公共读' . $name,
  180. 'Effect' => 'Allow',
  181. 'Principal' => [
  182. 'ID' => ['*']
  183. ],
  184. 'Action' => ['HeadBucket', 'GetBucketLocation', 'ListBucketVersions', 'GetObject', 'RestoreObject', 'GetObjectVersion'],
  185. 'Resource' => [$name, $name . '/*']
  186. ]
  187. ];
  188. $app->putPolicy($name, $region, $data);
  189. } catch (\Throwable $e) {
  190. return $this->setError('COS:' . $e->getMessage());
  191. }
  192. return true;
  193. }
  194. public function getRegion()
  195. {
  196. return $this->app()->getRegion();
  197. }
  198. public function deleteBucket(string $name, string $region = '')
  199. {
  200. try {
  201. $this->app()->deleteBucket($name, $region);
  202. return true;
  203. } catch (\Throwable $e) {
  204. return $this->setError($e->getMessage());
  205. }
  206. }
  207. public function getDomian($name, $region)
  208. {
  209. try {
  210. $res = $this->app()->getBucketDomain($name, $region);
  211. if ($res) {
  212. $domainRules = $res->toArray()['ListBucketCustomDomainsResult'];
  213. return array_column($domainRules, 'DomainName');
  214. } else {
  215. return [];
  216. }
  217. } catch (\Throwable $e) {
  218. }
  219. return [];
  220. }
  221. public function bindDomian(string $name, string $domain, string $region = null)
  222. {
  223. $parseDomin = parse_url($domain);
  224. try {
  225. $this->app()->putBucketDomain($name, $region, [
  226. 'domainname' => $parseDomin['host'],
  227. ]);
  228. return true;
  229. } catch (\Throwable $e) {
  230. return $this->setError($e->getMessage());
  231. }
  232. }
  233. public function setBucketCors(string $name, string $region)
  234. {
  235. try {
  236. $this->app()->putBucketCors($name, $region, [
  237. 'AllowedHeader' => ['*'],
  238. 'AllowedMethod' => ['PUT', 'GET', 'POST', 'DELETE', 'HEAD'],
  239. 'AllowedOrigin' => ['*'],
  240. 'ExposeHeader' => ['ETag'],
  241. 'MaxAgeSeconds' => 0
  242. ]);
  243. return true;
  244. } catch (\Throwable $e) {
  245. return $this->setError($e->getMessage());
  246. }
  247. }
  248. /**
  249. * @return array
  250. * @date 2023/6/13
  251. */
  252. public function getTempKeys($callbackUrl = '', $dir = '')
  253. {
  254. // return [
  255. // 'access_key' => $this->accessKey,
  256. // 'secret_key' => $this->secretKey,
  257. // 'type' => 'OBS'
  258. // ];
  259. // TODO: Implement getTempKeys() method.
  260. $base64CallbackBody = base64_encode(json_encode([
  261. 'callbackUrl' => $callbackUrl,
  262. 'callbackBody' => 'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}',
  263. 'callbackBodyType' => "application/x-www-form-urlencoded"
  264. ]));
  265. $policy = json_encode([
  266. 'expiration' => $this->gmtIso8601(time() + 300),
  267. 'conditions' =>
  268. [
  269. [0 => 'content-length-range', 1 => 0, 2 => 1048576000],
  270. ['bucket' => $this->storageName],
  271. [0 => 'starts-with', 1 => '$key', 2 => $dir],
  272. ]
  273. ]);
  274. $base64Policy = base64_encode($policy);
  275. $signature = base64_encode(hash_hmac('sha1', $base64Policy, $this->secretKey, true));
  276. return [
  277. 'accessid' => $this->accessKey,
  278. 'host' => $this->uploadUrl,
  279. 'policy' => $base64Policy,
  280. 'signature' => $signature,
  281. 'expire' => time() + 30,
  282. 'callback' => $base64CallbackBody,
  283. 'cdn' => $this->cdn,
  284. 'type' => 'OBS'
  285. ];
  286. }
  287. /**
  288. * 获取ISO时间格式
  289. * @param $time
  290. * @return string
  291. * @throws \Exception
  292. */
  293. protected function gmtIso8601($time): string
  294. {
  295. $dtStr = date("c", $time);
  296. $myDateTime = new \DateTime($dtStr);
  297. $expiration = $myDateTime->format(DateTimeInterface::ISO8601);
  298. $pos = strpos($expiration, '+');
  299. $expiration = substr($expiration, 0, $pos);
  300. return $expiration . "Z";
  301. }
  302. /**
  303. * 缩略图
  304. * @param string $filePath
  305. * @param string $fileName
  306. * @param string $type
  307. * @return array|mixed
  308. */
  309. public function thumb(string $filePath = '', string $fileName = '', string $type = 'all')
  310. {
  311. $filePath = $this->getFilePath($filePath);
  312. $data = ['big' => $filePath, 'mid' => $filePath, 'small' => $filePath];
  313. $this->fileInfo->filePathBig = $this->fileInfo->filePathMid = $this->fileInfo->filePathSmall = $this->fileInfo->filePathWater = $filePath;
  314. if ($filePath) {
  315. $config = $this->thumbConfig;
  316. foreach ($this->thumb as $v) {
  317. if ($type == 'all' || $type == $v) {
  318. $height = 'thumb_' . $v . '_height';
  319. $width = 'thumb_' . $v . '_width';
  320. $key = 'filePath' . ucfirst($v);
  321. // if (systemConfig('image_thumbnail_status') && isset($config[$height]) && isset($config[$width])) {
  322. if (isset($config[$height]) && isset($config[$width])) {
  323. if (!strpos($filePath, '?x-oss-process')) {
  324. $this->fileInfo->$key = $filePath . '?x-oss-process=image/resize,h_' . $config[$height] . ',w_' . $config[$width];
  325. }
  326. $this->fileInfo->$key = $this->water($this->fileInfo->$key);
  327. $data[$v] = $this->fileInfo->$key;
  328. } else {
  329. $this->fileInfo->$key = $this->water($this->fileInfo->$key);
  330. $data[$v] = $this->fileInfo->$key;
  331. }
  332. }
  333. }
  334. }
  335. return $data;
  336. }
  337. /**
  338. * 水印
  339. * @param string $filePath
  340. * @return mixed|string
  341. */
  342. public function water(string $filePath = '')
  343. {
  344. $filePath = $this->getFilePath($filePath);
  345. $waterConfig = $this->waterConfig;
  346. $waterPath = $filePath;
  347. if ($waterConfig['image_watermark_status'] && $filePath) {
  348. if (strpos($filePath, '?x-oss-process') === false) {
  349. $filePath .= ',x-image-process=image';
  350. }
  351. switch ($waterConfig['watermark_type']) {
  352. case 1://图片
  353. if (!$waterConfig['watermark_image']) {
  354. throw new AdminException(400722);
  355. }
  356. // 华为入参格式:filename.jpg
  357. $waterFileName = substr(parse_url($waterConfig['watermark_image'],PHP_URL_PATH), 1);
  358. $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'];
  359. break;
  360. case 2://文字
  361. if (!$waterConfig['watermark_text']) {
  362. throw new AdminException(400723);
  363. }
  364. $waterConfig['watermark_text_color'] = str_replace('#', '', $waterConfig['watermark_text_color']);
  365. $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'];
  366. break;
  367. }
  368. }
  369. return $waterPath;
  370. }
  371. }