<?php

class PublicAction extends CommonAction {

	
	public function index() {
		
		echo "";
	}

	//後台內容主頁
	public function main() {
		/* phpversion */
		$this->phpversion = phpversion();
		$this->software = $_SERVER["SERVER_SOFTWARE"] ;
		$this->os = PHP_OS;
		$mysql_ver = M()->query('SELECT VERSION();');
		if(is_array($mysql_ver)) {
			$this->mysql_ver = $mysql_ver[0]['VERSION()'];
		}else {
			$this->mysql_ver = '';
		}
		/* uploads */
		$this->environment_upload = ini_get('file_uploads') ? ini_get('upload_max_filesize') : '不支持';
		$this->cms_info =  F('ver', '', './Data/resource/');
		$this->display();
	}


	public function getFileOfImg() {

		header("Content-Type: text/html; charset=utf-8");

		$action = I('action', '', 'trim');
		if (IS_POST && $action != 'get') {
			exit();
		}


	    //需要遍歷的目錄列表，最好使用縮略圖地址，否則當網速慢時可能會造成嚴重的延時
	    //$paths = './uploads/img1';

        //顯示有縮略圖　文件
        $files = M('attachment')->where(array('filetype' => 1, 'haslitpic' => 1))->order('uploadtime DESC')->getField('filepath',50);//最新50條
       
        if ( !count($files) ) return;
        rsort($files,SORT_STRING);
        $str = "";
        foreach ( $files as $file ) {        	
            $str .= $file . "ue_separate_ue";
            $file = preg_replace('/\.(.+)$/', '_m.$1', $file);//縮略圖            
            $str .= $file . "ue_separate_ue";
        }
        echo $str;

	}
	

	//上傳圖片
	public function upload() {
		header("Content-Type:text/html; charset=utf-8");//不然返回中文亂碼
		$tb = I('get.tb', 0, 'intval'); //縮略圖地址前綴/,1:_s,2:_m,0默認
		

		//百度編輯新版要求--start
		//獲取存儲目錄--對應百度編輯器
		$imgSavePathConfig = array (
       		'upload',
    	);
	    if ( isset( $_GET[ 'fetch' ] ) ) {

	        header( 'Content-Type: text/javascript' );
	        echo 'updateSavePath('. json_encode($imgSavePathConfig) .');';
	        return;

	    }
	    //百度編輯要求--end 
	
		 //文件上傳地址提交給他，並且上傳完成之後返回一個信息，讓其寫入數據庫     
        if(empty($_FILES)){  
            //$this->error('必須選擇上傳文件');              
            echo json_encode(array(
						'url' => '', 'title' => '',	'original' => '',
		     			'state' => '必須選擇上傳文件'
		     	));
        }else{  
            $info = $this->_uploadPicture();//獲取圖片信息
          
            //p($info);exit();

            if(isset($info) && is_array($info)){  
                //寫入數據庫的自定義c方法  
				if(!$this->_uploadData($info)){  
                    //echo '上傳入庫失敗'; 
                    echo json_encode(array(
						'url' => '',
		     			'title' => '',
		     			'original' => '',
		     			'state' => '上傳入庫失敗'
		     			));
                    exit();
                }
                //$picture_url = ltrim($info[0]['savepath'],'.').$info[0]['savename'];                
                $picture_url = $info[0]['savepath'].$info[0]['savename'];
                //返回縮略圖地址

                $picture_turl = $picture_url;
                //if ($tb == 2 || $tb == 1) 
                {

                	//$picture_url = preg_replace('/\.(.+)$/', '_m.$1', $picture_url);//縮略圖的_m,_s後綴
                	$imgtbSize = explode(',', C('cfg_imgthumb_size'));//配置縮略圖第一個參數
                	$imgTSize = explode('X', $imgtbSize[0]);


					if (!empty($imgTSize)) {
						$picture_turl = get_picture($picture_url, $imgTSize[0], $imgTSize[1]);
					}
                }
                
                echo json_encode(array(
				'url' => $picture_url,
				'turl' => $picture_turl,
     			'title' => $info[0]['name'],
     			'original' => $info[0]['name'],
     			'state' => 'SUCCESS',
     			'size' => round($info[0]['size']/1024,2)
     			));


            }else{  
            //echo "{'url':'','title':'','original':'','state':'". $info ."'}";
           		echo json_encode(array(
				'url' => '',  'title' => '', 'original' => '',
     			'state' => '失敗:'. $info 
     			));
   
            }  
        }  

	}


	//上傳文件
	public function uploadFile() {
		header("Content-Type:text/html; charset=utf-8");//不然返回中文亂碼
		
		
		 //文件上傳地址提交給他，並且上傳完成之後返回一個信息，讓其寫入數據庫     
        if(empty($_FILES)){  
            //$this->error('必須選擇上傳文件');              
            echo json_encode(array(
						'url' => '', 'title' => '',	'original' => '',
		     			'state' => '必須選擇上傳文件'
		     	));
        }else{  
        	$sfile = I('post.sfile', '', 'htmlspecialchars,trim');//判斷其他子目錄
            $info = empty($sfile)? $this->_uploadFile() : $this->_uploadFile($sfile);//獲取附件信息
          
            //p($info);exit();

            if(isset($info) && is_array($info)){  
                //寫入數據庫的自定義c方法  
				if(!$this->_uploadData($info)){  
                    //echo '上傳入庫失敗'; 
                    echo json_encode(array(
						'url' => '',
		     			'title' => '',
		     			'original' => '',
		     			'state' => '上傳入庫失敗'
		     			));
                    exit();
                }

                $file_url = $info[0]['savepath'].$info[0]['savename'];
                //返回地址
               
                
                echo json_encode(array(
				'url' => $file_url,
     			'title' => $info[0]['name'],
     			'fileType' => '.'.$info[0]['extension'],
     			'original' => $info[0]['name'],
     			'state' => 'SUCCESS',
     			'size' => round($info[0]['size']/1024,2)
     			));


            }else{  
            //echo "{'url':'','title':'','original':'','state':'". $info ."'}";
           		echo json_encode(array(
				'url' => '',  'title' => '', 'fileType' => '', 'original' => '',
     			'state' => '失敗:'. $info 
     			));
   
            }  
        }  

	}





	/**
	//圖片(上傳後)數組入庫
	filearr:圖片數組
	**/	
	public function _uploadData($filearr) {

		$db=M('attachment');  
		$num  = 0;
		
		for($i = 0; $i < count($filearr); ++$i) {  
			$savepath = $filearr[$i]['savepath'];

			/*
			if (!empty($savepath) && substr($savepath,0,1)  == '.') {//判斷首字符是否是'.'
				$savepath = substr($savepath,1,(strlen($savepath)-1));//去掉第一個字符
			}
			*/

		    $data['filepath'] = $savepath .$filearr[$i]['savename'];  
		    $data['title'] = $filearr[$i]['name'];  
		    $data['haslitpic'] = empty($filearr[$i]['haslitpic']) ? 0 : 1;
		    $filetype =1;
		    //後綴
		    switch ($filearr[$i]['extension']) {
		       	case 'gif':
		       		$filetype =1;
		       		break;
		       	case 'jpg':
		       		$filetype =1;
		       		break;
		       	case 'png':
		       		$filetype =1;
		       		break;
		       	case 'bmp':
		       		$filetype =1;
		       		break;
		       	case 'swf'://flash
		       		$filetype =2;
		       		break;
		       	case 'mp3'://音樂
		       		$filetype =3;
		       		break;
		       	case 'wav':
		       		$filetype =3;
		       		break;
		       	case 'rm'://電影
		       		$filetype =4;
		       		break;

		       	case 'doc'://
		       		$filetype =5;
		       		break;
		       	case 'docx'://
		       		$filetype =5;
		       		break;
		       	case 'xls'://
		       		$filetype =5;
		       		break;
		       	case 'ppt'://
		       		$filetype =5;
		       		break;
		       	case 'zip'://
		       		$filetype =6;
		       		break;
		       	case 'rar'://
		       		$filetype =6;
		       		break;
		       	case '7z'://
		       		$filetype =6;
		       		break;
		       	
		       	default://其他
		       		$filetype = 0;
		       		break;
		       }   
		    $data['filetype'] = $filetype;
		    $data['filesize'] = $filearr[$i]['size'];
		    $data['uploadtime'] = time();
		    $data['aid'] = $_SESSION[C('USER_AUTH_KEY')];//管理員ID
			if( $db->add($data))  
			{
				++$num;
			}  
			//echo $db->getLastSql();
			//$db->getDbError()
		}  
		
		if($num==count($filearr))  
		{  
		    return true;     
		}else  
		{  
		    return false;  
		} 


	}

	//上傳圖片
	public function _uploadPicture() {
		$ext = '';//原文件後綴
		$ext_dest = 'jpg';//生成縮略圖格式
		foreach ($_FILES as $key => $v) {
			$strtemp = explode('.', $v['name']);
			$ext = end($strtemp);//獲取文件後綴，或$ext = end(explode('.', $_FILES['fileupload']['name']));
			break;
		}

		import('ORG.Net.UploadFile');//導入ThinkPHP的上傳類
		//..這裡可以配置上傳類的參數config，設置N個配置項，可在這裡設置new UploadFile($config)
		$upload = new UploadFile();
		//只修改幾個配置項，可在這裡設置
		$upload->autoSub =true;//是否使用子目錄保存圖片
		$upload->subType = 'date';//子目錄保存規則
		$upload->dateFormat = 'Ymd';
		$upload->maxSize = getUploadMaxsize();//設置上傳文件大小
		//設置上傳文件類型
		$upload->allowExts = explode(',', C('cfg_upload_img_ext'));
		//上傳目錄
		$upload->savePath ='./uploads/img1/';

		//$upload->saveRule = 'time';
		$upload->saveRule = 'uniqid';//設置上傳文件規則
		$upload->uploadReplace = true; //是否存在同名文件是否覆蓋

		/*縮略圖設置*/
		//設置需要生成縮略圖,僅對圖像文件有效
		//讀取配置文件中的設置
		$imgtbSize = explode(',', C('cfg_imgthumb_size'));
		$imgtbArray = array();
		foreach ($imgtbSize as $v) {
			$t_size = explode('X', $v);

			if (empty($t_size) || empty($t_size[0]) || empty($t_size[1])) {
				continue;
			}
			$imgtbArray[] = array('w' => intval($t_size[0]), 'h' => intval($t_size[1]));
		}


		/*

		$strWidth = '';
		$strHeight ='';
		$strSuffix ='';
		foreach ($imgtbArray as $i => $v) {
			if ($i !=0) {
				$strWidth .= ',';
				$strHeight .= ',';
				$strSuffix .= ',';
			}
			$strWidth .= $v['w'];
			$strHeight .= $v['h'];
			$strSuffix .= '.'.$ext.'!'.$v['w'].'X'.$v['h'];

		}



		//系統縮略圖設置
		$upload->thumb = true;
		//設置引用圖片類庫包路徑
		//$upload->imageClassPath = 'ORG.Util.Image';
		//設置需要生成縮略圖片的文件後綴
		//$upload->thumbPrefix = 'm_,s_'; //生成2張縮略圖前綴
		$upload->thumbPrefix = ''; //縮略圖前綴
		$upload->thumbExt = $ext_dest;//縮略圖後綴,但他根據後綴轉換類型，還是默認的格式
		//$upload->thumbMaxWidth = '300,100';//設置縮略圖最大寬度
		$upload->thumbMaxWidth = $strWidth;//設置縮略圖最大寬度
		$upload->thumbMaxHeight = $strHeight;//設置縮略圖最大寬度
		//$upload->thumbSuffix = '_m,_s';//
		$upload->thumbSuffix = $strSuffix;//
		$upload->thumbPath = './uploads/img1/'.date('Ym', time()) .'/';// . $path . date('Ymd', time()) . '/'; //縮略圖保存路徑
		$upload->thumbType = C('cfg_imgthumb_type') ? 1:0; // 縮略圖生成方式 1 按設置大小截取 0 按原圖等比例縮略
		
		$upload->thumbRemoveOrigin = false;//刪除原圖
		
		*/



		//$upload->upload('./uploads/img1/')
		if($upload->upload()) {
			$info = $upload->getUploadFileInfo();//獲取圖片信息
			$real_path = './uploads/img1/'.$info[0]['savename'];

			//讀取配置文件固定寬等比縮略
			$imgtbFixWidth = explode(',', C('cfg_imgthumb_width'));
			$imgtbFixArray = array();
			foreach ($imgtbFixWidth as $v) {
				if (empty($v) || intval($v) == 0) {
					continue;
				}
				$imgtbFixArray[] = array('w' => intval($v), 'h' => intval($v * 100));
			}
		
			if (!empty($imgtbFixArray) || !empty($imgtbArray)) {
				import('ORG.Util.Image.ThinkImage');
				$Think_img = new ThinkImage(THINKIMAGE_GD); 
				$thumbType = C('cfg_imgthumb_type') ? 3:1;//配置大小
				//生成縮略圖,固定大小
				foreach ($imgtbArray as $i => $v) {					
					$strSuffix = '!'.$v['w'].'X'.$v['h'];
					$Think_img->open($real_path)->thumb($v['w'],$v['h'], $thumbType)->save($real_path.$strSuffix.'.'.$ext_dest,$ext_dest);

				}
				//生成縮略圖，不放大，等寬，高度不限
				foreach ($imgtbFixArray as $v) {
					$strSuffix = '!'.$v['w'].'X';
					$Think_img->open($real_path)->thumb($v['w'],$v['h'], 1)->save($real_path.$strSuffix.'.'.$ext_dest,$ext_dest);
				}
				
			}
			
			//轉換成網站根目錄絕對路徑,.Uploads 轉成 /目錄/Uploads
			$info[0]['savepath'] = __ROOT__.ltrim($info[0]['savepath'],'.');//去掉第一個"."字符
			$info[0]['haslitpic'] = 1;
					
			return $info;		

		}else {
			
			//$str = array('err' =>1 ,'msg' => $upload->getErrorMsg() );
			return $upload->getErrorMsg();
		}


	}



	//上傳文件
	public function _uploadFile($sfile = 'file1') {
		$ext = '';//原文件後綴
		foreach ($_FILES as $key => $v) {
			$strtemp = explode('.', $v['name']);
			$ext = end($strtemp);//獲取文件後綴，或$ext = end(explode('.', $_FILES['fileupload']['name']));
			break;
		}

		import('ORG.Net.UploadFile');//導入ThinkPHP的上傳類
		//..這裡可以配置上傳類的參數config，設置N個配置項，可在這裡設置new UploadFile($config)
		$upload = new UploadFile();
		//只修改幾個配置項，可在這裡設置
		$upload->autoSub =true;//是否使用子目錄保存圖片
		$upload->subType = 'date';//子目錄保存規則
		$upload->dateFormat = 'Ymd';
		$upload->maxSize = getUploadMaxsize();//設置上傳文件大小
		//設置上傳文件類型
		$upload->allowExts = explode(',', C('cfg_upload_file_ext'));
		//上傳目錄
		//$upload->savePath ='./uploads/file1/';
		$upload->savePath ='./uploads/'.$sfile.'/';

		//$upload->saveRule = 'time';
		$upload->saveRule = 'uniqid';//設置上傳文件規則
		$upload->uploadReplace = true; //是否存在同名文件是否覆蓋	

		if($upload->upload()) {
			$info = $upload->getUploadFileInfo();//獲取文件信息					
			//轉換成網站根目錄絕對路徑,.Uploads 轉成 /目錄/Uploads
			$info[0]['savepath'] = __ROOT__.ltrim($info[0]['savepath'],'.');//去掉第一個"."字符	
			$info[0]['haslitpic'] = 0;//沒有縮略圖					
			return $info;		

		}else {
			
			return $upload->getErrorMsg();
		}


	}


	//文件/夾管理
	function browseFile($spath = '', $stype = 'file') {
		$base_path = '/uploads/img1';
		$enocdeflag = I('encodeflag', 0, 'intval');
		switch ($stype) {
			case 'picture':
				$base_path = '/uploads/img1';
				break;
			case 'file':
				$base_path = '/uploads/file1';
				break;			
			case 'ad':
				$base_path = '/uploads/abc1';
				break;
			default:
				exit('參數錯誤');
				break;
		}

		if ($enocdeflag) {
			$spath = base64_decode($spath);
		}
	
		$spath = str_replace('.', '', ltrim($spath,$base_path));
	
		$path = $base_path . '/'. $spath;
		import('Class.Dir', APP_PATH);
	
		$dir = new Dir('.'. $path);//加上.
		$list = $dir->toArray();
		for ($i=0; $i < count($list); $i++) { 
			
			$list[$i]['isImg'] = 0;
			if ($list[$i]['isFile']) {
				$url =  __ROOT__.rtrim($path,'/') . '/'. $list[$i]['filename'];
				$ext = explode('.', $list[$i]['filename']);
        		$ext = end($ext);
				if (in_array($ext, array('jpg','png','gif'))) {
					$list[$i]['isImg'] = 1;
				}
			}else {
				//為了兼容URL_MODEL(1、2)
				if (C('URL_MODEL') == 1 || C('URL_MODEL') == 2) {
					$url = U(GROUP_NAME. '/Public/browseFile', array('stype' => $stype, 'encodeflag' => 1 ,'spath'=>base64_encode(rtrim($path,'/') . '/'. $list[$i]['filename'])));
				}else {
					$url = U(GROUP_NAME. '/Public/browseFile', array('stype' => $stype, 'spath'=> rtrim($path,'/') . '/'. $list[$i]['filename']));
				}
				
			}	
			$list[$i]['url'] = $url;			
			$list[$i]['size'] = get_byte($list[$i]['size']);
		}
		//p($list);
		$parentpath = substr($path, 0, strrpos($path, '/'));
		//為了兼容URL_MODEL(1、2)
		if (C('URL_MODEL') == 1 || C('URL_MODEL') == 2) {
			$this->purl = U(GROUP_NAME. '/Public/browseFile', array('spath'=> base64_encode($parentpath),'encodeflag' => 1, 'stype' => $stype));
		}else {
			$this->purl = U(GROUP_NAME. '/Public/browseFile', array('spath'=> $parentpath, 'stype' => $stype));
		}
		$this->type = '瀏覽文件';
		$this->vlist = $list;
		$this->stype = $stype;
		$this->display();

	}


	public function editor($editorId = 'content', $width = '600', $height = '300', $type = 'ueditor') {
		$dataPath = __ROOT__. '/Data';
		$imageUrl = U(GROUP_NAME. '/Public/upload');
		$imageManagerUrl = U(GROUP_NAME. '/Public/getFileOfImg');
		$fileUrl = U(GROUP_NAME. '/Public/uploadFile');
		$PHPSESSID = session_id();
		$getEditor = '';
	
		if (!empty($editorId)) {
			$editorId = explode(',', $editorId);
			foreach ($editorId as $v) {
				if(!empty($v)) $getEditor .= 'UE.getEditor("'. $v .'");';
			}
		}
		$str = <<<str
	window.UEDITOR_HOME_URL = "$dataPath/ueditor/";
	window.onload = function() {
		window.UEDITOR_CONFIG.initialFrameWidth={$width};
		window.UEDITOR_CONFIG.initialFrameHeight={$height};
		//圖片上傳配置區
		window.UEDITOR_CONFIG.imageUrl = "{$imageUrl}" ;   //圖片上傳提交地址
		window.UEDITOR_CONFIG.imagePath = "";//圖片修正地址，引用了fixedImagePath,如有特殊需求，可自行配置
		window.UEDITOR_CONFIG.imageManagerUrl = "{$imageManagerUrl}" ;////圖片在線管理的處理地址
		window.UEDITOR_CONFIG.imageManagerPath = ""; //圖片在線管理修正地址  

		//附件上傳配置區
        window.UEDITOR_CONFIG.fileUrl = "{$fileUrl}"; //附件上傳提交地址
        window.UEDITOR_CONFIG.filePath = ""; //附件修正地址，同imagePath
        //視頻上傳配置區
        window.UEDITOR_CONFIG.videoUrl = "{$fileUrl}";//附件上傳提交地址
        window.UEDITOR_CONFIG.videoPath = "" ; //附件修正地址，同imagePath
        window.UEDITOR_CONFIG.PHPSESSID = "{$PHPSESSID}";
        
		{$getEditor}


	}

	document.write('<script type="text/javascript" src="$dataPath/ueditor/ueditor.config.js"></script>');
	document.write('<script type="text/javascript" src="$dataPath/ueditor/ueditor.all.min.js"></script>');

str;
	echo $str;
	}



}



?>