Obs.php 13 KB

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