<?php
class Upload
{
	var $isMark			=	0;   							//是否附加水印(1为加水印,0不加水印);
	var $markType		=	1;   							//水印类型(1为文字,2为图片)
	var $markPosition	=	1;   							//水印位置(1为左下角,2为右下角,3为左上角,4为右上角,5为居中);
	var $markStr		=	"HTTP://www.HuCart.COM";  		//水印字符串  //智伟科技 //http://Www.HuCart.Com
	var $markImg 		= 	"/sys/upmark.gif"; 				//水印图片
	var $isView			=	1;   							//是否生成预览图(1为生成,其他为不生成);
	var $imgUrl 		= 	'';
	var $errorInfo		= 	'上传信息有误！请重新再试！';
	//$max_file_size
	function Upload()
	{
		//$GLOBALS['WebSe'] -> isOnLine();					//用户登录后才可以上传
	}
	
	function checkType($type='img',$val)
	{
		//上传文件类型列表
		$imgtypes['pro']	= array('image/jpg', 'image/jpeg','image/png','image/pjpeg','image/gif','application/octet-stream','application/x-shockwave-flash','image/x-png');
		$imgtypes['ads']	= array('image/jpg', 'image/jpeg','image/png','image/pjpeg','image/gif','application/octet-stream','application/x-shockwave-flash','image/x-png');
		$imgtypes['file']	= array('image/jpg', 'image/jpeg','image/png','image/pjpeg','image/gif','application/octet-stream','application/zip','application/x-shockwave-flash','image/x-png');
		$imgtypes['flash']	= array('application/octet-stream','application/x-shockwave-flash');
		$imgtypes['img']	= array('image/jpg', 'image/jpeg','image/png','image/pjpeg','image/gif','image/x-png');
		$imgtypes['logo']	= array('image/jpg', 'image/jpeg','image/png','image/pjpeg','image/gif','image/x-png');
		$imgtypes['art']	= array('image/jpg', 'image/jpeg','image/png','image/pjpeg','image/gif','application/octet-stream','application/x-shockwave-flash','image/x-png');
		
		
		if(in_array($val,$imgtypes[$type]))
		{
			return true;
		}else{
			return false;
		}
	}


	//生成上传目录
	function makeDir( $strdir="" )
	{
		//生成用户目录
		if($_SESSION["emplyeeUser"]["use_id"])
		{
		 	$userdir 		= UPLOADS_DIR.'/'.$_SESSION["emplyeeUser"]["use_id"];
			$this -> imgUrl = IMG_URL.'/'.$_SESSION["emplyeeUser"]["use_id"];

		}else{
			$userdir 		= UPLOADS_DIR.'/'.$_SESSION["webUser"]["use_id"];
			$this -> imgUrl = IMG_URL.'/'.$_SESSION["webUser"]["use_id"];
		}
		//echo $userdir;
		if(!file_exists($userdir))
		{
			mkdir($userdir, 0755);
		}
		
		//生成用户上传目录
		if($strdir !='' )
		{
			$updir = $userdir.'/'.$strdir;
			$this -> imgUrl .= '/'.$strdir;
		}else{
			$strdir = date("Ymd");
			$updir = $userdir.'/'.$strdir;
			$this -> imgUrl .= '/'.$strdir;
		}		
	
		if(!file_exists($updir))
		{
			if(mkdir($updir, 0755))
			{	
				return $updir;
			}else{

				return false;
			}
		}else{
			return $updir;
		}	
	}
	
	//检查条件是否合法。
	function checkAll( $fileName, $key = '' )
	{
		$checkVal = true;

		if(is_array($_FILES[$fileName]["name"]))
		{
			$scriptarray  = array(".php", ".jsp", ".asp", "aspx",".exe",".bat");
			
			if(in_array(substr($_FILES[$fileName]["name"][$key],-4),$scriptarray) )
			{
				$this -> errorInfo = "<font color=\"red\">上传文件不类型不合要求！</font>";
				$checkVal = false;
				exit('error');
			}
			
			if(!$this -> checkType( $type='img' , $val = $_FILES[$fileName]["type"][$key] ))
			{
				$this -> errorInfo = "<font color=\"red\">上传文件不类型不合要求！</font>";
				$checkVal = false;
			}
			if (!is_uploaded_file($_FILES[$fileName]['tmp_name'][$key])) //是否存在上传文件
			{
				$this -> errorInfo = "<font color=\"red\">上传文件不存在！或者你上传的文件不合要求！</font>";	
				$checkVal = false;
			}		
			if( MAX_UPSIZE < $_FILES[$fileName]["size"][$key])//检查文件大小
			{
				//1024 X 1024 = 1048576
				$this -> errorInfo = "<font color=\"red\">你上传的文件有".round($_FILES[$fileName]["size"][$strkey]/1048576, 2)."M太大了！，请压缩或处理后再试！</font>";
				$checkVal = false;
			}
		}else{ 
			$scriptarray  = array(".php", ".jsp", ".asp", "aspx",".exe",".bat");
			
			if(in_array(substr($_FILES[$fileName]["type"]["name"],-4),$scriptarray) )
			{
				$this -> errorInfo = "<font color=\"red\">上传文件不类型不合要求！</font>";
				$checkVal = false;
				exit('error');
			}
		
			if(!$this -> checkType( $type = 'img' , $val = $_FILES[$fileName]["type"] ))
			{
				$this -> errorInfo = "<font color=\"red\">上传文件不类型不合要求！</font>";
				$checkVal = false;
			}
				
			if (!is_uploaded_file($_FILES[$fileName]['tmp_name'])) //是否存在上传文件
			{
				$this -> errorInfo = "<font color=\"red\">上传文件不存在！或者你上传的文件不合要求！</font>";
				$checkVal = false;
			}
			
			if( MAX_UPSIZE < $_FILES[$fileName]["size"])//检查文件大小
			{
				//1024 X 1024 = 1048576
				$this -> errorInfo = "<font color=\"red\">你上传的文件有".round($_FILES[$fileName]["size"][$strkey]/1048576, 2)."M太大了！，请压缩或处理后再试！</font>";
				$checkVal = false;
			}
		}
			
 		return $checkVal;
	}
	
	function uploadfile( $fileName = '' , $strdir = '', $strkey = '', $reUrl = '', $sizeType = '' )
	{
			
			if(file_exists($strdir))
			{
					$nowtime = time();
					if($strkey!=''){
						$image_size 	= 	getimagesize($_FILES[$fileName]["tmp_name"][$strkey]);
						$pinfo			=	pathinfo($_FILES[$fileName]["name"][$strkey]);
						$ftype			=	$pinfo[extension];
						$webfileName 	= 	$strdir."/".$nowtime.".".$ftype;
						$small_img   	= 	$webfileName.IMG_SMALLWIDTH."X".IMG_SMALLHEIGHT.".".$ftype;
						$datadir 		= 	$this -> imgUrl."/".$nowtime.".".$ftype;
	
	
						if (file_exists($webfileName))
						{
								$this -> errorInfo = "<font color=\"red\">同名文件已经存在了！请重新上传！</a>";
						}else{
							
								if(!move_uploaded_file ($_FILES[$fileName]["tmp_name"][$strkey], $webfileName))
								{
									$this -> errorInfo = "<font color=\"red\">移动文件出错！请重新上传！</a>";
								}else{
																				
									$this -> makeSmallImg( $webfileName ,  $width = IMG_SMALLWIDTH , $height = IMG_SMALLHEIGHT , $small_img );
									if($this -> isMark)
									{
										$this -> addMark( $nimage = $webfileName ,$markTypeval = 1 );
									}	
									$this -> errorInfo = "<font color=red>上传成功</font>".$datadir."<img src=\"".BASE_WEBURL."/uploads/sys/cancel.png\" width=\"16\" onclick=\"hiddenLoding(".$strkey.")\">";
								}
						}
						
						
						
					}else{
								$image_size 	= 	getimagesize($_FILES[$fileName]["tmp_name"]);
								$pinfo			=	pathinfo($_FILES[$fileName]["name"]);
								$ftype			=	$pinfo[extension];
								$webfileName 	= 	$strdir."/".$nowtime.".".$ftype;
								$small_img   	= 	$webfileName.IMG_SMALLWIDTH."X".IMG_SMALLHEIGHT.".".$ftype;
								$datadir 		= 	$this -> imgUrl."/".$nowtime.".".$ftype;
								
								if (file_exists($webfileName))
								{
									$this -> errorInfo = "<font color=\"red\">同名文件已经存在了！请重新上传！</a>";
								}else{
							
										if(!move_uploaded_file ($_FILES[$fileName]["tmp_name"], $webfileName))	//此句上传
										{
										   $this -> errorInfo = "<font color=\"red\">移动文件出错！请重新上传！</a>";
										}else{
										
											$this -> makeSmallImg( $webfileName ,  $width = IMG_SMALLWIDTH , $height = IMG_SMALLHEIGHT , $small_img );
											if($this -> isMark)
											{
												$this -> addMark( $nimage = $webfileName ,$markTypeval = 1 );
											}
											if($sizeType=='big')
											{
												$this -> errorInfo = "<font color=red>上传成功</font>".$datadir."<img src=\"".BASE_WEBURL."/uploads/sys/cancel.png\" width=\"16\" onclick=\"hiddenLoding(".$strkey.")\">";
											}else{
												$this -> errorInfo = "<font color=red>上传成功</font>".$datadir."<img src=\"".BASE_WEBURL."/uploads/sys/cancel.png\" width=\"16\" onclick=\"hiddenLoding(".$strkey.")\">";
											}
										}
								}
					}
								
			}
 			//echo $reUrl;
			echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n";
			echo "<script language=\"javascript\">\n";
 			
			if($sizeType=='big')
			{

				echo "parent.document.getElementById('".$reUrl."').value='".$datadir."';\n";
			}else{

				echo "parent.document.getElementById('".$reUrl."').value='".$datadir."';\n";
			}
				
			if($strkey!='')
			{
				echo "parent.document.getElementById('lodingdiv[".$strkey."]').style.display='';\n";
				echo "parent.document.getElementById('lodingdiv[".$strkey."]').innerHTML = '".$this -> errorInfo."';\n";
			}else{
				echo "parent.document.getElementById('lodingdiv').style.display='';\n";
				echo "parent.document.getElementById('lodingdiv').innerHTML = '".$this -> errorInfo."';\n";
			}
				echo "</script>\n";
				
	
	}
	
	
	function upFile( $fileName = '' , $reUrl = 'fileurl' , $dirName = '', $fileType = 'img', $lodingDiv = '', $strkey ='', $sizeType = '',$isMarkval = 1 )
	{
		
		$nowtime = time();
		$this -> isMark = $isMarkval;
		$this -> checkAll( $fileName , $strkey );
	    $strdir = $this -> makeDir();  //生成上传目录
		
		$this -> uploadfile( $fileName , $strdir, $strkey ,$reUrl,$sizeType);

	}


	function makeSmallImg( $fileName = '' , $width = 220 , $height = 220 , $small_img )
	{
		//大图文件地址，缩略宽，缩略高，小图地址
		//$width = 519 ; $height = 519 ;
		//echo $fileName;
		$imgage=getimagesize($fileName);//获取大图信息
		
		switch ($imgage[2])
		{//判断图像类型
		case 1:
			 $im=imagecreatefromgif($fileName);
			 break;
		case 2:
			 $im=imagecreatefromjpeg($fileName);
			 break;
		case 3:
			 $im=imagecreatefrompng($fileName);
			 break;  
		}
			
		$src_W	= imagesx($im);//获取大图宽
		$src_H	= imagesy($im);//获取大图高
		

		$sw =  $width/$height;

		$hw = $src_W/$src_H;
		
		$_cutwidth =0 ;
		$_cutheight= 0;
		
		
		//不作变形，不读取原图片比例切割后缩小
		if( $sw  < $hw )
		{
			$src_W = ceil($sw / $hw   * $src_W);
			
		}else{
			$src_H = ceil( $hw / $sw   * $src_H );
		}
		
		
		/*原方式，不切割缩小
		if( $sw  < $hw )
		{
			$height = ceil($sw / $hw * $height);

		}else{
			$width  = ceil($hw / $sw * $width);
		}
		*/
		
		
		
		$tn	=	imagecreatetruecolor($width,$height); //创建小图
		imagecopyresized($tn,$im,0,0,-$_cutwidth,-$_cutheight,$width,$height,$src_W,$src_H);//复制图像并改变大小
		imagejpeg($tn,$small_img);//输出图像
	}
	
 
	function addMark( $webfileName = '', $markTypeval = 2 )
	{

				$image_size	=	getimagesize( $webfileName );
				$nimage		=	imagecreatetruecolor($image_size[0],$image_size[1]);
				$white		=	imagecolorallocate($nimage,255,255,255);
				$black		=	imagecolorallocate($nimage,0,0,0);
				$red		=	imagecolorallocate($nimage,255,0,0);
				
				$bgcolor 	= 	imagecolorallocate($nimage,255,0,0);//
				imagefill($nimage,0,0,$white);
				
				switch ($image_size[2])
				{
					case 1:
						$simage 	=	imagecreatefromgif($webfileName);
						break;
					case 2:
						$simage 	=	imagecreatefromjpeg($webfileName);
						break;
					case 3:
						$simage 	=	imagecreatefrompng($webfileName);
						break;
					case 6:
						$simage 	=	imagecreatefromwbmp($webfileName);
						break;
					default:
						die("<font color=\"red\">不能上传此类型文件！</font>");
						exit;
				}
				
				imagecopy($nimage,$simage,0,0,0,0,$image_size[0],$image_size[1]);
				imagefilledrectangle($nimage,1,$image_size[1]-15,80,$image_size[1],$white);
			
				switch($markTypeval)
				{
					case 1: 
						//加水印字符串
						//imagestring() 用 col 颜色将字符串 s 画到 image 所代表的图像的 x ，y 坐标处（这是字符串左上角坐标，整幅图像的左上角为 0，0）。如果 font 是 1，2，3，4 或 5，则使用内置字体。 
						
						//imagestring($nimage,5,$image_size[0]-210,$image_size[1]-20,$waterstring='http://Www.HuCart.Com',$bgcolor);

						$font	= DOCUMENT_DIR.'/includes/fonts/simkai.ttf';
						
						imagettftext($nimage, 20, 0, $image_size[0]-260,$image_size[1]-20, $bgcolor, $font, $text='http://Www.HuCart.Com');
						//imagettftext($nimage,20,0,0,$waterstring='http://Www.HuCart.Com',$bgcolor);
						break;
					case 2: //加水印图片
						$simage1 =imagecreatefromgif(UPLOADS_DIR.$this->markImg);
						imagecopy($nimage,$simage1,0,0,0,100,100,231);	//原图片，水印图，X轴，Y轴，水印图X轴， 水印图Y轴,水印宽度，水印高度
						imagedestroy($simage1);
						break;
				}
				
				switch ($image_size[2])
				{
					case 1:
					imagegif($nimage, $webfileName);
					break;
					case 2:
					imagejpeg($nimage, $webfileName);
					break;
					case 3:
					imagepng($nimage, $webfileName);
					break;
					case 6:
					imagewbmp($nimage, $webfileName);
					break;
				}
			
				//覆盖原上传文件
				imagedestroy($nimage);
				imagedestroy($simage);
 
	}

}


$Uploa = new Upload();

?>