Obs.php 12 KB

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