<?php
if (!defined('HUCART_COM')) exit('HuCart.COM No direct script access allowed');
//上传图库管理
class Image_list extends HC_Controller
{
	//注意无须构造函数,使用了构造函数得重构父类 parent::__construct();
	function __construct()
	{
		parent::__construct();
		$this -> load_lang('adminsys/image');
		$this -> load('admin'); 
		$this -> admin -> online_admin();
		$this -> load('helper');
		
		$this -> upload_dir = UPLOADS_DIR.'';
		$this -> image_url 	= IMG_URL;
	}
	
	//选择图片专用
	function select_img( $front_str ='' , $page_num = 1)
	{
		$back_url = './index.php?load=image_list&act=select_img';
		
		$get_id = $this -> input ->  get["get_id"];
		if($this -> input ->  get["type"]!=''){
			$add_dir = $this -> input ->  get["type"];
		}else{
			$add_dir = $front_str;	
		}

		$page_num  = intval($_REQUEST["page_num"]);
 		
		if($add_dir != ''){
			$file_list = $this -> read_dir( $this -> upload_dir , $add_dir );
			//var_dump($file_list);
			$this -> view -> assign('back_url',$back_url);
			$this -> view -> assign('file_list',$file_list);
			$this -> view -> assign('get_id',$get_id);
			$this -> view -> assign('add_dir',$add_dir);
			$this -> view -> assign('image_url',$this -> image_url.'/'.$add_dir);
			//分页显示
			$this -> view -> display('select_image.tpl');
		
		}else{
			exit('NO_DIR');
		}
		
	}
	
	function info_list( $front_str ='' , $page_num = 1)
	{
		
		$front_str = $this -> input ->  get["type"];
		$page_num  = intval($_REQUEST["page_num"]);

		$file_list = $this -> read_dir( $this -> upload_dir , $front_str );
		
		$this -> view -> assign('file_list',$file_list);

		//分页显示
		$this -> view -> display('image_list.tpl');
		

	}
	
	function read_dir( $dir ='' ,  $front_str = '' )
	{
	  
	   $file_list = array();

	   if($front_str !=''){ $rootdir = $dir."/".$front_str; }else{ $rootdir = $dir; }

	   @$d = dir($rootdir);
		
	   while(false !== ($entry = @$d -> read()))
	   {
		   if($entry!='.' && $entry!='..')
		   {
 
			   if(is_dir($rootdir.'/'.$entry))
			   {
			   		
					//IMG_SMALLWIDTH IMG_SMALLHEIGHT
					//echo $entry;
					
					if(strchr($entry,IMG_SMALLWIDTH.'X'.IMG_SMALLHEIGHT))
					{
						//echo 'X';
					}else{
						if($front_str!='')
						{
							$file_list['0000' . $entry] = array('file_name'  => $entry,
															   'file_name_url' => $front_str.'/'.urlencode($entry),
															   ///'dir_url' => $front_str.urlencode($entry),
															   'is_dir'    => '1');
						}else{
							$file_list['0000' . $entry] = array('file_name'  => $entry,
															   'file_name_url' => urlencode($entry),
															   ///'dir_url' => $front_str.urlencode($entry),
															   'is_dir'    => '1');
						}
					}
				
				//这是目录处理
			   }else{
						@$fileAttribute = getimagesize($rootdir.'/'.$entry);
						$img_file = '';
						$fileExt = explode('.', $entry);
						$fileExt = $fileExt[count($fileExt) - 1];
						$img_file_val = strtolower($fileExt);

						if(in_array($img_file_val, $GLOBALS["cfg"]["img"]))
						{
							$img_file = 'img';
							
							//是图片现示
							
							$file_size = filesize($rootdir.'/'. $entry);
							
							$file_size = ($file_size >= 1000000) ? round($file_size / 1000000, 2) . ' Mb' : (($file_size >= 1000) ? round($file_size / 1000, 2) . ' Kb' : $file_size . ' b');
							
							if(strchr($entry,IMG_SMALLWIDTH.'X'.IMG_SMALLHEIGHT))
							{
								//echo 'X';
								//echo $entry;
								
							}else{
								
		 
								if(file_exists($this -> helper ->  build_img($this -> upload_dir.'/'.$front_str.'/'.$entry)))
								{
									$entrysmall = $this -> helper ->  build_img($front_str.'/'.$entry);	
								}else{
									$entrysmall = false;						
								}
								if($front_str!=''){
									$this -> view -> assign('image_url',$this -> image_url.$front_str.'/');
								}else{
									$this -> view -> assign('image_url',$this -> image_url);
								}
								if($front_str!='')
								{
									$file_list[$entry] = array('file_name'  => $entry,
														'is_dir'    => '0',
														'file_size'  => $file_size,
														'file_name_url' => urlencode($entry),
														'dir_url' => $front_str.'/',
														'file_type'  => $fileAttribute['mime'],
														'img_file'   => $img_file,
														'file_XYWH'  => $fileAttribute[0] ? $fileAttribute[0] . ' X ' . $fileAttribute[1] : '',
														//'filem_time' => date('Y-m-d H:i', filemtime($rootdir.'/'.$entry)),
														'filesmall' => $this -> image_url.$entrysmall );
														
														
								}else{
									$file_list[$entry] = array('file_name'  => $entry,
														'is_dir'    => '0',
														'file_size'  => $file_size,
														'file_name_url' => urlencode($entry),
														'dir_url' => $front_str,
														'file_type'  => $fileAttribute['mime'],
														'img_file'   => $img_file,
														'file_XYWH'  => $fileAttribute[0] ? $fileAttribute[0] . ' X ' . $fileAttribute[1] : '',
														//'filem_time' => date('Y-m-d H:i', filemtime($rootdir.'/'.$entry)),
														'filesmall' => $this -> image_url.$entrysmall );
								
								}
								
							}	
							
							
						}elseif($img_file =='')
						{
							$img_file = 'no';
							//非图片不显示
						}	

			   }
		   }
	   }
	   
	   //var_dump($file_list);
	   
	   $d->close();
	   return $file_list;
	}
	function del()
	{

		
		if($_REQUEST["deltype"]!=''){
			$deltype = $_REQUEST["deltype"];
		}else{
			$deltype = 'delFile';
		}
		$dirName  = $_REQUEST["dir"];
		$filename = $_REQUEST["name"];
		
		
		switch($deltype)
		{
			case 'delFile':
				//删除文件../../image/
				if( $filename != '' )
				{
					if(file_exists($this -> upload_dir.$dirName . $filename))
					{
						unlink($this -> upload_dir.$dirName . $filename);
						
						$this -> view ->  assign('info_title','文件“' . $filename . '”删除成功！');
						$this -> view ->  assign('URL_TIME',URL_TIME);
						$this -> view ->  assign('get_url',ADMIN_WEBURL."/index.php?load=image&act=info_list&dir=".$dirName);
						$this -> view ->  display('suggestion.tpl');

					}
				}
				break;

			case 'delDir':
			
				//删除文件目录

				if($filename != '')
				{
					//echo  $this -> upload_dir. $dirName . $filename;
					if(file_exists( $this -> upload_dir. $dirName . $filename) )  //if(file_exists($delete_filetype) && substr($delete_filetype, 0, 7) == UPLOADDIR)
					{
						$this -> delete_dir($dirName . $filename);
						
						$this -> view ->  assign('info_title','目录“' . $dirName .'/'. $filename . '”删除成功！');
						$this -> view ->  assign('URL_TIME',URL_TIME);
						$this -> view ->  assign('get_url',ADMIN_WEBURL."/index.php?load=image&act=info_list&dir=".$dirName);
						$this -> view ->  display('suggestion.tpl');
					}
				}
				break;
		}
	}



	function delete_dir($dir_name)
	{
		//$this -> upload_dir = UPLOADS_DIR."/".'/';
		$now_dir = dir($this -> upload_dir.$dir_name);
		while($entry = $now_dir->read())
		{
			if($entry != '' && $entry != '.' && $entry != '..' && $entry != './' && $entry != '../')
			{
				//如果是目录
				$this -> upload_dir . $dir_name.'/'.$entry;

				if(is_dir($this -> upload_dir . $dir_name.'/'.$entry))
				{
					$this -> delete_dir( $dir_name .'/'. $entry );
				}else
				{
					unlink( $this -> upload_dir .$dir_name.'/'. $entry );
				}
			}
		}
		
		$now_dir->close();
		
		rmdir($this -> upload_dir.$dir_name);
	}

	function up_load_file()
	{
		$add_dir = $this -> input ->  req["add_dir"];
		$get_id = $this -> input ->  req["get_id"];
		
	 	$dir = $this -> upload_dir.'/'.$add_dir.'/';
        //上传文件
        $up_file = $_FILES['up_file'];

        if($up_file['type'] == 'image/pjpeg' || $up_file['type'] == 'image/gif'
        || $up_file['type'] == 'image/x-png' || $up_file['type'] == 'image/png'
        || $up_file['type'] == 'image/jpeg' || $up_file['type'] == 'application/x-shockwave-flash')
        {
            $fileExt = explode('.', $up_file['name']);
            $fileExt = $fileExt[count($fileExt) - 1];
            $filename = $dirName .  time() . '.' .$fileExt;
			$ext_arr = array("jpeg", "jpg","png","JPEG","JPG", "GIF", "PNG");
			if(in_array($fileExt, $ext_arr))
			{
				copy($up_file['tmp_name'], $dir.$filename);
				if($up_file['type'] != 'application/x-shockwave-flash')
				{
					$this-> get_small_img($dir.$filename,$up_file['type'],$fileExt,IMG_SMALLWIDTH,IMG_SMALLHEIGHT);
				}

				@chmod($filename, 0600);
				echo  '<script language="javascript">alert(\''.$this->lang['up_success'].'\');</script>';
				echo  '<script language="javascript">window.opener.document.getElementById(\''.$get_id.'\').value="'.$this -> image_url.'/'.$add_dir.'/'.$filename.'";</script>';
				echo  '<script language="javascript">window.opener = null;</script>';
				echo  '<script language="javascript">window.open(\'\',\'_top\');</script>';
				echo  '<script language="javascript">window.top.close();</script>';
				exit();
			}
			else
			{
			  exit("Type Error");
			}

        }else{
          echo '<script language="javascript">alert(\''.$this->lang['up_error'].'\')</script>'; 
		  echo '<script language="javascript">history.back(-1);</script>'; 
        }
	
	}

 
 

	/**
	 * $img_file 获取目标文件
	 * $new_width 生成缩略图宽度
	 * $new_height 生成缩略图高度
	 * $type_val 图片类型
	**/
	function get_small_img($old_img_file,$type_val,$file_ext,$new_width=IMG_SMALLWIDTH,$new_height=IMG_SMALLHEIGHT){
	

		//复制图片
		$img_file = $old_img_file.'_sm.'.$file_ext;
		
		if(@copy($old_img_file,$img_file )){
	
			list($old_width,$old_height)=getimagesize( $img_file );//获取该图片大小
			
				$new_img=imagecreatetruecolor($new_width,$new_height);
			if($type_val == 'image/gif'){
				$source=imagecreatefromgif($img_file);
			}else if($type_val == 'image/jpeg' || $type_val == 'image/pjpeg' ){

				$source=imagecreatefromjpeg($img_file);
			}else if( $type_val == 'image/x-png' || $type_val == 'image/png'){
				$source=imagecreatefrompng($img_file);
			}
			@imagecopyresampled($new_img,$source,0,0,0,0,$new_width,$new_height,$old_width,$old_height);
			
			if($type_val == 'image/gif'){
				imagegif($new_img,$img_file);
			}else if($type_val == 'image/jpeg' || $type_val == 'image/pjpeg'){
				imagejpeg($new_img,$img_file);
			}else if($type_val == 'image/x-png' || $type_val == 'image/png' ){
				imagepng($new_img,$img_file);
			}
			return true;
		}else{
			return false;
		}
		//return $new_img;
	}



	
}

$GLOBALS["cfg"]["img"]=array("jpg","jpeg","bmp","gif","png"); //img允许后缀
