| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274 |
- <?php
- namespace app\api\controller;
- use app\common\controller\Api;
- use app\common\model\Area;
- use app\common\model\Version;
- use fast\Random;
- use think\Config;
- /**
- * 公共接口
- */
- class Common extends Api
- {
- protected $noNeedLogin = ['init'];
- protected $noNeedRight = '*';
- /**
- * 加载初始化
- *
- * @param string $version 版本号
- * @param string $lng 经度
- * @param string $lat 纬度
- */
- public function init()
- {
- if ($version = $this->request->request('version')) {
- $lng = $this->request->request('lng');
- $lat = $this->request->request('lat');
- $content = [
- 'citydata' => Area::getCityFromLngLat($lng, $lat),
- 'versiondata' => Version::check($version),
- 'uploaddata' => Config::get('upload'),
- 'coverdata' => Config::get("cover"),
- ];
- $this->success('', $content);
- } else {
- $this->error(__('Invalid parameters'));
- }
- }
- /**
- * 上传头像base64
- * @ApiMethod (POST)
- * @param File $file 文件流
- */
- public function base64_image_content(){
- //匹配出图片的格式
- $base64_image_content=input('base64');
- if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
- $type = $result[2];
- $timeYmd=date('Ymd',time());
- $new_file = ROOT_PATH . '/public/uploads/'.$timeYmd."/";//本地目录
- if(!file_exists($new_file)){
- //检查是否有该文件夹,如果没有就创建,并给予最高权限
- mkdir($new_file, 0700);
- }
- $filename = Md5(date('ymdh', time()) . rand(10000, 99999)).".{$type}";//文件名字
- $uploadDir="/uploads/".$timeYmd."/".$filename;//文件地址保存数据库 相对地址
- if (file_put_contents($new_file.$filename, base64_decode(str_replace($result[1], '', $base64_image_content)))){
- $rowUser = model('User')->get($this->auth->id);
- if (!$rowUser) {
- $this->error(__('No Results were found'));
- }
- $rowUser->allowField(true)->save(['avatar'=>$uploadDir]);
- $this->success(__('Upload successful'), [
- 'url' => $uploadDir
- ]);
- }else{
- $this->error('上传错误');
- }
- }else{
- $this->error('格式错误');
- }
- }
- /**
- * 上传文件
- * @ApiMethod (POST)
- * @param File $file 文件流
- */
- public function upload()
- {
- $file = $this->request->file('file');
- if (empty($file)) {
- $this->error(__('No file upload or server upload limit exceeded'));
- }
- //判断是否已经存在附件
- $sha1 = $file->hash();
- $upload = Config::get('upload');
- preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
- $type = strtolower($matches[2]);
- $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
- $size = (int)$upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
- $fileInfo = $file->getInfo();
- $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
- $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
- $mimetypeArr = explode(',', strtolower($upload['mimetype']));
- $typeArr = explode('/', $fileInfo['type']);
- //禁止上传PHP和HTML文件
- if (in_array($fileInfo['type'], ['text/x-php', 'text/html']) || in_array($suffix, ['php', 'html', 'htm'])) {
- $this->error(__('Uploaded file format is limited'));
- }
- //验证文件后缀
- if ($upload['mimetype'] !== '*' &&
- (
- !in_array($suffix, $mimetypeArr)
- || (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
- )
- ) {
- $this->error(__('Uploaded file format is limited'));
- }
- //验证是否为图片文件
- $imagewidth = $imageheight = 0;
- 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'])) {
- $imgInfo = getimagesize($fileInfo['tmp_name']);
- if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
- $this->error(__('Uploaded file is not a valid image'));
- }
- $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
- $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
- }
- $replaceArr = [
- '{year}' => date("Y"),
- '{mon}' => date("m"),
- '{day}' => date("d"),
- '{hour}' => date("H"),
- '{min}' => date("i"),
- '{sec}' => date("s"),
- '{random}' => Random::alnum(16),
- '{random32}' => Random::alnum(32),
- '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
- '{suffix}' => $suffix,
- '{.suffix}' => $suffix ? '.' . $suffix : '',
- '{filemd5}' => md5_file($fileInfo['tmp_name']),
- ];
- $savekey = $upload['savekey'];
- $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);
- $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
- $fileName = substr($savekey, strripos($savekey, '/') + 1);
- //
- $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
- if ($splInfo) {
- $params = array(
- 'admin_id' => 0,
- 'user_id' => (int)$this->auth->id,
- 'filesize' => $fileInfo['size'],
- 'imagewidth' => $imagewidth,
- 'imageheight' => $imageheight,
- 'imagetype' => $suffix,
- 'imageframes' => 0,
- 'mimetype' => $fileInfo['type'],
- 'url' => $uploadDir . $splInfo->getSaveName(),
- 'uploadtime' => time(),
- 'storage' => 'local',
- 'sha1' => $sha1,
- );
- $attachment = model("attachment");
- $attachment->data(array_filter($params));
- $attachment->save();
- \think\Hook::listen("upload_after", $attachment);
- $this->success(__('Upload successful'), [
- 'url' => $uploadDir . $splInfo->getSaveName()
- ]);
- } else {
- // 上传失败获取错误信息
- $this->error($file->getError());
- }
- }
- /**
- * 上传头像
- * @ApiMethod (POST)
- * @param File $file 文件流
- */
- public function uploadavatar()
- {
- $file = $this->request->file('file');
- if (empty($file)) {
- $this->error(__('No file upload or server upload limit exceeded'));
- }
- //判断是否已经存在附件
- $sha1 = $file->hash();
- $upload = Config::get('upload');
- preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
- $type = strtolower($matches[2]);
- $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
- $size = (int)$upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
- $fileInfo = $file->getInfo();
- $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
- $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
- $mimetypeArr = explode(',', strtolower($upload['mimetype']));
- $typeArr = explode('/', $fileInfo['type']);
- //禁止上传PHP和HTML文件
- if (in_array($fileInfo['type'], ['text/x-php', 'text/html']) || in_array($suffix, ['php', 'html', 'htm'])) {
- $this->error(__('Uploaded file format is limited'));
- }
- //验证文件后缀
- if ($upload['mimetype'] !== '*' &&
- (
- !in_array($suffix, $mimetypeArr)
- || (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
- )
- ) {
- $this->error(__('Uploaded file format is limited'));
- }
- //验证是否为图片文件
- $imagewidth = $imageheight = 0;
- 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'])) {
- $imgInfo = getimagesize($fileInfo['tmp_name']);
- if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
- $this->error(__('Uploaded file is not a valid image'));
- }
- $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
- $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
- }
- $replaceArr = [
- '{year}' => date("Y"),
- '{mon}' => date("m"),
- '{day}' => date("d"),
- '{hour}' => date("H"),
- '{min}' => date("i"),
- '{sec}' => date("s"),
- '{random}' => Random::alnum(16),
- '{random32}' => Random::alnum(32),
- '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
- '{suffix}' => $suffix,
- '{.suffix}' => $suffix ? '.' . $suffix : '',
- '{filemd5}' => md5_file($fileInfo['tmp_name']),
- ];
- $savekey = $upload['savekey'];
- $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);
- $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
- $fileName = substr($savekey, strripos($savekey, '/') + 1);
- $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
- if ($splInfo) {
- $params = array(
- 'admin_id' => 0,
- 'user_id' => (int)$this->auth->id,
- 'filesize' => $fileInfo['size'],
- 'imagewidth' => $imagewidth,
- 'imageheight' => $imageheight,
- 'imagetype' => $suffix,
- 'imageframes' => 0,
- 'mimetype' => $fileInfo['type'],
- 'url' => $uploadDir . $splInfo->getSaveName(),
- 'uploadtime' => time(),
- 'storage' => 'local',
- 'sha1' => $sha1,
- );
- $attachment = model("attachment");
- $attachment->data(array_filter($params));
- $attachment->save();
- \think\Hook::listen("upload_after", $attachment);
- $rowUser = model('User')->get($this->auth->id);
- if (!$rowUser) {
- $this->error(__('No Results were found'));
- }
- if($splInfo->getSaveName()){
- $rowUser->allowField(true)->save(['avatar'=>$uploadDir . $splInfo->getSaveName()]);
- }
- $this->success(__('Upload successful'), [
- 'url' => $uploadDir . $splInfo->getSaveName()
- ]);
- } else {
- // 上传失败获取错误信息
- $this->error($file->getError());
- }
- }
- }
|