Common.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use app\common\model\Area;
  5. use app\common\model\Version;
  6. use fast\Random;
  7. use think\Config;
  8. /**
  9. * 公共接口
  10. */
  11. class Common extends Api
  12. {
  13. protected $noNeedLogin = ['init'];
  14. protected $noNeedRight = '*';
  15. /**
  16. * 加载初始化
  17. *
  18. * @param string $version 版本号
  19. * @param string $lng 经度
  20. * @param string $lat 纬度
  21. */
  22. public function init()
  23. {
  24. if ($version = $this->request->request('version')) {
  25. $lng = $this->request->request('lng');
  26. $lat = $this->request->request('lat');
  27. $content = [
  28. 'citydata' => Area::getCityFromLngLat($lng, $lat),
  29. 'versiondata' => Version::check($version),
  30. 'uploaddata' => Config::get('upload'),
  31. 'coverdata' => Config::get("cover"),
  32. ];
  33. $this->success('', $content);
  34. } else {
  35. $this->error(__('Invalid parameters'));
  36. }
  37. }
  38. /**
  39. * 上传头像base64
  40. * @ApiMethod (POST)
  41. * @param File $file 文件流
  42. */
  43. public function base64_image_content(){
  44. //匹配出图片的格式
  45. $base64_image_content=input('base64');
  46. if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
  47. $type = $result[2];
  48. $timeYmd=date('Ymd',time());
  49. $new_file = ROOT_PATH . '/public/uploads/'.$timeYmd."/";//本地目录
  50. if(!file_exists($new_file)){
  51. //检查是否有该文件夹,如果没有就创建,并给予最高权限
  52. mkdir($new_file, 0700);
  53. }
  54. $filename = Md5(date('ymdh', time()) . rand(10000, 99999)).".{$type}";//文件名字
  55. $uploadDir="/uploads/".$timeYmd."/".$filename;//文件地址保存数据库 相对地址
  56. if (file_put_contents($new_file.$filename, base64_decode(str_replace($result[1], '', $base64_image_content)))){
  57. $rowUser = model('User')->get($this->auth->id);
  58. if (!$rowUser) {
  59. $this->error(__('No Results were found'));
  60. }
  61. $rowUser->allowField(true)->save(['avatar'=>$uploadDir]);
  62. $this->success(__('Upload successful'), [
  63. 'url' => $uploadDir
  64. ]);
  65. }else{
  66. $this->error('上传错误');
  67. }
  68. }else{
  69. $this->error('格式错误');
  70. }
  71. }
  72. /**
  73. * 上传文件
  74. * @ApiMethod (POST)
  75. * @param File $file 文件流
  76. */
  77. public function upload()
  78. {
  79. $file = $this->request->file('file');
  80. if (empty($file)) {
  81. $this->error(__('No file upload or server upload limit exceeded'));
  82. }
  83. //判断是否已经存在附件
  84. $sha1 = $file->hash();
  85. $upload = Config::get('upload');
  86. preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
  87. $type = strtolower($matches[2]);
  88. $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
  89. $size = (int)$upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
  90. $fileInfo = $file->getInfo();
  91. $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
  92. $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  93. $mimetypeArr = explode(',', strtolower($upload['mimetype']));
  94. $typeArr = explode('/', $fileInfo['type']);
  95. //禁止上传PHP和HTML文件
  96. if (in_array($fileInfo['type'], ['text/x-php', 'text/html']) || in_array($suffix, ['php', 'html', 'htm'])) {
  97. $this->error(__('Uploaded file format is limited'));
  98. }
  99. //验证文件后缀
  100. if ($upload['mimetype'] !== '*' &&
  101. (
  102. !in_array($suffix, $mimetypeArr)
  103. || (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
  104. )
  105. ) {
  106. $this->error(__('Uploaded file format is limited'));
  107. }
  108. //验证是否为图片文件
  109. $imagewidth = $imageheight = 0;
  110. 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'])) {
  111. $imgInfo = getimagesize($fileInfo['tmp_name']);
  112. if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
  113. $this->error(__('Uploaded file is not a valid image'));
  114. }
  115. $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
  116. $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
  117. }
  118. $replaceArr = [
  119. '{year}' => date("Y"),
  120. '{mon}' => date("m"),
  121. '{day}' => date("d"),
  122. '{hour}' => date("H"),
  123. '{min}' => date("i"),
  124. '{sec}' => date("s"),
  125. '{random}' => Random::alnum(16),
  126. '{random32}' => Random::alnum(32),
  127. '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
  128. '{suffix}' => $suffix,
  129. '{.suffix}' => $suffix ? '.' . $suffix : '',
  130. '{filemd5}' => md5_file($fileInfo['tmp_name']),
  131. ];
  132. $savekey = $upload['savekey'];
  133. $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);
  134. $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
  135. $fileName = substr($savekey, strripos($savekey, '/') + 1);
  136. //
  137. $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
  138. if ($splInfo) {
  139. $params = array(
  140. 'admin_id' => 0,
  141. 'user_id' => (int)$this->auth->id,
  142. 'filesize' => $fileInfo['size'],
  143. 'imagewidth' => $imagewidth,
  144. 'imageheight' => $imageheight,
  145. 'imagetype' => $suffix,
  146. 'imageframes' => 0,
  147. 'mimetype' => $fileInfo['type'],
  148. 'url' => $uploadDir . $splInfo->getSaveName(),
  149. 'uploadtime' => time(),
  150. 'storage' => 'local',
  151. 'sha1' => $sha1,
  152. );
  153. $attachment = model("attachment");
  154. $attachment->data(array_filter($params));
  155. $attachment->save();
  156. \think\Hook::listen("upload_after", $attachment);
  157. $this->success(__('Upload successful'), [
  158. 'url' => $uploadDir . $splInfo->getSaveName()
  159. ]);
  160. } else {
  161. // 上传失败获取错误信息
  162. $this->error($file->getError());
  163. }
  164. }
  165. /**
  166. * 上传头像
  167. * @ApiMethod (POST)
  168. * @param File $file 文件流
  169. */
  170. public function uploadavatar()
  171. {
  172. $file = $this->request->file('file');
  173. if (empty($file)) {
  174. $this->error(__('No file upload or server upload limit exceeded'));
  175. }
  176. //判断是否已经存在附件
  177. $sha1 = $file->hash();
  178. $upload = Config::get('upload');
  179. preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
  180. $type = strtolower($matches[2]);
  181. $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
  182. $size = (int)$upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
  183. $fileInfo = $file->getInfo();
  184. $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
  185. $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  186. $mimetypeArr = explode(',', strtolower($upload['mimetype']));
  187. $typeArr = explode('/', $fileInfo['type']);
  188. //禁止上传PHP和HTML文件
  189. if (in_array($fileInfo['type'], ['text/x-php', 'text/html']) || in_array($suffix, ['php', 'html', 'htm'])) {
  190. $this->error(__('Uploaded file format is limited'));
  191. }
  192. //验证文件后缀
  193. if ($upload['mimetype'] !== '*' &&
  194. (
  195. !in_array($suffix, $mimetypeArr)
  196. || (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
  197. )
  198. ) {
  199. $this->error(__('Uploaded file format is limited'));
  200. }
  201. //验证是否为图片文件
  202. $imagewidth = $imageheight = 0;
  203. 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'])) {
  204. $imgInfo = getimagesize($fileInfo['tmp_name']);
  205. if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
  206. $this->error(__('Uploaded file is not a valid image'));
  207. }
  208. $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
  209. $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
  210. }
  211. $replaceArr = [
  212. '{year}' => date("Y"),
  213. '{mon}' => date("m"),
  214. '{day}' => date("d"),
  215. '{hour}' => date("H"),
  216. '{min}' => date("i"),
  217. '{sec}' => date("s"),
  218. '{random}' => Random::alnum(16),
  219. '{random32}' => Random::alnum(32),
  220. '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
  221. '{suffix}' => $suffix,
  222. '{.suffix}' => $suffix ? '.' . $suffix : '',
  223. '{filemd5}' => md5_file($fileInfo['tmp_name']),
  224. ];
  225. $savekey = $upload['savekey'];
  226. $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);
  227. $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
  228. $fileName = substr($savekey, strripos($savekey, '/') + 1);
  229. $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
  230. if ($splInfo) {
  231. $params = array(
  232. 'admin_id' => 0,
  233. 'user_id' => (int)$this->auth->id,
  234. 'filesize' => $fileInfo['size'],
  235. 'imagewidth' => $imagewidth,
  236. 'imageheight' => $imageheight,
  237. 'imagetype' => $suffix,
  238. 'imageframes' => 0,
  239. 'mimetype' => $fileInfo['type'],
  240. 'url' => $uploadDir . $splInfo->getSaveName(),
  241. 'uploadtime' => time(),
  242. 'storage' => 'local',
  243. 'sha1' => $sha1,
  244. );
  245. $attachment = model("attachment");
  246. $attachment->data(array_filter($params));
  247. $attachment->save();
  248. \think\Hook::listen("upload_after", $attachment);
  249. $rowUser = model('User')->get($this->auth->id);
  250. if (!$rowUser) {
  251. $this->error(__('No Results were found'));
  252. }
  253. if($splInfo->getSaveName()){
  254. $rowUser->allowField(true)->save(['avatar'=>$uploadDir . $splInfo->getSaveName()]);
  255. }
  256. $this->success(__('Upload successful'), [
  257. 'url' => $uploadDir . $splInfo->getSaveName()
  258. ]);
  259. } else {
  260. // 上传失败获取错误信息
  261. $this->error($file->getError());
  262. }
  263. }
  264. }