Qiniu.php 16 KB

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