Common.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use app\common\exception\UploadException;
  5. use app\common\library\Upload;
  6. use app\common\model\Area;
  7. use app\common\model\Version;
  8. use fast\Random;
  9. use think\Config;
  10. use think\Hook;
  11. /**
  12. * 公共接口
  13. */
  14. class Common extends Api
  15. {
  16. protected $noNeedLogin = ['init','upload'];
  17. protected $noNeedRight = '*';
  18. /**
  19. * 加载初始化
  20. *
  21. * @param string $version 版本号
  22. * @param string $lng 经度
  23. * @param string $lat 纬度
  24. */
  25. public function init()
  26. {
  27. if ($version = $this->request->request('version')) {
  28. $lng = $this->request->request('lng');
  29. $lat = $this->request->request('lat');
  30. //配置信息
  31. $upload = Config::get('upload');
  32. //如果非服务端中转模式需要修改为中转
  33. if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
  34. //临时修改上传模式为服务端中转
  35. set_addon_config($upload['storage'], ["uploadmode" => "server"], false);
  36. $upload = \app\common\model\Config::upload();
  37. // 上传信息配置后
  38. Hook::listen("upload_config_init", $upload);
  39. $upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
  40. }
  41. $upload['cdnurl'] = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
  42. $upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);
  43. $content = [
  44. 'citydata' => Area::getCityFromLngLat($lng, $lat),
  45. 'versiondata' => Version::check($version),
  46. 'uploaddata' => $upload,
  47. 'coverdata' => Config::get("cover"),
  48. ];
  49. $this->success('', $content);
  50. } else {
  51. $this->error(__('Invalid parameters'));
  52. }
  53. }
  54. /**
  55. * 上传文件
  56. * @ApiMethod (POST)
  57. * @param File $file 文件流
  58. */
  59. public function upload()
  60. {
  61. Config::set('default_return_type', 'json');
  62. //必须设定cdnurl为空,否则cdnurl函数计算错误
  63. Config::set('upload.cdnurl', '');
  64. $chunkid = $this->request->post("chunkid");
  65. if ($chunkid) {
  66. if (!Config::get('upload.chunking')) {
  67. $this->error(__('Chunk file disabled'));
  68. }
  69. $action = $this->request->post("action");
  70. $chunkindex = $this->request->post("chunkindex/d");
  71. $chunkcount = $this->request->post("chunkcount/d");
  72. $filename = $this->request->post("filename");
  73. $method = $this->request->method(true);
  74. if ($action == 'merge') {
  75. $attachment = null;
  76. //合并分片文件
  77. try {
  78. $upload = new Upload();
  79. $attachment = $upload->merge($chunkid, $chunkcount, $filename);
  80. } catch (UploadException $e) {
  81. $this->error($e->getMessage());
  82. }
  83. $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
  84. } elseif ($method == 'clean') {
  85. //删除冗余的分片文件
  86. try {
  87. $upload = new Upload();
  88. $upload->clean($chunkid);
  89. } catch (UploadException $e) {
  90. $this->error($e->getMessage());
  91. }
  92. $this->success();
  93. } else {
  94. //上传分片文件
  95. //默认普通上传文件
  96. $file = $this->request->file('file');
  97. try {
  98. $upload = new Upload($file);
  99. $upload->chunk($chunkid, $chunkindex, $chunkcount);
  100. } catch (UploadException $e) {
  101. $this->error($e->getMessage());
  102. }
  103. $this->success();
  104. }
  105. } else {
  106. $attachment = null;
  107. //默认普通上传文件
  108. $file = $this->request->file('file');
  109. try {
  110. $upload = new Upload($file);
  111. $attachment = $upload->upload();
  112. } catch (UploadException $e) {
  113. $this->error($e->getMessage());
  114. }
  115. $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
  116. }
  117. }
  118. /**
  119. * 上传文件
  120. * @ApiMethod (POST)
  121. * @param File $file 文件流
  122. */
  123. public function uploads($file) {
  124. if (empty($file)) {
  125. $this->error(__('No file upload or server upload limit exceeded'));
  126. }
  127. //判断是否已经存在附件
  128. $sha1 = $file->hash();
  129. $upload = Config::get('upload');
  130. preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
  131. $type = strtolower($matches[2]);
  132. $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
  133. $size = (int)$upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
  134. $fileInfo = $file->getInfo();
  135. $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
  136. $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  137. $mimetypeArr = explode(',', strtolower($upload['mimetype']));
  138. $typeArr = explode('/', $fileInfo['type']);
  139. //禁止上传PHP和HTML文件
  140. if (in_array($fileInfo['type'], ['text/x-php', 'text/html']) || in_array($suffix, ['php', 'html', 'htm'])) {
  141. $this->error(__('Uploaded file format is limited'));
  142. }
  143. //验证文件后缀
  144. if ($upload['mimetype'] !== '*' &&
  145. (
  146. !in_array($suffix, $mimetypeArr)
  147. || (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
  148. )
  149. ) {
  150. $this->error(__('Uploaded file format is limited'));
  151. }
  152. // //验证是否为图片文件
  153. // $imagewidth = $imageheight = 0;
  154. // if (in_array($fileInfo['type'], ['image/gif', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/png', 'image/webp']) || in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'webp'])) {
  155. // $imgInfo = getimagesize($fileInfo['tmp_name']);
  156. // if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
  157. // $this->error(__('Uploaded file is not a valid image'));
  158. // }
  159. // $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
  160. // $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
  161. // }
  162. $replaceArr = [
  163. '{year}' => date("Y"),
  164. '{mon}' => date("m"),
  165. '{day}' => date("d"),
  166. '{hour}' => date("H"),
  167. '{min}' => date("i"),
  168. '{sec}' => date("s"),
  169. '{random}' => Random::alnum(16),
  170. '{random32}' => Random::alnum(32),
  171. '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
  172. '{suffix}' => $suffix,
  173. '{.suffix}' => $suffix ? '.' . $suffix : '',
  174. '{filemd5}' => md5_file($fileInfo['tmp_name']),
  175. ];
  176. $savekey = $upload['savekey'];
  177. $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);
  178. $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
  179. $fileName = substr($savekey, strripos($savekey, '/') + 1);
  180. //
  181. $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
  182. if ($splInfo) {
  183. $params = array(
  184. 'admin_id' => 0,
  185. 'user_id' => (int)$this->auth->id,
  186. 'filesize' => $fileInfo['size'],
  187. 'imagetype' => $suffix,
  188. 'imageframes' => 0,
  189. 'mimetype' => $fileInfo['type'],
  190. 'url' => $uploadDir . $splInfo->getSaveName(),
  191. 'uploadtime' => time(),
  192. 'storage' => 'local',
  193. 'sha1' => $sha1,
  194. );
  195. $attachment = model("attachment");
  196. $attachment->data(array_filter($params));
  197. $attachment->save();
  198. \think\Hook::listen("upload_after", $attachment);
  199. return $uploadDir . $splInfo->getSaveName();
  200. } else {
  201. // 上传失败获取错误信息
  202. $this->error($file->getError());
  203. }
  204. }
  205. // 返回执行日期所在周的第一天(周一)日期
  206. public function firstOfWeek($date) {
  207. $now = strtotime($date); //当时的时间戳
  208. $number = date("w",$now); //当时是周几
  209. $number = $number == 0 ? 7 : $number; //如遇周末,将0换成7
  210. $diff_day = $number - 1; //求到周一差几天
  211. return date("Ymd",$now - ($diff_day * 60 * 60 * 24));
  212. }
  213. /**
  214. * 数字转化
  215. */
  216. public function changeW($val) {
  217. return $val > 10000 ? round($val/10000,2)."w":$val;
  218. }
  219. public function getModelName($type)
  220. {
  221. return "app\common\model\\" . ucfirst($type);
  222. }
  223. /** 上传文件到 本地+cos
  224. * @param $file
  225. * @return array|bool|float|int|mixed|object|\stdClass|null
  226. * @throws UploadException
  227. */
  228. public function uploadCos($file)
  229. {
  230. $config = get_addon_config('cos');
  231. $cosConfig = array(
  232. 'region' => $config['region'],
  233. 'schema' => 'https', //协议头部,默认为http
  234. 'credentials' => array(
  235. 'secretId' => $config['secretId'],
  236. 'secretKey' => $config['secretKey']
  237. )
  238. );
  239. $upload = new Upload($file);
  240. $attachment = $upload->upload();
  241. $oss = new \Qcloud\Cos\Client($cosConfig);
  242. $oss->upload($config['bucket'], ltrim($attachment->url, "/"), $upload->getFile());
  243. return $attachment->url;
  244. }
  245. /** 删除本地文件
  246. * @param $url
  247. * @return string
  248. */
  249. public function unlinkLocal($url){
  250. if(file_exists($url)){
  251. unlink($url);
  252. return '已删除了哦!';
  253. }else{
  254. return '已经被删除了哦!';
  255. }
  256. }
  257. }