Common.php 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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. * 上传文件
  40. * @ApiMethod (POST)
  41. * @param File $file 文件流
  42. */
  43. public function upload()
  44. {
  45. $file = $this->request->file('file');
  46. if (empty($file)) {
  47. $this->error(__('No file upload or server upload limit exceeded'));
  48. }
  49. //判断是否已经存在附件
  50. $sha1 = $file->hash();
  51. $upload = Config::get('upload');
  52. preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
  53. $type = strtolower($matches[2]);
  54. $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
  55. $size = (int)$upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
  56. $fileInfo = $file->getInfo();
  57. $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
  58. $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  59. $mimetypeArr = explode(',', strtolower($upload['mimetype']));
  60. $typeArr = explode('/', $fileInfo['type']);
  61. //禁止上传PHP和HTML文件
  62. if (in_array($fileInfo['type'], ['text/x-php', 'text/html']) || in_array($suffix, ['php', 'html', 'htm'])) {
  63. $this->error(__('Uploaded file format is limited'));
  64. }
  65. //验证文件后缀
  66. if ($upload['mimetype'] !== '*' &&
  67. (
  68. !in_array($suffix, $mimetypeArr)
  69. || (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
  70. )
  71. ) {
  72. $this->error(__('Uploaded file format is limited'));
  73. }
  74. //验证是否为图片文件
  75. $imagewidth = $imageheight = 0;
  76. 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'])) {
  77. $imgInfo = getimagesize($fileInfo['tmp_name']);
  78. if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
  79. $this->error(__('Uploaded file is not a valid image'));
  80. }
  81. $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
  82. $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
  83. }
  84. $replaceArr = [
  85. '{year}' => date("Y"),
  86. '{mon}' => date("m"),
  87. '{day}' => date("d"),
  88. '{hour}' => date("H"),
  89. '{min}' => date("i"),
  90. '{sec}' => date("s"),
  91. '{random}' => Random::alnum(16),
  92. '{random32}' => Random::alnum(32),
  93. '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
  94. '{suffix}' => $suffix,
  95. '{.suffix}' => $suffix ? '.' . $suffix : '',
  96. '{filemd5}' => md5_file($fileInfo['tmp_name']),
  97. ];
  98. $savekey = $upload['savekey'];
  99. $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);
  100. $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
  101. $fileName = substr($savekey, strripos($savekey, '/') + 1);
  102. //
  103. $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
  104. if ($splInfo) {
  105. $params = array(
  106. 'admin_id' => 0,
  107. 'user_id' => (int)$this->auth->id,
  108. 'filesize' => $fileInfo['size'],
  109. 'imagewidth' => $imagewidth,
  110. 'imageheight' => $imageheight,
  111. 'imagetype' => $suffix,
  112. 'imageframes' => 0,
  113. 'mimetype' => $fileInfo['type'],
  114. 'url' => $uploadDir . $splInfo->getSaveName(),
  115. 'uploadtime' => time(),
  116. 'storage' => 'local',
  117. 'sha1' => $sha1,
  118. );
  119. $attachment = model("attachment");
  120. $attachment->data(array_filter($params));
  121. $attachment->save();
  122. \think\Hook::listen("upload_after", $attachment);
  123. $this->success(__('Upload successful'), [
  124. 'url' => $uploadDir . $splInfo->getSaveName()
  125. ]);
  126. } else {
  127. // 上传失败获取错误信息
  128. $this->error($file->getError());
  129. }
  130. }
  131. }