Ajax.php 18.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
<?php

namespace app\teacher\controller;


use app\common\controller\TeacherBase;
use app\school\model\basic\Clazz;
use app\school\model\basic\College;
use app\school\model\basic\Specialty;
use EasyWeChat\Factory;
use fast\Random;
use Overtrue\Socialite\AuthorizeFailedException;
use think\addons\Service;
use think\Cache;
use think\Config;
use think\Db;
use think\Exception;
use think\Lang;
use Upyun\Upyun;

/**
 * Ajax异步请求接口
 * @internal
 */
class Ajax extends TeacherBase
{

    protected $noNeedLogin = ['lang'];
    //'canvas','upyun_upload'
    protected $noNeedRight = ['*'];
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();

        //设置过滤方法
        $this->request->filter(['strip_tags', 'htmlspecialchars']);
    }

    /**
     * 加载语言包
     */
    public function lang()
    {
        header('Content-Type: application/javascript');
        $controllername = input("controllername");
        //默认只加载了控制器对应的语言名,你还根据控制器名来加载额外的语言包
        $this->loadlang($controllername);
        return jsonp(Lang::get(), 200, [], ['json_encode_param' => JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE]);
    }

    /**
     * 上传文件
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        $file = $this->request->file('file');
        if (empty($file)) {
            $this->error(__('No file upload or server upload limit exceeded'));
        }

        //判断是否已经存在附件
        $sha1 = $file->hash();
        $extparam = $this->request->post();

        $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(
                'school_id'    => (int)SCHOOL_ID,
                'user_id'     => 0,
                'filesize'    => $fileInfo['size'],
                'imagewidth'  => $imagewidth,
                'imageheight' => $imageheight,
                'imagetype'   => $suffix,
                'imageframes' => 0,
                'mimetype'    => $fileInfo['type'],
                'url'         => $uploadDir . $splInfo->getSaveName(),
                'uploadtime'  => time(),
                'storage'     => 'local',
                'sha1'        => $sha1,
                'extparam'    => json_encode($extparam),
            );
            $attachment = model("ManystoreAttachment");
            $attachment->data(array_filter($params));
            $attachment->save();
            \think\Hook::listen("upload_after", $attachment);
            $this->success(__('Upload successful'), null, [
                'url' => $uploadDir . $splInfo->getSaveName()
            ]);
        } else {
            // 上传失败获取错误信息
            $this->error($file->getError());
        }
    }

    /**
     * 通用排序
     */
    public function weigh()
    {
        //排序的数组
        $ids = $this->request->post("ids");
        //拖动的记录ID
        $changeid = $this->request->post("changeid");
        //操作字段
        $field = $this->request->post("field");
        //操作的数据表
        $table = $this->request->post("table");
        //主键
        $pk = $this->request->post("pk");
        //排序的方式
        $orderway = $this->request->post("orderway", "", 'strtolower');
        $orderway = $orderway == 'asc' ? 'ASC' : 'DESC';
        $sour = $weighdata = [];
        $ids = explode(',', $ids);
        $prikey = $pk ? $pk : (Db::name($table)->getPk() ?: 'id');
        $pid = $this->request->post("pid");
        //限制更新的字段
        $field = in_array($field, ['weigh']) ? $field : 'weigh';

        // 如果设定了pid的值,此时只匹配满足条件的ID,其它忽略
        if ($pid !== '') {
            $hasids = [];
            $list = Db::name($table)->where($prikey, 'in', $ids)->where('pid', 'in', $pid)->field("{$prikey},pid")->select();
            foreach ($list as $k => $v) {
                $hasids[] = $v[$prikey];
            }
            $ids = array_values(array_intersect($ids, $hasids));
        }

        $list = Db::name($table)->field("$prikey,$field")->where($prikey, 'in', $ids)->order($field, $orderway)->select();
        foreach ($list as $k => $v) {
            $sour[] = $v[$prikey];
            $weighdata[$v[$prikey]] = $v[$field];
        }
        $position = array_search($changeid, $ids);
        $desc_id = $sour[$position];    //移动到目标的ID值,取出所处改变前位置的值
        $sour_id = $changeid;
        $weighids = array();
        $temp = array_values(array_diff_assoc($ids, $sour));
        foreach ($temp as $m => $n) {
            if ($n == $sour_id) {
                $offset = $desc_id;
            } else {
                if ($sour_id == $temp[0]) {
                    $offset = isset($temp[$m + 1]) ? $temp[$m + 1] : $sour_id;
                } else {
                    $offset = isset($temp[$m - 1]) ? $temp[$m - 1] : $sour_id;
                }
            }
            $weighids[$n] = $weighdata[$offset];
            Db::name($table)->where($prikey, $n)->update([$field => $weighdata[$offset]]);
        }
        $this->success();
    }

    /**
     * 清空系统缓存
     */
    public function wipecache()
    {
        $type = $this->request->request("type");
        switch ($type) {
            case 'all':
            case 'content':
                rmdirs(CACHE_PATH, false);
                Cache::clear();
                if ($type == 'content')
                    break;
            case 'template':
                rmdirs(TEMP_PATH, false);
                if ($type == 'template')
                    break;
            case 'addons':
                Service::refresh();
                if ($type == 'addons')
                    break;
        }

        \think\Hook::listen("wipecache_after");
        $this->success();
    }

    /**
     * 读取分类数据,联动列表
     */
    public function category()
    {
        $type = $this->request->get('type');
        $pid = $this->request->get('pid');
        $where = ['status' => 'normal'];
        $categorylist = null;
        if ($pid !== '') {
            if ($type) {
                $where['type'] = $type;
            }
            if ($pid) {
                $where['pid'] = $pid;
            }

            $categorylist = Db::name('category')->where($where)->field('id as value,name')->order('weigh desc,id desc')->select();
        }
        $this->success('', null, $categorylist);
    }

    /**
     * 读取省市区数据,联动列表
     */
    public function area()
    {
        $params = $this->request->get("row/a");
        if (!empty($params)) {
            $province = isset($params['province']) ? $params['province'] : '';
            $city = isset($params['city']) ? $params['city'] : null;
        } else {
            $province = $this->request->get('province');
            $city = $this->request->get('city');
        }
        $where = ['pid' => 0, 'level' => 1];
        $provincelist = null;
        if ($province !== '') {
            if ($province) {
                $where['pid'] = $province;
                $where['level'] = 2;
            }
            if ($city !== '') {
                if ($city) {
                    $where['pid'] = $city;
                    $where['level'] = 3;
                }
                $provincelist = Db::name('area')->where($where)->field('id as value,name')->select();
            }
        }
        $this->success('', null, $provincelist);
    }

    public function getCollege($type="college",$college = 0){
            if ($type == 'college'){
                $CollegeVo = new College();
                $colleges = $CollegeVo->field('id as value,college_name as name')->where('school_id',SCHOOL_ID)->select();
                $this->success('',null,$colleges);
            }else if($type == 'specialty'){
                $SpecialtyVo = new Specialty();
                $specialty =  $SpecialtyVo->field('id as value,specialty_name as name')->where('school_id',SCHOOL_ID)->where('college_id',$college)->select();
                $this->success('',null,$specialty);
            }else if($type == 'clazz'){
                $ClazzVo = new Clazz();
                $clazz =  $ClazzVo->field('id as value,clazz_name as name')->where('school_id',SCHOOL_ID)->where('specialty_id',$college)->select();
                $this->success('',null,$clazz);
            }else{
                $this->error("没有可选");
            }
    }

    //手写签名板
    public function canvas(){
        $id = input('id');
        if ($this->request->isPost()){
            if (!$id) $this->error('用户项目数据异常');
            if (!$this->auth) $this->error('当前登录用户数据异常');
            $teacher_name = $this->auth['username'];
            $teacher_id = $this->auth['id'];
            $detail = Db::table('fa_project_register')->where(['id' => $id])->find();
            if ($detail['review_stage'] != 0)  $this->error('用户项目数据不在立项评审阶段');
            if ($detail['project_approval_status'] != 0)  $this->error('用户项目数据不在立项审核阶段');
            if (!$detail) $this->error('项目数据异常');
            //判断是否是审核成员
            $member_ids = Db::table('fa_members')
                ->alias('m')
//                ->field('m.container_id,m.member_id')
//                ->join('fa_project_register p','m.container_id = p.container_id and m.item_id = p.id','LEFT')
                ->where(['m.member_type' => 2 ,'m.member_source' => 2,'m.item_id' => $id])
                ->column('member_id');
            if (!in_array($teacher_id,$member_ids)) $this->error('当前用户不是该项目审核人员');
            $opinion = input('opinion');//意见
            $type = input('type');//审核 1:通过 2:退回
            $imgbase64 = input('imgbase64');
            $file_url = '';
            //图片上传
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/',$imgbase64,$result)){
                $type = $result[2];//图片后缀
                $new_file = ROOT_PATH . DS . 'public' . DS . 'signature' . DS ;
                $url = 'upload/'. date("Ymd", time()) . "/";
                $new_file = $new_file . $url;
                if (!file_exists($new_file)) {
                    //检查是否有该文件夹,如果没有就创建,并给予最高权限
                    mkdir($new_file, 0777,true);
                }
                $filename = time() . '_' . uniqid() . ".{$type}"; //文件名
                $new_file = $new_file . $filename;

                //写入操作
                if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $imgbase64)))) {
                    $file_url = $this->upyun_upload($new_file);
                }
            }
            //通过:project_approval_status => 1 退回:project_status => 2
            $data['signature_url'] = $file_url;
            $data['updatetime']    = time();
            if ($type == 2){
                $data['project_status'] = 2;
                $msg = '退回';
            }else{
                $data['project_approval_status'] = 1;
                $msg = '通过';
            }
            Db::table("fa_project_register")->where('id',$id)->update($data);
            //项目类型
            $project_type_name = Db::table('fa_project_type')->where('id',$detail['project_type'])->value('name');
            //fa_register_log  project_type_name => fa_project_register.project_type--fa_project_type
            $log['register_id']         = $id;
            $log['container_id']        = $detail['container_id'];
            $log['school_id']           = $this->auth['school_id'];
            $log['project_college']     = Db::table('fa_college')->where('id',$detail['project_college'])->value('college_name');
            $log['teacher_id']          = $teacher_id;
            $log['type']                = 'teacher';
            $log['verify_stage']        = 0;
            $log['project_name']        = $detail['project_name'];
            $log['project_type']        = $detail['project_type'];
            $log['project_type_name']   = $project_type_name;
            $log['created_time']        = datetime('Y-m-d H:i:s',time());
            $log['teacher_name']        = $teacher_name;
            $log['job_num']             = $this->auth['job_num'];
            $log['operation']           = '项目审核' . $msg;
            $log['memo']                = $opinion;
            Db::table("fa_register_log")->insert($log);
            $open_id = Db::table('fa_user')->where('id',$detail['user_id'])->value('open_id');
            if ($open_id){
                $config = Config::get('officialAccount');
                $app = Factory::officialAccount($config);
                $app->template_message->send([
                    'touser' => $open_id,
                    'template_id' => 'QUWHawyGohboStMgzZ4B4vQbqeFGWEnd-6MPh7jM8QQ',
                    'data' => array(
                        'first' => array('value' => "项目审核结果通知", 'color' => ''),
                        'keyword1' => array('value' => $project_type_name, 'color' => ''),
                        'keyword2' => array('value' => $detail['project_name'], 'color' => ''),
                        'keyword3' => array('value' => $msg, 'color' => ''),
                        'keyword4' => array('value' => $teacher_name, 'color' => ''),
                        'keyword5' => array('value' => $opinion, 'color' => ''),
                        'remark' => array('value' => '【您报名参加的' . $detail['project_name'] . '】被' . $msg, 'color' => ''),
                    ),
                ]);
            }


            $this->success('操作成功',$file_url);
        }
        $this->view->assign('id',$id);
        return $this->fetch('');
    }

    function upyun_upload($uploadFilePath){
        $config = get_addon_config('upyun');
        //创建的服务的名称
        $serviceName = $config['bucket'];
        //操作员账号 $config['operator']
        $operator = "zhaoyang";
        //操作员密码
        $password = "Lxq0ykCsvZ6q7abFfvzw51QmcxgOxr3B";
        //要上传目录
        $directory = 'signature/';
        //上传文件名,对象存储其实就是一个key value的存储结构。
        $key = basename($uploadFilePath);
        //又拍云默认域名
        $defaultDomain = $config['cdnurl'];
        //在对象存储中,其实并没有实际意义上的"目录"(或者叫"文件夹"),整个文件夹和最后的key一起,组成的一个整体也是key
        if($directory){
            //真正使用时,$directory可能是用户传过来的,在不知道用户是否写了右斜杠的情况下,统一先去掉再添加一个
            $key = rtrim($directory, '/') . '/' . $key;
        }

        //使用又拍云php-sdk上传文件非常方便,很new一个config对象
        $serviceConfig = new \Upyun\Config($serviceName, $operator, $password);
        // 15728640 = 15M,如果文件大于15M,则使用并行分块上传
        if(filesize($uploadFilePath) > 15728640){
            /* uploadType有两个值
               - BLOCK : 串行分块上传
               - BLOCK_PARALLEL : 并行分块上传
            */
            //然后可对new出的config对象的属性继续设置参数(有哪些参数可直接查看Config类: vendor/upyun/sdk/src/Upyun/Config.php)
            //设置uploadType=BLOCK_PARALLEL表示使用并行分片上传
            $serviceConfig->uploadType = 'BLOCK_PARALLEL';
        }
        $client = new Upyun($serviceConfig);
        $fp = fopen($uploadFilePath, 'rb');
        $retArr = $client->write($key, $fp);

        //随便拿一个元素来判断是否上传成功
        if(isset($retArr['x-upyun-content-length'])){
            //在实际使用中,$key可能是用户传过来的,在不知道$key是否以斜杠开头的情况下,统一先去掉再自己添加一个
            return $defaultDomain . '/' . ltrim($key);
        }else{
            return false;
        }
    }
}