Qiniu.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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 Qiniu\Auth;
  16. use Qiniu\Http\Client;
  17. use Qiniu\Http\Error;
  18. use Qiniu\Storage\BucketManager;
  19. use Qiniu\Storage\UploadManager;
  20. use Qiniu\Config;
  21. use think\exception\ValidateException;
  22. /**
  23. * 七牛云上传
  24. * Class Qiniu
  25. */
  26. class Qiniu 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 object
  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' => 'NorthWest',//:左上
  64. '2' => 'North',//:中上
  65. '3' => 'NorthEast',//:右上
  66. '4' => 'West',//:左中
  67. '5' => 'Center',//:中部
  68. '6' => 'East',//:右中
  69. '7' => 'SouthWest',//:左下
  70. '8' => 'South',//:中下
  71. '9' => 'SouthEast',//:右下
  72. ];
  73. /**
  74. * @var string
  75. */
  76. protected $cdn;
  77. /**
  78. * 初始化
  79. * @param array $config
  80. * @return mixed|void
  81. */
  82. public 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. * 实例化七牛云
  94. * @return object|Auth
  95. */
  96. protected function app()
  97. {
  98. if (!$this->accessKey || !$this->secretKey) {
  99. throw new UploadException('请填写存储配置或者更换存储方式');
  100. }
  101. $this->handle = new Auth($this->accessKey, $this->secretKey);
  102. return $this->handle;
  103. }
  104. /**
  105. * 上传文件
  106. * @param string $file
  107. * @param bool $realName
  108. * @return array|bool|mixed|\StdClass|string
  109. */
  110. public function move(string $file = 'file', $realName = false)
  111. {
  112. $fileHandle = app()->request->file($file);
  113. if (!$fileHandle) {
  114. return $this->setError('上传的文件不存在');
  115. }
  116. if ($this->validate) {
  117. if (!in_array($fileHandle->getOriginalExtension(), $this->validate['fileExt'])) {
  118. return $this->setError('不合法的文件后缀:'.$fileHandle->getOriginalExtension());
  119. }
  120. if (filesize($fileHandle) > $this->validate['filesize']) {
  121. return $this->setError('文件过大');
  122. }
  123. if (!in_array($fileHandle->getOriginalMime(), $this->validate['fileMime'])) {
  124. return $this->setError('不合法的文件类型:'.$fileHandle->getOriginalMime());
  125. }
  126. }
  127. $key = $this->saveFileName($fileHandle->getRealPath(), $fileHandle->getOriginalExtension());
  128. $key = $this->getUploadPath($key);
  129. $token = $this->app()->uploadToken($this->storageName);
  130. try {
  131. $uploadMgr = new UploadManager();
  132. [$result, $error] = $uploadMgr->putFile($token, $key, $fileHandle->getRealPath());
  133. if ($error !== null) {
  134. return $this->setError($error->message());
  135. }
  136. $this->fileInfo->uploadInfo = $result;
  137. $this->fileInfo->realName = isset($fileHandle) ? $fileHandle->getOriginalName() : $key;
  138. $this->fileInfo->filePath = $this->uploadUrl . '/' . $key;
  139. $this->fileInfo->fileName = $key;
  140. return $this->fileInfo;
  141. } catch (UploadException $e) {
  142. return $this->setError($e->getMessage());
  143. }
  144. }
  145. /**
  146. * 文件流上传
  147. * @param $fileContent
  148. * @param string|null $key
  149. * @return array|bool|mixed|\StdClass
  150. */
  151. public function stream($fileContent, string $key = null)
  152. {
  153. if (!$key) {
  154. $key = $this->saveFileName();
  155. }
  156. $key = $this->getUploadPath($key);
  157. $token = $this->app()->uploadToken($this->storageName, $key);
  158. try {
  159. $uploadMgr = new UploadManager();
  160. [$result, $error] = $uploadMgr->put($token, $key, $fileContent);
  161. if ($error !== null) {
  162. return $this->setError($error->message());
  163. }
  164. $this->fileInfo->uploadInfo = $result;
  165. $this->fileInfo->realName = $key;
  166. $this->fileInfo->filePath = trim(($this->cdn ?: $this->uploadUrl),'/') . '/'.$key;
  167. $this->fileInfo->fileName = $key;
  168. // $this->fileInfo->filePathWater = $this->water($this->fileInfo->filePath);
  169. // $this->thumb($this->fileInfo->filePath);
  170. return $this->fileInfo;
  171. } catch (UploadException $e) {
  172. return $this->setError($e->getMessage());
  173. }
  174. }
  175. /**
  176. * 缩略图
  177. * @param string $filePath
  178. * @param string $fileName
  179. * @param string $type
  180. * @return array|mixed
  181. */
  182. public function thumb(string $filePath = '', string $fileName = '', string $type = 'all')
  183. {
  184. $filePath = $this->getFilePath($filePath);
  185. $data = ['big' => $filePath, 'mid' => $filePath, 'small' => $filePath];
  186. $this->fileInfo->filePathBig = $this->fileInfo->filePathMid = $this->fileInfo->filePathSmall = $this->fileInfo->filePathWater = $filePath;
  187. if ($filePath) {
  188. $config = $this->thumbConfig;
  189. foreach ($this->thumb as $v) {
  190. if ($type == 'all' || $type == $v) {
  191. $height = 'thumb_' . $v . '_height';
  192. $width = 'thumb_' . $v . '_width';
  193. $key = 'filePath' . ucfirst($v);
  194. // if (systemConfig('image_thumbnail_status') && isset($config[$height]) && isset($config[$width])) {
  195. if (isset($config[$height]) && isset($config[$width])) {
  196. if (!strpos($filePath, '?watermark')) {
  197. $this->fileInfo->$key = $filePath . '?imageView2/2/w/' . $config[$width] . '/h/' . $config[$height];
  198. }
  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. $waterConfig = $this->waterConfig;
  218. $waterPath = $filePath;
  219. if ($waterConfig['image_watermark_status'] && $filePath) {
  220. if (strpos($filePath, '?') === false) {
  221. $filePath .= '?watermark';
  222. } else {
  223. $filePath .= '|watermark';
  224. }
  225. switch ($waterConfig['watermark_type']) {
  226. case 1://图片
  227. if (!$waterConfig['watermark_image']) {
  228. throw new AdminException('请上传水印图');
  229. }
  230. $waterPath = $filePath .= '/1/image/' . base64_encode($waterConfig['watermark_image']) . '/gravity/' . ($this->position[$waterConfig['watermark_position']] ?? 'SouthEest') . '/dissolve/' . $waterConfig['watermark_opacity'] . '/dx/' . $waterConfig['watermark_x'] . '/dy/' . $waterConfig['watermark_y'];
  231. break;
  232. case 2://文字
  233. if (!$waterConfig['watermark_text']) {
  234. throw new AdminException('请填写水印文字');
  235. }
  236. $fontSize = $waterConfig['watermark_text_size'] / 72 * 20 * 240;
  237. $waterPath = $filePath .= '/2/text/' . base64_encode($waterConfig['watermark_text']) . '/fill/' . base64_encode($waterConfig['watermark_text_color']) . '/fontsize/' . floor($fontSize) . '/dissolve/' . $waterConfig['watermark_opacity'] . '/gravity/' . ($this->position[$waterConfig['watermark_position']] ?? 'SouthEest') . '/dx/' . $waterConfig['watermark_x'] . '/dy/' . $waterConfig['watermark_y'];
  238. break;
  239. }
  240. }
  241. return $waterPath;
  242. }
  243. /**
  244. * 获取上传配置信息
  245. * @return array
  246. */
  247. public function getSystem()
  248. {
  249. $token = $this->app()->uploadToken($this->storageName);
  250. $domain = $this->uploadUrl;
  251. $key = $this->saveFileName();
  252. return compact('token', 'domain', 'key');
  253. }
  254. /**
  255. * 删除资源
  256. * @param $key
  257. * @param $bucket
  258. * @return mixed
  259. */
  260. public function delete(string $key)
  261. {
  262. $bucketManager = new BucketManager($this->app(), new Config());
  263. return $bucketManager->delete($this->storageName, $key);
  264. }
  265. /**
  266. * 获取七牛云上传密钥
  267. * @return mixed|string
  268. */
  269. public function getTempKeys()
  270. {
  271. $token = $this->app()->uploadToken($this->storageName);
  272. $domain = $this->uploadUrl;
  273. $cdn = $this->cdn;
  274. $key = $this->saveFileName(NULL, 'mp4');
  275. $type = 'QINIU';
  276. return compact('token', 'domain', 'key', 'type', 'cdn');
  277. }
  278. /**
  279. * 获取当前所有桶列表
  280. * @param string|null $region
  281. * @param bool $line
  282. * @param bool $shared
  283. * @return bool|mixed
  284. */
  285. public function listbuckets(string $region = null, bool $line = false, bool $shared = false)
  286. {
  287. $bucket = new BucketManager($this->app());
  288. [$response, $error] = $bucket->listbuckets($region, $line ? 'true' : 'false', $shared ? 'true' : 'false');
  289. if ($error !== null) {
  290. return $this->setError($error->message());
  291. }
  292. return $response;
  293. }
  294. /**
  295. * @param string $name
  296. * @param string $region
  297. * @return bool|mixed
  298. */
  299. public function createBucket(string $name, string $region = 'z0')
  300. {
  301. $regionData = $this->getRegion();
  302. if (!in_array($region, array_column($regionData, 'value'))) {
  303. return $this->setError('七牛云:无效的区域');
  304. }
  305. $url = 'https://' . Config::UC_HOST . '/mkbucketv3/' . $name . '/region/' . $region;
  306. $body = null;
  307. $headers = $this->app()->authorizationV2($url, 'POST', $body, 'application/json');
  308. $headers["Content-Type"] = 'application/json';
  309. $ret = Client::post($url, $body, $headers);
  310. if (!$ret->ok()) {
  311. $error = new Error($url, $ret);
  312. if ('bucket exists' === $error->message()) {
  313. return $this->setError('七牛云:云空间已存在,请尝试其他名称');
  314. }
  315. return $this->setError('七牛云:' . $error->message());
  316. }
  317. return ($ret->body === null) ? array() : $ret->json();
  318. }
  319. /**
  320. * 获取区域
  321. * @return mixed|\string[][]
  322. */
  323. public function getRegion()
  324. {
  325. return [
  326. [
  327. 'value' => 'z0',
  328. 'label' => '华东'
  329. ],
  330. [
  331. 'value' => 'z1',
  332. 'label' => '华北'
  333. ],
  334. [
  335. 'value' => 'z2',
  336. 'label' => '华南'
  337. ],
  338. [
  339. 'value' => 'na0',
  340. 'label' => '北美'
  341. ],
  342. [
  343. 'value' => 'as0',
  344. 'label' => '东南亚'
  345. ],
  346. [
  347. 'value' => 'cn-east-2',
  348. 'label' => '华东-浙江2'
  349. ],
  350. ];
  351. }
  352. /**
  353. * 删除空间
  354. * @param string $name
  355. * @return bool|mixed
  356. */
  357. public function deleteBucket(string $name)
  358. {
  359. $bucket = new BucketManager($this->app());
  360. [$response, $error] = $bucket->deleteBucket($name);
  361. if ($error !== null) {
  362. return $this->setError($error->message());
  363. }
  364. return $response;
  365. }
  366. /**
  367. * 获取七牛域名
  368. * @param string $name
  369. * @return array|bool|mixed|null
  370. */
  371. public function getDomian(string $name)
  372. {
  373. $url = 'https://' . Config::UC_HOST . '/v2/domains?tbl=' . $name;
  374. $body = null;
  375. $headers = $this->app()->authorizationV2($url, 'POST', $body, 'application/x-www-form-urlencoded');
  376. $headers["Content-Type"] = 'application/x-www-form-urlencoded';
  377. $ret = Client::post($url, $body, $headers);
  378. if (!$ret->ok()) {
  379. $error = new Error($url, $ret);
  380. return $this->setError('七牛云:' . $error->message());
  381. }
  382. return ($ret->body === null) ? array() : $ret->json();
  383. }
  384. public function getDomianInfo(string $host)
  385. {
  386. $url = 'https://' . Config::API_HOST . '/domain/' . $host;
  387. $headers = $this->app()->authorization($url, null, 'application/x-www-form-urlencoded');
  388. $headers["Content-Type"] = 'application/x-www-form-urlencoded';
  389. $ret = Client::get($url, $headers);
  390. if (!$ret->ok()) {
  391. $error = new Error($url, $ret);
  392. return $this->setError('七牛云:' . $error->message());
  393. }
  394. return ($ret->body === null) ? array() : $ret->json();
  395. }
  396. /**
  397. *
  398. * @param string $name
  399. * @param string $domain
  400. * @param string|null $region
  401. * @return array|bool|mixed|null
  402. */
  403. public function bindDomian(string $name, string $domain, string $region = null)
  404. {
  405. $parseDomin = parse_url($domain);
  406. $url = 'https://' . Config::API_HOST . '/domain/' . $parseDomin['host'];
  407. $body = [
  408. 'type' => 'normal',
  409. 'platform' => 'web',
  410. 'geocover' => 'china',
  411. 'source' => [
  412. 'sourceType' => 'qiniuBucket',
  413. 'sourceQiniuBucket' => $name,
  414. 'TestURLPath' => 'qiniu_do_not_delete.gif',
  415. ],
  416. 'protocol' => $parseDomin['scheme'],
  417. 'cache' => [
  418. 'cacheControls' => [
  419. [
  420. 'time' => 1,
  421. 'timeunit' => 4,
  422. 'type' => 'all',
  423. 'rule' => '*'
  424. ]
  425. ],
  426. 'ignoreParam' => false
  427. ]
  428. ];
  429. $bodyJson = json_encode($body);
  430. $headers = $this->app()->authorization($url, $bodyJson, 'application/json');
  431. $headers["Content-Type"] = 'application/json';
  432. $ret = Client::post($url, $bodyJson, $headers);
  433. if (!$ret->ok()) {
  434. $error = new Error($url, $ret);
  435. return $this->setError('七牛云:' . $error->message());
  436. }
  437. return ($ret->body === null) ? array() : $ret->json();
  438. }
  439. /**
  440. * 跨域
  441. * @param string $name
  442. * @param string $region
  443. * @return bool
  444. */
  445. public function setBucketCors(string $name, string $region)
  446. {
  447. return true;
  448. }
  449. }