<?php
class uploadControl extends skymvc{
	function __construct(){
		parent::__construct();
		$this->loadClass("image");
		$this->loadClass("upload");
		//$this->loadModel('attach_temp');
	}
	public function onDefault(){
			exit('出错了');
	}
	
	public function onUpload(){
		$dir=isset($_GET['dir'])?get('dir','h')."/":"";
		$this->upload->iddir=get('id','i');
		$this->upload->uploaddir="attach/".$dir; 
		$this->upload->uploaddir="attach/";
		$data=$this->upload->uploadfile("upimg");
		$data=array("error"=>$data['err'],"imgurl"=>$data['filename'],"msg"=>$data['err']);
		echo json_encode($data);
	}
	
	public function onMoto(){
		$dir=isset($_GET['dir'])?get('dir','h')."/":"";
		$this->upload->iddir=get('id','i');
		$this->upload->uploaddir="attach/".$dir; 
		$this->upload->uploaddir="attach/";
		$data=$this->upload->uploadfile("upimg");
		if(empty($data['err'])){
			$this->loadClass("image",false,false);
			$img=new image();
			$imgurl=$data['filename'];
			$img->makethumb($imgurl.".100x100.jpg",$imgurl,"100","100",1);
			$img->makethumb($imgurl.".small.jpg",$imgurl,"240","240",1);
			$img->makethumb($imgurl.".middle.jpg",$imgurl,"440","440",1);
		}
		$data=array("error"=>$data['err'],"imgurl"=>$data['filename'],"msg"=>$data['err']);
		echo json_encode($data);
	}
	
	public function onuploadtao(){
			$dir=isset($_GET['dir'])?get('dir','h')."/":"";
			$this->upload->iddir=get('id','i');
			$this->upload->uploaddir="attach/".$dir; 
			$data=$this->upload->uploadfile("upimg");
			if(empty($data['err'])){
				$this->loadClass("image",false,false);
				$img=new image();
				$imgurl=$data['filename'];
				$img->makethumb($imgurl.".100x100.jpg",$imgurl,"100","100",1);
				$img->makethumb($imgurl.".small.jpg",$imgurl,"240");
				$img->makethumb($imgurl.".middle.jpg",$imgurl,"440");
			}
			$data=array("error"=>$data['err'],"imgurl"=>$data['filename'],"msg"=>$data['err']);
			echo json_encode($data);
	}
	
	/*传广告图*/
	public function onuploadAd(){
			$dir=isset($_GET['dir'])?get('dir','h')."/":"";
			$this->upload->iddir=get('id','i');
			$this->upload->uploaddir="attach/".$dir; 
			$data=$this->upload->uploadfile("upimg");
			if(empty($data['err'])){
				$this->loadClass("image",false,false);
				$img=new image();
				$imgurl=$data['filename'];
				$img->makethumb($imgurl.".100x100.jpg",$imgurl,"100","100",1);
				$img->makethumb($imgurl,$imgurl,get_post('width'),get_post('height'),2);
			}
			$data=array("error"=>$data['err'],"imgurl"=>$data['filename'],"msg"=>$data['err']);
			echo json_encode($data);
	}
	
	/*kindeditor上传图片*/
	public function onKindImg(){
		$dir=isset($_GET['savedir'])?get('savedir','h')."/":"";
		$this->upload->iddir=get('id','i');
		$this->upload->uploaddir="attach/".$dir; 
		$data=$this->upload->uploadfile('imgFile');
		
		if(empty($data['err'])){
			echo json_encode(array("error"=>0,"url"=>$data['filename']));
		}else{
			echo json_encode(array("error"=>1,"message"=>$data['err']));
		}
	}
	
	/**
	*百度ueditor上传图片
	*/
	public function onUeImg(){
		$dir=isset($_GET['dir'])?get('dir','h')."/":"";
		$this->upload->iddir=get('id','i');
		$this->upload->uploaddir="attach/".$dir; 
		$data=$this->upload->uploadfile('upfile');
		echo "{'url':'" . $data["filename"] . "','title':'哈哈哈','original':'" . $data["original"] . "','state':'SUCCESS'}";
	}
	/*百度上传文件*/
	public function onUeFile(){
		$dir=isset($_GET['dir'])?get('dir','h')."/":"";
		$this->upload->iddir=get('id','i');
		$this->upload->uploaddir="attach/".$dir;
		$this->upload->upimg=false;
		$this->upload->allowtype=$this->upload->sysallowtype;
		$data=$this->upload->uploadfile('upfile');
		
		if($data['err']){
			echo "{'url':'" . $data["filename"] . "','title':'".$data['err']."','original':'" . $data["original"] . "','state':'falied'}";		
		}else{
			echo "{'url':'" . $data["filename"] . "','title':'上传成功','original':'" . $data["original"] . "','state':'SUCCESS'}";	
		}
	}
	/*远程文件保存本地*/
	public function onUeRemote(){
		error_reporting(E_ERROR|E_WARNING);
		//远程抓取图片配置
		$config = array(
			"savePath" => "attach/uploads/".date("Y/m/d/") ,             //保存路径
			"allowFiles" => array( ".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp" ) , //文件允许格式
			"maxSize" => 3000                    //文件大小限制，单位KB
		);
		$dir=isset($_GET['dir'])?get('dir','h')."/":"";
		if(get('id','i')){
			umkdir("attach/$dir".$this->dirId(get('id','i')));
		}else{
			umkdir("attach/$dir".date("Y/m/d/").$this->dirId(get('id','i')));
		}
		$uri = htmlspecialchars( $_POST[ 'upfile' ] );
		$uri = str_replace( "&amp;" , "&" , $uri );
		$this->getRemoteImage( $uri,$config );
	}
	
	public function getRemoteImage( $uri,$config)
    {
        //忽略抓取时间限制
        set_time_limit( 0 );
        //ue_separate_ue  ue用于传递数据分割符号
        $imgUrls = explode( "ue_separate_ue" , $uri );
        $tmpNames = array();
        foreach ( $imgUrls as $imgUrl ) {
            //http开头验证
            if(strpos($imgUrl,"http")!==0){
                array_push( $tmpNames , "error" );
                continue;
            }
            //获取请求头
            $heads = get_headers( $imgUrl );
            //死链检测
            if ( !( stristr( $heads[ 0 ] , "200" ) && stristr( $heads[ 0 ] , "OK" ) ) ) {
                array_push( $tmpNames , "error" );
                continue;
            }

            //格式验证(扩展名验证和Content-Type验证)
            $fileType = strtolower( strrchr( $imgUrl , '.' ) );
            if ( !in_array( $fileType , $config[ 'allowFiles' ] ) || stristr( $heads[ 'Content-Type' ] , "image" ) ) {
                array_push( $tmpNames , "error" );
                continue;
            }

            //打开输出缓冲区并获取远程图片
            ob_start();
            $context = stream_context_create(
                array (
                    'http' => array (
                        'follow_location' => false // don't follow redirects
                    )
                )
            );
            //请确保php.ini中的fopen wrappers已经激活
            readfile( $imgUrl,false,$context);
            $img = ob_get_contents();
            ob_end_clean();

            //大小验证
            $uriSize = strlen( $img ); //得到图片大小
            $allowSize = 1024 * $config[ 'maxSize' ];
            if ( $uriSize > $allowSize ) {
                array_push( $tmpNames , "error" );
                continue;
            }
            //创建保存位置
            $savePath = $config[ 'savePath' ];
            if ( !file_exists( $savePath ) ) {
                mkdir( "$savePath" , 0777 );
            }
            //写入文件
            $tmpName = $savePath . rand( 1 , 10000 ) . time() . strrchr( $imgUrl , '.' );
            try {
                $fp2 = @fopen( $tmpName , "a" );
                fwrite( $fp2 , $img );
                fclose( $fp2 );
                array_push( $tmpNames ,  $tmpName );
            } catch ( Exception $e ) {
                array_push( $tmpNames , "error" );
            }
        }
        /**
         * 返回数据格式
         * {
         *   'url'   : '新地址一ue_separate_ue新地址二ue_separate_ue新地址三',
         *   'srcUrl': '原始地址一ue_separate_ue原始地址二ue_separate_ue原始地址三'，
         *   'tip'   : '状态提示'
         * }
         */
        echo "{'url':'" . implode( "ue_separate_ue" , $tmpNames ) . "','tip':'远程图片抓取成功！','srcUrl':'" . $uri . "'}";
    }
	
	/*根据id来存储*/
	public function dirId($id){
		if(!$id) return false;
		return (($id/1000000)%100)."/".(($id/10000)%100)."/".(($id/100)%100)."/".($id%100)."/".$id."/";
	}
}
?>