<?php
/**
 * 人人站CMS
 * ============================================================================
 * 版权所有 2015-2030 山东康程信息科技有限公司，并保留所有权利。
 * 网站地址: http://www.rrzcms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 */
namespace app\admin\controller;
use app\BaseController;
use think\exception\ValidateException;

class Upload extends BaseController
{

    var $upConfig = [
        'video' => ['fileSize' => 4194304, 'fileExt' => 'mp4', 'fileMime' => 'video/mp4',],
        'audio' => ['fileSize' => 4194304, 'fileExt' => 'mp3', 'fileMime' => 'audio/mpeg',],
        'images' => ['fileSize' => 4194304, 'fileExt' => 'jpg,jpeg,png,bmp,gif,ico', 'fileMime' => 'image/jpeg,image/png,image/x-ms-bmp,image/gif,image/x-icon',],
        'zip' => ['fileSize' => 4194304, 'fileExt' => 'zip', 'fileMime' => 'application/zip',],
    ];

    function index(){
        $type=I('get.type');
        if(!$type||!isset($this->upConfig[$type])){
            $this->error('参数错误！');
        }
        $this->upload($type);
    }

    private function upload($type){

        if (!$this->request->isPost()) {
            return $this->error('非法上传');
        }

        $conf = $this->upConfig[$type];
        $files = $this->request->file();

        if (empty($files) || !@ini_get('file_uploads')) {
            return $this->error('请检查空间是否开启文件上传功能！');
        }

        try {
            validate(
                ['file' => $conf],
                ['file.fileSize' => '上传文件过大', 'file.fileExt' => '上传文件后缀名必须为' . $conf['fileExt'],]
            )->check($files);

            $filesystem = \think\facade\Filesystem::class;
            $config = $filesystem::getDiskConfig($filesystem::getDefaultDriver());

            $dir = $config['root'] . DIRECTORY_SEPARATOR . $type;
            is_dir($dir) or mkdir($dir, 0777, true);

            $savename = [];
            foreach ($files as $file) {
                /*验证图片一句话木马*/
                $imgstr = @file_get_contents($file->getPathname());
                if (false !== $imgstr && preg_match('#<([^?]*)\?php#i', $imgstr)) {
                    return $this->error('禁止上传木马图片！');
                }

                $url = $config['url'] . '/' . $filesystem::putFile($type, $file);
                $savename[] = str_replace('\\', '/', $url);
            }
            $this->success('', $savename[0], $savename);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }
    }
}