<?php
namespace app\common\controller;
use think\Controller;
use think\facade\Env;
/**
* 上传
*/
class Upload extends Controller
{
	private $uppath;
	protected function initialize()
    {
        parent::initialize();
        if(empty(session('userid')) && empty(session('adminid'))) $this->error('拒绝访问');
        $this->uppath = config('app.upload.uppath') . '/';
    }
	//接口
	public function upload()
	{
		date_default_timezone_set("Asia/Chongqing");
		error_reporting(E_ERROR);
		header("Content-Type: text/html; charset=utf-8");
		$CONFIG = config('upload.');
		$action = input('param.action');
		switch ($action) {
		    case 'config':
		        $result =  json_encode($CONFIG);
		        break;

		    /* 上传图片 */
		    case 'uploadimage':
		    /* 上传涂鸦 */
		    case 'uploadscrawl':
		    /* 上传视频 */
		    case 'uploadvideo':
		    /* 上传文件 */
		    case 'uploadfile':
		    	$result = $this->action_upload($CONFIG);
		        break;
		    /* 列出图片 */
		    case 'listimage':
		    /* 列出文件 */
		    case 'listfile':
		        $result = $this->action_list($CONFIG);
		        break;
		    /* 抓取远程文件 */
		    case 'catchimage':
		        $result = $this->action_crawler($CONFIG);
		        break;

		    default:
		        $result = json_encode(array(
		            'state'=> lang('requestfalse')
		        ));
		        break;
		}
		/* 输出结果 */
		if (isset($_GET["callback"])) {
		    if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
		        echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
		    } else {
		        echo json_encode(array(
		            'state'=> lang('paramerror')
		        ));
		    }
		} else {
		    echo $result;
		}
	}

	// 上传
	private function action_upload($CONFIG)
	{
		/* 上传配置 */
		$base64 = "upload";
		switch (input('param.action')) {
		    case 'uploadimage':
		        $config = array(
		            "pathFormat" => $this->uppath . "image/{yyyy}{mm}{dd}/{time}{rand:6}",
		            "maxSize" => intval(config('app.upload.imageMaxSize'))*1024*1024,
		            "allowFiles" => explode("|",str_replace("|","|.",".".config('app.upload.imageAllowFiles'))),
		            "filetype" => "image"
		        );
		        $fieldName = $CONFIG['imageFieldName'];
		        break;
		    case 'uploadscrawl':
		        $config = array(
		            "pathFormat" => $this->uppath . "image/{yyyy}{mm}{dd}/{time}{rand:6}",
		            "maxSize" => intval(config('app.upload.scrawlMaxSize'))*1024*1024,
		            "allowFiles" => explode("|",str_replace("|","|.",".".config('app.upload.scrawlAllowFiles'))),
		            "filetype" => "image",
		            "oriName" => "scrawl.png"
		        );
		        $fieldName = $CONFIG['scrawlFieldName'];
		        $base64 = "base64";
		        break;
		    case 'uploadvideo':
		        $config = array(
		            "pathFormat" => $this->uppath . "video/{yyyy}{mm}{dd}/{time}{rand:6}",
		            "maxSize" => intval(config('app.upload.videoMaxSize'))*1024*1024,
		            "allowFiles" => explode("|",str_replace("|","|.",".".config('app.upload.videoAllowFiles'))),
		            "filetype" => "video"
		        );
		        $fieldName = $CONFIG['videoFieldName'];
		        break;
		    case 'uploadfile':
		    default:
		        $config = array(
		            "pathFormat" => $this->uppath . "file/{yyyy}{mm}{dd}/{time}{rand:6}",
		            "maxSize" => intval(config('app.upload.fileMaxSize'))*1024*1024,
		            "allowFiles" => explode("|",str_replace("|","|.",".".config('app.upload.fileAllowFiles'))),
		            "filetype" => "file"
		        );
		        $fieldName = $CONFIG['fileFieldName'];
		        break;
		}
		/* 生成上传实例对象并完成上传 */
		$up = new \rg\Uploader($fieldName, $config, $base64);
		/**
		 * 得到上传文件所对应的各个参数,数组结构
		 * array(
		 *     "state" => "",          //上传状态，上传成功时必须返回"SUCCESS"
		 *     "url" => "",            //返回的地址
		 *     "title" => "",          //新文件名
		 *     "original" => "",       //原始文件名
		 *     "type" => ""            //文件类型
		 *     "size" => "",           //文件大小
		 * )
		 */

		/* 返回数据 */
		return json_encode($up->getFileInfo());
	}

	// 获取文件列表
	private function action_list($CONFIG)
	{
		/* 判断类型 */
		switch (input('param.action')) {
		    /* 列出文件 */
		    case 'listfile':
		        $allowFiles = $CONFIG['fileManagerAllowFiles'];
		        $listSize = $CONFIG['fileManagerListSize'];
		        $path = $this->uppath . "file/";
		        break;
		    /* 列出图片 */
		    case 'listimage':
		    default:
		        $allowFiles = $CONFIG['imageManagerAllowFiles'];
		        $listSize = $CONFIG['imageManagerListSize'];
		        $path = $this->uppath . "image/";
		}
		$allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);

		/* 获取参数 */
		$size = isset($_GET['size']) ? htmlspecialchars($_GET['size']) : $listSize;
		$start = isset($_GET['start']) ? htmlspecialchars($_GET['start']) : 0;
		$end = $start + $size;

		/* 获取文件列表 */
		$path = $_SERVER['DOCUMENT_ROOT'] . (substr($path, 0, 1) == "/" ? "":"/") . $path;
		$files = getfiles($path, $allowFiles);
		if (!count($files)) {
		    return json_encode(array(
		        "state" => "no match file",
		        "list" => array(),
		        "start" => $start,
		        "total" => count($files)
		    ));
		}
		/* 获取指定范围的列表 */
		$len = count($files);
		for ($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--){
		    $list[] = $files[$i];
		}
		//倒序
		//for ($i = $end, $list = array(); $i < $len && $i < $end; $i++){
		//    $list[] = $files[$i];
		//}

		/* 返回数据 */
		$result = json_encode(array(
		    "state" => "SUCCESS",
		    "list" => $list,
		    "start" => $start,
		    "total" => count($files)
		));
		return $result;
	}

	// 抓取远程图片
	private function action_crawler($CONFIG)
	{
		set_time_limit(0);
		/* 上传配置 */
		$config = array(
		    "pathFormat" => $this->uppath . "image/{yyyy}{mm}{dd}/{time}{rand:6}",
		    "maxSize" => intval(config('app.upload.imageMaxSize'))*1024*1024,
		    "allowFiles" => explode("|",str_replace("|","|.",".".config('app.upload.imageAllowFiles'))),
		    "oriName" => "remote.png"
		);
		$fieldName = $CONFIG['catcherFieldName'];

		/* 抓取远程图片 */
		$list = array();
		if (isset($_POST[$fieldName])) {
		    $source = $_POST[$fieldName];
		} else {
		    $source = $_GET[$fieldName];
		}
		foreach ($source as $imgUrl) {
		    $item = new \rg\Uploader($imgUrl, $config, "remote");
		    $info = $item->getFileInfo();
		    array_push($list, array(
		        "state" => $info["state"],
		        "url" => $info["url"],
		        "size" => $info["size"],
		        "title" => htmlspecialchars($info["title"]),
		        "original" => htmlspecialchars($info["original"]),
		        "source" => htmlspecialchars($imgUrl),
		        "md5" => $info["md5"]
		    ));
		}
		/* 返回抓取数据 */
		return json_encode(array(
		    'state'=> count($list) ? 'SUCCESS':'ERROR',
		    'list'=> $list
		));
	}
}