Qiniu.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 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\basic\BaseUpload;
  13. use crmeb\exceptions\UploadException;
  14. use crmeb\services\HttpService;
  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. * 初始化
  75. * @param array $config
  76. * @return mixed|void
  77. */
  78. public function initialize(array $config)
  79. {
  80. parent::initialize($config);
  81. $this->accessKey = $config['accessKey'] ?? null;
  82. $this->secretKey = $config['secretKey'] ?? null;
  83. $this->uploadUrl = $this->checkUploadUrl($config['uploadUrl'] ?? '');
  84. $this->storageName = $config['storageName'] ?? null;
  85. $this->storageRegion = $config['storageRegion'] ?? null;
  86. }
  87. /**
  88. * 实例化七牛云
  89. * @return object|Auth
  90. */
  91. protected function app()
  92. {
  93. if (!$this->accessKey || !$this->secretKey) {
  94. throw new UploadException('Please configure accessKey and secretKey');
  95. }
  96. $this->handle = new Auth($this->accessKey, $this->secretKey);
  97. return $this->handle;
  98. }
  99. /**
  100. * 上传文件
  101. * @param string $file
  102. * @return array|bool|mixed|\StdClass|string
  103. */
  104. public function move(string $file = 'file')
  105. {
  106. $fileHandle = app()->request->file($file);
  107. if (!$fileHandle) {
  108. return $this->setError('Upload file does not exist');
  109. }
  110. if ($this->validate) {
  111. try {
  112. $error = [
  113. $file . '.filesize' => 'Upload filesize error',
  114. $file . '.fileExt' => 'Upload fileExt error',
  115. $file . '.fileMime' => 'Upload fileMine error'
  116. ];
  117. validate([$file => $this->validate], $error)->check([$file => $fileHandle]);
  118. } catch (ValidateException $e) {
  119. return $this->setError($e->getMessage());
  120. }
  121. }
  122. $key = $this->saveFileName($fileHandle->getRealPath(), $fileHandle->getOriginalExtension());
  123. $key = $this->getUploadPath($key);
  124. $token = $this->app()->uploadToken($this->storageName);
  125. try {
  126. $uploadMgr = new UploadManager();
  127. [$result, $error] = $uploadMgr->putFile($token, $key, $fileHandle->getRealPath());
  128. if ($error !== null) {
  129. return $this->setError($error->message());
  130. }
  131. $this->fileInfo->uploadInfo = $result;
  132. $this->fileInfo->realName = $fileHandle->getOriginalName();
  133. $this->fileInfo->filePath = $this->uploadUrl . '/' . $key;
  134. $this->fileInfo->fileName = $key;
  135. $this->fileInfo->filePathWater = $this->water($this->fileInfo->filePath);
  136. $this->authThumb && $this->thumb($this->fileInfo->filePath);
  137. return $this->fileInfo;
  138. } catch (UploadException $e) {
  139. return $this->setError($e->getMessage());
  140. }
  141. }
  142. /**
  143. * 文件流上传
  144. * @param string $fileContent
  145. * @param string|null $key
  146. * @return array|bool|mixed|\StdClass
  147. */
  148. public function stream(string $fileContent, string $key = null)
  149. {
  150. if (!$key) {
  151. $key = $this->saveFileName();
  152. }
  153. $key = $this->getUploadPath($key);
  154. $token = $this->app()->uploadToken($this->storageName, $key);
  155. try {
  156. $uploadMgr = new UploadManager();
  157. [$result, $error] = $uploadMgr->put($token, $key, $fileContent);
  158. if ($error !== null) {
  159. return $this->setError($error->message());
  160. }
  161. $this->fileInfo->uploadInfo = $result;
  162. $this->fileInfo->realName = $key;
  163. $this->fileInfo->filePath = $this->uploadUrl . '/' . $key;
  164. $this->fileInfo->fileName = $key;
  165. $this->fileInfo->filePathWater = $this->water($this->fileInfo->filePath);
  166. $this->authThumb && $this->thumb($this->fileInfo->filePath);
  167. return $this->fileInfo;
  168. } catch (UploadException $e) {
  169. return $this->setError($e->getMessage());
  170. }
  171. }
  172. /**
  173. * 缩略图
  174. * @param string $filePath
  175. * @param string $type
  176. * @return mixed|string[]
  177. */
  178. public function thumb(string $filePath = '', string $type = 'all')
  179. {
  180. $filePath = $this->getFilePath($filePath);
  181. $data = ['big' => $filePath, 'mid' => $filePath, 'small' => $filePath];
  182. $this->fileInfo->filePathBig = $this->fileInfo->filePathMid = $this->fileInfo->filePathSmall = $this->fileInfo->filePathWater = $filePath;
  183. if ($filePath) {
  184. $config = $this->thumbConfig;
  185. foreach ($this->thumb as $v) {
  186. if ($type == 'all' || $type == $v) {
  187. $height = 'thumb_' . $v . '_height';
  188. $width = 'thumb_' . $v . '_width';
  189. if (isset($config[$height]) && isset($config[$width]) && $config[$height] && $config[$width]) {
  190. $key = 'filePath' . ucfirst($v);
  191. $this->fileInfo->$key = $filePath . '?imageView2/2/w/' . $config[$width] . '/h/' . $config[$height];
  192. $this->fileInfo->$key = $this->water($this->fileInfo->$key);
  193. $data[$v] = $this->fileInfo->$key;
  194. }
  195. }
  196. }
  197. }
  198. return $data;
  199. }
  200. /**
  201. * 水印
  202. * @param string $filePath
  203. * @return mixed|string
  204. */
  205. public function water(string $filePath = '')
  206. {
  207. $filePath = $this->getFilePath($filePath);
  208. $waterConfig = $this->waterConfig;
  209. $waterPath = $filePath;
  210. if ($waterConfig['image_watermark_status'] && $filePath) {
  211. if (strpos($filePath, '?') === false) {
  212. $filePath .= '?watermark';
  213. } else {
  214. $filePath .= '&watermark';
  215. }
  216. switch ($waterConfig['watermark_type']) {
  217. case 1://图片
  218. if (!$waterConfig['watermark_image']) {
  219. throw new ValidateException('请先配置水印图片');
  220. }
  221. $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'];
  222. break;
  223. case 2://文字
  224. if (!$waterConfig['watermark_text']) {
  225. throw new ValidateException('请先配置水印文字');
  226. }
  227. $waterPath = $filePath .= '/2/text/' . base64_encode($waterConfig['watermark_text']) . '/fill/' . base64_encode($waterConfig['watermark_text_color']) . '/fontsize/' . $waterConfig['watermark_text_size'] . '/gravity/' . ($this->position[$waterConfig['watermark_position']] ?? 'SouthEest') . '/dx/' . $waterConfig['watermark_x'] . '/dy/' . $waterConfig['watermark_y'];
  228. break;
  229. }
  230. }
  231. return $waterPath;
  232. }
  233. /**
  234. * 获取视频封面图
  235. * @param string $filePath
  236. * @param string $type
  237. * @param int $time
  238. * @return array
  239. */
  240. public function videoCoverImage(string $filePath = '', string $type = 'all', int $time = 1)
  241. {
  242. $data = ['big' => $filePath, 'mid' => $filePath, 'small' => $filePath];
  243. $this->fileInfo->filePathBig = $this->fileInfo->filePathMid = $this->fileInfo->filePathSmall = $this->fileInfo->filePathWater = $filePath;
  244. if ($filePath) {
  245. //?fops=vframe/jpg/offset/7/w/480/h/360
  246. foreach ($this->thumb as $v) {
  247. if ($type == 'all' || $type == $v) {
  248. $height = 600;
  249. $width = 400;
  250. $key = 'filePath' . ucfirst($v);
  251. $this->fileInfo->$key = $filePath . '?fops=vframe/jpg/offset/' . $time . '/w/' . $width . '/h/' . $height;
  252. $data[$v] = $this->fileInfo->$key;
  253. }
  254. }
  255. }
  256. return $data;
  257. }
  258. /**
  259. * 获取上传配置信息
  260. * @return array
  261. */
  262. public function getSystem()
  263. {
  264. $token = $this->app()->uploadToken($this->storageName);
  265. $domain = $this->uploadUrl;
  266. $key = $this->saveFileName();
  267. return compact('token', 'domain', 'key');
  268. }
  269. /**
  270. * 删除资源
  271. * @param $key
  272. * @param $bucket
  273. * @return mixed
  274. */
  275. public function delete(string $key)
  276. {
  277. $bucketManager = new BucketManager($this->app(), new Config());
  278. return $bucketManager->delete($this->storageName, $key);
  279. }
  280. /**
  281. * 获取七牛云上传密钥
  282. * @return mixed|string
  283. */
  284. public function getTempKeys()
  285. {
  286. $token = $this->app()->uploadToken($this->storageName);
  287. $domain = $this->uploadUrl;
  288. $key = $this->saveFileName(NULL, 'mp4');
  289. $type = 'QINIU';
  290. return compact('token', 'domain', 'key', 'type');
  291. }
  292. /**
  293. * 获取当前所有桶列表
  294. * @param string|null $region
  295. * @param bool $line
  296. * @param bool $shared
  297. * @return bool|mixed
  298. */
  299. public function listbuckets(string $region = null, bool $line = false, bool $shared = false)
  300. {
  301. $bucket = new BucketManager($this->app());
  302. [$response, $error] = $bucket->listbuckets($region, $line ? 'true' : 'false', $shared ? 'true' : 'false');
  303. if ($error !== null) {
  304. return $this->setError($error->message());
  305. }
  306. return $response;
  307. }
  308. /**
  309. * @param string $name
  310. * @param string $region
  311. * @return bool|mixed
  312. */
  313. public function createBucket(string $name, string $region = 'z0')
  314. {
  315. $regionData = $this->getRegion();
  316. if (!in_array($region, array_column($regionData, 'value'))) {
  317. return $this->setError('七牛云:无效的区域');
  318. }
  319. $url = 'https://' . Config::UC_HOST . '/mkbucketv3/' . $name . '/region/' . $region;
  320. $body = null;
  321. $headers = $this->app()->authorizationV2($url, 'POST', $body, 'application/json');
  322. $headers["Content-Type"] = 'application/json';
  323. $ret = Client::post($url, $body, $headers);
  324. if (!$ret->ok()) {
  325. $error = new Error($url, $ret);
  326. if ('bucket exists' === $error->message()) {
  327. return $this->setError('七牛云:云空间已存在');
  328. }
  329. return $this->setError('七牛云:' . $error->message());
  330. }
  331. return ($ret->body === null) ? array() : $ret->json();
  332. }
  333. /**
  334. * 获取区域
  335. * @return mixed|\string[][]
  336. */
  337. public function getRegion()
  338. {
  339. return [
  340. [
  341. 'value' => 'z0',
  342. 'label' => '华东'
  343. ],
  344. [
  345. 'value' => 'z1',
  346. 'label' => '华北'
  347. ],
  348. [
  349. 'value' => 'z2',
  350. 'label' => '华南'
  351. ],
  352. [
  353. 'value' => 'na0',
  354. 'label' => '北美'
  355. ],
  356. [
  357. 'value' => 'as0',
  358. 'label' => '东南亚'
  359. ],
  360. [
  361. 'value' => 'cn-east-2',
  362. 'label' => '华东-浙江2'
  363. ],
  364. ];
  365. }
  366. /**
  367. * 删除空间
  368. * @param string $name
  369. * @return bool|mixed
  370. */
  371. public function deleteBucket(string $name)
  372. {
  373. $bucket = new BucketManager($this->app());
  374. [$response, $error] = $bucket->deleteBucket($name);
  375. if ($error !== null) {
  376. return $this->setError($error->message());
  377. }
  378. return $response;
  379. }
  380. /**
  381. * 获取七牛域名
  382. * @param string $name
  383. * @return array|bool|mixed|null
  384. */
  385. public function getDomian(string $name)
  386. {
  387. $url = 'https://' . Config::UC_HOST . '/v2/domains?tbl=' . $name;
  388. $body = null;
  389. $headers = $this->app()->authorizationV2($url, 'POST', $body, 'application/x-www-form-urlencoded');
  390. $headers["Content-Type"] = 'application/x-www-form-urlencoded';
  391. $ret = Client::post($url, $body, $headers);
  392. if (!$ret->ok()) {
  393. $error = new Error($url, $ret);
  394. return $this->setError('七牛云:' . $error->message());
  395. }
  396. return ($ret->body === null) ? array() : $ret->json();
  397. }
  398. public function getDomianInfo(string $host)
  399. {
  400. $url = 'https://' . Config::API_HOST . '/domain/' . $host;
  401. $headers = $this->app()->authorization($url, null, 'application/x-www-form-urlencoded');
  402. $headers["Content-Type"] = 'application/x-www-form-urlencoded';
  403. $ret = Client::get($url, $headers);
  404. if (!$ret->ok()) {
  405. $error = new Error($url, $ret);
  406. return $this->setError('七牛云:' . $error->message());
  407. }
  408. return ($ret->body === null) ? array() : $ret->json();
  409. }
  410. /**
  411. *
  412. * @param string $name
  413. * @param string $domain
  414. * @param string|null $region
  415. * @return array|bool|mixed|null
  416. */
  417. public function bindDomian(string $name, string $domain, string $region = null)
  418. {
  419. $parseDomin = parse_url($domain);
  420. $url = 'https://' . Config::API_HOST . '/domain/' . $parseDomin['host'];
  421. $body = [
  422. 'type' => 'normal',
  423. 'platform' => 'web',
  424. 'geocover' => 'china',
  425. 'source' => [
  426. 'sourceType' => 'qiniuBucket',
  427. 'sourceQiniuBucket' => $name,
  428. 'TestURLPath' => 'qiniu_do_not_delete.gif',
  429. ],
  430. 'protocol' => $parseDomin['scheme'],
  431. 'cache' => [
  432. 'cacheControls' => [
  433. [
  434. 'time' => 1,
  435. 'timeunit' => 4,
  436. 'type' => 'all',
  437. 'rule' => '*'
  438. ]
  439. ],
  440. 'ignoreParam' => false
  441. ]
  442. ];
  443. $bodyJson = json_encode($body);
  444. $headers = $this->app()->authorization($url, $bodyJson, 'application/json');
  445. $headers["Content-Type"] = 'application/json';
  446. $ret = Client::post($url, $bodyJson, $headers);
  447. if (!$ret->ok()) {
  448. $error = new Error($url, $ret);
  449. return $this->setError('七牛云:' . $error->message());
  450. }
  451. return ($ret->body === null) ? array() : $ret->json();
  452. }
  453. /**
  454. * 跨域
  455. * @param string $name
  456. * @param string $region
  457. * @return bool
  458. */
  459. public function setBucketCors(string $name, string $region)
  460. {
  461. return true;
  462. }
  463. }