<?php
/**
 * @package iCMS
 * @copyright 2007-2010, iDreamSoft
 * @license http://www.idreamsoft.cn iDreamSoft
 * @author coolmoo <idreamsoft@qq.com>
 */
//上传
class iUpload {
	function __construct($ikey){
		global $iCMS;
//		if($iCMS->config['remoteKey']!=$ikey){
//			exit("KEY Error!");
//		}
	}
	function iUpload($ikey){
		self::__construct($ikey);
	}
	function FILES($field,$intro="",$_dir="",$FileName="",$type="upload"){
		global $iCMS;
		$RootPath		= FS::path_join(iPATH,$iCMS->config['uploadfiledir']).'/';//绝对路径

		if($_FILES[$field]['name']){
			$tmp_name = $_FILES[$field]['tmp_name'];
			!is_uploaded_file($tmp_name) && exit("What are you doing?");
			if($_FILES[$field]['error'] > 0){
				switch((int)$_FILES[$field]['error']){
				case UPLOAD_ERR_NO_FILE:
					@unlink($tmp_name);
					alert('请选择上传文件!');
					return false;break;
				case UPLOAD_ERR_FORM_SIZE: 
					@unlink($tmp_name);
					alert('上传的文件超过大小!');
					return false;break;
				}
				return false;
			}
			$_FileSize = @filesize($tmp_name);
			//文件类型
			preg_match("/\.([a-zA-Z0-9]{2,4})$/",$_FILES[$field]['name'],$exts);
			$FileExt=strtolower($exts[1]);//&#316;&#701;
			self::CheckValidExt($FileExt);//判断文件类型
			//过滤文件;
			strstr($FileExt, 'ph') && $FileExt="phpfile";
			in_array($FileExt,array('cer','htr','cdx','asa','asp','jsp','aspx','cgi'))&& $FileExt.="file";
			
	//		$FileNameTmp =get_date('',"YmdHis").rand(1,999999);
			$FileNameTmp = md5_file($tmp_name);
			empty($FileName) && $FileName = $FileNameTmp.".".$FileExt;
			$oFileName = $_FILES[$field]['name'];
			// 文件保存目录方式
			$_CreateDir = "";
			if(empty($_dir)){
				if($iCMS->config['savedir']){
					$_CreateDir = str_replace(array('Y','y','m','n','d','j','EXT'),
					array(get_date('','Y'),get_date('','y'),get_date('','m'),get_date('','n'),get_date('','d'),get_date('','j'),$FileExt),
					$iCMS->config['savedir']).'/';
				}
			}else{
				$_CreateDir=$_dir.'/';
			}
			$RootPath		= $RootPath.$_CreateDir;
			//创建目录
			FS::mkdir($RootPath);
			//文件名
			$FilePath		= $_CreateDir.$FileName;
			$FileRootPath	= $RootPath.$FileName;
			self::saveUpload($tmp_name,$FileRootPath);

			if(in_array($FileExt,array('gif','jpg','jpeg','png'))){
				if($iCMS->config['isthumb'] &&($iCMS->config['thumbwidth']||$iCMS->config['thumbhight'])){
					FS::mkdir($RootPath."thumb");
					$Thumb=self::thumbnail($RootPath, $FileRootPath, $FileNameTmp);
					!empty($Thumb['src']) && self::watermark($Thumb['src']);
				}
				self::watermark($FileRootPath);
			}
			// 写入数据库
			empty($_FileSize) && $_FileSize = 0;
			if($type=='upload'){
			$iCMS->db->query("INSERT INTO `#iCMS@__file` (`filename`,`ofilename`,`path`,`intro`,`ext`,`size`,`time`,`type`) VALUES ('$FileName', '$oFileName', '$FilePath','$intro', '$FileExt', '$_FileSize', '".time()."', '0') ");
			}
			return array('fid'=>$iCMS->db->insert_id,'FilePath'=>$FilePath,'OriginalFileName'=>$oFileName,'FileName'=>$FileName);
		}else{
			return;
		}

	}
	//保存文件
	function saveUpload($tn,$fp){
		if (function_exists('move_uploaded_file') && @move_uploaded_file($tn, $fp)) {
			@chmod ($fp, 0777);
		}elseif (@copy($tn, $fp)) {
			@chmod ($fp, 0777);
		}elseif (@is_readable($tn)) {
			if ($fp = @fopen($tn,'rb')) {
				@flock($fp,2);
				$filedata = @fread($fp,@filesize($tn));
				@fclose($fp);
			}
			if ($fp = @fopen($fp, 'wb')) {
				@flock($fp, 2);
				@fwrite($fp, $filedata);
				@fclose($fp);
				@chmod ($fp, 0777);
			} else {
				exit("Upload Unknown Error (fopen)");
				return false;
			}
		}else{
			exit("Upload Unknown Error");
			return false;
		}
	}
	function CheckValidExt($sExt){
		global $iCMS;
		$aExt = explode(',',strtoupper($iCMS->config['fileext']));
		if(!in_array(strtoupper($sExt),$aExt)){
			exit("不支持上传此类扩展名的附件");
		}
	}

	function watermark($groundImage){ 
		global $iCMS;
		if(empty($iCMS->config['iswatermark']))return;
		list($width, $height,$imagetype) = @getimagesize($groundImage);
		if ( $width < $iCMS->config['waterwidth'] || $height<$iCMS->config['waterheight'] ) { 
			return FALSE;
		}
	   	$isWaterImage = FALSE; 
		$formatMsg = "暂不支持该文件格式，请用图片处理软件将图片转换为GIF、JPG、PNG等格式。"; 
	   //读取水印文件 
	   if(!empty($iCMS->config['waterimg']) && file_exists(iPATH."include/watermark/".$iCMS->config['waterimg'])){ 
	   	   $waterImage	= iPATH."include/watermark/".$iCMS->config['waterimg'];
	       $isWaterImage = TRUE; 
	       $water_info = @getimagesize($waterImage); 
	       $water_w    = $water_info[0];//取得水印图片的宽 
	       $water_h    = $water_info[1];//取得水印图片的高 
	       switch($water_info[2]){//取得水印图片的格式 
	           case 1:$water_im = imagecreatefromgif($waterImage);break; 
	           case 2:$water_im = imagecreatefromjpeg($waterImage);break; 
	           case 3:$water_im = imagecreatefrompng($waterImage);break; 
	           default:die($formatMsg); 
	       } 
	   }else{
	   	   	//putenv('GDFONTPATH=' .iPATH.'include/');
	   		//$iCMS->config['watertext']=g2u($iCMS->config['watertext']);
	   		$fontfile=iPATH.'include/'.$iCMS->config['waterfont'];
	   }

	   //读取背景图片 
	   if(!empty($groundImage) && file_exists($groundImage)){ 
	       $ground_info = @getimagesize($groundImage); 
	       $ground_w    = $ground_info[0];//取得背景图片的宽 
	       $ground_h    = $ground_info[1];//取得背景图片的高 

	       switch($ground_info[2]){ //取得背景图片的格式 
	           case 1:$ground_im = imagecreatefromgif($groundImage);break; 
	           case 2:$ground_im = imagecreatefromjpeg($groundImage);break; 
	           case 3:$ground_im = imagecreatefrompng($groundImage);break; 
	           default:die($formatMsg); 
	       } 
	   }else{ 
	       die("需要加水印的图片不存在！"); 
	   } 

	   //水印位置 
	   if($isWaterImage){ //图片水印 
	       $w = $water_w; 
	       $h = $water_h; 
	   }else{ //文字水印
		   if($iCMS->config['waterfont']){
		       $temp = imagettfbbox($iCMS->config['waterfontsize'],0,$fontfile,$iCMS->config['watertext']);//取得使用 TrueType 字体的文本的范围 
		       $w = $temp[2] - $temp[6]; 
		       $h = $temp[3] - $temp[7]; 
		       unset($temp); 
		   }else{
		       $w = $iCMS->config['waterfontsize']*cstrlen($iCMS->config['watertext']); 
		       $h = $iCMS->config['waterfontsize']+5; 
		   }
	   } 
	   if( ($ground_w<$w) || ($ground_h<$h) ){ 
	//       echo "需要加水印的图片的长度或宽度比水印".$label."还小，无法生成水印！"; 
	       return; 
	   } 
	   switch($iCMS->config['waterpos']) { 
	       case 0://随机 
	           $posX = rand(0,($ground_w - $w)); 
	           $posY = rand($h,($ground_h - $h)); 
	           break; 
	       case 1://1为顶端居左 
	           $posX = 0; 
	           $posY = 0;
	           break; 
	       case 2://2为顶端居中 
	           $posX = ($ground_w - $w) / 2; 
	           $posY = 0;
	           break; 
	       case 3://3为顶端居右 
	           $posX = $ground_w - $w; 
	           $posY = 0;
	           break; 
	       case 4://4为中部居左 
	           $posX = 0; 
	           $posY = ($ground_h - $h) / 2;
	           break; 
	       case 5://5为中部居中 
	           $posX = ($ground_w - $w) / 2;
	           $posY = ($ground_h - $h) / 2;
	           break; 
	       case 6://6为中部居右 
	           $posX = $ground_w - $w;
	           $posY = ($ground_h - $h) / 2;
	           break; 
	       case 7://7为底端居左 
	           $posX = 0; 
	           $posY = $ground_h - $h;
	           break; 
	       case 8://8为底端居中 
	           $posX = ($ground_w - $w) / 2;
	           $posY = $ground_h - $h;
	           break; 
	       case 9://9为底端居右 
	           $posX = $ground_w - $w;
	           $posY = $ground_h - $h;
	           break; 
	       default://随机 
	           $posX = rand(0,($ground_w - $w)); 
	           $posY = rand($h,($ground_h - $h)); 
	           break;     
	   } 

	   //设定图像的混色模式 
	   imagealphablending($ground_im, true); 

	   if($isWaterImage){ //图片水印 
	       imagecopymerge($ground_im, $water_im, $posX, $posY, 0, 0, $water_w,$water_h,$iCMS->config['waterpct']);//拷贝水印到目标文件         
	   }else{//文字水印 
			if(empty($iCMS->config['watercolor']))$iCMS->config['watercolor']="#FFFFFF";
			if(!empty($iCMS->config['watercolor']) && (strlen($iCMS->config['watercolor'])==7) ){ 
	           $R = hexdec(substr($iCMS->config['watercolor'],1,2)); 
	           $G = hexdec(substr($iCMS->config['watercolor'],3,2)); 
	           $B = hexdec(substr($iCMS->config['watercolor'],5)); 
	           $textcolor = imagecolorallocate($ground_im, $R, $G, $B);
	       }else{
	           die("水印文字颜色格式不正确！"); 
	       }
			if($iCMS->config['waterfont']){
				imagettftext($ground_im,$iCMS->config['waterfontsize'], 0, $posX, $posY, $textcolor,$fontfile, $iCMS->config['watertext']);
			}else{
				imagestring ($ground_im, $iCMS->config['waterfontsize'], $posX, $posY, $iCMS->config['watertext'],$textcolor);
			}
	   }

	   //生成水印后的图片 
	   @unlink($groundImage); 
	   switch($ground_info[2]){//取得背景图片的格式 
	       case 1:imagegif($ground_im,$groundImage);break; 
	       case 2:imagejpeg($ground_im,$groundImage);break; 
	       case 3:imagepng($ground_im,$groundImage);break; 
	       default:die($errorMsg); 
	   }
	   //释放内存 
	   if(isset($water_info))unset($water_info);
	   isset($water_im) && imagedestroy($water_im);
	   unset($ground_info);
	   imagedestroy($ground_im);
	}
	function thumbnail($upfiledir,$src,$tName,$tw='',$th='',$scale=true,$tDir="thumb") {
		global $iCMS;
		$R 		= array();
		$image  = "";
		$tMap  = array( 1 => 'gif', 2 => 'jpeg', 3 => 'png' );
		$tw		=empty($tw)?(int)$iCMS->config['thumbwidth']:$tw;
		$th		=empty($th)?(int)$iCMS->config['thumbhight']:$th;
		
		if ( $tw && $th ) {
			list($width, $height,$type) = @getimagesize($src);
			if ( $width < 1 && $height < 1 ) {
				$R['width']    = $tw;
				$R['height']   = $th;
				$R['src'] = $src;
				return $R;
			}

			if ( $width > $tw || $height >$th ) {
				FS::mkdir($upfiledir.$tDir);
				if($scale){
					$im = self::scale(array("mw"  => $tw,"mh" => $th,"cw"  => $width,"ch" => $height ));
				}else{
					$im = array('w'=>$tw,'h'=> $th);
				}
				$R['width']   = $im['w'];
				$R['height']  = $im['h'];
				$tName.= '_'.$R['width'].'x'.$R['height'];
				$img	= self::imagecreate($tMap[$type],$src);
				if ($img['res']) {
					$thumb = imagecreatetruecolor($im['w'], $im['h']);
					imagecopyresampled($thumb, $img['res'], 0, 0, 0, 0, $im['w'], $im['h'], $width, $height);
					PHP_VERSION != '4.3.2' && self::UnsharpMask($thumb);
					$R['src'] =$upfiledir.$tDir."/".$tName;
					self::image($thumb,$img['type'],$R['src']);
					$R['src'] .='.'.$img['type'];
				} else {
					$R['src'] = $src;
				}
			} else { 
				$R['width']    = $width;
				$R['height']   = $height;
				$R['src'] = $src;
			}
			return $R;
		}

	}
	function image($dst,$imgType,$fn,$save=true){
		$save && $fn.=".".$imgType;
		if($imgType == 'gif'){
			imagegif($dst,$fn);
		}elseif($imgType == 'jpg' ){
			imagejpeg($dst,$fn);
		}elseif($imgType == 'png' ){
			imagepng($dst,$fn);
		}
	//	imagedestroy($dst);
	}
	function imagecreate($imgType,$pf){
		if($imgType=='gif' && function_exists('imagecreatefromgif')) {
			$res = imagecreatefromgif($pf);
			$type = 'gif';
		}elseif ($imgType == 'png' && function_exists('imagecreatefrompng')) {
			$res = imagecreatefrompng($pf);
			$type = 'png';
		}elseif ($imgType == 'jpeg' && function_exists('imagecreatefromjpeg')) {
			$res = imagecreatefromjpeg($pf);
			$type = 'jpg';
		}
		return array('res'=>$res,'type'=>$type);
	}
	function scale($a) {
		$ret = array('w' => $a['cw'], 'h' => $a['ch']);
		if ( $a['cw'] > $a['mw'] ) {
			$ret['w']  = $a['mw'];
			$ret['h']  = ceil( ( $a['ch'] * ( ( $a['mw'] * 100 ) / $a['cw'] ) ) / 100 );
			$a['ch'] = $ret['h'];
			$a['cw'] = $ret['w'];
		}
		if ( $a['ch'] > $a['mh'] ) {
			$ret['h']  = $a['mh'];
			$ret['w']  = ceil( ( $a['cw'] * ( ( $a['mh'] * 100 ) / $a['ch'] ) ) / 100 );
		}
		return $ret;
	}



	function UnsharpMask($img, $amount = 100, $radius = .5, $threshold = 3) {
		$amount = min($amount, 500);
		$amount = $amount * 0.016;
		if ($amount == 0) return true;
		$radius = min($radius, 50);
		$radius = $radius * 2;
		$threshold = min($threshold, 255);
		$radius = abs(round($radius));
		if ($radius == 0) return true;
		$w = ImageSX($img);
		$h = ImageSY($img);
		$imgCanvas  = ImageCreateTrueColor($w, $h);
		$imgCanvas2 = ImageCreateTrueColor($w, $h);
		$imgBlur    = ImageCreateTrueColor($w, $h);
		$imgBlur2   = ImageCreateTrueColor($w, $h);
		ImageCopy($imgCanvas,  $img, 0, 0, 0, 0, $w, $h);
		ImageCopy($imgCanvas2, $img, 0, 0, 0, 0, $w, $h);
		for ($i = 0; $i < $radius; $i++)	{
			ImageCopy($imgBlur, $imgCanvas, 0, 0, 1, 1, $w - 1, $h - 1);
			ImageCopyMerge($imgBlur, $imgCanvas, 1, 1, 0, 0, $w, $h, 50);
			ImageCopyMerge($imgBlur, $imgCanvas, 0, 1, 1, 0, $w - 1, $h, 33.33333);
			ImageCopyMerge($imgBlur, $imgCanvas, 1, 0, 0, 1, $w, $h - 1, 25);
			ImageCopyMerge($imgBlur, $imgCanvas, 0, 0, 1, 0, $w - 1, $h, 33.33333);
			ImageCopyMerge($imgBlur, $imgCanvas, 1, 0, 0, 0, $w, $h, 25);
			ImageCopyMerge($imgBlur, $imgCanvas, 0, 0, 0, 1, $w, $h - 1, 20 );
			ImageCopyMerge($imgBlur, $imgCanvas, 0, 1, 0, 0, $w, $h, 16.666667); // dow
			ImageCopyMerge($imgBlur, $imgCanvas, 0, 0, 0, 0, $w, $h, 50);
			ImageCopy($imgCanvas, $imgBlur, 0, 0, 0, 0, $w, $h);
			ImageCopy($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h);
			ImageCopyMerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 50);
			ImageCopyMerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 33.33333);
			ImageCopyMerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 25);
			ImageCopyMerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 33.33333);
			ImageCopyMerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 25);
			ImageCopyMerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 20 );
			ImageCopyMerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 16.666667);
			ImageCopyMerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 50);
			ImageCopy($imgCanvas2, $imgBlur2, 0, 0, 0, 0, $w, $h);
		}
		for ($x = 0; $x < $w; $x++)	{
			for ($y = 0; $y < $h; $y++)	{
				$rgbOrig = ImageColorAt($imgCanvas2, $x, $y);
				$rOrig = (($rgbOrig >> 16) & 0xFF);
				$gOrig = (($rgbOrig >>  8) & 0xFF);
				$bOrig =  ($rgbOrig        & 0xFF);
				$rgbBlur = ImageColorAt($imgCanvas, $x, $y);
				$rBlur = (($rgbBlur >> 16) & 0xFF);
				$gBlur = (($rgbBlur >>  8) & 0xFF);
				$bBlur =  ($rgbBlur        & 0xFF);
				$rNew = (abs($rOrig - $rBlur) >= $threshold) ? max(0, min(255, ($amount * ($rOrig - $rBlur)) + $rOrig)) : $rOrig;
				$gNew = (abs($gOrig - $gBlur) >= $threshold) ? max(0, min(255, ($amount * ($gOrig - $gBlur)) + $gOrig)) : $gOrig;
				$bNew = (abs($bOrig - $bBlur) >= $threshold) ? max(0, min(255, ($amount * ($bOrig - $bBlur)) + $bOrig)) : $bOrig;
				if (($rOrig != $rNew) || ($gOrig != $gNew) || ($bOrig != $bNew)) {
					$pixCol = ImageColorAllocate($img, $rNew, $gNew, $bNew);
					ImageSetPixel($img, $x, $y, $pixCol);
				}
			}
		}
		ImageDestroy($imgCanvas);
		ImageDestroy($imgCanvas2);
		ImageDestroy($imgBlur);
		ImageDestroy($imgBlur2);
		return true;
	}
}
?>