<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
@set_time_limit(0);
class Upload extends CI_Controller {

	function __construct(){
		parent::__construct();
        	$this->load->helper('url');
        	$this->load->helper('form');
                $this->load->library('session'); //加载session
		$this->load->model('CsdjDB');
                $this->load->library('ftp');
                $this->load->helper('string');
		$this->load->model('CsdjSkins');
		$this->load->model('CsdjUser');
	}

	public function index()
	{
	      $this->CsdjUser->User_Login();
              $data['ac'] = $this->input->get_post('ac', TRUE);   //ac，dance为歌曲，vod为视频
              $data['fhurl'] = $this->input->get_post('fhurl', TRUE);   //返回URL框
              $data['dxurl'] = $this->input->get_post('dxurl', TRUE);   //返回URL框
              $data['yzurl'] = $this->input->get_post('yzurl', TRUE);   //返回URL框
              $data['scurl'] = $this->input->get_post('scurl', TRUE);   //返回URL框
              $data['msgurl'] =$this->input->get_post('msgurl', TRUE);   //返回提示框
              if($data['ac']=='dance'){
                   $data['types']="*.flv;*.f4a;*.m4a;*.mp4;*.mp3;*.wma";
                   $data['size']="200MB";
                   $data['title']="歌曲文件";
                   $data['limit']=1;
              }else{
                   $data['types']="*.flv;*.swf;*.mp4;*.wmv;*.asf;*.avi";
                   $data['size']="2000MB";
                   $data['title']="视频文件";
                   $data['limit']=1;
              }
              if(empty($data['fhurl'])) $data['fhurl']='cs_playurl';
			  $key = sys_auth($this->session->userdata('cs_id').'-cscms-'.$this->session->userdata('cs_name').'-cscms-'.$this->session->userdata('cs_pass'),'E');
              if(FTP_Fun==0){  //开启远程附件
                   $data['uplink']=site_url('user/upload/ftp_save').'?ac='.$data['ac'].'&fhurl='.$data['fhurl'].'&dxurl='.$data['dxurl'].'&scurl='.$data['scurl'].'&yzurl='.$data['yzurl'].'&msgurl='.$data['msgurl'];
                   $this->load->view('upload_ftp',$data);
              }else{
                   $data['uplink']=site_url('user/upload/upload_save').'?key='.$key.'&ac='.$data['ac'];
                   $this->load->view('upload_duo',$data);
              }
        }

	public function pic()
	{
	      $this->CsdjUser->User_Login();
              $data['ac'] = $this->input->get_post('ac', TRUE);   //ac，topic为专集，vod为视频，pic为图片
              $data['msgurl'] = $this->input->get_post('msgurl', TRUE);   //返回提示框
              $this->load->view('upload_pic', $data);
        }

	public function pic_save()
	{
	         $this->CsdjUser->User_Login();
                 $op   = $this->input->get('ac', TRUE);
                 $msgurl   = $this->input->get('msgurl', TRUE);

                 if($op=='topic'){  //专集图片
                       $config['upload_path'] = './attachment/topic/'.date('Ymd').'/';
                       $config['allowed_types'] = 'gif|jpg|png';
                 }elseif($op=='vod'){  //视频图片
                       $config['upload_path'] = './attachment/vod/'.date('Ymd').'/';
                       $config['allowed_types'] = 'gif|jpg|png';
                 }elseif($op=='pic'){  //图片
                       $config['upload_path'] = './attachment/pic/'.date('Ymd').'/';
                       $config['allowed_types'] = 'gif|jpg|png';
                 }elseif($op=='music'){  //歌曲图片
                       $config['upload_path'] = './attachment/tp/'.date('Ymd').'/';
                       $config['allowed_types'] = 'gif|jpg|png';
                 }elseif($op=='bgpic'){  //主页背景
                       $config['upload_path'] = './attachment/bgpic/'.date('Ymd').'/';
                       $config['allowed_types'] = 'gif|jpg|png';
                 }elseif($op=='toppic'){  //主页背景
                       $config['upload_path'] = './attachment/toppic/'.date('Ymd').'/';
                       $config['allowed_types'] = 'gif|jpg|png';
                 }else{  //文章图片
                       $config['upload_path'] = './attachment/news/'.date('Ymd').'/';
                       $config['allowed_types'] = 'gif|jpg|png';
                 }


	         !is_dir($config['upload_path']) && mkdir($config['upload_path'], 0755, true);  //创建目录
                 $config['encrypt_name'] = TRUE;  //重命名
                 $this->load->library('upload', $config);
                 if ( ! $this->upload->do_upload()){
                            $error = array('error' => $this->upload->display_errors());
                            exit($error['error']);
                 } else{
                            $data = $this->upload->data();
                            if(!file_exists($config['upload_path'].'index.html')){
	                         @file_put_contents($config['upload_path'].'index.html','cscms');
                            }
                            $targetFile=date('Ymd')."/".$data['file_name'];
                           
                            //判断水印
                            if(CS_WaterMark==1){
		                   $this->load->model('CsdjPic');
                                   $this->CsdjPic->imageWaterMark($data['full_path']);
                            }

                            if(FTP_Fun==1){  //开启远程附件

                                  $FTPUP['hostname'] = FTP_Server;
                                  $FTPUP['port']     = FTP_Port;
                                  $FTPUP['username'] = FTP_Name;
                                  $FTPUP['password'] = FTP_Pass;
                                  $FTPUP['passive']  = FTP_Ive;
                                  $this->ftp->connect($FTPUP);


                                  //----------创建目录------------------------
                                  $Dirs=FTP_Dir;
                                  if(substr($Dirs,0,1)=='/') $Dirs=substr($Dirs,1);
                                  if(substr($Dirs,-1)=='/') $Dirs=substr($Dirs,0,-1);
                                  if(!empty($Dirs)) $Dirs.='/';
                                  $All=explode("/",$config['upload_path']);
                                  $Dir1='./'.$Dirs.$All[1].'/';
                                  $this->ftp->mkdir($Dir1, DIR_WRITE_MODE); 
                                  $Dir2=$Dir1.$All[2].'/';
                                  $this->ftp->mkdir($Dir2, DIR_WRITE_MODE); 
                                  $Dir3=$Dir2.$All[3].'/';
                                  $this->ftp->mkdir($Dir3, DIR_WRITE_MODE); 

                                  //----------上传文件------------------------
                                  $tmp_name=$config['upload_path'].$data['file_name'];
                                  $this->ftp->mkdir($config['upload_path'], DIR_WRITE_MODE); 
                                  $this->ftp->upload($config['upload_path'].$data['file_name'], $Dir3.$data['file_name']);
                                  $this->ftp->close();
                                  //删除本地附件
                                  @unlink($tmp_name);

                             }


                            $targetFile=date('Ymd')."/".$data['file_name'];
                            if(empty($msgurl) || $msgurl=='undefined'){
			          exit("<script type=\"text/javascript\">
				     window.parent.document.getElementById('cs_pic').value= '{$targetFile}';
				     parent.Dialog.close();
		                  </script>");
                            }else{
			          exit("<script type=\"text/javascript\">
				     window.parent.document.getElementById('cs_pic').value= '{$targetFile}';
				     window.parent.document.getElementById('".$msgurl."').innerHTML='<font color=#0000ff>恭喜您，图片上传成功!</font>';
				     parent.Dialog.close();
		                  </script>");
                            }
                 }
        }

        public function upload_save() {  //多文件

            $key   = $this->input->get_post('key', TRUE);
            $ac   = $this->input->get_post('ac', TRUE);
			$this->CsdjUser->User_Login(0,$key);
            //允许动作
            if($ac!='dance' && $ac!='video') $ac='dance';
            if (!empty($_FILES)) {

	            $tempFile = $_FILES['Filedata']['tmp_name'];
	            $targetPath = './attachment/' . $ac . '/'.date('Ym').'/'.date('d').'/';
	            $file_name = $_FILES['Filedata']['name'];
                    $file_size = @filesize($_FILES['Filedata']['tmp_name']);

	            //获得文件扩展名
	            $file_ext = strtolower(trim(substr(strrchr($file_name, '.'), 1)));

                    if($file_ext=='mp3' || $file_ext=='wma' || $file_ext=='m4a' || $file_ext=='f4a' || $file_ext=='mp4' || $file_ext=='flv' || $file_ext=='avi' || $file_ext=='asf' || $file_ext=='wmv' || $file_ext=='swf'){  //判断后缀
                    }else{
                            @unlink($tempFile);
                    }

                    //---------获取歌曲属性------------------
                    $djinfo=$this->CsdjSkins->djinfo($tempFile);
                    if($djinfo){
                       $info=explode("|",$djinfo);
                       $dx =$info[0];
                       $yz =$info[1];
                       $sc =$info[2];
                    } else {
                       $dx ='';
                       $yz ='';
                       $sc ='';
                    }

	            //新文件名
	            $new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $file_ext;
	            $targetFile =  str_replace('//','/',$targetPath) . $new_file_name;
	            !is_dir(str_replace('//','/',$targetPath)) && mkdir(str_replace('//','/',$targetPath), 0755, true);
                    if(!file_exists($targetPath.'index.html')){
	                  @file_put_contents($targetPath.'index.html','cscms');
                    }
	            @move_uploaded_file($tempFile,$targetFile);
	            echo "/attachment/" . $ac . "/".date('Ym')."/".date('d')."/".$new_file_name."=cscms=".$dx."=cscms=".$yz."=cscms=".$sc;

            }
            
        }

        public function ftp_save() {  //远程文件
			$this->CsdjUser->User_Login();
            $ac   = $this->input->get_post('ac', TRUE);
            $fhurl = $this->input->get_post('fhurl', TRUE);   //返回URL框
            $dxurl = $this->input->get_post('dxurl', TRUE);   //返回URL框
            $yzurl = $this->input->get_post('yzurl', TRUE);   //返回URL框
            $scurl = $this->input->get_post('scurl', TRUE);   //返回URL框
            $msgurl = $this->input->get_post('msgurl', TRUE);   //返回提示框
            //允许动作
            if($ac!='dance' && $ac!='video') $ac='dance';
            if (!empty($_FILES)) {

	            $tempFile = $_FILES['userfile']['tmp_name'];
	            $file_name = $_FILES['userfile']['name'];
                    $file_size = @filesize($_FILES['userfile']['tmp_name']);

	            //获得文件扩展名
	            $file_ext = strtolower(trim(substr(strrchr($file_name, '.'), 1)));
                    if($file_ext=='mp3' || $file_ext=='wma' || $file_ext=='m4a' || $file_ext=='f4a' || $file_ext=='mp4' || $file_ext=='flv' || $file_ext=='avi' || $file_ext=='asf' || $file_ext=='wmv' || $file_ext=='swf'){  //判断后缀
                    }else{
                            @unlink($tempFile);
			    echo "<script type=\"text/javascript\">";
                            echo "alert('抱歉不支持的文件类型~!');";
			    echo "parent.Dialog.close();";
		            echo "</script>";
                            exit;
                    }

                    //---------获取歌曲属性------------------
                    $djinfo=$this->CsdjSkins->djinfo($tempFile);
                    if($djinfo){
                       $info=explode("|",$djinfo);
                       $dx =$info[0];
                       $yz =$info[1];
                       $sc =$info[2];
                    } else {
                       $dx ='';
                       $yz ='';
                       $sc ='';
                    }

	            //新文件名
	            $new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $file_ext;
	            $targetFile = './attachment/' . $ac . '/'.$new_file_name;
	            if(move_uploaded_file($tempFile,$targetFile)){

                              $FTPUP['hostname'] = FTP_Server;
                              $FTPUP['port']     = FTP_Port;
                              $FTPUP['username'] = FTP_Name;
                              $FTPUP['password'] = FTP_Pass;
                              $FTPUP['passive']  = FTP_Ive;
                              $this->ftp->connect($FTPUP);

                              $targetPath = './attachment/' . $ac . '/'.date('Ym').'/'.date('d').'/';
                              //----------创建目录------------------------
                              $Dirs=FTP_Dir;
                              if(substr($Dirs,0,1)=='/') $Dirs=substr($Dirs,1);
                              if(substr($Dirs,-1)=='/') $Dirs=substr($Dirs,0,-1);
                              if(!empty($Dirs)) $Dirs.='/';
                              $All=explode("/",$targetPath);
                              $Dir1='./'.$Dirs.$All[1].'/';
							  $Dir1 = str_replace('//','/',$Dir1);
                              $this->ftp->mkdir($Dir1, DIR_WRITE_MODE); 
                              $Dir2=$Dir1.$All[2].'/';
                              $this->ftp->mkdir($Dir2, DIR_WRITE_MODE); 
                              $Dir3=$Dir2.$All[3].'/';
                              $this->ftp->mkdir($Dir3, DIR_WRITE_MODE); 
                              $Dir4=$Dir3.$All[4].'/';
                              $this->ftp->mkdir($Dir4, DIR_WRITE_MODE); 

                              //----------上传文件------------------------
                              $this->ftp->upload($targetFile, $Dir4.$new_file_name);
                              $this->ftp->close();
                              //删除本地附件
                              @unlink($targetFile);
			     echo "<script type=\"text/javascript\">";
                             echo "window.parent.document.getElementById('".$fhurl."').value='/attachment/" . $ac . "/".date('Ym')."/".date('d')."/".$new_file_name."';";
                             if (!empty($dxurl) && $dxurl!='undefined'){
		                  echo "window.parent.document.getElementById('".$dxurl."').value='".$dx."';";
                             }
                             if (!empty($yzurl) && $yzurl!='undefined'){
		                  echo "window.parent.document.getElementById('".$yzurl."').value='".$yz."';";
                             }
                             if (!empty($scurl) && $scurl!='undefined'){
		                  echo "window.parent.document.getElementById('".$scurl."').value='".$sc."';";
                             }
                             if (!empty($msgurl) && $msgurl!='undefined'){
		                  echo "window.parent.document.getElementById('".$msgurl."').innerHTML='<font color=#0000ff>恭喜您，文件上传成功!</font>';";
                             }
			     echo "parent.Dialog.close();";
		             echo "</script>";
	            }else{
			     echo "<script type=\"text/javascript\">";
                             if (!empty($msgurl) && $msgurl!='undefined'){
		                  echo "window.parent.document.getElementById('".$msgurl."').innerHTML='<font color=red>抱歉上传失败，本地文件夹没有写入权限~!</font>';";
                             }else{
                                  echo "alert('抱歉上传失败，本地文件夹没有写入权限~!');";
                             }
			     echo "parent.Dialog.close();";
		             echo "</script>";
                    }
            }
            
        }

    //编辑器上传
	public function editor()
	{
		 if (strpos($_SERVER['HTTP_REFERER'],'/index.php/') !== FALSE) {
			$this->CsdjUser->User_Login();
		 }else{
		    $this->load->model('CsdjAdmin');
			$this->CsdjAdmin->Admin_Login();
		 }
            //文件保存目录路径
            $save_path = './attachment/editor/';
            //文件保存目录URL
            $save_url = 'http://'.Web_Url.Web_Path.'/attachment/editor/';
            //定义允许上传的文件扩展名
            $ext_arr = array(
	            'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
	            'flash' => array('swf', 'flv'),
	            'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
	            'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
            );
            //最大文件大小
            $max_size = 10000000;
            //PHP上传失败
            if (!empty($_FILES['imgFile']['error'])) {
	            switch($_FILES['imgFile']['error']){
		            case '1':
			            $error = '超过php.ini允许的大小。';
			            break;
		            case '2':
			            $error = '超过表单允许的大小。';
			            break;
		            case '3':
			            $error = '图片只有部分被上传。';
			            break;
		            case '4':
			            $error = '请选择图片。';
			            break;
		            case '6':
			            $error = '找不到临时目录。';
			            break;
		            case '7':
			            $error = '写文件到硬盘出错。';
			            break;
		            case '8':
			            $error = 'File upload stopped by extension。';
			            break;
		            case '999':
		            default:
			            $error = '未知错误。';
	            }
	            $this->alert($error);
            }

            //有上传文件时
            if (!empty($_FILES) === false) {
                   $this->alert("请选择文件。");
            }
	            //原文件名
	            $file_name = $_FILES['imgFile']['name'];
	            //服务器上临时文件名
	            $tmp_name = $_FILES['imgFile']['tmp_name'];
	            //文件大小
	            $file_size = $_FILES['imgFile']['size'];
	            //检查文件名
	            if (!$file_name) {
		            $this->alert("请选择文件。");
	            }
	            //检查目录
	            if (@is_dir($save_path) === false) {
		            $this->alert("上传目录不存在。");
	            }
	            //检查目录写权限
	            if (@is_writable($save_path) === false) {
		            $this->alert("上传目录没有写权限。");
	            }
	            //检查是否已上传
	            if (@is_uploaded_file($tmp_name) === false) {
	            	$this->alert("上传失败。");
	            }
	            //检查文件大小
	            if ($file_size > $max_size) {
		            $this->alert("上传文件大小超过限制。");
	            }
	            //检查目录名
	            $dir_name = empty($_GET['dir']) ? 'image' : trim($_GET['dir']);
	            if (empty($ext_arr[$dir_name])) {
	            	$this->alert("目录名不正确。");
	            }
                    //检查图片文件是否正确
                    if($dir_name=='image'){
                         $aa=getimagesize($tmp_name);
                         $weight=$aa["0"];////获取图片的宽
                         $height=$aa["1"];///获取图片的高
                         if($weight<1 || $height<1){
                                 @unlink($tmp_name);
                                 $this->alert("图片内容不正确。");
                         }
                    }

	            //获得文件扩展名
	            $temp_arr = explode(".", $file_name);
	            $file_ext = array_pop($temp_arr);
	            $file_ext = trim($file_ext);
	            $file_ext = strtolower($file_ext);
	            //检查扩展名
	            if (in_array($file_ext, $ext_arr[$dir_name]) === false) {
		            $this->alert("上传文件扩展名是不允许的扩展名。\n只允许" . implode(",", $ext_arr[$dir_name]) . "格式。");
	            }

                    if($dir_name=='file'){
                         $dir_name='papers';
                    }

	            //创建文件夹
	            if ($dir_name !== '') {
		            $save_path .= $dir_name . "/";
		            $save_url .= $dir_name . "/";
		            if (!file_exists($save_path)) {
			            @mkdir($save_path);
		            }
	            }
	            $ymd = date("Ymd");
	            $save_path .= $ymd . "/";
	            $save_url .= $ymd . "/";
	            if (!file_exists($save_path)) {
	            	@mkdir($save_path);
	            }
	            //新文件名
	            $new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $file_ext;
	            //移动文件
	            $file_path = $save_path . $new_file_name;
	            if (move_uploaded_file($tmp_name, $file_path) === false) {
		            $this->alert("上传文件失败。");
	            }
	            @chmod($file_path, 0644);
                           
                    //判断水印
                    if(CS_WaterMark==1 && $dir_name=='image'){
		        $this->load->model('CsdjPic');
                        $this->CsdjPic->imageWaterMark($file_path);
                    }

	            $file_url = $save_url . $new_file_name;


	            echo json_encode(array('error' => 0, 'url' => $file_url));


	}

	public function alert($msg) {

		echo json_encode(array('error' => 1, 'message' => $msg));
        exit();
	}
}
