Index.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. <?php
  2. namespace addons\qiniu\controller;
  3. use app\common\exception\UploadException;
  4. use app\common\library\Upload;
  5. use app\common\model\Attachment;
  6. use Qiniu\Auth;
  7. use Qiniu\Storage\ResumeUploader;
  8. use Qiniu\Storage\UploadManager;
  9. use think\addons\Controller;
  10. use think\Config;
  11. /**
  12. * 七牛管理
  13. *
  14. */
  15. class Index extends Controller
  16. {
  17. public function _initialize()
  18. {
  19. //跨域检测
  20. check_cors_request();
  21. parent::_initialize();
  22. Config::set('default_return_type', 'json');
  23. }
  24. public function index()
  25. {
  26. Config::set('default_return_type', 'html');
  27. $this->error("当前插件暂无前台页面");
  28. }
  29. /**
  30. * 获取签名
  31. */
  32. public function params()
  33. {
  34. $this->check();
  35. $name = $this->request->post('name');
  36. $md5 = $this->request->post('md5');
  37. $chunk = $this->request->post('chunk');
  38. $config = get_addon_config('qiniu');
  39. $name = xss_clean($name);
  40. $config['savekey'] = (new Upload())->getSavekey($config['savekey'], $name, '$(etag)');
  41. preg_match('/(\d+)(\w+)/', $config['maxsize'], $matches);
  42. $type = strtolower($matches[2]);
  43. $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
  44. $size = (int)$config['maxsize'] * pow(1024, $typeDict[$type] ?? 0);
  45. // 构建鉴权对象
  46. $auth = new Auth($config['accessKey'], $config['secretKey']);
  47. // 生成上传 Token
  48. $token = $auth->uploadToken($config['bucket'], null, 3600, ['saveKey' => ltrim($config['savekey'], '/'), 'fsizeLimit' => $size]);
  49. $params['qiniutoken'] = $token;
  50. $this->success('', null, $params);
  51. return;
  52. }
  53. /**
  54. * 中转上传文件
  55. * 上传分片
  56. * 合并分片
  57. * @param bool $isApi
  58. * @throws \Exception
  59. */
  60. public function upload($isApi = false)
  61. {
  62. Config::set('default_return_type', 'json');
  63. if ($isApi === true) {
  64. if (!\addons\qiniu\library\Auth::isModuleAllow()) {
  65. $this->error("请登录后再进行操作");
  66. }
  67. } else {
  68. $this->check();
  69. }
  70. $config = get_addon_config('qiniu');
  71. $config['savekey'] = str_replace(
  72. ['$(year)', '$(mon)', '$(day)', '$(hour)', '$(min)', '$(sec)', '$(etag)', '$(ext)', '$(fname)', '$(fprefix)'],
  73. ['{year}', '{mon}', '{day}', '{hour}', '{min}', '{sec}', '{filemd5}', '{.suffix}', '{filename}', '{fileprefix}'],
  74. $config['savekey']
  75. );
  76. $file = $this->request->file('file');
  77. $chunkid = $this->request->post("chunkid");
  78. $md5 = $chunkid && $this->request->post("action") == 'merge' ? md5(str_replace('-', '', $chunkid)) : null;
  79. $config['savekey'] = (new Upload($file))->getSavekey($config['savekey'], null, $md5);
  80. preg_match('/(\d+)(\w+)/', $config['maxsize'], $matches);
  81. $type = strtolower($matches[2]);
  82. $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
  83. $size = (int)$config['maxsize'] * pow(1024, $typeDict[$type] ?? 0);
  84. // 构建鉴权对象
  85. $auth = new Auth($config['accessKey'], $config['secretKey']);
  86. // 生成上传 Token
  87. $token = $auth->uploadToken($config['bucket'], null, 3600, ['saveKey' => ltrim($config['savekey'], '/'), 'fsizeLimit' => $size]);
  88. // 初始化 UploadManager 对象并进行文件的上传。
  89. $uploadMgr = new UploadManager();
  90. //检测删除文件或附件
  91. $checkDeleteFile = function ($attachment, $upload, $force = false) use ($config) {
  92. //如果设定为不备份则删除文件和记录 或 强制删除
  93. if ((isset($config['serverbackup']) && !$config['serverbackup']) || $force) {
  94. if ($attachment && !empty($attachment['id'])) {
  95. $attachment->delete();
  96. }
  97. if ($upload) {
  98. //文件绝对路径
  99. $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();
  100. @unlink($filePath);
  101. }
  102. }
  103. };
  104. $chunkid = $this->request->post("chunkid");
  105. if ($chunkid) {
  106. $action = $this->request->post("action");
  107. $chunkindex = $this->request->post("chunkindex/d");
  108. $chunkcount = $this->request->post("chunkcount/d");
  109. $filesize = $this->request->post("filesize");
  110. $filename = $this->request->post("filename");
  111. if ($action == 'merge') {
  112. $attachment = null;
  113. $upload = null;
  114. if ($config['uploadmode'] == 'server') {
  115. //合并分片文件
  116. try {
  117. $upload = new Upload();
  118. $attachment = $upload->merge($chunkid, $chunkcount, $filename);
  119. } catch (UploadException $e) {
  120. $this->error($e->getMessage());
  121. }
  122. }
  123. $config = get_addon_config('qiniu');
  124. $name = xss_clean($filename);
  125. $config['savekey'] = (new Upload())->getSavekey($config['savekey'], $name, $md5);
  126. // 重新生成上传 Token
  127. $token = $auth->uploadToken($config['bucket'], null, 3600, ['saveKey' => ltrim($config['savekey'], '/'), 'fsizeLimit' => $size]);
  128. $contexts = $this->request->post("contexts/a", []);
  129. $uploader = new ResumeUploader($token, null, null, $filesize);
  130. list($ret, $err) = $uploader->setContexts($contexts)->makeFile($filename);
  131. if ($err !== null) {
  132. $checkDeleteFile($attachment, $upload, true);
  133. $this->error("上传失败");
  134. } else {
  135. $checkDeleteFile($attachment, $upload);
  136. $this->success("上传成功", '', ['url' => '/' . $ret['key'], 'fullurl' => cdnurl('/' . $ret['key'], true), 'hash' => $ret['hash']]);
  137. }
  138. } else {
  139. //默认普通上传文件
  140. $file = $this->request->file('file');
  141. try {
  142. $upload = new Upload($file);
  143. $file = $upload->chunk($chunkid, $chunkindex, $chunkcount);
  144. } catch (UploadException $e) {
  145. $this->error($e->getMessage());
  146. }
  147. //上传分片文件
  148. //$file = $this->request->file('file');
  149. $filesize = $file->getSize();
  150. //合并分片文件
  151. $uploader = new ResumeUploader($token, null, fopen($file->getRealPath(), 'rb'), $filesize);
  152. $ret = $uploader->uploadChunk($chunkindex, $file, $filesize);
  153. $this->success("上传成功", "", $ret);
  154. }
  155. } else {
  156. $attachment = null;
  157. //默认普通上传文件
  158. $file = $this->request->file('file');
  159. try {
  160. $upload = new Upload($file);
  161. $suffix = $upload->getSuffix();
  162. $md5 = md5_file($file->getRealPath());
  163. $filename = $file->getFilename();
  164. $fileprefix = substr($filename, 0, strripos($filename, '.'));
  165. $search = ['$(year)', '$(mon)', '$(day)', '$(hour)', '$(min)', '$(sec)', '$(etag)', '$(ext)', '$(fname)', '$(fprefix)'];
  166. $replace = [date("Y"), date("m"), date("d"), date("H"), date("i"), date("s"), $md5, '.' . $suffix, $filename, $fileprefix];
  167. $savekey = ltrim(str_replace($search, $replace, $config['savekey']), '/');
  168. $attachment = $upload->upload($savekey);
  169. } catch (UploadException $e) {
  170. $this->error($e->getMessage());
  171. }
  172. //文件绝对路径
  173. $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();
  174. //上传到七牛后保存的文件名
  175. $saveKey = ltrim($attachment->url, '/');
  176. $url = $attachment->url;
  177. try {
  178. // 调用 UploadManager 的 putFile 方法进行文件的上传。
  179. list($ret, $err) = $uploadMgr->putFile($token, $saveKey, $filePath);
  180. if ($err !== null) {
  181. throw new \Exception("上传失败");
  182. }
  183. //成功不做任何操作
  184. } catch (\Exception $e) {
  185. $checkDeleteFile($attachment, $upload, true);
  186. $this->error("上传失败");
  187. }
  188. $hash = md5_file($filePath);
  189. $checkDeleteFile($attachment, $upload);
  190. // 记录云存储记录
  191. $data = $attachment->toArray();
  192. unset($data['id']);
  193. $data['storage'] = 'qiniu';
  194. Attachment::create($data, true);
  195. //水印
  196. /*if(in_array($suffix,['jpg','png','bmp','jpeg']))
  197. {
  198. $username = \app\common\library\Auth::instance()->username;
  199. $url.= $this->water_param($username);
  200. }*/
  201. //水印
  202. $this->success("上传成功", '', ['url' => $url, 'fullurl' => cdnurl($url, true), 'hash' => $hash]);
  203. }
  204. }
  205. /**
  206. * 七牛云水印链接
  207. * 传入用户展示id
  208. * https://developer.qiniu.com/dora/1316/image-watermarking-processing-watermark
  209. */
  210. public function water_param($username = ''){
  211. return '-tkenimg';
  212. $shuiyin_img = 'kodo://tken'.config('site.shuiyin') ?: 'kodo://tken/water.png';
  213. $username = !empty($username) ? 'TK号:'.$username : 'TK号:未知';
  214. $param_str = '?watermark/3/image/'.base64_encode($shuiyin_img).'/ws/0.05/wst/0/dx/25/dy/30/text/'.base64_encode($username).'/fontsize/300/dx/20/dy/10/fill/'.base64_encode('#FFFFFF');
  215. return $param_str;
  216. }
  217. /**
  218. * 通知回调
  219. */
  220. public function notify()
  221. {
  222. Config::set('default_return_type', 'json');
  223. $this->check();
  224. $config = get_addon_config('qiniu');
  225. if ($config['uploadmode'] != 'client') {
  226. $this->error("无需执行该操作");
  227. }
  228. $this->request->filter('trim,strip_tags,htmlspecialchars,xss_clean');
  229. $size = $this->request->post('size/d');
  230. $name = $this->request->post('name', '');
  231. $hash = $this->request->post('hash', '');
  232. $type = $this->request->post('type', '');
  233. $url = $this->request->post('url', '');
  234. $width = $this->request->post('width/d');
  235. $height = $this->request->post('height/d');
  236. $category = $this->request->post('category', '');
  237. $suffix = strtolower(pathinfo($name, PATHINFO_EXTENSION));
  238. $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  239. $attachment = Attachment::where('url', $url)->where('storage', 'qiniu')->find();
  240. if (!$attachment) {
  241. $params = array(
  242. 'category' => $category,
  243. 'admin_id' => (int)session('admin.id'),
  244. 'user_id' => (int)cookie('uid'),
  245. 'filename' => $name,
  246. 'filesize' => $size,
  247. 'imagewidth' => $width,
  248. 'imageheight' => $height,
  249. 'imagetype' => $suffix,
  250. 'imageframes' => 0,
  251. 'mimetype' => $type,
  252. 'url' => $url,
  253. 'uploadtime' => time(),
  254. 'storage' => 'qiniu',
  255. 'sha1' => $hash,
  256. );
  257. Attachment::create($params, true);
  258. }
  259. $this->success();
  260. }
  261. /**
  262. * 检查签名是否正确或过期
  263. */
  264. protected function check()
  265. {
  266. $qiniutoken = $this->request->post('qiniutoken', $this->request->server('AUTHORIZATION'), 'trim');
  267. if (!$qiniutoken) {
  268. $this->error("参数不正确(code:1)");
  269. }
  270. $config = get_addon_config('qiniu');
  271. $auth = new Auth($config['accessKey'], $config['secretKey']);
  272. list($accessKey, $sign, $data) = explode(':', $qiniutoken);
  273. if (!$accessKey || !$sign || !$data) {
  274. $this->error("参数不正确(code:2)");
  275. }
  276. if ($accessKey !== $config['accessKey']) {
  277. $this->error("参数不正确(code:3)");
  278. }
  279. if ($accessKey . ':' . $sign !== $auth->sign($data)) {
  280. $this->error("签名不正确");
  281. }
  282. $json = json_decode(\Qiniu\base64_urlSafeDecode($data), true);
  283. if ($json['deadline'] < time()) {
  284. $this->error("请求已经超时");
  285. }
  286. }
  287. }